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: replace hand-written flex layout with Yoga engine
esenginea59da814f879
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 12e77f9c7..8b8a78548 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -284,7 +284,7 @@ target_include_directories(esengine${CMAKE_CURRENT_SOURCE_DIR}/third_party/stb)-target_link_libraries(esengine PUBLIC glm)+target_link_libraries(esengine PUBLIC glm yogacore)if(ES_ENABLE_TILEMAP)target_link_libraries(esengine PUBLIC cute_tiled)diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex 291196d42..2a3c2d9a9 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}function n(){return"wechat"===e?.name}async function s(e,n){return t().fetch(e,n)}async function o(e){return t().readFile(e)}async function i(e){return t().readTextFile(e)}async function r(e){return t().fileExists(e)}async function a(e,n){return t().instantiateWasm(e,n)}function l(e,n){return t().createCanvas(e,n)}function c(){return t().now()}function u(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class d{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof d?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class h{constructor(e,t,n){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class p{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.obeyMuteSwitch=!1;const o=++this.nextId_;this.contexts_.set(o,s);const i=new h(o,s,this.contexts_);return s.onEnded(()=>{i.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(o))}),s.onError(e=>{console.error(`[WeChatAudio] Playback error for "${n}":`,e.errMsg)}),s.src=n,s.play(),i}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function f(e,t){return new Promise((n,s)=>{const o=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===o?"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 g(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}`)}}const m=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["estimeline"],contentType:"json",editorType:"timeline",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",estimeline:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,x=new Set;for(const e of m)for(const t of e.extensions)_.set(t,e),x.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function b(e){return _.get(w(e))}function v(e){return x.has(e.toLowerCase())}function S(){const e=[];for(const t of m)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function P(e){const t=b(e);return t?.wechatPackInclude??!1}function M(e){const t=b(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}let T=null;function C(){return T||(T=wx.getFileSystemManager()),T}function E(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(P(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function A(e){const t=C();try{return t.accessSync(e),!0}catch{return!1}}function R(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 k(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const o=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(o.data.buffer)}}async function I(e){return k(await R(e))}let F=!1;const B=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return f(e,t)}async readFile(e){return function(e){return C().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return C().readFileSync(e,t)}(M(e))}async fileExists(e){return A(M(e))}async loadImagePixels(e){return I(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return g(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),o="function"==typeof wx.onKeyDown;o&&(wx.onKeyDown(n),wx.onKeyUp(s));const i=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(i),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{o&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(i),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new p}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch(e){console.warn("[WeChat] setStorageSync failed:",e)}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch(e){console.warn("[WeChat] removeStorageSync failed:",e)}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const n of t)n.startsWith(e)&&wx.removeStorageSync(n)}catch(e){console.warn("[WeChat] clearStorage failed:",e)}}},U=1920,D=1080,L={x:100,y:100},z={x:0,y:-9.81},W=1/60,H={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};const $={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function O(e,t){if(void 0!==t.maxDeltaTime&&(H.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(H.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(H.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(H.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(H.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");H.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(H.canvasScaleMode=$[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(H.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(H.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(H.assetFailureCooldown=t.assetFailureCooldown)}const V=4294967295,N=4294967295,j=new Map;function X(e,t){j.set(e,t)}function Y(e){return j.get(e)}function G(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(G);const t={};for(const n in e)t[n]=G(e[n]);return t}let q=0;function K(e,t){const n=++q,s=function(e){const t=[],n=[],s=[];let o=!1;for(const i in e){const r=e[i];null!==r&&"object"==typeof r?(o=!0,Array.isArray(r)?s.push(i):n.push(i)):t.push(i)}return o?{flatKeys:t,objectKeys:n,arrayKeys:s}:null}(t),o=t;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create(e){if(s){const t={...o};for(const e of s.objectKeys)t[e]={...o[e]};for(const e of s.arrayKeys)t[e]=o[e].slice();return e&&Object.assign(t,e),t}return e?{...t,...e}:{...t}}}}function J(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Q(e,t,n){const s=ne.get(e)??J().get(e);if(s)return s;const o=K(e,t);return J().set(e,o),ne.set(e,o),ee(e,t,!1),n?.entityFields&&X(e,n.entityFields),o}function Z(e){return J().get(e)}function ee(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function te(e){return!0===e._builtin}const ne=new Map;function se(e,t){ne.set(e,t)}function oe(e){return ne.get(e)??Z(e)}function ie(e){if(null===e||"object"!=typeof e)return[];const t=[];for(const n of Object.keys(e)){const s=e[n];if(null!==s&&"object"==typeof s&&!Array.isArray(s)){"r"in s&&"g"in s&&"b"in s&&"a"in s&&t.push(n)}}return t}function re(e,t,n){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t,_colorKeys:ie(t)};return ne.set(e,s),s}const ae={Perspective:0,Orthographic:1},le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ce={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ue={Circle:0,Capsule:1,RoundedRect:2},de=re("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),he=de,pe=de,fe=re("Sprite",{texture:V,color:{r:1,g:1,b:1,a:1},size:{x:L.x,y:L.y},pivot:{x:.5,y:.5},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),ge=re("ShapeRenderer",{shapeType:ue.Circle,color:{r:1,g:1,b:1,a:1},size:{x:100,y:100},cornerRadius:0,layer:0,enabled:!0}),me=re("Camera",{projectionType:ae.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth}),ye=re("Canvas",{designResolution:{x:U,y:D},pixelsPerUnit:100,scaleMode:ce.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),_e=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),xe=re("Parent",{entity:0}),we=re("Children",{entities:[]}),be=re("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:N,enabled:!0}),ve=re("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,enabled:!0}),Se={Point:0,Circle:1,Rectangle:2,Cone:3},Pe={World:0,Local:1},Me={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},Te=re("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:Se.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:Me.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:Me.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:V,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:Pe.World,enabled:!0}),Ce=Q("Name",{value:""}),Ee=Q("SceneOwner",{scene:"",persistent:!1}),Ae=Q("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});const Re=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ke=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},radius:.05,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ie=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Fe=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Be=re("SegmentCollider",{point1:{x:-.5,y:0},point2:{x:.5,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ue=Q("PolygonCollider",{vertices:[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}],radius:0,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),De=Q("ChainCollider",{points:[{x:-1,y:0},{x:0,y:.5},{x:1,y:0},{x:0,y:-.5}],isLoop:!0,friction:.6,restitution:0,categoryBits:1,maskBits:65535,enabled:!0}),Le=Q("RevoluteJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},enableMotor:!1,motorSpeed:0,maxMotorTorque:0,enableLimit:!1,lowerAngle:0,upperAngle:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),ze=Q("DistanceJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},length:1,enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,minLength:.5,maxLength:2,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),We=Q("PrismaticJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:1,y:0},enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),He=Q("WeldJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},linearHertz:0,angularHertz:0,linearDampingRatio:1,angularDampingRatio:1,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),$e=Q("WheelJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:0,y:1},enableSpring:!0,hertz:5,dampingRatio:.7,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorTorque:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Oe={Static:0,Kinematic:1,Dynamic:2};let Ve=0;function Ne(e,t){const n=++Ve;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function je(e){return{_type:"res",_resource:e}}function Xe(e){return{_type:"res_mut",_resource:e}}class Ye{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_)}updateValue(e){this.value_=e}}class Ge{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Ye(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const qe=Ne({delta:0,elapsed:0,frameCount:0},"Time"),Ke="esengine:",Je={getString(e,n){const s=t().getStorageItem(Ke+e);return null!==s?s:n},setString(e,n){t().setStorageItem(Ke+e,n)},getNumber(e,n){const s=t().getStorageItem(Ke+e);if(null===s)return n;const o=Number(s);return Number.isNaN(o)?n:o},setNumber(e,n){t().setStorageItem(Ke+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(Ke+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(Ke+e,String(n))},getJSON(e,n){const s=t().getStorageItem(Ke+e);if(null===s)return n;try{return JSON.parse(s)}catch(t){return console.warn(`[Storage] Failed to parse JSON for key "${e}"`,t),n}},setJSON(e,n){t().setStorageItem(Ke+e,JSON.stringify(n))},remove(e){t().removeStorageItem(Ke+e)},has:e=>null!==t().getStorageItem(Ke+e),clear(){t().clearStorage(Ke)}};function Qe(e,t,n){const s=[];for(const[e,o]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:o});continue}const n=Ze(t[e]),i=Ze(o);"null"!==n&&"undefined"!==n&&(n!==i&&null!=o&&s.push({field:e,expected:n,actual:i,value:o}))}return s}function Ze(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function et(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let tt=null;function nt(e){tt=e}function st(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),tt&&tt(e,t)}function ot(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={r:t.x,g:t.y,b:t.z,a:t.w})}return n}function it(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={x:t.r,y:t.g,z:t.b,w:t.a})}return n}const rt={Transform:{ptrFn:"getTransformPtr",fields:[{name:"position",type:"vec3",offset:0},{name:"rotation",type:"quat",offset:12},{name:"scale",type:"vec3",offset:28},{name:"worldPosition",type:"vec3",offset:40},{name:"worldRotation",type:"quat",offset:52},{name:"worldScale",type:"vec3",offset:68}]},Sprite:{ptrFn:"getSpritePtr",fields:[{name:"texture",type:"u32",offset:0},{name:"color",type:"color",offset:4},{name:"size",type:"vec2",offset:20},{name:"uvOffset",type:"vec2",offset:28},{name:"uvScale",type:"vec2",offset:36},{name:"layer",type:"i32",offset:44},{name:"flipX",type:"bool",offset:48},{name:"flipY",type:"bool",offset:49},{name:"material",type:"u32",offset:52},{name:"enabled",type:"bool",offset:56}]},Velocity:{ptrFn:"getVelocityPtr",fields:[{name:"linear",type:"vec3",offset:0},{name:"angular",type:"vec3",offset:12}]},Camera:{ptrFn:"getCameraPtr",fields:[{name:"projectionType",type:"u8",offset:0},{name:"fov",type:"f32",offset:4},{name:"orthoSize",type:"f32",offset:8},{name:"nearPlane",type:"f32",offset:12},{name:"farPlane",type:"f32",offset:16},{name:"aspectRatio",type:"f32",offset:20},{name:"isActive",type:"bool",offset:24},{name:"priority",type:"i32",offset:28},{name:"viewportX",type:"f32",offset:32},{name:"viewportY",type:"f32",offset:36},{name:"viewportW",type:"f32",offset:40},{name:"viewportH",type:"f32",offset:44},{name:"clearFlags",type:"i32",offset:48}]},UIRect:{ptrFn:"getUIRectPtr",fields:[{name:"anchorMin",type:"vec2",offset:0},{name:"anchorMax",type:"vec2",offset:8},{name:"offsetMin",type:"vec2",offset:16},{name:"offsetMax",type:"vec2",offset:24},{name:"size",type:"vec2",offset:32},{name:"pivot",type:"vec2",offset:40}]},RigidBody:{ptrFn:"getRigidBodyPtr",fields:[{name:"bodyType",type:"u8",offset:0},{name:"gravityScale",type:"f32",offset:4},{name:"linearDamping",type:"f32",offset:8},{name:"angularDamping",type:"f32",offset:12},{name:"fixedRotation",type:"bool",offset:16},{name:"bullet",type:"bool",offset:17},{name:"enabled",type:"bool",offset:18}]},BoxCollider:{ptrFn:"getBoxColliderPtr",fields:[{name:"halfExtents",type:"vec2",offset:0},{name:"offset",type:"vec2",offset:8},{name:"density",type:"f32",offset:16},{name:"friction",type:"f32",offset:20},{name:"restitution",type:"f32",offset:24},{name:"isSensor",type:"bool",offset:28},{name:"enabled",type:"bool",offset:29},{name:"categoryBits",type:"u32",offset:32},{name:"maskBits",type:"u32",offset:36}]},CircleCollider:{ptrFn:"getCircleColliderPtr",fields:[{name:"radius",type:"f32",offset:0},{name:"offset",type:"vec2",offset:4},{name:"density",type:"f32",offset:12},{name:"friction",type:"f32",offset:16},{name:"restitution",type:"f32",offset:20},{name:"isSensor",type:"bool",offset:24},{name:"enabled",type:"bool",offset:25},{name:"categoryBits",type:"u32",offset:28},{name:"maskBits",type:"u32",offset:32}]}};function at(e,t,n,s,o,i){const r=s+o.offset,a=r>>2;switch(o.type){case"f32":e[a]=i;break;case"i32":t[a]=0|i;break;case"u32":t[a]=i;break;case"bool":n[r]=i?1:0;break;case"u8":n[r]=i;break;case"vec2":e[a]=i.x,e[a+1]=i.y;break;case"vec3":e[a]=i.x,e[a+1]=i.y,e[a+2]=i.z;break;case"quat":e[a]=i.x,e[a+1]=i.y,e[a+2]=i.z,e[a+3]=i.w;break;case"color":e[a]=i.r,e[a+1]=i.g,e[a+2]=i.b,e[a+3]=i.a}}let lt=1;const ct=new WeakMap;function ut(e){let t=ct.get(e);return void 0===t&&(t=lt++,ct.set(e,t)),t}const dt=[];function ht(e,t=[],n=[]){dt.length=0;for(const t of e)dt.push(ut(t));dt.sort((e,t)=>e-t);let s=dt.join(",");if(t.length>0){dt.length=0;for(const e of t)dt.push(ut(e));dt.sort((e,t)=>e-t),s+="|+"+dt.join(",")}if(n.length>0){dt.length=0;for(const e of n)dt.push(ut(e));dt.sort((e,t)=>e-t),s+="|-"+dt.join(",")}return s}class pt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.builtinEntitySets_=new Map,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map,this.trackedComponents_=new Set}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}getWasmModule(){return this.module_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw st(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch(e){console.warn("[World] Spawn callback error:",e)}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch(e){console.warn("[World] Despawn callback error:",e)}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){st(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;for(const[,t]of this.builtinEntitySets_)t.delete(e);const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){st(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){st(t,`removeParent(entity=${e})`)}}insert(e,t,n){return te(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(te(t)){if(this.cppRegistry_)try{const s=t._default,o=n;let i=o;for(const e of Object.keys(o))e in s||(i===o&&(i={...o}),delete i[e]);this.getBuiltinMethods(t._cppName).add(e,it(i,t._colorKeys))}catch(n){st(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return te(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){if(t._builtin){if(!this.cppRegistry_)return!1;const n=t._cppName,s=this.builtinEntitySets_.get(n);return s?s.has(e):this.getBuiltinMethods(n).has(e)}return this.hasScript(e,t)}tryGet(e,t){if(te(t)){if(!this.cppRegistry_)return null;const n=this.builtinEntitySets_.get(t._cppName);if(n&&!n.has(e))return null;try{const s=this.getBuiltinMethods(t._cppName);return n||s.has(e)?ot(s.get(e),t._colorKeys):null}catch(n){return st(n,`tryGet(${t._name}, entity=${e})`),null}}const n=this.tsStorage_.get(t._id);if(!n)return null;const s=n.get(e);return void 0!==s?s:null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");te(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],o=n[`get${e}`],i=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof o||"function"!=typeof i||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:o.bind(n),has:i.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,o={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(o[e]=t);const e=Qe(t._name,s,o);if(e.length>0)throw new Error(et(t._name,e))}const i={...t._default,...o};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,it(i,t._colorKeys))}catch(n){st(n,`insertBuiltin(${t._name}, entity=${e})`)}let a=this.builtinEntitySets_.get(t._cppName);a||(a=new Set,this.builtinEntitySets_.set(t._cppName,a));const l=a.has(e);return!r&&l||(l||a.add(e),this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return ot(this.getBuiltinMethods(t._cppName).get(e),t._colorKeys)}catch(n){return st(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return st(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){st(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++,this.builtinEntitySets_.get(t._cppName)?.delete(e)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const o=Qe(t._name,t._default,e);if(o.length>0)throw new Error(et(t._name,o));s=e}const o=t.create(s),i=this.getStorage(t),r=!i.has(e);i.set(e,o);let a=this.entityComponents_.get(e);return a||(a=new Set,this.entityComponents_.set(e,a)),a.add(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);s&&s.delete(t._id)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resolveGetter(e){if(te(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrGetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?e=>t.get(e):e=>ot(t.get(e),n)}const t=this.tsStorage_.get(e._id);return t?e=>t.get(e):null}resolveHas(e){if(te(e)){if(!this.cppRegistry_)return null;const t=this.getBuiltinMethods(e._cppName);return e=>t.has(e)}const t=this.tsStorage_.get(e._id);return t?e=>t.has(e):null}resolveSetter(e){if(te(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrSetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?(e,n)=>t.add(e,n):(e,s)=>t.add(e,it(s,n))}const t=this.tsStorage_.get(e._id);return t?(e,n)=>t.set(e,n):null}resolvePtrFn_(e){const t=rt[e];if(!t)return null;const n=this.module_[t.ptrFn];if(!n)return null;const s=this.cppRegistry_;return e=>n(s,e)}resolvePtrSetter_(e){const t=rt[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,o=t.fields;return(e,t)=>{const i=n(e);if(!i)return;const r=t;for(let e=0;e<o.length;e++)at(s.HEAPF32,s.HEAPU32,s.HEAPU8,i,o[e],r[o[e].name])}}resolvePtrGetter_(e){const t=rt[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,o=t.fields,i=function(e){const t={};for(const n of e)switch(n.type){case"vec2":t[n.name]={x:0,y:0};break;case"vec3":t[n.name]={x:0,y:0,z:0};break;case"quat":t[n.name]={x:0,y:0,z:0,w:0};break;case"color":t[n.name]={r:0,g:0,b:0,a:0};break;default:t[n.name]=null}return t}(o);return e=>{const t=n(e);return t?(function(e,t,n,s,o,i){for(let r=0;r<o.length;r++){const a=o[r],l=s+a.offset,c=l>>2;switch(a.type){case"f32":i[a.name]=e[c];break;case"i32":i[a.name]=0|t[c];break;case"u32":i[a.name]=t[c];break;case"bool":i[a.name]=0!==n[l];break;case"u8":i[a.name]=n[l];break;case"vec2":{const t=i[a.name];t.x=e[c],t.y=e[c+1];break}case"vec3":{const t=i[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2];break}case"quat":{const t=i[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2],t.w=e[c+3];break}case"color":{const t=i[a.name];t.r=e[c],t.g=e[c+1],t.b=e[c+2],t.a=e[c+3];break}}}}(s.HEAPF32,s.HEAPU32,s.HEAPU8,t,o,i),i):null}}resetQueryPool(){}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch(e){console.warn(`[World] Component check failed for ${n}:`,e)}if(this.cppRegistry_)for(const[n,s]of ne)if(te(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch(e){console.warn(`[World] Builtin check failed for ${n}:`,e)}const n=this.entityComponents_.get(e);if(n){const e=J();for(const s of n)for(const[n,o]of e)if(o._id===s){t.add(n);break}}return Array.from(t)}resolveStorages_(e,t,n){for(const s of e)if(te(s)){if(!this.cppRegistry_)return!1;n.push(this.getBuiltinMethods(s._cppName))}else{const e=this.tsStorage_.get(s._id);if(!e)return!1;t.push(e)}return!0}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const o=s??ht(e,t,n),i=this.queryCache_.get(o);if(i&&i.version===this.worldVersion_)return i.result;const r=[],a=[],l=[];if(!this.resolveStorages_(e,a,l))return this.queryCache_.set(o,{version:this.worldVersion_,result:[]}),r;let c=null,u=null;if(t.length>0&&(c=[],u=[],!this.resolveStorages_(t,c,u)))return this.queryCache_.set(o,{version:this.worldVersion_,result:[]}),r;let d=null,h=null;n.length>0&&(d=[],h=[],this.resolveStorages_(n,d,h));let p=null,f=1/0;for(let e=0;e<a.length;e++){const t=a[e].size;t<f&&(f=t,p=a[e])}for(const t of e)if(te(t)){const e=this.builtinEntitySets_.get(t._cppName);e&&e.size<f&&(f=e.size,p=e)}const g=p?p.keys():this.entities_.keys(),m=a.length,y=l.length;for(const e of g){let t=!0;for(let n=0;n<m;n++)if(!a[n].has(e)){t=!1;break}if(t)for(let n=0;n<y;n++)if(!l[n].has(e)){t=!1;break}if(t&&c){for(let n=0;n<c.length;n++)if(!c[n].has(e)){t=!1;break}if(t)for(let n=0;n<u.length;n++)if(!u[n].has(e)){t=!1;break}}if(t&&d){for(let n=0;n<d.length;n++)if(d[n].has(e)){t=!1;break}if(t)for(let n=0;n<h.length;n++)if(h[n].has(e)){t=!1;break}}t&&r.push(e)}return this.queryCache_.set(o,{version:this.worldVersion_,result:r}),r}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}enableChangeTracking(e){this.trackedComponents_.add(e._id)}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const o=s.get(e);return void 0!==o&&o>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const o=s.get(e);return void 0!==o&&o>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}markChanged(e,t){this.recordChangedTick_(t,e)}recordChangedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function ft(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function gt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function mt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function yt(e){return ft(e)||gt(e)||mt(e)?e._component:e}function _t(e,t=[],n=[]){const s=[],o=[],i=[];return e.forEach((e,t)=>{ft(e)&&s.push(t),gt(e)?o.push({index:t,component:e._component}):mt(e)&&i.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:o,_changedFilters:i,with:(...s)=>_t(e,[...t,...s],n),without:(...s)=>_t(e,t,[...n,...s])}}function xt(...e){return _t(e)}class wt{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(yt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=ht(this.allRequired_,t._with,t._without),this.getters_=this.actualComponents_.map(t=>e.resolveGetter(t)),this.mutSetters_=t._mutIndices.map(t=>e.resolveSetter(this.actualComponents_[t])),this.mutIsBuiltin_=t._mutIndices.map(e=>te(this.actualComponents_[e]));for(const n of t._addedFilters)e.enableChangeTracking(n.component);for(const n of t._changedFilters)e.enableChangeTracking(n.component)}resetTick(e){this.lastRunTick_=e}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,o=e.length>0,i=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,d=this.getters_,h=this;let p=0,f=null,g=!1,m=!1;const y=this.mutIsBuiltin_,_=()=>{for(let e=0;e<l;e++){const t=a[e];if(y[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}},x=()=>{m||(m=!0,u.endIteration(),null!==f&&o&&_())},w={value:r,done:!1},b={value:void 0,done:!0};return{next(){for(g||(g=!0,u.beginIteration());p<n.length;){const c=n[p++];if(!i||h.passesChangeFilters_(c)){null!==f&&o&&_(),r[0]=c;for(let e=0;e<s;e++){const n=d[e];r[e+1]=n?n(c):u.get(c,t[e])}if(o){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];f=c}return w}}return x(),b},return:()=>(x(),b)}}forEach(e){const{_mutIndices:t}=this.descriptor_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=this.actualComponents_.length,o=t.length>0,i=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,d=this.getters_,h=this.actualComponents_;u.beginIteration();let p=null;for(let f=0;f<n.length;f++){const g=n[f];if(!i||this.passesChangeFilters_(g)){if(null!==p&&o)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(p,t.data):u.set(p,t.component,t.data)}else u.markChanged(p,t.component)}r[0]=g;for(let e=0;e<s;e++){const t=d[e];r[e+1]=t?t(g):u.get(g,h[e])}if(o){for(let e=0;e<l;e++)a[e].data=r[t[e]+1];p=g}switch(s){case 1:e(g,r[1]);break;case 2:e(g,r[1],r[2]);break;case 3:e(g,r[1],r[2],r[3]);break;default:e.apply(null,r)}}}if(null!==p&&o)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(p,t.data):u.set(p,t.component,t.data)}else u.markChanged(p,t.component)}u.endIteration()}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class bt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n,e.enableChangeTracking(t)}resetTick(e){this.lastRunTick_=e}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}class vt{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=te(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 St{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new vt(this,null);return this.spawned_.push(e),e}entity(e){return new vt(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}class Pt{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class Mt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Pt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Pt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class Tt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ct{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Et;function At(){return{_type:"get_world"}}exports.Schedule=void 0,(Et=exports.Schedule||(exports.Schedule={}))[Et.Startup=0]="Startup",Et[Et.First=1]="First",Et[Et.PreUpdate=2]="PreUpdate",Et[Et.Update=3]="Update",Et[Et.PostUpdate=4]="PostUpdate",Et[Et.Last=5]="Last",Et[Et.FixedPreUpdate=10]="FixedPreUpdate",Et[Et.FixedUpdate=11]="FixedUpdate",Et[Et.FixedPostUpdate=12]="FixedPostUpdate";let Rt=0;function kt(e,t,n){const s=++Rt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function It(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class Ft{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.queryCache_=new Map,this.removedCache_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;let n=this.queryCache_.get(e._id),s=this.removedCache_.get(e._id);const o=!n;o&&(n=[],s=[],this.queryCache_.set(e._id,n),this.removedCache_.set(e._id,s));let i=0,r=0;for(let a=0;a<e._params.length;a++){const l=e._params[a];if("query"===l._type){if(o){const e=new wt(this.world_,l,this.currentLastRunTick_);n.push(e),t[a]=e}else{const e=n[i];e.resetTick(this.currentLastRunTick_),t[a]=e}i++}else if("removed"===l._type){if(o){const e=l,n=new bt(this.world_,e._component,this.currentLastRunTick_);s.push(n),t[a]=n}else{const e=s[r];e.resetTick(this.currentLastRunTick_),t[a]=e}r++}else t[a]=this.resolveParam(l)}const a=this.timings_?performance.now():0;let l;try{l=e._fn(...t)}catch(n){throw this.flushSystem_(e,t,a),n}if(l instanceof Promise)return l.then(()=>{this.flushSystem_(e,t,a)},n=>{throw this.flushSystem_(e,t,a),n});this.flushSystem_(e,t,a)}flushSystem_(e,t,n){for(let e=0;e<t.length;e++)t[e]instanceof St&&t[e].flush();this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}resolveParam(e){switch(e._type){case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new St(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Tt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ct(n)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Bt{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 Ut=Ne(new Bt,"Input");class Dt{constructor(e){this.target_=e??null}build(e){const n=new Bt;e.insertResource(Ut,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,kt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Lt=new Dt,zt=Ne({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Wt;function Ht(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(Wt=exports.BlendMode||(exports.BlendMode={}))[Wt.Normal=0]="Normal",Wt[Wt.Additive=1]="Additive",Wt[Wt.Multiply=2]="Multiply",Wt[Wt.Screen=3]="Screen",Wt[Wt.PremultipliedAlpha=4]="PremultipliedAlpha";let $t=null,Ot=null,Vt=1;const Nt=new Map;function jt(e){$t=e,Ot=e.getResourceManager(),tn()}function Xt(){0!==Kt&&$t&&($t._free(Kt),Kt=0),Nt.clear(),Vt=1,qt=!1,Qt.clear(),Zt=null,Ot=null,$t=null}function Yt(){if(!Ot)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ot}const Gt={createShader:(e,t)=>Yt().createShader(e,t),releaseShader(e){e>0&&Yt().releaseShader(e)},create(e){const t=Vt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Nt.set(t,n),t},get:e=>Nt.get(e),setUniform(e,t,n){const s=Nt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,$t?.invalidateMaterialCache(e))},getUniform(e,t){const n=Nt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Nt.get(e);n&&(n.blendMode=t,$t?.invalidateMaterialCache(e))},getBlendMode(e){const t=Nt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const n=Nt.get(e);n&&(n.depthTest=t,$t?.invalidateMaterialCache(e))},getShader(e){const t=Nt.get(e);return t?.shader??0},release(e){Nt.delete(e),$t?.invalidateMaterialCache(e)},isValid:e=>Nt.has(e),releaseAll(){Nt.clear(),$t?.clearMaterialCache()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Nt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Vt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Nt.set(n,s),n},toAssetData(e,t){const n=Nt.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=Nt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let qt=!1,Kt=0;const Jt=16384,Qt=new Map;let Zt=null;function en(e){const t=(0===Kt&&$t&&(Kt=$t._malloc(Jt)),Kt);if(0===t||!$t)return{ptr:0,count:0};let n=0,s=0;const o=$t.HEAPU8,i=$t.HEAPU32,r=$t.HEAPF32;for(const[a,l]of e){if(Ht(l))continue;let e=Qt.get(a);e||(Zt||(Zt=new TextEncoder),e=Zt.encode(a),Qt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Jt){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Jt} bytes), skipping remaining uniforms`);break}i[t+n>>2]=c,n+=4,o.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);i[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function tn(){if(!$t||qt)return;$t.materialDataProvider=(e,t,n,s,o)=>{const i=Nt.get(e);if(!i)return $t.HEAPU32[t>>2]=0,$t.HEAPU32[n>>2]=0,$t.HEAPU32[s>>2]=0,void($t.HEAPU32[o>>2]=0);$t.HEAPU32[t>>2]=i.shader,$t.HEAPU32[n>>2]=i.blendMode;const{ptr:r,count:a}=en(i.uniforms);$t.HEAPU32[s>>2]=r,$t.HEAPU32[o>>2]=a},qt=!0}const nn={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 sn{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=H.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const o=this.failed_.get(e);if(o&&Date.now()<o.expiry)throw o.error;this.failed_.delete(e);const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),o=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,o),this.pending_.delete(e),o})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+H.assetFailureCooldown}),t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`)),t}}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()}clearAll(){this.cache_.clear(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class on{constructor(e,t=""){this.cache_=new sn,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Gt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Gt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await r(t))throw new Error(`Material file not found: ${t}`);const n=await i(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 o=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(o);return{handle:Gt.createFromAsset(s,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function rn(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function an(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0,duration:e.duration};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const ln=new Map;function cn(e){ln.set(e.name,e)}const un=Q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function dn(e,t){const n=e.getEntitiesWithComponents([un]);for(const s of n){const n=e.get(s,un);if(!n.enabled||!n.playing||!n.clip)continue;const o=ln.get(n.clip);if(!o||0===o.frames.length)continue;const i=o.frames[n.currentFrame],r=i?.duration??1/(o.fps*n.speed),a=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let l=a;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=o.frames.length&&(n.loop&&o.loop?n.currentFrame=0:(n.currentFrame=o.frames.length-1,n.playing=!1)),l=!0),l&&e.has(s,fe)){const t=o.frames[n.currentFrame],i=e.get(s,fe);i.texture=t.texture,t.uvOffset&&(i.uvOffset=t.uvOffset,i.uvScale=t.uvScale),e.insert(s,fe,i)}l&&e.insert(s,un,n)}}class hn{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static setAssetResolver(e){this.assetResolver_=e}static resolveUrl_(e){return!this.baseUrl||e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}/${e}`}static async preload(e){if(this.bufferCache_.has(e))return;if(this.assetResolver_){const t=this.assetResolver_(e);if(t)return this.preloadFromData(e,t)}const t=await this.backend_.loadBuffer(this.resolveUrl_(e));this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const o=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:o?0:n,loop:!0}),o&&this.fadeIn(this.bgmHandle_,o,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),o=()=>{const i=(performance.now()-s)/1e3,r=Math.min(i/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(o):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(o)}static fadeOut(e,t,n){const s=performance.now(),o=()=>{const i=(performance.now()-s)/1e3,r=Math.min(i/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(o):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(o)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}hn.mixer_=null,hn.bufferCache_=new Map,hn.bgmHandle_=null,hn.bgmVolume_=1,hn.fadeAnimId_=0,hn.disposed_=!1,hn.assetResolver_=null,hn.baseUrl="";const pn=new Map,fn=new Map;function gn(e,t,n){pn.set(e,{width:t,height:n})}function mn(e){return pn.get(e)}function yn(){pn.clear()}function _n(e,t){fn.set(e,t)}function xn(e){return fn.get(e)}let wn=null;function bn(e){wn=e}function vn(){wn=null}const Sn={initLayer(e,t,n,s,o){wn?.tilemap_initLayer(e,t,n,s,o)},destroyLayer(e){wn?.tilemap_destroyLayer(e)},setTile(e,t,n,s){wn?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>wn?wn.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,o,i){wn?.tilemap_fillRect(e,t,n,s,o,i)},setTiles(e,t){if(!wn)return;const n=t.byteLength,s=wn._malloc(n);new Uint16Array(wn.HEAPU8.buffer,s,t.length).set(t),wn.tilemap_setTiles(e,s,t.length),wn._free(s)},hasLayer:e=>!!wn&&wn.tilemap_hasLayer(e),setRenderProps(e,t,n,s,o,i,r,a,l){wn?.tilemap_setRenderProps(e,t,n,s,o,i,r,a,l)},setTint(e,t,n,s,o,i){wn?.tilemap_setTint(e,t,n,s,o,i)},setVisible(e,t){wn?.tilemap_setVisible(e,t)},setOriginEntity(e,t){wn?.tilemap_setOriginEntity(e,t)},submitLayer(e,t,n,s,o,i,r,a,l,c,u,d,h,p,f,g,m,y,_,x){wn?.tilemap_submitLayer(e,t,n,s,o,i,r,a,l,c,u,d,h,p,f,g,m,y,_,x)},setTileAnimation(e,t,n){if(!wn||0===n.length)return;const s=new Uint32Array(2*n.length);for(let e=0;e<n.length;e++)s[2*e]=n[e].tileId,s[2*e+1]=n[e].duration;const o=s.byteLength,i=wn._malloc(o);new Uint32Array(wn.HEAPU8.buffer,i,s.length).set(s),wn.tilemap_setTileAnimation(e,t,i,n.length),wn._free(i)},advanceAnimations(e,t){wn?.tilemap_advanceAnimations(e,t)},setTileProperty(e,t,n,s){wn?.tilemap_setTileProperty(e,t,n,s)},getTileProperty:(e,t,n,s)=>wn?wn.tilemap_getTileProperty(e,t,n,s):"",flipTile(e,t,n,s,o,i){wn?.tilemap_flipTile(e,t,n,s,o,i)},rotateTile(e,t,n,s){wn?.tilemap_rotateTile(e,t,n,s)},setGridType(e,t){wn?.tilemap_setGridType(e,t)},tileToWorld(e,t,n,s,o){if(!wn)return{x:0,y:0};const i=wn.tilemap_tileToWorld(e,t,n,s,o),r=new Float32Array(wn.HEAPU8.buffer,i,2);return{x:r[0],y:r[1]}},worldToTile(e,t,n,s,o){if(!wn)return{x:0,y:0};const i=wn.tilemap_worldToTile(e,t,n,s,o),r=new Float32Array(wn.HEAPU8.buffer,i,2);return{x:r[0],y:r[1]}}},Pn=Q("Tilemap",{source:""}),Mn=Q("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function Tn(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function Cn(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function En(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function An(e){const t=e.width,n=e.height,s=e.tilewidth??0,o=e.tileheight??0;if(!(t&&n&&s&&o))return null;const i=e.tilesets,r=[],a=[];if(i)for(const e of i){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??o,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,o=e.height??n,i=!1!==e.visible,r=e.data,l=new Uint16Array(s*o);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=En(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=Cn(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,p="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:o,visible:i,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:p})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let o="rect",i=null;if(e.ellipse)o="ellipse";else if(e.point)o="point";else if(e.polygon){o="polygon";const t=e.polygon;i=[];for(const e of t)i.push(e.x,e.y)}else if(e.polyline){o="polygon";const t=e.polyline;i=[];for(const e of t)i.push(e.x,e.y)}n.push({shape:o,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:i,properties:t})}u.push({name:e.name??"",objects:n})}const h=new Map,p=new Map;if(i)for(const e of i){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.id,s=n+1,o=e.animation;if(o&&o.length>0){const e=o.map(e=>({tileId:(e.tileid??0)+1,duration:e.duration??100}));h.set(s,e)}const i=e.properties;if(i){const e=new Map;for(const s of i){const o=s.name;"collision"===o&&!0===s.value&&d.push(n+t),e.set(o,String(s.value))}e.size>0&&p.set(s,e)}}}return{width:t,height:n,tileWidth:s,tileHeight:o,orientation:e.orientation??"orthogonal",layers:c,tilesets:r,objectGroups:u,collisionTileIds:d,tileAnimations:h,tileProperties:p}}function Rn(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),o=[];for(const e of s)".."===e?o.pop():"."!==e&&""!==e&&o.push(e);return o.join("/")}const kn=Math.PI/180;function In(e,t,n,s,o,i){const r=function(e,t,n,s){const o=new Uint8Array(t*n),i=[],r=(i,r)=>{if(i>=t||r>=n)return!1;const a=r*t+i;if(o[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let i=0;i<a;i++)o[(e+n)*t+(s+i)]=1;i.push({col:s,row:e,width:a,height:l})}return i}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=o+t.col*l+.5*n,d=i+(u-t.row*c)-.5*s,h=e.spawn();e.insert(h,de,{position:{x:r,y:d,z:0}}),e.insert(h,Re,{bodyType:Oe.Static}),e.insert(h,ke,{halfExtents:{x:.5*n,y:.5*s}}),a.push(h)}return a}const Fn=0,Bn=1,Un=2,Dn="property",Ln="spine",zn="spriteAnim",Wn="audio",Hn="activation",$n="marker",On="customEvent",Vn="animFrames",Nn="hermite",jn="linear",Xn="step",Yn="easeIn",Gn="easeOut",qn="easeInOut",Kn=[["1.0","1.1",e=>{for(const t of e.tracks??[])if(t.type===Dn)for(const e of t.channels??[])for(const t of e.keyframes??[])t.interpolation||Math.abs(t.outTangent)>=1e5&&(t.interpolation="step",t.outTangent=0)}]];const Jn={once:Fn,loop:Bn,pingPong:Un};function Qn(e){const t={name:e.name??"",childPath:e.childPath??""};switch(e.type){case Dn:return{...t,type:Dn,component:e.component??"",channels:(e.channels??[]).map(e=>({property:e.property,keyframes:e.keyframes??[]}))};case Ln:return{...t,type:Ln,clips:e.clips??[],blendIn:e.blendIn??0};case zn:return{...t,type:zn,clip:e.clip??"",startTime:e.startTime??0};case Wn:return{...t,type:Wn,events:e.events??[]};case Hn:return{...t,type:Hn,ranges:e.ranges??[]};case $n:return{...t,type:$n,markers:e.markers??[]};case On:return{...t,type:On,events:(e.events??[]).map(e=>({time:e.time??0,name:e.name??"",payload:e.payload??{}}))};case Vn:return{...t,type:Vn,frames:(e.animFrames??[]).map(e=>({texture:e.texture??"",duration:e.duration}))};default:return console.warn(`[Timeline] Unknown track type: ${e.type}, skipping`),null}}function Zn(e){return function(e){let t=e.version??"1.0";for(const[n,s,o]of Kn)t===n&&(o(e),t=s);e.version="1.1"}(e),{version:"1.1",type:"timeline",duration:e.duration??0,wrapMode:(t=e.wrapMode,t?Jn[t]??Fn:Fn),tracks:(e.tracks??[]).map(Qn).filter(e=>null!==e)};var t}let es=!1,ts=!1;function ns(){return es}function ss(){return ts}var os,is;!function(e){e[e.PositionX=0]="PositionX",e[e.PositionY=1]="PositionY",e[e.PositionZ=2]="PositionZ",e[e.ScaleX=3]="ScaleX",e[e.ScaleY=4]="ScaleY",e[e.ScaleZ=5]="ScaleZ",e[e.RotationZ=6]="RotationZ",e[e.ColorR=7]="ColorR",e[e.ColorG=8]="ColorG",e[e.ColorB=9]="ColorB",e[e.ColorA=10]="ColorA",e[e.SpriteOpacity=11]="SpriteOpacity",e[e.SpriteSizeX=12]="SpriteSizeX",e[e.SpriteSizeY=13]="SpriteSizeY",e[e.OffsetMinX=14]="OffsetMinX",e[e.OffsetMinY=15]="OffsetMinY",e[e.OffsetMaxX=16]="OffsetMaxX",e[e.OffsetMaxY=17]="OffsetMaxY",e[e.AnchorMinX=18]="AnchorMinX",e[e.AnchorMinY=19]="AnchorMinY",e[e.AnchorMaxX=20]="AnchorMaxX",e[e.AnchorMaxY=21]="AnchorMaxY",e[e.PivotX=22]="PivotX",e[e.PivotY=23]="PivotY",e[e.CameraOrthoSize=24]="CameraOrthoSize",e[e.CustomField=25]="CustomField"}(os||(os={})),function(e){e[e.Transform=0]="Transform",e[e.Sprite=1]="Sprite",e[e.UIRect=2]="UIRect",e[e.Camera=3]="Camera",e[e.Custom=4]="Custom"}(is||(is={}));const rs={Transform:{"position.x":os.PositionX,"position.y":os.PositionY,"position.z":os.PositionZ,"scale.x":os.ScaleX,"scale.y":os.ScaleY,"scale.z":os.ScaleZ,rotation:os.RotationZ},Sprite:{"color.r":os.ColorR,"color.g":os.ColorG,"color.b":os.ColorB,"color.a":os.ColorA,opacity:os.SpriteOpacity,"size.x":os.SpriteSizeX,"size.y":os.SpriteSizeY},UIRect:{"offsetMin.x":os.OffsetMinX,"offsetMin.y":os.OffsetMinY,"offsetMax.x":os.OffsetMaxX,"offsetMax.y":os.OffsetMaxY,"anchorMin.x":os.AnchorMinX,"anchorMin.y":os.AnchorMinY,"anchorMax.x":os.AnchorMaxX,"anchorMax.y":os.AnchorMaxY,"pivot.x":os.PivotX,"pivot.y":os.PivotY},Camera:{orthoSize:os.CameraOrthoSize}},as={Transform:is.Transform,Sprite:is.Sprite,UIRect:is.UIRect,Camera:is.Camera},ls={[Nn]:0,[jn]:1,[Xn]:2,[Yn]:3,[Gn]:4,[qn]:5};function cs(e){return e?ls[e]??0:0}function us(e,t){return rs[e]?.[t]??os.CustomField}function ds(e,t){const n=(new TextEncoder).encode(t),s=e._malloc(n.length);return new Uint8Array(e.HEAPU8.buffer,s,n.length).set(n),[s,n.length]}function hs(e,t){e._free(t)}function ps(e,t){const n=e._tl_create(t.duration,t.wrapMode);if(!n)return{handle:0,tracks:[],totalPropertyChannels:0};const s=[];let o=0;for(const i of t.tracks)switch(i.type){case Dn:fs(e,n,i),s.push({type:"property",component:i.component,childPath:i.childPath,channelProperties:i.channels.map(e=>e.property)}),o+=i.channels.length;break;case Ln:gs(e,n,i),s.push({type:"spine",childPath:i.childPath});break;case Wn:ms(e,n,i),s.push({type:"audio",childPath:i.childPath});break;case Hn:ys(e,n,i),s.push({type:"activation",childPath:i.childPath});break;case zn:_s(e,n,i),s.push({type:"spriteAnim",childPath:i.childPath})}return{handle:n,tracks:s,totalPropertyChannels:o}}function fs(e,t,n){const s=e,o=n.channels.length,i=as[n.component]??is.Custom;if(i===is.Custom)return void function(e,t,n){const s=e,o=n.channels.length,[i,r]=ds(e,n.childPath),[a,l]=ds(e,n.component),c=n.channels.map(e=>(new TextEncoder).encode(e.property));let u=0;for(const e of c)u+=e.length;const d=s._malloc(u);let h=0;for(const e of c)new Uint8Array(s.HEAPU8.buffer,d+h,e.length).set(e),h+=e.length;const p=s._malloc(4*o);new Int32Array(s.HEAPU8.buffer,p,o).set(c.map(e=>e.length));let f=0;const g=[];for(const e of n.channels)g.push(e.keyframes.length),f+=e.keyframes.length;const m=s._malloc(4*o);new Int32Array(s.HEAPU8.buffer,m,o).set(g);const y=s._malloc(5*f*4),_=new Float32Array(s.HEAPU8.buffer,y,5*f);let x=0;for(const e of n.channels)for(const t of e.keyframes)_[x++]=t.time,_[x++]=t.value,_[x++]=t.inTangent,_[x++]=t.outTangent,_[x++]=cs(t.interpolation);e._tl_addCustomPropertyTrack(t,i,r,a,l,d,p,o,y,m),hs(e,i),hs(e,a),hs(e,d),hs(e,p),hs(e,m),hs(e,y)}(e,t,n);const[r,a]=ds(e,n.childPath),l=s._malloc(o),c=new Uint8Array(s.HEAPU8.buffer,l,o);for(let e=0;e<o;e++)c[e]=us(n.component,n.channels[e].property);let u=0;const d=[];for(const e of n.channels)d.push(e.keyframes.length),u+=e.keyframes.length;const h=s._malloc(4*o);new Int32Array(s.HEAPU8.buffer,h,o).set(d);const p=s._malloc(5*u*4),f=new Float32Array(s.HEAPU8.buffer,p,5*u);let g=0;for(const e of n.channels)for(const t of e.keyframes)f[g++]=t.time,f[g++]=t.value,f[g++]=t.inTangent,f[g++]=t.outTangent,f[g++]=cs(t.interpolation);e._tl_addPropertyTrack(t,r,a,i,l,o,p,h),hs(e,r),hs(e,l),hs(e,h),hs(e,p)}function gs(e,t,n){if(n.type!==Ln)return;const s=e,[o,i]=ds(e,n.childPath),r=n.clips.length,a=s._malloc(4*r*4),l=new Float32Array(s.HEAPU8.buffer,a,4*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),d=s._malloc(4*r),h=new Int32Array(s.HEAPU8.buffer,d,r),p=[];for(let t=0;t<r;t++){const s=n.clips[t];l[4*t]=s.start,l[4*t+1]=s.duration,l[4*t+2]=s.speed,l[4*t+3]=s.loop?1:0;const[o,i]=ds(e,s.animation);u[t]=o,h[t]=i,p.push(o)}e._tl_addSpineTrack(t,o,i,a,c,d,r,n.blendIn),hs(e,o),hs(e,a),hs(e,c),hs(e,d);for(const t of p)hs(e,t)}function ms(e,t,n){if(n.type!==Wn)return;const s=e,[o,i]=ds(e,n.childPath),r=n.events.length,a=s._malloc(2*r*4),l=new Float32Array(s.HEAPU8.buffer,a,2*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),d=s._malloc(4*r),h=new Int32Array(s.HEAPU8.buffer,d,r),p=[];for(let t=0;t<r;t++){const s=n.events[t];l[2*t]=s.time,l[2*t+1]=s.volume;const[o,i]=ds(e,s.clip);u[t]=o,h[t]=i,p.push(o)}e._tl_addAudioTrack(t,o,i,a,c,d,r),hs(e,o),hs(e,a),hs(e,c),hs(e,d);for(const t of p)hs(e,t)}function ys(e,t,n){if(n.type!==Hn)return;const s=e,[o,i]=ds(e,n.childPath),r=s._malloc(2*n.ranges.length*4),a=new Float32Array(s.HEAPU8.buffer,r,2*n.ranges.length);for(let e=0;e<n.ranges.length;e++)a[2*e]=n.ranges[e].start,a[2*e+1]=n.ranges[e].end;e._tl_addActivationTrack(t,o,i,r,n.ranges.length),hs(e,o),hs(e,r)}function _s(e,t,n){if(n.type!==zn)return;const[s,o]=ds(e,n.childPath),[i,r]=ds(e,n.clip);e._tl_addSpriteAnimTrack(t,s,o,i,r,n.startTime),hs(e,s),hs(e,i)}const xs=new Map;let ws=null;function bs(e,t){xs.set(e,t)}var vs;exports.AttenuationModel=void 0,(vs=exports.AttenuationModel||(exports.AttenuationModel={}))[vs.Linear=0]="Linear",vs[vs.Inverse=1]="Inverse",vs[vs.Exponential=2]="Exponential";const Ss={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Ps(e,t=Ss){const{model:n,refDistance:s,maxDistance:o,rolloff:i}=t,r=Math.max(e,.001);let a;switch(n){case exports.AttenuationModel.Linear:{const e=o-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),o)-s)/e;break}case exports.AttenuationModel.Inverse:a=s/Math.max(r,s);break;case exports.AttenuationModel.Exponential:a=Math.pow(Math.max(r,s)/s,-i);break;default:return 1}return Math.max(0,Math.min(1,a))}function Ms(e,t,n,s,o){const i=e-n;return Math.max(-1,Math.min(1,i/o))}const Ts=Q("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:exports.AttenuationModel.Inverse,rolloff:1,priority:0,enabled:!0}),Cs=Q("AudioListener",{enabled:!0});class Es{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const o=n.mixer;hn.init(n,o),o&&(void 0!==s.masterVolume&&(o.master.volume=s.masterVolume),void 0!==s.musicVolume&&(o.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(o.sfx.volume=s.sfxVolume));const i=new Map;this.activeSourceHandles_=i;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(qe)],t=>{if(!(!ns()||ss()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let o=0,u=0,d=!1;const h=s.getEntitiesWithComponents([Cs,pe]);for(const e of h){if(s.get(e,Cs).enabled){const t=s.get(e,pe);o=t.position.x,u=t.position.y,d=!0;break}}const p=s.getEntitiesWithComponents([Ts]);a.clear();for(const e of p){const t=s.get(e,Ts);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!i.has(c)&&n.isReady){const e=hn.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});i.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&i.has(c)){const n=i.get(c);if(!n.isPlaying){i.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,pe),a=r?.position.x??0,h=r?.position.y??0,p=a-o,f=h-u,g=Ps(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),m=Ms(a,0,o,0,t.maxDistance);n.setVolume(t.volume*g),n.setPan(m)}}for(const[e,t]of i)a.has(e)&&t.isPlaying||i.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),hn.dispose()}}const As=new Es,Rs=Q("TimelinePlayer",{timeline:"",playing:!1,speed:1,wrapMode:"once"}),ks=new Map;function Is(e,t){ks.set(e,t)}const Fs=new Map;function Bs(e,t){return Fs.get(e)?.get(t)??0}const Us={once:Fn,loop:Bn,pingPong:Un};function Ds(e,t,n){const s=t.split(".");let o=e;for(let e=0;e<s.length-1;e++)if(o=o[s[e]],null==o||"object"!=typeof o)return!1;const i=s[s.length-1];return i in o&&(o[i]=n,!0)}function Ls(e,t,n){if(!n)return t;const s=oe("Children"),o=oe("Name");if(!s||!o)return null;let i=t;const r=n.split("/");for(const t of r){const n=e.tryGet(i,s);if(!n)return null;const r=n.entities||[];let a=null;for(const n of r){const s=e.tryGet(n,o);if(s&&s.value===t){a=n;break}}if(null===a)return null;i=a}return i}class zs{constructor(){this.name="TimelinePlugin",this.handles_=new Map,this.animFramesStates_=new Map}build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,kt([je(qe)],e=>{if(ns()&&!ss())return;const n=t.getWasmModule();if(!n)return;ws=n;const s=t.getCppRegistry();n.uiRect_clearAnimOverrides(s);const o=t.getEntitiesWithComponents([Rs]);for(const s of o){const o=t.get(s,Rs);if(!o.timeline)continue;let i=this.handles_.get(s);if(!i){const e=ks.get(o.timeline);if(!e)continue;if(i=ps(n,e),!i.handle)continue;this.resolveTrackTargets(t,n,i,s),this.handles_.set(s,i),bs(s,i.handle);const r=e.tracks.filter(e=>e.type===Vn);r.length>0&&this.animFramesStates_.set(s,{tracks:r,lastFrameIndices:r.map(()=>-1)})}const r=i.handle;if(o.playing&&!n._tl_isPlaying(r)){const e=n._tl_getTime(r);0===e?n._tl_play(r):(n._tl_play(r),n._tl_setTime(r,e))}else!o.playing&&n._tl_isPlaying(r)&&n._tl_pause(r);const a=Us[o.wrapMode]??Fn;n._tl_setWrapMode(r,a),n._tl_advance(t.getCppRegistry(),r,s,e.delta,o.speed),this.processEvents(t,n),this.processCustomProperties(t,n,i),this.processAnimFrames(t,n,s,i.handle,o.timeline),n._tl_clearResults(),!n._tl_isPlaying(r)&&o.playing&&(o.playing=!1,t.insert(s,Rs,o))}},{name:"TimelineSystem"}))}clearHandles(){this.handles_.clear(),this.animFramesStates_.clear()}cleanup(){this.handles_.clear(),this.animFramesStates_.clear(),ks.clear()}processAnimFrames(e,t,n,s,o){const i=this.animFramesStates_.get(n);if(!i)return;const r=t._tl_getTime(s),a=oe("Sprite");if(!a||!e.has(n,a))return;const l=1/12;for(let t=0;t<i.tracks.length;t++){const s=i.tracks[t].frames;if(0===s.length)continue;let c=0,u=0;for(let e=0;e<s.length;e++){const t=s[e].duration??l;if(r<c+t){u=e;break}c+=t,e===s.length-1&&(u=s.length-1)}if(u!==i.lastFrameIndices[t]){i.lastFrameIndices[t]=u;const r=Bs(o,s[u].texture);if(r){const t=e.get(n,a);t.texture=r,e.set(n,a,t)}}}}resolveTrackTargets(e,t,n,s){let o=0,i=0;for(const r of n.tracks){if(!r.childPath){"property"===r.type?o++:i++;continue}const a=Ls(e,s,r.childPath);if(null!==a){const e="property"!==r.type,s=e?i:o;t._tl_setTrackTarget(n.handle,e?1:0,s,a)}"property"===r.type?o++:i++}}decodeEventString(e,t){const n=e._tl_getEventString(t),s=e._tl_getEventStringLen(t);if(!n||s<=0)return"";const o=new Uint8Array(e.HEAPU8.buffer,n,s);return(new TextDecoder).decode(o)}processEvents(e,t){const n=t._tl_getEventCount();for(let s=0;s<n;s++){const n=t._tl_getEventType(s),o=t._tl_getEventEntity(s);switch(n){case 0:{const n=this.decodeEventString(t,s),i=0!==t._tl_getEventIntParam(s);if(e.has(o,ve)){const t=e.get(o,ve);t.animation=n,t.playing=!0,t.loop=i,e.set(o,ve,t)}break}case 1:if(e.has(o,ve)){const t=e.get(o,ve);t.playing=!1,e.set(o,ve,t)}break;case 2:{const n=this.decodeEventString(t,s);if(e.has(o,un)){const t=e.get(o,un);e.insert(o,un,{...t,clip:n,playing:!0})}break}case 3:{const e=this.decodeEventString(t,s),n=t._tl_getEventFloatParam(s);e&&hn.playSFX(e,{volume:n});break}case 4:{const n=0!==t._tl_getEventIntParam(s);if(e.has(o,ve)){const t=e.get(o,ve);t.enabled=n,e.set(o,ve,t)}if(e.has(o,un)){const t=e.get(o,un);e.insert(o,un,{...t,enabled:n})}const i=oe("Sprite");if(i&&e.has(o,i)){const t=e.get(o,i);e.set(o,i,{...t,enabled:n})}break}}}}processCustomProperties(e,t,n){const s=t._tl_getCustomPropertyCount();if(0!==s)for(let o=0;o<s;o++){const s=t._tl_getCustomPropertyEntity(o),i=t._tl_getCustomPropertyTrackIndex(o),r=t._tl_getCustomPropertyChannelIndex(o),a=t._tl_getCustomPropertyValue(o),l=n.tracks.filter(e=>"property"===e.type)[i];if(!l?.component||!l.channelProperties)continue;const c=oe(l.component);if(!c||!e.has(s,c))continue;const u=e.get(s,c),d=l.channelProperties[r];d&&Ds(u,d,a)&&e.set(s,c,u)}}}const Ws=new zs,Hs=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["UIRenderer",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}],["TimelinePlayer",{fields:[{field:"timeline",type:"timeline"}]}]]);function $s(e){const t=Hs.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function Os(e){return Hs.get(e)?.fields??[]}function Vs(e){return Hs.get(e)?.spine??null}function Ns(e,t){const n=Y(e.type);if(!n)return;const s=e.data;for(const o of n){const n=s[o];if("number"==typeof n&&0!==n){const i=t.get(n);void 0===i&&console.warn(`[Scene] Entity reference not found: ${e.type}.${o} references entity ${n} which does not exist`),s[o]=void 0!==i?i:0}}}function js(e){const t=e.components.some(e=>"UIRect"===e.type),n=e.components.findIndex(e=>"Sprite"===e.type),s=e.components.some(e=>"UIRenderer"===e.type);if(!t||-1===n||s)return;const o=e.components[n].data,i=o.texture;e.components.push({type:"UIRenderer",data:{visualType:i?2:1,texture:i??0,color:o.color??{r:1,g:1,b:1,a:1},uvOffset:o.uvOffset??{x:0,y:0},uvScale:o.uvScale??{x:1,y:1},sliceBorder:o.sliceBorder??{x:0,y:0,z:0,w:0},material:o.material??0,enabled:o.enabled??!0}}),e.components.splice(n,1)}function Xs(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,Ce,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;js(s);const t=n.get(s.id);for(const o of s.components)Ns(o,n),Ks(e,t,o,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),o=n.get(s.parent);void 0!==t&&void 0!==o&&e.setParent(t,o)}return n}function Ys(e,t){return Xs(e,t)}async function Gs(e,t,n){const s=n?.assetServer,o=n?.assetBaseUrl??s?.baseUrl,i=new Map;s&&await async function(e,t,n,s,o){const i=new Map;for(const e of qs.keys())i.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Hs.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&i.get(e.type)?.add(t)}}const l=new Map,c=[...qs.entries()].map(async([e,o])=>{const r=await o.load(i.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),o){for(const e of s.values())o.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&o.materialHandles.add(t);const t=i.get("font");if(t)for(const e of t)o.fontPaths.add(e);for(const e of a)o.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Hs.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const o=t.get(s);void 0!==o&&(n[e.field]=o)}}}(t,s,o,i,n?.collectAssets);const r=Xs(e,t);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}const qs=new Map([["texture",{async load(e,t,n,s){const o=new Map,i=[...e].map(async e=>{try{const i=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(i);o.set(e,r.handle),s.set(e,i),gn(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),o.set(e,0)}});return await Promise.all(i),o}}],["material",{async load(e,t,n){const s=new Map,o=[...e].map(async e=>{try{const o=await t.loadMaterial(e,n);s.set(e,o.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(o),s}}],["font",{async load(e,t,n){const s=new Map,o=[...e].map(async e=>{try{const o=await t.loadBitmapFont(e,n);s.set(e,o)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(o),s}}],["anim-clip",{async load(e,t,n,s){const o=[...e].map(async e=>{try{const o=await t.loadJson(e),i=rn(o),r=new Map,a=i.map(async e=>{try{const o=n?`${n}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),s.set(e,o)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);cn(an(e,o,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(o),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await hn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const o=[...e].map(async e=>{try{const o=An(await t.loadJson(e));if(!o)return void console.warn(`Failed to parse tilemap: ${e}`);const i=[];for(const r of o.tilesets){const o=Rn(e,r.image);let a=0;try{const e=n?`${n}/${o}`:`/${o}`,i=await t.loadTexture(e);a=i.handle,s.set(o,e),gn(i.handle,i.width,i.height)}catch(e){console.warn(`Failed to load tileset texture: ${o}`,e)}i.push({textureHandle:a,columns:r.columns})}_n(e,{tileWidth:o.tileWidth,tileHeight:o.tileHeight,layers:o.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:i})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(o),new Map}}],["timeline",{async load(e,t,n,s){const o=[...e].map(async e=>{try{const o=Zn(await t.loadJson(e));Is(e,o);const i=function(e){const t=new Set,n=new Set,s=new Set;for(const o of e.tracks)if(o.type===Wn)for(const e of o.events)t.add(e.clip);else if(o.type===zn)o.clip&&n.add(o.clip);else if(o.type===Vn)for(const e of o.frames)e.texture&&s.add(e.texture);return{audio:Array.from(t),animClips:Array.from(n),textures:Array.from(s)}}(o);if(i.textures.length>0){const o=new Map,r=i.textures.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(i);o.set(e,r.handle),s.set(e,i)}catch(t){console.warn(`Failed to load animFrames texture: ${e}`,t),o.set(e,0)}});await Promise.all(r),function(e,t){Fs.set(e,t)}(e,o)}}catch(t){console.warn(`Failed to load timeline: ${e}`,t)}});return await Promise.all(o),new Map}}]]);function Ks(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const o=oe(n.type);if(o)e.insert(t,o,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Js(e,t){const n=e.getEntitiesWithComponents([me]);for(const s of n){const n=e.get(s,me);n&&(n.aspectRatio=t,e.insert(s,me,n))}}class Qs{constructor(e){this.textureCache_=new sn,this.shaderCache_=new sn,this.jsonCache_=new sn,this.textCache_=new sn,this.binaryCache_=new sn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new sn,this.prefabCache_=new sn,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=l(H.textCanvasSize,H.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new on(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),o=this.textureRefCounts_.get(s);if(void 0===o)continue;const i=this.textureCache_.get(s);if(!i)continue;const r=o-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),Gt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const o=this.resolveUrl(t,n),i=await this.fetchText(o);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===b(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,i,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),o=l.find(e=>e.name===n);if(o){const n=t.getTextureGLId(o.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,o.info.width,o.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=b(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 o=n?`${n}/${s}`:s;return this.loadFntFile(o)}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],o=e.substring(0,e.lastIndexOf("/")),i=o?`${o}/${s}`:s,r=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of $s(e.type)){const s=e.data[n];if("string"==typeof s&&s){const o=t(s);o&&(e.data[n]=o)}}const n=Vs(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const o=t(n);o&&(e.data[s]=o)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 Gs(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const o=s.metadata?.atlas;o&&n.push(this.loadSpine(s.path,o).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,o=this.getWebGL2Context();return o?this.createTextureWebGL2(o,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,o){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o?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 r=this.module_.GL,a=r.getNewId(r.textures);r.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 o=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(o.data.buffer);this.unpremultiplyAlpha(i);const r=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const l=r.createTexture(t,n,a,i.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:o}=this.parseEsShader(t);if(!s||!o)throw new Error(`Invalid shader format: ${e}`);return Gt.createShader(s,o)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(t))throw new Error(`Shader file not found: ${e}`);const s=await i(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:o,fragment:a}=this.parseEsShader(s);if(!o||!a)throw new Error(`Invalid shader format: ${e}`);return Gt.createShader(o,a)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(M(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await i(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(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 n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return i(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(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 n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 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 o="";for(const e of s){o=o?`${o}/${e}`:e;try{t.analyzePath(o).exists||t.mkdir(o)}catch{try{t.mkdir(o)}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 Zs=Ne(null,"Assets");class eo{build(e){const t=e.wasmModule;t?e.insertResource(Zs,new Qs(t)):console.warn("AssetPlugin: No WASM module available")}}const to=new eo;function no(e){return e.map(e=>({type:e.type,data:JSON.parse(JSON.stringify(e.data))}))}function so(e){return JSON.parse(JSON.stringify(e))}function oo(e,t){for(const n of e){const e=Y(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const o=t.get(e);void 0!==o&&(n.data[s]=o)}}}}function io(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:so(n.componentData.data)})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}function ro(e,t,n){const s=n.depth??0;if(s>10)throw new Error(`Prefab nesting depth exceeded 10. Check for deep or circular nesting in: ${e.name}`);if(e.basePrefab)return function(e,t,n,s){const o=e.basePrefab,i=n.visited??new Set;if(i.has(o))throw new Error(`[Prefab] Circular variant reference detected: "${o}" is already being instantiated in the current prefab chain`);const r=n.loadPrefab(o);if(!r)throw new Error(`Failed to load base prefab for variant: ${o}`);i.add(o);const a=[...e.overrides??[],...t];return ro(r,a,{...n,visited:i,depth:s+1})}(e,t,n,s);const o=n.visited??new Set,i=new Map;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,n.allocateId());const r=[];for(const a of e.entities){if(a.nestedPrefab){const e=a.nestedPrefab.prefabPath;if(o.has(e))throw new Error(`[Prefab] Circular reference detected: "${e}" is already being instantiated in the current prefab chain`);const t=n.loadPrefab(e);if(!t)throw new Error(`Failed to load nested prefab: ${e}`);o.add(e);const l=ro(t,a.nestedPrefab.overrides,{...n,visited:o,depth:s+1});i.set(a.prefabEntityId,l.rootId);const c=l.entities.find(e=>e.id===l.rootId);c&&(c.parent=null!==a.parent?i.get(a.parent)??null:null),r.push(...l.entities);continue}const l=i.get(a.prefabEntityId),c=a.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:a.prefabEntityId,name:a.name,parent:c?null:null!==a.parent?i.get(a.parent)??null:null,children:a.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:no(a.components),visible:a.visible};oo(u.components,i),io(u,t),r.push(u)}const a=i.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:r,rootId:a}}async function ao(e,t,n,s,o=0){if(o>10)return;const i=s??new Set;if(e.basePrefab&&!i.has(e.basePrefab)&&!n.has(e.basePrefab)){i.add(e.basePrefab);const s=await t(e.basePrefab);n.set(e.basePrefab,s),await ao(s,t,n,i,o+1)}for(const s of e.entities){if(!s.nestedPrefab)continue;const e=s.nestedPrefab.prefabPath;if(i.has(e)||n.has(e))continue;i.add(e);const r=await t(e);n.set(e,r),await ao(r,t,n,i,o+1)}}async function lo(e,t,n){const s=new Map;n?.assetServer&&await ao(t,e=>n.assetServer.loadPrefab(e,n.assetBaseUrl),s);let o=0;const i={allocateId:()=>o++,loadPrefab:e=>s.get(e)??null,visited:new Set},{entities:r,rootId:a}=ro(t,n?.overrides??[],i),l={version:t.version,name:t.name,entities:r.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},c=await Gs(e,l,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),u=c.get(a);return void 0!==n?.parent&&e.setParent(u,n.parent),{root:u,entities:c}}class co{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,o=await this.assetServer_.loadPrefab(s,t?.baseUrl);return lo(this.world_,o,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const uo=Ne(null,"Prefabs");class ho{constructor(){this.name="PrefabsPlugin",this.dependencies=[Zs]}build(e){const t=e.getResource(Zs);e.insertResource(uo,new co(e.world,t))}}const po=new ho;let fo=null,go=0,mo=0,yo=0;const _o=new Float32Array(256);function xo(e){fo=e,go=fo._malloc(64),mo=fo._malloc(64),yo=fo._malloc(1024)}function wo(){fo&&(go&&(fo._free(go),go=0),mo&&(fo._free(mo),mo=0),yo&&(fo._free(yo),yo=0)),fo=null}function bo(){if(!fo)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return fo}const vo={r:1,g:1,b:1,a:1},So={begin(e){const t=bo();try{t.HEAPF32.set(e,go/4),t.draw_begin(go)}catch(e){st(e,"Draw.begin")}},end(){try{bo().draw_end()}catch(e){st(e,"Draw.end")}},line(e,t,n,s=1){try{bo().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){st(e,"Draw.line")}},rect(e,t,n,s=!0){try{bo().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){st(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{bo().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){st(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,o=32){try{bo().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,o)}catch(e){st(e,"Draw.circle")}},circleOutline(e,t,n,s=1,o=32){try{bo().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,o)}catch(e){st(e,"Draw.circleOutline")}},texture(e,t,n,s=vo){try{bo().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){st(e,"Draw.texture")}},textureRotated(e,t,n,s,o=vo){try{bo().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,o.r,o.g,o.b,o.a)}catch(e){st(e,"Draw.textureRotated")}},setLayer(e){bo().draw_setLayer(e)},setDepth(e){bo().draw_setDepth(e)},getDrawCallCount:()=>fo?fo.draw_getDrawCallCount():0,getPrimitiveCount:()=>fo?fo.draw_getPrimitiveCount():0,setBlendMode(e){bo().draw_setBlendMode(e)},setDepthTest(e){bo().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=bo();s.HEAPF32.set(n,mo/4),s.draw_mesh(e,t,mo)}catch(n){st(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=bo(),o=Gt.get(t);if(!o)return;if(So.setBlendMode(o.blendMode),So.setDepthTest(o.depthTest),0===o.uniforms.size)return void So.drawMesh(e,o.shader,n);let i;if(s.HEAPF32.set(n,mo/4),!o.dirty_&&o.cachedBuffer_)i=o.cachedIdx_;else{i=0;let e=0;for(const[t,n]of o.uniforms){const s=To(t);if(!(s<0)){if(Ht(n))_o[i++]=10,_o[i++]=s,_o[i++]=n.slot??e++,_o[i++]=n.textureId;else if("number"==typeof n)_o[i++]=1,_o[i++]=s,_o[i++]=n;else if(Array.isArray(n)){_o[i++]=n.length,_o[i++]=s;for(let e=0;e<n.length;e++)_o[i++]=n[e]}else"w"in n?(_o[i++]=4,_o[i++]=s,_o[i++]=n.x,_o[i++]=n.y,_o[i++]=n.z,_o[i++]=n.w):"z"in n?(_o[i++]=3,_o[i++]=s,_o[i++]=n.x,_o[i++]=n.y,_o[i++]=n.z):(_o[i++]=2,_o[i++]=s,_o[i++]=n.x,_o[i++]=n.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!o.cachedBuffer_||o.cachedBuffer_.length<i)&&(o.cachedBuffer_=new Float32Array(i)),o.cachedBuffer_.set(_o.subarray(0,i)),o.cachedIdx_=i,o.dirty_=!1}if(0===i)return void s.draw_mesh(e,o.shader,mo);s.HEAPF32.set(o.cachedBuffer_.subarray(0,i),yo/4),s.draw_meshWithUniforms(e,o.shader,mo,yo,i)}catch(n){st(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Po={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},Mo=new Set;function To(e){const t=Po[e];return void 0!==t?t:(Mo.has(e)||(Mo.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Po).join(", ")}`)),-1)}const Co=new Map;function Eo(e,t,n){Co.set(e,{fn:t,scene:n??""})}function Ao(e){Co.delete(e)}function Ro(){Co.clear()}var ko;exports.DataType=void 0,(ko=exports.DataType||(exports.DataType={}))[ko.Float=1]="Float",ko[ko.Float2=2]="Float2",ko[ko.Float3=3]="Float3",ko[ko.Float4=4]="Float4",ko[ko.Int=5]="Int",ko[ko.Int2=6]="Int2",ko[ko.Int3=7]="Int3",ko[ko.Int4=8]="Int4";let Io=null,Fo=0,Bo=0,Uo=0;function Do(e){Io=e,Fo=Io._malloc(262144),Bo=Io._malloc(65536),Uo=Io._malloc(256)}function Lo(){Io&&(Fo&&Io._free(Fo),Bo&&Io._free(Bo),Uo&&Io._free(Uo),Fo=0,Bo=0,Uo=0),Io=null}function zo(){if(!Io)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Io}const Wo={create(e){const t=zo(),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,Fo/4);const o=e.layout.length,i=new Int32Array(o);for(let t=0;t<o;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Uo,o).set(i),t.geometry_init(n,Fo,s,Uo,o,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,Bo,s).set(e.indices),t.geometry_setIndices16(n,Bo,s)}else{new Uint32Array(t.HEAPU8.buffer,Bo,s).set(e.indices),t.geometry_setIndices32(n,Bo,s)}}return n},updateVertices(e,t,n=0){const s=zo(),o=t.length;if(4*o>262144)throw new Error(`Vertex data too large: ${o} floats (max 65536)`);s.HEAPF32.set(t,Fo/4),s.geometry_updateVertices(e,Fo,o,n)},release(e){e>0&&zo().geometry_release(e)},isValid:e=>!(!Io||e<=0)&&Io.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Wo.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const o=s/t*Math.PI*2,i=Math.cos(o)*e,r=Math.sin(o)*e,a=(Math.cos(o)+1)/2,l=(Math.sin(o)+1)/2;n.push(i,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Wo.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,o=-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),o=Math.max(o,i.y);const i=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(o-n);i.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return Wo.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};let Ho=1;const $o=new Map,Oo=new Map;function Vo(){return $o}function No(){return Oo}class jo{constructor(){this.passes_=[],this.destroyed_=!1,this.id=Ho++,$o.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}clearPasses(){return this.passes_.length=0,this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of Oo)t===this&&Oo.delete(e);$o.delete(this.id)}}}const Xo="#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";let Yo=null;function Go(e){Yo=e}function qo(){for(const e of Vo().values())e.destroy();Vo().clear(),No().clear(),Yo&&Jo.isInitialized()&&Jo.shutdown(),Yo=null}function Ko(){if(!Yo)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Yo}const Jo={createStack:()=>new jo,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");No().set(e,t)},unbind(e){No().delete(e)},getStack:e=>No().get(e)??null,init(e,t){try{return Ko().postprocess_init(e,t)}catch(n){return st(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ko().postprocess_shutdown()}catch(e){st(e,"PostProcess.shutdown")}},resize(e,t){try{Ko().postprocess_resize(e,t)}catch(n){st(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!Yo)return!1;try{return Yo.postprocess_isInitialized()}catch(e){return st(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ko().postprocess_setBypass(e)}catch(e){st(e,"PostProcess.setBypass")}},begin(){try{Ko().postprocess_begin()}catch(e){st(e,"PostProcess.begin")}},end(){try{Ko().postprocess_end()}catch(e){st(e,"PostProcess.end")}},setOutputViewport(e,t,n,s){try{Ko().postprocess_setOutputViewport(e,t,n,s)}catch(e){st(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=No().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Jo.isInitialized()||Jo.init(1,1),Jo.setBypass(!1),function(e){const t=Ko();try{t.postprocess_clearPasses()}catch(e){return void st(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){st(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){st(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){st(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):Jo.setBypass(!0)},_resetAfterCamera(){try{Ko().postprocess_clearPasses(),Ko().postprocess_setBypass(!0)}catch(e){st(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of No().keys())e(t)||No().delete(t)},screenStack:null,setScreenStack(e){Jo.screenStack=e},_beginScreenCapture(){try{Ko().postprocess_beginScreenCapture()}catch(e){st(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Ko().postprocess_endScreenCapture()}catch(e){st(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Jo.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Ko();try{t.postprocess_clearScreenPasses()}catch(e){return void st(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){st(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){st(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){st(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{Ko().postprocess_executeScreenPasses()}catch(e){st(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Gt.createShader(Xo,"#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:()=>Gt.createShader(Xo,"#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 vig = 1.0 - smoothstep(1.0 - u_softness, 1.0, dist);\n fragColor = vec4(color.rgb * mix(1.0, vig, u_intensity), color.a);\n}\n"),createGrayscale:()=>Gt.createShader(Xo,"#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"),createBloomExtract:()=>Gt.createShader(Xo,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_threshold;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float brightness = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float knee = u_threshold * 0.5;\n float soft = brightness - u_threshold + knee;\n soft = clamp(soft, 0.0, 2.0 * knee);\n soft = soft * soft / (4.0 * knee + 0.00001);\n float contrib = max(soft, brightness - u_threshold);\n contrib /= max(brightness, 0.00001);\n fragColor = vec4(color.rgb * contrib, 1.0);\n}\n"),createBloomKawase(e){const t=`#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n float d = (${e.toFixed(1)} + 0.5) * max(u_radius, 0.5);\n vec2 ts = 1.0 / u_resolution;\n fragColor = (\n texture(u_texture, v_texCoord + vec2(-d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2(-d, d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, d) * ts)\n ) * 0.25;\n}\n`;return Gt.createShader(Xo,t)},createBloomComposite:()=>Gt.createShader(Xo,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform sampler2D u_sceneTexture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 blur = texture(u_texture, v_texCoord);\n vec4 scene = texture(u_sceneTexture, v_texCoord);\n fragColor = vec4(scene.rgb + blur.rgb * u_intensity, scene.a);\n}\n"),createChromaticAberration:()=>Gt.createShader(Xo,"#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")},Qo=new Map;function Zo(e){Qo.set(e.type,e)}function ei(e){return Qo.get(e)}Zo({type:"blur",label:"Blur",factory:()=>Jo.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Zo({type:"bloom",label:"Bloom",factory:()=>Jo.createBloomExtract(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:1,step:.01,defaultValue:.4},{name:"u_intensity",label:"Intensity",min:0,max:5,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:.5,max:5,step:.1,defaultValue:1}],multiPass:[{name:"bloom_extract",factory:()=>Jo.createBloomExtract()},{name:"bloom_kawase_0",factory:()=>Jo.createBloomKawase(0)},{name:"bloom_kawase_1",factory:()=>Jo.createBloomKawase(1)},{name:"bloom_kawase_2",factory:()=>Jo.createBloomKawase(2)},{name:"bloom_kawase_3",factory:()=>Jo.createBloomKawase(3)},{name:"bloom_kawase_4",factory:()=>Jo.createBloomKawase(4)},{name:"bloom_composite",factory:()=>Jo.createBloomComposite()}]}),Zo({type:"vignette",label:"Vignette",factory:()=>Jo.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:.6},{name:"u_softness",label:"Softness",min:0,max:1,step:.01,defaultValue:.5}]}),Zo({type:"grayscale",label:"Grayscale",factory:()=>Jo.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Zo({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Jo.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const ti=new Map,ni=new Map;function si(e){const t=ti.get(e);t&&(Jo.unbind(e),t.destroy(),ti.delete(e));const n=ni.get(e);if(n){for(const e of n.values())Gt.releaseShader(e);ni.delete(e)}}function oi(){for(const e of ti.keys())si(e)}const ii=Ne({enabled:!0},"PostProcessVolumeConfig"),ri=new Map,ai=new Map;function li(e,t){const n=ai.get(e);if(void 0!==n)return n;const s=t();return ai.set(e,s),s}function ci(e,t){if(0===t.size){const t=ri.get(e);return void(t&&(Jo.unbind(e),t.destroy(),ri.delete(e)))}let n=ri.get(e);n||(n=Jo.createStack(),ri.set(e,n)),n.clearPasses();for(const[e,s]of t){if(!s.enabled)continue;const t=ei(e);if(t)if(t.multiPass)for(const e of t.multiPass){const t=li(e.name,e.factory);n.addPass(e.name,t);for(const[t,o]of s.uniforms)n.setUniform(e.name,t,o)}else{const o=li(e,t.factory);n.addPass(e,o);for(const[t,o]of s.uniforms)n.setUniform(e,t,o)}}n.enabledPassCount>0?Jo.bind(e,n):Jo.unbind(e)}const ui=kt([xt(Ae,de),xt(me)],(e,t)=>{const n=[];for(const[t,s,o]of e)n.push({data:s,tx:{x:o.position.x,y:o.position.y}});const s=[];for(const{data:e}of n)e.isGlobal&&s.push({data:e,factor:1});const o=s.length>0?function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,o]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(o-n)*s)}else{const e=new Map;for(const[t,o]of Object.entries(n.uniforms))e.set(t,o*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(s):new Map;for(const[e,n]of t)n.isActive&&ci(e,o)},{name:"PostProcessVolumeSystem"});class di{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(ii,{enabled:!0}),e.addSystemToSchedule(exports.Schedule.PostUpdate,ui)}cleanup(){oi(),function(){for(const[e,t]of ri)Jo.unbind(e),t.destroy();ri.clear();for(const e of ai.values())Gt.releaseShader(e);ai.clear()}(),Jo.setScreenStack(null)}}const hi=new di;var pi,fi;exports.FlushReason=void 0,(pi=exports.FlushReason||(exports.FlushReason={}))[pi.BatchFull=0]="BatchFull",pi[pi.TextureSlotsFull=1]="TextureSlotsFull",pi[pi.ScissorChange=2]="ScissorChange",pi[pi.StencilChange=3]="StencilChange",pi[pi.MaterialChange=4]="MaterialChange",pi[pi.BlendModeChange=5]="BlendModeChange",pi[pi.StageEnd=6]="StageEnd",pi[pi.TypeChange=7]="TypeChange",pi[pi.FrameEnd=8]="FrameEnd",exports.RenderType=void 0,(fi=exports.RenderType||(exports.RenderType={}))[fi.Sprite=0]="Sprite",fi[fi.Spine=1]="Spine",fi[fi.Mesh=2]="Mesh",fi[fi.ExternalMesh=3]="ExternalMesh",fi[fi.Text=4]="Text",fi[fi.Particle=5]="Particle",fi[fi.Shape=6]="Shape",fi[fi.UIElement=7]="UIElement";var gi;exports.RenderStage=void 0,(gi=exports.RenderStage||(exports.RenderStage={}))[gi.Background=0]="Background",gi[gi.Opaque=1]="Opaque",gi[gi.Transparent=2]="Transparent",gi[gi.Overlay=3]="Overlay";let mi=null,yi=0;function _i(e){mi=e,yi=mi._malloc(64)}function xi(){mi&&yi&&(mi._free(yi),yi=0),mi=null}const wi={init(e,t){mi?.renderer_init(e,t)},resize(e,t){mi?.renderer_resize(e,t)},beginFrame(){mi?.renderer_beginFrame()},updateTransforms(e){if(mi)try{mi.renderer_updateTransforms(e._cpp)}catch(e){st(e,"Renderer.updateTransforms")}},begin(e,t){if(mi&&yi)try{mi.HEAPF32.set(e,yi/4),mi.renderer_begin(yi,t??0)}catch(e){st(e,"Renderer.begin")}},flush(){try{mi?.renderer_flush()}catch(e){st(e,"Renderer.flush")}},end(){try{mi?.renderer_end()}catch(e){st(e,"Renderer.end")}},submitAll(e,t,n,s,o,i){if(mi)try{mi.renderer_submitAll(e._cpp,t,n,s,o,i)}catch(e){st(e,"Renderer.submitAll")}},setStage(e){mi?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>mi?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){mi?.renderer_releaseTarget(e)},getTargetTexture:e=>mi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>mi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){mi?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){mi?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,o){mi?.renderer_setScissor(e,t,n,s,o)},clearBuffers(e){mi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>mi?mi.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>mi?{drawCalls:mi.renderer_getDrawCalls(),triangles:mi.renderer_getTriangles(),sprites:mi.renderer_getSprites(),text:mi.renderer_getText(),spine:mi.renderer_getSpine?.()??0,meshes:mi.renderer_getMeshes(),culled:mi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0},captureNextFrame(){mi?.renderer_captureNextFrame()},getCapturedData:()=>mi?function(e){if(!e.renderer_hasCapturedData())return null;const t=e.renderer_getCapturedFrameSize();if(0===t)return null;const n=e.renderer_getCapturedFrameData(),s=e.renderer_getCapturedEntities(),o=e.renderer_getCapturedEntityCount(),i=e.renderer_getCapturedCameraCount(),r=e.HEAPU8,a=new DataView(r.buffer,n,76*t),l=new Uint32Array(r.buffer,s,o),c=[];for(let e=0;e<t;e++){const t=76*e,n=a.getUint32(t,!0),s=a.getUint32(t+4,!0),i=a.getUint8(t+8),r=a.getUint8(t+9),u=a.getUint8(t+10),d=a.getUint32(t+12,!0),h=a.getUint32(t+16,!0),p=a.getUint32(t+20,!0),f=a.getUint32(t+24,!0),g=a.getUint32(t+28,!0),m=a.getUint32(t+32,!0),y=a.getUint32(t+36,!0),_=a.getInt32(t+40,!0),x=a.getUint8(t+44),w=a.getInt32(t+48,!0),b=a.getInt32(t+52,!0),v=a.getInt32(t+56,!0),S=a.getInt32(t+60,!0),P=0!==a.getUint8(t+64),M=0!==a.getUint8(t+65),T=0!==a.getUint8(t+66),C=a.getInt32(t+68,!0),E=a.getUint8(t+72),A=[];for(let e=0;e<m&&y+e<o;e++)A.push(l[y+e]);c.push({index:n,cameraIndex:s,stage:i,type:r,blendMode:u,textureId:d,materialId:h,shaderId:p,vertexCount:f,triangleCount:g,entityCount:m,entityOffset:y,layer:_,flushReason:x,scissorX:w,scissorY:b,scissorW:v,scissorH:S,scissorEnabled:P,stencilWrite:M,stencilTest:T,stencilRef:C,textureSlotUsage:E,entities:A})}return{drawCalls:c,cameraCount:i}}(mi):null,hasCapturedData:()=>mi?.renderer_hasCapturedData()??!1,replayToDrawCall(e){mi&&function(e,t){e.renderer_replayToDrawCall(t)}(mi,e)},getSnapshotImageData:()=>mi?function(e){const t=e.renderer_getSnapshotSize();if(0===t)return null;const n=e.renderer_getSnapshotWidth(),s=e.renderer_getSnapshotHeight();if(0===n||0===s)return null;const o=e.renderer_getSnapshotPtr(),i=e.HEAPU8,r=new Uint8ClampedArray(i.buffer,o,t),a=new Uint8ClampedArray(t),l=4*n;for(let e=0;e<s;e++){const t=e*l,n=(s-1-e)*l;a.set(r.subarray(t,t+l),n)}return new ImageData(a,n,s)}(mi):null};let bi=null;function vi(e){bi=e}function Si(){bi=null}const Pi={enable(){bi?.gl_enableErrorCheck(!0)},disable(){bi?.gl_enableErrorCheck(!1)},check:e=>bi?.gl_checkErrors(e)??0,diagnose(){bi?.renderer_diagnose()}};class Mi{constructor(){this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null,this.preFlushCallbacks_=[]}setActiveScenes(e){this.activeScenes_=e}addPreFlushCallback(e){this.preFlushCallbacks_.push(e)}beginFrame(){wi.beginFrame()}beginScreenCapture(){Jo.screenStack&&Jo.screenStack.enabledPassCount>0&&(Jo.isInitialized()||Jo.init(1,1),Jo._applyScreenStack(),Jo._beginScreenCapture())}endScreenCapture(){Jo.screenStack&&Jo.screenStack.enabledPassCount>0&&(Jo._endScreenCapture(),Jo._executeScreenPasses())}submitScene(e,t,n,s){wi.updateTransforms(e),wi.submitAll(e,0,n.x,n.y,n.w,n.h);for(const t of this.preFlushCallbacks_)t(e);wi.flush(),this.executeDrawCallbacks(t,s)}render(e){const{registry:t,viewProjection:n,width:s,height:o,elapsed:i}=e;s===this.lastWidth_&&o===this.lastHeight_||(wi.resize(s,o),this.lastWidth_=s,this.lastHeight_=o),wi.beginFrame(),wi.setViewport(0,0,s,o),wi.clearBuffers(3),wi.begin(n),this.submitScene(t,n,{x:0,y:0,w:s,h:o},i),wi.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:o,elapsed:i,cameraEntity:r}=e,a=void 0!==r&&null!==Jo.getStack(r);a&&(Jo._applyForCamera(r),Jo.resize(s.w,s.h),Jo.setOutputViewport(s.x,s.y,s.w,s.h),Jo.begin()),wi.setViewport(s.x,s.y,s.w,s.h),wi.setScissor(s.x,s.y,s.w,s.h,!0),wi.clearBuffers(o),wi.setScissor(0,0,0,0,!1),wi.begin(n),this.submitScene(t,n,s,i),wi.end(),a&&(Jo.end(),Jo._resetAfterCamera())}executeDrawCallbacks(e,t){const n=Co;if(n.size>0){So.begin(e);const s=[];for(const[e,o]of n.entries())if(!o.scene||!this.activeScenes_||this.activeScenes_.has(o.scene))try{o.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}So.end();for(const e of s)Ao(e)}}}const Ti={None:0,SolidColor:1,Image:2,NineSlice:3},Ci=re("UIRenderer",{visualType:Ti.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),Ei="__scene_transition_overlay__";class Ai{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Ri{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Ee,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Eo(e,t,this.instance_.config.name)}bindPostProcess(e,t){Jo.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Jo.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Ee)){const n=this.app_.world.get(e,Ee);n.persistent=t,this.app_.world.insert(e,Ee,n)}}}class ki{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())Ao(t);for(const t of e.postProcessBindings.keys())Jo.unbind(t)}this.transition_&&(Ao(Ei),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise((n,s)=>{const o=t.duration??H.sceneTransitionDuration,i=t.color??{...H.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:o,color:i,targetScene:e,options:t,resolve:n,reject:s},Eo(Ei,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;So.setLayer(9999),So.setDepth(9999),So.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{reject:t}=this.transition_;this.transition_=null,Ao(Ei),t(e)}})().catch(()=>{})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ao(Ei),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Ai(t);this.scenes_.set(e,n);const s=new Ri(n,this.app_);this.contexts_.set(e,s);const o=(async()=>{let o=t.data;if(!o&&t.path){const e=this.app_.hasResource(Zs)?this.app_.getResource(Zs):null;if(e)o=await e.loadJson(t.path);else{const e=await fetch(t.path);o=await e.json()}}return await this.loadSceneData_(n,e,t,o),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,o);try{return await o}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Ai(t);this.scenes_.set(e,n);const s=new Ri(n,this.app_);this.contexts_.set(e,s);const o=(async()=>{let o=t.data;if(!o&&t.path){const e=this.app_.hasResource(Zs)?this.app_.getResource(Zs):null;if(e)o=await e.loadJson(t.path);else{const e=await fetch(t.path);o=await e.json()}}return await this.loadSceneData_(n,e,t,o),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,o);try{return await o}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const o=t?.keepPersistent??!0;for(const e of n.entities){if(o&&this.app_.world.valid(e)&&this.app_.world.has(e,Ee)){if(this.app_.world.get(e,Ee).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Ao(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())Jo.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},o={collectAssets:n};this.app_.hasResource(Zs)&&(o.assetServer=this.app_.getResource(Zs));const i=await Gs(this.app_.world,s,o);e.loadedAssets=n;for(const n of i.values())e.entities.add(n),this.app_.world.insert(n,Ee,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Fi(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const o=this.contexts_.get(t);n.setup&&await n.setup(o)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(Zs)?this.app_.getResource(Zs):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)Gt.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let o=!1;if(n.has(e,fe)){const t=n.get(e,fe);s.sprite=t.color.a,t.color.a=0,n.insert(e,fe,t),o=!0}if(n.has(e,ve)){const t=n.get(e,ve);s.spine=t.color.a,t.color.a=0,n.insert(e,ve,t),o=!0}if(n.has(e,be)){const t=n.get(e,be);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,be,t),o=!0}if(n.has(e,Ci)){const t=n.get(e,Ci);s.uiRenderer=t.color.a,t.color.a=0,n.insert(e,Ci,t),o=!0}o&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,fe)){const t=n.get(e,fe);t.color.a=s.sprite,n.insert(e,fe,t)}if(void 0!==s.spine&&n.has(e,ve)){const t=n.get(e,ve);t.color.a=s.spine,n.insert(e,ve,t)}if(void 0!==s.bitmapText&&n.has(e,be)){const t=n.get(e,be);t.color.a=s.bitmapText,n.insert(e,be,t)}if(void 0!==s.uiRenderer&&n.has(e,Ci)){const t=n.get(e,Ci);t.color.a=s.uiRenderer,n.insert(e,Ci,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Ii=Ne(null,"SceneManager");function Fi(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Ii).getSceneStatus(t)&&n._fn(...s)}}}const Bi=kt([Xe(Ii),je(qe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ui={name:"SceneManager",build(e){const t=new ki(e);e.insertResource(Ii,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ii),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,n),e.addSystemToSchedule(exports.Schedule.Last,Bi)}};class Di{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new Mt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=async()=>{if(!this.running_)return;const e=c(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(exports.Schedule.Last);else{await this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(exports.Schedule.FixedPreUpdate),await this.runSchedule(exports.Schedule.FixedUpdate),await this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(exports.Schedule.PreUpdate),await this.runSchedule(exports.Schedule.Update),await this.runSchedule(exports.Schedule.PostUpdate),await this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new pt,this.resources_=new Ge;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Di}getPlugin(e){return this.installed_plugins_.find(t=>t instanceof e)}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const o=s.filter(t=>t.system._id!==e);o.length!==s.length&&(this.systems_.set(n,o),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}async waitForPhysics(){this.physicsInitPromise_?await this.physicsInitPromise_:console.warn("[ESEngine] No PhysicsPlugin installed, waitForPhysics() is a no-op")}get isPhysicsReady(){return null!=this.physicsModule_}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return nt(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Ii).register(e),this}setInitialScene(e){return this.getResource(Ii).setInitial(e),this}async tick(e){if(this.runner_||(this.runner_=new Ft(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(qe)||this.resources_.insert(qe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_()),await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(exports.Schedule.Last);else{await this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(exports.Schedule.FixedPreUpdate),await this.runSchedule(exports.Schedule.FixedUpdate),await this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(exports.Schedule.PreUpdate),await this.runSchedule(exports.Schedule.Update),await this.runSchedule(exports.Schedule.PostUpdate),await this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}async run(){this.running_||(this.running_=!0,this.runner_=new Ft(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(qe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),await this.flushStartupSystems_(),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,Ro();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Si,xi,qo,Lo,Xt,wo];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){console.warn("[App] Shutdown despawn error:",e)}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const o=t.get(s);if(void 0!==o){const t=e[o];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,o=new Set,i=r=>{if(s.has(r))return;if(o.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}o.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&i(n)}o.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)i(t);return n}async flushStartupSystems_(){const e=this.systems_.get(exports.Schedule.Startup);0!==e.length&&(this.sortedSystemsCache_.delete(exports.Schedule.Startup),await this.runSchedule(exports.Schedule.Startup),e.length=0,this.sortedSystemsCache_.delete(exports.Schedule.Startup))}async runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{const t=this.runner_.run(e.system);t instanceof Promise&&await t}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(exports.Schedule[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(qe);t.delta=e,t.elapsed+=e,t.frameCount++}}function Li(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const zi=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Wi(e,t,n,s,o){const i=e*t/n,r=e;switch(s){case ce.FixedWidth:return i;case ce.FixedHeight:return r;case ce.Expand:return Math.max(i,r);case ce.Shrink:return Math.min(i,r);case ce.Match:{const e=o;return Math.pow(i,1-e)*Math.pow(r,e)}default:return r}}const Hi=[];function $i(e){if(e<Hi.length)return Hi[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return Hi.push(t),t}function Oi(e,t,n,s,o,i){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=i&&o?r.filter(e=>{const t=o.tryGet(e,Ee);return!t||""===t.scene||i.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const o=t.getCamera(e),i=t.getTransform(e),r=o.viewportW*n/(o.viewportH*s);let a,u=0,d=0;if(o.projectionType===ae.Orthographic){if(d=o.orthoSize,l){d=Wi(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=Ni(-u,u,-d,d,-o.farPlane,o.farPlane)}else a=Xi(o.fov*Math.PI/180,r,o.nearPlane,o.farPlane);const h=Gi(i.position.x,i.position.y,i.position.z),p=$i(c.length);p.entity=e,p.viewProjection.set(Ki(a,h)),p.viewportRect.x=o.viewportX,p.viewportRect.y=o.viewportY,p.viewportRect.w=o.viewportW,p.viewportRect.h=o.viewportH,p.clearFlags=o.clearFlags,p.priority=o.priority,p.halfW=u,p.halfH=d,p.cameraX=i.position.x,p.cameraY=i.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const Vi=new Float32Array(16);function Ni(e,t,n,s,o,i){const r=Vi;r.fill(0);const a=t-e,l=s-n,c=i-o;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(i+o)/c,r[15]=1,r}const ji=new Float32Array(16);function Xi(e,t,n,s){const o=ji;o.fill(0);const i=1/Math.tan(e/2),r=n-s;return o[0]=i/t,o[5]=i,o[10]=(s+n)/r,o[11]=-1,o[14]=2*s*n/r,o}const Yi=new Float32Array(16);function Gi(e,t,n){const s=Yi;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}const qi=new Float32Array(16);function Ki(e,t){const n=qi;for(let s=0;s<4;s++)for(let o=0;o<4;o++)n[4*o+s]=e[0+s]*t[4*o+0]+e[4+s]*t[4*o+1]+e[8+s]*t[4*o+2]+e[12+s]*t[4*o+3];return n}const Ji={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},Qi={Simple:0,Sliced:1,Tiled:2,Filled:3},Zi={Horizontal:0,Vertical:1},er={Left:0,Right:1,Bottom:2,Top:3},tr=Q("Image",{texture:V,color:{r:1,g:1,b:1,a:1},imageType:Qi.Simple,fillMethod:Zi.Horizontal,fillOrigin:er.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),nr=re("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}}),sr=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0});let or=null,ir=null;function rr(e,t){switch(e){case Ji.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ji.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ji.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function ar(e,t,n,s){if(!e.has(t,nr))return;const o=e.get(t,nr),i=rr(n,s);o.anchorMin=i.anchorMin,o.anchorMax=i.anchorMax,i.anchorMin.x===i.anchorMax.x&&(o.size={...o.size,x:0}),i.anchorMin.y===i.anchorMax.y&&(o.size={...o.size,y:0}),e.insert(t,nr,o)}function lr(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}const cr=1.15,ur=.75;function dr(e,t,n,s){return t?n?{r:e.r*ur,g:e.g*ur,b:e.b*ur,a:e.a}:s?{r:Math.min(1,e.r*cr),g:Math.min(1,e.g*cr),b:Math.min(1,e.b*cr),a:e.a}:{...e}:{r:.5*e.r,g:.5*e.g,b:.5*e.b,a:.6*e.a}}function hr(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function pr(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),o=[];for(const t of s){if(!t){o.push("");continue}let s="";for(let i=0;i<t.length;i++){const r=t[i],a=s+r;if(e.measureText(a).width>n&&s){if(hr(r.charCodeAt(0))&&s.length>0&&hr(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!hr(s.charCodeAt(t))){e=t;break}e>=0?(o.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(o.push(s),s=r)}else o.push(s),s=r}else s=a}s&&o.push(s)}return o.length>0?o:[""]}function fr(e){let t=1;for(;t<e;)t*=2;return t}function gr(e,t){let n=0,s=t;for(;e.has(s,xe);){const t=e.get(s,xe).entity;if(!e.valid(t))break;n++,s=t}return n}function mr(e,t){if(or&&ir){const e=or.getUIRectComputedWidth(ir,t);if(e>0)return e}return e.size.x}function yr(e,t){if(or&&ir){const e=or.getUIRectComputedHeight(ir,t);if(e>0)return e}return e.size.y}function _r(e,t,n){or&&ir&&or.setUIRectSize(ir,e,t,n)}function xr(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function wr(e,t,n){0!==t&&e.valid(t)&&n(t)}function br(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a}function vr(e,t,n){if(e.has(t,tr)){const s=e.get(t,tr);br(s.color,n)||(s.color=n,e.insert(t,tr,s))}else if(e.has(t,fe)){const s=e.get(t,fe);br(s.color,n)||(s.color=n,e.insert(t,fe,s))}else if(e.has(t,Ci)){const s=e.get(t,Ci);br(s.color,n)||(s.color=n,e.insert(t,Ci,s))}}function Sr(e,t,n){if(e.has(t,tr)){const s=e.get(t,tr);s.enabled!==n&&(s.enabled=n,e.insert(t,tr,s))}else if(e.has(t,fe)){const s=e.get(t,fe);s.enabled!==n&&(s.enabled=n,e.insert(t,fe,s))}else if(e.has(t,Ci)){const s=e.get(t,Ci);s.enabled!==n&&(s.enabled=n,e.insert(t,Ci,s))}}class Pr{constructor(){this.map_=new Map}get(e){return this.map_.get(e)}set(e,t){this.map_.set(e,t)}delete(e){this.map_.delete(e)}has(e){return this.map_.has(e)}cleanup(e){for(const[t]of this.map_)e.valid(t)||this.map_.delete(t)}ensureInit(e,t){let n=this.map_.get(e);return n||(n=t(),this.map_.set(e,n)),n}clear(){this.map_.clear()}[Symbol.iterator](){return this.map_[Symbol.iterator]()}}function Mr(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let o=0;o<t.length;o++)s[t[o]]=n[o](e);return s},changed(e,s){for(let o=0;o<t.length;o++)if(e[t[o]]!==n[o](s))return!0;return!1},update(e,s){for(let o=0;o<t.length;o++)e[t[o]]=n[o](s)}}}const Tr=.1,Cr={r:.3,g:.5,b:.8,a:1},Er={r:.9,g:.9,b:.9,a:1},Ar={r:.95,g:.95,b:.95,a:1},Rr={Left:0,Center:1,Right:2},kr={Top:0,Middle:1,Bottom:2},Ir={Visible:0,Clip:1,Ellipsis:2},Fr=Q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Rr.Left,verticalAlign:kr.Top,wordWrap:!0,overflow:Ir.Visible,lineHeight:1.2});class Br{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l(H.textCanvasSize,H.textCanvasSize);const t=this.canvas.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("TextRenderer: failed to create 2D canvas context");this.ctx=t}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,fr(this.frameMaxW_)),e.height=Math.max(e.height,fr(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=fr(this.frameMaxW_),e.height=fr(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const o=t&&t.size.x>0&&t.size.y>0,i=o?t.size.x:0,r=o?t.size.y:0,a=e.wordWrap&&o;let l=pr(n,e.content,a?i:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=o?Math.ceil(i):d+2*u,f=o?Math.ceil(r):h+2*u;if(o&&e.overflow===Ir.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,i)}}this.frameMaxW_=Math.max(this.frameMaxW_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(s.width<p||s.height<f)&&(s.width=Math.max(s.width,fr(p)),s.height=Math.max(s.height,fr(f)));const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${m}, ${y}, ${_})`,o&&e.overflow===Ir.Clip&&(n.save(),n.beginPath(),n.rect(0,0,p,f),n.clip());const x=l.length*c;let w;if(o){switch(e.verticalAlign){case kr.Top:w=u;break;case kr.Middle:w=u+(f-2*u-x)/2;break;case kr.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let s;switch(e.align){case Rr.Left:s=u;break;case Rr.Center:s=p/2;break;case Rr.Right:s=p-u;break;default:s=u}n.fillText(t,s,b),b+=c}o&&e.overflow===Ir.Clip&&n.restore();const v=n.getImageData(0,0,p,f),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const o=this.renderText(t,n);return this.cache.set(e,o),o}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Rr.Left:return"left";case Rr.Center:return"center";case Rr.Right:return"right"}}}const Ur=Mr({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?mr(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?yr(e.uiRect,e.entity):0});function Dr(e,t){e.has(t,Ci)||e.insert(t,Ci,{visualType:Ti.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Lr{build(e){se("Text",Fr);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Br(t),s=e.world,o=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Fr));for(const e of o.keys())if(!s.valid(e)||!s.has(e,Fr)){if(s.valid(e)&&s.has(e,Ci)){const t=s.get(e,Ci);t.texture=0,t.visualType=Ti.None,s.insert(e,Ci,t)}o.delete(e)}const e=s.getEntitiesWithComponents([Fr]);for(const t of e){const e=s.get(t,Fr),i=s.has(t,nr)?s.get(t,nr):null,r={text:e,uiRect:i,entity:t},a=o.get(t);if(a&&!Ur.changed(a,r)){if(s.has(t,Ci)&&0!==s.get(t,Ci).texture)continue}Dr(s,t);const l=i?{size:{x:mr(i,t),y:yr(i,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Ci);u.texture=c.textureHandle,u.visualType=Ti.Image,u.color={r:1,g:1,b:1,a:1},u.uvOffset={x:0,y:0},u.uvScale={x:1,y:1},s.insert(t,Ci,u),i&&_r(t,c.width,c.height),o.set(t,Ur.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const zr=new Lr,Wr=0,Hr=re("UIMask",{enabled:!0,mode:Wr});class $r{build(e){se("UIMask",Hr)}}const Or=new $r;function Vr(e,t){const n=t??new Float32Array(16),s=e[0],o=e[1],i=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],g=e[12],m=e[13],y=e[14],_=e[15],x=s*l-o*a,w=s*c-i*a,b=s*u-r*a,v=o*c-i*l,S=o*u-r*l,P=i*u-r*c,M=d*m-h*g,T=d*y-p*g,C=d*_-f*g,E=h*y-p*m,A=h*_-f*m,R=p*_-f*y;let k=x*R-w*A+b*E+v*C-S*T+P*M;return 0===k||(k=1/k,n[0]=(l*R-c*A+u*E)*k,n[1]=(i*A-o*R-r*E)*k,n[2]=(m*P-y*S+_*v)*k,n[3]=(p*S-h*P-f*v)*k,n[4]=(c*C-a*R-u*T)*k,n[5]=(s*R-i*C+r*T)*k,n[6]=(y*b-g*P-_*w)*k,n[7]=(d*P-p*b+f*w)*k,n[8]=(a*A-l*C+u*M)*k,n[9]=(o*C-s*A-r*M)*k,n[10]=(g*S-m*b+_*x)*k,n[11]=(h*b-d*S-f*x)*k,n[12]=(l*T-a*E-c*M)*k,n[13]=(s*E-o*T+i*M)*k,n[14]=(m*w-g*v-y*x)*k,n[15]=(d*v-h*w+p*x)*k),n}function Nr(e,t,n,s,o,i,r){const a=(e-s)/i*2-1,l=(t-o)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function jr(e,t,n,s,o,i,r,a){return e>=n-o*r&&e<=n+o*(1-r)&&t>=s-i*a&&t<=s+i*(1-a)}function Xr(e,t){return 2*Math.atan2(e,t)}const Yr=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Gr={Normal:0,Hovered:1,Pressed:2,Disabled:3},qr=Q("Button",{state:Gr.Normal,transition:null});class Kr{constructor(){this.events_=[],this.entityTypeHandlers_=new Map,this.globalHandlers_=new Map,this.activeDispatches_=new Set,this.entityValidator_=null}on(e,t,n){if(void 0!==n){const s=e,o=t;let i=this.entityTypeHandlers_.get(s);i||(i=new Map,this.entityTypeHandlers_.set(s,i));let r=i.get(o);r||(r=[],i.set(o,r)),r.push(n);let a=!1;return()=>{if(a)return;a=!0;const e=i.get(o);if(e){const t=e.indexOf(n);-1!==t&&e.splice(t,1)}}}{const n=e,s=t;let o=this.globalHandlers_.get(n);o||(o=[],this.globalHandlers_.set(n,o)),o.push(s);let i=!1;return()=>{if(i)return;i=!0;const e=this.globalHandlers_.get(n);if(e){const t=e.indexOf(s);-1!==t&&e.splice(t,1)}}}}removeAll(e){this.entityTypeHandlers_.delete(e)}setEntityValidator(e){this.entityValidator_=e}emit(e,t,n){const s={entity:e,type:t,target:n??e,currentTarget:e,propagationStopped:!1,stopPropagation(){this.propagationStopped=!0}};this.events_.push(s);const o=`${e}:${t}`;return this.activeDispatches_.has(o)||(this.activeDispatches_.add(o),this.dispatchToHandlers_(s),this.activeDispatches_.delete(o)),s}emitBubbled(e,t,n,s){const o={entity:e,type:t,target:n,currentTarget:e,propagationStopped:!1,stopPropagation(){s.propagationStopped=!0}};this.events_.push(o);const i=`${e}:${t}`;this.activeDispatches_.has(i)||(this.activeDispatches_.add(i),this.dispatchToHandlers_(o),this.activeDispatches_.delete(i))}drain(){if(this.entityValidator_)for(const e of this.entityTypeHandlers_.keys())this.entityValidator_(e)||this.entityTypeHandlers_.delete(e);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)}dispatchToHandlers_(e){const t=this.entityTypeHandlers_.get(e.entity);if(t){const n=t.get(e.type);n&&this.invokeHandlers_([...n],e)}const n=this.globalHandlers_.get(e.type);n&&this.invokeHandlers_([...n],e)}invokeHandlers_(e,t){for(const n of e)try{n(t)}catch(e){console.error(`UIEvent handler error [${t.type}]:`,e)}}}const Jr=Ne(new Kr,"UIEvents"),Qr=Ne({generation:0},"UILayoutGeneration");class Zr{build(e){se("UIRect",nr),se("UIRenderer",Ci);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){or=e,ir=t}(n,s);const o={generation:0};e.insertResource(Qr,o);e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(zt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.transform_update(s),o.generation++)},{name:"UILayoutSystem"})),e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([je(zt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),o.generation++)},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const ea=new Zr,ta=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(Vr(t,e),n=!1),e)}}();function na(e,t,n,s){const o=t.emit(n,s,n);!function(e,t,n){let s=t;for(;e.has(s,xe);){const t=e.get(s,xe).entity;if(!e.valid(t))break;if(n(t))return;s=t}}(e,n,i=>{if(o.propagationStopped)return!0;if(!e.has(i,sr))return!1;const r=e.get(i,sr);return r.enabled&&t.emitBubbled(i,s,n,o),r.blockRaycast})}class sa{build(e){se("Interactable",sr),se("Button",qr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),o=new Kr;o.setEntityValidator(e=>t.valid(e)),e.insertResource(Jr,o);let i=null,r=null,a=NaN,l=NaN,c=-1;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(Ut),je(zt),je(Qr)],(e,d,h)=>{if(o.drain(),ns()&&!ss())return;const p=t.getEntitiesWithComponents([Yr]);for(const e of p){const n=t.get(e,Yr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Yr,n))}if(!d.valid)return;const f=u(),g=e.mouseX*f,m=d.screenH-e.mouseY*f;ta.update(d.viewProjection);const y=Nr(g,m,ta.getInverse(d.viewProjection),d.vpX,d.vpY,d.vpW,d.vpH);d.worldMouseX=y.x,d.worldMouseY=y.y;const _=e.isMouseButtonDown(0),x=e.isMouseButtonPressed(0),w=e.isMouseButtonReleased(0),b=y.x!==a||y.y!==l,v=h.generation!==c,S=b||v||(x||w);a=y.x,l=y.y,c=h.generation;let P=i;if(S){n.uiHitTest_update(s,y.x,y.y,_,x,w);const e=n.uiHitTest_getHitEntity();P=4294967295===e?null:e}if(null===i||t.valid(i)||(i=null),i!==P){if(null!==i&&t.valid(i)&&t.has(i,Yr)){const e=t.get(i,Yr);e.hovered=!1,t.insert(i,Yr,e),o.emit(i,"hover_exit")}if(null!==P){xr(t,P,Yr);const e=t.get(P,Yr);e.hovered=!0,t.insert(P,Yr,e),o.emit(P,"hover_enter")}i=P}if(x&&null!==P){const e=t.get(P,Yr);e.pressed=!0,e.justPressed=!0,t.insert(P,Yr,e),r=P,na(t,o,P,"press")}if(w&&null!==r){if(t.valid(r)&&t.has(r,Yr)){const e=t.get(r,Yr);e.pressed=!1,e.justReleased=!0,t.insert(r,Yr,e),na(t,o,r,"release"),r===i&&na(t,o,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const d=new Set;e.addSystemToSchedule(exports.Schedule.Update,kt([],()=>{for(const e of d)t.valid(e)||d.delete(e);const e=t.getEntitiesWithComponents([qr]);for(const n of e){if(xr(t,n,sr,{enabled:!0}),!t.has(n,Yr))continue;const e=t.get(n,Yr),s=t.get(n,qr),o=t.get(n,sr),i=!d.has(n),r=s.state;if(o.enabled?e.pressed?s.state=Gr.Pressed:e.hovered?s.state=Gr.Hovered:s.state=Gr.Normal:s.state=Gr.Disabled,i&&d.add(n),(i||r!==s.state)&&s.transition){const i=lr(s.transition,o.enabled,e.pressed,e.hovered);vr(t,n,i)}else if((i||r!==s.state)&&!s.transition&&t.has(n,tr)){const s=dr(t.get(n,tr).color,o.enabled,e.pressed,e.hovered);vr(t,n,s)}}},{name:"ButtonSystem"}))}}const oa=new sa,ia=Q("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),ra=Q("Focusable",{tabIndex:0,isFocused:!1});class aa{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const la=Ne(new aa,"FocusManager");class ca{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(se("TextInput",ia),ns()&&!ss())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=t,s=e.world,o=new Map,i=l(H.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});if(!r)return void console.warn("TextInputPlugin: failed to create 2D canvas context");const a=r;let c=0,u=0,d=!1,h=!0,p=0,f=0;const g=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!g)return;const m=g;function y(){const t=e.getResource(la);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,ia)?n:null}const _=()=>{d||null===y()||S()},x=()=>{d=!0},w=()=>{d=!1,S()},b=t=>{const n=y();if(null===n)return;if("Escape"===t.key)return void P();const o=s.get(n,ia);if("Enter"===t.key&&!o.multiline){t.preventDefault();return e.getResource(Jr).emit(n,"submit"),void P()}let i=o.cursorPos;"ArrowLeft"===t.key?i=Math.max(0,o.cursorPos-1):"ArrowRight"===t.key?i=Math.min(o.value.length,o.cursorPos+1):"Home"===t.key?i=0:"End"===t.key&&(i=o.value.length),i!==o.cursorPos&&(o.cursorPos=i,m.selectionStart=i,m.selectionEnd=i,o.dirty=!0,M())},v=()=>{const t=y();if(null!==t){const n=s.get(t,ia);n.focused=!1,n.dirty=!0;e.getResource(la).blur()}};function S(){const t=y();if(null===t)return;const n=s.get(t,ia);if(n.readOnly)return;let o=m.value;if(n.maxLength>0&&o.length>n.maxLength&&(o=o.substring(0,n.maxLength),m.value=o),o!==n.value){n.value=o;e.getResource(Jr).emit(t,"change")}n.cursorPos=m.selectionStart??o.length,n.dirty=!0,M()}function P(){const t=y();if(null!==t){const e=s.get(t,ia);e.focused=!1,e.dirty=!0}e.getResource(la).blur(),m.blur()}function M(){h=!0,p=0}m.addEventListener("input",_),m.addEventListener("compositionstart",x),m.addEventListener("compositionend",w),m.addEventListener("keydown",b),m.addEventListener("blur",v),this.cleanupListeners_=()=>{m.removeEventListener("input",_),m.removeEventListener("compositionstart",x),m.removeEventListener("compositionend",w),m.removeEventListener("keydown",b),m.removeEventListener("blur",v),m.remove();const e=n.getResourceManager();for(const t of o.values())e.releaseTexture(t);o.clear(),0!==c&&(n._free(c),c=0,u=0)};let T=null;function C(e,t,r,l){(i.width<r||i.height<l)&&(i.width=fr(Math.max(i.width,r)),i.height=fr(Math.max(i.height,l))),a.clearRect(0,0,i.width,i.height);const d=t.backgroundColor;a.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,a.fillRect(0,0,r,l),a.save(),a.beginPath(),a.rect(t.padding,0,r-2*t.padding,l),a.clip(),a.font=`${t.fontSize}px ${t.fontFamily}`,a.textBaseline="top",a.textAlign="left";const p=0===t.value.length,f=p?t.placeholder:t.password?"●".repeat(t.value.length):t.value,g=p?t.placeholderColor:t.color;a.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const m=Math.ceil(1.2*t.fontSize),y=t.padding;if(t.multiline){const e=pr(a,f,r-2*y);let t=y;for(const n of e)a.fillText(n,y,t),t+=m}else{const e=(l-t.fontSize)/2;a.fillText(f,y,e)}if(t.focused&&h){const e=t.password?"●".repeat(t.cursorPos):t.value.substring(0,t.cursorPos);let n,s,o;if(t.multiline){const e=pr(a,t.value,r-2*y);let i=0,l=0,c=0;for(let n=0;n<e.length;n++){const s=e[n].length;if(i+s>=t.cursorPos){l=n,c=t.cursorPos-i;break}i+=s,n<e.length-1&&i<t.value.length&&"\n"===t.value[i]&&i++,l=n+1,c=0}const u=l<e.length?e[l].substring(0,c):"";n=y+a.measureText(u).width,s=y+l*m,o=m}else n=y+a.measureText(e).width,s=(l-t.fontSize)/2,o=t.fontSize;a.fillStyle=`rgba(${Math.round(255*t.color.r)}, ${Math.round(255*t.color.g)}, ${Math.round(255*t.color.b)}, ${t.color.a})`,a.fillRect(n,s,2,o)}a.restore();const _=a.getImageData(0,0,r,l),x=new Uint8Array(_.data.buffer),w=n.getResourceManager();x.length>u&&(0!==c&&n._free(c),c=n._malloc(x.length),u=x.length),n.HEAPU8.set(x,c);const b=o.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(r,l,c,x.length,1,!0);o.set(e,v);const S=s.get(e,Ci);S.texture=v,S.visualType=Ti.Image,S.uvOffset={x:0,y:0},S.uvScale={x:1,y:1},S.color={r:1,g:1,b:1,a:1},S.enabled=!0,s.insert(e,Ci,S)}e.addSystemToSchedule(exports.Schedule.Update,kt([je(la)],e=>{const t=s.getEntitiesWithComponents([ia]);for(const e of t)xr(s,e,ra,{tabIndex:0,isFocused:!1}),xr(s,e,sr,{enabled:!0,blockRaycast:!0});const n=y();if(n!==T){if(null!==T&&s.valid(T)&&s.has(T,ia)){const e=s.get(T,ia);e.focused=!1,e.dirty=!0,m.blur()}null!==n&&function(e){const t=s.get(e,ia);t.readOnly||(t.focused=!0,t.dirty=!0,m.value=t.value,m.selectionStart=t.cursorPos,m.selectionEnd=t.cursorPos,m.focus(),M())}(n),T=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let t=0===f?0:(e-f)/1e3;f=e,t=Math.min(t,.1);const i=y();if(null!==i&&(p+=t,p>=.5)){p-=.5,h=!h;s.get(i,ia).dirty=!0}const r=n.getResourceManager();for(const[e,t]of o)s.valid(e)&&s.has(e,ia)||(r.releaseTexture(t),o.delete(e));const a=s.getEntitiesWithComponents([ia,nr]);for(const e of a){const t=s.get(e,ia);if(!t.dirty)continue;const n=s.get(e,nr),o=Math.ceil(n.size.x),i=Math.ceil(n.size.y);o<=0||i<=0||(s.has(e,Ci)||s.insert(e,Ci,{visualType:Ti.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),C(e,t,o,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const ua=new ca,da=Mr({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?mr(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?yr(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});function ha(e,t){e.has(t,Ci)||e.insert(t,Ci,{visualType:Ti.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class pa{build(e){se("Image",tr);const t=e.world,n=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,tr)||n.delete(e);const e=t.getEntitiesWithComponents([tr]);for(const s of e){const e=t.get(s,tr),o=t.has(s,nr)?t.get(s,nr):null,i={image:e,uiRect:o,entity:s},r=n.get(s);if(r&&t.has(s,Ci)&&!da.changed(r,i))continue;ha(t,s);const a=t.get(s,Ci);if(!e.enabled){a.enabled=!1,t.insert(s,Ci,a),n.set(s,da.take(i));continue}a.enabled=!0,a.texture=e.texture,a.color={r:e.color.r,g:e.color.g,b:e.color.b,a:e.color.a},a.material=e.material,a.uvOffset={x:0,y:0},a.uvScale={x:1,y:1};if(e.texture!==V&&0!==e.texture?e.imageType===Qi.Sliced?a.visualType=Ti.NineSlice:a.visualType=Ti.Image:a.visualType=Ti.SolidColor,e.imageType===Qi.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));o&&mr(o,s),o&&yr(o,s),e.fillMethod===Zi.Horizontal?(e.fillOrigin===er.Left||(a.uvOffset={x:1-t,y:0}),a.uvScale={x:t,y:1}):(e.fillOrigin===er.Bottom||(a.uvOffset={x:0,y:1-t}),a.uvScale={x:1,y:t})}else if(e.imageType===Qi.Tiled){const t=o?mr(o,s):0,n=o?yr(o,s):0;e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale={x:t/e.tileSize.x,y:n/e.tileSize.y})}t.insert(s,Ci,a),n.set(s,da.take(i))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const fa=new pa,ga=Q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null,onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1}},{entityFields:["graphicEntity","group"]}),ma=Q("ToggleGroup",{allowSwitchOff:!1});function ya(e,t,n){if(!e.has(t,Ci))return;const s=e.get(t,Ci);s.color.r===n.r&&s.color.g===n.g&&s.color.b===n.b&&s.color.a===n.a||(s.color=n,e.insert(t,Ci,s))}function _a(e,t,n){if(!e.has(t,Ci))return;const s=e.get(t,Ci);s.enabled!==n&&(s.enabled=n,e.insert(t,Ci,s))}class xa{build(e){se("Toggle",ga),se("ToggleGroup",ma);const t=e.world,n=new Set;e.addSystemToSchedule(exports.Schedule.Update,kt([je(Jr)],e=>{const s=t.getEntitiesWithComponents([ga]);if(!ns()||ss()){const o=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,ga);s.isOn&&0!==s.group&&t.valid(s.group)&&(o.has(s.group)?(s.isOn=!1,t.insert(e,ga,s)):o.set(s.group,e))}const i=new Map;for(const e of s){const n=t.get(e,ga);if(0!==n.group&&t.valid(n.group)){let t=i.get(n.group);t||(t=[],i.set(n.group,t)),t.push(e)}}for(const n of s){if(xr(t,n,sr,{enabled:!0}),!t.has(n,Yr))continue;const s=t.get(n,Yr),o=t.get(n,ga),r=t.get(n,sr);if(s.justPressed&&r.enabled){const s=o.group,r=0!==s&&t.valid(s)&&t.has(s,ma);if(o.isOn&&r){if(!t.get(s,ma).allowSwitchOff)continue}if(o.isOn=!o.isOn,t.insert(n,ga,o),o.isOn&&r){const o=i.get(s);if(o)for(const s of o){if(s===n)continue;const o=t.get(s,ga);o.isOn&&(o.isOn=!1,t.insert(s,ga,o),e.emit(s,"change"))}}e.emit(n,"change")}let a;if(o.transition)a=lr(o.transition,r.enabled,s.pressed,s.hovered);else{a=dr(o.isOn?o.onColor:o.offColor,r.enabled,s.pressed,s.hovered)}ya(t,n,a)}}for(const e of s){const n=t.get(e,ga);wr(t,n.graphicEntity,e=>{_a(t,e,n.isOn)})}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const wa=new xa,ba=Ji,va=Q("ProgressBar",{value:0,fillEntity:0,direction:Ji.LeftToRight},{entityFields:["fillEntity"]});class Sa{build(e){se("ProgressBar",va);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([],()=>{const e=t.getEntitiesWithComponents([va,nr]);for(const n of e){const e=t.get(n,va),s=Math.max(0,Math.min(1,e.value));wr(t,e.fillEntity,n=>{ar(t,n,e.direction,s)})}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Pa=new Sa,Ma=Q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ta=Q("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});function Ca(e,t,n,s){if(!e.has(t,xe))return{x:n,y:s};const o=e.get(t,xe).entity;if(!e.valid(o)||!e.has(o,de))return{x:n,y:s};const i=e.get(o,de),r=0!==i.worldScale.x?i.worldScale.x:1,a=0!==i.worldScale.y?i.worldScale.y:1,l=Xr(i.worldRotation.z,i.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}class Ea{build(e){se("Draggable",Ma),se("DragState",Ta);const t=e.world,n=e.getResource(Jr);let s=null,o={x:0,y:0},i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(Ut),je(zt)],(e,r)=>{if(ns()&&!ss())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ma,Yr]);let n=null,i=-1/0,r=-1;for(const s of e){if(!t.get(s,Ma).enabled)continue;if(t.get(s,Yr).hovered){let e=0;t.has(s,fe)&&(e=t.get(s,fe).layer);const o=gr(t,s);(e>i||e===i&&o>=r)&&(i=e,r=o,n=s)}}if(null!==n){s=n,o={x:a.x,y:a.y},t.has(n,Ta)||t.insert(n,Ta);const e=t.get(n,Ta),i=t.get(n,de);e.startWorldPos={x:i.worldPosition.x,y:i.worldPosition.y},e.currentWorldPos={x:i.worldPosition.x,y:i.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Ta)){t.get(s,Ta).isDragging=!1}s=null}if(null!==s&&null===i){if(!t.valid(s))return void(s=null);const e=a.x-o.x,l=a.y-o.y,c=Math.sqrt(e*e+l*l),u=t.get(s,Ma);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){i=s,s=null;t.get(i,Ta).isDragging=!0,n.emit(i,"drag_start")}}if(null!==i){if(!t.valid(i)||!t.has(i,Ta))return void(i=null);const s=t.get(i,Ta),o=t.get(i,Ma),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const d=function(e,t,n,s){let o=e.lockX?t.startWorldPos.x:n,i=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(o=Math.max(o,e.constraintMin.x),i=Math.max(i,e.constraintMin.y)),null!==e.constraintMax&&(o=Math.min(o,e.constraintMax.x),i=Math.min(i,e.constraintMax.y)),{x:o,y:i}}(o,s,c,u);c=d.x,u=d.y;const h=s.currentWorldPos.x,p=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,y:u-p},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(i,nr)){const e=t.get(i,nr),n=Ca(t,i,s.deltaWorld.x,s.deltaWorld.y);e.offsetMin.x+=n.x,e.offsetMin.y+=n.y,t.insert(i,nr,e)}else if(t.has(i,de)){const e=Ca(t,i,s.deltaWorld.x,s.deltaWorld.y),n=t.get(i,de);n.position.x+=e.x,n.position.y+=e.y,t.insert(i,de,n)}n.emit(i,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(i,"drag_end"),i=null)}},{name:"DragSystem"}))}}const Aa=new Ea,Ra=Q("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1},{entityFields:["contentEntity"]});function ka(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function Ia(e,t,n,s,o){const i=2/(s=Math.max(1e-4,s)),r=i*o,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+i*l)*o,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-i*c)*a}}class Fa{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){se("ScrollView",Ra);const t=e.world,n=new Pr,s={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([je(Ut),je(zt),je(qe)],(e,o,i)=>{const r=ns()&&!ss(),a=Math.min(i.delta,.05);n.cleanup(t),o.valid&&(s.x=o.worldMouseX,s.y=o.worldMouseY);const l=t.getEntitiesWithComponents([Ra,nr]);for(const i of l){xr(t,i,Hr,{enabled:!0,mode:Wr});const l=t.get(i,Ra),c=t.get(i,nr),u=n.ensureInit(i,()=>({isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN})),d=mr(c,i),h=yr(c,i);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,we)){const e=t.get(l.contentEntity,we).entities;let n=0,s=0,o=0,i=0;for(const r of e){if(!t.valid(r)||!t.has(r,de))continue;const e=t.get(r,de);let a=0,l=0,c=.5,u=.5;if(t.has(r,nr)){const e=t.get(r,nr);a=mr(e,r)||e.size.x,l=yr(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*u,f=e.position.y+l*(1-u);d<n&&(n=d),h>s&&(s=h),p<o&&(o=p),f>i&&(i=f)}0===p&&(p=s-n),0===f&&(f=i-o)}const g=Math.max(0,p-d),m=Math.max(0,f-h);if(!r&&o.valid){xr(t,i,sr,{enabled:!0,blockRaycast:!0});const n=t.has(i,Yr)?t.get(i,Yr):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=ka(l.scrollX,0,g,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=ka(l.scrollY,0,m,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=ka(l.scrollY,0,m,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=ka(l.scrollX,0,g,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>m;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Ia(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Tr&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Tr?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:m,t=Ia(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Tr&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Tr?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,m)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,m+t))}wr(t,l.contentEntity,e=>{if(!t.has(e,de))return;const n=t.get(e,de),s=n.position.x,o=n.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(o-u.lastAppliedY)>.01)&&(u.contentBaseY=o),n.position.x=u.contentBaseX-l.scrollX,n.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=n.position.x,u.lastAppliedY=n.position.y,t.insert(e,de,n)})}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{n.clear()}}}const Ba=new Fa,Ua=Ji,Da=Q("Slider",{value:0,minValue:0,maxValue:1,direction:Ji.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1},{entityFields:["fillEntity","handleEntity"]});function La(e,t,n,s,o,i){const r=mr(s,o)*n.worldScale.x,a=yr(s,o)*n.worldScale.y,l=Xr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,p=d*u-h*c,f=d*c+h*u,g=-s.pivot.x*r,m=-s.pivot.y*a;switch(i){case Ji.LeftToRight:return r>0?(p-g)/r:0;case Ji.RightToLeft:return r>0?1-(p-g)/r:0;case Ji.BottomToTop:return a>0?(f-m)/a:0;case Ji.TopToBottom:return a>0?1-(f-m)/a:0}}function za(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Ji.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=.5,e.anchorMax.x=n,e.anchorMax.y=.5;break;case Ji.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=.5,e.anchorMax.x=1-n,e.anchorMax.y=.5;break;case Ji.BottomToTop:e.anchorMin.x=.5,e.anchorMin.y=n,e.anchorMax.x=.5,e.anchorMax.y=n;break;case Ji.TopToBottom:e.anchorMin.x=.5,e.anchorMin.y=1-n,e.anchorMax.x=.5,e.anchorMax.y=1-n}}class Wa{build(e){se("Slider",Da);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(Ut),je(zt),je(Jr)],(e,n,s)=>{if(!n.valid)return;const o=t.getEntitiesWithComponents([Da,nr]);for(const i of o){const o=t.get(i,Da),r=t.get(i,nr);if(!ns()||ss()){if(t.has(i,de)){xr(t,i,sr,{enabled:!0,blockRaycast:!0}),wr(t,o.handleEntity,e=>{xr(t,e,sr,{enabled:!0,blockRaycast:!1})});const a=t.get(i,de);let l=!1;if(t.has(i,Yr)&&(l=t.get(i,Yr).pressed),wr(t,o.handleEntity,e=>{!l&&t.has(e,Yr)&&(l=t.get(e,Yr).pressed)}),l&&e.isMouseButtonDown(0)){let e=La(n.worldMouseX,n.worldMouseY,a,r,i,o.direction);e=Math.max(0,Math.min(1,e));let l=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(l=Math.round(l));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,l)),t.insert(i,Da,o),o.value!==c&&s.emit(i,"change")}}}const a=o.maxValue-o.minValue,l=a>0?(o.value-o.minValue)/a:0;wr(t,o.fillEntity,e=>{ar(t,e,o.direction,l)}),wr(t,o.handleEntity,e=>{if(!t.has(e,nr))return;const n=t.get(e,nr);za(n,o.direction,l),t.insert(e,nr,n)})}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Ha=new Wa;class $a{build(e){se("Focusable",ra);const t=e.world,n=new aa;e.insertResource(la,n),e.addSystemToSchedule(exports.Schedule.Update,kt([je(Ut),je(Jr)],(e,s)=>{if(ns()&&!ss())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const o=t.getEntitiesWithComponents([ra]);for(const e of o){if(!t.has(e,Yr))continue;t.get(e,Yr).justPressed&&i(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of o){if(!t.valid(n))continue;if(t.has(n,sr)){if(!t.get(n,sr).enabled)continue}const s=t.get(n,ra);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,i(s[l])}function i(e){const o=n.focusedEntity;if(o===e)return;if(null!==o&&t.valid(o)&&t.has(o,ra)){t.get(o,ra).isFocused=!1,s.emit(o,"blur",o)}n.focus(e);t.get(e,ra).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Oa=new $a,Va=Q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Na(){return n()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:o}=t;return{top:n.top,bottom:o-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class ja{build(e){se("SafeArea",Va);const t=e.world;let s=Na(),o=!0,i=0,r=0;if(n()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=Na(),o=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=Na(),o=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(zt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===i&&a===r||(i=e.screenH,r=a,o=!0),!o)return;o=!1;const l=u(),c=n()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([Va,nr]);for(const e of d){const n=t.get(e,Va),o=t.get(e,nr),i=n.applyTop?s.top*c:0,r=n.applyBottom?s.bottom*c:0,a=n.applyLeft?s.left*c:0,l=n.applyRight?s.right*c:0;let u=!1;o.offsetMin.x===a&&o.offsetMin.y===r||(o.offsetMin={x:a,y:r},u=!0),o.offsetMax.x===-l&&o.offsetMax.y===-i||(o.offsetMax={x:-l,y:-i},u=!0),u&&t.insert(e,nr,o)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Xa=new ja,Ya=Q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Ga=null;class qa{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null),Ga=null}build(e){se("ListView",Ya);const t=e.world,n=new Map;Ga=n,e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([je(Ut)],e=>{const s=ns()&&!ss();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const o=t.getEntitiesWithComponents([Ya,nr]);for(const i of o){xr(t,i,sr,{enabled:!0,blockRaycast:!0}),xr(t,i,Hr,{enabled:!0,mode:Wr});let o=n.get(i);o||(o={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(i,o));const r=t.get(i,Ya),a=t.get(i,nr),l=yr(a,i),c=mr(a,i);if(!s){const n=t.has(i,Yr)?t.get(i,Yr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of o.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),o.itemEntities.delete(e));for(let e=d;e<h;e++){let n=o.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Ce,{value:`ListItem_${e}`}),t.insert(n,nr,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,i),o.itemEntities.set(e,n),o.renderer&&o.renderer(e,n)),t.has(n,de)){const s=t.get(n,de);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,de,s)}}o.visibleStart=d,o.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{for(const[,e]of n)for(const n of e.itemEntities.values())t.valid(n)&&t.despawn(n);n.clear()}}}const Ka=new qa,Ja=Q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0},{entityFields:["listEntity","labelEntity"]});class Qa{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){se("Dropdown",Ja);const t=e.world,n=new Map,s=new Set;function o(e){wr(t,e,e=>{if(!t.has(e,de))return;const n=t.get(e,de);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,de,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})})}function i(e){if(t.has(e,Ci)){const n=t.get(e,Ci);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&vr(t,e,{...Er})}else if(t.has(e,fe)){const n=t.get(e,fe);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&vr(t,e,{...Er})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const o=n.listEntity;if(0===o||!t.valid(o))return;d(o,!0),u(s);let i=0;if(t.has(e,nr)){const n=t.get(e,nr);i=mr(n,e)||n.size.x}else if(t.has(e,fe)){i=t.get(e,fe).size.x}s.ddWidth=i;const r=30*n.options.length;t.insert(o,nr,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:r},pivot:{x:.5,y:1}}),t.insert(o,Ci,{visualType:Ti.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn();t.insert(r,Ce,{value:`Option_${e}`}),t.insert(r,nr,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:30*-e},offsetMax:{x:0,y:0},size:{x:i,y:30},pivot:{x:.5,y:1}}),t.insert(r,de,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,Ci,{visualType:Ti.SolidColor,texture:0,color:{...Ar},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),t.insert(r,sr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,o),s.optionEntities.push(r);const a=t.spawn();t.insert(a,de,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(a,Fr,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Rr.Left,verticalAlign:kr.Middle,wordWrap:!1,overflow:Ir.Clip,lineHeight:1.2}),t.insert(a,nr,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:30},pivot:{x:.5,y:.5}}),t.setParent(a,r),s.textEntities.push(a)}h(s)}function a(e,t,n){t.isOpen=!1,u(n),d(t.listEntity,!1)}function l(e,t,n,s,o){t.selectedIndex=s,a(0,t,n),o.emit(e,"change")}function c(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Fr))return;const s=t.get(n,Fr);let o={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},i=s.content,r=!1;if(1===o.r&&1===o.g&&1===o.b&&1===o.a&&(o={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];i!==t&&(i=t,r=!0)}r&&t.insert(n,Fr,{content:i,fontSize:s.fontSize,fontFamily:s.fontFamily,color:o,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function u(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function d(e,n){wr(t,e,e=>{t.has(e,sr)&&t.insert(e,sr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),Sr(t,e,n)})}function h(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s))continue;const o=n===e.highlightIndex?{...Cr}:{...Ar};vr(t,s,o)}}function p(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Yr))continue;if(t.get(n,Yr).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,kt([je(Ut),je(Jr)],(e,f)=>{for(const[e,o]of n)t.valid(e)||(u(o),n.delete(e),s.delete(e));const g=ns()&&!ss(),m=t.getEntitiesWithComponents([Ja]);for(const u of m){const m=t.get(u,Ja);let y=n.get(u);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(u,y)),o(m.listEntity),s.has(u)||(i(u),s.add(u)),m.isOpen||d(m.listEntity,!1),c(m),g)continue;xr(t,u,sr,{enabled:!0,blockRaycast:!0});const _=t.has(u,Yr)?t.get(u,Yr):null;if(_?.justPressed&&(m.isOpen?a(u,m,y):r(u,m,y)),m.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,Yr))continue;if(t.get(n,Yr).justPressed){l(u,m,y,e,f);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,Yr))continue;if(t.get(s,Yr).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,h(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=m.options.length-1?y.highlightIndex=0:y.highlightIndex++,h(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=m.options.length-1:y.highlightIndex--,h(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?l(u,m,y,y.highlightIndex,f):e.isKeyPressed("Escape")&&a(u,m,y),e.isMouseButtonPressed(0)&&(_?.hovered||p(y)||a(u,m,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]}),this.cleanup_=()=>{for(const[,e]of n)u(e);n.clear(),s.clear()}}}const Za=new Qa,el=re("LayoutGroup",{direction:0,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:0,reverseOrder:!1});class tl{build(e){se("LayoutGroup",el)}}const nl=new tl,sl=0,ol=1,il=0,rl=1,al=0,ll=0,cl=3,ul=re("FlexContainer",{direction:sl,wrap:il,justifyContent:al,alignItems:cl,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0}}),dl=re("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class hl{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const pl=new hl,fl={primary:{r:.25,g:.56,b:.96,a:1},secondary:{r:.4,g:.4,b:.4,a:1},background:{r:.08,g:.08,b:.08,a:1},surface:{r:.14,g:.14,b:.14,a:1},error:{r:.9,g:.2,b:.2,a:1},text:{r:.93,g:.93,b:.93,a:1},textSecondary:{r:.6,g:.6,b:.6,a:1},border:{r:.3,g:.3,b:.3,a:1},fontFamily:"Arial",fontSize:{xs:10,sm:12,md:14,lg:18,xl:24},spacing:{xs:4,sm:8,md:12,lg:16,xl:24},button:{height:36,color:{r:.25,g:.25,b:.25,a:1},textColor:{r:.93,g:.93,b:.93,a:1},transition:{normalColor:{r:.25,g:.25,b:.25,a:1},hoveredColor:{r:.3,g:.3,b:.3,a:1},pressedColor:{r:.18,g:.18,b:.18,a:1},disabledColor:{r:.15,g:.15,b:.15,a:.6}}},slider:{trackHeight:16,trackColor:{r:.15,g:.15,b:.15,a:1},fillColor:{r:.25,g:.56,b:.96,a:1},handleSize:24,handleColor:{r:1,g:1,b:1,a:1}},toggle:{size:{x:24,y:24},onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1},checkColor:{r:1,g:1,b:1,a:1}},input:{height:36,backgroundColor:{r:.15,g:.15,b:.15,a:1},textColor:{r:1,g:1,b:1,a:1},placeholderColor:{r:.6,g:.6,b:.6,a:1},fontSize:16,padding:6},dropdown:{height:32,backgroundColor:{r:.2,g:.2,b:.2,a:1},itemHeight:28},panel:{backgroundColor:{r:.14,g:.14,b:.14,a:1},padding:12},scrollView:{backgroundColor:{r:.1,g:.1,b:.1,a:1}}},gl=Ne(null,"UITheme");let ml=null;function yl(){return ml??fl}function _l(e,t){const n=e.spawn();if(t.name&&e.insert(n,Ce,{value:t.name}),e.insert(n,de,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},...t.transform}),t.rect&&e.insert(n,nr,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:0,y:0},pivot:{x:.5,y:.5},...t.rect}),t.renderer&&e.insert(n,Ci,{visualType:Ti.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0,...t.renderer}),t.interactable&&e.insert(n,sr,{enabled:!0,blockRaycast:!0,raycastTarget:!0,...t.interactable}),t.text){const s=yl();e.insert(n,Fr,{content:"",fontFamily:s.fontFamily,fontSize:s.fontSize.md,color:{r:1,g:1,b:1,a:1},align:Rr.Left,verticalAlign:kr.Top,wordWrap:!1,overflow:0,lineHeight:1.2,...t.text})}if(t.image&&e.insert(n,tr,{...tr._default,...t.image}),t.flex&&e.insert(n,ul,{direction:sl,wrap:il,justifyContent:al,alignItems:cl,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0},...t.flex}),t.flexItem&&e.insert(n,dl,{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,...t.flexItem}),t.mask&&e.insert(n,Hr,{enabled:!0,mode:Wr,...t.mask}),t.components)for(const[s,o]of t.components)e.insert(n,s,o);return t.parent&&e.setParent(n,t.parent),n}function xl(e,t={}){const n=yl(),{text:s="Button",fontSize:o=n.fontSize.md,size:i={x:120,y:n.button.height},color:r=n.button.color,textColor:a=n.button.textColor,transition:l=null,parent:c}=t,u=_l(e,{name:"ButtonLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:s,fontSize:o,color:a,align:Rr.Center,verticalAlign:kr.Middle}}),d=_l(e,{name:"Button",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Ti.SolidColor,color:r},interactable:{enabled:!0},components:[[qr,{state:0,transition:l}]]});if(e.setParent(u,d),t.events){if(t.onClick){const e=t.onClick;t.events.on(d,"click",()=>e(d))}if(t.onHover){const e=t.onHover;t.events.on(d,"hover_enter",()=>e(d))}}return d}function wl(e,t={}){const n=yl(),{value:s=0,minValue:o=0,maxValue:i=1,direction:r=Ji.LeftToRight,size:a={x:200,y:n.slider.trackHeight},trackColor:l=n.slider.trackColor,fillColor:c=n.slider.fillColor,handleSize:u={x:n.slider.handleSize,y:n.slider.handleSize},handleColor:d=n.slider.handleColor,wholeNumbers:h=!1,parent:p}=t,f=_l(e,{name:"SliderFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Ti.SolidColor,color:c}}),g=_l(e,{name:"SliderHandle",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:u},renderer:{visualType:Ti.SolidColor,color:d},interactable:{enabled:!0,blockRaycast:!0},components:[[Ma,{enabled:!0,dragThreshold:5,lockX:!1,lockY:!0}]]}),m=_l(e,{name:"Slider",parent:p,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Ti.SolidColor,color:l},interactable:{enabled:!0,blockRaycast:!0},components:[[Da,{value:s,minValue:o,maxValue:i,direction:r,wholeNumbers:h,fillEntity:f,handleEntity:g}]]});if(e.setParent(f,m),e.setParent(g,m),t.onChange&&t.events){const n=t.onChange;t.events.on(m,"change",()=>{const t=e.get(m,Da);n(t.value,m)})}return m}function bl(e,t={}){const n=yl(),{isOn:s=!0,size:o=n.toggle.size,onColor:i=n.toggle.onColor,offColor:r=n.toggle.offColor,checkSize:a={x:.58*n.toggle.size.x,y:.58*n.toggle.size.y},checkColor:l=n.toggle.checkColor,group:c=0,transition:u=null,label:d,parent:h}=t,p=_l(e,{name:"ToggleCheck",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Ti.SolidColor,color:l}}),f=_l(e,{name:"Toggle",parent:h,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Ti.SolidColor,color:s?i:r},interactable:{enabled:!0},components:[[ga,{isOn:s,graphicEntity:p,group:c,transition:u,onColor:i,offColor:r}]]});if(e.setParent(p,f),d&&_l(e,{name:"ToggleLabel",parent:f,rect:{anchorMin:{x:1,y:0},anchorMax:{x:1,y:1},offsetMin:{x:8,y:0},size:{x:100,y:0}},text:{content:d,fontSize:n.fontSize.md,align:Rr.Left,verticalAlign:kr.Middle}}),t.onChange&&t.events){const n=t.onChange;t.events.on(f,"change",()=>{const t=e.get(f,ga);n(t.isOn,f)})}return f}function vl(e,t={}){const n=yl(),{value:s=0,size:o={x:200,y:n.slider.trackHeight},direction:i=Ji.LeftToRight,trackColor:r=n.slider.trackColor,fillColor:a=n.primary,parent:l}=t,c=_l(e,{name:"ProgressFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Ti.SolidColor,color:a}}),u=_l(e,{name:"ProgressBar",parent:l,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Ti.SolidColor,color:r},components:[[va,{value:s,fillEntity:c,direction:i}]]});return e.setParent(c,u),u}function Sl(e,t={}){const n=yl(),{size:s={x:300,y:400},contentSize:o={x:300,y:800},horizontal:i=!1,vertical:r=!0,elastic:a=!0,mask:l=!0,parent:c}=t,u=_l(e,{name:"ScrollContent",rect:{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},size:{x:o.x,y:o.y},pivot:{x:.5,y:1}}}),d=_l(e,{name:"ScrollView",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:s},renderer:{visualType:Ti.SolidColor,color:n.scrollView.backgroundColor},mask:l?{mode:Wr,enabled:!0}:void 0,components:[[Ra,{contentEntity:u,horizontalEnabled:i,verticalEnabled:r,contentWidth:o.x,contentHeight:o.y,elastic:a,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,wheelSensitivity:.1}]]});return e.setParent(u,d),d}function Pl(e,t={}){const n=yl(),{placeholder:s="",value:o="",size:i={x:200,y:n.input.height},fontSize:r=n.input.fontSize,backgroundColor:a=n.input.backgroundColor,textColor:l=n.input.textColor,maxLength:c=0,multiline:u=!1,password:d=!1,parent:h}=t,p=_l(e,{name:"TextInput",parent:h,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Ti.SolidColor,color:a},interactable:{enabled:!0},components:[[ia,{value:o,placeholder:s,fontSize:r,fontFamily:n.fontFamily,color:l,backgroundColor:a,placeholderColor:n.input.placeholderColor,padding:n.input.padding,maxLength:c,multiline:u,password:d,readOnly:!1,focused:!1,cursorPos:o.length,dirty:!0}],[ra,{tabIndex:0,isFocused:!1}]]});if(t.events){if(t.onChange){const n=t.onChange;t.events.on(p,"change",()=>{const t=e.get(p,ia);n(t.value,p)})}if(t.onSubmit){const n=t.onSubmit;t.events.on(p,"submit",()=>{const t=e.get(p,ia);n(t.value,p)})}}return p}function Ml(e,t){const n=yl(),{options:s,selectedIndex:o=-1,size:i={x:160,y:n.dropdown.height},fontSize:r=n.fontSize.md,parent:a}=t,l=_l(e,{name:"DropdownLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:(o>=0?s[o]:s[0])??"",fontSize:r,align:Rr.Left,verticalAlign:kr.Middle}}),c=_l(e,{name:"DropdownList",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},size:{x:i.x,y:Math.min(s.length*n.dropdown.itemHeight,200)},pivot:{x:.5,y:1}},renderer:{visualType:Ti.SolidColor,color:n.surface},mask:{mode:Wr,enabled:!0}}),u=_l(e,{name:"Dropdown",parent:a,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Ti.SolidColor,color:n.dropdown.backgroundColor},interactable:{enabled:!0},components:[[Ja,{options:s,selectedIndex:o,isOpen:!1,listEntity:c,labelEntity:l}]]});if(e.setParent(l,u),e.setParent(c,u),t.onChange&&t.events){const n=t.onChange;t.events.on(u,"change",()=>{const t=e.get(u,Ja);n(t.selectedIndex,u)})}return u}function Tl(e,t){const n=yl();return _l(e,{name:"Label",parent:t.parent,rect:t.size?{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size}:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:t.text,fontSize:t.fontSize??n.fontSize.md,color:t.color??n.text,align:t.align??Rr.Left,verticalAlign:t.verticalAlign??kr.Middle}})}function Cl(e,t={}){const n=yl();return _l(e,{name:"Panel",parent:t.parent,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size??{x:300,y:200}},renderer:{visualType:Ti.SolidColor,color:t.color??n.panel.backgroundColor}})}function El(e,t={}){return _l(e,{name:"FlexRow",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:sl,wrap:t.wrap?rl:il,justifyContent:t.justifyContent??al,alignItems:t.alignItems??ll,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}function Al(e,t={}){return _l(e,{name:"FlexColumn",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:ol,wrap:t.wrap?rl:il,justifyContent:t.justifyContent??al,alignItems:t.alignItems??ll,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}const Rl={button:xl,slider:wl,toggle:bl,textInput:Pl,dropdown:Ml,progressBar:vl,label:Tl,panel:Cl,flexRow:El,flexColumn:Al,scrollView:Sl};const kl={spawn:_l,destroy:function e(t,n){if(t.valid(n)){if(t.has(n,we)){const s=[...t.get(n,we).entities];for(const n of s)e(t,n)}t.despawn(n)}},build:function e(t,n,s){let o,i;if("element"===n.type)o=_l(t,{...n,parent:s}),i=o;else{if(o=(0,Rl[n.type])(t,{...n.options??{},parent:s}),"scrollView"===n.type){i=t.get(o,Ra).contentEntity}else i=o}const r=n.children;if(r&&i)for(const n of r)e(t,n,i);return n.ref&&n.ref(o),o},label:Tl,panel:Cl,button:xl,slider:wl,toggle:bl,scrollView:Sl,textInput:Pl,dropdown:Ml,progressBar:vl,flexRow:El,flexColumn:Al};class Il{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let s,o;if("string"==typeof e){const t=(new TextEncoder).encode(e);o=t.length,s=this.raw_._malloc(o+1),this.raw_.HEAPU8.set(t,s),this.raw_.HEAPU8[s+o]=0}else o=e.length,s=this.raw_._malloc(o),this.raw_.HEAPU8.set(e,s);const i=this.api_.loadSkeleton(s,o,t,t.length,n);return this.raw_._free(s),i}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,s,o){this.api_.setAtlasPageTexture(e,t,n,s,o)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,s=0){return!!this.api_.playAnimation(e,t,n,s)}addAnimation(e,t,n=!0,s=0,o=0){return!!this.api_.addAnimation(e,t,n,s,o)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse animations JSON",e),[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse skins JSON",e),[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,s))return this.raw_._free(n),this.raw_._free(s),null;const o=this.raw_.HEAPF32[n>>2],i=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:o,y:i}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,s=t>>2,o={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(t),o}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],s=this.raw_._malloc(8),o=s,i=s+4;for(let s=0;s<t;s++){const t=this.api_.getMeshBatchVertexCount(e,s),r=this.api_.getMeshBatchIndexCount(e,s);if(t<=0||r<=0)continue;const a=8*t*4,l=2*r,c=this.raw_._malloc(a),u=this.raw_._malloc(l);this.api_.getMeshBatchData(e,s,c,u,o,i);const d=new Float32Array(this.raw_.HEAPF32.buffer,c,8*t),h=new Uint16Array(this.raw_.HEAPU8.buffer,u,r);n.push({vertices:new Float32Array(d),indices:new Uint16Array(h),textureId:this.raw_.HEAPU32[o>>2],blendMode:this.raw_.HEAPU32[i>>2]}),this.raw_._free(c),this.raw_._free(u)}return this.raw_._free(s),n}setDefaultMix(e,t){this.api_.setDefaultMix(e,t)}setMixDuration(e,t,n,s){this.api_.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){this.api_.setTrackAlpha(e,t,n)}setAttachment(e,t,n){return!!this.api_.setAttachment(e,t,n)}setIKTarget(e,t,n,s,o){return!!this.api_.setIKTarget(e,t,n,s,o)}setSlotColor(e,t,n,s,o,i){return!!this.api_.setSlotColor(e,t,n,s,o,i)}enableEvents(e){this.api_.enableEvents(e)}collectEvents(e){const t=this.api_.getEventCount(e);if(0===t)return[];const n=this.api_.getEventBuffer(),s=this.raw_.HEAPF32,o=n>>2,i=[];for(let e=0;e<t;e++){const t=o+4*e;i.push({type:s[t],track:s[t+1],floatValue:s[t+2],intValue:s[t+3]})}return this.api_.clearEvents(),i}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(n)}off(e,t,n){const s=this.listeners_.get(e);if(!s)return;const o=s.get(t);o&&o.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}class Fl{constructor(e){this.entities_=new Map,this.cachedFrame_=-1,this.cachedEntries_=[],this.controller_=e}get controller(){return this.controller_}get entityCount(){return this.entities_.size}loadEntity(e,t,n,s,o){const i=this.controller_.loadSkeleton(t,n,o);if(i<0)return console.error(`[ModuleBackend] Failed to load skeleton: ${this.controller_.getLastError()}`),!1;const r=this.controller_.getAtlasPageCount(i);for(let e=0;e<r;e++){const t=this.controller_.getAtlasPageTextureName(i,e),n=s.get(t);n&&this.controller_.setAtlasPageTexture(i,e,n.glId,n.w,n.h)}const a=this.controller_.createInstance(i);return this.entities_.set(e,{skelHandle:i,instanceId:a,skeletonScale:1,flipX:!1,flipY:!1,layer:0}),!0}setEntityProps(e,t){const n=this.entities_.get(e);n&&(void 0!==t.skeletonScale&&(n.skeletonScale=t.skeletonScale),void 0!==t.flipX&&(n.flipX=t.flipX),void 0!==t.flipY&&(n.flipY=t.flipY),void 0!==t.layer&&(n.layer=t.layer))}setAnimation(e,t,n){const s=this.entities_.get(e);s&&this.controller_.play(s.instanceId,t,n)}setSkin(e,t){const n=this.entities_.get(e);n&&this.controller_.setSkin(n.instanceId,t)}getBounds(e){const t=this.entities_.get(e);return t?this.controller_.getBounds(t.instanceId):null}getAnimations(e){const t=this.entities_.get(e);return t?this.controller_.getAnimations(t.instanceId):[]}getSkins(e){const t=this.entities_.get(e);return t?this.controller_.getSkins(t.instanceId):[]}setDefaultMix(e,t){const n=this.entities_.get(e);n&&this.controller_.setDefaultMix(n.skelHandle,t)}setMixDuration(e,t,n,s){const o=this.entities_.get(e);o&&this.controller_.setMixDuration(o.skelHandle,t,n,s)}setTrackAlpha(e,t,n){const s=this.entities_.get(e);s&&this.controller_.setTrackAlpha(s.instanceId,t,n)}setAttachment(e,t,n){const s=this.entities_.get(e);return!!s&&this.controller_.setAttachment(s.instanceId,t,n)}setIKTarget(e,t,n,s,o){const i=this.entities_.get(e);return!!i&&this.controller_.setIKTarget(i.instanceId,t,n,s,o)}setSlotColor(e,t,n,s,o,i){const r=this.entities_.get(e);return!!r&&this.controller_.setSlotColor(r.instanceId,t,n,s,o,i)}enableEvents(e){const t=this.entities_.get(e);t&&this.controller_.enableEvents(t.instanceId)}updateAll(e){for(const t of this.entities_.values())this.controller_.update(t.instanceId,e)}extractAndSubmitMeshes(e,t,n=-1){const s=e.renderer_submitSpineBatchByEntity;if(!s)return;if(this.cachedFrame_!==n){this.cachedEntries_.length=0;for(const[e,t]of this.entities_){const n=this.controller_.extractMeshBatches(t.instanceId);for(const s of n)0!==s.vertices.length&&0!==s.indices.length&&this.cachedEntries_.push({vertices:s.vertices,indices:s.indices,textureId:s.textureId,blendMode:s.blendMode,entity:e,info:t})}this.cachedFrame_=n}if(0===this.cachedEntries_.length)return;let o=0,i=0;for(const e of this.cachedEntries_)o+=e.vertices.byteLength,i+=e.indices.byteLength;const r=e._malloc(o),a=e._malloc(i);let l=0,c=0;for(const n of this.cachedEntries_){const o=r+l,i=a+c;e.HEAPF32.set(n.vertices,o>>2),new Uint16Array(e.HEAPU8.buffer,i,n.indices.length).set(n.indices),s.call(e,t,o,n.vertices.length/8,i,n.indices.length,n.textureId,n.blendMode,n.entity,n.info.skeletonScale,n.info.flipX,n.info.flipY,n.info.layer,0),l+=n.vertices.byteLength,c+=n.indices.byteLength}e._free(r),e._free(a)}removeEntity(e){const t=this.entities_.get(e);t&&(this.controller_.destroyInstance(t.instanceId),this.controller_.unloadSkeleton(t.skelHandle),this.entities_.delete(e))}shutdown(){for(const e of this.entities_.values())this.controller_.destroyInstance(e.instanceId),this.controller_.unloadSkeleton(e.skelHandle);this.entities_.clear()}}class Bl{constructor(e,t){this.backends_=new Map,this.loadingBackends_=new Map,this.entityVersions_=new Map,this.coreModule_=e,this.factories_=t}static detectVersion(e){const t=function(e){if(e.length<10)return null;let t=8;const{value:n,bytesRead:s}=Ul(e,t);if(t+=s,n<=1||t+n-1>e.length)return null;const o=(new TextDecoder).decode(e.subarray(t,t+n-1));return o.startsWith("4.2")?"4.2":o.startsWith("4.1")?"4.1":null}(e);return t||function(e){if(e.length<4)return null;let t=0;const{value:n,bytesRead:s}=Ul(e,t);t+=s,n>0&&(t+=n-1);if(t>=e.length)return null;const{value:o,bytesRead:i}=Ul(e,t);if(t+=i,o<=1||t+o-1>e.length)return null;const r=(new TextDecoder).decode(e.subarray(t,t+o-1));return r.startsWith("3.")?"3.8":null}(e)}static detectVersionJson(e){const t=e.match(/"spine"\s*:\s*"(\d+\.\d+)/);return t?t[1].startsWith("4.2")?"4.2":t[1].startsWith("4.1")?"4.1":t[1].startsWith("3.")?"3.8":null:null}async loadEntity(e,t,n,s,o){const i="string"==typeof t?Bl.detectVersionJson(t):Bl.detectVersion(t);if(!i)return null;if("4.2"===i&&!this.factories_.has("4.2"))return this.entityVersions_.set(e,"4.2"),"4.2";this.coreModule_.spine_setNeedsReload?.(o,e,!1);const r=await this.ensureBackend(i);if(!r)return console.error(`[SpineManager] Failed to create backend for version ${i}`),null;const a=t instanceof Uint8Array;return r.loadEntity(e,t,n,s,a)?(this.entityVersions_.set(e,i),i):(console.error(`[SpineManager] Failed to load entity ${e} into backend ${i}`),null)}updateAnimations(e){for(const t of this.backends_.values())t.updateAll(e)}submitMeshes(e,t=-1){for(const n of this.backends_.values())n.extractAndSubmitMeshes(this.coreModule_,e,t)}removeEntity(e){const t=this.entityVersions_.get(e);if(!t)return void this.entityVersions_.delete(e);const n=this.backends_.get(t);n&&n.removeEntity(e),this.entityVersions_.delete(e)}getEntityVersion(e){return this.entityVersions_.get(e)}hasModuleBackend(e){return this.backends_.has(e)}getModuleBackend(e){return this.backends_.get(e)}setAnimation(e,t,n){const s=this.entityVersions_.get(e);if(!s)return;const o=this.backends_.get(s);o&&o.setAnimation(e,t,n)}setSkin(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setSkin(e,t)}setEntityProps(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setEntityProps(e,t)}getBounds(e){const t=this.entityVersions_.get(e);if(!t)return null;const n=this.backends_.get(t);return n?n.getBounds(e):null}getAnimations(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getAnimations(e):[]}getSkins(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getSkins(e):[]}setDefaultMix(e,t){const n=this.getEntityBackend_(e);n&&n.setDefaultMix(e,t)}setMixDuration(e,t,n,s){const o=this.getEntityBackend_(e);o&&o.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){const s=this.getEntityBackend_(e);s&&s.setTrackAlpha(e,t,n)}setAttachment(e,t,n){const s=this.getEntityBackend_(e);return!!s&&s.setAttachment(e,t,n)}setIKTarget(e,t,n,s,o){const i=this.getEntityBackend_(e);return!!i&&i.setIKTarget(e,t,n,s,o)}setSlotColor(e,t,n,s,o,i){const r=this.getEntityBackend_(e);return!!r&&r.setSlotColor(e,t,n,s,o,i)}enableEvents(e){const t=this.getEntityBackend_(e);t&&t.enableEvents(e)}hasInstance(e){return this.entityVersions_.has(e)}shutdown(){for(const e of this.backends_.values())e.shutdown();this.backends_.clear(),this.loadingBackends_.clear(),this.entityVersions_.clear()}getEntityBackend_(e){const t=this.entityVersions_.get(e);if(t)return this.backends_.get(t)}async ensureBackend(e){const t=this.backends_.get(e);if(t)return t;const n=this.loadingBackends_.get(e);if(n)return n;const s=this.factories_.get(e);if(!s)return console.warn(`[SpineManager] No module factory for version ${e}`),null;const o=(async()=>{try{const t=await s(),n=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"]),setDefaultMix:t("spine_setDefaultMix",null,["number","number"]),setMixDuration:t("spine_setMixDuration",null,["number","string","string","number"]),setTrackAlpha:t("spine_setTrackAlpha",null,["number","number","number"]),enableEvents:t("spine_enableEvents",null,["number"]),getEventCount:t("spine_getEventCount","number",["number"]),getEventBuffer:t("spine_getEventBuffer","number",[]),clearEvents:t("spine_clearEvents",null,[]),setAttachment:t("spine_setAttachment","number",["number","string","string"]),setIKTarget:t("spine_setIKTarget","number",["number","string","number","number","number"]),setSlotColor:t("spine_setSlotColor","number",["number","string","number","number","number","number"])}}(t),o=new Il(t,n),i=new Fl(o);return this.backends_.set(e,i),i}catch(t){return console.error(`[SpineManager] Failed to load WASM module for version ${e}:`,t),null}finally{this.loadingBackends_.delete(e)}})();return this.loadingBackends_.set(e,o),o}}function Ul(e,t){let n=0,s=0,o=0;do{const i=e[t+o++];if(n|=(127&i)<<s,s+=7,!(128&i))break}while(s<35);return{value:n,bytesRead:o}}async function Dl(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Ll=Ne({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),zl={r:.2,g:.4,b:1,a:.7},Wl={r:.2,g:1,b:.2,a:.7},Hl={r:.2,g:1,b:1,a:.7},$l={r:1,g:1,b:.2,a:.5},Ol={r:1,g:.2,b:.2,a:.8},Vl={r:1,g:.2,b:.2,a:1},Nl=1.5,jl=16;function Xl(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Yl(e){switch(e){case Oe.Static:return zl;case Oe.Kinematic:return Hl;default:return Wl}}function Gl(e,t,n,s,o,i){const r=Math.cos(o),a=Math.sin(o),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)So.line(l[e],l[(e+1)%4],i,Nl)}function ql(e,t,n,s,o,i){const r=Math.cos(o),a=Math.sin(o),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),d=l(-n,-s),h=l(n,-s);So.line(c,d,i,Nl),So.line(u,h,i,Nl);for(let e=0;e<jl;e++){const t=e/jl*Math.PI,o=(e+1)/jl*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(o),s+n*Math.sin(o));So.line(r,a,i,Nl)}for(let e=0;e<jl;e++){const t=Math.PI+e/jl*Math.PI,o=Math.PI+(e+1)/jl*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(o),-s+n*Math.sin(o));So.line(r,a,i,Nl)}}function Kl(e,t,n,s){const o=e+.5*n,i=t+.5*s;So.line({x:e,y:t},{x:o,y:i},Ol,Nl);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=o-6*(l*Math.cos(a)-c*Math.sin(a)),d=i-6*(l*Math.sin(a)+c*Math.cos(a)),h=o-6*(l*Math.cos(a)+c*Math.sin(a)),p=i-6*(-l*Math.sin(a)+c*Math.cos(a));So.line({x:o,y:i},{x:u,y:d},Ol,Nl),So.line({x:o,y:i},{x:h,y:p},Ol,Nl)}function Jl(e,t,n){const s=e.getResource(Ll);if(!s||!s.enabled)return;const o=function(e){const t=e.world.getEntitiesWithComponents([ye]);for(const n of t){const t=e.world.get(n,ye);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=e.world.getEntitiesWithComponents([Re,de]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of i){const n=e.world.get(t,Re);if(!n.enabled)continue;const i=e.world.get(t,de),a=i.worldPosition.x,l=i.worldPosition.y,c=Xl(i.worldRotation);if(s.showColliders){if(e.world.has(t,ke)){const s=e.world.get(t,ke),i=s.isSensor?$l:Yl(n.bodyType),r=s.offset.x*o,u=s.offset.y*o,d=Math.cos(c),h=Math.sin(c);Gl(a+r*d-u*h,l+r*h+u*d,s.halfExtents.x*o,s.halfExtents.y*o,c,i)}if(e.world.has(t,Ie)){const s=e.world.get(t,Ie),i=s.isSensor?$l:Yl(n.bodyType),r=s.offset.x*o,u=s.offset.y*o,d=Math.cos(c),h=Math.sin(c),p=a+r*d-u*h,f=l+r*h+u*d;So.circleOutline({x:p,y:f},s.radius*o,i,Nl,32)}if(e.world.has(t,Fe)){const s=e.world.get(t,Fe),i=s.isSensor?$l:Yl(n.bodyType),r=s.offset.x*o,u=s.offset.y*o,d=Math.cos(c),h=Math.sin(c);ql(a+r*d-u*h,l+r*h+u*d,s.radius*o,s.halfHeight*o,c,i)}if(e.world.has(t,Be)){const s=e.world.get(t,Be),i=s.isSensor?$l:Yl(n.bodyType),r=Math.cos(c),u=Math.sin(c),d=a+(s.point1.x*o*r-s.point1.y*o*u),h=l+(s.point1.x*o*u+s.point1.y*o*r),p=a+(s.point2.x*o*r-s.point2.y*o*u),f=l+(s.point2.x*o*u+s.point2.y*o*r);So.line({x:d,y:h},{x:p,y:f},i,Nl)}if(e.world.has(t,Ue)){const s=e.world.get(t,Ue),i=s.isSensor?$l:Yl(n.bodyType),r=Math.cos(c),u=Math.sin(c),d=s.vertices;for(let e=0;e<d.length;e++){const t=d[e],n=d[(e+1)%d.length],s=a+(t.x*o*r-t.y*o*u),c=l+(t.x*o*u+t.y*o*r),h=a+(n.x*o*r-n.y*o*u),p=l+(n.x*o*u+n.y*o*r);So.line({x:s,y:c},{x:h,y:p},i,Nl)}}if(e.world.has(t,De)){const s=e.world.get(t,De),i=Yl(n.bodyType),r=Math.cos(c),u=Math.sin(c),d=s.points,h=s.isLoop?d.length:d.length-1;for(let e=0;e<h;e++){const t=d[e],n=d[(e+1)%d.length],s=a+(t.x*o*r-t.y*o*u),c=l+(t.x*o*u+t.y*o*r),h=a+(n.x*o*r-n.y*o*u),p=l+(n.x*o*u+n.y*o*r);So.line({x:s,y:c},{x:h,y:p},i,Nl)}}}if(s.showVelocity&&r&&n.bodyType===Oe.Dynamic){const e=r.getLinearVelocity(t);Kl(a,l,e.x*o,e.y*o)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)So.circle({x:e.contactX,y:e.contactY},3,Vl,!0,32)}}const Ql=Ne({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Zl=Ne(null,"PhysicsAPI");function ec(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}class tc{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/30,subStepCount:t.subStepCount??4,contactHertz:t.contactHertz??30,contactDampingRatio:t.contactDampingRatio??10,contactSpeed:t.contactSpeed??3,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(Ql,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Set,s=new Set,o=new Map;let i=-1;const r=Dl(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount,this.config_.contactHertz,this.config_.contactDampingRatio,this.config_.contactSpeed);const a=function(e){const t=e.world.getEntitiesWithComponents([ye]);for(const n of t){const t=e.world.get(n,ye);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),l=1/a,c=e.world;c.onDespawn(e=>{n.has(e)&&(r._physics_destroyJoint(e),n.delete(e)),t.has(e)&&(r._physics_destroyBody(e),t.delete(e),o.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([je(qe)],u=>{if(ns()&&!ss())return;const d=c.getEntitiesWithComponents([Re,de]),h=new Set;for(const n of d)if(h.add(n),t.has(n)){if(c.isChangedSince(n,Re,i)){const e=c.get(n,Re),t=o.get(n);!t||t.bodyType===e.bodyType&&t.gravityScale===e.gravityScale&&t.linearDamping===e.linearDamping&&t.angularDamping===e.angularDamping&&t.fixedRotation===e.fixedRotation&&t.bullet===e.bullet||(r._physics_updateBodyProperties(n,e.bodyType,e.gravityScale,e.linearDamping,e.angularDamping,e.fixedRotation?1:0,e.bullet?1:0),t.bodyType=e.bodyType,t.gravityScale=e.gravityScale,t.linearDamping=e.linearDamping,t.angularDamping=e.angularDamping,t.fixedRotation=e.fixedRotation,t.bullet=e.bullet)}const e=o.get(n);if(e&&e.bodyType===Oe.Kinematic){const e=c.get(n,de),t=ec(e.worldRotation);r._physics_setBodyTransform(n,e.worldPosition.x*l,e.worldPosition.y*l,t)}}else{const i=c.get(n,Re);if(!i.enabled)continue;const a=c.get(n,de),u=c.has(n,xe),d=u?a.worldPosition.x:a.position.x,h=u?a.worldPosition.y:a.position.y,p=ec(u?a.worldRotation:a.rotation);r._physics_createBody(n,i.bodyType,d*l,h*l,p,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation?1:0,i.bullet?1:0),oc(e,r,n,this.config_.collisionLayerMasks),t.add(n),c.has(n,xe)&&s.add(n),o.set(n,{bodyType:i.bodyType,gravityScale:i.gravityScale,linearDamping:i.linearDamping,angularDamping:i.angularDamping,fixedRotation:i.fixedRotation,bullet:i.bullet})}i=c.getWorldTick();for(const e of t)h.has(e)||(r._physics_destroyBody(e),t.delete(e),o.delete(e));!function(e,t,n,s,o){const i=e.getEntitiesWithComponents([Le,Re]);for(const r of i){if(s.has(r))continue;if(!n.has(r))continue;const i=e.get(r,Le);if(!i.enabled)continue;const a=i.connectedEntity;n.has(a)&&(t._physics_createRevoluteJoint(a,r,i.anchorA.x*o,i.anchorA.y*o,i.anchorB.x*o,i.anchorB.y*o,i.enableMotor?1:0,i.motorSpeed,i.maxMotorTorque,i.enableLimit?1:0,i.lowerAngle,i.upperAngle,i.collideConnected?1:0),s.add(r))}for(const i of e.getEntitiesWithComponents([ze,Re])){if(s.has(i))continue;if(!n.has(i))continue;const r=e.get(i,ze);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createDistanceJoint(a,i,r.anchorA.x*o,r.anchorA.y*o,r.anchorB.x*o,r.anchorB.y*o,r.length*o,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.minLength*o,r.maxLength*o,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(i))}for(const i of e.getEntitiesWithComponents([We,Re])){if(s.has(i))continue;if(!n.has(i))continue;const r=e.get(i,We);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createPrismaticJoint(a,i,r.anchorA.x*o,r.anchorA.y*o,r.anchorB.x*o,r.anchorB.y*o,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*o,r.upperTranslation*o,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(i))}for(const i of e.getEntitiesWithComponents([He,Re])){if(s.has(i))continue;if(!n.has(i))continue;const r=e.get(i,He);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWeldJoint(a,i,r.anchorA.x*o,r.anchorA.y*o,r.anchorB.x*o,r.anchorB.y*o,r.linearHertz,r.angularHertz,r.linearDampingRatio,r.angularDampingRatio,r.collideConnected?1:0),s.add(i))}for(const i of e.getEntitiesWithComponents([$e,Re])){if(s.has(i))continue;if(!n.has(i))continue;const r=e.get(i,$e);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWheelJoint(a,i,r.anchorA.x*o,r.anchorA.y*o,r.anchorB.x*o,r.anchorB.y*o,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*o,r.upperTranslation*o,r.enableMotor?1:0,r.maxMotorTorque,r.motorSpeed,r.collideConnected?1:0),s.add(i))}}(c,r,t,n,l),t.size>0&&u.delta>0&&r._physics_step(u.delta),function(e,t,n,s){const o=t._physics_getDynamicBodyCount();if(0===o)return;const i=t._physics_getDynamicBodyTransforms(),r=i>>2,a=t.HEAPU32,l=t.HEAPF32,c=e.world.getCppRegistry();if(!c)return;const u=e.world.getWasmModule(),d=s.size>0;if(!d&&u?.registry_batchSyncPhysicsTransforms){const e=o*ac,s=u._malloc(e);return u.HEAPU8.set(new Uint8Array(t.HEAPU8.buffer,i,e),s),u.registry_batchSyncPhysicsTransforms(c,s,o,n),void u._free(s)}const h=u?.getTransformPtr?e=>u.getTransformPtr(c,e):null,p=u?.HEAPF32,f=h&&p?null:c.addTransform.bind(c),g=ic;for(let t=0;t<o;t++){const o=r+t*rc,i=a[o];let c=l[o+1]*n,u=l[o+2]*n,m=l[o+3];if(d&&s.has(i)){const t=e.world.get(i,xe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,de)){const n=e.world.get(t.entity,de),s=ec(n.worldRotation),o=u,i=c-n.worldPosition.x,r=o-n.worldPosition.y,a=Math.cos(-s),l=Math.sin(-s);c=(i*a-r*l)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*l+r*a)/(0!==n.worldScale.y?n.worldScale.y:1),m-=s}}const y=.5*m,_=Math.cos(y),x=Math.sin(y);if(h&&p){const e=h(i);if(e){const t=e>>2;p[t]=c,p[t+1]=u,p[t+2]=0,p[t+3]=0,p[t+4]=0,p[t+5]=x,p[t+6]=_,p[t+7]=1,p[t+8]=1,p[t+9]=1,p[t+10]=c,p[t+11]=u,p[t+12]=0,p[t+13]=0,p[t+14]=0,p[t+15]=x,p[t+16]=_,p[t+17]=1,p[t+18]=1,p[t+19]=1;continue}}g.position.x=c,g.position.y=u,g.rotation.w=_,g.rotation.x=0,g.rotation.y=0,g.rotation.z=x,g.worldPosition.x=c,g.worldPosition.y=u,g.worldRotation.w=_,g.worldRotation.x=0,g.worldRotation.y=0,g.worldRotation.z=x,f(i,g)}}(e,r,a,s),function(e,t,n){t._physics_collectEvents();const s=[],o=t._physics_getCollisionEnterCount();if(o>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<o;i++){const o=e+6*i;s.push({entityA:t.HEAPU32[o],entityB:t.HEAPU32[o+1],normalX:t.HEAPF32[o+2],normalY:t.HEAPF32[o+3],contactX:t.HEAPF32[o+4]*n,contactY:t.HEAPF32[o+5]*n})}}const i=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Ql,{collisionEnters:s,collisionExits:i,sensorEnters:a,sensorExits:c})}(e,r,a)},{name:"PhysicsSystem"})),e.physicsModule=r,e.insertResource(Zl,lc._fromModule(r)),function(e,t,n){e.insertResource(Ll,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Eo("physics-debug-draw",()=>{Jl(e,t,n)})}(e,Zl,Ql),e.setFixedTimestep(this.config_.fixedTimestep)});r.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=r}}const nc=16;function sc(e,t,n){if(!n)return t;for(let t=0;t<nc;t++)if(e===1<<t)return n[t];return t}function oc(e,t,n,s){const o=e.world;if(o.has(n,ke)){const e=o.get(n,ke),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s);t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.radius??.05,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r)}if(o.has(n,Ie)){const e=o.get(n,Ie),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s);t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r)}if(o.has(n,Fe)){const e=o.get(n,Fe),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r)}if(o.has(n,Be)){const e=o.get(n,Be),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s);t._physics_addSegmentShape(n,e.point1.x,e.point1.y,e.point2.x,e.point2.y,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r)}if(o.has(n,Ue)){const e=o.get(n,Ue),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s),a=e.vertices,l=Math.min(a.length,8),c=2*l*4,u=t._malloc(c),d=u>>2;for(let e=0;e<l;e++)t.HEAPF32[d+2*e]=a[e].x,t.HEAPF32[d+2*e+1]=a[e].y;t._physics_addPolygonShape(n,u,l,e.radius??0,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r),t._free(u)}if(o.has(n,De)){const e=o.get(n,De),s=e.points;if(s.length<4)return;const i=2*s.length*4,r=t._malloc(i),a=r>>2;for(let e=0;e<s.length;e++)t.HEAPF32[a+2*e]=s[e].x,t.HEAPF32[a+2*e+1]=s[e].y;t._physics_addChainShape(n,r,s.length,e.isLoop?1:0,e.friction,e.restitution,e.categoryBits??1,e.maskBits??65535),t._free(r)}}const ic={position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}},rc=4,ac=4*rc;class lc{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(lc.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)}createRevoluteJoint(e,t,n,s,o){const i=o??{};return 0!==this.module_._physics_createRevoluteJoint(e,t,n.x,n.y,s.x,s.y,i.enableMotor?1:0,i.motorSpeed??0,i.maxMotorTorque??0,i.enableLimit?1:0,i.lowerAngle??0,i.upperAngle??0,i.collideConnected?1:0)}destroyJoint(e){this.module_._physics_destroyJoint(e)}setRevoluteMotorSpeed(e,t){this.module_._physics_setRevoluteMotorSpeed(e,t)}setRevoluteMaxMotorTorque(e,t){this.module_._physics_setRevoluteMaxMotorTorque(e,t)}enableRevoluteMotor(e,t){this.module_._physics_enableRevoluteMotor(e,t?1:0)}enableRevoluteLimit(e,t){this.module_._physics_enableRevoluteLimit(e,t?1:0)}setRevoluteLimits(e,t,n){this.module_._physics_setRevoluteLimits(e,t,n)}getRevoluteAngle(e){return this.module_._physics_getRevoluteAngle(e)}getRevoluteMotorTorque(e){return this.module_._physics_getRevoluteMotorTorque(e)}raycast(e,t,n,s=65535,o=100){const i=1/o,r=this.module_._physics_raycast(e.x*i,e.y*i,t.x,t.y,n*i,s);if(0===r)return[];const a=this.module_._physics_getRaycastBuffer()>>2,l=[];for(let e=0;e<r;e++){const t=a+6*e;l.push({entity:this.module_.HEAPU32[t],point:{x:this.module_.HEAPF32[t+1]*o,y:this.module_.HEAPF32[t+2]*o},normal:{x:this.module_.HEAPF32[t+3],y:this.module_.HEAPF32[t+4]},fraction:this.module_.HEAPF32[t+5]})}return l.sort((e,t)=>e.fraction-t.fraction),l}overlapCircle(e,t,n=65535,s=100){const o=1/s,i=this.module_._physics_overlapCircle(e.x*o,e.y*o,t*o,n);if(0===i)return[];const r=this.module_._physics_getOverlapBuffer()>>2,a=[],l=new Set;for(let e=0;e<i;e++){const t=this.module_.HEAPU32[r+e];l.has(t)||(l.add(t),a.push(t))}return a}setAwake(e,t){this.module_._physics_setAwake(e,t?1:0)}isAwake(e){return 0!==this.module_._physics_isAwake(e)}static setDebugDraw(e,t){const n=e.getResource(Ll);n&&(n.enabled=t,e.insertResource(Ll,n))}static setDebugDrawConfig(e,t){const n=e.getResource(Ll);n&&e.insertResource(Ll,{...n,...t})}}const cc={nearest:0,linear:1},uc={repeat:0,clamp:1,mirror:2};function dc(e,t,n=!0,s){const o=e.getResourceManager(),i=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,i),s&&(s.filterMode||s.wrapMode)&&o.createTextureEx){const e=cc[s.filterMode??"linear"]??1,a=uc[s.wrapMode??"clamp"]??1;r=o.createTextureEx(t.width,t.height,i,t.pixels.length,1,n,e,a)}else r=o.createTexture(t.width,t.height,i,t.pixels.length,1,n);return e._free(i),r}function hc(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 pc(e,t,n){const s=e.FS;if(!s)return!1;try{return function(e,t){const n=e.FS;if(!n)return;const s=t.substring(0,t.lastIndexOf("/"));if(!s)return;const o=s.split("/").filter(e=>e);let i="";for(const e of o){i+="/"+e;try{n.mkdir(i)}catch{}}}(e,t),s.writeFile(t,n),!0}catch(e){return console.warn(`[Runtime] Failed to write virtual FS: ${t}`,e),!1}}async function fc(e){const{app:t,module:n,sceneData:s,provider:o,spineManager:i,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},o=t.textureImporterSettings;for(const i of t.entities)for(const t of i.components){const i=Os(t.type);for(const r of i){if("texture"!==r.type)continue;const i=t.data[r.field];if("string"==typeof i&&i&&void 0===s[i])try{const t=o?.[i];s[i]=dc(e,await n.loadPixels(i),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${i}`,e),s[i]=0}}}return s}(n,s,o);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const o=n[e];if(o&&o>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(o,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);const d=await async function(e,t,n,s){const o=new Set,i=new Map;for(const r of t.entities)for(const t of r.components){const r=Vs(t.type);if(!r||!t.data)continue;const a=t.data[r.skeletonField],l=t.data[r.atlasField];if(!a||!l)continue;const c=`${a}:${l}`;if(o.has(c))continue;o.add(c);const u=n.resolvePath(l);try{const t=await n.readText(l),o=n.resolvePath(a),r="binary"===b(o)?.contentType?await n.readBinary(a):await n.readText(a),d=s?"string"==typeof r?Bl.detectVersionJson(r):Bl.detectVersion(r):null,h=hc(t),p=u.substring(0,u.lastIndexOf("/")),f=e.getResourceManager(),g=new Map;for(const t of h){const s=p+"/"+t;try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=dc(e,o,!1);f.registerTextureWithPath(i,s),g.set(t,{glId:f.getTextureGLId(i),w:o.width,h:o.height})}catch(e){console.warn(`[Spine] Failed to load texture: ${s}`,e)}}(!d||"4.2"===d)&&(pc(e,u,t),pc(e,o,r)),i.set(c,{version:d,skelData:r,atlasText:t,textures:g})}catch(e){console.warn(`[Runtime] Failed to load spine asset: skel=${a} atlas=${l}`,e)}}return i}(n,s,o,i);if(r){const e={gravity:a?.gravity??{...z},fixedTimestep:a?.fixedTimestep??W,subStepCount:a?.subStepCount??4,contactHertz:a?.contactHertz??120,contactDampingRatio:a?.contactDampingRatio??10,contactSpeed:a?.contactSpeed??10};new tc("",e,()=>Promise.resolve(r)).build(t)}const h=await async function(e,t,n){const s={};for(const o of t.entities)for(const t of o.components){const o=Os(t.type).find(e=>"font"===e.type);if(!o)continue;const i=t.data[o.field];if("string"==typeof i&&i&&void 0===s[i])try{let t,o;const r=b(i);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(i)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[i]=0;continue}const a=i.substring(0,i.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(i),o=i.substring(0,i.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[i]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=dc(e,c,!1),d=e.getResourceManager();s[i]=d.loadBitmapFont(t,u,c.width,c.height)}catch(e){console.warn(`[Runtime] Failed to load bitmap font: ${i}`,e),s[i]=0}}return s}(n,s,o),p=await async function(e,t){const n={},s={};for(const o of e.entities)for(const e of o.components){if(!e.data)continue;const o=Os(e.type).find(e=>"material"===e.type);if(!o)continue;const i=e.data[o.field];if("string"==typeof i&&i&&void 0===n[i])try{const e=JSON.parse(await t.readText(i));if(!e.vertexSource||!e.fragmentSource){n[i]=0;continue}const o=e.vertexSource+e.fragmentSource;let r=s[o];r||(r=Gt.createShader(e.vertexSource,e.fragmentSource),s[o]=r),n[i]=Gt.createFromAsset(e,r)}catch(e){console.warn(`[Runtime] Failed to load material: ${i}`,e),n[i]=0}}return n}(s,o);await async function(e,t,n){const s=new Set;for(const o of t.entities)for(const t of o.components){const o=Os(t.type);for(const i of o){if("anim-clip"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&!s.has(o)){s.add(o);try{const t=await n.readText(o),s=JSON.parse(t),i=rn(s),r=new Map;for(const t of i)try{const s=await n.loadPixels(t);r.set(t,dc(e,s))}catch(e){console.warn(`[Runtime] Failed to load anim texture: ${t}`,e),r.set(t,0)}cn(an(o,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${o}`,e)}}}}}(n,s,o),await async function(e,t,n){const s=new Set;for(const o of t.entities)for(const t of o.components){const o=Os(t.type);for(const i of o){if("tilemap"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&!s.has(o)){s.add(o);try{const t=await n.readText(o),s=An(JSON.parse(t));if(!s)continue;const i=[];for(const t of s.tilesets){const s=Rn(o,t.image);let r=0;try{const t=await n.loadPixels(s);r=dc(e,t),gn(r,t.width,t.height)}catch(e){console.warn(`[Runtime] Failed to load tileset texture: ${s}`,e)}i.push({textureHandle:r,columns:t.columns})}_n(o,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:i})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${o}`,e)}}}}}(n,s,o),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=Os(e.type);for(const o of t){if("audio"!==o.type)continue;const t=e.data[o.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await hn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await hn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,o),function(e,t,n,s){const o={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Os(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=o[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,h,p);const f=Ys(t.world,s),g=t.world.getCppRegistry();if(g&&n.transform_update(g),i&&g&&d.size>0)for(const e of s.entities)for(const t of e.components){const n=Vs(t.type);if(!n||!t.data)continue;const s=t.data[n.skeletonField],o=t.data[n.atlasField];if(!s||!o)continue;const r=`${s}:${o}`,a=d.get(r);if(!a||!a.version||"4.2"===a.version)continue;const l=f.get(e.id);if(void 0===l)continue;await i.loadEntity(l,a.skelData,a.atlasText,a.textures,g),i.setEntityProps(l,{skeletonScale:t.data.skeletonScale??1,flipX:t.data.flipX??!1,flipY:t.data.flipY??!1,layer:t.data.layer??0});const c=t.data.skin;c&&i.setSkin(l,c);const u=t.data.animation;u&&i.setAnimation(l,u,!1!==t.data.loop)}if(c&&t.hasResource(Ii))for(const e of f.values())t.world.insert(e,Ee,{scene:c,persistent:!1});if(l){const e=t.getResource(Zs);e&&e.setAddressableManifest(l)}}function gc(e,t,n){return{name:e,async setup(){await fc({...n,sceneData:t,sceneName:e})}}}async function mc(e){const{app:t,firstScene:n,aspectRatio:s}=e;Li(t);const o={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,spineManager:e.spineManager,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},i=t.getResource(Ii);for(const t of e.scenes)i.register(gc(t.name,t.data,o));n&&(i.setInitial(n),await i.load(n)),void 0!==s&&Js(t.world,s)}class yc{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const o of e.entities)for(const e of o.components){if(!e.data)continue;const o=Vs(e.type);if(o){const s=e.data[o.skeletonField],i=e.data[o.atlasField];s&&("binary"===b(s)?.contentType?n.add(s):t.add(s)),i&&t.add(i)}const i=Os(e.type);for(const o of i){const i=e.data[o.field];"string"==typeof i&&i&&("font"===o.type?(s.add(i),t.add(i)):"material"===o.type||"anim-clip"===o.type||"tilemap"===o.type?t.add(i):"audio"===o.type&&n.add(i))}}const o=[];for(const e of t)o.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)o.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(o);const i=[];for(const e of s){const t=b(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||i.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}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(),o=await createImageBitmap(s),i=new OffscreenCanvas(o.width,o.height).getContext("2d");i.drawImage(o,0,0);const r=i.getImageData(0,0,o.width,o.height);return o.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}let _c=null;const xc={update(e,t){_c?.spine_update?.(e._cpp,t)},play:(e,t,n=!0,s=0)=>_c?.spine_play?.(e,t,n,s)??!1,addAnimation:(e,t,n=!0,s=0,o=0)=>_c?.spine_addAnimation?.(e,t,n,s,o)??!1,setSkin:(e,t)=>_c?.spine_setSkin?.(e,t)??!1,getBonePosition:(e,t)=>_c?.spine_getBonePosition?.(e,t)??null,hasInstance:e=>_c?.spine_hasInstance?.(e)??!1,reloadAssets(e){_c?.spine_reloadAssets?.(e._cpp)},getAnimations:e=>_c?.spine_getAnimations?.(e)??[],getSkins:e=>_c?.spine_getSkins?.(e)??[]};class wc{constructor(e){this.app_=null,e instanceof Bl?(this.spineManager_=e,this.provider_=null):(this.spineManager_=null,this.provider_=e??null)}get spineManager(){return this.spineManager_}setSpineManager(e){if(this.spineManager_=e,this.app_){const t=this.app_,n=t.pipeline;n?.addPreFlushCallback(n=>{const s=t.getResource(qe).frameCount;e.submitMeshes(n._cpp,s)})}}build(e){this.app_=e;const t=e.wasmModule;if(_c=t,!this.spineManager_&&this.provider_){const e=function(e){const t=["3.8","4.1","4.2"],n=new Map;for(const s of t)n.set(s,async()=>{const[t,n]=await Promise.all([e.loadJs(s),e.loadWasm(s)]),o=new Blob([`${t};\nself.__ESSpineModule__ = ESSpineModule;`],{type:"application/javascript"}),i=URL.createObjectURL(o);await import(/* @vite-ignore */i),URL.revokeObjectURL(i);const r=globalThis.__ESSpineModule__;return delete globalThis.__ESSpineModule__,r({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Spine] WASM instantiation failed:",e)}),{})})});return n}(this.provider_);this.spineManager_=new Bl(t,e)}const n=this,s={_id:Symbol("SpineUpdateSystem"),_name:"SpineUpdateSystem",_params:[],_fn:()=>{const t=e.world.getCppRegistry();if(!t)return;const s=e.getResource(qe);xc.update({_cpp:t},s.delta),n.spineManager_?.updateAnimations(s.delta)}};if(e.addSystemToSchedule(exports.Schedule.PreUpdate,s),this.spineManager_){const t=this.spineManager_,n=e.pipeline;n?.addPreFlushCallback(n=>{const s=e.getResource(qe).frameCount;t.submitMeshes(n._cpp,s)})}}}const bc="__preview__";const vc={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),o=wi.createRenderTarget(e.width,e.height,s);return{_handle:o,textureId:wi.getTargetTexture(o),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){wi.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(wi.releaseRenderTarget(e._handle),vc.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){wi.begin(t,e._handle)},end(){wi.end()},getDepthTexture:e=>wi.getTargetDepthTexture(e._handle)};var Sc;exports.LogLevel=void 0,(Sc=exports.LogLevel||(exports.LogLevel={}))[Sc.Debug=0]="Debug",Sc[Sc.Info=1]="Info",Sc[Sc.Warn=2]="Warn",Sc[Sc.Error=3]="Error";class Pc{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,n);break;case exports.LogLevel.Info:console.log(t,n);break;case exports.LogLevel.Warn:console.warn(t,n);break;case exports.LogLevel.Error:console.error(t,n)}}}class Mc{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Pc)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(exports.LogLevel.Debug,e,t,n)}info(e,t,n){this.log(exports.LogLevel.Info,e,t,n)}warn(e,t,n){this.log(exports.LogLevel.Warn,e,t,n)}error(e,t,n){this.log(exports.LogLevel.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const o={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(o)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Tc=new Mc;const Cc={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},Ec={Running:0,Paused:1,Completed:2,Cancelled:3},Ac={None:0,Restart:1,PingPong:2};const Rc=1.70158,kc=2.70158,Ic=2.5949095;const Fc=2*Math.PI/3,Bc=2*Math.PI/4.5;const Uc=7.5625,Dc=2.75;const Lc=1e-6;function zc(e,t,n){switch(e){case Cc.Linear:return t;case Cc.EaseInQuad:return function(e){return e*e}(t);case Cc.EaseOutQuad:return function(e){return e*(2-e)}(t);case Cc.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Cc.EaseInCubic:return function(e){return e*e*e}(t);case Cc.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Cc.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Cc.EaseInBack:return function(e){return kc*e*e*e-Rc*e*e}(t);case Cc.EaseOutBack:return function(e){const t=e-1;return 1+kc*t*t*t+Rc*t*t}(t);case Cc.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Ic)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Ic)+2)/2}(t);case Cc.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Fc)}(t);case Cc.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Fc)+1}(t);case Cc.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Bc)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Bc)/2+1}(t);case Cc.EaseOutBounce:return function(e){return e<1/Dc?Uc*e*e:e<2/Dc?Uc*(e-=1.5/Dc)*e+.75:e<2.5/Dc?Uc*(e-=2.25/Dc)*e+.9375:Uc*(e-=2.625/Dc)*e+.984375}(t);case Cc.CubicBezier:return n?function(e,t,n,s,o){let i=e;for(let n=0;n<8;n++){const n=1-i,o=3*t*n*n*i+3*s*n*i*i+i*i*i-e;if(Math.abs(o)<Lc)break;const r=3*t*(1-2*i)*(1-i)+6*s*i*(1-i)-3*s*i*i+3*i*i;if(Math.abs(r)<Lc)break;i-=o/r}const r=1-i;return 3*n*r*r*i+3*o*r*i*i+i*i*i}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case Cc.Step:return function(e){return e<1?0:1}(t);default:return t}}const Wc=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,o){const i=this.nextId_++;return this.entries_.set(i,{id:i,from:e,to:t,duration:n,elapsed:0,delay:o?.delay??0,easing:o?.easing??Cc.Linear,bezierPoints:null,state:Ec.Running,loop:o?.loop??Ac.None,loopCount:o?.loopCount??0,loopsRemaining:o?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),i}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===Ec.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Ec.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=zc(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Ac.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Ac.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Ec.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Ec.Running&&(t.state=Ec.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Ec.Paused&&(t.state=Ec.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Ec.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Ec.Cancelled}setBezier(e,t,n,s,o){const i=this.entries_.get(e);i&&(i.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:o})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Hc{constructor(e){this.id=e}get state(){return Wc.getState(this.id)}bezier(e,t,n,s){return Wc.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Hc?Wc.setSequenceNext(this.id,e.id):Wc.setSequenceNextExternal(this.id,e),this}pause(){Wc.pause(this.id)}resume(){Wc.resume(this.id)}cancel(){Wc.cancel(this.id)}}class $c{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof Hc?(Wc.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Oc=null,Vc=null;function Nc(e,t){Oc=e,Vc=t,Wc.init(e,t)}function jc(){Wc.shutdown(),Oc=null,Vc=null}function Xc(){if(!Oc)throw new Error("Tween API not initialized");return Oc}function Yc(){if(!Vc)throw new Error("Tween API not initialized");return Vc}const Gc={to(e,t,n,s,o,i){const r=Xc(),a=Yc(),l=i?.easing??Cc.Linear,c=i?.delay??0,u=i?.loop??Ac.None,d=i?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,o,l,c,u,d);return new $c(r,a,h)},value(e,t,n,s,o){const i=Wc.create(e,t,n,s,o);return new Hc(i)},cancel(e){Xc()._anim_cancelTween(Yc(),e.entity)},cancelAll(e){Xc()._anim_cancelAllTweens(Yc(),e)},update(e){Xc()._anim_updateTweens(Yc(),e),Wc.update(e)}};class qc{constructor(){this.name="AnimationPlugin"}build(e){Nc(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,kt([je(qe)],e=>{ns()&&!ss()||Gc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,kt([je(qe)],e=>{ns()&&!ss()||dn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){jc()}}const Kc=new qc;let Jc=null,Qc=null;function Zc(e,t){Jc=e,Qc=t}function eu(){Jc=null,Qc=null}const tu={update(e){Jc&&Qc&&Jc.particle_update?.(Qc,e)},play(e){Jc&&Qc&&Jc.particle_play?.(Qc,e)},stop(e){Jc&&Qc&&Jc.particle_stop?.(Qc,e)},reset(e){Jc&&Qc&&Jc.particle_reset?.(Qc,e)},getAliveCount:e=>Jc?Jc.particle_getAliveCount?.(e)??0:0};class nu{constructor(){this.name="ParticlePlugin"}build(e){Zc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(exports.Schedule.Update,kt([je(qe)],e=>{tu.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){eu()}}const su=new nu,ou=1073741824,iu={orthogonal:0,isometric:1,staggered:2};class ru{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.animatedLayers_=new Set,this.sourceEntityKeys_=new Map,this.layerState_=new Map}build(e){bn(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.animatedLayers_,o=this.sourceEntityKeys_,i=this.layerState_,r={_id:Symbol("TilemapSyncSystem"),_name:"TilemapSyncSystem",_params:[],_fn:()=>{const r=t.getEntitiesWithComponents([Mn,de]),a=new Set(r);for(const e of n)e>=ou||a.has(e)||(Sn.destroyLayer(e),n.delete(e),i.delete(e));for(const e of r){const s=t.tryGet(e,Mn);if(!s)continue;const o=s.texture;if(!o)continue;const r=mn(o);if(!r)continue;if(!n.has(e)){if(Sn.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),Sn.setOriginEntity(e,e),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];Sn.setTiles(e,t)}n.add(e)}const a=s.tileWidth/r.width,l=s.tileHeight/r.height,c=s.tint,u=s.parallaxFactor,d=i.get(e);(!d||d.texture!==o||d.tilesetColumns!==s.tilesetColumns||d.layer!==s.layer||d.parallaxX!==u.x||d.parallaxY!==u.y||d.tintR!==c.r||d.tintG!==c.g||d.tintB!==c.b||d.tintA!==c.a||d.opacity!==s.opacity||d.visible!==s.visible)&&(Sn.setRenderProps(e,o,s.tilesetColumns,a,l,s.layer,0,u.x,u.y),Sn.setTint(e,c.r,c.g,c.b,c.a,s.opacity),Sn.setVisible(e,s.visible),i.set(e,{texture:o,tilesetColumns:s.tilesetColumns,layer:s.layer,tintR:c.r,tintG:c.g,tintB:c.b,tintA:c.a,opacity:s.opacity,parallaxX:u.x,parallaxY:u.y,visible:s.visible}))}const l=t.getEntitiesWithComponents([Pn,de]);for(const e of l){if(t.tryGet(e,Mn))continue;const i=t.tryGet(e,Pn);if(!i?.source)continue;const r=xn(i.source);if(r&&!o.has(e)){const t=[],i=iu[r.orientation??"orthogonal"]??0;for(let o=0;o<r.layers.length;o++){const a=ou+256*e+o,l=r.layers[o];if(Sn.initLayer(a,l.width,l.height,r.tileWidth,r.tileHeight),Sn.setOriginEntity(a,e),l.tiles.length>0&&Sn.setTiles(a,l.tiles),0!==i&&Sn.setGridType(a,i),r.tileAnimations){for(const[e,t]of r.tileAnimations)Sn.setTileAnimation(a,e,t);r.tileAnimations.size>0&&s.add(a)}if(r.tileProperties)for(const[e,t]of r.tileProperties)for(const[n,s]of t)Sn.setTileProperty(a,e,n,s);const c=r.tilesets[0];if(c){const e=mn(c.textureHandle);e&&(Sn.setRenderProps(a,c.textureHandle,c.columns,r.tileWidth/e.width,r.tileHeight/e.height,o,0,1,1),Sn.setTint(a,1,1,1,1,1),Sn.setVisible(a,!0))}t.push(a),n.add(a)}o.set(e,t)}}const c=new Set(l);for(const[e,t]of o)if(!c.has(e)){for(const e of t)Sn.destroyLayer(e),n.delete(e),s.delete(e),i.delete(e);o.delete(e)}if(s.size>0){const t=1e3*e.getResource(qe).delta;for(const e of s)Sn.advanceAnimations(e,t)}}};e.addSystemToSchedule(exports.Schedule.PreUpdate,r)}cleanup(){for(const e of this.initializedLayers_)Sn.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),this.layerState_.clear(),yn(),vn()}}const au=new ru;function lu(e,t){return e.toFixed(t)}function cu(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class uu{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.lastUpdateTime_=0,this.lastStats_=null,this.accumulatedTimings_=new Map,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 220px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;this.lastStats_=e,this.accumulateTimings_(e.systemTimings);const t=performance.now();this.lastUpdateTime_>0&&t-this.lastUpdateTime_<500||(this.lastUpdateTime_=t,this.render_())}show(){this.visible_=!0,this.lastUpdateTime_=0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}accumulateTimings_(e){for(const[t,n]of e){const e=this.accumulatedTimings_.get(t);e?(e.sum+=n,e.count++,n>e.max&&(e.max=n)):this.accumulatedTimings_.set(t,{sum:n,max:n,count:1})}}render_(){const e=this.lastStats_;if(!e)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${lu(e.fps,1)}</span> Frame: <span style="color:#d19a66">${lu(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),this.accumulatedTimings_.size>0){const e=[];for(const[t,n]of this.accumulatedTimings_){const s=n.sum/n.count;e.push([t,s,n.max])}e.sort((e,t)=>t[2]-e[2]);const n=e.slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t,o]of n){s+=`<div>${cu(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${lu(t,1)} / ${lu(o,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join(""),this.accumulatedTimings_.clear()}}function du(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const hu=Ne(du(),"Stats");const pu="StatsCollect";class fu{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class gu{constructor(e){this.name="Stats",this.collector_=new fu,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(hu,du());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new uu(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=kt([je(qe),{_type:"get_world"}],(s,o)=>{t.pushFrame(s.delta);const i=e.getResource(hu);i.fps=t.getFps(),i.frameTimeMs=t.getFrameTimeMs(),i.entityCount=o.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(pu),i.systemTimings=e}else i.systemTimings=new Map;const a=e.getPhaseTimings();i.phaseTimings=a?new Map(a):new Map;const l=wi.getStats();i.drawCalls=l.drawCalls,i.triangles=l.triangles,i.sprites=l.sprites,i.text=l.text,i.spine=l.spine,i.meshes=l.meshes,i.culled=l.culled,n?.update(i)},{name:pu});e.addSystemToSchedule(exports.Schedule.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const mu=new gu;class yu{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const o=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(o.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return _u(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}function _u(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}function xu(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function wu(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await async function(e,t){try{const n=xu(t),s={instantiateWasm(e,t){const s=new Response(n.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,e).then(e=>t(e.instance,e.module),()=>{WebAssembly.instantiate(n.buffer,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Playable] WASM instantiation fallback failed:",e)})}),{}}};return await e(s)}catch(e){return console.error("[Playable] WASM module init failed:",e),null}}(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}const bu=[zr,Or,ea,fa,Pa,oa,Aa,Ba,Ha,wa,ua,Oa,Xa,Ka,Za,nl,pl],vu=[Kc,As,su,au,hi,Ws];function Su(e,t){const n=new wc(t?.spineProvider),s=[...bu,...vu,n,...t?.plugins??[]];return function(e,t){const n=Di.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),xo(e),jt(e),Do(e),Go(e),_i(e),vi(e);const o=new Mi;n.setPipeline(o);let i=c();const r=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,o,i){i||(i=Oi(e,s,t,o));const r=n.getResource(zt);if(i.length>0){const e=i[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*o),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*o),r.screenW=t,r.screenH=o,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(zt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(s);if(u>=0){const e=s.getCanvas(u).backgroundColor;wi.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-i)/1e3;let h;if(wi.resize(t,l),n.hasResource(Ii)){const e=n.getResource(Ii).getActiveScenes();e.length>0&&(h=new Set(e))}o.setActiveScenes(h??null);const p=Oi(e,s,t,l,n.world,h);if(a(t,l,p),0===p.length)o.render({registry:{_cpp:s},viewProjection:zi,width:t,height:l,elapsed:d});else{o.beginFrame(),o.beginScreenCapture();for(const e of p){const n=e.viewportRect,i=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);o.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d,cameraEntity:e.entity})}o.endScreenCapture(),wi.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(exports.Schedule.First,l),n.addSystemToSchedule(exports.Schedule.Last,d),n.addPlugin(to),n.addPlugin(po),n.addPlugin(Lt),n.addPlugin(Ui),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{...t,plugins:s})}class Pu{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return i(this.resolvePath_(e))}async readBinary(e){const t=await o(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Mu(e){return(t,n)=>(a(e,t).then(e=>{n(e.instance,e.module)}).catch(e=>{console.error("[WeChat] WASM instantiation failed:",e)}),{})}async function Tu(e,t){try{return await e({instantiateWasm:Mu(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}F||(F=!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},o=await f(n,s);return{ok:o.ok,status:o.status,statusText:o.statusText,headers:new Headers(o.headers),json:()=>o.json(),text:()=>o.text(),arrayBuffer:()=>o.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 g(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 o=e.charCodeAt(t);o<128?n[s++]=o:o<2048?(n[s++]=192|o>>6,n[s++]=128|63&o):o>=55296&&o<=56319?(o=e.charCodeAt(++t)-56320+(o-55296<<10)+65536,n[s++]=240|o>>18,n[s++]=128|o>>12&63,n[s++]=128|o>>6&63,n[s++]=128|63&o):(n[s++]=224|o>>12,n[s++]=128|o>>6&63,n[s++]=128|63&o)}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 o=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(o>>10),56320+(1023&o)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=B,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=qc,exports.App=Di,exports.AssetPlugin=eo,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=Qs,exports.Assets=Zs,exports.AsyncCache=sn,exports.Audio=hn,exports.AudioBus=d,exports.AudioListener=Cs,exports.AudioMixer=class{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new d(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new d(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new d(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new d(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new d(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new d(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}},exports.AudioPlugin=Es,exports.AudioPool=class{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}},exports.AudioSource=Ts,exports.BitmapText=be,exports.BodyType=Oe,exports.BoxCollider=ke,exports.Button=qr,exports.ButtonState=Gr,exports.Camera=me,exports.Canvas=ye,exports.CapsuleCollider=Fe,exports.ChainCollider=De,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=we,exports.CircleCollider=Ie,exports.ClearFlags=le,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=St,exports.DARK_THEME=fl,exports.DEFAULT_DESIGN_HEIGHT=D,exports.DEFAULT_DESIGN_WIDTH=U,exports.DEFAULT_FALLBACK_DT=1/60,exports.DEFAULT_FIXED_TIMESTEP=W,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=z,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE=L,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragPlugin=Ea,exports.DragState=Ta,exports.Draggable=Ma,exports.Draw=So,exports.Dropdown=Ja,exports.DropdownPlugin=Qa,exports.EasingType=Cc,exports.EmitterShape=Se,exports.EntityCommands=vt,exports.EntityStateMap=Pr,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=Ct,exports.EventRegistry=Mt,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=Tt,exports.FillDirection=Ji,exports.FillMethod=Zi,exports.FillOrigin=er,exports.FocusManager=la,exports.FocusManagerState=aa,exports.FocusPlugin=$a,exports.Focusable=ra,exports.FrameHistory=class{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}},exports.GLDebug=Pi,exports.Geometry=Wo,exports.GetWorld=At,exports.INVALID_ENTITY=0,exports.INVALID_FONT=N,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=V,exports.Image=tr,exports.ImagePlugin=pa,exports.ImageType=Qi,exports.Input=Ut,exports.InputPlugin=Dt,exports.InputState=Bt,exports.Interactable=sr,exports.LayoutGroupPlugin=tl,exports.ListView=Ya,exports.ListViewPlugin=qa,exports.LocalTransform=he,exports.Logger=Mc,exports.LoopMode=Ac,exports.Material=Gt,exports.MaterialLoader=on,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=Ce,exports.Parent=xe,exports.Particle=tu,exports.ParticleEasing=Me,exports.ParticleEmitter=Te,exports.ParticlePlugin=nu,exports.Physics=lc,exports.PhysicsEvents=Ql,exports.PhysicsPlugin=tc,exports.PolygonCollider=Ue,exports.PostProcess=Jo,exports.PostProcessPlugin=di,exports.PostProcessStack=jo,exports.PostProcessVolume=Ae,exports.PrefabServer=co,exports.Prefabs=uo,exports.PrefabsPlugin=ho,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Ii);t.register({name:bc,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(bc),this.loadPromise_=t.load(bc).then(()=>{}).catch(e=>{console.error("[Preview] Failed to load preview scene:",e)}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new yc(this.baseUrl_);await n.prefetch(t);const o=this.app_.getPlugin(wc),i=o?.spineManager??null;await fc({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineManager:i,sceneName:bc})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([me]);for(const s of n){if(e.get(s,me).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([ye]);for(const o of s){const s=e.get(o,ye);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const o=this.app_.getResource(Ii).getScene(bc),i=o?o.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(i,de,r);const a={isActive:!0,projectionType:ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth};e.insert(i,me,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Ii);await e.switchTo(bc),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=va,exports.ProgressBarDirection=ba,exports.ProgressBarPlugin=Sa,exports.ProjectionType=ae,exports.Query=xt,exports.QueryInstance=wt,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=bt,exports.RenderPipeline=Mi,exports.RenderTexture=vc,exports.Renderer=wi,exports.Res=je,exports.ResMut=Xe,exports.RevoluteJoint=Le,exports.RigidBody=Re,exports.RuntimeConfig=H,exports.SafeArea=Va,exports.SafeAreaPlugin=ja,exports.ScaleMode=ce,exports.SceneManager=Ii,exports.SceneManagerState=ki,exports.SceneOwner=Ee,exports.ScrollView=Ra,exports.ScrollViewPlugin=Fa,exports.SegmentCollider=Be,exports.ShaderSources=nn,exports.ShapeRenderer=ge,exports.ShapeType=ue,exports.SimulationSpace=Pe,exports.Slider=Da,exports.SliderDirection=Ua,exports.SliderPlugin=Wa,exports.SpineAnimation=ve,exports.Sprite=fe,exports.SpriteAnimator=un,exports.Stats=hu,exports.StatsCollector=fu,exports.StatsOverlay=uu,exports.StatsPlugin=gu,exports.Storage=Je,exports.SubmitSkipFlags={None:0,Spine:1,Particles:2},exports.SystemRunner=Ft,exports.Text=Fr,exports.TextAlign=Rr,exports.TextInput=ia,exports.TextInputPlugin=ca,exports.TextOverflow=Ir,exports.TextPlugin=Lr,exports.TextRenderer=Br,exports.TextVerticalAlign=kr,exports.Tilemap=Pn,exports.TilemapAPI=Sn,exports.TilemapLayer=Mn,exports.TilemapPlugin=ru,exports.Time=qe,exports.TimelinePlugin=zs,exports.Toggle=ga,exports.TogglePlugin=xa,exports.Transform=de,exports.Tween=Gc,exports.TweenHandle=$c,exports.TweenState=Ec,exports.TweenTarget={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},exports.UI=kl,exports.UICameraInfo=zt,exports.UIEventQueue=Kr,exports.UIEvents=Jr,exports.UIInteraction=Yr,exports.UIInteractionPlugin=sa,exports.UILayoutGeneration=Qr,exports.UILayoutPlugin=Zr,exports.UIMask=Hr,exports.UIMaskPlugin=$r,exports.UIRect=nr,exports.UIRenderOrderPlugin=hl,exports.UIRenderer=Ci,exports.UIThemeRes=gl,exports.UIVisualType=Ti,exports.Velocity=_e,exports.WeChatAssetProvider=Pu,exports.WebAssetProvider=yc,exports.World=pt,exports.WorldTransform=pe,exports.addStartupSystem=function(e){It().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){It().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){It().push({schedule:e,system:t})},exports.animationPlugin=Kc,exports.applyBuildRuntimeConfig=O,exports.applyDirectionalFill=ar,exports.applyOverrides=io,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=H.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=H.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=H.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=H.canvasMatchWidthOrHeight)},exports.assetPlugin=to,exports.audioPlugin=As,exports.calculateAttenuation=Ps,exports.calculatePanning=Ms,exports.cleanupAllPostProcessVolumes=oi,exports.cleanupPostProcessVolume=si,exports.clearAnimClips=function(){ln.clear()},exports.clearDrawCallbacks=Ro,exports.clearTextureDimensionsCache=yn,exports.clearTilemapSourceCache=function(){fn.clear()},exports.clearTimelineHandles=function(){if(ws)for(const e of xs.values())ws._tl_destroy(e);xs.clear()},exports.clearUserComponents=function(){const e=J();for(const t of e.keys())ne.delete(t);e.clear()},exports.cloneComponentData=so,exports.cloneComponents=no,exports.collectNestedPrefabPaths=function e(t,n,s){const o=[],i=s??new Set;if(t.basePrefab&&!i.has(t.basePrefab)){i.add(t.basePrefab),o.push(t.basePrefab);const s=n(t.basePrefab);s&&o.push(...e(s,n,i))}for(const s of t.entities){if(!s.nestedPrefab)continue;const t=s.nestedPrefab.prefabPath;if(i.has(t))continue;i.add(t),o.push(t);const r=n(t);r&&o.push(...e(r,n,i))}return o},exports.color=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),exports.colorScale=function(e,t){return{r:Math.min(1,e.r*t),g:Math.min(1,e.g*t),b:Math.min(1,e.b*t),a:e.a}},exports.colorWithAlpha=function(e,t){return{r:e.r,g:e.g,b:e.b,a:t}},exports.computeFillAnchors=rr,exports.computeFillSize=function(e,t,n,s){switch(e){case Ji.BottomToTop:case Ji.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}},exports.computeHandleAnchors=function(e,t){switch(e){case Ji.RightToLeft:return{anchorMin:{x:1-t,y:.5},anchorMax:{x:1-t,y:.5}};case Ji.BottomToTop:return{anchorMin:{x:.5,y:t},anchorMax:{x:.5,y:t}};case Ji.TopToBottom:return{anchorMin:{x:.5,y:1-t},anchorMax:{x:.5,y:1-t}};default:return{anchorMin:{x:t,y:.5},anchorMax:{x:t,y:.5}}}},exports.computeUIRectLayout=function(e,t,n,s,o,i,r={x:.5,y:.5}){const a=i.right-i.left,l=i.top-i.bottom,c=i.left+e.x*a,u=i.left+t.x*a,d=i.bottom+e.y*l,h=i.bottom+t.y*l;let p,f,g,m;e.x===t.x?(p=c+n.x-o.x*r.x,g=p+o.x):(p=c+n.x,g=u+s.x),e.y===t.y?(f=d+n.y-o.y*r.y,m=f+o.y):(f=d+n.y,m=h+s.y);const y=Math.max(0,g-p),_=Math.max(0,m-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:g,top:m}}},exports.createRuntimeSceneConfig=gc,exports.createWebApp=Su,exports.debug=function(e,t,n){Tc.debug(e,t,n)},exports.defaultFrameStats=du,exports.defineComponent=Q,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Ne,exports.defineSystem=kt,exports.defineTag=function(e){const t=ne.get(e)??J().get(e);if(t)return t;const n=K(e,{});return J().set(e,n),ne.set(e,n),ee(e,{},!0),n},exports.dragPlugin=Aa,exports.dropdownPlugin=Za,exports.error=function(e,t,n){Tc.error(e,t,n)},exports.extractAnimClipTexturePaths=rn,exports.findEntityByName=function(e,t){const n=e.getEntitiesWithComponents([Ce]);for(const s of n){const n=e.get(s,Ce);if(n&&n.value===t)return s}return null},exports.flattenPrefab=ro,exports.flushPendingSystems=Li,exports.focusPlugin=Oa,exports.getAddressableType=function(e){return b(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of m)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return x},exports.getAllEffectDefs=function(){return Array.from(Qo.values())},exports.getAnimClip=function(e){return ln.get(e)},exports.getAssetBuildTransform=function(e){return b(e)?.buildTransform},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=b,exports.getComponent=oe,exports.getComponentAssetFieldDescriptors=Os,exports.getComponentAssetFields=$s,exports.getComponentDefaults=function(e){const t=oe(e);return t?G(t._default):null},exports.getComponentEntityFields=Y,exports.getComponentSpineFieldDescriptor=Vs,exports.getCustomExtensions=S,exports.getEditorType=function(e){return b(e)?.editorType??"unknown"},exports.getEffectDef=ei,exports.getEffectTypes=function(){return Array.from(Qo.keys())},exports.getLogger=function(){return Tc},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getTextureDimensions=mn,exports.getTilemapSource=xn,exports.getTimelineHandle=function(e){return xs.get(e)},exports.getUserComponent=Z,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=fa,exports.info=function(e,t,n){Tc.info(e,t,n)},exports.initDrawAPI=xo,exports.initGLDebugAPI=vi,exports.initGeometryAPI=Do,exports.initMaterialAPI=jt,exports.initParticleAPI=Zc,exports.initPlayableRuntime=async function(e){const{app:t,module:n,assets:s,scenes:o,firstScene:i}=e,r=t.getResource(Zs);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));let a=null;if(e.spineModules&&Object.keys(e.spineModules).length>0){a=function(e,t){const n=new Map;for(const[e,s]of Object.entries(t)){const t=e;n.set(t,async()=>{const e=xu(s.wasmBase64);return s.factory({instantiateWasm(t,n){const s=new Response(e.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,t).then(e=>n(e.instance,e.module),()=>{WebAssembly.instantiate(e.buffer,t).then(e=>n(e.instance,e.module)).catch(e=>{console.error("[Playable] Spine WASM instantiation fallback failed:",e)})}),{}}})})}return new Bl(e,n)}(n,e.spineModules);const s=t.getPlugin(wc);s&&s.setSpineManager(a)}const l=e.physicsWasmBase64?await wu(e.physicsWasmBase64):null,c=new yu(s);hn.setAssetResolver(e=>{const t=s[e];return t?_u(t).buffer:null}),await mc({app:t,module:n,provider:c,scenes:o,firstScene:i,spineManager:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=Go,exports.initRendererAPI=_i,exports.initRuntime=mc,exports.initTilemapAPI=bn,exports.initTweenAPI=Nc,exports.initUIBuilder=function(e){e.hasResource(gl)&&(ml=e.getResource(gl))},exports.initWeChatRuntime=async function(e){const t=await i("asset-manifest.json"),n=JSON.parse(t),s=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=M(e),o=t[e]||t[s]||n[s]||n[e];return o?o.path:s}}(function(e){const t={},n={};for(const s in e.groups){const o=e.groups[s];for(const e in o.assets){const s=o.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n)),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:Mu("esengine.wasm")}),l=o.getContext("webgl2")||o.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=Su(a,{glContextHandle:c,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&O(u,e.runtimeConfig);let d=null;if(e.spineFactories&&Object.keys(e.spineFactories).length>0){const t=new Map;for(const[n,s]of Object.entries(e.spineFactories)){const e=n,o=`spine_${n.replace(".","")}.wasm`;t.set(e,()=>Tu(s,o))}d=new Bl(a,t)}let h=null;e.physicsFactory&&(h=await Tu(e.physicsFactory,"physics.wasm"));const p=new Pu(s),f=[];for(const t of e.sceneNames){const e=await i(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await mc({app:u,module:a,provider:p,scenes:f,firstScene:e.firstScene,spineManager:d,physicsModule:h,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),u.run()},exports.inputPlugin=Lt,exports.instantiatePrefab=lo,exports.intersectRects=function(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),o=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,o-n),h:Math.max(0,i-s)}},exports.invertMatrix4=Vr,exports.isBuiltinComponent=te,exports.isCustomExtension=P,exports.isEditor=ns,exports.isKnownAssetExtension=v,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=ss,exports.isRuntime=function(){return!es},exports.isTextureRef=Ht,exports.isWeChat=n,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=nl,exports.listViewPlugin=Ka,exports.loadComponent=Ks,exports.loadPhysicsModule=Dl,exports.loadRuntimeScene=fc,exports.loadSceneData=Ys,exports.loadSceneWithAssets=Gs,exports.loadTiledMap=function(e,t,n,s={}){const o=[],i=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,de,{});const l=i?n.get(i.image)??0:0,c=i?.columns??1;e.insert(a,Mn,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),o.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const o=[],i=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(i-l)-.5*t.height,d=-t.rotation*kn;if(e.insert(r,de,{position:{x:c,y:u,z:0}}),e.insert(r,Re,{bodyType:Oe.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,Ie,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,o=-1/0,i=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>o&&(o=r),a<s&&(s=a),a>i&&(i=a)}const a=o-n,l=i-s,c=.5*(n+o),u=.5*(s+i);e.insert(r,ke,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,ke,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,de,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}o.push(r)}return o}(e,t,0,0);o.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=In(e,n,t,a,0,0);o.push(...s)}return o},exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&v(w(e)))},exports.makeInteractable=function(e,t){xr(e,t,sr,{enabled:!0,blockRaycast:!0,raycastTarget:!0})},exports.parseAnimClipData=an,exports.parseTiledMap=async function(e,t){const n=wn;if(!n)return null;const s=new TextEncoder,o=s.encode(e),i=n._malloc(o.byteLength);n.HEAPU8.set(o,i);const r=n.tiled_loadMap(i,o.byteLength);if(n._free(i),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let o=0;o<e;o++){const e=n.tiled_getExternalTilesetSource(r,o);if(!t)return n.tiled_freeMap(r),null;const i=await t(e),a=s.encode(i),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,o,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const o={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),orientation:"orthogonal",layers:[],tilesets:[],objectGroups:[],collisionTileIds:[],tileAnimations:new Map,tileProperties:new Map},i=n.tiled_getLayerCount(r);for(let e=0;e<i;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),i=t*s,a=2*i,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,i);const c=new Uint16Array(i);c.set(new Uint16Array(n.HEAPU8.buffer,l,i)),n._free(l),o.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?Tn(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)o.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),o}catch(e){return console.warn("[Tiled] Failed to parse tilemap",e),n.tiled_freeMap(r),null}},exports.parseTimelineAsset=Zn,exports.parseTmjJson=An,exports.particlePlugin=su,exports.platformFetch=s,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=o,exports.platformReadTextFile=i,exports.pointInOBB=function(e,t,n,s,o,i,r,a,l,c){if(0===l&&1===c)return jr(e,t,n,s,o,i,r,a);const u=Xr(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-n,f=t-s,g=p*h-f*d+n,m=p*d+f*h+s;return g>=n-o*r&&g<=n+o*(1-r)&&m>=s-i*a&&m<=s+i*(1-a)},exports.pointInWorldRect=jr,exports.postProcessPlugin=hi,exports.prefabsPlugin=po,exports.preloadNestedPrefabs=ao,exports.progressBarPlugin=Pa,exports.quat=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s}),exports.registerAnimClip=cn,exports.registerAssetBuildTransform=function(e,t){for(const n of m)n.editorType===e&&(n.buildTransform=t)},exports.registerComponent=se,exports.registerComponentAssetFields=function(e,t){Hs.set(e,t)},exports.registerComponentEntityFields=X,exports.registerDrawCallback=Eo,exports.registerEmbeddedAssets=function(e,t){const n=e.getResource(Zs);n&&n.registerEmbeddedAssets(t)},exports.registerMaterialCallback=tn,exports.registerTextureDimensions=gn,exports.registerTilemapSource=_n,exports.registerTimelineAsset=Is,exports.remapComponentEntityRefs=oo,exports.remapEntityFields=Ns,exports.resolveRelativePath=Rn,exports.safeAreaPlugin=Xa,exports.sceneManagerPlugin=Ui,exports.screenToWorld=Nr,exports.scrollViewPlugin=Ba,exports.setEditorMode=function(e){es=e},exports.setEntityColor=vr,exports.setEntityEnabled=Sr,exports.setListViewRenderer=function(e,t){if(!Ga)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Ga.get(e);n?n.renderer=t:Ga.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Tc.setMinLevel(e)},exports.setPlayMode=function(e){ts=e},exports.setWasmErrorHandler=nt,exports.shutdownDrawAPI=wo,exports.shutdownGLDebugAPI=Si,exports.shutdownGeometryAPI=Lo,exports.shutdownMaterialAPI=Xt,exports.shutdownParticleAPI=eu,exports.shutdownPostProcessAPI=qo,exports.shutdownRendererAPI=xi,exports.shutdownTilemapAPI=vn,exports.shutdownTweenAPI=jc,exports.sliderPlugin=Ha,exports.spriteAnimatorSystemUpdate=dn,exports.statsPlugin=mu,exports.syncFillSpriteSize=function(e,t,n,s,o,i){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(n){case Ji.BottomToTop:case Ji.TopToBottom:a=o,l=i*s;break;default:a=o*s,l=i}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,fe,r))},exports.syncPostProcessVolume=function(e,t){let n=ti.get(e),s=ni.get(e);const o=t.effects.filter(e=>e.enabled);if(0!==o.length){for(n||(n=Jo.createStack(),ti.set(e,n)),s||(s=new Map,ni.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of o){const t=ei(e.type);if(!t)continue;let o=s.get(e.type);void 0===o&&(o=t.factory(),s.set(e.type,o)),n.addPass(e.type,o);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}Jo.bind(e,n)}else if(n&&(Jo.unbind(e),n.destroy(),ti.delete(e)),s){for(const e of s.values())Gt.releaseShader(e);ni.delete(e)}},exports.textInputPlugin=ua,exports.textPlugin=zr,exports.tilemapPlugin=au,exports.timelinePlugin=Ws,exports.toBuildPath=M,exports.togglePlugin=wa,exports.transitionTo=async function(e,t,n){const s=e.getResource(Ii);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})},exports.uiInteractionPlugin=oa,exports.uiLayoutPlugin=ea,exports.uiMaskPlugin=Or,exports.uiPlugins=bu,exports.uiRenderOrderPlugin=pl,exports.unregisterAnimClip=function(e){ln.delete(e)},exports.unregisterComponent=function(e){J().delete(e),ne.delete(e)},exports.unregisterDrawCallback=Ao,exports.updateCameraAspectRatio=Js,exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),exports.vec4=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),exports.warn=function(e,t,n){Tc.warn(e,t,n)},exports.withChildEntity=wr,exports.wrapSceneSystem=Fi,exports.wxFileExists=function(e){return new Promise(t=>{C().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=A,exports.wxGetImagePixels=k,exports.wxLoadImage=R,exports.wxLoadImagePixels=I,exports.wxReadFile=function(e){return new Promise((t,n)=>{C().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(E(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((n,s)=>{C().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(E(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((n,s)=>{C().writeFile({filePath:e,data:t,success:()=>n(),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}function n(){return"wechat"===e?.name}async function s(e,n){return t().fetch(e,n)}async function o(e){return t().readFile(e)}async function i(e){return t().readTextFile(e)}async function r(e){return t().fileExists(e)}async function a(e,n){return t().instantiateWasm(e,n)}function l(e,n){return t().createCanvas(e,n)}function c(){return t().now()}function u(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class d{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof d?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class h{constructor(e,t,n){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class p{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.obeyMuteSwitch=!1;const o=++this.nextId_;this.contexts_.set(o,s);const i=new h(o,s,this.contexts_);return s.onEnded(()=>{i.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(o))}),s.onError(e=>{console.error(`[WeChatAudio] Playback error for "${n}":`,e.errMsg)}),s.src=n,s.play(),i}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function f(e,t){return new Promise((n,s)=>{const o=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===o?"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 g(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}`)}}const m=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["estimeline"],contentType:"json",editorType:"timeline",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",estimeline:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,x=new Set;for(const e of m)for(const t of e.extensions)_.set(t,e),x.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function b(e){return _.get(w(e))}function v(e){return x.has(e.toLowerCase())}function S(){const e=[];for(const t of m)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function P(e){const t=b(e);return t?.wechatPackInclude??!1}function M(e){const t=b(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}let T=null;function C(){return T||(T=wx.getFileSystemManager()),T}function E(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(P(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function A(e){const t=C();try{return t.accessSync(e),!0}catch{return!1}}function R(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 k(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const o=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(o.data.buffer)}}async function I(e){return k(await R(e))}let F=!1;const B=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return f(e,t)}async readFile(e){return function(e){return C().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return C().readFileSync(e,t)}(M(e))}async fileExists(e){return A(M(e))}async loadImagePixels(e){return I(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return g(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),o="function"==typeof wx.onKeyDown;o&&(wx.onKeyDown(n),wx.onKeyUp(s));const i=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(i),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{o&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(i),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new p}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch(e){console.warn("[WeChat] setStorageSync failed:",e)}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch(e){console.warn("[WeChat] removeStorageSync failed:",e)}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const n of t)n.startsWith(e)&&wx.removeStorageSync(n)}catch(e){console.warn("[WeChat] clearStorage failed:",e)}}},U=1920,D=1080,L={x:100,y:100},z={x:0,y:-9.81},W=1/60,H={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};const $={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function O(e,t){if(void 0!==t.maxDeltaTime&&(H.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(H.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(H.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(H.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(H.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");H.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(H.canvasScaleMode=$[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(H.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(H.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(H.assetFailureCooldown=t.assetFailureCooldown)}const V=4294967295,N=4294967295,j=new Map;function X(e,t){j.set(e,t)}function Y(e){return j.get(e)}function G(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(G);const t={};for(const n in e)t[n]=G(e[n]);return t}let q=0;function K(e,t){const n=++q,s=function(e){const t=[],n=[],s=[];let o=!1;for(const i in e){const r=e[i];null!==r&&"object"==typeof r?(o=!0,Array.isArray(r)?s.push(i):n.push(i)):t.push(i)}return o?{flatKeys:t,objectKeys:n,arrayKeys:s}:null}(t),o=t;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create(e){if(s){const t={...o};for(const e of s.objectKeys)t[e]={...o[e]};for(const e of s.arrayKeys)t[e]=o[e].slice();return e&&Object.assign(t,e),t}return e?{...t,...e}:{...t}}}}function J(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Q(e,t,n){const s=ne.get(e)??J().get(e);if(s)return s;const o=K(e,t);return J().set(e,o),ne.set(e,o),ee(e,t,!1),n?.entityFields&&X(e,n.entityFields),o}function Z(e){return J().get(e)}function ee(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function te(e){return!0===e._builtin}const ne=new Map;function se(e,t){ne.set(e,t)}function oe(e){return ne.get(e)??Z(e)}function ie(e){if(null===e||"object"!=typeof e)return[];const t=[];for(const n of Object.keys(e)){const s=e[n];if(null!==s&&"object"==typeof s&&!Array.isArray(s)){"r"in s&&"g"in s&&"b"in s&&"a"in s&&t.push(n)}}return t}function re(e,t,n){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t,_colorKeys:ie(t)};return ne.set(e,s),s}const ae={Perspective:0,Orthographic:1},le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ce={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ue={Circle:0,Capsule:1,RoundedRect:2},de=re("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),he=de,pe=de,fe=re("Sprite",{texture:V,color:{r:1,g:1,b:1,a:1},size:{x:L.x,y:L.y},pivot:{x:.5,y:.5},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),ge=re("ShapeRenderer",{shapeType:ue.Circle,color:{r:1,g:1,b:1,a:1},size:{x:100,y:100},cornerRadius:0,layer:0,enabled:!0}),me=re("Camera",{projectionType:ae.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth}),ye=re("Canvas",{designResolution:{x:U,y:D},pixelsPerUnit:100,scaleMode:ce.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),_e=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),xe=re("Parent",{entity:0}),we=re("Children",{entities:[]}),be=re("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:N,enabled:!0}),ve=re("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,enabled:!0}),Se={Point:0,Circle:1,Rectangle:2,Cone:3},Pe={World:0,Local:1},Me={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},Te=re("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:Se.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:Me.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:Me.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:V,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:Pe.World,enabled:!0}),Ce=Q("Name",{value:""}),Ee=Q("SceneOwner",{scene:"",persistent:!1}),Ae=Q("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});const Re=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ke=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},radius:.05,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ie=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Fe=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Be=re("SegmentCollider",{point1:{x:-.5,y:0},point2:{x:.5,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ue=Q("PolygonCollider",{vertices:[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}],radius:0,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),De=Q("ChainCollider",{points:[{x:-1,y:0},{x:0,y:.5},{x:1,y:0},{x:0,y:-.5}],isLoop:!0,friction:.6,restitution:0,categoryBits:1,maskBits:65535,enabled:!0}),Le=Q("RevoluteJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},enableMotor:!1,motorSpeed:0,maxMotorTorque:0,enableLimit:!1,lowerAngle:0,upperAngle:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),ze=Q("DistanceJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},length:1,enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,minLength:.5,maxLength:2,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),We=Q("PrismaticJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:1,y:0},enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),He=Q("WeldJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},linearHertz:0,angularHertz:0,linearDampingRatio:1,angularDampingRatio:1,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),$e=Q("WheelJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:0,y:1},enableSpring:!0,hertz:5,dampingRatio:.7,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorTorque:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Oe={Static:0,Kinematic:1,Dynamic:2};let Ve=0;function Ne(e,t){const n=++Ve;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function je(e){return{_type:"res",_resource:e}}function Xe(e){return{_type:"res_mut",_resource:e}}class Ye{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_)}updateValue(e){this.value_=e}}class Ge{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Ye(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const qe=Ne({delta:0,elapsed:0,frameCount:0},"Time"),Ke="esengine:",Je={getString(e,n){const s=t().getStorageItem(Ke+e);return null!==s?s:n},setString(e,n){t().setStorageItem(Ke+e,n)},getNumber(e,n){const s=t().getStorageItem(Ke+e);if(null===s)return n;const o=Number(s);return Number.isNaN(o)?n:o},setNumber(e,n){t().setStorageItem(Ke+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(Ke+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(Ke+e,String(n))},getJSON(e,n){const s=t().getStorageItem(Ke+e);if(null===s)return n;try{return JSON.parse(s)}catch(t){return console.warn(`[Storage] Failed to parse JSON for key "${e}"`,t),n}},setJSON(e,n){t().setStorageItem(Ke+e,JSON.stringify(n))},remove(e){t().removeStorageItem(Ke+e)},has:e=>null!==t().getStorageItem(Ke+e),clear(){t().clearStorage(Ke)}};function Qe(e,t,n){const s=[];for(const[e,o]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:o});continue}const n=Ze(t[e]),i=Ze(o);"null"!==n&&"undefined"!==n&&(n!==i&&null!=o&&s.push({field:e,expected:n,actual:i,value:o}))}return s}function Ze(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function et(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let tt=null;function nt(e){tt=e}function st(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),tt&&tt(e,t)}function ot(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={r:t.x,g:t.y,b:t.z,a:t.w})}return n}function it(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={x:t.r,y:t.g,z:t.b,w:t.a})}return n}const rt={Transform:{ptrFn:"getTransformPtr",fields:[{name:"position",type:"vec3",offset:0},{name:"rotation",type:"quat",offset:12},{name:"scale",type:"vec3",offset:28},{name:"worldPosition",type:"vec3",offset:40},{name:"worldRotation",type:"quat",offset:52},{name:"worldScale",type:"vec3",offset:68}]},Sprite:{ptrFn:"getSpritePtr",fields:[{name:"texture",type:"u32",offset:0},{name:"color",type:"color",offset:4},{name:"size",type:"vec2",offset:20},{name:"uvOffset",type:"vec2",offset:28},{name:"uvScale",type:"vec2",offset:36},{name:"layer",type:"i32",offset:44},{name:"flipX",type:"bool",offset:48},{name:"flipY",type:"bool",offset:49},{name:"material",type:"u32",offset:52},{name:"enabled",type:"bool",offset:56}]},Velocity:{ptrFn:"getVelocityPtr",fields:[{name:"linear",type:"vec3",offset:0},{name:"angular",type:"vec3",offset:12}]},Camera:{ptrFn:"getCameraPtr",fields:[{name:"projectionType",type:"u8",offset:0},{name:"fov",type:"f32",offset:4},{name:"orthoSize",type:"f32",offset:8},{name:"nearPlane",type:"f32",offset:12},{name:"farPlane",type:"f32",offset:16},{name:"aspectRatio",type:"f32",offset:20},{name:"isActive",type:"bool",offset:24},{name:"priority",type:"i32",offset:28},{name:"viewportX",type:"f32",offset:32},{name:"viewportY",type:"f32",offset:36},{name:"viewportW",type:"f32",offset:40},{name:"viewportH",type:"f32",offset:44},{name:"clearFlags",type:"i32",offset:48}]},UIRect:{ptrFn:"getUIRectPtr",fields:[{name:"anchorMin",type:"vec2",offset:0},{name:"anchorMax",type:"vec2",offset:8},{name:"offsetMin",type:"vec2",offset:16},{name:"offsetMax",type:"vec2",offset:24},{name:"size",type:"vec2",offset:32},{name:"pivot",type:"vec2",offset:40}]},RigidBody:{ptrFn:"getRigidBodyPtr",fields:[{name:"bodyType",type:"u8",offset:0},{name:"gravityScale",type:"f32",offset:4},{name:"linearDamping",type:"f32",offset:8},{name:"angularDamping",type:"f32",offset:12},{name:"fixedRotation",type:"bool",offset:16},{name:"bullet",type:"bool",offset:17},{name:"enabled",type:"bool",offset:18}]},BoxCollider:{ptrFn:"getBoxColliderPtr",fields:[{name:"halfExtents",type:"vec2",offset:0},{name:"offset",type:"vec2",offset:8},{name:"density",type:"f32",offset:16},{name:"friction",type:"f32",offset:20},{name:"restitution",type:"f32",offset:24},{name:"isSensor",type:"bool",offset:28},{name:"enabled",type:"bool",offset:29},{name:"categoryBits",type:"u32",offset:32},{name:"maskBits",type:"u32",offset:36}]},CircleCollider:{ptrFn:"getCircleColliderPtr",fields:[{name:"radius",type:"f32",offset:0},{name:"offset",type:"vec2",offset:4},{name:"density",type:"f32",offset:12},{name:"friction",type:"f32",offset:16},{name:"restitution",type:"f32",offset:20},{name:"isSensor",type:"bool",offset:24},{name:"enabled",type:"bool",offset:25},{name:"categoryBits",type:"u32",offset:28},{name:"maskBits",type:"u32",offset:32}]}};function at(e,t,n,s,o,i){const r=s+o.offset,a=r>>2;switch(o.type){case"f32":e[a]=i;break;case"i32":t[a]=0|i;break;case"u32":t[a]=i;break;case"bool":n[r]=i?1:0;break;case"u8":n[r]=i;break;case"vec2":e[a]=i.x,e[a+1]=i.y;break;case"vec3":e[a]=i.x,e[a+1]=i.y,e[a+2]=i.z;break;case"quat":e[a]=i.x,e[a+1]=i.y,e[a+2]=i.z,e[a+3]=i.w;break;case"color":e[a]=i.r,e[a+1]=i.g,e[a+2]=i.b,e[a+3]=i.a}}let lt=1;const ct=new WeakMap;function ut(e){let t=ct.get(e);return void 0===t&&(t=lt++,ct.set(e,t)),t}const dt=[];function ht(e,t=[],n=[]){dt.length=0;for(const t of e)dt.push(ut(t));dt.sort((e,t)=>e-t);let s=dt.join(",");if(t.length>0){dt.length=0;for(const e of t)dt.push(ut(e));dt.sort((e,t)=>e-t),s+="|+"+dt.join(",")}if(n.length>0){dt.length=0;for(const e of n)dt.push(ut(e));dt.sort((e,t)=>e-t),s+="|-"+dt.join(",")}return s}class pt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.builtinEntitySets_=new Map,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map,this.trackedComponents_=new Set}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}getWasmModule(){return this.module_}spawn(e){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let t;if(this.cppRegistry_)try{t=this.cppRegistry_.create()}catch(e){throw st(e,"spawn"),e}else t=++this.nextEntityId_;let n=0;if(this.module_&&this.cppRegistry_)try{n=this.module_.registry_getGeneration(this.cppRegistry_,t)}catch{}else n=++this.nextGeneration_;this.entities_.set(t,n),this.worldVersion_++,void 0!==e&&this.insert(t,Ce,{value:e});for(const e of this.spawnCallbacks_)try{e(t)}catch(e){console.warn("[World] Spawn callback error:",e)}return t}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch(e){console.warn("[World] Despawn callback error:",e)}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){st(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;for(const[,t]of this.builtinEntitySets_)t.delete(e);const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){st(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){st(t,`removeParent(entity=${e})`)}}insert(e,t,n){return te(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(te(t)){if(this.cppRegistry_)try{const s=t._default,o=n;let i=o;for(const e of Object.keys(o))e in s||(i===o&&(i={...o}),delete i[e]);this.getBuiltinMethods(t._cppName).add(e,it(i,t._colorKeys))}catch(n){st(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return te(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){if(t._builtin){if(!this.cppRegistry_)return!1;const n=t._cppName,s=this.builtinEntitySets_.get(n);return s?s.has(e):this.getBuiltinMethods(n).has(e)}return this.hasScript(e,t)}tryGet(e,t){if(te(t)){if(!this.cppRegistry_)return null;const n=this.builtinEntitySets_.get(t._cppName);if(n&&!n.has(e))return null;try{const s=this.getBuiltinMethods(t._cppName);return n||s.has(e)?ot(s.get(e),t._colorKeys):null}catch(n){return st(n,`tryGet(${t._name}, entity=${e})`),null}}const n=this.tsStorage_.get(t._id);if(!n)return null;const s=n.get(e);return void 0!==s?s:null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");te(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],o=n[`get${e}`],i=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof o||"function"!=typeof i||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:o.bind(n),has:i.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,o={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(o[e]=t);const e=Qe(t._name,s,o);if(e.length>0)throw new Error(et(t._name,e))}const i={...t._default,...o};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,it(i,t._colorKeys))}catch(n){st(n,`insertBuiltin(${t._name}, entity=${e})`)}let a=this.builtinEntitySets_.get(t._cppName);a||(a=new Set,this.builtinEntitySets_.set(t._cppName,a));const l=a.has(e);return!r&&l||(l||a.add(e),this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return ot(this.getBuiltinMethods(t._cppName).get(e),t._colorKeys)}catch(n){return st(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return st(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){st(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++,this.builtinEntitySets_.get(t._cppName)?.delete(e)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const o=Qe(t._name,t._default,e);if(o.length>0)throw new Error(et(t._name,o));s=e}const o=t.create(s),i=this.getStorage(t),r=!i.has(e);i.set(e,o);let a=this.entityComponents_.get(e);return a||(a=new Set,this.entityComponents_.set(e,a)),a.add(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);s&&s.delete(t._id)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resolveGetter(e){if(te(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrGetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?e=>t.get(e):e=>ot(t.get(e),n)}const t=this.tsStorage_.get(e._id);return t?e=>t.get(e):null}resolveHas(e){if(te(e)){if(!this.cppRegistry_)return null;const t=this.getBuiltinMethods(e._cppName);return e=>t.has(e)}const t=this.tsStorage_.get(e._id);return t?e=>t.has(e):null}resolveSetter(e){if(te(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrSetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?(e,n)=>t.add(e,n):(e,s)=>t.add(e,it(s,n))}const t=this.tsStorage_.get(e._id);return t?(e,n)=>t.set(e,n):null}resolvePtrFn_(e){const t=rt[e];if(!t)return null;const n=this.module_[t.ptrFn];if(!n)return null;const s=this.cppRegistry_;return e=>n(s,e)}resolvePtrSetter_(e){const t=rt[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,o=t.fields;return(e,t)=>{const i=n(e);if(!i)return;const r=t;for(let e=0;e<o.length;e++)at(s.HEAPF32,s.HEAPU32,s.HEAPU8,i,o[e],r[o[e].name])}}resolvePtrGetter_(e){const t=rt[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,o=t.fields,i=function(e){const t={};for(const n of e)switch(n.type){case"vec2":t[n.name]={x:0,y:0};break;case"vec3":t[n.name]={x:0,y:0,z:0};break;case"quat":t[n.name]={x:0,y:0,z:0,w:0};break;case"color":t[n.name]={r:0,g:0,b:0,a:0};break;default:t[n.name]=null}return t}(o);return e=>{const t=n(e);return t?(function(e,t,n,s,o,i){for(let r=0;r<o.length;r++){const a=o[r],l=s+a.offset,c=l>>2;switch(a.type){case"f32":i[a.name]=e[c];break;case"i32":i[a.name]=0|t[c];break;case"u32":i[a.name]=t[c];break;case"bool":i[a.name]=0!==n[l];break;case"u8":i[a.name]=n[l];break;case"vec2":{const t=i[a.name];t.x=e[c],t.y=e[c+1];break}case"vec3":{const t=i[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2];break}case"quat":{const t=i[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2],t.w=e[c+3];break}case"color":{const t=i[a.name];t.r=e[c],t.g=e[c+1],t.b=e[c+2],t.a=e[c+3];break}}}}(s.HEAPF32,s.HEAPU32,s.HEAPU8,t,o,i),i):null}}resetQueryPool(){}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch(e){console.warn(`[World] Component check failed for ${n}:`,e)}if(this.cppRegistry_)for(const[n,s]of ne)if(te(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch(e){console.warn(`[World] Builtin check failed for ${n}:`,e)}const n=this.entityComponents_.get(e);if(n){const e=J();for(const s of n)for(const[n,o]of e)if(o._id===s){t.add(n);break}}return Array.from(t)}resolveStorages_(e,t,n){for(const s of e)if(te(s)){if(!this.cppRegistry_)return!1;n.push(this.getBuiltinMethods(s._cppName))}else{const e=this.tsStorage_.get(s._id);if(!e)return!1;t.push(e)}return!0}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const o=s??ht(e,t,n),i=this.queryCache_.get(o);if(i&&i.version===this.worldVersion_)return i.result;const r=[],a=[],l=[];if(!this.resolveStorages_(e,a,l))return this.queryCache_.set(o,{version:this.worldVersion_,result:[]}),r;let c=null,u=null;if(t.length>0&&(c=[],u=[],!this.resolveStorages_(t,c,u)))return this.queryCache_.set(o,{version:this.worldVersion_,result:[]}),r;let d=null,h=null;n.length>0&&(d=[],h=[],this.resolveStorages_(n,d,h));let p=null,f=1/0;for(let e=0;e<a.length;e++){const t=a[e].size;t<f&&(f=t,p=a[e])}for(const t of e)if(te(t)){const e=this.builtinEntitySets_.get(t._cppName);e&&e.size<f&&(f=e.size,p=e)}const g=p?p.keys():this.entities_.keys(),m=a.length,y=l.length;for(const e of g){let t=!0;for(let n=0;n<m;n++)if(!a[n].has(e)){t=!1;break}if(t)for(let n=0;n<y;n++)if(!l[n].has(e)){t=!1;break}if(t&&c){for(let n=0;n<c.length;n++)if(!c[n].has(e)){t=!1;break}if(t)for(let n=0;n<u.length;n++)if(!u[n].has(e)){t=!1;break}}if(t&&d){for(let n=0;n<d.length;n++)if(d[n].has(e)){t=!1;break}if(t)for(let n=0;n<h.length;n++)if(h[n].has(e)){t=!1;break}}t&&r.push(e)}return this.queryCache_.set(o,{version:this.worldVersion_,result:r}),r}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}enableChangeTracking(e){this.trackedComponents_.add(e._id)}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const o=s.get(e);return void 0!==o&&o>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const o=s.get(e);return void 0!==o&&o>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}markChanged(e,t){this.recordChangedTick_(t,e)}recordChangedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function ft(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function gt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function mt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function yt(e){return ft(e)||gt(e)||mt(e)?e._component:e}function _t(e,t=[],n=[]){const s=[],o=[],i=[];return e.forEach((e,t)=>{ft(e)&&s.push(t),gt(e)?o.push({index:t,component:e._component}):mt(e)&&i.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:o,_changedFilters:i,with:(...s)=>_t(e,[...t,...s],n),without:(...s)=>_t(e,t,[...n,...s])}}function xt(...e){return _t(e)}class wt{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(yt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=ht(this.allRequired_,t._with,t._without),this.getters_=this.actualComponents_.map(t=>e.resolveGetter(t)),this.mutSetters_=t._mutIndices.map(t=>e.resolveSetter(this.actualComponents_[t])),this.mutIsBuiltin_=t._mutIndices.map(e=>te(this.actualComponents_[e]));for(const n of t._addedFilters)e.enableChangeTracking(n.component);for(const n of t._changedFilters)e.enableChangeTracking(n.component)}resetTick(e){this.lastRunTick_=e}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,o=e.length>0,i=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,d=this.getters_,h=this;let p=0,f=null,g=!1,m=!1;const y=this.mutIsBuiltin_,_=()=>{for(let e=0;e<l;e++){const t=a[e];if(y[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}},x=()=>{m||(m=!0,u.endIteration(),null!==f&&o&&_())},w={value:r,done:!1},b={value:void 0,done:!0};return{next(){for(g||(g=!0,u.beginIteration());p<n.length;){const c=n[p++];if(!i||h.passesChangeFilters_(c)){null!==f&&o&&_(),r[0]=c;for(let e=0;e<s;e++){const n=d[e];r[e+1]=n?n(c):u.get(c,t[e])}if(o){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];f=c}return w}}return x(),b},return:()=>(x(),b)}}forEach(e){const{_mutIndices:t}=this.descriptor_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=this.actualComponents_.length,o=t.length>0,i=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,d=this.getters_,h=this.actualComponents_;u.beginIteration();let p=null;for(let f=0;f<n.length;f++){const g=n[f];if(!i||this.passesChangeFilters_(g)){if(null!==p&&o)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(p,t.data):u.set(p,t.component,t.data)}else u.markChanged(p,t.component)}r[0]=g;for(let e=0;e<s;e++){const t=d[e];r[e+1]=t?t(g):u.get(g,h[e])}if(o){for(let e=0;e<l;e++)a[e].data=r[t[e]+1];p=g}switch(s){case 1:e(g,r[1]);break;case 2:e(g,r[1],r[2]);break;case 3:e(g,r[1],r[2],r[3]);break;default:e.apply(null,r)}}}if(null!==p&&o)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(p,t.data):u.set(p,t.component,t.data)}else u.markChanged(p,t.component)}u.endIteration()}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class bt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n,e.enableChangeTracking(t)}resetTick(e){this.lastRunTick_=e}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}class vt{constructor(e,t,n){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0,void 0!==n&&this.insert(Ce,{value:n})):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=te(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 St{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(e){const t=new vt(this,null,e);return this.spawned_.push(t),t}entity(e){return new vt(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}class Pt{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class Mt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Pt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Pt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class Tt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ct{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Et;function At(){return{_type:"get_world"}}exports.Schedule=void 0,(Et=exports.Schedule||(exports.Schedule={}))[Et.Startup=0]="Startup",Et[Et.First=1]="First",Et[Et.PreUpdate=2]="PreUpdate",Et[Et.Update=3]="Update",Et[Et.PostUpdate=4]="PostUpdate",Et[Et.Last=5]="Last",Et[Et.FixedPreUpdate=10]="FixedPreUpdate",Et[Et.FixedUpdate=11]="FixedUpdate",Et[Et.FixedPostUpdate=12]="FixedPostUpdate";let Rt=0;function kt(e,t,n){const s=++Rt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function It(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class Ft{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.queryCache_=new Map,this.removedCache_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;let n=this.queryCache_.get(e._id),s=this.removedCache_.get(e._id);const o=!n;o&&(n=[],s=[],this.queryCache_.set(e._id,n),this.removedCache_.set(e._id,s));let i=0,r=0;for(let a=0;a<e._params.length;a++){const l=e._params[a];if("query"===l._type){if(o){const e=new wt(this.world_,l,this.currentLastRunTick_);n.push(e),t[a]=e}else{const e=n[i];e.resetTick(this.currentLastRunTick_),t[a]=e}i++}else if("removed"===l._type){if(o){const e=l,n=new bt(this.world_,e._component,this.currentLastRunTick_);s.push(n),t[a]=n}else{const e=s[r];e.resetTick(this.currentLastRunTick_),t[a]=e}r++}else t[a]=this.resolveParam(l)}const a=this.timings_?performance.now():0;let l;try{l=e._fn(...t)}catch(n){throw this.flushSystem_(e,t,a),n}if(l instanceof Promise)return l.then(()=>{this.flushSystem_(e,t,a)},n=>{throw this.flushSystem_(e,t,a),n});this.flushSystem_(e,t,a)}flushSystem_(e,t,n){for(let e=0;e<t.length;e++)t[e]instanceof St&&t[e].flush();this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}resolveParam(e){switch(e._type){case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new St(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Tt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ct(n)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Bt{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 Ut=Ne(new Bt,"Input");class Dt{constructor(e){this.target_=e??null}build(e){const n=new Bt;e.insertResource(Ut,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,kt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Lt=new Dt,zt=Ne({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Wt;function Ht(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(Wt=exports.BlendMode||(exports.BlendMode={}))[Wt.Normal=0]="Normal",Wt[Wt.Additive=1]="Additive",Wt[Wt.Multiply=2]="Multiply",Wt[Wt.Screen=3]="Screen",Wt[Wt.PremultipliedAlpha=4]="PremultipliedAlpha";let $t=null,Ot=null,Vt=1;const Nt=new Map;function jt(e){$t=e,Ot=e.getResourceManager(),tn()}function Xt(){0!==Kt&&$t&&($t._free(Kt),Kt=0),Nt.clear(),Vt=1,qt=!1,Qt.clear(),Zt=null,Ot=null,$t=null}function Yt(){if(!Ot)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ot}const Gt={createShader:(e,t)=>Yt().createShader(e,t),releaseShader(e){e>0&&Yt().releaseShader(e)},create(e){const t=Vt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Nt.set(t,n),t},get:e=>Nt.get(e),setUniform(e,t,n){const s=Nt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,$t?.invalidateMaterialCache(e))},getUniform(e,t){const n=Nt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Nt.get(e);n&&(n.blendMode=t,$t?.invalidateMaterialCache(e))},getBlendMode(e){const t=Nt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const n=Nt.get(e);n&&(n.depthTest=t,$t?.invalidateMaterialCache(e))},getShader(e){const t=Nt.get(e);return t?.shader??0},release(e){Nt.delete(e),$t?.invalidateMaterialCache(e)},isValid:e=>Nt.has(e),releaseAll(){Nt.clear(),$t?.clearMaterialCache()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Nt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Vt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Nt.set(n,s),n},toAssetData(e,t){const n=Nt.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=Nt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let qt=!1,Kt=0;const Jt=16384,Qt=new Map;let Zt=null;function en(e){const t=(0===Kt&&$t&&(Kt=$t._malloc(Jt)),Kt);if(0===t||!$t)return{ptr:0,count:0};let n=0,s=0;const o=$t.HEAPU8,i=$t.HEAPU32,r=$t.HEAPF32;for(const[a,l]of e){if(Ht(l))continue;let e=Qt.get(a);e||(Zt||(Zt=new TextEncoder),e=Zt.encode(a),Qt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Jt){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Jt} bytes), skipping remaining uniforms`);break}i[t+n>>2]=c,n+=4,o.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);i[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function tn(){if(!$t||qt)return;$t.materialDataProvider=(e,t,n,s,o)=>{const i=Nt.get(e);if(!i)return $t.HEAPU32[t>>2]=0,$t.HEAPU32[n>>2]=0,$t.HEAPU32[s>>2]=0,void($t.HEAPU32[o>>2]=0);$t.HEAPU32[t>>2]=i.shader,$t.HEAPU32[n>>2]=i.blendMode;const{ptr:r,count:a}=en(i.uniforms);$t.HEAPU32[s>>2]=r,$t.HEAPU32[o>>2]=a},qt=!0}const nn={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 sn{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=H.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const o=this.failed_.get(e);if(o&&Date.now()<o.expiry)throw o.error;this.failed_.delete(e);const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),o=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,o),this.pending_.delete(e),o})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+H.assetFailureCooldown}),t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`)),t}}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()}clearAll(){this.cache_.clear(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class on{constructor(e,t=""){this.cache_=new sn,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Gt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Gt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await r(t))throw new Error(`Material file not found: ${t}`);const n=await i(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 o=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(o);return{handle:Gt.createFromAsset(s,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function rn(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function an(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0,duration:e.duration};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const ln=new Map;function cn(e){ln.set(e.name,e)}const un=Q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function dn(e,t){const n=e.getEntitiesWithComponents([un]);for(const s of n){const n=e.get(s,un);if(!n.enabled||!n.playing||!n.clip)continue;const o=ln.get(n.clip);if(!o||0===o.frames.length)continue;const i=o.frames[n.currentFrame],r=i?.duration??1/(o.fps*n.speed),a=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let l=a;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=o.frames.length&&(n.loop&&o.loop?n.currentFrame=0:(n.currentFrame=o.frames.length-1,n.playing=!1)),l=!0),l&&e.has(s,fe)){const t=o.frames[n.currentFrame],i=e.get(s,fe);i.texture=t.texture,t.uvOffset&&(i.uvOffset=t.uvOffset,i.uvScale=t.uvScale),e.insert(s,fe,i)}l&&e.insert(s,un,n)}}class hn{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static setAssetResolver(e){this.assetResolver_=e}static resolveUrl_(e){return!this.baseUrl||e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}/${e}`}static async preload(e){if(this.bufferCache_.has(e))return;if(this.assetResolver_){const t=this.assetResolver_(e);if(t)return this.preloadFromData(e,t)}const t=await this.backend_.loadBuffer(this.resolveUrl_(e));this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const o=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:o?0:n,loop:!0}),o&&this.fadeIn(this.bgmHandle_,o,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),o=()=>{const i=(performance.now()-s)/1e3,r=Math.min(i/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(o):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(o)}static fadeOut(e,t,n){const s=performance.now(),o=()=>{const i=(performance.now()-s)/1e3,r=Math.min(i/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(o):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(o)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}hn.mixer_=null,hn.bufferCache_=new Map,hn.bgmHandle_=null,hn.bgmVolume_=1,hn.fadeAnimId_=0,hn.disposed_=!1,hn.assetResolver_=null,hn.baseUrl="";const pn=new Map,fn=new Map;function gn(e,t,n){pn.set(e,{width:t,height:n})}function mn(e){return pn.get(e)}function yn(){pn.clear()}function _n(e,t){fn.set(e,t)}function xn(e){return fn.get(e)}let wn=null;function bn(e){wn=e}function vn(){wn=null}const Sn={initLayer(e,t,n,s,o){wn?.tilemap_initLayer(e,t,n,s,o)},destroyLayer(e){wn?.tilemap_destroyLayer(e)},setTile(e,t,n,s){wn?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>wn?wn.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,o,i){wn?.tilemap_fillRect(e,t,n,s,o,i)},setTiles(e,t){if(!wn)return;const n=t.byteLength,s=wn._malloc(n);new Uint16Array(wn.HEAPU8.buffer,s,t.length).set(t),wn.tilemap_setTiles(e,s,t.length),wn._free(s)},hasLayer:e=>!!wn&&wn.tilemap_hasLayer(e),setRenderProps(e,t,n,s,o,i,r,a,l){wn?.tilemap_setRenderProps(e,t,n,s,o,i,r,a,l)},setTint(e,t,n,s,o,i){wn?.tilemap_setTint(e,t,n,s,o,i)},setVisible(e,t){wn?.tilemap_setVisible(e,t)},setOriginEntity(e,t){wn?.tilemap_setOriginEntity(e,t)},submitLayer(e,t,n,s,o,i,r,a,l,c,u,d,h,p,f,g,m,y,_,x){wn?.tilemap_submitLayer(e,t,n,s,o,i,r,a,l,c,u,d,h,p,f,g,m,y,_,x)},setTileAnimation(e,t,n){if(!wn||0===n.length)return;const s=new Uint32Array(2*n.length);for(let e=0;e<n.length;e++)s[2*e]=n[e].tileId,s[2*e+1]=n[e].duration;const o=s.byteLength,i=wn._malloc(o);new Uint32Array(wn.HEAPU8.buffer,i,s.length).set(s),wn.tilemap_setTileAnimation(e,t,i,n.length),wn._free(i)},advanceAnimations(e,t){wn?.tilemap_advanceAnimations(e,t)},setTileProperty(e,t,n,s){wn?.tilemap_setTileProperty(e,t,n,s)},getTileProperty:(e,t,n,s)=>wn?wn.tilemap_getTileProperty(e,t,n,s):"",flipTile(e,t,n,s,o,i){wn?.tilemap_flipTile(e,t,n,s,o,i)},rotateTile(e,t,n,s){wn?.tilemap_rotateTile(e,t,n,s)},setGridType(e,t){wn?.tilemap_setGridType(e,t)},tileToWorld(e,t,n,s,o){if(!wn)return{x:0,y:0};const i=wn.tilemap_tileToWorld(e,t,n,s,o),r=new Float32Array(wn.HEAPU8.buffer,i,2);return{x:r[0],y:r[1]}},worldToTile(e,t,n,s,o){if(!wn)return{x:0,y:0};const i=wn.tilemap_worldToTile(e,t,n,s,o),r=new Float32Array(wn.HEAPU8.buffer,i,2);return{x:r[0],y:r[1]}}},Pn=Q("Tilemap",{source:""}),Mn=Q("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function Tn(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function Cn(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function En(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function An(e){const t=e.width,n=e.height,s=e.tilewidth??0,o=e.tileheight??0;if(!(t&&n&&s&&o))return null;const i=e.tilesets,r=[],a=[];if(i)for(const e of i){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??o,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,o=e.height??n,i=!1!==e.visible,r=e.data,l=new Uint16Array(s*o);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=En(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=Cn(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,p="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:o,visible:i,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:p})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let o="rect",i=null;if(e.ellipse)o="ellipse";else if(e.point)o="point";else if(e.polygon){o="polygon";const t=e.polygon;i=[];for(const e of t)i.push(e.x,e.y)}else if(e.polyline){o="polygon";const t=e.polyline;i=[];for(const e of t)i.push(e.x,e.y)}n.push({shape:o,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:i,properties:t})}u.push({name:e.name??"",objects:n})}const h=new Map,p=new Map;if(i)for(const e of i){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.id,s=n+1,o=e.animation;if(o&&o.length>0){const e=o.map(e=>({tileId:(e.tileid??0)+1,duration:e.duration??100}));h.set(s,e)}const i=e.properties;if(i){const e=new Map;for(const s of i){const o=s.name;"collision"===o&&!0===s.value&&d.push(n+t),e.set(o,String(s.value))}e.size>0&&p.set(s,e)}}}return{width:t,height:n,tileWidth:s,tileHeight:o,orientation:e.orientation??"orthogonal",layers:c,tilesets:r,objectGroups:u,collisionTileIds:d,tileAnimations:h,tileProperties:p}}function Rn(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),o=[];for(const e of s)".."===e?o.pop():"."!==e&&""!==e&&o.push(e);return o.join("/")}const kn=Math.PI/180;function In(e,t,n,s,o,i){const r=function(e,t,n,s){const o=new Uint8Array(t*n),i=[],r=(i,r)=>{if(i>=t||r>=n)return!1;const a=r*t+i;if(o[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let i=0;i<a;i++)o[(e+n)*t+(s+i)]=1;i.push({col:s,row:e,width:a,height:l})}return i}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=o+t.col*l+.5*n,d=i+(u-t.row*c)-.5*s,h=e.spawn();e.insert(h,de,{position:{x:r,y:d,z:0}}),e.insert(h,Re,{bodyType:Oe.Static}),e.insert(h,ke,{halfExtents:{x:.5*n,y:.5*s}}),a.push(h)}return a}const Fn=0,Bn=1,Un=2,Dn="property",Ln="spine",zn="spriteAnim",Wn="audio",Hn="activation",$n="marker",On="customEvent",Vn="animFrames",Nn="hermite",jn="linear",Xn="step",Yn="easeIn",Gn="easeOut",qn="easeInOut",Kn=[["1.0","1.1",e=>{for(const t of e.tracks??[])if(t.type===Dn)for(const e of t.channels??[])for(const t of e.keyframes??[])t.interpolation||Math.abs(t.outTangent)>=1e5&&(t.interpolation="step",t.outTangent=0)}]];const Jn={once:Fn,loop:Bn,pingPong:Un};function Qn(e){const t={name:e.name??"",childPath:e.childPath??""};switch(e.type){case Dn:return{...t,type:Dn,component:e.component??"",channels:(e.channels??[]).map(e=>({property:e.property,keyframes:e.keyframes??[]}))};case Ln:return{...t,type:Ln,clips:e.clips??[],blendIn:e.blendIn??0};case zn:return{...t,type:zn,clip:e.clip??"",startTime:e.startTime??0};case Wn:return{...t,type:Wn,events:e.events??[]};case Hn:return{...t,type:Hn,ranges:e.ranges??[]};case $n:return{...t,type:$n,markers:e.markers??[]};case On:return{...t,type:On,events:(e.events??[]).map(e=>({time:e.time??0,name:e.name??"",payload:e.payload??{}}))};case Vn:return{...t,type:Vn,frames:(e.animFrames??[]).map(e=>({texture:e.texture??"",duration:e.duration}))};default:return console.warn(`[Timeline] Unknown track type: ${e.type}, skipping`),null}}function Zn(e){return function(e){let t=e.version??"1.0";for(const[n,s,o]of Kn)t===n&&(o(e),t=s);e.version="1.1"}(e),{version:"1.1",type:"timeline",duration:e.duration??0,wrapMode:(t=e.wrapMode,t?Jn[t]??Fn:Fn),tracks:(e.tracks??[]).map(Qn).filter(e=>null!==e)};var t}let es=!1,ts=!1;function ns(){return es}function ss(){return ts}var os,is;!function(e){e[e.PositionX=0]="PositionX",e[e.PositionY=1]="PositionY",e[e.PositionZ=2]="PositionZ",e[e.ScaleX=3]="ScaleX",e[e.ScaleY=4]="ScaleY",e[e.ScaleZ=5]="ScaleZ",e[e.RotationZ=6]="RotationZ",e[e.ColorR=7]="ColorR",e[e.ColorG=8]="ColorG",e[e.ColorB=9]="ColorB",e[e.ColorA=10]="ColorA",e[e.SpriteOpacity=11]="SpriteOpacity",e[e.SpriteSizeX=12]="SpriteSizeX",e[e.SpriteSizeY=13]="SpriteSizeY",e[e.OffsetMinX=14]="OffsetMinX",e[e.OffsetMinY=15]="OffsetMinY",e[e.OffsetMaxX=16]="OffsetMaxX",e[e.OffsetMaxY=17]="OffsetMaxY",e[e.AnchorMinX=18]="AnchorMinX",e[e.AnchorMinY=19]="AnchorMinY",e[e.AnchorMaxX=20]="AnchorMaxX",e[e.AnchorMaxY=21]="AnchorMaxY",e[e.PivotX=22]="PivotX",e[e.PivotY=23]="PivotY",e[e.CameraOrthoSize=24]="CameraOrthoSize",e[e.CustomField=25]="CustomField"}(os||(os={})),function(e){e[e.Transform=0]="Transform",e[e.Sprite=1]="Sprite",e[e.UIRect=2]="UIRect",e[e.Camera=3]="Camera",e[e.Custom=4]="Custom"}(is||(is={}));const rs={Transform:{"position.x":os.PositionX,"position.y":os.PositionY,"position.z":os.PositionZ,"scale.x":os.ScaleX,"scale.y":os.ScaleY,"scale.z":os.ScaleZ,rotation:os.RotationZ},Sprite:{"color.r":os.ColorR,"color.g":os.ColorG,"color.b":os.ColorB,"color.a":os.ColorA,opacity:os.SpriteOpacity,"size.x":os.SpriteSizeX,"size.y":os.SpriteSizeY},UIRect:{"offsetMin.x":os.OffsetMinX,"offsetMin.y":os.OffsetMinY,"offsetMax.x":os.OffsetMaxX,"offsetMax.y":os.OffsetMaxY,"anchorMin.x":os.AnchorMinX,"anchorMin.y":os.AnchorMinY,"anchorMax.x":os.AnchorMaxX,"anchorMax.y":os.AnchorMaxY,"pivot.x":os.PivotX,"pivot.y":os.PivotY},Camera:{orthoSize:os.CameraOrthoSize}},as={Transform:is.Transform,Sprite:is.Sprite,UIRect:is.UIRect,Camera:is.Camera},ls={[Nn]:0,[jn]:1,[Xn]:2,[Yn]:3,[Gn]:4,[qn]:5};function cs(e){return e?ls[e]??0:0}function us(e,t){return rs[e]?.[t]??os.CustomField}function ds(e,t){const n=(new TextEncoder).encode(t),s=e._malloc(n.length);return new Uint8Array(e.HEAPU8.buffer,s,n.length).set(n),[s,n.length]}function hs(e,t){e._free(t)}function ps(e,t){const n=e._tl_create(t.duration,t.wrapMode);if(!n)return{handle:0,tracks:[],totalPropertyChannels:0};const s=[];let o=0;for(const i of t.tracks)switch(i.type){case Dn:fs(e,n,i),s.push({type:"property",component:i.component,childPath:i.childPath,channelProperties:i.channels.map(e=>e.property)}),o+=i.channels.length;break;case Ln:gs(e,n,i),s.push({type:"spine",childPath:i.childPath});break;case Wn:ms(e,n,i),s.push({type:"audio",childPath:i.childPath});break;case Hn:ys(e,n,i),s.push({type:"activation",childPath:i.childPath});break;case zn:_s(e,n,i),s.push({type:"spriteAnim",childPath:i.childPath})}return{handle:n,tracks:s,totalPropertyChannels:o}}function fs(e,t,n){const s=e,o=n.channels.length,i=as[n.component]??is.Custom;if(i===is.Custom)return void function(e,t,n){const s=e,o=n.channels.length,[i,r]=ds(e,n.childPath),[a,l]=ds(e,n.component),c=n.channels.map(e=>(new TextEncoder).encode(e.property));let u=0;for(const e of c)u+=e.length;const d=s._malloc(u);let h=0;for(const e of c)new Uint8Array(s.HEAPU8.buffer,d+h,e.length).set(e),h+=e.length;const p=s._malloc(4*o);new Int32Array(s.HEAPU8.buffer,p,o).set(c.map(e=>e.length));let f=0;const g=[];for(const e of n.channels)g.push(e.keyframes.length),f+=e.keyframes.length;const m=s._malloc(4*o);new Int32Array(s.HEAPU8.buffer,m,o).set(g);const y=s._malloc(5*f*4),_=new Float32Array(s.HEAPU8.buffer,y,5*f);let x=0;for(const e of n.channels)for(const t of e.keyframes)_[x++]=t.time,_[x++]=t.value,_[x++]=t.inTangent,_[x++]=t.outTangent,_[x++]=cs(t.interpolation);e._tl_addCustomPropertyTrack(t,i,r,a,l,d,p,o,y,m),hs(e,i),hs(e,a),hs(e,d),hs(e,p),hs(e,m),hs(e,y)}(e,t,n);const[r,a]=ds(e,n.childPath),l=s._malloc(o),c=new Uint8Array(s.HEAPU8.buffer,l,o);for(let e=0;e<o;e++)c[e]=us(n.component,n.channels[e].property);let u=0;const d=[];for(const e of n.channels)d.push(e.keyframes.length),u+=e.keyframes.length;const h=s._malloc(4*o);new Int32Array(s.HEAPU8.buffer,h,o).set(d);const p=s._malloc(5*u*4),f=new Float32Array(s.HEAPU8.buffer,p,5*u);let g=0;for(const e of n.channels)for(const t of e.keyframes)f[g++]=t.time,f[g++]=t.value,f[g++]=t.inTangent,f[g++]=t.outTangent,f[g++]=cs(t.interpolation);e._tl_addPropertyTrack(t,r,a,i,l,o,p,h),hs(e,r),hs(e,l),hs(e,h),hs(e,p)}function gs(e,t,n){if(n.type!==Ln)return;const s=e,[o,i]=ds(e,n.childPath),r=n.clips.length,a=s._malloc(4*r*4),l=new Float32Array(s.HEAPU8.buffer,a,4*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),d=s._malloc(4*r),h=new Int32Array(s.HEAPU8.buffer,d,r),p=[];for(let t=0;t<r;t++){const s=n.clips[t];l[4*t]=s.start,l[4*t+1]=s.duration,l[4*t+2]=s.speed,l[4*t+3]=s.loop?1:0;const[o,i]=ds(e,s.animation);u[t]=o,h[t]=i,p.push(o)}e._tl_addSpineTrack(t,o,i,a,c,d,r,n.blendIn),hs(e,o),hs(e,a),hs(e,c),hs(e,d);for(const t of p)hs(e,t)}function ms(e,t,n){if(n.type!==Wn)return;const s=e,[o,i]=ds(e,n.childPath),r=n.events.length,a=s._malloc(2*r*4),l=new Float32Array(s.HEAPU8.buffer,a,2*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),d=s._malloc(4*r),h=new Int32Array(s.HEAPU8.buffer,d,r),p=[];for(let t=0;t<r;t++){const s=n.events[t];l[2*t]=s.time,l[2*t+1]=s.volume;const[o,i]=ds(e,s.clip);u[t]=o,h[t]=i,p.push(o)}e._tl_addAudioTrack(t,o,i,a,c,d,r),hs(e,o),hs(e,a),hs(e,c),hs(e,d);for(const t of p)hs(e,t)}function ys(e,t,n){if(n.type!==Hn)return;const s=e,[o,i]=ds(e,n.childPath),r=s._malloc(2*n.ranges.length*4),a=new Float32Array(s.HEAPU8.buffer,r,2*n.ranges.length);for(let e=0;e<n.ranges.length;e++)a[2*e]=n.ranges[e].start,a[2*e+1]=n.ranges[e].end;e._tl_addActivationTrack(t,o,i,r,n.ranges.length),hs(e,o),hs(e,r)}function _s(e,t,n){if(n.type!==zn)return;const[s,o]=ds(e,n.childPath),[i,r]=ds(e,n.clip);e._tl_addSpriteAnimTrack(t,s,o,i,r,n.startTime),hs(e,s),hs(e,i)}const xs=new Map;let ws=null;function bs(e,t){xs.set(e,t)}var vs;exports.AttenuationModel=void 0,(vs=exports.AttenuationModel||(exports.AttenuationModel={}))[vs.Linear=0]="Linear",vs[vs.Inverse=1]="Inverse",vs[vs.Exponential=2]="Exponential";const Ss={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Ps(e,t=Ss){const{model:n,refDistance:s,maxDistance:o,rolloff:i}=t,r=Math.max(e,.001);let a;switch(n){case exports.AttenuationModel.Linear:{const e=o-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),o)-s)/e;break}case exports.AttenuationModel.Inverse:a=s/Math.max(r,s);break;case exports.AttenuationModel.Exponential:a=Math.pow(Math.max(r,s)/s,-i);break;default:return 1}return Math.max(0,Math.min(1,a))}function Ms(e,t,n,s,o){const i=e-n;return Math.max(-1,Math.min(1,i/o))}const Ts=Q("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:exports.AttenuationModel.Inverse,rolloff:1,priority:0,enabled:!0}),Cs=Q("AudioListener",{enabled:!0});class Es{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const o=n.mixer;hn.init(n,o),o&&(void 0!==s.masterVolume&&(o.master.volume=s.masterVolume),void 0!==s.musicVolume&&(o.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(o.sfx.volume=s.sfxVolume));const i=new Map;this.activeSourceHandles_=i;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(qe)],t=>{if(!(!ns()||ss()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let o=0,u=0,d=!1;const h=s.getEntitiesWithComponents([Cs,pe]);for(const e of h){if(s.get(e,Cs).enabled){const t=s.get(e,pe);o=t.position.x,u=t.position.y,d=!0;break}}const p=s.getEntitiesWithComponents([Ts]);a.clear();for(const e of p){const t=s.get(e,Ts);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!i.has(c)&&n.isReady){const e=hn.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});i.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&i.has(c)){const n=i.get(c);if(!n.isPlaying){i.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,pe),a=r?.position.x??0,h=r?.position.y??0,p=a-o,f=h-u,g=Ps(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),m=Ms(a,0,o,0,t.maxDistance);n.setVolume(t.volume*g),n.setPan(m)}}for(const[e,t]of i)a.has(e)&&t.isPlaying||i.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),hn.dispose()}}const As=new Es,Rs=Q("TimelinePlayer",{timeline:"",playing:!1,speed:1,wrapMode:"once"}),ks=new Map;function Is(e,t){ks.set(e,t)}const Fs=new Map;function Bs(e,t){return Fs.get(e)?.get(t)??0}const Us={once:Fn,loop:Bn,pingPong:Un};function Ds(e,t,n){const s=t.split(".");let o=e;for(let e=0;e<s.length-1;e++)if(o=o[s[e]],null==o||"object"!=typeof o)return!1;const i=s[s.length-1];return i in o&&(o[i]=n,!0)}function Ls(e,t,n){if(!n)return t;const s=oe("Children"),o=oe("Name");if(!s||!o)return null;let i=t;const r=n.split("/");for(const t of r){const n=e.tryGet(i,s);if(!n)return null;const r=n.entities||[];let a=null;for(const n of r){const s=e.tryGet(n,o);if(s&&s.value===t){a=n;break}}if(null===a)return null;i=a}return i}class zs{constructor(){this.name="TimelinePlugin",this.handles_=new Map,this.animFramesStates_=new Map}build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,kt([je(qe)],e=>{if(ns()&&!ss())return;const n=t.getWasmModule();if(!n)return;ws=n;const s=t.getCppRegistry();n.uiRect_clearAnimOverrides(s);const o=t.getEntitiesWithComponents([Rs]);for(const s of o){const o=t.get(s,Rs);if(!o.timeline)continue;let i=this.handles_.get(s);if(!i){const e=ks.get(o.timeline);if(!e)continue;if(i=ps(n,e),!i.handle)continue;this.resolveTrackTargets(t,n,i,s),this.handles_.set(s,i),bs(s,i.handle);const r=e.tracks.filter(e=>e.type===Vn);r.length>0&&this.animFramesStates_.set(s,{tracks:r,lastFrameIndices:r.map(()=>-1)})}const r=i.handle;if(o.playing&&!n._tl_isPlaying(r)){const e=n._tl_getTime(r);0===e?n._tl_play(r):(n._tl_play(r),n._tl_setTime(r,e))}else!o.playing&&n._tl_isPlaying(r)&&n._tl_pause(r);const a=Us[o.wrapMode]??Fn;n._tl_setWrapMode(r,a),n._tl_advance(t.getCppRegistry(),r,s,e.delta,o.speed),this.processEvents(t,n),this.processCustomProperties(t,n,i),this.processAnimFrames(t,n,s,i.handle,o.timeline),n._tl_clearResults(),!n._tl_isPlaying(r)&&o.playing&&(o.playing=!1,t.insert(s,Rs,o))}},{name:"TimelineSystem"}))}clearHandles(){this.handles_.clear(),this.animFramesStates_.clear()}cleanup(){this.handles_.clear(),this.animFramesStates_.clear(),ks.clear()}processAnimFrames(e,t,n,s,o){const i=this.animFramesStates_.get(n);if(!i)return;const r=t._tl_getTime(s),a=oe("Sprite");if(!a||!e.has(n,a))return;const l=1/12;for(let t=0;t<i.tracks.length;t++){const s=i.tracks[t].frames;if(0===s.length)continue;let c=0,u=0;for(let e=0;e<s.length;e++){const t=s[e].duration??l;if(r<c+t){u=e;break}c+=t,e===s.length-1&&(u=s.length-1)}if(u!==i.lastFrameIndices[t]){i.lastFrameIndices[t]=u;const r=Bs(o,s[u].texture);if(r){const t=e.get(n,a);t.texture=r,e.set(n,a,t)}}}}resolveTrackTargets(e,t,n,s){let o=0,i=0;for(const r of n.tracks){if(!r.childPath){"property"===r.type?o++:i++;continue}const a=Ls(e,s,r.childPath);if(null!==a){const e="property"!==r.type,s=e?i:o;t._tl_setTrackTarget(n.handle,e?1:0,s,a)}"property"===r.type?o++:i++}}decodeEventString(e,t){const n=e._tl_getEventString(t),s=e._tl_getEventStringLen(t);if(!n||s<=0)return"";const o=new Uint8Array(e.HEAPU8.buffer,n,s);return(new TextDecoder).decode(o)}processEvents(e,t){const n=t._tl_getEventCount();for(let s=0;s<n;s++){const n=t._tl_getEventType(s),o=t._tl_getEventEntity(s);switch(n){case 0:{const n=this.decodeEventString(t,s),i=0!==t._tl_getEventIntParam(s);if(e.has(o,ve)){const t=e.get(o,ve);t.animation=n,t.playing=!0,t.loop=i,e.set(o,ve,t)}break}case 1:if(e.has(o,ve)){const t=e.get(o,ve);t.playing=!1,e.set(o,ve,t)}break;case 2:{const n=this.decodeEventString(t,s);if(e.has(o,un)){const t=e.get(o,un);e.insert(o,un,{...t,clip:n,playing:!0})}break}case 3:{const e=this.decodeEventString(t,s),n=t._tl_getEventFloatParam(s);e&&hn.playSFX(e,{volume:n});break}case 4:{const n=0!==t._tl_getEventIntParam(s);if(e.has(o,ve)){const t=e.get(o,ve);t.enabled=n,e.set(o,ve,t)}if(e.has(o,un)){const t=e.get(o,un);e.insert(o,un,{...t,enabled:n})}const i=oe("Sprite");if(i&&e.has(o,i)){const t=e.get(o,i);e.set(o,i,{...t,enabled:n})}break}}}}processCustomProperties(e,t,n){const s=t._tl_getCustomPropertyCount();if(0!==s)for(let o=0;o<s;o++){const s=t._tl_getCustomPropertyEntity(o),i=t._tl_getCustomPropertyTrackIndex(o),r=t._tl_getCustomPropertyChannelIndex(o),a=t._tl_getCustomPropertyValue(o),l=n.tracks.filter(e=>"property"===e.type)[i];if(!l?.component||!l.channelProperties)continue;const c=oe(l.component);if(!c||!e.has(s,c))continue;const u=e.get(s,c),d=l.channelProperties[r];d&&Ds(u,d,a)&&e.set(s,c,u)}}}const Ws=new zs,Hs=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["UIRenderer",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}],["TimelinePlayer",{fields:[{field:"timeline",type:"timeline"}]}]]);function $s(e){const t=Hs.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function Os(e){return Hs.get(e)?.fields??[]}function Vs(e){return Hs.get(e)?.spine??null}function Ns(e,t){const n=Y(e.type);if(!n)return;const s=e.data;for(const o of n){const n=s[o];if("number"==typeof n&&0!==n){const i=t.get(n);void 0===i&&console.warn(`[Scene] Entity reference not found: ${e.type}.${o} references entity ${n} which does not exist`),s[o]=void 0!==i?i:0}}}function js(e){const t=e.components.some(e=>"UIRect"===e.type),n=e.components.findIndex(e=>"Sprite"===e.type),s=e.components.some(e=>"UIRenderer"===e.type);if(!t||-1===n||s)return;const o=e.components[n].data,i=o.texture;e.components.push({type:"UIRenderer",data:{visualType:i?2:1,texture:i??0,color:o.color??{r:1,g:1,b:1,a:1},uvOffset:o.uvOffset??{x:0,y:0},uvScale:o.uvScale??{x:1,y:1},sliceBorder:o.sliceBorder??{x:0,y:0,z:0,w:0},material:o.material??0,enabled:o.enabled??!0}}),e.components.splice(n,1)}function Xs(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,Ce,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;js(s);const t=n.get(s.id);for(const o of s.components)Ns(o,n),Ks(e,t,o,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),o=n.get(s.parent);void 0!==t&&void 0!==o&&e.setParent(t,o)}return n}function Ys(e,t){return Xs(e,t)}async function Gs(e,t,n){const s=n?.assetServer,o=n?.assetBaseUrl??s?.baseUrl,i=new Map;s&&await async function(e,t,n,s,o){const i=new Map;for(const e of qs.keys())i.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Hs.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&i.get(e.type)?.add(t)}}const l=new Map,c=[...qs.entries()].map(async([e,o])=>{const r=await o.load(i.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),o){for(const e of s.values())o.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&o.materialHandles.add(t);const t=i.get("font");if(t)for(const e of t)o.fontPaths.add(e);for(const e of a)o.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Hs.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const o=t.get(s);void 0!==o&&(n[e.field]=o)}}}(t,s,o,i,n?.collectAssets);const r=Xs(e,t);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}const qs=new Map([["texture",{async load(e,t,n,s){const o=new Map,i=[...e].map(async e=>{try{const i=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(i);o.set(e,r.handle),s.set(e,i),gn(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),o.set(e,0)}});return await Promise.all(i),o}}],["material",{async load(e,t,n){const s=new Map,o=[...e].map(async e=>{try{const o=await t.loadMaterial(e,n);s.set(e,o.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(o),s}}],["font",{async load(e,t,n){const s=new Map,o=[...e].map(async e=>{try{const o=await t.loadBitmapFont(e,n);s.set(e,o)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(o),s}}],["anim-clip",{async load(e,t,n,s){const o=[...e].map(async e=>{try{const o=await t.loadJson(e),i=rn(o),r=new Map,a=i.map(async e=>{try{const o=n?`${n}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),s.set(e,o)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);cn(an(e,o,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(o),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await hn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const o=[...e].map(async e=>{try{const o=An(await t.loadJson(e));if(!o)return void console.warn(`Failed to parse tilemap: ${e}`);const i=[];for(const r of o.tilesets){const o=Rn(e,r.image);let a=0;try{const e=n?`${n}/${o}`:`/${o}`,i=await t.loadTexture(e);a=i.handle,s.set(o,e),gn(i.handle,i.width,i.height)}catch(e){console.warn(`Failed to load tileset texture: ${o}`,e)}i.push({textureHandle:a,columns:r.columns})}_n(e,{tileWidth:o.tileWidth,tileHeight:o.tileHeight,layers:o.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:i})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(o),new Map}}],["timeline",{async load(e,t,n,s){const o=[...e].map(async e=>{try{const o=Zn(await t.loadJson(e));Is(e,o);const i=function(e){const t=new Set,n=new Set,s=new Set;for(const o of e.tracks)if(o.type===Wn)for(const e of o.events)t.add(e.clip);else if(o.type===zn)o.clip&&n.add(o.clip);else if(o.type===Vn)for(const e of o.frames)e.texture&&s.add(e.texture);return{audio:Array.from(t),animClips:Array.from(n),textures:Array.from(s)}}(o);if(i.textures.length>0){const o=new Map,r=i.textures.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(i);o.set(e,r.handle),s.set(e,i)}catch(t){console.warn(`Failed to load animFrames texture: ${e}`,t),o.set(e,0)}});await Promise.all(r),function(e,t){Fs.set(e,t)}(e,o)}}catch(t){console.warn(`Failed to load timeline: ${e}`,t)}});return await Promise.all(o),new Map}}]]);function Ks(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const o=oe(n.type);if(o)e.insert(t,o,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Js(e,t){const n=e.getEntitiesWithComponents([me]);for(const s of n){const n=e.get(s,me);n&&(n.aspectRatio=t,e.insert(s,me,n))}}class Qs{constructor(e){this.textureCache_=new sn,this.shaderCache_=new sn,this.jsonCache_=new sn,this.textCache_=new sn,this.binaryCache_=new sn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new sn,this.prefabCache_=new sn,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=l(H.textCanvasSize,H.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new on(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),o=this.textureRefCounts_.get(s);if(void 0===o)continue;const i=this.textureCache_.get(s);if(!i)continue;const r=o-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),Gt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const o=this.resolveUrl(t,n),i=await this.fetchText(o);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===b(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,i,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),o=l.find(e=>e.name===n);if(o){const n=t.getTextureGLId(o.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,o.info.width,o.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=b(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 o=n?`${n}/${s}`:s;return this.loadFntFile(o)}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],o=e.substring(0,e.lastIndexOf("/")),i=o?`${o}/${s}`:s,r=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of $s(e.type)){const s=e.data[n];if("string"==typeof s&&s){const o=t(s);o&&(e.data[n]=o)}}const n=Vs(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const o=t(n);o&&(e.data[s]=o)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 Gs(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const o=s.metadata?.atlas;o&&n.push(this.loadSpine(s.path,o).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,o=this.getWebGL2Context();return o?this.createTextureWebGL2(o,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,o){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o?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 r=this.module_.GL,a=r.getNewId(r.textures);r.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 o=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(o.data.buffer);this.unpremultiplyAlpha(i);const r=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const l=r.createTexture(t,n,a,i.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:o}=this.parseEsShader(t);if(!s||!o)throw new Error(`Invalid shader format: ${e}`);return Gt.createShader(s,o)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(t))throw new Error(`Shader file not found: ${e}`);const s=await i(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:o,fragment:a}=this.parseEsShader(s);if(!o||!a)throw new Error(`Invalid shader format: ${e}`);return Gt.createShader(o,a)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(M(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await i(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(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 n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return i(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(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 n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 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 o="";for(const e of s){o=o?`${o}/${e}`:e;try{t.analyzePath(o).exists||t.mkdir(o)}catch{try{t.mkdir(o)}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 Zs=Ne(null,"Assets");class eo{build(e){const t=e.wasmModule;t?e.insertResource(Zs,new Qs(t)):console.warn("AssetPlugin: No WASM module available")}}const to=new eo;function no(e){return e.map(e=>({type:e.type,data:JSON.parse(JSON.stringify(e.data))}))}function so(e){return JSON.parse(JSON.stringify(e))}function oo(e,t){for(const n of e){const e=Y(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const o=t.get(e);void 0!==o&&(n.data[s]=o)}}}}function io(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:so(n.componentData.data)})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}function ro(e,t,n){const s=n.depth??0;if(s>10)throw new Error(`Prefab nesting depth exceeded 10. Check for deep or circular nesting in: ${e.name}`);if(e.basePrefab)return function(e,t,n,s){const o=e.basePrefab,i=n.visited??new Set;if(i.has(o))throw new Error(`[Prefab] Circular variant reference detected: "${o}" is already being instantiated in the current prefab chain`);const r=n.loadPrefab(o);if(!r)throw new Error(`Failed to load base prefab for variant: ${o}`);i.add(o);const a=[...e.overrides??[],...t];return ro(r,a,{...n,visited:i,depth:s+1})}(e,t,n,s);const o=n.visited??new Set,i=new Map;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,n.allocateId());const r=[];for(const a of e.entities){if(a.nestedPrefab){const e=a.nestedPrefab.prefabPath;if(o.has(e))throw new Error(`[Prefab] Circular reference detected: "${e}" is already being instantiated in the current prefab chain`);const t=n.loadPrefab(e);if(!t)throw new Error(`Failed to load nested prefab: ${e}`);o.add(e);const l=ro(t,a.nestedPrefab.overrides,{...n,visited:o,depth:s+1});i.set(a.prefabEntityId,l.rootId);const c=l.entities.find(e=>e.id===l.rootId);c&&(c.parent=null!==a.parent?i.get(a.parent)??null:null),r.push(...l.entities);continue}const l=i.get(a.prefabEntityId),c=a.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:a.prefabEntityId,name:a.name,parent:c?null:null!==a.parent?i.get(a.parent)??null:null,children:a.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:no(a.components),visible:a.visible};oo(u.components,i),io(u,t),r.push(u)}const a=i.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:r,rootId:a}}async function ao(e,t,n,s,o=0){if(o>10)return;const i=s??new Set;if(e.basePrefab&&!i.has(e.basePrefab)&&!n.has(e.basePrefab)){i.add(e.basePrefab);const s=await t(e.basePrefab);n.set(e.basePrefab,s),await ao(s,t,n,i,o+1)}for(const s of e.entities){if(!s.nestedPrefab)continue;const e=s.nestedPrefab.prefabPath;if(i.has(e)||n.has(e))continue;i.add(e);const r=await t(e);n.set(e,r),await ao(r,t,n,i,o+1)}}async function lo(e,t,n){const s=new Map;n?.assetServer&&await ao(t,e=>n.assetServer.loadPrefab(e,n.assetBaseUrl),s);let o=0;const i={allocateId:()=>o++,loadPrefab:e=>s.get(e)??null,visited:new Set},{entities:r,rootId:a}=ro(t,n?.overrides??[],i),l={version:t.version,name:t.name,entities:r.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},c=await Gs(e,l,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),u=c.get(a);return void 0!==n?.parent&&e.setParent(u,n.parent),{root:u,entities:c}}class co{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,o=await this.assetServer_.loadPrefab(s,t?.baseUrl);return lo(this.world_,o,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const uo=Ne(null,"Prefabs");class ho{constructor(){this.name="PrefabsPlugin",this.dependencies=[Zs]}build(e){const t=e.getResource(Zs);e.insertResource(uo,new co(e.world,t))}}const po=new ho;let fo=null,go=0,mo=0,yo=0;const _o=new Float32Array(256);function xo(e){fo=e,go=fo._malloc(64),mo=fo._malloc(64),yo=fo._malloc(1024)}function wo(){fo&&(go&&(fo._free(go),go=0),mo&&(fo._free(mo),mo=0),yo&&(fo._free(yo),yo=0)),fo=null}function bo(){if(!fo)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return fo}const vo={r:1,g:1,b:1,a:1},So={begin(e){const t=bo();try{t.HEAPF32.set(e,go/4),t.draw_begin(go)}catch(e){st(e,"Draw.begin")}},end(){try{bo().draw_end()}catch(e){st(e,"Draw.end")}},line(e,t,n,s=1){try{bo().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){st(e,"Draw.line")}},rect(e,t,n,s=!0){try{bo().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){st(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{bo().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){st(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,o=32){try{bo().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,o)}catch(e){st(e,"Draw.circle")}},circleOutline(e,t,n,s=1,o=32){try{bo().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,o)}catch(e){st(e,"Draw.circleOutline")}},texture(e,t,n,s=vo){try{bo().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){st(e,"Draw.texture")}},textureRotated(e,t,n,s,o=vo){try{bo().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,o.r,o.g,o.b,o.a)}catch(e){st(e,"Draw.textureRotated")}},setLayer(e){bo().draw_setLayer(e)},setDepth(e){bo().draw_setDepth(e)},getDrawCallCount:()=>fo?fo.draw_getDrawCallCount():0,getPrimitiveCount:()=>fo?fo.draw_getPrimitiveCount():0,setBlendMode(e){bo().draw_setBlendMode(e)},setDepthTest(e){bo().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=bo();s.HEAPF32.set(n,mo/4),s.draw_mesh(e,t,mo)}catch(n){st(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=bo(),o=Gt.get(t);if(!o)return;if(So.setBlendMode(o.blendMode),So.setDepthTest(o.depthTest),0===o.uniforms.size)return void So.drawMesh(e,o.shader,n);let i;if(s.HEAPF32.set(n,mo/4),!o.dirty_&&o.cachedBuffer_)i=o.cachedIdx_;else{i=0;let e=0;for(const[t,n]of o.uniforms){const s=To(t);if(!(s<0)){if(Ht(n))_o[i++]=10,_o[i++]=s,_o[i++]=n.slot??e++,_o[i++]=n.textureId;else if("number"==typeof n)_o[i++]=1,_o[i++]=s,_o[i++]=n;else if(Array.isArray(n)){_o[i++]=n.length,_o[i++]=s;for(let e=0;e<n.length;e++)_o[i++]=n[e]}else"w"in n?(_o[i++]=4,_o[i++]=s,_o[i++]=n.x,_o[i++]=n.y,_o[i++]=n.z,_o[i++]=n.w):"z"in n?(_o[i++]=3,_o[i++]=s,_o[i++]=n.x,_o[i++]=n.y,_o[i++]=n.z):(_o[i++]=2,_o[i++]=s,_o[i++]=n.x,_o[i++]=n.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!o.cachedBuffer_||o.cachedBuffer_.length<i)&&(o.cachedBuffer_=new Float32Array(i)),o.cachedBuffer_.set(_o.subarray(0,i)),o.cachedIdx_=i,o.dirty_=!1}if(0===i)return void s.draw_mesh(e,o.shader,mo);s.HEAPF32.set(o.cachedBuffer_.subarray(0,i),yo/4),s.draw_meshWithUniforms(e,o.shader,mo,yo,i)}catch(n){st(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Po={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},Mo=new Set;function To(e){const t=Po[e];return void 0!==t?t:(Mo.has(e)||(Mo.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Po).join(", ")}`)),-1)}const Co=new Map;function Eo(e,t,n){Co.set(e,{fn:t,scene:n??""})}function Ao(e){Co.delete(e)}function Ro(){Co.clear()}var ko;exports.DataType=void 0,(ko=exports.DataType||(exports.DataType={}))[ko.Float=1]="Float",ko[ko.Float2=2]="Float2",ko[ko.Float3=3]="Float3",ko[ko.Float4=4]="Float4",ko[ko.Int=5]="Int",ko[ko.Int2=6]="Int2",ko[ko.Int3=7]="Int3",ko[ko.Int4=8]="Int4";let Io=null,Fo=0,Bo=0,Uo=0;function Do(e){Io=e,Fo=Io._malloc(262144),Bo=Io._malloc(65536),Uo=Io._malloc(256)}function Lo(){Io&&(Fo&&Io._free(Fo),Bo&&Io._free(Bo),Uo&&Io._free(Uo),Fo=0,Bo=0,Uo=0),Io=null}function zo(){if(!Io)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Io}const Wo={create(e){const t=zo(),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,Fo/4);const o=e.layout.length,i=new Int32Array(o);for(let t=0;t<o;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Uo,o).set(i),t.geometry_init(n,Fo,s,Uo,o,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,Bo,s).set(e.indices),t.geometry_setIndices16(n,Bo,s)}else{new Uint32Array(t.HEAPU8.buffer,Bo,s).set(e.indices),t.geometry_setIndices32(n,Bo,s)}}return n},updateVertices(e,t,n=0){const s=zo(),o=t.length;if(4*o>262144)throw new Error(`Vertex data too large: ${o} floats (max 65536)`);s.HEAPF32.set(t,Fo/4),s.geometry_updateVertices(e,Fo,o,n)},release(e){e>0&&zo().geometry_release(e)},isValid:e=>!(!Io||e<=0)&&Io.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Wo.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const o=s/t*Math.PI*2,i=Math.cos(o)*e,r=Math.sin(o)*e,a=(Math.cos(o)+1)/2,l=(Math.sin(o)+1)/2;n.push(i,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Wo.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,o=-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),o=Math.max(o,i.y);const i=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(o-n);i.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return Wo.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};let Ho=1;const $o=new Map,Oo=new Map;function Vo(){return $o}function No(){return Oo}class jo{constructor(){this.passes_=[],this.destroyed_=!1,this.id=Ho++,$o.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}clearPasses(){return this.passes_.length=0,this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of Oo)t===this&&Oo.delete(e);$o.delete(this.id)}}}const Xo="#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";let Yo=null;function Go(e){Yo=e}function qo(){for(const e of Vo().values())e.destroy();Vo().clear(),No().clear(),Yo&&Jo.isInitialized()&&Jo.shutdown(),Yo=null}function Ko(){if(!Yo)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Yo}const Jo={createStack:()=>new jo,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");No().set(e,t)},unbind(e){No().delete(e)},getStack:e=>No().get(e)??null,init(e,t){try{return Ko().postprocess_init(e,t)}catch(n){return st(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ko().postprocess_shutdown()}catch(e){st(e,"PostProcess.shutdown")}},resize(e,t){try{Ko().postprocess_resize(e,t)}catch(n){st(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!Yo)return!1;try{return Yo.postprocess_isInitialized()}catch(e){return st(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ko().postprocess_setBypass(e)}catch(e){st(e,"PostProcess.setBypass")}},begin(){try{Ko().postprocess_begin()}catch(e){st(e,"PostProcess.begin")}},end(){try{Ko().postprocess_end()}catch(e){st(e,"PostProcess.end")}},setOutputViewport(e,t,n,s){try{Ko().postprocess_setOutputViewport(e,t,n,s)}catch(e){st(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=No().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Jo.isInitialized()||Jo.init(1,1),Jo.setBypass(!1),function(e){const t=Ko();try{t.postprocess_clearPasses()}catch(e){return void st(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){st(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){st(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){st(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):Jo.setBypass(!0)},_resetAfterCamera(){try{Ko().postprocess_clearPasses(),Ko().postprocess_setBypass(!0)}catch(e){st(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of No().keys())e(t)||No().delete(t)},screenStack:null,setScreenStack(e){Jo.screenStack=e},_beginScreenCapture(){try{Ko().postprocess_beginScreenCapture()}catch(e){st(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Ko().postprocess_endScreenCapture()}catch(e){st(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Jo.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Ko();try{t.postprocess_clearScreenPasses()}catch(e){return void st(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){st(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){st(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){st(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{Ko().postprocess_executeScreenPasses()}catch(e){st(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Gt.createShader(Xo,"#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:()=>Gt.createShader(Xo,"#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 vig = 1.0 - smoothstep(1.0 - u_softness, 1.0, dist);\n fragColor = vec4(color.rgb * mix(1.0, vig, u_intensity), color.a);\n}\n"),createGrayscale:()=>Gt.createShader(Xo,"#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"),createBloomExtract:()=>Gt.createShader(Xo,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_threshold;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float brightness = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float knee = u_threshold * 0.5;\n float soft = brightness - u_threshold + knee;\n soft = clamp(soft, 0.0, 2.0 * knee);\n soft = soft * soft / (4.0 * knee + 0.00001);\n float contrib = max(soft, brightness - u_threshold);\n contrib /= max(brightness, 0.00001);\n fragColor = vec4(color.rgb * contrib, 1.0);\n}\n"),createBloomKawase(e){const t=`#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n float d = (${e.toFixed(1)} + 0.5) * max(u_radius, 0.5);\n vec2 ts = 1.0 / u_resolution;\n fragColor = (\n texture(u_texture, v_texCoord + vec2(-d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2(-d, d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, d) * ts)\n ) * 0.25;\n}\n`;return Gt.createShader(Xo,t)},createBloomComposite:()=>Gt.createShader(Xo,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform sampler2D u_sceneTexture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 blur = texture(u_texture, v_texCoord);\n vec4 scene = texture(u_sceneTexture, v_texCoord);\n fragColor = vec4(scene.rgb + blur.rgb * u_intensity, scene.a);\n}\n"),createChromaticAberration:()=>Gt.createShader(Xo,"#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")},Qo=new Map;function Zo(e){Qo.set(e.type,e)}function ei(e){return Qo.get(e)}Zo({type:"blur",label:"Blur",factory:()=>Jo.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Zo({type:"bloom",label:"Bloom",factory:()=>Jo.createBloomExtract(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:1,step:.01,defaultValue:.4},{name:"u_intensity",label:"Intensity",min:0,max:5,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:.5,max:5,step:.1,defaultValue:1}],multiPass:[{name:"bloom_extract",factory:()=>Jo.createBloomExtract()},{name:"bloom_kawase_0",factory:()=>Jo.createBloomKawase(0)},{name:"bloom_kawase_1",factory:()=>Jo.createBloomKawase(1)},{name:"bloom_kawase_2",factory:()=>Jo.createBloomKawase(2)},{name:"bloom_kawase_3",factory:()=>Jo.createBloomKawase(3)},{name:"bloom_kawase_4",factory:()=>Jo.createBloomKawase(4)},{name:"bloom_composite",factory:()=>Jo.createBloomComposite()}]}),Zo({type:"vignette",label:"Vignette",factory:()=>Jo.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:.6},{name:"u_softness",label:"Softness",min:0,max:1,step:.01,defaultValue:.5}]}),Zo({type:"grayscale",label:"Grayscale",factory:()=>Jo.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Zo({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Jo.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const ti=new Map,ni=new Map;function si(e){const t=ti.get(e);t&&(Jo.unbind(e),t.destroy(),ti.delete(e));const n=ni.get(e);if(n){for(const e of n.values())Gt.releaseShader(e);ni.delete(e)}}function oi(){for(const e of ti.keys())si(e)}const ii=Ne({enabled:!0},"PostProcessVolumeConfig"),ri=new Map,ai=new Map;function li(e,t){const n=ai.get(e);if(void 0!==n)return n;const s=t();return ai.set(e,s),s}function ci(e,t){if(0===t.size){const t=ri.get(e);return void(t&&(Jo.unbind(e),t.destroy(),ri.delete(e)))}let n=ri.get(e);n||(n=Jo.createStack(),ri.set(e,n)),n.clearPasses();for(const[e,s]of t){if(!s.enabled)continue;const t=ei(e);if(t)if(t.multiPass)for(const e of t.multiPass){const t=li(e.name,e.factory);n.addPass(e.name,t);for(const[t,o]of s.uniforms)n.setUniform(e.name,t,o)}else{const o=li(e,t.factory);n.addPass(e,o);for(const[t,o]of s.uniforms)n.setUniform(e,t,o)}}n.enabledPassCount>0?Jo.bind(e,n):Jo.unbind(e)}const ui=kt([xt(Ae,de),xt(me)],(e,t)=>{const n=[];for(const[t,s,o]of e)n.push({data:s,tx:{x:o.position.x,y:o.position.y}});const s=[];for(const{data:e}of n)e.isGlobal&&s.push({data:e,factor:1});const o=s.length>0?function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,o]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(o-n)*s)}else{const e=new Map;for(const[t,o]of Object.entries(n.uniforms))e.set(t,o*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(s):new Map;for(const[e,n]of t)n.isActive&&ci(e,o)},{name:"PostProcessVolumeSystem"});class di{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(ii,{enabled:!0}),e.addSystemToSchedule(exports.Schedule.PostUpdate,ui)}cleanup(){oi(),function(){for(const[e,t]of ri)Jo.unbind(e),t.destroy();ri.clear();for(const e of ai.values())Gt.releaseShader(e);ai.clear()}(),Jo.setScreenStack(null)}}const hi=new di;var pi,fi;exports.FlushReason=void 0,(pi=exports.FlushReason||(exports.FlushReason={}))[pi.BatchFull=0]="BatchFull",pi[pi.TextureSlotsFull=1]="TextureSlotsFull",pi[pi.ScissorChange=2]="ScissorChange",pi[pi.StencilChange=3]="StencilChange",pi[pi.MaterialChange=4]="MaterialChange",pi[pi.BlendModeChange=5]="BlendModeChange",pi[pi.StageEnd=6]="StageEnd",pi[pi.TypeChange=7]="TypeChange",pi[pi.FrameEnd=8]="FrameEnd",exports.RenderType=void 0,(fi=exports.RenderType||(exports.RenderType={}))[fi.Sprite=0]="Sprite",fi[fi.Spine=1]="Spine",fi[fi.Mesh=2]="Mesh",fi[fi.ExternalMesh=3]="ExternalMesh",fi[fi.Text=4]="Text",fi[fi.Particle=5]="Particle",fi[fi.Shape=6]="Shape",fi[fi.UIElement=7]="UIElement";var gi;exports.RenderStage=void 0,(gi=exports.RenderStage||(exports.RenderStage={}))[gi.Background=0]="Background",gi[gi.Opaque=1]="Opaque",gi[gi.Transparent=2]="Transparent",gi[gi.Overlay=3]="Overlay";let mi=null,yi=0;function _i(e){mi=e,yi=mi._malloc(64)}function xi(){mi&&yi&&(mi._free(yi),yi=0),mi=null}const wi={init(e,t){mi?.renderer_init(e,t)},resize(e,t){mi?.renderer_resize(e,t)},beginFrame(){mi?.renderer_beginFrame()},updateTransforms(e){if(mi)try{mi.renderer_updateTransforms(e._cpp)}catch(e){st(e,"Renderer.updateTransforms")}},begin(e,t){if(mi&&yi)try{mi.HEAPF32.set(e,yi/4),mi.renderer_begin(yi,t??0)}catch(e){st(e,"Renderer.begin")}},flush(){try{mi?.renderer_flush()}catch(e){st(e,"Renderer.flush")}},end(){try{mi?.renderer_end()}catch(e){st(e,"Renderer.end")}},submitAll(e,t,n,s,o,i){if(mi)try{mi.renderer_submitAll(e._cpp,t,n,s,o,i)}catch(e){st(e,"Renderer.submitAll")}},setStage(e){mi?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>mi?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){mi?.renderer_releaseTarget(e)},getTargetTexture:e=>mi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>mi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){mi?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){mi?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,o){mi?.renderer_setScissor(e,t,n,s,o)},clearBuffers(e){mi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>mi?mi.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>mi?{drawCalls:mi.renderer_getDrawCalls(),triangles:mi.renderer_getTriangles(),sprites:mi.renderer_getSprites(),text:mi.renderer_getText(),spine:mi.renderer_getSpine?.()??0,meshes:mi.renderer_getMeshes(),culled:mi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0},captureNextFrame(){mi?.renderer_captureNextFrame()},getCapturedData:()=>mi?function(e){if(!e.renderer_hasCapturedData())return null;const t=e.renderer_getCapturedFrameSize();if(0===t)return null;const n=e.renderer_getCapturedFrameData(),s=e.renderer_getCapturedEntities(),o=e.renderer_getCapturedEntityCount(),i=e.renderer_getCapturedCameraCount(),r=e.HEAPU8,a=new DataView(r.buffer,n,76*t),l=new Uint32Array(r.buffer,s,o),c=[];for(let e=0;e<t;e++){const t=76*e,n=a.getUint32(t,!0),s=a.getUint32(t+4,!0),i=a.getUint8(t+8),r=a.getUint8(t+9),u=a.getUint8(t+10),d=a.getUint32(t+12,!0),h=a.getUint32(t+16,!0),p=a.getUint32(t+20,!0),f=a.getUint32(t+24,!0),g=a.getUint32(t+28,!0),m=a.getUint32(t+32,!0),y=a.getUint32(t+36,!0),_=a.getInt32(t+40,!0),x=a.getUint8(t+44),w=a.getInt32(t+48,!0),b=a.getInt32(t+52,!0),v=a.getInt32(t+56,!0),S=a.getInt32(t+60,!0),P=0!==a.getUint8(t+64),M=0!==a.getUint8(t+65),T=0!==a.getUint8(t+66),C=a.getInt32(t+68,!0),E=a.getUint8(t+72),A=[];for(let e=0;e<m&&y+e<o;e++)A.push(l[y+e]);c.push({index:n,cameraIndex:s,stage:i,type:r,blendMode:u,textureId:d,materialId:h,shaderId:p,vertexCount:f,triangleCount:g,entityCount:m,entityOffset:y,layer:_,flushReason:x,scissorX:w,scissorY:b,scissorW:v,scissorH:S,scissorEnabled:P,stencilWrite:M,stencilTest:T,stencilRef:C,textureSlotUsage:E,entities:A})}return{drawCalls:c,cameraCount:i}}(mi):null,hasCapturedData:()=>mi?.renderer_hasCapturedData()??!1,replayToDrawCall(e){mi&&function(e,t){e.renderer_replayToDrawCall(t)}(mi,e)},getSnapshotImageData:()=>mi?function(e){const t=e.renderer_getSnapshotSize();if(0===t)return null;const n=e.renderer_getSnapshotWidth(),s=e.renderer_getSnapshotHeight();if(0===n||0===s)return null;const o=e.renderer_getSnapshotPtr(),i=e.HEAPU8,r=new Uint8ClampedArray(i.buffer,o,t),a=new Uint8ClampedArray(t),l=4*n;for(let e=0;e<s;e++){const t=e*l,n=(s-1-e)*l;a.set(r.subarray(t,t+l),n)}return new ImageData(a,n,s)}(mi):null};let bi=null;function vi(e){bi=e}function Si(){bi=null}const Pi={enable(){bi?.gl_enableErrorCheck(!0)},disable(){bi?.gl_enableErrorCheck(!1)},check:e=>bi?.gl_checkErrors(e)??0,diagnose(){bi?.renderer_diagnose()}};class Mi{constructor(){this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null,this.preFlushCallbacks_=[]}setActiveScenes(e){this.activeScenes_=e}addPreFlushCallback(e){this.preFlushCallbacks_.push(e)}beginFrame(){wi.beginFrame()}beginScreenCapture(){Jo.screenStack&&Jo.screenStack.enabledPassCount>0&&(Jo.isInitialized()||Jo.init(1,1),Jo._applyScreenStack(),Jo._beginScreenCapture())}endScreenCapture(){Jo.screenStack&&Jo.screenStack.enabledPassCount>0&&(Jo._endScreenCapture(),Jo._executeScreenPasses())}submitScene(e,t,n,s){wi.updateTransforms(e),wi.submitAll(e,0,n.x,n.y,n.w,n.h);for(const t of this.preFlushCallbacks_)t(e);wi.flush(),this.executeDrawCallbacks(t,s)}render(e){const{registry:t,viewProjection:n,width:s,height:o,elapsed:i}=e;s===this.lastWidth_&&o===this.lastHeight_||(wi.resize(s,o),this.lastWidth_=s,this.lastHeight_=o),wi.beginFrame(),wi.setViewport(0,0,s,o),wi.clearBuffers(3),wi.begin(n),this.submitScene(t,n,{x:0,y:0,w:s,h:o},i),wi.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:o,elapsed:i,cameraEntity:r}=e,a=void 0!==r&&null!==Jo.getStack(r);a&&(Jo._applyForCamera(r),Jo.resize(s.w,s.h),Jo.setOutputViewport(s.x,s.y,s.w,s.h),Jo.begin()),wi.setViewport(s.x,s.y,s.w,s.h),wi.setScissor(s.x,s.y,s.w,s.h,!0),wi.clearBuffers(o),wi.setScissor(0,0,0,0,!1),wi.begin(n),this.submitScene(t,n,s,i),wi.end(),a&&(Jo.end(),Jo._resetAfterCamera())}executeDrawCallbacks(e,t){const n=Co;if(n.size>0){So.begin(e);const s=[];for(const[e,o]of n.entries())if(!o.scene||!this.activeScenes_||this.activeScenes_.has(o.scene))try{o.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}So.end();for(const e of s)Ao(e)}}}const Ti={None:0,SolidColor:1,Image:2,NineSlice:3},Ci=re("UIRenderer",{visualType:Ti.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),Ei="__scene_transition_overlay__";class Ai{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Ri{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Ee,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Eo(e,t,this.instance_.config.name)}bindPostProcess(e,t){Jo.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Jo.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Ee)){const n=this.app_.world.get(e,Ee);n.persistent=t,this.app_.world.insert(e,Ee,n)}}}class ki{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())Ao(t);for(const t of e.postProcessBindings.keys())Jo.unbind(t)}this.transition_&&(Ao(Ei),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise((n,s)=>{const o=t.duration??H.sceneTransitionDuration,i=t.color??{...H.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:o,color:i,targetScene:e,options:t,resolve:n,reject:s},Eo(Ei,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;So.setLayer(9999),So.setDepth(9999),So.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{reject:t}=this.transition_;this.transition_=null,Ao(Ei),t(e)}})().catch(()=>{})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ao(Ei),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Ai(t);this.scenes_.set(e,n);const s=new Ri(n,this.app_);this.contexts_.set(e,s);const o=(async()=>{let o=t.data;if(!o&&t.path){const e=this.app_.hasResource(Zs)?this.app_.getResource(Zs):null;if(e)o=await e.loadJson(t.path);else{const e=await fetch(t.path);o=await e.json()}}return await this.loadSceneData_(n,e,t,o),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,o);try{return await o}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Ai(t);this.scenes_.set(e,n);const s=new Ri(n,this.app_);this.contexts_.set(e,s);const o=(async()=>{let o=t.data;if(!o&&t.path){const e=this.app_.hasResource(Zs)?this.app_.getResource(Zs):null;if(e)o=await e.loadJson(t.path);else{const e=await fetch(t.path);o=await e.json()}}return await this.loadSceneData_(n,e,t,o),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,o);try{return await o}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const o=t?.keepPersistent??!0;for(const e of n.entities){if(o&&this.app_.world.valid(e)&&this.app_.world.has(e,Ee)){if(this.app_.world.get(e,Ee).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Ao(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())Jo.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},o={collectAssets:n};this.app_.hasResource(Zs)&&(o.assetServer=this.app_.getResource(Zs));const i=await Gs(this.app_.world,s,o);e.loadedAssets=n;for(const n of i.values())e.entities.add(n),this.app_.world.insert(n,Ee,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Fi(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const o=this.contexts_.get(t);n.setup&&await n.setup(o)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(Zs)?this.app_.getResource(Zs):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)Gt.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let o=!1;if(n.has(e,fe)){const t=n.get(e,fe);s.sprite=t.color.a,t.color.a=0,n.insert(e,fe,t),o=!0}if(n.has(e,ve)){const t=n.get(e,ve);s.spine=t.color.a,t.color.a=0,n.insert(e,ve,t),o=!0}if(n.has(e,be)){const t=n.get(e,be);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,be,t),o=!0}if(n.has(e,Ci)){const t=n.get(e,Ci);s.uiRenderer=t.color.a,t.color.a=0,n.insert(e,Ci,t),o=!0}o&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,fe)){const t=n.get(e,fe);t.color.a=s.sprite,n.insert(e,fe,t)}if(void 0!==s.spine&&n.has(e,ve)){const t=n.get(e,ve);t.color.a=s.spine,n.insert(e,ve,t)}if(void 0!==s.bitmapText&&n.has(e,be)){const t=n.get(e,be);t.color.a=s.bitmapText,n.insert(e,be,t)}if(void 0!==s.uiRenderer&&n.has(e,Ci)){const t=n.get(e,Ci);t.color.a=s.uiRenderer,n.insert(e,Ci,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Ii=Ne(null,"SceneManager");function Fi(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Ii).getSceneStatus(t)&&n._fn(...s)}}}const Bi=kt([Xe(Ii),je(qe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ui={name:"SceneManager",build(e){const t=new ki(e);e.insertResource(Ii,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ii),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,n),e.addSystemToSchedule(exports.Schedule.Last,Bi)}};class Di{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new Mt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=async()=>{if(!this.running_)return;const e=c(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(exports.Schedule.Last);else{await this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(exports.Schedule.FixedPreUpdate),await this.runSchedule(exports.Schedule.FixedUpdate),await this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(exports.Schedule.PreUpdate),await this.runSchedule(exports.Schedule.Update),await this.runSchedule(exports.Schedule.PostUpdate),await this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new pt,this.resources_=new Ge;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Di}getPlugin(e){return this.installed_plugins_.find(t=>t instanceof e)}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const o=s.filter(t=>t.system._id!==e);o.length!==s.length&&(this.systems_.set(n,o),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}async waitForPhysics(){this.physicsInitPromise_?await this.physicsInitPromise_:console.warn("[ESEngine] No PhysicsPlugin installed, waitForPhysics() is a no-op")}get isPhysicsReady(){return null!=this.physicsModule_}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return nt(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Ii).register(e),this}setInitialScene(e){return this.getResource(Ii).setInitial(e),this}async tick(e){if(this.runner_||(this.runner_=new Ft(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(qe)||this.resources_.insert(qe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_()),await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(exports.Schedule.Last);else{await this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(exports.Schedule.FixedPreUpdate),await this.runSchedule(exports.Schedule.FixedUpdate),await this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(exports.Schedule.PreUpdate),await this.runSchedule(exports.Schedule.Update),await this.runSchedule(exports.Schedule.PostUpdate),await this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}async run(){this.running_||(this.running_=!0,this.runner_=new Ft(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(qe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),await this.flushStartupSystems_(),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,Ro();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Si,xi,qo,Lo,Xt,wo];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){console.warn("[App] Shutdown despawn error:",e)}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const o=t.get(s);if(void 0!==o){const t=e[o];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,o=new Set,i=r=>{if(s.has(r))return;if(o.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}o.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&i(n)}o.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)i(t);return n}async flushStartupSystems_(){const e=this.systems_.get(exports.Schedule.Startup);0!==e.length&&(this.sortedSystemsCache_.delete(exports.Schedule.Startup),await this.runSchedule(exports.Schedule.Startup),e.length=0,this.sortedSystemsCache_.delete(exports.Schedule.Startup))}async runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{const t=this.runner_.run(e.system);t instanceof Promise&&await t}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(exports.Schedule[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(qe);t.delta=e,t.elapsed+=e,t.frameCount++}}function Li(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const zi=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Wi(e,t,n,s,o){const i=e*t/n,r=e;switch(s){case ce.FixedWidth:return i;case ce.FixedHeight:return r;case ce.Expand:return Math.max(i,r);case ce.Shrink:return Math.min(i,r);case ce.Match:{const e=o;return Math.pow(i,1-e)*Math.pow(r,e)}default:return r}}const Hi=[];function $i(e){if(e<Hi.length)return Hi[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return Hi.push(t),t}function Oi(e,t,n,s,o,i){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=i&&o?r.filter(e=>{const t=o.tryGet(e,Ee);return!t||""===t.scene||i.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const o=t.getCamera(e),i=t.getTransform(e),r=o.viewportW*n/(o.viewportH*s);let a,u=0,d=0;if(o.projectionType===ae.Orthographic){if(d=o.orthoSize,l){d=Wi(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=Ni(-u,u,-d,d,-o.farPlane,o.farPlane)}else a=Xi(o.fov*Math.PI/180,r,o.nearPlane,o.farPlane);const h=Gi(i.position.x,i.position.y,i.position.z),p=$i(c.length);p.entity=e,p.viewProjection.set(Ki(a,h)),p.viewportRect.x=o.viewportX,p.viewportRect.y=o.viewportY,p.viewportRect.w=o.viewportW,p.viewportRect.h=o.viewportH,p.clearFlags=o.clearFlags,p.priority=o.priority,p.halfW=u,p.halfH=d,p.cameraX=i.position.x,p.cameraY=i.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const Vi=new Float32Array(16);function Ni(e,t,n,s,o,i){const r=Vi;r.fill(0);const a=t-e,l=s-n,c=i-o;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(i+o)/c,r[15]=1,r}const ji=new Float32Array(16);function Xi(e,t,n,s){const o=ji;o.fill(0);const i=1/Math.tan(e/2),r=n-s;return o[0]=i/t,o[5]=i,o[10]=(s+n)/r,o[11]=-1,o[14]=2*s*n/r,o}const Yi=new Float32Array(16);function Gi(e,t,n){const s=Yi;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}const qi=new Float32Array(16);function Ki(e,t){const n=qi;for(let s=0;s<4;s++)for(let o=0;o<4;o++)n[4*o+s]=e[0+s]*t[4*o+0]+e[4+s]*t[4*o+1]+e[8+s]*t[4*o+2]+e[12+s]*t[4*o+3];return n}const Ji={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},Qi={Simple:0,Sliced:1,Tiled:2,Filled:3},Zi={Horizontal:0,Vertical:1},er={Left:0,Right:1,Bottom:2,Top:3},tr=Q("Image",{texture:V,color:{r:1,g:1,b:1,a:1},imageType:Qi.Simple,fillMethod:Zi.Horizontal,fillOrigin:er.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),nr=re("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}}),sr=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0});let or=null,ir=null;function rr(e,t){switch(e){case Ji.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ji.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ji.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function ar(e,t,n,s){if(!e.has(t,nr))return;const o=e.get(t,nr),i=rr(n,s);o.anchorMin=i.anchorMin,o.anchorMax=i.anchorMax,i.anchorMin.x===i.anchorMax.x&&(o.size={...o.size,x:0}),i.anchorMin.y===i.anchorMax.y&&(o.size={...o.size,y:0}),e.insert(t,nr,o)}function lr(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}const cr=1.15,ur=.75;function dr(e,t,n,s){return t?n?{r:e.r*ur,g:e.g*ur,b:e.b*ur,a:e.a}:s?{r:Math.min(1,e.r*cr),g:Math.min(1,e.g*cr),b:Math.min(1,e.b*cr),a:e.a}:{...e}:{r:.5*e.r,g:.5*e.g,b:.5*e.b,a:.6*e.a}}function hr(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function pr(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),o=[];for(const t of s){if(!t){o.push("");continue}let s="";for(let i=0;i<t.length;i++){const r=t[i],a=s+r;if(e.measureText(a).width>n&&s){if(hr(r.charCodeAt(0))&&s.length>0&&hr(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!hr(s.charCodeAt(t))){e=t;break}e>=0?(o.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(o.push(s),s=r)}else o.push(s),s=r}else s=a}s&&o.push(s)}return o.length>0?o:[""]}function fr(e){let t=1;for(;t<e;)t*=2;return t}function gr(e,t){let n=0,s=t;for(;e.has(s,xe);){const t=e.get(s,xe).entity;if(!e.valid(t))break;n++,s=t}return n}function mr(e,t){if(or&&ir){const e=or.getUIRectComputedWidth(ir,t);if(e>0)return e}return e.size.x}function yr(e,t){if(or&&ir){const e=or.getUIRectComputedHeight(ir,t);if(e>0)return e}return e.size.y}function _r(e,t,n){or&&ir&&or.setUIRectSize(ir,e,t,n)}function xr(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function wr(e,t,n){0!==t&&e.valid(t)&&n(t)}function br(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a}function vr(e,t,n){if(e.has(t,tr)){const s=e.get(t,tr);br(s.color,n)||(s.color=n,e.insert(t,tr,s))}else if(e.has(t,fe)){const s=e.get(t,fe);br(s.color,n)||(s.color=n,e.insert(t,fe,s))}else if(e.has(t,Ci)){const s=e.get(t,Ci);br(s.color,n)||(s.color=n,e.insert(t,Ci,s))}}function Sr(e,t,n){if(e.has(t,tr)){const s=e.get(t,tr);s.enabled!==n&&(s.enabled=n,e.insert(t,tr,s))}else if(e.has(t,fe)){const s=e.get(t,fe);s.enabled!==n&&(s.enabled=n,e.insert(t,fe,s))}else if(e.has(t,Ci)){const s=e.get(t,Ci);s.enabled!==n&&(s.enabled=n,e.insert(t,Ci,s))}}class Pr{constructor(){this.map_=new Map}get(e){return this.map_.get(e)}set(e,t){this.map_.set(e,t)}delete(e){this.map_.delete(e)}has(e){return this.map_.has(e)}cleanup(e){for(const[t]of this.map_)e.valid(t)||this.map_.delete(t)}ensureInit(e,t){let n=this.map_.get(e);return n||(n=t(),this.map_.set(e,n)),n}clear(){this.map_.clear()}[Symbol.iterator](){return this.map_[Symbol.iterator]()}}function Mr(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let o=0;o<t.length;o++)s[t[o]]=n[o](e);return s},changed(e,s){for(let o=0;o<t.length;o++)if(e[t[o]]!==n[o](s))return!0;return!1},update(e,s){for(let o=0;o<t.length;o++)e[t[o]]=n[o](s)}}}const Tr=.1,Cr={r:.3,g:.5,b:.8,a:1},Er={r:.9,g:.9,b:.9,a:1},Ar={r:.95,g:.95,b:.95,a:1},Rr={Left:0,Center:1,Right:2},kr={Top:0,Middle:1,Bottom:2},Ir={Visible:0,Clip:1,Ellipsis:2},Fr=Q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Rr.Left,verticalAlign:kr.Top,wordWrap:!0,overflow:Ir.Visible,lineHeight:1.2});class Br{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l(H.textCanvasSize,H.textCanvasSize);const t=this.canvas.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("TextRenderer: failed to create 2D canvas context");this.ctx=t}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,fr(this.frameMaxW_)),e.height=Math.max(e.height,fr(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=fr(this.frameMaxW_),e.height=fr(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const o=t&&t.size.x>0&&t.size.y>0,i=o?t.size.x:0,r=o?t.size.y:0,a=e.wordWrap&&o;let l=pr(n,e.content,a?i:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=o?Math.ceil(i):d+2*u,f=o?Math.ceil(r):h+2*u;if(o&&e.overflow===Ir.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,i)}}this.frameMaxW_=Math.max(this.frameMaxW_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(s.width<p||s.height<f)&&(s.width=Math.max(s.width,fr(p)),s.height=Math.max(s.height,fr(f)));const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${m}, ${y}, ${_})`,o&&e.overflow===Ir.Clip&&(n.save(),n.beginPath(),n.rect(0,0,p,f),n.clip());const x=l.length*c;let w;if(o){switch(e.verticalAlign){case kr.Top:w=u;break;case kr.Middle:w=u+(f-2*u-x)/2;break;case kr.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let s;switch(e.align){case Rr.Left:s=u;break;case Rr.Center:s=p/2;break;case Rr.Right:s=p-u;break;default:s=u}n.fillText(t,s,b),b+=c}o&&e.overflow===Ir.Clip&&n.restore();const v=n.getImageData(0,0,p,f),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const o=this.renderText(t,n);return this.cache.set(e,o),o}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Rr.Left:return"left";case Rr.Center:return"center";case Rr.Right:return"right"}}}const Ur=Mr({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?mr(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?yr(e.uiRect,e.entity):0});function Dr(e,t){e.has(t,Ci)||e.insert(t,Ci,{visualType:Ti.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Lr{build(e){se("Text",Fr);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Br(t),s=e.world,o=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Fr));for(const e of o.keys())if(!s.valid(e)||!s.has(e,Fr)){if(s.valid(e)&&s.has(e,Ci)){const t=s.get(e,Ci);t.texture=0,t.visualType=Ti.None,s.insert(e,Ci,t)}o.delete(e)}const e=s.getEntitiesWithComponents([Fr]);for(const t of e){const e=s.get(t,Fr),i=s.has(t,nr)?s.get(t,nr):null,r={text:e,uiRect:i,entity:t},a=o.get(t);if(a&&!Ur.changed(a,r)){if(s.has(t,Ci)&&0!==s.get(t,Ci).texture)continue}Dr(s,t);const l=i?{size:{x:mr(i,t),y:yr(i,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Ci);u.texture=c.textureHandle,u.visualType=Ti.Image,u.color={r:1,g:1,b:1,a:1},u.uvOffset={x:0,y:0},u.uvScale={x:1,y:1},s.insert(t,Ci,u),i&&_r(t,c.width,c.height),o.set(t,Ur.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const zr=new Lr,Wr=0,Hr=re("UIMask",{enabled:!0,mode:Wr});class $r{build(e){se("UIMask",Hr)}}const Or=new $r;function Vr(e,t){const n=t??new Float32Array(16),s=e[0],o=e[1],i=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],g=e[12],m=e[13],y=e[14],_=e[15],x=s*l-o*a,w=s*c-i*a,b=s*u-r*a,v=o*c-i*l,S=o*u-r*l,P=i*u-r*c,M=d*m-h*g,T=d*y-p*g,C=d*_-f*g,E=h*y-p*m,A=h*_-f*m,R=p*_-f*y;let k=x*R-w*A+b*E+v*C-S*T+P*M;return 0===k||(k=1/k,n[0]=(l*R-c*A+u*E)*k,n[1]=(i*A-o*R-r*E)*k,n[2]=(m*P-y*S+_*v)*k,n[3]=(p*S-h*P-f*v)*k,n[4]=(c*C-a*R-u*T)*k,n[5]=(s*R-i*C+r*T)*k,n[6]=(y*b-g*P-_*w)*k,n[7]=(d*P-p*b+f*w)*k,n[8]=(a*A-l*C+u*M)*k,n[9]=(o*C-s*A-r*M)*k,n[10]=(g*S-m*b+_*x)*k,n[11]=(h*b-d*S-f*x)*k,n[12]=(l*T-a*E-c*M)*k,n[13]=(s*E-o*T+i*M)*k,n[14]=(m*w-g*v-y*x)*k,n[15]=(d*v-h*w+p*x)*k),n}function Nr(e,t,n,s,o,i,r){const a=(e-s)/i*2-1,l=(t-o)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function jr(e,t,n,s,o,i,r,a){return e>=n-o*r&&e<=n+o*(1-r)&&t>=s-i*a&&t<=s+i*(1-a)}function Xr(e,t){return 2*Math.atan2(e,t)}const Yr=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Gr={Normal:0,Hovered:1,Pressed:2,Disabled:3},qr=Q("Button",{state:Gr.Normal,transition:null});class Kr{constructor(){this.events_=[],this.entityTypeHandlers_=new Map,this.globalHandlers_=new Map,this.activeDispatches_=new Set,this.entityValidator_=null}on(e,t,n){if(void 0!==n){const s=e,o=t;let i=this.entityTypeHandlers_.get(s);i||(i=new Map,this.entityTypeHandlers_.set(s,i));let r=i.get(o);r||(r=[],i.set(o,r)),r.push(n);let a=!1;return()=>{if(a)return;a=!0;const e=i.get(o);if(e){const t=e.indexOf(n);-1!==t&&e.splice(t,1)}}}{const n=e,s=t;let o=this.globalHandlers_.get(n);o||(o=[],this.globalHandlers_.set(n,o)),o.push(s);let i=!1;return()=>{if(i)return;i=!0;const e=this.globalHandlers_.get(n);if(e){const t=e.indexOf(s);-1!==t&&e.splice(t,1)}}}}removeAll(e){this.entityTypeHandlers_.delete(e)}setEntityValidator(e){this.entityValidator_=e}emit(e,t,n){const s={entity:e,type:t,target:n??e,currentTarget:e,propagationStopped:!1,stopPropagation(){this.propagationStopped=!0}};this.events_.push(s);const o=`${e}:${t}`;return this.activeDispatches_.has(o)||(this.activeDispatches_.add(o),this.dispatchToHandlers_(s),this.activeDispatches_.delete(o)),s}emitBubbled(e,t,n,s){const o={entity:e,type:t,target:n,currentTarget:e,propagationStopped:!1,stopPropagation(){s.propagationStopped=!0}};this.events_.push(o);const i=`${e}:${t}`;this.activeDispatches_.has(i)||(this.activeDispatches_.add(i),this.dispatchToHandlers_(o),this.activeDispatches_.delete(i))}drain(){if(this.entityValidator_)for(const e of this.entityTypeHandlers_.keys())this.entityValidator_(e)||this.entityTypeHandlers_.delete(e);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)}dispatchToHandlers_(e){const t=this.entityTypeHandlers_.get(e.entity);if(t){const n=t.get(e.type);n&&this.invokeHandlers_([...n],e)}const n=this.globalHandlers_.get(e.type);n&&this.invokeHandlers_([...n],e)}invokeHandlers_(e,t){for(const n of e)try{n(t)}catch(e){console.error(`UIEvent handler error [${t.type}]:`,e)}}}const Jr=Ne(new Kr,"UIEvents"),Qr=Ne({generation:0},"UILayoutGeneration");class Zr{build(e){se("UIRect",nr),se("UIRenderer",Ci);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){or=e,ir=t}(n,s);const o={generation:0};e.insertResource(Qr,o);e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(zt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.transform_update(s),o.generation++)},{name:"UILayoutSystem"})),e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([je(zt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),o.generation++)},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const ea=new Zr,ta=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(Vr(t,e),n=!1),e)}}();function na(e,t,n,s){const o=t.emit(n,s,n);!function(e,t,n){let s=t;for(;e.has(s,xe);){const t=e.get(s,xe).entity;if(!e.valid(t))break;if(n(t))return;s=t}}(e,n,i=>{if(o.propagationStopped)return!0;if(!e.has(i,sr))return!1;const r=e.get(i,sr);return r.enabled&&t.emitBubbled(i,s,n,o),r.blockRaycast})}class sa{build(e){se("Interactable",sr),se("Button",qr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),o=new Kr;o.setEntityValidator(e=>t.valid(e)),e.insertResource(Jr,o);let i=null,r=null,a=NaN,l=NaN,c=-1;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(Ut),je(zt),je(Qr)],(e,d,h)=>{if(o.drain(),ns()&&!ss())return;const p=t.getEntitiesWithComponents([Yr]);for(const e of p){const n=t.get(e,Yr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Yr,n))}if(!d.valid)return;const f=u(),g=e.mouseX*f,m=d.screenH-e.mouseY*f;ta.update(d.viewProjection);const y=Nr(g,m,ta.getInverse(d.viewProjection),d.vpX,d.vpY,d.vpW,d.vpH);d.worldMouseX=y.x,d.worldMouseY=y.y;const _=e.isMouseButtonDown(0),x=e.isMouseButtonPressed(0),w=e.isMouseButtonReleased(0),b=y.x!==a||y.y!==l,v=h.generation!==c,S=b||v||(x||w);a=y.x,l=y.y,c=h.generation;let P=i;if(S){n.uiHitTest_update(s,y.x,y.y,_,x,w);const e=n.uiHitTest_getHitEntity();P=4294967295===e?null:e}if(null===i||t.valid(i)||(i=null),i!==P){if(null!==i&&t.valid(i)&&t.has(i,Yr)){const e=t.get(i,Yr);e.hovered=!1,t.insert(i,Yr,e),o.emit(i,"hover_exit")}if(null!==P){xr(t,P,Yr);const e=t.get(P,Yr);e.hovered=!0,t.insert(P,Yr,e),o.emit(P,"hover_enter")}i=P}if(x&&null!==P){const e=t.get(P,Yr);e.pressed=!0,e.justPressed=!0,t.insert(P,Yr,e),r=P,na(t,o,P,"press")}if(w&&null!==r){if(t.valid(r)&&t.has(r,Yr)){const e=t.get(r,Yr);e.pressed=!1,e.justReleased=!0,t.insert(r,Yr,e),na(t,o,r,"release"),r===i&&na(t,o,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const d=new Set;e.addSystemToSchedule(exports.Schedule.Update,kt([],()=>{for(const e of d)t.valid(e)||d.delete(e);const e=t.getEntitiesWithComponents([qr]);for(const n of e){if(xr(t,n,sr,{enabled:!0}),!t.has(n,Yr))continue;const e=t.get(n,Yr),s=t.get(n,qr),o=t.get(n,sr),i=!d.has(n),r=s.state;if(o.enabled?e.pressed?s.state=Gr.Pressed:e.hovered?s.state=Gr.Hovered:s.state=Gr.Normal:s.state=Gr.Disabled,i&&d.add(n),(i||r!==s.state)&&s.transition){const i=lr(s.transition,o.enabled,e.pressed,e.hovered);vr(t,n,i)}else if((i||r!==s.state)&&!s.transition&&t.has(n,tr)){const s=dr(t.get(n,tr).color,o.enabled,e.pressed,e.hovered);vr(t,n,s)}}},{name:"ButtonSystem"}))}}const oa=new sa,ia=Q("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),ra=Q("Focusable",{tabIndex:0,isFocused:!1});class aa{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const la=Ne(new aa,"FocusManager");class ca{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(se("TextInput",ia),ns()&&!ss())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=t,s=e.world,o=new Map,i=l(H.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});if(!r)return void console.warn("TextInputPlugin: failed to create 2D canvas context");const a=r;let c=0,u=0,d=!1,h=!0,p=0,f=0;const g=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!g)return;const m=g;function y(){const t=e.getResource(la);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,ia)?n:null}const _=()=>{d||null===y()||S()},x=()=>{d=!0},w=()=>{d=!1,S()},b=t=>{const n=y();if(null===n)return;if("Escape"===t.key)return void P();const o=s.get(n,ia);if("Enter"===t.key&&!o.multiline){t.preventDefault();return e.getResource(Jr).emit(n,"submit"),void P()}let i=o.cursorPos;"ArrowLeft"===t.key?i=Math.max(0,o.cursorPos-1):"ArrowRight"===t.key?i=Math.min(o.value.length,o.cursorPos+1):"Home"===t.key?i=0:"End"===t.key&&(i=o.value.length),i!==o.cursorPos&&(o.cursorPos=i,m.selectionStart=i,m.selectionEnd=i,o.dirty=!0,M())},v=()=>{const t=y();if(null!==t){const n=s.get(t,ia);n.focused=!1,n.dirty=!0;e.getResource(la).blur()}};function S(){const t=y();if(null===t)return;const n=s.get(t,ia);if(n.readOnly)return;let o=m.value;if(n.maxLength>0&&o.length>n.maxLength&&(o=o.substring(0,n.maxLength),m.value=o),o!==n.value){n.value=o;e.getResource(Jr).emit(t,"change")}n.cursorPos=m.selectionStart??o.length,n.dirty=!0,M()}function P(){const t=y();if(null!==t){const e=s.get(t,ia);e.focused=!1,e.dirty=!0}e.getResource(la).blur(),m.blur()}function M(){h=!0,p=0}m.addEventListener("input",_),m.addEventListener("compositionstart",x),m.addEventListener("compositionend",w),m.addEventListener("keydown",b),m.addEventListener("blur",v),this.cleanupListeners_=()=>{m.removeEventListener("input",_),m.removeEventListener("compositionstart",x),m.removeEventListener("compositionend",w),m.removeEventListener("keydown",b),m.removeEventListener("blur",v),m.remove();const e=n.getResourceManager();for(const t of o.values())e.releaseTexture(t);o.clear(),0!==c&&(n._free(c),c=0,u=0)};let T=null;function C(e,t,r,l){(i.width<r||i.height<l)&&(i.width=fr(Math.max(i.width,r)),i.height=fr(Math.max(i.height,l))),a.clearRect(0,0,i.width,i.height);const d=t.backgroundColor;a.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,a.fillRect(0,0,r,l),a.save(),a.beginPath(),a.rect(t.padding,0,r-2*t.padding,l),a.clip(),a.font=`${t.fontSize}px ${t.fontFamily}`,a.textBaseline="top",a.textAlign="left";const p=0===t.value.length,f=p?t.placeholder:t.password?"●".repeat(t.value.length):t.value,g=p?t.placeholderColor:t.color;a.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const m=Math.ceil(1.2*t.fontSize),y=t.padding;if(t.multiline){const e=pr(a,f,r-2*y);let t=y;for(const n of e)a.fillText(n,y,t),t+=m}else{const e=(l-t.fontSize)/2;a.fillText(f,y,e)}if(t.focused&&h){const e=t.password?"●".repeat(t.cursorPos):t.value.substring(0,t.cursorPos);let n,s,o;if(t.multiline){const e=pr(a,t.value,r-2*y);let i=0,l=0,c=0;for(let n=0;n<e.length;n++){const s=e[n].length;if(i+s>=t.cursorPos){l=n,c=t.cursorPos-i;break}i+=s,n<e.length-1&&i<t.value.length&&"\n"===t.value[i]&&i++,l=n+1,c=0}const u=l<e.length?e[l].substring(0,c):"";n=y+a.measureText(u).width,s=y+l*m,o=m}else n=y+a.measureText(e).width,s=(l-t.fontSize)/2,o=t.fontSize;a.fillStyle=`rgba(${Math.round(255*t.color.r)}, ${Math.round(255*t.color.g)}, ${Math.round(255*t.color.b)}, ${t.color.a})`,a.fillRect(n,s,2,o)}a.restore();const _=a.getImageData(0,0,r,l),x=new Uint8Array(_.data.buffer),w=n.getResourceManager();x.length>u&&(0!==c&&n._free(c),c=n._malloc(x.length),u=x.length),n.HEAPU8.set(x,c);const b=o.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(r,l,c,x.length,1,!0);o.set(e,v);const S=s.get(e,Ci);S.texture=v,S.visualType=Ti.Image,S.uvOffset={x:0,y:0},S.uvScale={x:1,y:1},S.color={r:1,g:1,b:1,a:1},S.enabled=!0,s.insert(e,Ci,S)}e.addSystemToSchedule(exports.Schedule.Update,kt([je(la)],e=>{const t=s.getEntitiesWithComponents([ia]);for(const e of t)xr(s,e,ra,{tabIndex:0,isFocused:!1}),xr(s,e,sr,{enabled:!0,blockRaycast:!0});const n=y();if(n!==T){if(null!==T&&s.valid(T)&&s.has(T,ia)){const e=s.get(T,ia);e.focused=!1,e.dirty=!0,m.blur()}null!==n&&function(e){const t=s.get(e,ia);t.readOnly||(t.focused=!0,t.dirty=!0,m.value=t.value,m.selectionStart=t.cursorPos,m.selectionEnd=t.cursorPos,m.focus(),M())}(n),T=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let t=0===f?0:(e-f)/1e3;f=e,t=Math.min(t,.1);const i=y();if(null!==i&&(p+=t,p>=.5)){p-=.5,h=!h;s.get(i,ia).dirty=!0}const r=n.getResourceManager();for(const[e,t]of o)s.valid(e)&&s.has(e,ia)||(r.releaseTexture(t),o.delete(e));const a=s.getEntitiesWithComponents([ia,nr]);for(const e of a){const t=s.get(e,ia);if(!t.dirty)continue;const n=s.get(e,nr),o=Math.ceil(n.size.x),i=Math.ceil(n.size.y);o<=0||i<=0||(s.has(e,Ci)||s.insert(e,Ci,{visualType:Ti.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),C(e,t,o,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const ua=new ca,da=Mr({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?mr(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?yr(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});function ha(e,t){e.has(t,Ci)||e.insert(t,Ci,{visualType:Ti.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class pa{build(e){se("Image",tr);const t=e.world,n=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,tr)||n.delete(e);const e=t.getEntitiesWithComponents([tr]);for(const s of e){const e=t.get(s,tr),o=t.has(s,nr)?t.get(s,nr):null,i={image:e,uiRect:o,entity:s},r=n.get(s);if(r&&t.has(s,Ci)&&!da.changed(r,i))continue;ha(t,s);const a=t.get(s,Ci);if(!e.enabled){a.enabled=!1,t.insert(s,Ci,a),n.set(s,da.take(i));continue}a.enabled=!0,a.texture=e.texture,a.color={r:e.color.r,g:e.color.g,b:e.color.b,a:e.color.a},a.material=e.material,a.uvOffset={x:0,y:0},a.uvScale={x:1,y:1};if(e.texture!==V&&0!==e.texture?e.imageType===Qi.Sliced?a.visualType=Ti.NineSlice:a.visualType=Ti.Image:a.visualType=Ti.SolidColor,e.imageType===Qi.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));o&&mr(o,s),o&&yr(o,s),e.fillMethod===Zi.Horizontal?(e.fillOrigin===er.Left||(a.uvOffset={x:1-t,y:0}),a.uvScale={x:t,y:1}):(e.fillOrigin===er.Bottom||(a.uvOffset={x:0,y:1-t}),a.uvScale={x:1,y:t})}else if(e.imageType===Qi.Tiled){const t=o?mr(o,s):0,n=o?yr(o,s):0;e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale={x:t/e.tileSize.x,y:n/e.tileSize.y})}t.insert(s,Ci,a),n.set(s,da.take(i))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const fa=new pa,ga=Q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null,onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1}},{entityFields:["graphicEntity","group"]}),ma=Q("ToggleGroup",{allowSwitchOff:!1});function ya(e,t,n){if(!e.has(t,Ci))return;const s=e.get(t,Ci);s.color.r===n.r&&s.color.g===n.g&&s.color.b===n.b&&s.color.a===n.a||(s.color=n,e.insert(t,Ci,s))}function _a(e,t,n){if(!e.has(t,Ci))return;const s=e.get(t,Ci);s.enabled!==n&&(s.enabled=n,e.insert(t,Ci,s))}class xa{build(e){se("Toggle",ga),se("ToggleGroup",ma);const t=e.world,n=new Set;e.addSystemToSchedule(exports.Schedule.Update,kt([je(Jr)],e=>{const s=t.getEntitiesWithComponents([ga]);if(!ns()||ss()){const o=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,ga);s.isOn&&0!==s.group&&t.valid(s.group)&&(o.has(s.group)?(s.isOn=!1,t.insert(e,ga,s)):o.set(s.group,e))}const i=new Map;for(const e of s){const n=t.get(e,ga);if(0!==n.group&&t.valid(n.group)){let t=i.get(n.group);t||(t=[],i.set(n.group,t)),t.push(e)}}for(const n of s){if(xr(t,n,sr,{enabled:!0}),!t.has(n,Yr))continue;const s=t.get(n,Yr),o=t.get(n,ga),r=t.get(n,sr);if(s.justPressed&&r.enabled){const s=o.group,r=0!==s&&t.valid(s)&&t.has(s,ma);if(o.isOn&&r){if(!t.get(s,ma).allowSwitchOff)continue}if(o.isOn=!o.isOn,t.insert(n,ga,o),o.isOn&&r){const o=i.get(s);if(o)for(const s of o){if(s===n)continue;const o=t.get(s,ga);o.isOn&&(o.isOn=!1,t.insert(s,ga,o),e.emit(s,"change"))}}e.emit(n,"change")}let a;if(o.transition)a=lr(o.transition,r.enabled,s.pressed,s.hovered);else{a=dr(o.isOn?o.onColor:o.offColor,r.enabled,s.pressed,s.hovered)}ya(t,n,a)}}for(const e of s){const n=t.get(e,ga);wr(t,n.graphicEntity,e=>{_a(t,e,n.isOn)})}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const wa=new xa,ba=Ji,va=Q("ProgressBar",{value:0,fillEntity:0,direction:Ji.LeftToRight},{entityFields:["fillEntity"]});class Sa{build(e){se("ProgressBar",va);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([],()=>{const e=t.getEntitiesWithComponents([va,nr]);for(const n of e){const e=t.get(n,va),s=Math.max(0,Math.min(1,e.value));wr(t,e.fillEntity,n=>{ar(t,n,e.direction,s)})}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Pa=new Sa,Ma=Q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ta=Q("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});function Ca(e,t,n,s){if(!e.has(t,xe))return{x:n,y:s};const o=e.get(t,xe).entity;if(!e.valid(o)||!e.has(o,de))return{x:n,y:s};const i=e.get(o,de),r=0!==i.worldScale.x?i.worldScale.x:1,a=0!==i.worldScale.y?i.worldScale.y:1,l=Xr(i.worldRotation.z,i.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}class Ea{build(e){se("Draggable",Ma),se("DragState",Ta);const t=e.world,n=e.getResource(Jr);let s=null,o={x:0,y:0},i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(Ut),je(zt)],(e,r)=>{if(ns()&&!ss())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ma,Yr]);let n=null,i=-1/0,r=-1;for(const s of e){if(!t.get(s,Ma).enabled)continue;if(t.get(s,Yr).hovered){let e=0;t.has(s,fe)&&(e=t.get(s,fe).layer);const o=gr(t,s);(e>i||e===i&&o>=r)&&(i=e,r=o,n=s)}}if(null!==n){s=n,o={x:a.x,y:a.y},t.has(n,Ta)||t.insert(n,Ta);const e=t.get(n,Ta),i=t.get(n,de);e.startWorldPos={x:i.worldPosition.x,y:i.worldPosition.y},e.currentWorldPos={x:i.worldPosition.x,y:i.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Ta)){t.get(s,Ta).isDragging=!1}s=null}if(null!==s&&null===i){if(!t.valid(s))return void(s=null);const e=a.x-o.x,l=a.y-o.y,c=Math.sqrt(e*e+l*l),u=t.get(s,Ma);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){i=s,s=null;t.get(i,Ta).isDragging=!0,n.emit(i,"drag_start")}}if(null!==i){if(!t.valid(i)||!t.has(i,Ta))return void(i=null);const s=t.get(i,Ta),o=t.get(i,Ma),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const d=function(e,t,n,s){let o=e.lockX?t.startWorldPos.x:n,i=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(o=Math.max(o,e.constraintMin.x),i=Math.max(i,e.constraintMin.y)),null!==e.constraintMax&&(o=Math.min(o,e.constraintMax.x),i=Math.min(i,e.constraintMax.y)),{x:o,y:i}}(o,s,c,u);c=d.x,u=d.y;const h=s.currentWorldPos.x,p=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,y:u-p},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(i,nr)){const e=t.get(i,nr),n=Ca(t,i,s.deltaWorld.x,s.deltaWorld.y);e.offsetMin.x+=n.x,e.offsetMin.y+=n.y,t.insert(i,nr,e)}else if(t.has(i,de)){const e=Ca(t,i,s.deltaWorld.x,s.deltaWorld.y),n=t.get(i,de);n.position.x+=e.x,n.position.y+=e.y,t.insert(i,de,n)}n.emit(i,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(i,"drag_end"),i=null)}},{name:"DragSystem"}))}}const Aa=new Ea,Ra=Q("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1},{entityFields:["contentEntity"]});function ka(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function Ia(e,t,n,s,o){const i=2/(s=Math.max(1e-4,s)),r=i*o,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+i*l)*o,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-i*c)*a}}class Fa{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){se("ScrollView",Ra);const t=e.world,n=new Pr,s={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([je(Ut),je(zt),je(qe)],(e,o,i)=>{const r=ns()&&!ss(),a=Math.min(i.delta,.05);n.cleanup(t),o.valid&&(s.x=o.worldMouseX,s.y=o.worldMouseY);const l=t.getEntitiesWithComponents([Ra,nr]);for(const i of l){xr(t,i,Hr,{enabled:!0,mode:Wr});const l=t.get(i,Ra),c=t.get(i,nr),u=n.ensureInit(i,()=>({isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN})),d=mr(c,i),h=yr(c,i);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,we)){const e=t.get(l.contentEntity,we).entities;let n=0,s=0,o=0,i=0;for(const r of e){if(!t.valid(r)||!t.has(r,de))continue;const e=t.get(r,de);let a=0,l=0,c=.5,u=.5;if(t.has(r,nr)){const e=t.get(r,nr);a=mr(e,r)||e.size.x,l=yr(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*u,f=e.position.y+l*(1-u);d<n&&(n=d),h>s&&(s=h),p<o&&(o=p),f>i&&(i=f)}0===p&&(p=s-n),0===f&&(f=i-o)}const g=Math.max(0,p-d),m=Math.max(0,f-h);if(!r&&o.valid){xr(t,i,sr,{enabled:!0,blockRaycast:!0});const n=t.has(i,Yr)?t.get(i,Yr):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=ka(l.scrollX,0,g,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=ka(l.scrollY,0,m,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=ka(l.scrollY,0,m,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=ka(l.scrollX,0,g,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>m;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Ia(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Tr&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Tr?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:m,t=Ia(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Tr&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Tr?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,m)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,m+t))}wr(t,l.contentEntity,e=>{if(!t.has(e,de))return;const n=t.get(e,de),s=n.position.x,o=n.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(o-u.lastAppliedY)>.01)&&(u.contentBaseY=o),n.position.x=u.contentBaseX-l.scrollX,n.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=n.position.x,u.lastAppliedY=n.position.y,t.insert(e,de,n)})}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{n.clear()}}}const Ba=new Fa,Ua=Ji,Da=Q("Slider",{value:0,minValue:0,maxValue:1,direction:Ji.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1},{entityFields:["fillEntity","handleEntity"]});function La(e,t,n,s,o,i){const r=mr(s,o)*n.worldScale.x,a=yr(s,o)*n.worldScale.y,l=Xr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,p=d*u-h*c,f=d*c+h*u,g=-s.pivot.x*r,m=-s.pivot.y*a;switch(i){case Ji.LeftToRight:return r>0?(p-g)/r:0;case Ji.RightToLeft:return r>0?1-(p-g)/r:0;case Ji.BottomToTop:return a>0?(f-m)/a:0;case Ji.TopToBottom:return a>0?1-(f-m)/a:0}}function za(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Ji.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=.5,e.anchorMax.x=n,e.anchorMax.y=.5;break;case Ji.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=.5,e.anchorMax.x=1-n,e.anchorMax.y=.5;break;case Ji.BottomToTop:e.anchorMin.x=.5,e.anchorMin.y=n,e.anchorMax.x=.5,e.anchorMax.y=n;break;case Ji.TopToBottom:e.anchorMin.x=.5,e.anchorMin.y=1-n,e.anchorMax.x=.5,e.anchorMax.y=1-n}}class Wa{build(e){se("Slider",Da);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(Ut),je(zt),je(Jr)],(e,n,s)=>{if(!n.valid)return;const o=t.getEntitiesWithComponents([Da,nr]);for(const i of o){const o=t.get(i,Da),r=t.get(i,nr);if(!ns()||ss()){if(t.has(i,de)){xr(t,i,sr,{enabled:!0,blockRaycast:!0}),wr(t,o.handleEntity,e=>{xr(t,e,sr,{enabled:!0,blockRaycast:!1})});const a=t.get(i,de);let l=!1;if(t.has(i,Yr)&&(l=t.get(i,Yr).pressed),wr(t,o.handleEntity,e=>{!l&&t.has(e,Yr)&&(l=t.get(e,Yr).pressed)}),l&&e.isMouseButtonDown(0)){let e=La(n.worldMouseX,n.worldMouseY,a,r,i,o.direction);e=Math.max(0,Math.min(1,e));let l=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(l=Math.round(l));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,l)),t.insert(i,Da,o),o.value!==c&&s.emit(i,"change")}}}const a=o.maxValue-o.minValue,l=a>0?(o.value-o.minValue)/a:0;wr(t,o.fillEntity,e=>{ar(t,e,o.direction,l)}),wr(t,o.handleEntity,e=>{if(!t.has(e,nr))return;const n=t.get(e,nr);za(n,o.direction,l),t.insert(e,nr,n)})}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Ha=new Wa;class $a{build(e){se("Focusable",ra);const t=e.world,n=new aa;e.insertResource(la,n),e.addSystemToSchedule(exports.Schedule.Update,kt([je(Ut),je(Jr)],(e,s)=>{if(ns()&&!ss())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const o=t.getEntitiesWithComponents([ra]);for(const e of o){if(!t.has(e,Yr))continue;t.get(e,Yr).justPressed&&i(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of o){if(!t.valid(n))continue;if(t.has(n,sr)){if(!t.get(n,sr).enabled)continue}const s=t.get(n,ra);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,i(s[l])}function i(e){const o=n.focusedEntity;if(o===e)return;if(null!==o&&t.valid(o)&&t.has(o,ra)){t.get(o,ra).isFocused=!1,s.emit(o,"blur",o)}n.focus(e);t.get(e,ra).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Oa=new $a,Va=Q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Na(){return n()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:o}=t;return{top:n.top,bottom:o-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class ja{build(e){se("SafeArea",Va);const t=e.world;let s=Na(),o=!0,i=0,r=0;if(n()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=Na(),o=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=Na(),o=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,kt([je(zt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===i&&a===r||(i=e.screenH,r=a,o=!0),!o)return;o=!1;const l=u(),c=n()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([Va,nr]);for(const e of d){const n=t.get(e,Va),o=t.get(e,nr),i=n.applyTop?s.top*c:0,r=n.applyBottom?s.bottom*c:0,a=n.applyLeft?s.left*c:0,l=n.applyRight?s.right*c:0;let u=!1;o.offsetMin.x===a&&o.offsetMin.y===r||(o.offsetMin={x:a,y:r},u=!0),o.offsetMax.x===-l&&o.offsetMax.y===-i||(o.offsetMax={x:-l,y:-i},u=!0),u&&t.insert(e,nr,o)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Xa=new ja,Ya=Q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Ga=null;class qa{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null),Ga=null}build(e){se("ListView",Ya);const t=e.world,n=new Map;Ga=n,e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([je(Ut)],e=>{const s=ns()&&!ss();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const o=t.getEntitiesWithComponents([Ya,nr]);for(const i of o){xr(t,i,sr,{enabled:!0,blockRaycast:!0}),xr(t,i,Hr,{enabled:!0,mode:Wr});let o=n.get(i);o||(o={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(i,o));const r=t.get(i,Ya),a=t.get(i,nr),l=yr(a,i),c=mr(a,i);if(!s){const n=t.has(i,Yr)?t.get(i,Yr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of o.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),o.itemEntities.delete(e));for(let e=d;e<h;e++){let n=o.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Ce,{value:`ListItem_${e}`}),t.insert(n,nr,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,i),o.itemEntities.set(e,n),o.renderer&&o.renderer(e,n)),t.has(n,de)){const s=t.get(n,de);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,de,s)}}o.visibleStart=d,o.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{for(const[,e]of n)for(const n of e.itemEntities.values())t.valid(n)&&t.despawn(n);n.clear()}}}const Ka=new qa,Ja=Q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0},{entityFields:["listEntity","labelEntity"]});class Qa{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){se("Dropdown",Ja);const t=e.world,n=new Map,s=new Set;function o(e){wr(t,e,e=>{if(!t.has(e,de))return;const n=t.get(e,de);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,de,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})})}function i(e){if(t.has(e,Ci)){const n=t.get(e,Ci);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&vr(t,e,{...Er})}else if(t.has(e,fe)){const n=t.get(e,fe);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&vr(t,e,{...Er})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const o=n.listEntity;if(0===o||!t.valid(o))return;d(o,!0),u(s);let i=0;if(t.has(e,nr)){const n=t.get(e,nr);i=mr(n,e)||n.size.x}else if(t.has(e,fe)){i=t.get(e,fe).size.x}s.ddWidth=i;const r=30*n.options.length;t.insert(o,nr,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:r},pivot:{x:.5,y:1}}),t.insert(o,Ci,{visualType:Ti.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn();t.insert(r,Ce,{value:`Option_${e}`}),t.insert(r,nr,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:30*-e},offsetMax:{x:0,y:0},size:{x:i,y:30},pivot:{x:.5,y:1}}),t.insert(r,de,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,Ci,{visualType:Ti.SolidColor,texture:0,color:{...Ar},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),t.insert(r,sr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,o),s.optionEntities.push(r);const a=t.spawn();t.insert(a,de,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(a,Fr,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Rr.Left,verticalAlign:kr.Middle,wordWrap:!1,overflow:Ir.Clip,lineHeight:1.2}),t.insert(a,nr,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:30},pivot:{x:.5,y:.5}}),t.setParent(a,r),s.textEntities.push(a)}h(s)}function a(e,t,n){t.isOpen=!1,u(n),d(t.listEntity,!1)}function l(e,t,n,s,o){t.selectedIndex=s,a(0,t,n),o.emit(e,"change")}function c(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Fr))return;const s=t.get(n,Fr);let o={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},i=s.content,r=!1;if(1===o.r&&1===o.g&&1===o.b&&1===o.a&&(o={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];i!==t&&(i=t,r=!0)}r&&t.insert(n,Fr,{content:i,fontSize:s.fontSize,fontFamily:s.fontFamily,color:o,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function u(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function d(e,n){wr(t,e,e=>{t.has(e,sr)&&t.insert(e,sr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),Sr(t,e,n)})}function h(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s))continue;const o=n===e.highlightIndex?{...Cr}:{...Ar};vr(t,s,o)}}function p(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Yr))continue;if(t.get(n,Yr).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,kt([je(Ut),je(Jr)],(e,f)=>{for(const[e,o]of n)t.valid(e)||(u(o),n.delete(e),s.delete(e));const g=ns()&&!ss(),m=t.getEntitiesWithComponents([Ja]);for(const u of m){const m=t.get(u,Ja);let y=n.get(u);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(u,y)),o(m.listEntity),s.has(u)||(i(u),s.add(u)),m.isOpen||d(m.listEntity,!1),c(m),g)continue;xr(t,u,sr,{enabled:!0,blockRaycast:!0});const _=t.has(u,Yr)?t.get(u,Yr):null;if(_?.justPressed&&(m.isOpen?a(u,m,y):r(u,m,y)),m.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,Yr))continue;if(t.get(n,Yr).justPressed){l(u,m,y,e,f);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,Yr))continue;if(t.get(s,Yr).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,h(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=m.options.length-1?y.highlightIndex=0:y.highlightIndex++,h(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=m.options.length-1:y.highlightIndex--,h(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?l(u,m,y,y.highlightIndex,f):e.isKeyPressed("Escape")&&a(u,m,y),e.isMouseButtonPressed(0)&&(_?.hovered||p(y)||a(u,m,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]}),this.cleanup_=()=>{for(const[,e]of n)u(e);n.clear(),s.clear()}}}const Za=new Qa,el=re("LayoutGroup",{direction:0,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:0,reverseOrder:!1});class tl{build(e){se("LayoutGroup",el)}}const nl=new tl,sl=0,ol=1,il=0,rl=1,al=0,ll=0,cl=3,ul=re("FlexContainer",{direction:sl,wrap:il,justifyContent:al,alignItems:cl,alignContent:0,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0}}),dl=re("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,alignSelf:0,margin:{left:0,top:0,right:0,bottom:0},minWidth:-1,minHeight:-1,maxWidth:-1,maxHeight:-1,widthPercent:-1,heightPercent:-1});class hl{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const pl=new hl,fl={primary:{r:.25,g:.56,b:.96,a:1},secondary:{r:.4,g:.4,b:.4,a:1},background:{r:.08,g:.08,b:.08,a:1},surface:{r:.14,g:.14,b:.14,a:1},error:{r:.9,g:.2,b:.2,a:1},text:{r:.93,g:.93,b:.93,a:1},textSecondary:{r:.6,g:.6,b:.6,a:1},border:{r:.3,g:.3,b:.3,a:1},fontFamily:"Arial",fontSize:{xs:10,sm:12,md:14,lg:18,xl:24},spacing:{xs:4,sm:8,md:12,lg:16,xl:24},button:{height:36,color:{r:.25,g:.25,b:.25,a:1},textColor:{r:.93,g:.93,b:.93,a:1},transition:{normalColor:{r:.25,g:.25,b:.25,a:1},hoveredColor:{r:.3,g:.3,b:.3,a:1},pressedColor:{r:.18,g:.18,b:.18,a:1},disabledColor:{r:.15,g:.15,b:.15,a:.6}}},slider:{trackHeight:16,trackColor:{r:.15,g:.15,b:.15,a:1},fillColor:{r:.25,g:.56,b:.96,a:1},handleSize:24,handleColor:{r:1,g:1,b:1,a:1}},toggle:{size:{x:24,y:24},onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1},checkColor:{r:1,g:1,b:1,a:1}},input:{height:36,backgroundColor:{r:.15,g:.15,b:.15,a:1},textColor:{r:1,g:1,b:1,a:1},placeholderColor:{r:.6,g:.6,b:.6,a:1},fontSize:16,padding:6},dropdown:{height:32,backgroundColor:{r:.2,g:.2,b:.2,a:1},itemHeight:28},panel:{backgroundColor:{r:.14,g:.14,b:.14,a:1},padding:12},scrollView:{backgroundColor:{r:.1,g:.1,b:.1,a:1}}},gl=Ne(null,"UITheme");let ml=null;function yl(){return ml??fl}function _l(e,t){const n=e.spawn();if(t.name&&e.insert(n,Ce,{value:t.name}),e.insert(n,de,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},...t.transform}),t.rect&&e.insert(n,nr,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:0,y:0},pivot:{x:.5,y:.5},...t.rect}),t.renderer&&e.insert(n,Ci,{visualType:Ti.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0,...t.renderer}),t.interactable&&e.insert(n,sr,{enabled:!0,blockRaycast:!0,raycastTarget:!0,...t.interactable}),t.text){const s=yl();e.insert(n,Fr,{content:"",fontFamily:s.fontFamily,fontSize:s.fontSize.md,color:{r:1,g:1,b:1,a:1},align:Rr.Left,verticalAlign:kr.Top,wordWrap:!1,overflow:0,lineHeight:1.2,...t.text})}if(t.image&&e.insert(n,tr,{...tr._default,...t.image}),t.flex&&e.insert(n,ul,{direction:sl,wrap:il,justifyContent:al,alignItems:cl,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0},...t.flex}),t.flexItem&&e.insert(n,dl,{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,...t.flexItem}),t.mask&&e.insert(n,Hr,{enabled:!0,mode:Wr,...t.mask}),t.components)for(const[s,o]of t.components)e.insert(n,s,o);return t.parent&&e.setParent(n,t.parent),n}function xl(e,t={}){const n=yl(),{text:s="Button",fontSize:o=n.fontSize.md,size:i={x:120,y:n.button.height},color:r=n.button.color,textColor:a=n.button.textColor,transition:l=null,parent:c}=t,u=_l(e,{name:"ButtonLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:s,fontSize:o,color:a,align:Rr.Center,verticalAlign:kr.Middle}}),d=_l(e,{name:"Button",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Ti.SolidColor,color:r},interactable:{enabled:!0},components:[[qr,{state:0,transition:l}]]});if(e.setParent(u,d),t.events){if(t.onClick){const e=t.onClick;t.events.on(d,"click",()=>e(d))}if(t.onHover){const e=t.onHover;t.events.on(d,"hover_enter",()=>e(d))}}return d}function wl(e,t={}){const n=yl(),{value:s=0,minValue:o=0,maxValue:i=1,direction:r=Ji.LeftToRight,size:a={x:200,y:n.slider.trackHeight},trackColor:l=n.slider.trackColor,fillColor:c=n.slider.fillColor,handleSize:u={x:n.slider.handleSize,y:n.slider.handleSize},handleColor:d=n.slider.handleColor,wholeNumbers:h=!1,parent:p}=t,f=_l(e,{name:"SliderFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Ti.SolidColor,color:c}}),g=_l(e,{name:"SliderHandle",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:u},renderer:{visualType:Ti.SolidColor,color:d},interactable:{enabled:!0,blockRaycast:!0},components:[[Ma,{enabled:!0,dragThreshold:5,lockX:!1,lockY:!0}]]}),m=_l(e,{name:"Slider",parent:p,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Ti.SolidColor,color:l},interactable:{enabled:!0,blockRaycast:!0},components:[[Da,{value:s,minValue:o,maxValue:i,direction:r,wholeNumbers:h,fillEntity:f,handleEntity:g}]]});if(e.setParent(f,m),e.setParent(g,m),t.onChange&&t.events){const n=t.onChange;t.events.on(m,"change",()=>{const t=e.get(m,Da);n(t.value,m)})}return m}function bl(e,t={}){const n=yl(),{isOn:s=!0,size:o=n.toggle.size,onColor:i=n.toggle.onColor,offColor:r=n.toggle.offColor,checkSize:a={x:.58*n.toggle.size.x,y:.58*n.toggle.size.y},checkColor:l=n.toggle.checkColor,group:c=0,transition:u=null,label:d,parent:h}=t,p=_l(e,{name:"ToggleCheck",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Ti.SolidColor,color:l}}),f=_l(e,{name:"Toggle",parent:h,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Ti.SolidColor,color:s?i:r},interactable:{enabled:!0},components:[[ga,{isOn:s,graphicEntity:p,group:c,transition:u,onColor:i,offColor:r}]]});if(e.setParent(p,f),d&&_l(e,{name:"ToggleLabel",parent:f,rect:{anchorMin:{x:1,y:0},anchorMax:{x:1,y:1},offsetMin:{x:8,y:0},size:{x:100,y:0}},text:{content:d,fontSize:n.fontSize.md,align:Rr.Left,verticalAlign:kr.Middle}}),t.onChange&&t.events){const n=t.onChange;t.events.on(f,"change",()=>{const t=e.get(f,ga);n(t.isOn,f)})}return f}function vl(e,t={}){const n=yl(),{value:s=0,size:o={x:200,y:n.slider.trackHeight},direction:i=Ji.LeftToRight,trackColor:r=n.slider.trackColor,fillColor:a=n.primary,parent:l}=t,c=_l(e,{name:"ProgressFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Ti.SolidColor,color:a}}),u=_l(e,{name:"ProgressBar",parent:l,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Ti.SolidColor,color:r},components:[[va,{value:s,fillEntity:c,direction:i}]]});return e.setParent(c,u),u}function Sl(e,t={}){const n=yl(),{size:s={x:300,y:400},contentSize:o={x:300,y:800},horizontal:i=!1,vertical:r=!0,elastic:a=!0,mask:l=!0,parent:c}=t,u=_l(e,{name:"ScrollContent",rect:{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},size:{x:o.x,y:o.y},pivot:{x:.5,y:1}}}),d=_l(e,{name:"ScrollView",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:s},renderer:{visualType:Ti.SolidColor,color:n.scrollView.backgroundColor},mask:l?{mode:Wr,enabled:!0}:void 0,components:[[Ra,{contentEntity:u,horizontalEnabled:i,verticalEnabled:r,contentWidth:o.x,contentHeight:o.y,elastic:a,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,wheelSensitivity:.1}]]});return e.setParent(u,d),d}function Pl(e,t={}){const n=yl(),{placeholder:s="",value:o="",size:i={x:200,y:n.input.height},fontSize:r=n.input.fontSize,backgroundColor:a=n.input.backgroundColor,textColor:l=n.input.textColor,maxLength:c=0,multiline:u=!1,password:d=!1,parent:h}=t,p=_l(e,{name:"TextInput",parent:h,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Ti.SolidColor,color:a},interactable:{enabled:!0},components:[[ia,{value:o,placeholder:s,fontSize:r,fontFamily:n.fontFamily,color:l,backgroundColor:a,placeholderColor:n.input.placeholderColor,padding:n.input.padding,maxLength:c,multiline:u,password:d,readOnly:!1,focused:!1,cursorPos:o.length,dirty:!0}],[ra,{tabIndex:0,isFocused:!1}]]});if(t.events){if(t.onChange){const n=t.onChange;t.events.on(p,"change",()=>{const t=e.get(p,ia);n(t.value,p)})}if(t.onSubmit){const n=t.onSubmit;t.events.on(p,"submit",()=>{const t=e.get(p,ia);n(t.value,p)})}}return p}function Ml(e,t){const n=yl(),{options:s,selectedIndex:o=-1,size:i={x:160,y:n.dropdown.height},fontSize:r=n.fontSize.md,parent:a}=t,l=_l(e,{name:"DropdownLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:(o>=0?s[o]:s[0])??"",fontSize:r,align:Rr.Left,verticalAlign:kr.Middle}}),c=_l(e,{name:"DropdownList",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},size:{x:i.x,y:Math.min(s.length*n.dropdown.itemHeight,200)},pivot:{x:.5,y:1}},renderer:{visualType:Ti.SolidColor,color:n.surface},mask:{mode:Wr,enabled:!0}}),u=_l(e,{name:"Dropdown",parent:a,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Ti.SolidColor,color:n.dropdown.backgroundColor},interactable:{enabled:!0},components:[[Ja,{options:s,selectedIndex:o,isOpen:!1,listEntity:c,labelEntity:l}]]});if(e.setParent(l,u),e.setParent(c,u),t.onChange&&t.events){const n=t.onChange;t.events.on(u,"change",()=>{const t=e.get(u,Ja);n(t.selectedIndex,u)})}return u}function Tl(e,t){const n=yl();return _l(e,{name:"Label",parent:t.parent,rect:t.size?{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size}:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:t.text,fontSize:t.fontSize??n.fontSize.md,color:t.color??n.text,align:t.align??Rr.Left,verticalAlign:t.verticalAlign??kr.Middle}})}function Cl(e,t={}){const n=yl();return _l(e,{name:"Panel",parent:t.parent,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size??{x:300,y:200}},renderer:{visualType:Ti.SolidColor,color:t.color??n.panel.backgroundColor}})}function El(e,t={}){return _l(e,{name:"FlexRow",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:sl,wrap:t.wrap?rl:il,justifyContent:t.justifyContent??al,alignItems:t.alignItems??ll,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}function Al(e,t={}){return _l(e,{name:"FlexColumn",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:ol,wrap:t.wrap?rl:il,justifyContent:t.justifyContent??al,alignItems:t.alignItems??ll,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}const Rl={button:xl,slider:wl,toggle:bl,textInput:Pl,dropdown:Ml,progressBar:vl,label:Tl,panel:Cl,flexRow:El,flexColumn:Al,scrollView:Sl};const kl={spawn:_l,destroy:function e(t,n){if(t.valid(n)){if(t.has(n,we)){const s=[...t.get(n,we).entities];for(const n of s)e(t,n)}t.despawn(n)}},build:function e(t,n,s){let o,i;if("element"===n.type)o=_l(t,{...n,parent:s}),i=o;else{if(o=(0,Rl[n.type])(t,{...n.options??{},parent:s}),"scrollView"===n.type){i=t.get(o,Ra).contentEntity}else i=o}const r=n.children;if(r&&i)for(const n of r)e(t,n,i);return n.ref&&n.ref(o),o},label:Tl,panel:Cl,button:xl,slider:wl,toggle:bl,scrollView:Sl,textInput:Pl,dropdown:Ml,progressBar:vl,flexRow:El,flexColumn:Al};class Il{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let s,o;if("string"==typeof e){const t=(new TextEncoder).encode(e);o=t.length,s=this.raw_._malloc(o+1),this.raw_.HEAPU8.set(t,s),this.raw_.HEAPU8[s+o]=0}else o=e.length,s=this.raw_._malloc(o),this.raw_.HEAPU8.set(e,s);const i=this.api_.loadSkeleton(s,o,t,t.length,n);return this.raw_._free(s),i}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,s,o){this.api_.setAtlasPageTexture(e,t,n,s,o)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,s=0){return!!this.api_.playAnimation(e,t,n,s)}addAnimation(e,t,n=!0,s=0,o=0){return!!this.api_.addAnimation(e,t,n,s,o)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse animations JSON",e),[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse skins JSON",e),[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,s))return this.raw_._free(n),this.raw_._free(s),null;const o=this.raw_.HEAPF32[n>>2],i=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:o,y:i}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,s=t>>2,o={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(t),o}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],s=this.raw_._malloc(8),o=s,i=s+4;for(let s=0;s<t;s++){const t=this.api_.getMeshBatchVertexCount(e,s),r=this.api_.getMeshBatchIndexCount(e,s);if(t<=0||r<=0)continue;const a=8*t*4,l=2*r,c=this.raw_._malloc(a),u=this.raw_._malloc(l);this.api_.getMeshBatchData(e,s,c,u,o,i);const d=new Float32Array(this.raw_.HEAPF32.buffer,c,8*t),h=new Uint16Array(this.raw_.HEAPU8.buffer,u,r);n.push({vertices:new Float32Array(d),indices:new Uint16Array(h),textureId:this.raw_.HEAPU32[o>>2],blendMode:this.raw_.HEAPU32[i>>2]}),this.raw_._free(c),this.raw_._free(u)}return this.raw_._free(s),n}setDefaultMix(e,t){this.api_.setDefaultMix(e,t)}setMixDuration(e,t,n,s){this.api_.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){this.api_.setTrackAlpha(e,t,n)}setAttachment(e,t,n){return!!this.api_.setAttachment(e,t,n)}setIKTarget(e,t,n,s,o){return!!this.api_.setIKTarget(e,t,n,s,o)}setSlotColor(e,t,n,s,o,i){return!!this.api_.setSlotColor(e,t,n,s,o,i)}enableEvents(e){this.api_.enableEvents(e)}collectEvents(e){const t=this.api_.getEventCount(e);if(0===t)return[];const n=this.api_.getEventBuffer(),s=this.raw_.HEAPF32,o=n>>2,i=[];for(let e=0;e<t;e++){const t=o+4*e;i.push({type:s[t],track:s[t+1],floatValue:s[t+2],intValue:s[t+3]})}return this.api_.clearEvents(),i}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(n)}off(e,t,n){const s=this.listeners_.get(e);if(!s)return;const o=s.get(t);o&&o.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}class Fl{constructor(e){this.entities_=new Map,this.cachedFrame_=-1,this.cachedEntries_=[],this.controller_=e}get controller(){return this.controller_}get entityCount(){return this.entities_.size}loadEntity(e,t,n,s,o){const i=this.controller_.loadSkeleton(t,n,o);if(i<0)return console.error(`[ModuleBackend] Failed to load skeleton: ${this.controller_.getLastError()}`),!1;const r=this.controller_.getAtlasPageCount(i);for(let e=0;e<r;e++){const t=this.controller_.getAtlasPageTextureName(i,e),n=s.get(t);n&&this.controller_.setAtlasPageTexture(i,e,n.glId,n.w,n.h)}const a=this.controller_.createInstance(i);return this.entities_.set(e,{skelHandle:i,instanceId:a,skeletonScale:1,flipX:!1,flipY:!1,layer:0}),!0}setEntityProps(e,t){const n=this.entities_.get(e);n&&(void 0!==t.skeletonScale&&(n.skeletonScale=t.skeletonScale),void 0!==t.flipX&&(n.flipX=t.flipX),void 0!==t.flipY&&(n.flipY=t.flipY),void 0!==t.layer&&(n.layer=t.layer))}setAnimation(e,t,n){const s=this.entities_.get(e);s&&this.controller_.play(s.instanceId,t,n)}setSkin(e,t){const n=this.entities_.get(e);n&&this.controller_.setSkin(n.instanceId,t)}getBounds(e){const t=this.entities_.get(e);return t?this.controller_.getBounds(t.instanceId):null}getAnimations(e){const t=this.entities_.get(e);return t?this.controller_.getAnimations(t.instanceId):[]}getSkins(e){const t=this.entities_.get(e);return t?this.controller_.getSkins(t.instanceId):[]}setDefaultMix(e,t){const n=this.entities_.get(e);n&&this.controller_.setDefaultMix(n.skelHandle,t)}setMixDuration(e,t,n,s){const o=this.entities_.get(e);o&&this.controller_.setMixDuration(o.skelHandle,t,n,s)}setTrackAlpha(e,t,n){const s=this.entities_.get(e);s&&this.controller_.setTrackAlpha(s.instanceId,t,n)}setAttachment(e,t,n){const s=this.entities_.get(e);return!!s&&this.controller_.setAttachment(s.instanceId,t,n)}setIKTarget(e,t,n,s,o){const i=this.entities_.get(e);return!!i&&this.controller_.setIKTarget(i.instanceId,t,n,s,o)}setSlotColor(e,t,n,s,o,i){const r=this.entities_.get(e);return!!r&&this.controller_.setSlotColor(r.instanceId,t,n,s,o,i)}enableEvents(e){const t=this.entities_.get(e);t&&this.controller_.enableEvents(t.instanceId)}updateAll(e){for(const t of this.entities_.values())this.controller_.update(t.instanceId,e)}extractAndSubmitMeshes(e,t,n=-1){const s=e.renderer_submitSpineBatchByEntity;if(!s)return;if(this.cachedFrame_!==n){this.cachedEntries_.length=0;for(const[e,t]of this.entities_){const n=this.controller_.extractMeshBatches(t.instanceId);for(const s of n)0!==s.vertices.length&&0!==s.indices.length&&this.cachedEntries_.push({vertices:s.vertices,indices:s.indices,textureId:s.textureId,blendMode:s.blendMode,entity:e,info:t})}this.cachedFrame_=n}if(0===this.cachedEntries_.length)return;let o=0,i=0;for(const e of this.cachedEntries_)o+=e.vertices.byteLength,i+=e.indices.byteLength;const r=e._malloc(o),a=e._malloc(i);let l=0,c=0;for(const n of this.cachedEntries_){const o=r+l,i=a+c;e.HEAPF32.set(n.vertices,o>>2),new Uint16Array(e.HEAPU8.buffer,i,n.indices.length).set(n.indices),s.call(e,t,o,n.vertices.length/8,i,n.indices.length,n.textureId,n.blendMode,n.entity,n.info.skeletonScale,n.info.flipX,n.info.flipY,n.info.layer,0),l+=n.vertices.byteLength,c+=n.indices.byteLength}e._free(r),e._free(a)}removeEntity(e){const t=this.entities_.get(e);t&&(this.controller_.destroyInstance(t.instanceId),this.controller_.unloadSkeleton(t.skelHandle),this.entities_.delete(e))}shutdown(){for(const e of this.entities_.values())this.controller_.destroyInstance(e.instanceId),this.controller_.unloadSkeleton(e.skelHandle);this.entities_.clear()}}class Bl{constructor(e,t){this.backends_=new Map,this.loadingBackends_=new Map,this.entityVersions_=new Map,this.coreModule_=e,this.factories_=t}static detectVersion(e){const t=function(e){if(e.length<10)return null;let t=8;const{value:n,bytesRead:s}=Ul(e,t);if(t+=s,n<=1||t+n-1>e.length)return null;const o=(new TextDecoder).decode(e.subarray(t,t+n-1));return o.startsWith("4.2")?"4.2":o.startsWith("4.1")?"4.1":null}(e);return t||function(e){if(e.length<4)return null;let t=0;const{value:n,bytesRead:s}=Ul(e,t);t+=s,n>0&&(t+=n-1);if(t>=e.length)return null;const{value:o,bytesRead:i}=Ul(e,t);if(t+=i,o<=1||t+o-1>e.length)return null;const r=(new TextDecoder).decode(e.subarray(t,t+o-1));return r.startsWith("3.")?"3.8":null}(e)}static detectVersionJson(e){const t=e.match(/"spine"\s*:\s*"(\d+\.\d+)/);return t?t[1].startsWith("4.2")?"4.2":t[1].startsWith("4.1")?"4.1":t[1].startsWith("3.")?"3.8":null:null}async loadEntity(e,t,n,s,o){const i="string"==typeof t?Bl.detectVersionJson(t):Bl.detectVersion(t);if(!i)return null;if("4.2"===i&&!this.factories_.has("4.2"))return this.entityVersions_.set(e,"4.2"),"4.2";this.coreModule_.spine_setNeedsReload?.(o,e,!1);const r=await this.ensureBackend(i);if(!r)return console.error(`[SpineManager] Failed to create backend for version ${i}`),null;const a=t instanceof Uint8Array;return r.loadEntity(e,t,n,s,a)?(this.entityVersions_.set(e,i),i):(console.error(`[SpineManager] Failed to load entity ${e} into backend ${i}`),null)}updateAnimations(e){for(const t of this.backends_.values())t.updateAll(e)}submitMeshes(e,t=-1){for(const n of this.backends_.values())n.extractAndSubmitMeshes(this.coreModule_,e,t)}removeEntity(e){const t=this.entityVersions_.get(e);if(!t)return void this.entityVersions_.delete(e);const n=this.backends_.get(t);n&&n.removeEntity(e),this.entityVersions_.delete(e)}getEntityVersion(e){return this.entityVersions_.get(e)}hasModuleBackend(e){return this.backends_.has(e)}getModuleBackend(e){return this.backends_.get(e)}setAnimation(e,t,n){const s=this.entityVersions_.get(e);if(!s)return;const o=this.backends_.get(s);o&&o.setAnimation(e,t,n)}setSkin(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setSkin(e,t)}setEntityProps(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setEntityProps(e,t)}getBounds(e){const t=this.entityVersions_.get(e);if(!t)return null;const n=this.backends_.get(t);return n?n.getBounds(e):null}getAnimations(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getAnimations(e):[]}getSkins(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getSkins(e):[]}setDefaultMix(e,t){const n=this.getEntityBackend_(e);n&&n.setDefaultMix(e,t)}setMixDuration(e,t,n,s){const o=this.getEntityBackend_(e);o&&o.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){const s=this.getEntityBackend_(e);s&&s.setTrackAlpha(e,t,n)}setAttachment(e,t,n){const s=this.getEntityBackend_(e);return!!s&&s.setAttachment(e,t,n)}setIKTarget(e,t,n,s,o){const i=this.getEntityBackend_(e);return!!i&&i.setIKTarget(e,t,n,s,o)}setSlotColor(e,t,n,s,o,i){const r=this.getEntityBackend_(e);return!!r&&r.setSlotColor(e,t,n,s,o,i)}enableEvents(e){const t=this.getEntityBackend_(e);t&&t.enableEvents(e)}hasInstance(e){return this.entityVersions_.has(e)}shutdown(){for(const e of this.backends_.values())e.shutdown();this.backends_.clear(),this.loadingBackends_.clear(),this.entityVersions_.clear()}getEntityBackend_(e){const t=this.entityVersions_.get(e);if(t)return this.backends_.get(t)}async ensureBackend(e){const t=this.backends_.get(e);if(t)return t;const n=this.loadingBackends_.get(e);if(n)return n;const s=this.factories_.get(e);if(!s)return console.warn(`[SpineManager] No module factory for version ${e}`),null;const o=(async()=>{try{const t=await s(),n=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"]),setDefaultMix:t("spine_setDefaultMix",null,["number","number"]),setMixDuration:t("spine_setMixDuration",null,["number","string","string","number"]),setTrackAlpha:t("spine_setTrackAlpha",null,["number","number","number"]),enableEvents:t("spine_enableEvents",null,["number"]),getEventCount:t("spine_getEventCount","number",["number"]),getEventBuffer:t("spine_getEventBuffer","number",[]),clearEvents:t("spine_clearEvents",null,[]),setAttachment:t("spine_setAttachment","number",["number","string","string"]),setIKTarget:t("spine_setIKTarget","number",["number","string","number","number","number"]),setSlotColor:t("spine_setSlotColor","number",["number","string","number","number","number","number"])}}(t),o=new Il(t,n),i=new Fl(o);return this.backends_.set(e,i),i}catch(t){return console.error(`[SpineManager] Failed to load WASM module for version ${e}:`,t),null}finally{this.loadingBackends_.delete(e)}})();return this.loadingBackends_.set(e,o),o}}function Ul(e,t){let n=0,s=0,o=0;do{const i=e[t+o++];if(n|=(127&i)<<s,s+=7,!(128&i))break}while(s<35);return{value:n,bytesRead:o}}async function Dl(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Ll=Ne({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),zl={r:.2,g:.4,b:1,a:.7},Wl={r:.2,g:1,b:.2,a:.7},Hl={r:.2,g:1,b:1,a:.7},$l={r:1,g:1,b:.2,a:.5},Ol={r:1,g:.2,b:.2,a:.8},Vl={r:1,g:.2,b:.2,a:1},Nl=1.5,jl=16;function Xl(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Yl(e){switch(e){case Oe.Static:return zl;case Oe.Kinematic:return Hl;default:return Wl}}function Gl(e,t,n,s,o,i){const r=Math.cos(o),a=Math.sin(o),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)So.line(l[e],l[(e+1)%4],i,Nl)}function ql(e,t,n,s,o,i){const r=Math.cos(o),a=Math.sin(o),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),d=l(-n,-s),h=l(n,-s);So.line(c,d,i,Nl),So.line(u,h,i,Nl);for(let e=0;e<jl;e++){const t=e/jl*Math.PI,o=(e+1)/jl*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(o),s+n*Math.sin(o));So.line(r,a,i,Nl)}for(let e=0;e<jl;e++){const t=Math.PI+e/jl*Math.PI,o=Math.PI+(e+1)/jl*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(o),-s+n*Math.sin(o));So.line(r,a,i,Nl)}}function Kl(e,t,n,s){const o=e+.5*n,i=t+.5*s;So.line({x:e,y:t},{x:o,y:i},Ol,Nl);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=o-6*(l*Math.cos(a)-c*Math.sin(a)),d=i-6*(l*Math.sin(a)+c*Math.cos(a)),h=o-6*(l*Math.cos(a)+c*Math.sin(a)),p=i-6*(-l*Math.sin(a)+c*Math.cos(a));So.line({x:o,y:i},{x:u,y:d},Ol,Nl),So.line({x:o,y:i},{x:h,y:p},Ol,Nl)}function Jl(e,t,n){const s=e.getResource(Ll);if(!s||!s.enabled)return;const o=function(e){const t=e.world.getEntitiesWithComponents([ye]);for(const n of t){const t=e.world.get(n,ye);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=e.world.getEntitiesWithComponents([Re,de]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of i){const n=e.world.get(t,Re);if(!n.enabled)continue;const i=e.world.get(t,de),a=i.worldPosition.x,l=i.worldPosition.y,c=Xl(i.worldRotation);if(s.showColliders){if(e.world.has(t,ke)){const s=e.world.get(t,ke),i=s.isSensor?$l:Yl(n.bodyType),r=s.offset.x*o,u=s.offset.y*o,d=Math.cos(c),h=Math.sin(c);Gl(a+r*d-u*h,l+r*h+u*d,s.halfExtents.x*o,s.halfExtents.y*o,c,i)}if(e.world.has(t,Ie)){const s=e.world.get(t,Ie),i=s.isSensor?$l:Yl(n.bodyType),r=s.offset.x*o,u=s.offset.y*o,d=Math.cos(c),h=Math.sin(c),p=a+r*d-u*h,f=l+r*h+u*d;So.circleOutline({x:p,y:f},s.radius*o,i,Nl,32)}if(e.world.has(t,Fe)){const s=e.world.get(t,Fe),i=s.isSensor?$l:Yl(n.bodyType),r=s.offset.x*o,u=s.offset.y*o,d=Math.cos(c),h=Math.sin(c);ql(a+r*d-u*h,l+r*h+u*d,s.radius*o,s.halfHeight*o,c,i)}if(e.world.has(t,Be)){const s=e.world.get(t,Be),i=s.isSensor?$l:Yl(n.bodyType),r=Math.cos(c),u=Math.sin(c),d=a+(s.point1.x*o*r-s.point1.y*o*u),h=l+(s.point1.x*o*u+s.point1.y*o*r),p=a+(s.point2.x*o*r-s.point2.y*o*u),f=l+(s.point2.x*o*u+s.point2.y*o*r);So.line({x:d,y:h},{x:p,y:f},i,Nl)}if(e.world.has(t,Ue)){const s=e.world.get(t,Ue),i=s.isSensor?$l:Yl(n.bodyType),r=Math.cos(c),u=Math.sin(c),d=s.vertices;for(let e=0;e<d.length;e++){const t=d[e],n=d[(e+1)%d.length],s=a+(t.x*o*r-t.y*o*u),c=l+(t.x*o*u+t.y*o*r),h=a+(n.x*o*r-n.y*o*u),p=l+(n.x*o*u+n.y*o*r);So.line({x:s,y:c},{x:h,y:p},i,Nl)}}if(e.world.has(t,De)){const s=e.world.get(t,De),i=Yl(n.bodyType),r=Math.cos(c),u=Math.sin(c),d=s.points,h=s.isLoop?d.length:d.length-1;for(let e=0;e<h;e++){const t=d[e],n=d[(e+1)%d.length],s=a+(t.x*o*r-t.y*o*u),c=l+(t.x*o*u+t.y*o*r),h=a+(n.x*o*r-n.y*o*u),p=l+(n.x*o*u+n.y*o*r);So.line({x:s,y:c},{x:h,y:p},i,Nl)}}}if(s.showVelocity&&r&&n.bodyType===Oe.Dynamic){const e=r.getLinearVelocity(t);Kl(a,l,e.x*o,e.y*o)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)So.circle({x:e.contactX,y:e.contactY},3,Vl,!0,32)}}const Ql=Ne({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Zl=Ne(null,"PhysicsAPI");function ec(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}class tc{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/30,subStepCount:t.subStepCount??4,contactHertz:t.contactHertz??30,contactDampingRatio:t.contactDampingRatio??10,contactSpeed:t.contactSpeed??3,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(Ql,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Set,s=new Set,o=new Map;let i=-1;const r=Dl(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount,this.config_.contactHertz,this.config_.contactDampingRatio,this.config_.contactSpeed);const a=function(e){const t=e.world.getEntitiesWithComponents([ye]);for(const n of t){const t=e.world.get(n,ye);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),l=1/a,c=e.world;c.onDespawn(e=>{n.has(e)&&(r._physics_destroyJoint(e),n.delete(e)),t.has(e)&&(r._physics_destroyBody(e),t.delete(e),o.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,kt([je(qe)],u=>{if(ns()&&!ss())return;const d=c.getEntitiesWithComponents([Re,de]),h=new Set;for(const n of d)if(h.add(n),t.has(n)){if(c.isChangedSince(n,Re,i)){const e=c.get(n,Re),t=o.get(n);!t||t.bodyType===e.bodyType&&t.gravityScale===e.gravityScale&&t.linearDamping===e.linearDamping&&t.angularDamping===e.angularDamping&&t.fixedRotation===e.fixedRotation&&t.bullet===e.bullet||(r._physics_updateBodyProperties(n,e.bodyType,e.gravityScale,e.linearDamping,e.angularDamping,e.fixedRotation?1:0,e.bullet?1:0),t.bodyType=e.bodyType,t.gravityScale=e.gravityScale,t.linearDamping=e.linearDamping,t.angularDamping=e.angularDamping,t.fixedRotation=e.fixedRotation,t.bullet=e.bullet)}const e=o.get(n);if(e&&e.bodyType===Oe.Kinematic){const e=c.get(n,de),t=ec(e.worldRotation);r._physics_setBodyTransform(n,e.worldPosition.x*l,e.worldPosition.y*l,t)}}else{const i=c.get(n,Re);if(!i.enabled)continue;const a=c.get(n,de),u=c.has(n,xe),d=u?a.worldPosition.x:a.position.x,h=u?a.worldPosition.y:a.position.y,p=ec(u?a.worldRotation:a.rotation);r._physics_createBody(n,i.bodyType,d*l,h*l,p,i.gravityScale,i.linearDamping,i.angularDamping,i.fixedRotation?1:0,i.bullet?1:0),oc(e,r,n,this.config_.collisionLayerMasks),t.add(n),c.has(n,xe)&&s.add(n),o.set(n,{bodyType:i.bodyType,gravityScale:i.gravityScale,linearDamping:i.linearDamping,angularDamping:i.angularDamping,fixedRotation:i.fixedRotation,bullet:i.bullet})}i=c.getWorldTick();for(const e of t)h.has(e)||(r._physics_destroyBody(e),t.delete(e),o.delete(e));!function(e,t,n,s,o){const i=e.getEntitiesWithComponents([Le,Re]);for(const r of i){if(s.has(r))continue;if(!n.has(r))continue;const i=e.get(r,Le);if(!i.enabled)continue;const a=i.connectedEntity;n.has(a)&&(t._physics_createRevoluteJoint(a,r,i.anchorA.x*o,i.anchorA.y*o,i.anchorB.x*o,i.anchorB.y*o,i.enableMotor?1:0,i.motorSpeed,i.maxMotorTorque,i.enableLimit?1:0,i.lowerAngle,i.upperAngle,i.collideConnected?1:0),s.add(r))}for(const i of e.getEntitiesWithComponents([ze,Re])){if(s.has(i))continue;if(!n.has(i))continue;const r=e.get(i,ze);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createDistanceJoint(a,i,r.anchorA.x*o,r.anchorA.y*o,r.anchorB.x*o,r.anchorB.y*o,r.length*o,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.minLength*o,r.maxLength*o,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(i))}for(const i of e.getEntitiesWithComponents([We,Re])){if(s.has(i))continue;if(!n.has(i))continue;const r=e.get(i,We);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createPrismaticJoint(a,i,r.anchorA.x*o,r.anchorA.y*o,r.anchorB.x*o,r.anchorB.y*o,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*o,r.upperTranslation*o,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(i))}for(const i of e.getEntitiesWithComponents([He,Re])){if(s.has(i))continue;if(!n.has(i))continue;const r=e.get(i,He);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWeldJoint(a,i,r.anchorA.x*o,r.anchorA.y*o,r.anchorB.x*o,r.anchorB.y*o,r.linearHertz,r.angularHertz,r.linearDampingRatio,r.angularDampingRatio,r.collideConnected?1:0),s.add(i))}for(const i of e.getEntitiesWithComponents([$e,Re])){if(s.has(i))continue;if(!n.has(i))continue;const r=e.get(i,$e);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWheelJoint(a,i,r.anchorA.x*o,r.anchorA.y*o,r.anchorB.x*o,r.anchorB.y*o,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*o,r.upperTranslation*o,r.enableMotor?1:0,r.maxMotorTorque,r.motorSpeed,r.collideConnected?1:0),s.add(i))}}(c,r,t,n,l),t.size>0&&u.delta>0&&r._physics_step(u.delta),function(e,t,n,s){const o=t._physics_getDynamicBodyCount();if(0===o)return;const i=t._physics_getDynamicBodyTransforms(),r=i>>2,a=t.HEAPU32,l=t.HEAPF32,c=e.world.getCppRegistry();if(!c)return;const u=e.world.getWasmModule(),d=s.size>0;if(!d&&u?.registry_batchSyncPhysicsTransforms){const e=o*ac,s=u._malloc(e);return u.HEAPU8.set(new Uint8Array(t.HEAPU8.buffer,i,e),s),u.registry_batchSyncPhysicsTransforms(c,s,o,n),void u._free(s)}const h=u?.getTransformPtr?e=>u.getTransformPtr(c,e):null,p=u?.HEAPF32,f=h&&p?null:c.addTransform.bind(c),g=ic;for(let t=0;t<o;t++){const o=r+t*rc,i=a[o];let c=l[o+1]*n,u=l[o+2]*n,m=l[o+3];if(d&&s.has(i)){const t=e.world.get(i,xe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,de)){const n=e.world.get(t.entity,de),s=ec(n.worldRotation),o=u,i=c-n.worldPosition.x,r=o-n.worldPosition.y,a=Math.cos(-s),l=Math.sin(-s);c=(i*a-r*l)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*l+r*a)/(0!==n.worldScale.y?n.worldScale.y:1),m-=s}}const y=.5*m,_=Math.cos(y),x=Math.sin(y);if(h&&p){const e=h(i);if(e){const t=e>>2;p[t]=c,p[t+1]=u,p[t+2]=0,p[t+3]=0,p[t+4]=0,p[t+5]=x,p[t+6]=_,p[t+7]=1,p[t+8]=1,p[t+9]=1,p[t+10]=c,p[t+11]=u,p[t+12]=0,p[t+13]=0,p[t+14]=0,p[t+15]=x,p[t+16]=_,p[t+17]=1,p[t+18]=1,p[t+19]=1;continue}}g.position.x=c,g.position.y=u,g.rotation.w=_,g.rotation.x=0,g.rotation.y=0,g.rotation.z=x,g.worldPosition.x=c,g.worldPosition.y=u,g.worldRotation.w=_,g.worldRotation.x=0,g.worldRotation.y=0,g.worldRotation.z=x,f(i,g)}}(e,r,a,s),function(e,t,n){t._physics_collectEvents();const s=[],o=t._physics_getCollisionEnterCount();if(o>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<o;i++){const o=e+6*i;s.push({entityA:t.HEAPU32[o],entityB:t.HEAPU32[o+1],normalX:t.HEAPF32[o+2],normalY:t.HEAPF32[o+3],contactX:t.HEAPF32[o+4]*n,contactY:t.HEAPF32[o+5]*n})}}const i=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Ql,{collisionEnters:s,collisionExits:i,sensorEnters:a,sensorExits:c})}(e,r,a)},{name:"PhysicsSystem"})),e.physicsModule=r,e.insertResource(Zl,lc._fromModule(r)),function(e,t,n){e.insertResource(Ll,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Eo("physics-debug-draw",()=>{Jl(e,t,n)})}(e,Zl,Ql),e.setFixedTimestep(this.config_.fixedTimestep)});r.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=r}}const nc=16;function sc(e,t,n){if(!n)return t;for(let t=0;t<nc;t++)if(e===1<<t)return n[t];return t}function oc(e,t,n,s){const o=e.world;if(o.has(n,ke)){const e=o.get(n,ke),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s);t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.radius??.05,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r)}if(o.has(n,Ie)){const e=o.get(n,Ie),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s);t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r)}if(o.has(n,Fe)){const e=o.get(n,Fe),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r)}if(o.has(n,Be)){const e=o.get(n,Be),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s);t._physics_addSegmentShape(n,e.point1.x,e.point1.y,e.point2.x,e.point2.y,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r)}if(o.has(n,Ue)){const e=o.get(n,Ue),i=e.categoryBits??1,r=sc(i,e.maskBits??65535,s),a=e.vertices,l=Math.min(a.length,8),c=2*l*4,u=t._malloc(c),d=u>>2;for(let e=0;e<l;e++)t.HEAPF32[d+2*e]=a[e].x,t.HEAPF32[d+2*e+1]=a[e].y;t._physics_addPolygonShape(n,u,l,e.radius??0,e.density,e.friction,e.restitution,e.isSensor?1:0,i,r),t._free(u)}if(o.has(n,De)){const e=o.get(n,De),s=e.points;if(s.length<4)return;const i=2*s.length*4,r=t._malloc(i),a=r>>2;for(let e=0;e<s.length;e++)t.HEAPF32[a+2*e]=s[e].x,t.HEAPF32[a+2*e+1]=s[e].y;t._physics_addChainShape(n,r,s.length,e.isLoop?1:0,e.friction,e.restitution,e.categoryBits??1,e.maskBits??65535),t._free(r)}}const ic={position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}},rc=4,ac=4*rc;class lc{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(lc.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)}createRevoluteJoint(e,t,n,s,o){const i=o??{};return 0!==this.module_._physics_createRevoluteJoint(e,t,n.x,n.y,s.x,s.y,i.enableMotor?1:0,i.motorSpeed??0,i.maxMotorTorque??0,i.enableLimit?1:0,i.lowerAngle??0,i.upperAngle??0,i.collideConnected?1:0)}destroyJoint(e){this.module_._physics_destroyJoint(e)}setRevoluteMotorSpeed(e,t){this.module_._physics_setRevoluteMotorSpeed(e,t)}setRevoluteMaxMotorTorque(e,t){this.module_._physics_setRevoluteMaxMotorTorque(e,t)}enableRevoluteMotor(e,t){this.module_._physics_enableRevoluteMotor(e,t?1:0)}enableRevoluteLimit(e,t){this.module_._physics_enableRevoluteLimit(e,t?1:0)}setRevoluteLimits(e,t,n){this.module_._physics_setRevoluteLimits(e,t,n)}getRevoluteAngle(e){return this.module_._physics_getRevoluteAngle(e)}getRevoluteMotorTorque(e){return this.module_._physics_getRevoluteMotorTorque(e)}raycast(e,t,n,s=65535,o=100){const i=1/o,r=this.module_._physics_raycast(e.x*i,e.y*i,t.x,t.y,n*i,s);if(0===r)return[];const a=this.module_._physics_getRaycastBuffer()>>2,l=[];for(let e=0;e<r;e++){const t=a+6*e;l.push({entity:this.module_.HEAPU32[t],point:{x:this.module_.HEAPF32[t+1]*o,y:this.module_.HEAPF32[t+2]*o},normal:{x:this.module_.HEAPF32[t+3],y:this.module_.HEAPF32[t+4]},fraction:this.module_.HEAPF32[t+5]})}return l.sort((e,t)=>e.fraction-t.fraction),l}overlapCircle(e,t,n=65535,s=100){const o=1/s,i=this.module_._physics_overlapCircle(e.x*o,e.y*o,t*o,n);if(0===i)return[];const r=this.module_._physics_getOverlapBuffer()>>2,a=[],l=new Set;for(let e=0;e<i;e++){const t=this.module_.HEAPU32[r+e];l.has(t)||(l.add(t),a.push(t))}return a}setAwake(e,t){this.module_._physics_setAwake(e,t?1:0)}isAwake(e){return 0!==this.module_._physics_isAwake(e)}static setDebugDraw(e,t){const n=e.getResource(Ll);n&&(n.enabled=t,e.insertResource(Ll,n))}static setDebugDrawConfig(e,t){const n=e.getResource(Ll);n&&e.insertResource(Ll,{...n,...t})}}const cc={nearest:0,linear:1},uc={repeat:0,clamp:1,mirror:2};function dc(e,t,n=!0,s){const o=e.getResourceManager(),i=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,i),s&&(s.filterMode||s.wrapMode)&&o.createTextureEx){const e=cc[s.filterMode??"linear"]??1,a=uc[s.wrapMode??"clamp"]??1;r=o.createTextureEx(t.width,t.height,i,t.pixels.length,1,n,e,a)}else r=o.createTexture(t.width,t.height,i,t.pixels.length,1,n);return e._free(i),r}function hc(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 pc(e,t,n){const s=e.FS;if(!s)return!1;try{return function(e,t){const n=e.FS;if(!n)return;const s=t.substring(0,t.lastIndexOf("/"));if(!s)return;const o=s.split("/").filter(e=>e);let i="";for(const e of o){i+="/"+e;try{n.mkdir(i)}catch{}}}(e,t),s.writeFile(t,n),!0}catch(e){return console.warn(`[Runtime] Failed to write virtual FS: ${t}`,e),!1}}async function fc(e){const{app:t,module:n,sceneData:s,provider:o,spineManager:i,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},o=t.textureImporterSettings;for(const i of t.entities)for(const t of i.components){const i=Os(t.type);for(const r of i){if("texture"!==r.type)continue;const i=t.data[r.field];if("string"==typeof i&&i&&void 0===s[i])try{const t=o?.[i];s[i]=dc(e,await n.loadPixels(i),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${i}`,e),s[i]=0}}}return s}(n,s,o);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const o=n[e];if(o&&o>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(o,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);const d=await async function(e,t,n,s){const o=new Set,i=new Map;for(const r of t.entities)for(const t of r.components){const r=Vs(t.type);if(!r||!t.data)continue;const a=t.data[r.skeletonField],l=t.data[r.atlasField];if(!a||!l)continue;const c=`${a}:${l}`;if(o.has(c))continue;o.add(c);const u=n.resolvePath(l);try{const t=await n.readText(l),o=n.resolvePath(a),r="binary"===b(o)?.contentType?await n.readBinary(a):await n.readText(a),d=s?"string"==typeof r?Bl.detectVersionJson(r):Bl.detectVersion(r):null,h=hc(t),p=u.substring(0,u.lastIndexOf("/")),f=e.getResourceManager(),g=new Map;for(const t of h){const s=p+"/"+t;try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),i=dc(e,o,!1);f.registerTextureWithPath(i,s),g.set(t,{glId:f.getTextureGLId(i),w:o.width,h:o.height})}catch(e){console.warn(`[Spine] Failed to load texture: ${s}`,e)}}(!d||"4.2"===d)&&(pc(e,u,t),pc(e,o,r)),i.set(c,{version:d,skelData:r,atlasText:t,textures:g})}catch(e){console.warn(`[Runtime] Failed to load spine asset: skel=${a} atlas=${l}`,e)}}return i}(n,s,o,i);if(r){const e={gravity:a?.gravity??{...z},fixedTimestep:a?.fixedTimestep??W,subStepCount:a?.subStepCount??4,contactHertz:a?.contactHertz??120,contactDampingRatio:a?.contactDampingRatio??10,contactSpeed:a?.contactSpeed??10};new tc("",e,()=>Promise.resolve(r)).build(t)}const h=await async function(e,t,n){const s={};for(const o of t.entities)for(const t of o.components){const o=Os(t.type).find(e=>"font"===e.type);if(!o)continue;const i=t.data[o.field];if("string"==typeof i&&i&&void 0===s[i])try{let t,o;const r=b(i);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(i)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[i]=0;continue}const a=i.substring(0,i.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(i),o=i.substring(0,i.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[i]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=dc(e,c,!1),d=e.getResourceManager();s[i]=d.loadBitmapFont(t,u,c.width,c.height)}catch(e){console.warn(`[Runtime] Failed to load bitmap font: ${i}`,e),s[i]=0}}return s}(n,s,o),p=await async function(e,t){const n={},s={};for(const o of e.entities)for(const e of o.components){if(!e.data)continue;const o=Os(e.type).find(e=>"material"===e.type);if(!o)continue;const i=e.data[o.field];if("string"==typeof i&&i&&void 0===n[i])try{const e=JSON.parse(await t.readText(i));if(!e.vertexSource||!e.fragmentSource){n[i]=0;continue}const o=e.vertexSource+e.fragmentSource;let r=s[o];r||(r=Gt.createShader(e.vertexSource,e.fragmentSource),s[o]=r),n[i]=Gt.createFromAsset(e,r)}catch(e){console.warn(`[Runtime] Failed to load material: ${i}`,e),n[i]=0}}return n}(s,o);await async function(e,t,n){const s=new Set;for(const o of t.entities)for(const t of o.components){const o=Os(t.type);for(const i of o){if("anim-clip"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&!s.has(o)){s.add(o);try{const t=await n.readText(o),s=JSON.parse(t),i=rn(s),r=new Map;for(const t of i)try{const s=await n.loadPixels(t);r.set(t,dc(e,s))}catch(e){console.warn(`[Runtime] Failed to load anim texture: ${t}`,e),r.set(t,0)}cn(an(o,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${o}`,e)}}}}}(n,s,o),await async function(e,t,n){const s=new Set;for(const o of t.entities)for(const t of o.components){const o=Os(t.type);for(const i of o){if("tilemap"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&!s.has(o)){s.add(o);try{const t=await n.readText(o),s=An(JSON.parse(t));if(!s)continue;const i=[];for(const t of s.tilesets){const s=Rn(o,t.image);let r=0;try{const t=await n.loadPixels(s);r=dc(e,t),gn(r,t.width,t.height)}catch(e){console.warn(`[Runtime] Failed to load tileset texture: ${s}`,e)}i.push({textureHandle:r,columns:t.columns})}_n(o,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:i})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${o}`,e)}}}}}(n,s,o),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=Os(e.type);for(const o of t){if("audio"!==o.type)continue;const t=e.data[o.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await hn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await hn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,o),function(e,t,n,s){const o={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Os(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=o[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,h,p);const f=Ys(t.world,s),g=t.world.getCppRegistry();if(g&&n.transform_update(g),i&&g&&d.size>0)for(const e of s.entities)for(const t of e.components){const n=Vs(t.type);if(!n||!t.data)continue;const s=t.data[n.skeletonField],o=t.data[n.atlasField];if(!s||!o)continue;const r=`${s}:${o}`,a=d.get(r);if(!a||!a.version||"4.2"===a.version)continue;const l=f.get(e.id);if(void 0===l)continue;await i.loadEntity(l,a.skelData,a.atlasText,a.textures,g),i.setEntityProps(l,{skeletonScale:t.data.skeletonScale??1,flipX:t.data.flipX??!1,flipY:t.data.flipY??!1,layer:t.data.layer??0});const c=t.data.skin;c&&i.setSkin(l,c);const u=t.data.animation;u&&i.setAnimation(l,u,!1!==t.data.loop)}if(c&&t.hasResource(Ii))for(const e of f.values())t.world.insert(e,Ee,{scene:c,persistent:!1});if(l){const e=t.getResource(Zs);e&&e.setAddressableManifest(l)}}function gc(e,t,n){return{name:e,async setup(){await fc({...n,sceneData:t,sceneName:e})}}}async function mc(e){const{app:t,firstScene:n,aspectRatio:s}=e;Li(t);const o={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,spineManager:e.spineManager,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},i=t.getResource(Ii);for(const t of e.scenes)i.register(gc(t.name,t.data,o));n&&(i.setInitial(n),await i.load(n)),void 0!==s&&Js(t.world,s)}class yc{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const o of e.entities)for(const e of o.components){if(!e.data)continue;const o=Vs(e.type);if(o){const s=e.data[o.skeletonField],i=e.data[o.atlasField];s&&("binary"===b(s)?.contentType?n.add(s):t.add(s)),i&&t.add(i)}const i=Os(e.type);for(const o of i){const i=e.data[o.field];"string"==typeof i&&i&&("font"===o.type?(s.add(i),t.add(i)):"material"===o.type||"anim-clip"===o.type||"tilemap"===o.type?t.add(i):"audio"===o.type&&n.add(i))}}const o=[];for(const e of t)o.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)o.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(o);const i=[];for(const e of s){const t=b(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||i.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}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(),o=await createImageBitmap(s),i=new OffscreenCanvas(o.width,o.height).getContext("2d");i.drawImage(o,0,0);const r=i.getImageData(0,0,o.width,o.height);return o.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}let _c=null;const xc={update(e,t){_c?.spine_update?.(e._cpp,t)},play:(e,t,n=!0,s=0)=>_c?.spine_play?.(e,t,n,s)??!1,addAnimation:(e,t,n=!0,s=0,o=0)=>_c?.spine_addAnimation?.(e,t,n,s,o)??!1,setSkin:(e,t)=>_c?.spine_setSkin?.(e,t)??!1,getBonePosition:(e,t)=>_c?.spine_getBonePosition?.(e,t)??null,hasInstance:e=>_c?.spine_hasInstance?.(e)??!1,reloadAssets(e){_c?.spine_reloadAssets?.(e._cpp)},getAnimations:e=>_c?.spine_getAnimations?.(e)??[],getSkins:e=>_c?.spine_getSkins?.(e)??[]};class wc{constructor(e){this.app_=null,e instanceof Bl?(this.spineManager_=e,this.provider_=null):(this.spineManager_=null,this.provider_=e??null)}get spineManager(){return this.spineManager_}setSpineManager(e){if(this.spineManager_=e,this.app_){const t=this.app_,n=t.pipeline;n?.addPreFlushCallback(n=>{const s=t.getResource(qe).frameCount;e.submitMeshes(n._cpp,s)})}}build(e){this.app_=e;const t=e.wasmModule;if(_c=t,!this.spineManager_&&this.provider_){const e=function(e){const t=["3.8","4.1","4.2"],n=new Map;for(const s of t)n.set(s,async()=>{const[t,n]=await Promise.all([e.loadJs(s),e.loadWasm(s)]),o=new Blob([`${t};\nself.__ESSpineModule__ = ESSpineModule;`],{type:"application/javascript"}),i=URL.createObjectURL(o);await import(/* @vite-ignore */i),URL.revokeObjectURL(i);const r=globalThis.__ESSpineModule__;return delete globalThis.__ESSpineModule__,r({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Spine] WASM instantiation failed:",e)}),{})})});return n}(this.provider_);this.spineManager_=new Bl(t,e)}const n=this,s={_id:Symbol("SpineUpdateSystem"),_name:"SpineUpdateSystem",_params:[],_fn:()=>{const t=e.world.getCppRegistry();if(!t)return;const s=e.getResource(qe);xc.update({_cpp:t},s.delta),n.spineManager_?.updateAnimations(s.delta)}};if(e.addSystemToSchedule(exports.Schedule.PreUpdate,s),this.spineManager_){const t=this.spineManager_,n=e.pipeline;n?.addPreFlushCallback(n=>{const s=e.getResource(qe).frameCount;t.submitMeshes(n._cpp,s)})}}}const bc="__preview__";const vc={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),o=wi.createRenderTarget(e.width,e.height,s);return{_handle:o,textureId:wi.getTargetTexture(o),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){wi.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(wi.releaseRenderTarget(e._handle),vc.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){wi.begin(t,e._handle)},end(){wi.end()},getDepthTexture:e=>wi.getTargetDepthTexture(e._handle)};var Sc;exports.LogLevel=void 0,(Sc=exports.LogLevel||(exports.LogLevel={}))[Sc.Debug=0]="Debug",Sc[Sc.Info=1]="Info",Sc[Sc.Warn=2]="Warn",Sc[Sc.Error=3]="Error";class Pc{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,n);break;case exports.LogLevel.Info:console.log(t,n);break;case exports.LogLevel.Warn:console.warn(t,n);break;case exports.LogLevel.Error:console.error(t,n)}}}class Mc{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Pc)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(exports.LogLevel.Debug,e,t,n)}info(e,t,n){this.log(exports.LogLevel.Info,e,t,n)}warn(e,t,n){this.log(exports.LogLevel.Warn,e,t,n)}error(e,t,n){this.log(exports.LogLevel.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const o={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(o)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Tc=new Mc;const Cc={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},Ec={Running:0,Paused:1,Completed:2,Cancelled:3},Ac={None:0,Restart:1,PingPong:2};const Rc=1.70158,kc=2.70158,Ic=2.5949095;const Fc=2*Math.PI/3,Bc=2*Math.PI/4.5;const Uc=7.5625,Dc=2.75;const Lc=1e-6;function zc(e,t,n){switch(e){case Cc.Linear:return t;case Cc.EaseInQuad:return function(e){return e*e}(t);case Cc.EaseOutQuad:return function(e){return e*(2-e)}(t);case Cc.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Cc.EaseInCubic:return function(e){return e*e*e}(t);case Cc.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Cc.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Cc.EaseInBack:return function(e){return kc*e*e*e-Rc*e*e}(t);case Cc.EaseOutBack:return function(e){const t=e-1;return 1+kc*t*t*t+Rc*t*t}(t);case Cc.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Ic)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Ic)+2)/2}(t);case Cc.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Fc)}(t);case Cc.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Fc)+1}(t);case Cc.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Bc)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Bc)/2+1}(t);case Cc.EaseOutBounce:return function(e){return e<1/Dc?Uc*e*e:e<2/Dc?Uc*(e-=1.5/Dc)*e+.75:e<2.5/Dc?Uc*(e-=2.25/Dc)*e+.9375:Uc*(e-=2.625/Dc)*e+.984375}(t);case Cc.CubicBezier:return n?function(e,t,n,s,o){let i=e;for(let n=0;n<8;n++){const n=1-i,o=3*t*n*n*i+3*s*n*i*i+i*i*i-e;if(Math.abs(o)<Lc)break;const r=3*t*(1-2*i)*(1-i)+6*s*i*(1-i)-3*s*i*i+3*i*i;if(Math.abs(r)<Lc)break;i-=o/r}const r=1-i;return 3*n*r*r*i+3*o*r*i*i+i*i*i}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case Cc.Step:return function(e){return e<1?0:1}(t);default:return t}}const Wc=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,o){const i=this.nextId_++;return this.entries_.set(i,{id:i,from:e,to:t,duration:n,elapsed:0,delay:o?.delay??0,easing:o?.easing??Cc.Linear,bezierPoints:null,state:Ec.Running,loop:o?.loop??Ac.None,loopCount:o?.loopCount??0,loopsRemaining:o?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),i}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===Ec.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Ec.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=zc(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Ac.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Ac.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Ec.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Ec.Running&&(t.state=Ec.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Ec.Paused&&(t.state=Ec.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Ec.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Ec.Cancelled}setBezier(e,t,n,s,o){const i=this.entries_.get(e);i&&(i.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:o})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Hc{constructor(e){this.id=e}get state(){return Wc.getState(this.id)}bezier(e,t,n,s){return Wc.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Hc?Wc.setSequenceNext(this.id,e.id):Wc.setSequenceNextExternal(this.id,e),this}pause(){Wc.pause(this.id)}resume(){Wc.resume(this.id)}cancel(){Wc.cancel(this.id)}}class $c{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof Hc?(Wc.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Oc=null,Vc=null;function Nc(e,t){Oc=e,Vc=t,Wc.init(e,t)}function jc(){Wc.shutdown(),Oc=null,Vc=null}function Xc(){if(!Oc)throw new Error("Tween API not initialized");return Oc}function Yc(){if(!Vc)throw new Error("Tween API not initialized");return Vc}const Gc={to(e,t,n,s,o,i){const r=Xc(),a=Yc(),l=i?.easing??Cc.Linear,c=i?.delay??0,u=i?.loop??Ac.None,d=i?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,o,l,c,u,d);return new $c(r,a,h)},value(e,t,n,s,o){const i=Wc.create(e,t,n,s,o);return new Hc(i)},cancel(e){Xc()._anim_cancelTween(Yc(),e.entity)},cancelAll(e){Xc()._anim_cancelAllTweens(Yc(),e)},update(e){Xc()._anim_updateTweens(Yc(),e),Wc.update(e)}};class qc{constructor(){this.name="AnimationPlugin"}build(e){Nc(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,kt([je(qe)],e=>{ns()&&!ss()||Gc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,kt([je(qe)],e=>{ns()&&!ss()||dn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){jc()}}const Kc=new qc;let Jc=null,Qc=null;function Zc(e,t){Jc=e,Qc=t}function eu(){Jc=null,Qc=null}const tu={update(e){Jc&&Qc&&Jc.particle_update?.(Qc,e)},play(e){Jc&&Qc&&Jc.particle_play?.(Qc,e)},stop(e){Jc&&Qc&&Jc.particle_stop?.(Qc,e)},reset(e){Jc&&Qc&&Jc.particle_reset?.(Qc,e)},getAliveCount:e=>Jc?Jc.particle_getAliveCount?.(e)??0:0};class nu{constructor(){this.name="ParticlePlugin"}build(e){Zc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(exports.Schedule.Update,kt([je(qe)],e=>{tu.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){eu()}}const su=new nu,ou=1073741824,iu={orthogonal:0,isometric:1,staggered:2};class ru{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.animatedLayers_=new Set,this.sourceEntityKeys_=new Map,this.layerState_=new Map}build(e){bn(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.animatedLayers_,o=this.sourceEntityKeys_,i=this.layerState_,r={_id:Symbol("TilemapSyncSystem"),_name:"TilemapSyncSystem",_params:[],_fn:()=>{const r=t.getEntitiesWithComponents([Mn,de]),a=new Set(r);for(const e of n)e>=ou||a.has(e)||(Sn.destroyLayer(e),n.delete(e),i.delete(e));for(const e of r){const s=t.tryGet(e,Mn);if(!s)continue;const o=s.texture;if(!o)continue;const r=mn(o);if(!r)continue;if(!n.has(e)){if(Sn.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),Sn.setOriginEntity(e,e),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];Sn.setTiles(e,t)}n.add(e)}const a=s.tileWidth/r.width,l=s.tileHeight/r.height,c=s.tint,u=s.parallaxFactor,d=i.get(e);(!d||d.texture!==o||d.tilesetColumns!==s.tilesetColumns||d.layer!==s.layer||d.parallaxX!==u.x||d.parallaxY!==u.y||d.tintR!==c.r||d.tintG!==c.g||d.tintB!==c.b||d.tintA!==c.a||d.opacity!==s.opacity||d.visible!==s.visible)&&(Sn.setRenderProps(e,o,s.tilesetColumns,a,l,s.layer,0,u.x,u.y),Sn.setTint(e,c.r,c.g,c.b,c.a,s.opacity),Sn.setVisible(e,s.visible),i.set(e,{texture:o,tilesetColumns:s.tilesetColumns,layer:s.layer,tintR:c.r,tintG:c.g,tintB:c.b,tintA:c.a,opacity:s.opacity,parallaxX:u.x,parallaxY:u.y,visible:s.visible}))}const l=t.getEntitiesWithComponents([Pn,de]);for(const e of l){if(t.tryGet(e,Mn))continue;const i=t.tryGet(e,Pn);if(!i?.source)continue;const r=xn(i.source);if(r&&!o.has(e)){const t=[],i=iu[r.orientation??"orthogonal"]??0;for(let o=0;o<r.layers.length;o++){const a=ou+256*e+o,l=r.layers[o];if(Sn.initLayer(a,l.width,l.height,r.tileWidth,r.tileHeight),Sn.setOriginEntity(a,e),l.tiles.length>0&&Sn.setTiles(a,l.tiles),0!==i&&Sn.setGridType(a,i),r.tileAnimations){for(const[e,t]of r.tileAnimations)Sn.setTileAnimation(a,e,t);r.tileAnimations.size>0&&s.add(a)}if(r.tileProperties)for(const[e,t]of r.tileProperties)for(const[n,s]of t)Sn.setTileProperty(a,e,n,s);const c=r.tilesets[0];if(c){const e=mn(c.textureHandle);e&&(Sn.setRenderProps(a,c.textureHandle,c.columns,r.tileWidth/e.width,r.tileHeight/e.height,o,0,1,1),Sn.setTint(a,1,1,1,1,1),Sn.setVisible(a,!0))}t.push(a),n.add(a)}o.set(e,t)}}const c=new Set(l);for(const[e,t]of o)if(!c.has(e)){for(const e of t)Sn.destroyLayer(e),n.delete(e),s.delete(e),i.delete(e);o.delete(e)}if(s.size>0){const t=1e3*e.getResource(qe).delta;for(const e of s)Sn.advanceAnimations(e,t)}}};e.addSystemToSchedule(exports.Schedule.PreUpdate,r)}cleanup(){for(const e of this.initializedLayers_)Sn.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),this.layerState_.clear(),yn(),vn()}}const au=new ru;function lu(e,t){return e.toFixed(t)}function cu(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class uu{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.lastUpdateTime_=0,this.lastStats_=null,this.accumulatedTimings_=new Map,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 220px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;this.lastStats_=e,this.accumulateTimings_(e.systemTimings);const t=performance.now();this.lastUpdateTime_>0&&t-this.lastUpdateTime_<500||(this.lastUpdateTime_=t,this.render_())}show(){this.visible_=!0,this.lastUpdateTime_=0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}accumulateTimings_(e){for(const[t,n]of e){const e=this.accumulatedTimings_.get(t);e?(e.sum+=n,e.count++,n>e.max&&(e.max=n)):this.accumulatedTimings_.set(t,{sum:n,max:n,count:1})}}render_(){const e=this.lastStats_;if(!e)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${lu(e.fps,1)}</span> Frame: <span style="color:#d19a66">${lu(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),this.accumulatedTimings_.size>0){const e=[];for(const[t,n]of this.accumulatedTimings_){const s=n.sum/n.count;e.push([t,s,n.max])}e.sort((e,t)=>t[2]-e[2]);const n=e.slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t,o]of n){s+=`<div>${cu(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${lu(t,1)} / ${lu(o,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join(""),this.accumulatedTimings_.clear()}}function du(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const hu=Ne(du(),"Stats");const pu="StatsCollect";class fu{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class gu{constructor(e){this.name="Stats",this.collector_=new fu,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(hu,du());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new uu(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=kt([je(qe),{_type:"get_world"}],(s,o)=>{t.pushFrame(s.delta);const i=e.getResource(hu);i.fps=t.getFps(),i.frameTimeMs=t.getFrameTimeMs(),i.entityCount=o.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(pu),i.systemTimings=e}else i.systemTimings=new Map;const a=e.getPhaseTimings();i.phaseTimings=a?new Map(a):new Map;const l=wi.getStats();i.drawCalls=l.drawCalls,i.triangles=l.triangles,i.sprites=l.sprites,i.text=l.text,i.spine=l.spine,i.meshes=l.meshes,i.culled=l.culled,n?.update(i)},{name:pu});e.addSystemToSchedule(exports.Schedule.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const mu=new gu;class yu{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const o=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(o.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return _u(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}function _u(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}function xu(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function wu(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await async function(e,t){try{const n=xu(t),s={instantiateWasm(e,t){const s=new Response(n.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,e).then(e=>t(e.instance,e.module),()=>{WebAssembly.instantiate(n.buffer,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Playable] WASM instantiation fallback failed:",e)})}),{}}};return await e(s)}catch(e){return console.error("[Playable] WASM module init failed:",e),null}}(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}const bu=[zr,Or,ea,fa,Pa,oa,Aa,Ba,Ha,wa,ua,Oa,Xa,Ka,Za,nl,pl],vu=[Kc,As,su,au,hi,Ws];function Su(e,t){const n=new wc(t?.spineProvider),s=[...bu,...vu,n,...t?.plugins??[]];return function(e,t){const n=Di.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),xo(e),jt(e),Do(e),Go(e),_i(e),vi(e);const o=new Mi;n.setPipeline(o);let i=c();const r=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,o,i){i||(i=Oi(e,s,t,o));const r=n.getResource(zt);if(i.length>0){const e=i[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*o),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*o),r.screenW=t,r.screenH=o,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(zt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(s);if(u>=0){const e=s.getCanvas(u).backgroundColor;wi.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-i)/1e3;let h;if(wi.resize(t,l),n.hasResource(Ii)){const e=n.getResource(Ii).getActiveScenes();e.length>0&&(h=new Set(e))}o.setActiveScenes(h??null);const p=Oi(e,s,t,l,n.world,h);if(a(t,l,p),0===p.length)o.render({registry:{_cpp:s},viewProjection:zi,width:t,height:l,elapsed:d});else{o.beginFrame(),o.beginScreenCapture();for(const e of p){const n=e.viewportRect,i=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);o.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d,cameraEntity:e.entity})}o.endScreenCapture(),wi.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(exports.Schedule.First,l),n.addSystemToSchedule(exports.Schedule.Last,d),n.addPlugin(to),n.addPlugin(po),n.addPlugin(Lt),n.addPlugin(Ui),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{...t,plugins:s})}class Pu{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return i(this.resolvePath_(e))}async readBinary(e){const t=await o(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Mu(e){return(t,n)=>(a(e,t).then(e=>{n(e.instance,e.module)}).catch(e=>{console.error("[WeChat] WASM instantiation failed:",e)}),{})}async function Tu(e,t){try{return await e({instantiateWasm:Mu(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}F||(F=!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},o=await f(n,s);return{ok:o.ok,status:o.status,statusText:o.statusText,headers:new Headers(o.headers),json:()=>o.json(),text:()=>o.text(),arrayBuffer:()=>o.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 g(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 o=e.charCodeAt(t);o<128?n[s++]=o:o<2048?(n[s++]=192|o>>6,n[s++]=128|63&o):o>=55296&&o<=56319?(o=e.charCodeAt(++t)-56320+(o-55296<<10)+65536,n[s++]=240|o>>18,n[s++]=128|o>>12&63,n[s++]=128|o>>6&63,n[s++]=128|63&o):(n[s++]=224|o>>12,n[s++]=128|o>>6&63,n[s++]=128|63&o)}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 o=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(o>>10),56320+(1023&o)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=B,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=qc,exports.App=Di,exports.AssetPlugin=eo,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=Qs,exports.Assets=Zs,exports.AsyncCache=sn,exports.Audio=hn,exports.AudioBus=d,exports.AudioListener=Cs,exports.AudioMixer=class{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new d(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new d(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new d(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new d(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new d(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new d(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}},exports.AudioPlugin=Es,exports.AudioPool=class{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}},exports.AudioSource=Ts,exports.BitmapText=be,exports.BodyType=Oe,exports.BoxCollider=ke,exports.Button=qr,exports.ButtonState=Gr,exports.Camera=me,exports.Canvas=ye,exports.CapsuleCollider=Fe,exports.ChainCollider=De,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=we,exports.CircleCollider=Ie,exports.ClearFlags=le,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=St,exports.DARK_THEME=fl,exports.DEFAULT_DESIGN_HEIGHT=D,exports.DEFAULT_DESIGN_WIDTH=U,exports.DEFAULT_FALLBACK_DT=1/60,exports.DEFAULT_FIXED_TIMESTEP=W,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=z,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE=L,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragPlugin=Ea,exports.DragState=Ta,exports.Draggable=Ma,exports.Draw=So,exports.Dropdown=Ja,exports.DropdownPlugin=Qa,exports.EasingType=Cc,exports.EmitterShape=Se,exports.EntityCommands=vt,exports.EntityStateMap=Pr,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=Ct,exports.EventRegistry=Mt,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=Tt,exports.FillDirection=Ji,exports.FillMethod=Zi,exports.FillOrigin=er,exports.FocusManager=la,exports.FocusManagerState=aa,exports.FocusPlugin=$a,exports.Focusable=ra,exports.FrameHistory=class{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}},exports.GLDebug=Pi,exports.Geometry=Wo,exports.GetWorld=At,exports.INVALID_ENTITY=0,exports.INVALID_FONT=N,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=V,exports.Image=tr,exports.ImagePlugin=pa,exports.ImageType=Qi,exports.Input=Ut,exports.InputPlugin=Dt,exports.InputState=Bt,exports.Interactable=sr,exports.LayoutGroupPlugin=tl,exports.ListView=Ya,exports.ListViewPlugin=qa,exports.LocalTransform=he,exports.Logger=Mc,exports.LoopMode=Ac,exports.Material=Gt,exports.MaterialLoader=on,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=Ce,exports.Parent=xe,exports.Particle=tu,exports.ParticleEasing=Me,exports.ParticleEmitter=Te,exports.ParticlePlugin=nu,exports.Physics=lc,exports.PhysicsEvents=Ql,exports.PhysicsPlugin=tc,exports.PolygonCollider=Ue,exports.PostProcess=Jo,exports.PostProcessPlugin=di,exports.PostProcessStack=jo,exports.PostProcessVolume=Ae,exports.PrefabServer=co,exports.Prefabs=uo,exports.PrefabsPlugin=ho,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Ii);t.register({name:bc,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(bc),this.loadPromise_=t.load(bc).then(()=>{}).catch(e=>{console.error("[Preview] Failed to load preview scene:",e)}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new yc(this.baseUrl_);await n.prefetch(t);const o=this.app_.getPlugin(wc),i=o?.spineManager??null;await fc({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineManager:i,sceneName:bc})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([me]);for(const s of n){if(e.get(s,me).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([ye]);for(const o of s){const s=e.get(o,ye);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const o=this.app_.getResource(Ii).getScene(bc),i=o?o.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(i,de,r);const a={isActive:!0,projectionType:ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth};e.insert(i,me,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Ii);await e.switchTo(bc),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=va,exports.ProgressBarDirection=ba,exports.ProgressBarPlugin=Sa,exports.ProjectionType=ae,exports.Query=xt,exports.QueryInstance=wt,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=bt,exports.RenderPipeline=Mi,exports.RenderTexture=vc,exports.Renderer=wi,exports.Res=je,exports.ResMut=Xe,exports.RevoluteJoint=Le,exports.RigidBody=Re,exports.RuntimeConfig=H,exports.SafeArea=Va,exports.SafeAreaPlugin=ja,exports.ScaleMode=ce,exports.SceneManager=Ii,exports.SceneManagerState=ki,exports.SceneOwner=Ee,exports.ScrollView=Ra,exports.ScrollViewPlugin=Fa,exports.SegmentCollider=Be,exports.ShaderSources=nn,exports.ShapeRenderer=ge,exports.ShapeType=ue,exports.SimulationSpace=Pe,exports.Slider=Da,exports.SliderDirection=Ua,exports.SliderPlugin=Wa,exports.SpineAnimation=ve,exports.Sprite=fe,exports.SpriteAnimator=un,exports.Stats=hu,exports.StatsCollector=fu,exports.StatsOverlay=uu,exports.StatsPlugin=gu,exports.Storage=Je,exports.SubmitSkipFlags={None:0,Spine:1,Particles:2},exports.SystemRunner=Ft,exports.Text=Fr,exports.TextAlign=Rr,exports.TextInput=ia,exports.TextInputPlugin=ca,exports.TextOverflow=Ir,exports.TextPlugin=Lr,exports.TextRenderer=Br,exports.TextVerticalAlign=kr,exports.Tilemap=Pn,exports.TilemapAPI=Sn,exports.TilemapLayer=Mn,exports.TilemapPlugin=ru,exports.Time=qe,exports.TimelinePlugin=zs,exports.Toggle=ga,exports.TogglePlugin=xa,exports.Transform=de,exports.Tween=Gc,exports.TweenHandle=$c,exports.TweenState=Ec,exports.TweenTarget={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},exports.UI=kl,exports.UICameraInfo=zt,exports.UIEventQueue=Kr,exports.UIEvents=Jr,exports.UIInteraction=Yr,exports.UIInteractionPlugin=sa,exports.UILayoutGeneration=Qr,exports.UILayoutPlugin=Zr,exports.UIMask=Hr,exports.UIMaskPlugin=$r,exports.UIRect=nr,exports.UIRenderOrderPlugin=hl,exports.UIRenderer=Ci,exports.UIThemeRes=gl,exports.UIVisualType=Ti,exports.Velocity=_e,exports.WeChatAssetProvider=Pu,exports.WebAssetProvider=yc,exports.World=pt,exports.WorldTransform=pe,exports.addStartupSystem=function(e){It().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){It().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){It().push({schedule:e,system:t})},exports.animationPlugin=Kc,exports.applyBuildRuntimeConfig=O,exports.applyDirectionalFill=ar,exports.applyOverrides=io,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=H.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=H.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=H.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=H.canvasMatchWidthOrHeight)},exports.assetPlugin=to,exports.audioPlugin=As,exports.calculateAttenuation=Ps,exports.calculatePanning=Ms,exports.cleanupAllPostProcessVolumes=oi,exports.cleanupPostProcessVolume=si,exports.clearAnimClips=function(){ln.clear()},exports.clearDrawCallbacks=Ro,exports.clearTextureDimensionsCache=yn,exports.clearTilemapSourceCache=function(){fn.clear()},exports.clearTimelineHandles=function(){if(ws)for(const e of xs.values())ws._tl_destroy(e);xs.clear()},exports.clearUserComponents=function(){const e=J();for(const t of e.keys())ne.delete(t);e.clear()},exports.cloneComponentData=so,exports.cloneComponents=no,exports.collectNestedPrefabPaths=function e(t,n,s){const o=[],i=s??new Set;if(t.basePrefab&&!i.has(t.basePrefab)){i.add(t.basePrefab),o.push(t.basePrefab);const s=n(t.basePrefab);s&&o.push(...e(s,n,i))}for(const s of t.entities){if(!s.nestedPrefab)continue;const t=s.nestedPrefab.prefabPath;if(i.has(t))continue;i.add(t),o.push(t);const r=n(t);r&&o.push(...e(r,n,i))}return o},exports.color=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),exports.colorScale=function(e,t){return{r:Math.min(1,e.r*t),g:Math.min(1,e.g*t),b:Math.min(1,e.b*t),a:e.a}},exports.colorWithAlpha=function(e,t){return{r:e.r,g:e.g,b:e.b,a:t}},exports.computeFillAnchors=rr,exports.computeFillSize=function(e,t,n,s){switch(e){case Ji.BottomToTop:case Ji.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}},exports.computeHandleAnchors=function(e,t){switch(e){case Ji.RightToLeft:return{anchorMin:{x:1-t,y:.5},anchorMax:{x:1-t,y:.5}};case Ji.BottomToTop:return{anchorMin:{x:.5,y:t},anchorMax:{x:.5,y:t}};case Ji.TopToBottom:return{anchorMin:{x:.5,y:1-t},anchorMax:{x:.5,y:1-t}};default:return{anchorMin:{x:t,y:.5},anchorMax:{x:t,y:.5}}}},exports.computeUIRectLayout=function(e,t,n,s,o,i,r={x:.5,y:.5}){const a=i.right-i.left,l=i.top-i.bottom,c=i.left+e.x*a,u=i.left+t.x*a,d=i.bottom+e.y*l,h=i.bottom+t.y*l;let p,f,g,m;e.x===t.x?(p=c+n.x-o.x*r.x,g=p+o.x):(p=c+n.x,g=u+s.x),e.y===t.y?(f=d+n.y-o.y*r.y,m=f+o.y):(f=d+n.y,m=h+s.y);const y=Math.max(0,g-p),_=Math.max(0,m-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:g,top:m}}},exports.createRuntimeSceneConfig=gc,exports.createWebApp=Su,exports.debug=function(e,t,n){Tc.debug(e,t,n)},exports.defaultFrameStats=du,exports.defineComponent=Q,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Ne,exports.defineSystem=kt,exports.defineTag=function(e){const t=ne.get(e)??J().get(e);if(t)return t;const n=K(e,{});return J().set(e,n),ne.set(e,n),ee(e,{},!0),n},exports.dragPlugin=Aa,exports.dropdownPlugin=Za,exports.error=function(e,t,n){Tc.error(e,t,n)},exports.extractAnimClipTexturePaths=rn,exports.findEntityByName=function(e,t){const n=e.getEntitiesWithComponents([Ce]);for(const s of n){const n=e.get(s,Ce);if(n&&n.value===t)return s}return null},exports.flattenPrefab=ro,exports.flushPendingSystems=Li,exports.focusPlugin=Oa,exports.getAddressableType=function(e){return b(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of m)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return x},exports.getAllEffectDefs=function(){return Array.from(Qo.values())},exports.getAnimClip=function(e){return ln.get(e)},exports.getAssetBuildTransform=function(e){return b(e)?.buildTransform},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=b,exports.getComponent=oe,exports.getComponentAssetFieldDescriptors=Os,exports.getComponentAssetFields=$s,exports.getComponentDefaults=function(e){const t=oe(e);return t?G(t._default):null},exports.getComponentEntityFields=Y,exports.getComponentSpineFieldDescriptor=Vs,exports.getCustomExtensions=S,exports.getEditorType=function(e){return b(e)?.editorType??"unknown"},exports.getEffectDef=ei,exports.getEffectTypes=function(){return Array.from(Qo.keys())},exports.getLogger=function(){return Tc},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getTextureDimensions=mn,exports.getTilemapSource=xn,exports.getTimelineHandle=function(e){return xs.get(e)},exports.getUserComponent=Z,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=fa,exports.info=function(e,t,n){Tc.info(e,t,n)},exports.initDrawAPI=xo,exports.initGLDebugAPI=vi,exports.initGeometryAPI=Do,exports.initMaterialAPI=jt,exports.initParticleAPI=Zc,exports.initPlayableRuntime=async function(e){const{app:t,module:n,assets:s,scenes:o,firstScene:i}=e,r=t.getResource(Zs);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));let a=null;if(e.spineModules&&Object.keys(e.spineModules).length>0){a=function(e,t){const n=new Map;for(const[e,s]of Object.entries(t)){const t=e;n.set(t,async()=>{const e=xu(s.wasmBase64);return s.factory({instantiateWasm(t,n){const s=new Response(e.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,t).then(e=>n(e.instance,e.module),()=>{WebAssembly.instantiate(e.buffer,t).then(e=>n(e.instance,e.module)).catch(e=>{console.error("[Playable] Spine WASM instantiation fallback failed:",e)})}),{}}})})}return new Bl(e,n)}(n,e.spineModules);const s=t.getPlugin(wc);s&&s.setSpineManager(a)}const l=e.physicsWasmBase64?await wu(e.physicsWasmBase64):null,c=new yu(s);hn.setAssetResolver(e=>{const t=s[e];return t?_u(t).buffer:null}),await mc({app:t,module:n,provider:c,scenes:o,firstScene:i,spineManager:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=Go,exports.initRendererAPI=_i,exports.initRuntime=mc,exports.initTilemapAPI=bn,exports.initTweenAPI=Nc,exports.initUIBuilder=function(e){e.hasResource(gl)&&(ml=e.getResource(gl))},exports.initWeChatRuntime=async function(e){const t=await i("asset-manifest.json"),n=JSON.parse(t),s=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=M(e),o=t[e]||t[s]||n[s]||n[e];return o?o.path:s}}(function(e){const t={},n={};for(const s in e.groups){const o=e.groups[s];for(const e in o.assets){const s=o.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n)),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:Mu("esengine.wasm")}),l=o.getContext("webgl2")||o.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=Su(a,{glContextHandle:c,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&O(u,e.runtimeConfig);let d=null;if(e.spineFactories&&Object.keys(e.spineFactories).length>0){const t=new Map;for(const[n,s]of Object.entries(e.spineFactories)){const e=n,o=`spine_${n.replace(".","")}.wasm`;t.set(e,()=>Tu(s,o))}d=new Bl(a,t)}let h=null;e.physicsFactory&&(h=await Tu(e.physicsFactory,"physics.wasm"));const p=new Pu(s),f=[];for(const t of e.sceneNames){const e=await i(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await mc({app:u,module:a,provider:p,scenes:f,firstScene:e.firstScene,spineManager:d,physicsModule:h,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),u.run()},exports.inputPlugin=Lt,exports.instantiatePrefab=lo,exports.intersectRects=function(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),o=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,o-n),h:Math.max(0,i-s)}},exports.invertMatrix4=Vr,exports.isBuiltinComponent=te,exports.isCustomExtension=P,exports.isEditor=ns,exports.isKnownAssetExtension=v,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=ss,exports.isRuntime=function(){return!es},exports.isTextureRef=Ht,exports.isWeChat=n,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=nl,exports.listViewPlugin=Ka,exports.loadComponent=Ks,exports.loadPhysicsModule=Dl,exports.loadRuntimeScene=fc,exports.loadSceneData=Ys,exports.loadSceneWithAssets=Gs,exports.loadTiledMap=function(e,t,n,s={}){const o=[],i=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,de,{});const l=i?n.get(i.image)??0:0,c=i?.columns??1;e.insert(a,Mn,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),o.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const o=[],i=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(i-l)-.5*t.height,d=-t.rotation*kn;if(e.insert(r,de,{position:{x:c,y:u,z:0}}),e.insert(r,Re,{bodyType:Oe.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,Ie,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,o=-1/0,i=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>o&&(o=r),a<s&&(s=a),a>i&&(i=a)}const a=o-n,l=i-s,c=.5*(n+o),u=.5*(s+i);e.insert(r,ke,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,ke,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,de,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}o.push(r)}return o}(e,t,0,0);o.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=In(e,n,t,a,0,0);o.push(...s)}return o},exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&v(w(e)))},exports.makeInteractable=function(e,t){xr(e,t,sr,{enabled:!0,blockRaycast:!0,raycastTarget:!0})},exports.parseAnimClipData=an,exports.parseTiledMap=async function(e,t){const n=wn;if(!n)return null;const s=new TextEncoder,o=s.encode(e),i=n._malloc(o.byteLength);n.HEAPU8.set(o,i);const r=n.tiled_loadMap(i,o.byteLength);if(n._free(i),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let o=0;o<e;o++){const e=n.tiled_getExternalTilesetSource(r,o);if(!t)return n.tiled_freeMap(r),null;const i=await t(e),a=s.encode(i),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,o,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const o={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),orientation:"orthogonal",layers:[],tilesets:[],objectGroups:[],collisionTileIds:[],tileAnimations:new Map,tileProperties:new Map},i=n.tiled_getLayerCount(r);for(let e=0;e<i;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),i=t*s,a=2*i,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,i);const c=new Uint16Array(i);c.set(new Uint16Array(n.HEAPU8.buffer,l,i)),n._free(l),o.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?Tn(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)o.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),o}catch(e){return console.warn("[Tiled] Failed to parse tilemap",e),n.tiled_freeMap(r),null}},exports.parseTimelineAsset=Zn,exports.parseTmjJson=An,exports.particlePlugin=su,exports.platformFetch=s,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=o,exports.platformReadTextFile=i,exports.pointInOBB=function(e,t,n,s,o,i,r,a,l,c){if(0===l&&1===c)return jr(e,t,n,s,o,i,r,a);const u=Xr(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-n,f=t-s,g=p*h-f*d+n,m=p*d+f*h+s;return g>=n-o*r&&g<=n+o*(1-r)&&m>=s-i*a&&m<=s+i*(1-a)},exports.pointInWorldRect=jr,exports.postProcessPlugin=hi,exports.prefabsPlugin=po,exports.preloadNestedPrefabs=ao,exports.progressBarPlugin=Pa,exports.quat=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s}),exports.registerAnimClip=cn,exports.registerAssetBuildTransform=function(e,t){for(const n of m)n.editorType===e&&(n.buildTransform=t)},exports.registerComponent=se,exports.registerComponentAssetFields=function(e,t){Hs.set(e,t)},exports.registerComponentEntityFields=X,exports.registerDrawCallback=Eo,exports.registerEmbeddedAssets=function(e,t){const n=e.getResource(Zs);n&&n.registerEmbeddedAssets(t)},exports.registerMaterialCallback=tn,exports.registerTextureDimensions=gn,exports.registerTilemapSource=_n,exports.registerTimelineAsset=Is,exports.remapComponentEntityRefs=oo,exports.remapEntityFields=Ns,exports.resolveRelativePath=Rn,exports.safeAreaPlugin=Xa,exports.sceneManagerPlugin=Ui,exports.screenToWorld=Nr,exports.scrollViewPlugin=Ba,exports.setEditorMode=function(e){es=e},exports.setEntityColor=vr,exports.setEntityEnabled=Sr,exports.setListViewRenderer=function(e,t){if(!Ga)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Ga.get(e);n?n.renderer=t:Ga.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Tc.setMinLevel(e)},exports.setPlayMode=function(e){ts=e},exports.setWasmErrorHandler=nt,exports.shutdownDrawAPI=wo,exports.shutdownGLDebugAPI=Si,exports.shutdownGeometryAPI=Lo,exports.shutdownMaterialAPI=Xt,exports.shutdownParticleAPI=eu,exports.shutdownPostProcessAPI=qo,exports.shutdownRendererAPI=xi,exports.shutdownTilemapAPI=vn,exports.shutdownTweenAPI=jc,exports.sliderPlugin=Ha,exports.spriteAnimatorSystemUpdate=dn,exports.statsPlugin=mu,exports.syncFillSpriteSize=function(e,t,n,s,o,i){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(n){case Ji.BottomToTop:case Ji.TopToBottom:a=o,l=i*s;break;default:a=o*s,l=i}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,fe,r))},exports.syncPostProcessVolume=function(e,t){let n=ti.get(e),s=ni.get(e);const o=t.effects.filter(e=>e.enabled);if(0!==o.length){for(n||(n=Jo.createStack(),ti.set(e,n)),s||(s=new Map,ni.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of o){const t=ei(e.type);if(!t)continue;let o=s.get(e.type);void 0===o&&(o=t.factory(),s.set(e.type,o)),n.addPass(e.type,o);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}Jo.bind(e,n)}else if(n&&(Jo.unbind(e),n.destroy(),ti.delete(e)),s){for(const e of s.values())Gt.releaseShader(e);ni.delete(e)}},exports.textInputPlugin=ua,exports.textPlugin=zr,exports.tilemapPlugin=au,exports.timelinePlugin=Ws,exports.toBuildPath=M,exports.togglePlugin=wa,exports.transitionTo=async function(e,t,n){const s=e.getResource(Ii);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})},exports.uiInteractionPlugin=oa,exports.uiLayoutPlugin=ea,exports.uiMaskPlugin=Or,exports.uiPlugins=bu,exports.uiRenderOrderPlugin=pl,exports.unregisterAnimClip=function(e){ln.delete(e)},exports.unregisterComponent=function(e){J().delete(e),ne.delete(e)},exports.unregisterDrawCallback=Ao,exports.updateCameraAspectRatio=Js,exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),exports.vec4=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),exports.warn=function(e,t,n){Tc.warn(e,t,n)},exports.withChildEntity=wr,exports.wrapSceneSystem=Fi,exports.wxFileExists=function(e){return new Promise(t=>{C().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=A,exports.wxGetImagePixels=k,exports.wxLoadImage=R,exports.wxLoadImagePixels=I,exports.wxReadFile=function(e){return new Promise((t,n)=>{C().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(E(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((n,s)=>{C().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(E(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((n,s)=>{C().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};//# sourceMappingURL=index.wechat.cjs.js.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex c2cff845a..55bbc3c4d 100644--- a/desktop/public/sdk/cjs/index.wechat.js+++ b/desktop/public/sdk/cjs/index.wechat.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class y{constructor(e,t,n){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class _{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,s);const o=new y(i,s,this.contexts_);return s.onEnded(()=>{o.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(i))}),s.onError(e=>{console.error(`[WeChatAudio] Playback error for "${n}":`,e.errMsg)}),s.src=n,s.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function x(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"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 w(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}`)}}const b=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["estimeline"],contentType:"json",editorType:"timeline",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],v={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",estimeline:"application/json",bmfont:"application/json",fnt:"text/plain"},S=new Map,M=new Set;for(const e of b)for(const t of e.extensions)S.set(t,e),M.add(t);function C(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function P(e){return S.get(C(e))}function T(e){return P(e)?.editorType??"unknown"}function E(e){return P(e)?.addressableType??null}function A(e){for(const t of b)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function k(e){return M.has(e.toLowerCase())}function R(){return M}function I(e){return"string"==typeof e&&(!!e.includes("/")&&k(C(e)))}function F(){const e=[];for(const t of b)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function B(){return F().map(e=>({type:"suffix",value:e}))}function U(e){return v[e.toLowerCase()]}function z(e){const t=P(e);return t?.wechatPackInclude??!1}function W(e){const t=P(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function D(e,t){for(const n of b)n.editorType===e&&(n.buildTransform=t)}function H(e){return P(e)?.buildTransform}let $=null;function L(){return $||($=wx.getFileSystemManager()),$}function O(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(z(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function V(e){return new Promise((t,n)=>{L().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(O(e,t.errMsg)))}})})}function N(e,t="utf-8"){return new Promise((n,s)=>{L().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(O(e,t.errMsg)))}})})}function j(e){return new Promise(t=>{L().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function X(e){const t=L();try{return t.accessSync(e),!0}catch{return!1}}function Y(e,t){return new Promise((n,s)=>{L().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function G(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 q(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const i=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(i.data.buffer)}}async function K(e){return q(await G(e))}let J=!1;const Z=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return x(e,t)}async readFile(e){return function(e){return L().readFileSync(e)}(W(e))}async readTextFile(e){return function(e,t="utf-8"){return L().readFileSync(e,t)}(W(e))}async fileExists(e){return X(W(e))}async loadImagePixels(e){return K(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return w(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(n),wx.onKeyUp(s));const o=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new _}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch(e){console.warn("[WeChat] setStorageSync failed:",e)}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch(e){console.warn("[WeChat] removeStorageSync failed:",e)}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const n of t)n.startsWith(e)&&wx.removeStorageSync(n)}catch(e){console.warn("[WeChat] clearStorage failed:",e)}}},Q=1920,ee=1080,te=100,ne=512,se={x:100,y:100},ie="Arial",oe=24,re=1.2,ae=.5,le=1/60,ce={x:0,y:-9.81},ue=1/60,he="default",de={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};function fe(e){e.Text&&(e.Text._default.fontFamily=de.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=de.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=de.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=de.canvasMatchWidthOrHeight)}const pe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function me(e,t){if(void 0!==t.maxDeltaTime&&(de.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(de.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(de.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(de.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(de.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");de.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(de.canvasScaleMode=pe[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(de.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(de.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(de.assetFailureCooldown=t.assetFailureCooldown)}const ge=0,ye=4294967295,_e=4294967295,xe=0,we=(e=0,t=0)=>({x:e,y:t}),be=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ve=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),Se=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),Me=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s}),Ce=new Map;function Pe(e,t){Ce.set(e,t)}function Te(e){return Ce.get(e)}function Ee(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Ee);const t={};for(const n in e)t[n]=Ee(e[n]);return t}let Ae=0;function ke(e,t){const n=++Ae,s=function(e){const t=[],n=[],s=[];let i=!1;for(const o in e){const r=e[o];null!==r&&"object"==typeof r?(i=!0,Array.isArray(r)?s.push(o):n.push(o)):t.push(o)}return i?{flatKeys:t,objectKeys:n,arrayKeys:s}:null}(t),i=t;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create(e){if(s){const t={...i};for(const e of s.objectKeys)t[e]={...i[e]};for(const e of s.arrayKeys)t[e]=i[e].slice();return e&&Object.assign(t,e),t}return e?{...t,...e}:{...t}}}}function Re(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ie(e,t,n){const s=He.get(e)??Re().get(e);if(s)return s;const i=ke(e,t);return Re().set(e,i),He.set(e,i),We(e,t,!1),n?.entityFields&&Pe(e,n.entityFields),i}function Fe(e){const t=He.get(e)??Re().get(e);if(t)return t;const n=ke(e,{});return Re().set(e,n),He.set(e,n),We(e,{},!0),n}function Be(e){return Re().get(e)}function Ue(){const e=Re();for(const t of e.keys())He.delete(t);e.clear()}function ze(e){Re().delete(e),He.delete(e)}function We(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function De(e){return!0===e._builtin}const He=new Map;function $e(e,t){He.set(e,t)}function Le(e){return He.get(e)??Be(e)}function Oe(e){if(null===e||"object"!=typeof e)return[];const t=[];for(const n of Object.keys(e)){const s=e[n];if(null!==s&&"object"==typeof s&&!Array.isArray(s)){"r"in s&&"g"in s&&"b"in s&&"a"in s&&t.push(n)}}return t}function Ve(e,t,n){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t,_colorKeys:Oe(t)};return He.set(e,s),s}const Ne={Perspective:0,Orthographic:1},je={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Xe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Ye={Circle:0,Capsule:1,RoundedRect:2},Ge=Ve("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),qe=Ge,Ke=Ge,Je=Ve("Sprite",{texture:ye,color:{r:1,g:1,b:1,a:1},size:{x:se.x,y:se.y},pivot:{x:.5,y:.5},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Ze=Ve("ShapeRenderer",{shapeType:Ye.Circle,color:{r:1,g:1,b:1,a:1},size:{x:100,y:100},cornerRadius:0,layer:0,enabled:!0}),Qe=Ve("Camera",{projectionType:Ne.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:je.ColorAndDepth}),et=Ve("Canvas",{designResolution:{x:Q,y:ee},pixelsPerUnit:100,scaleMode:Xe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),tt=Ve("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),nt=Ve("Parent",{entity:0}),st=Ve("Children",{entities:[]}),it=Ve("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_e,enabled:!0}),ot=Ve("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,enabled:!0}),rt={Point:0,Circle:1,Rectangle:2,Cone:3},at={World:0,Local:1},lt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},ct=Ve("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:rt.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:lt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:lt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:ye,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:at.World,enabled:!0}),ut=Ie("Name",{value:""}),ht=Ie("SceneOwner",{scene:"",persistent:!1}),dt=Ie("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function ft(e){const t=Le(e);return t?Ee(t._default):null}const pt=Ve("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),mt=Ve("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},radius:.05,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),gt=Ve("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),yt=Ve("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),_t=Ve("SegmentCollider",{point1:{x:-.5,y:0},point2:{x:.5,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),xt=Ie("PolygonCollider",{vertices:[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}],radius:0,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),wt=Ie("ChainCollider",{points:[{x:-1,y:0},{x:0,y:.5},{x:1,y:0},{x:0,y:-.5}],isLoop:!0,friction:.6,restitution:0,categoryBits:1,maskBits:65535,enabled:!0}),bt=Ie("RevoluteJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},enableMotor:!1,motorSpeed:0,maxMotorTorque:0,enableLimit:!1,lowerAngle:0,upperAngle:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),vt=Ie("DistanceJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},length:1,enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,minLength:.5,maxLength:2,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),St=Ie("PrismaticJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:1,y:0},enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Mt=Ie("WeldJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},linearHertz:0,angularHertz:0,linearDampingRatio:1,angularDampingRatio:1,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Ct=Ie("WheelJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:0,y:1},enableSpring:!0,hertz:5,dampingRatio:.7,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorTorque:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Pt={Static:0,Kinematic:1,Dynamic:2};let Tt=0;function Et(e,t){const n=++Tt;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function At(e){return{_type:"res",_resource:e}}function kt(e){return{_type:"res_mut",_resource:e}}class Rt{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_)}updateValue(e){this.value_=e}}class It{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Rt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ft=Et({delta:0,elapsed:0,frameCount:0},"Time"),Bt="esengine:",Ut={getString(e,n){const s=t().getStorageItem(Bt+e);return null!==s?s:n},setString(e,n){t().setStorageItem(Bt+e,n)},getNumber(e,n){const s=t().getStorageItem(Bt+e);if(null===s)return n;const i=Number(s);return Number.isNaN(i)?n:i},setNumber(e,n){t().setStorageItem(Bt+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(Bt+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(Bt+e,String(n))},getJSON(e,n){const s=t().getStorageItem(Bt+e);if(null===s)return n;try{return JSON.parse(s)}catch(t){return console.warn(`[Storage] Failed to parse JSON for key "${e}"`,t),n}},setJSON(e,n){t().setStorageItem(Bt+e,JSON.stringify(n))},remove(e){t().removeStorageItem(Bt+e)},has:e=>null!==t().getStorageItem(Bt+e),clear(){t().clearStorage(Bt)}};function zt(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=Wt(t[e]),o=Wt(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function Wt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Dt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Ht=null;function $t(e){Ht=e}function Lt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Ht&&Ht(e,t)}function Ot(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={r:t.x,g:t.y,b:t.z,a:t.w})}return n}function Vt(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={x:t.r,y:t.g,z:t.b,w:t.a})}return n}const Nt={Transform:{ptrFn:"getTransformPtr",fields:[{name:"position",type:"vec3",offset:0},{name:"rotation",type:"quat",offset:12},{name:"scale",type:"vec3",offset:28},{name:"worldPosition",type:"vec3",offset:40},{name:"worldRotation",type:"quat",offset:52},{name:"worldScale",type:"vec3",offset:68}]},Sprite:{ptrFn:"getSpritePtr",fields:[{name:"texture",type:"u32",offset:0},{name:"color",type:"color",offset:4},{name:"size",type:"vec2",offset:20},{name:"uvOffset",type:"vec2",offset:28},{name:"uvScale",type:"vec2",offset:36},{name:"layer",type:"i32",offset:44},{name:"flipX",type:"bool",offset:48},{name:"flipY",type:"bool",offset:49},{name:"material",type:"u32",offset:52},{name:"enabled",type:"bool",offset:56}]},Velocity:{ptrFn:"getVelocityPtr",fields:[{name:"linear",type:"vec3",offset:0},{name:"angular",type:"vec3",offset:12}]},Camera:{ptrFn:"getCameraPtr",fields:[{name:"projectionType",type:"u8",offset:0},{name:"fov",type:"f32",offset:4},{name:"orthoSize",type:"f32",offset:8},{name:"nearPlane",type:"f32",offset:12},{name:"farPlane",type:"f32",offset:16},{name:"aspectRatio",type:"f32",offset:20},{name:"isActive",type:"bool",offset:24},{name:"priority",type:"i32",offset:28},{name:"viewportX",type:"f32",offset:32},{name:"viewportY",type:"f32",offset:36},{name:"viewportW",type:"f32",offset:40},{name:"viewportH",type:"f32",offset:44},{name:"clearFlags",type:"i32",offset:48}]},UIRect:{ptrFn:"getUIRectPtr",fields:[{name:"anchorMin",type:"vec2",offset:0},{name:"anchorMax",type:"vec2",offset:8},{name:"offsetMin",type:"vec2",offset:16},{name:"offsetMax",type:"vec2",offset:24},{name:"size",type:"vec2",offset:32},{name:"pivot",type:"vec2",offset:40}]},RigidBody:{ptrFn:"getRigidBodyPtr",fields:[{name:"bodyType",type:"u8",offset:0},{name:"gravityScale",type:"f32",offset:4},{name:"linearDamping",type:"f32",offset:8},{name:"angularDamping",type:"f32",offset:12},{name:"fixedRotation",type:"bool",offset:16},{name:"bullet",type:"bool",offset:17},{name:"enabled",type:"bool",offset:18}]},BoxCollider:{ptrFn:"getBoxColliderPtr",fields:[{name:"halfExtents",type:"vec2",offset:0},{name:"offset",type:"vec2",offset:8},{name:"density",type:"f32",offset:16},{name:"friction",type:"f32",offset:20},{name:"restitution",type:"f32",offset:24},{name:"isSensor",type:"bool",offset:28},{name:"enabled",type:"bool",offset:29},{name:"categoryBits",type:"u32",offset:32},{name:"maskBits",type:"u32",offset:36}]},CircleCollider:{ptrFn:"getCircleColliderPtr",fields:[{name:"radius",type:"f32",offset:0},{name:"offset",type:"vec2",offset:4},{name:"density",type:"f32",offset:12},{name:"friction",type:"f32",offset:16},{name:"restitution",type:"f32",offset:20},{name:"isSensor",type:"bool",offset:24},{name:"enabled",type:"bool",offset:25},{name:"categoryBits",type:"u32",offset:28},{name:"maskBits",type:"u32",offset:32}]}};function jt(e,t,n,s,i,o){const r=s+i.offset,a=r>>2;switch(i.type){case"f32":e[a]=o;break;case"i32":t[a]=0|o;break;case"u32":t[a]=o;break;case"bool":n[r]=o?1:0;break;case"u8":n[r]=o;break;case"vec2":e[a]=o.x,e[a+1]=o.y;break;case"vec3":e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z;break;case"quat":e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z,e[a+3]=o.w;break;case"color":e[a]=o.r,e[a+1]=o.g,e[a+2]=o.b,e[a+3]=o.a}}let Xt=1;const Yt=new WeakMap;function Gt(e){let t=Yt.get(e);return void 0===t&&(t=Xt++,Yt.set(e,t)),t}const qt=[];function Kt(e,t=[],n=[]){qt.length=0;for(const t of e)qt.push(Gt(t));qt.sort((e,t)=>e-t);let s=qt.join(",");if(t.length>0){qt.length=0;for(const e of t)qt.push(Gt(e));qt.sort((e,t)=>e-t),s+="|+"+qt.join(",")}if(n.length>0){qt.length=0;for(const e of n)qt.push(Gt(e));qt.sort((e,t)=>e-t),s+="|-"+qt.join(",")}return s}class Jt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.builtinEntitySets_=new Map,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map,this.trackedComponents_=new Set}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}getWasmModule(){return this.module_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Lt(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch(e){console.warn("[World] Spawn callback error:",e)}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch(e){console.warn("[World] Despawn callback error:",e)}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Lt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;for(const[,t]of this.builtinEntitySets_)t.delete(e);const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){Lt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Lt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return De(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(De(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Vt(o,t._colorKeys))}catch(n){Lt(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return De(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){if(t._builtin){if(!this.cppRegistry_)return!1;const n=t._cppName,s=this.builtinEntitySets_.get(n);return s?s.has(e):this.getBuiltinMethods(n).has(e)}return this.hasScript(e,t)}tryGet(e,t){if(De(t)){if(!this.cppRegistry_)return null;const n=this.builtinEntitySets_.get(t._cppName);if(n&&!n.has(e))return null;try{const s=this.getBuiltinMethods(t._cppName);return n||s.has(e)?Ot(s.get(e),t._colorKeys):null}catch(n){return Lt(n,`tryGet(${t._name}, entity=${e})`),null}}const n=this.tsStorage_.get(t._id);if(!n)return null;const s=n.get(e);return void 0!==s?s:null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");De(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=zt(t._name,s,i);if(e.length>0)throw new Error(Dt(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Vt(o,t._colorKeys))}catch(n){Lt(n,`insertBuiltin(${t._name}, entity=${e})`)}let a=this.builtinEntitySets_.get(t._cppName);a||(a=new Set,this.builtinEntitySets_.set(t._cppName,a));const l=a.has(e);return!r&&l||(l||a.add(e),this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return Ot(this.getBuiltinMethods(t._cppName).get(e),t._colorKeys)}catch(n){return Lt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Lt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Lt(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++,this.builtinEntitySets_.get(t._cppName)?.delete(e)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=zt(t._name,t._default,e);if(i.length>0)throw new Error(Dt(t._name,i));s=e}const i=t.create(s),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=new Set,this.entityComponents_.set(e,a)),a.add(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);s&&s.delete(t._id)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resolveGetter(e){if(De(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrGetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?e=>t.get(e):e=>Ot(t.get(e),n)}const t=this.tsStorage_.get(e._id);return t?e=>t.get(e):null}resolveHas(e){if(De(e)){if(!this.cppRegistry_)return null;const t=this.getBuiltinMethods(e._cppName);return e=>t.has(e)}const t=this.tsStorage_.get(e._id);return t?e=>t.has(e):null}resolveSetter(e){if(De(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrSetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?(e,n)=>t.add(e,n):(e,s)=>t.add(e,Vt(s,n))}const t=this.tsStorage_.get(e._id);return t?(e,n)=>t.set(e,n):null}resolvePtrFn_(e){const t=Nt[e];if(!t)return null;const n=this.module_[t.ptrFn];if(!n)return null;const s=this.cppRegistry_;return e=>n(s,e)}resolvePtrSetter_(e){const t=Nt[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,i=t.fields;return(e,t)=>{const o=n(e);if(!o)return;const r=t;for(let e=0;e<i.length;e++)jt(s.HEAPF32,s.HEAPU32,s.HEAPU8,o,i[e],r[i[e].name])}}resolvePtrGetter_(e){const t=Nt[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,i=t.fields,o=function(e){const t={};for(const n of e)switch(n.type){case"vec2":t[n.name]={x:0,y:0};break;case"vec3":t[n.name]={x:0,y:0,z:0};break;case"quat":t[n.name]={x:0,y:0,z:0,w:0};break;case"color":t[n.name]={r:0,g:0,b:0,a:0};break;default:t[n.name]=null}return t}(i);return e=>{const t=n(e);return t?(function(e,t,n,s,i,o){for(let r=0;r<i.length;r++){const a=i[r],l=s+a.offset,c=l>>2;switch(a.type){case"f32":o[a.name]=e[c];break;case"i32":o[a.name]=0|t[c];break;case"u32":o[a.name]=t[c];break;case"bool":o[a.name]=0!==n[l];break;case"u8":o[a.name]=n[l];break;case"vec2":{const t=o[a.name];t.x=e[c],t.y=e[c+1];break}case"vec3":{const t=o[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2];break}case"quat":{const t=o[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2],t.w=e[c+3];break}case"color":{const t=o[a.name];t.r=e[c],t.g=e[c+1],t.b=e[c+2],t.a=e[c+3];break}}}}(s.HEAPF32,s.HEAPU32,s.HEAPU8,t,i,o),o):null}}resetQueryPool(){}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch(e){console.warn(`[World] Component check failed for ${n}:`,e)}if(this.cppRegistry_)for(const[n,s]of He)if(De(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch(e){console.warn(`[World] Builtin check failed for ${n}:`,e)}const n=this.entityComponents_.get(e);if(n){const e=Re();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}resolveStorages_(e,t,n){for(const s of e)if(De(s)){if(!this.cppRegistry_)return!1;n.push(this.getBuiltinMethods(s._cppName))}else{const e=this.tsStorage_.get(s._id);if(!e)return!1;t.push(e)}return!0}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??Kt(e,t,n),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;const r=[],a=[],l=[];if(!this.resolveStorages_(e,a,l))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),r;let c=null,u=null;if(t.length>0&&(c=[],u=[],!this.resolveStorages_(t,c,u)))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),r;let h=null,d=null;n.length>0&&(h=[],d=[],this.resolveStorages_(n,h,d));let f=null,p=1/0;for(let e=0;e<a.length;e++){const t=a[e].size;t<p&&(p=t,f=a[e])}for(const t of e)if(De(t)){const e=this.builtinEntitySets_.get(t._cppName);e&&e.size<p&&(p=e.size,f=e)}const m=f?f.keys():this.entities_.keys(),g=a.length,y=l.length;for(const e of m){let t=!0;for(let n=0;n<g;n++)if(!a[n].has(e)){t=!1;break}if(t)for(let n=0;n<y;n++)if(!l[n].has(e)){t=!1;break}if(t&&c){for(let n=0;n<c.length;n++)if(!c[n].has(e)){t=!1;break}if(t)for(let n=0;n<u.length;n++)if(!u[n].has(e)){t=!1;break}}if(t&&h){for(let n=0;n<h.length;n++)if(h[n].has(e)){t=!1;break}if(t)for(let n=0;n<d.length;n++)if(d[n].has(e)){t=!1;break}}t&&r.push(e)}return this.queryCache_.set(i,{version:this.worldVersion_,result:r}),r}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}enableChangeTracking(e){this.trackedComponents_.add(e._id)}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}markChanged(e,t){this.recordChangedTick_(t,e)}recordChangedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Zt(e){return{_type:"mut",_component:e}}function Qt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function en(e){return{_filterType:"added",_component:e}}function tn(e){return{_filterType:"changed",_component:e}}function nn(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function sn(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function on(e){return Qt(e)||nn(e)||sn(e)?e._component:e}function rn(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Qt(e)&&s.push(t),nn(e)?i.push({index:t,component:e._component}):sn(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>rn(e,[...t,...s],n),without:(...s)=>rn(e,t,[...n,...s])}}function an(...e){return rn(e)}class ln{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(on),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Kt(this.allRequired_,t._with,t._without),this.getters_=this.actualComponents_.map(t=>e.resolveGetter(t)),this.mutSetters_=t._mutIndices.map(t=>e.resolveSetter(this.actualComponents_[t])),this.mutIsBuiltin_=t._mutIndices.map(e=>De(this.actualComponents_[e]));for(const n of t._addedFilters)e.enableChangeTracking(n.component);for(const n of t._changedFilters)e.enableChangeTracking(n.component)}resetTick(e){this.lastRunTick_=e}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,h=this.getters_,d=this;let f=0,p=null,m=!1,g=!1;const y=this.mutIsBuiltin_,_=()=>{for(let e=0;e<l;e++){const t=a[e];if(y[e]){const n=c[e];n?n(p,t.data):u.set(p,t.component,t.data)}else u.markChanged(p,t.component)}},x=()=>{g||(g=!0,u.endIteration(),null!==p&&i&&_())},w={value:r,done:!1},b={value:void 0,done:!0};return{next(){for(m||(m=!0,u.beginIteration());f<n.length;){const c=n[f++];if(!o||d.passesChangeFilters_(c)){null!==p&&i&&_(),r[0]=c;for(let e=0;e<s;e++){const n=h[e];r[e+1]=n?n(c):u.get(c,t[e])}if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];p=c}return w}}return x(),b},return:()=>(x(),b)}}forEach(e){const{_mutIndices:t}=this.descriptor_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=this.actualComponents_.length,i=t.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,h=this.getters_,d=this.actualComponents_;u.beginIteration();let f=null;for(let p=0;p<n.length;p++){const m=n[p];if(!o||this.passesChangeFilters_(m)){if(null!==f&&i)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}r[0]=m;for(let e=0;e<s;e++){const t=h[e];r[e+1]=t?t(m):u.get(m,d[e])}if(i){for(let e=0;e<l;e++)a[e].data=r[t[e]+1];f=m}switch(s){case 1:e(m,r[1]);break;case 2:e(m,r[1],r[2]);break;case 3:e(m,r[1],r[2],r[3]);break;default:e.apply(null,r)}}}if(null!==f&&i)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}u.endIteration()}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function cn(e){return{_type:"removed",_component:e}}class un{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n,e.enableChangeTracking(t)}resetTick(e){this.lastRunTick_=e}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function hn(){return{_type:"commands"}}class dn{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=De(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 fn{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new dn(this,null);return this.spawned_.push(e),e}entity(e){return new dn(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function pn(e){return{_id:Symbol(`Event_${e}`),_name:e}}class mn{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class gn{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new mn)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new mn,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function yn(e){return{_type:"event_writer",_event:e}}function _n(e){return{_type:"event_reader",_event:e}}class xn{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class wn{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var bn;function vn(){return{_type:"get_world"}}!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"}(bn||(bn={}));let Sn=0;function Mn(e,t,n){const s=++Sn;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Cn(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Pn(e){Cn().push({schedule:bn.Update,system:e})}function Tn(e){Cn().push({schedule:bn.Startup,system:e})}function En(e,t){Cn().push({schedule:e,system:t})}class An{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.queryCache_=new Map,this.removedCache_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;let n=this.queryCache_.get(e._id),s=this.removedCache_.get(e._id);const i=!n;i&&(n=[],s=[],this.queryCache_.set(e._id,n),this.removedCache_.set(e._id,s));let o=0,r=0;for(let a=0;a<e._params.length;a++){const l=e._params[a];if("query"===l._type){if(i){const e=new ln(this.world_,l,this.currentLastRunTick_);n.push(e),t[a]=e}else{const e=n[o];e.resetTick(this.currentLastRunTick_),t[a]=e}o++}else if("removed"===l._type){if(i){const e=l,n=new un(this.world_,e._component,this.currentLastRunTick_);s.push(n),t[a]=n}else{const e=s[r];e.resetTick(this.currentLastRunTick_),t[a]=e}r++}else t[a]=this.resolveParam(l)}const a=this.timings_?performance.now():0;let l;try{l=e._fn(...t)}catch(n){throw this.flushSystem_(e,t,a),n}if(l instanceof Promise)return l.then(()=>{this.flushSystem_(e,t,a)},n=>{throw this.flushSystem_(e,t,a),n});this.flushSystem_(e,t,a)}flushSystem_(e,t,n){for(let e=0;e<t.length;e++)t[e]instanceof fn&&t[e].flush();this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}resolveParam(e){switch(e._type){case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new fn(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new xn(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new wn(n)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class kn{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 Rn=Et(new kn,"Input");class In{constructor(e){this.target_=e??null}build(e){const n=new kn;e.insertResource(Rn,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(bn.Last,Mn([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fn=new In,Bn=Et({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Un;function zn(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"}(Un||(Un={}));let Wn=null,Dn=null,Hn=1;const $n=new Map;function Ln(e){Wn=e,Dn=e.getResourceManager(),Jn()}function On(){0!==Xn&&Wn&&(Wn._free(Xn),Xn=0),$n.clear(),Hn=1,jn=!1,Gn.clear(),qn=null,Dn=null,Wn=null}function Vn(){if(!Dn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Dn}const Nn={createShader:(e,t)=>Vn().createShader(e,t),releaseShader(e){e>0&&Vn().releaseShader(e)},create(e){const t=Hn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Un.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return $n.set(t,n),t},get:e=>$n.get(e),setUniform(e,t,n){const s=$n.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Wn?.invalidateMaterialCache(e))},getUniform(e,t){const n=$n.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=$n.get(e);n&&(n.blendMode=t,Wn?.invalidateMaterialCache(e))},getBlendMode(e){const t=$n.get(e);return t?.blendMode??Un.Normal},setDepthTest(e,t){const n=$n.get(e);n&&(n.depthTest=t,Wn?.invalidateMaterialCache(e))},getShader(e){const t=$n.get(e);return t?.shader??0},release(e){$n.delete(e),Wn?.invalidateMaterialCache(e)},isValid:e=>$n.has(e),releaseAll(){$n.clear(),Wn?.clearMaterialCache()},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??Un.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=$n.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Hn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return $n.set(n,s),n},toAssetData(e,t){const n=$n.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=$n.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let jn=!1,Xn=0;const Yn=16384,Gn=new Map;let qn=null;function Kn(e){const t=(0===Xn&&Wn&&(Xn=Wn._malloc(Yn)),Xn);if(0===t||!Wn)return{ptr:0,count:0};let n=0,s=0;const i=Wn.HEAPU8,o=Wn.HEAPU32,r=Wn.HEAPF32;for(const[a,l]of e){if(zn(l))continue;let e=Gn.get(a);e||(qn||(qn=new TextEncoder),e=qn.encode(a),Gn.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Yn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Yn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Jn(){if(!Wn||jn)return;Wn.materialDataProvider=(e,t,n,s,i)=>{const o=$n.get(e);if(!o)return Wn.HEAPU32[t>>2]=0,Wn.HEAPU32[n>>2]=0,Wn.HEAPU32[s>>2]=0,void(Wn.HEAPU32[i>>2]=0);Wn.HEAPU32[t>>2]=o.shader,Wn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Kn(o.uniforms);Wn.HEAPU32[s>>2]=r,Wn.HEAPU32[i>>2]=a},jn=!0}const Zn={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 Qn{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=de.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+de.assetFailureCooldown}),t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`)),t}}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()}clearAll(){this.cache_.clear(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class es{constructor(e,t=""){this.cache_=new Qn,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Nn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Nn.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:Nn.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 ts(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function ns(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0,duration:e.duration};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const ss=new Map;function is(e){ss.set(e.name,e)}function os(e){ss.delete(e)}function rs(e){return ss.get(e)}function as(){ss.clear()}const ls=Ie("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function cs(e,t){const n=e.getEntitiesWithComponents([ls]);for(const s of n){const n=e.get(s,ls);if(!n.enabled||!n.playing||!n.clip)continue;const i=ss.get(n.clip);if(!i||0===i.frames.length)continue;const o=i.frames[n.currentFrame],r=o?.duration??1/(i.fps*n.speed),a=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let l=a;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),l=!0),l&&e.has(s,Je)){const t=i.frames[n.currentFrame],o=e.get(s,Je);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,Je,o)}l&&e.insert(s,ls,n)}}class us{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static setAssetResolver(e){this.assetResolver_=e}static resolveUrl_(e){return!this.baseUrl||e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}/${e}`}static async preload(e){if(this.bufferCache_.has(e))return;if(this.assetResolver_){const t=this.assetResolver_(e);if(t)return this.preloadFromData(e,t)}const t=await this.backend_.loadBuffer(this.resolveUrl_(e));this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}us.mixer_=null,us.bufferCache_=new Map,us.bgmHandle_=null,us.bgmVolume_=1,us.fadeAnimId_=0,us.disposed_=!1,us.assetResolver_=null,us.baseUrl="";const hs=new Map,ds=new Map;function fs(e,t,n){hs.set(e,{width:t,height:n})}function ps(e){return hs.get(e)}function ms(){hs.clear()}function gs(e,t){ds.set(e,t)}function ys(e){return ds.get(e)}function _s(){ds.clear()}let xs=null;function ws(e){xs=e}function bs(){xs=null}const vs={initLayer(e,t,n,s,i){xs?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){xs?.tilemap_destroyLayer(e)},setTile(e,t,n,s){xs?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>xs?xs.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){xs?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!xs)return;const n=t.byteLength,s=xs._malloc(n);new Uint16Array(xs.HEAPU8.buffer,s,t.length).set(t),xs.tilemap_setTiles(e,s,t.length),xs._free(s)},hasLayer:e=>!!xs&&xs.tilemap_hasLayer(e),setRenderProps(e,t,n,s,i,o,r,a,l){xs?.tilemap_setRenderProps(e,t,n,s,i,o,r,a,l)},setTint(e,t,n,s,i,o){xs?.tilemap_setTint(e,t,n,s,i,o)},setVisible(e,t){xs?.tilemap_setVisible(e,t)},setOriginEntity(e,t){xs?.tilemap_setOriginEntity(e,t)},submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,y,_,x){xs?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,y,_,x)},setTileAnimation(e,t,n){if(!xs||0===n.length)return;const s=new Uint32Array(2*n.length);for(let e=0;e<n.length;e++)s[2*e]=n[e].tileId,s[2*e+1]=n[e].duration;const i=s.byteLength,o=xs._malloc(i);new Uint32Array(xs.HEAPU8.buffer,o,s.length).set(s),xs.tilemap_setTileAnimation(e,t,o,n.length),xs._free(o)},advanceAnimations(e,t){xs?.tilemap_advanceAnimations(e,t)},setTileProperty(e,t,n,s){xs?.tilemap_setTileProperty(e,t,n,s)},getTileProperty:(e,t,n,s)=>xs?xs.tilemap_getTileProperty(e,t,n,s):"",flipTile(e,t,n,s,i,o){xs?.tilemap_flipTile(e,t,n,s,i,o)},rotateTile(e,t,n,s){xs?.tilemap_rotateTile(e,t,n,s)},setGridType(e,t){xs?.tilemap_setGridType(e,t)},tileToWorld(e,t,n,s,i){if(!xs)return{x:0,y:0};const o=xs.tilemap_tileToWorld(e,t,n,s,i),r=new Float32Array(xs.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}},worldToTile(e,t,n,s,i){if(!xs)return{x:0,y:0};const o=xs.tilemap_worldToTile(e,t,n,s,i),r=new Float32Array(xs.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}}},Ss=Ie("Tilemap",{source:""}),Ms=Ie("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function Cs(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function Ps(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function Ts(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function Es(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=Ts(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,h=Ps(e.tintcolor),d="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:h,parallaxX:d,parallaxY:f})}const u=[],h=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}const d=new Map,f=new Map;if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.id,s=n+1,i=e.animation;if(i&&i.length>0){const e=i.map(e=>({tileId:(e.tileid??0)+1,duration:e.duration??100}));d.set(s,e)}const o=e.properties;if(o){const e=new Map;for(const s of o){const i=s.name;"collision"===i&&!0===s.value&&h.push(n+t),e.set(i,String(s.value))}e.size>0&&f.set(s,e)}}}return{width:t,height:n,tileWidth:s,tileHeight:i,orientation:e.orientation??"orthogonal",layers:c,tilesets:r,objectGroups:u,collisionTileIds:h,tileAnimations:d,tileProperties:f}}function As(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function ks(e,t){const n=xs;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),orientation:"orthogonal",layers:[],tilesets:[],objectGroups:[],collisionTileIds:[],tileAnimations:new Map,tileProperties:new Map},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?Cs(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch(e){return console.warn("[Tiled] Failed to parse tilemap",e),n.tiled_freeMap(r),null}}const Rs=Math.PI/180;function Is(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,h=o+(u-t.row*c)-.5*s,d=e.spawn();e.insert(d,Ge,{position:{x:r,y:h,z:0}}),e.insert(d,pt,{bodyType:Pt.Static}),e.insert(d,mt,{halfExtents:{x:.5*n,y:.5*s}}),a.push(d)}return a}function Fs(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,Ge,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Ms,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,h=-t.rotation*Rs;if(e.insert(r,Ge,{position:{x:c,y:u,z:0}}),e.insert(r,pt,{bodyType:Pt.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,gt,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,mt,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,mt,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,Ge,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=Is(e,n,t,a,0,0);i.push(...s)}return i}const Bs=0,Us=1,zs=2,Ws="property",Ds="spine",Hs="spriteAnim",$s="audio",Ls="activation",Os="marker",Vs="customEvent",Ns="animFrames",js="hermite",Xs="linear",Ys="step",Gs="easeIn",qs="easeOut",Ks="easeInOut",Js=[["1.0","1.1",e=>{for(const t of e.tracks??[])if(t.type===Ws)for(const e of t.channels??[])for(const t of e.keyframes??[])t.interpolation||Math.abs(t.outTangent)>=1e5&&(t.interpolation="step",t.outTangent=0)}]];const Zs={once:Bs,loop:Us,pingPong:zs};function Qs(e){const t={name:e.name??"",childPath:e.childPath??""};switch(e.type){case Ws:return{...t,type:Ws,component:e.component??"",channels:(e.channels??[]).map(e=>({property:e.property,keyframes:e.keyframes??[]}))};case Ds:return{...t,type:Ds,clips:e.clips??[],blendIn:e.blendIn??0};case Hs:return{...t,type:Hs,clip:e.clip??"",startTime:e.startTime??0};case $s:return{...t,type:$s,events:e.events??[]};case Ls:return{...t,type:Ls,ranges:e.ranges??[]};case Os:return{...t,type:Os,markers:e.markers??[]};case Vs:return{...t,type:Vs,events:(e.events??[]).map(e=>({time:e.time??0,name:e.name??"",payload:e.payload??{}}))};case Ns:return{...t,type:Ns,frames:(e.animFrames??[]).map(e=>({texture:e.texture??"",duration:e.duration}))};default:return console.warn(`[Timeline] Unknown track type: ${e.type}, skipping`),null}}function ei(e){return function(e){let t=e.version??"1.0";for(const[n,s,i]of Js)t===n&&(i(e),t=s);e.version="1.1"}(e),{version:"1.1",type:"timeline",duration:e.duration??0,wrapMode:(t=e.wrapMode,t?Zs[t]??Bs:Bs),tracks:(e.tracks??[]).map(Qs).filter(e=>null!==e)};var t}let ti=!1,ni=!1;function si(e){ti=e}function ii(){return ti}function oi(){return!ti}function ri(e){ni=e}function ai(){return ni}var li,ci;!function(e){e[e.PositionX=0]="PositionX",e[e.PositionY=1]="PositionY",e[e.PositionZ=2]="PositionZ",e[e.ScaleX=3]="ScaleX",e[e.ScaleY=4]="ScaleY",e[e.ScaleZ=5]="ScaleZ",e[e.RotationZ=6]="RotationZ",e[e.ColorR=7]="ColorR",e[e.ColorG=8]="ColorG",e[e.ColorB=9]="ColorB",e[e.ColorA=10]="ColorA",e[e.SpriteOpacity=11]="SpriteOpacity",e[e.SpriteSizeX=12]="SpriteSizeX",e[e.SpriteSizeY=13]="SpriteSizeY",e[e.OffsetMinX=14]="OffsetMinX",e[e.OffsetMinY=15]="OffsetMinY",e[e.OffsetMaxX=16]="OffsetMaxX",e[e.OffsetMaxY=17]="OffsetMaxY",e[e.AnchorMinX=18]="AnchorMinX",e[e.AnchorMinY=19]="AnchorMinY",e[e.AnchorMaxX=20]="AnchorMaxX",e[e.AnchorMaxY=21]="AnchorMaxY",e[e.PivotX=22]="PivotX",e[e.PivotY=23]="PivotY",e[e.CameraOrthoSize=24]="CameraOrthoSize",e[e.CustomField=25]="CustomField"}(li||(li={})),function(e){e[e.Transform=0]="Transform",e[e.Sprite=1]="Sprite",e[e.UIRect=2]="UIRect",e[e.Camera=3]="Camera",e[e.Custom=4]="Custom"}(ci||(ci={}));const ui={Transform:{"position.x":li.PositionX,"position.y":li.PositionY,"position.z":li.PositionZ,"scale.x":li.ScaleX,"scale.y":li.ScaleY,"scale.z":li.ScaleZ,rotation:li.RotationZ},Sprite:{"color.r":li.ColorR,"color.g":li.ColorG,"color.b":li.ColorB,"color.a":li.ColorA,opacity:li.SpriteOpacity,"size.x":li.SpriteSizeX,"size.y":li.SpriteSizeY},UIRect:{"offsetMin.x":li.OffsetMinX,"offsetMin.y":li.OffsetMinY,"offsetMax.x":li.OffsetMaxX,"offsetMax.y":li.OffsetMaxY,"anchorMin.x":li.AnchorMinX,"anchorMin.y":li.AnchorMinY,"anchorMax.x":li.AnchorMaxX,"anchorMax.y":li.AnchorMaxY,"pivot.x":li.PivotX,"pivot.y":li.PivotY},Camera:{orthoSize:li.CameraOrthoSize}},hi={Transform:ci.Transform,Sprite:ci.Sprite,UIRect:ci.UIRect,Camera:ci.Camera},di={[js]:0,[Xs]:1,[Ys]:2,[Gs]:3,[qs]:4,[Ks]:5};function fi(e){return e?di[e]??0:0}function pi(e,t){return ui[e]?.[t]??li.CustomField}function mi(e,t){const n=(new TextEncoder).encode(t),s=e._malloc(n.length);return new Uint8Array(e.HEAPU8.buffer,s,n.length).set(n),[s,n.length]}function gi(e,t){e._free(t)}function yi(e,t){const n=e._tl_create(t.duration,t.wrapMode);if(!n)return{handle:0,tracks:[],totalPropertyChannels:0};const s=[];let i=0;for(const o of t.tracks)switch(o.type){case Ws:_i(e,n,o),s.push({type:"property",component:o.component,childPath:o.childPath,channelProperties:o.channels.map(e=>e.property)}),i+=o.channels.length;break;case Ds:xi(e,n,o),s.push({type:"spine",childPath:o.childPath});break;case $s:wi(e,n,o),s.push({type:"audio",childPath:o.childPath});break;case Ls:bi(e,n,o),s.push({type:"activation",childPath:o.childPath});break;case Hs:vi(e,n,o),s.push({type:"spriteAnim",childPath:o.childPath})}return{handle:n,tracks:s,totalPropertyChannels:i}}function _i(e,t,n){const s=e,i=n.channels.length,o=hi[n.component]??ci.Custom;if(o===ci.Custom)return void function(e,t,n){const s=e,i=n.channels.length,[o,r]=mi(e,n.childPath),[a,l]=mi(e,n.component),c=n.channels.map(e=>(new TextEncoder).encode(e.property));let u=0;for(const e of c)u+=e.length;const h=s._malloc(u);let d=0;for(const e of c)new Uint8Array(s.HEAPU8.buffer,h+d,e.length).set(e),d+=e.length;const f=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,f,i).set(c.map(e=>e.length));let p=0;const m=[];for(const e of n.channels)m.push(e.keyframes.length),p+=e.keyframes.length;const g=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,g,i).set(m);const y=s._malloc(5*p*4),_=new Float32Array(s.HEAPU8.buffer,y,5*p);let x=0;for(const e of n.channels)for(const t of e.keyframes)_[x++]=t.time,_[x++]=t.value,_[x++]=t.inTangent,_[x++]=t.outTangent,_[x++]=fi(t.interpolation);e._tl_addCustomPropertyTrack(t,o,r,a,l,h,f,i,y,g),gi(e,o),gi(e,a),gi(e,h),gi(e,f),gi(e,g),gi(e,y)}(e,t,n);const[r,a]=mi(e,n.childPath),l=s._malloc(i),c=new Uint8Array(s.HEAPU8.buffer,l,i);for(let e=0;e<i;e++)c[e]=pi(n.component,n.channels[e].property);let u=0;const h=[];for(const e of n.channels)h.push(e.keyframes.length),u+=e.keyframes.length;const d=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,d,i).set(h);const f=s._malloc(5*u*4),p=new Float32Array(s.HEAPU8.buffer,f,5*u);let m=0;for(const e of n.channels)for(const t of e.keyframes)p[m++]=t.time,p[m++]=t.value,p[m++]=t.inTangent,p[m++]=t.outTangent,p[m++]=fi(t.interpolation);e._tl_addPropertyTrack(t,r,a,o,l,i,f,d),gi(e,r),gi(e,l),gi(e,d),gi(e,f)}function xi(e,t,n){if(n.type!==Ds)return;const s=e,[i,o]=mi(e,n.childPath),r=n.clips.length,a=s._malloc(4*r*4),l=new Float32Array(s.HEAPU8.buffer,a,4*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),h=s._malloc(4*r),d=new Int32Array(s.HEAPU8.buffer,h,r),f=[];for(let t=0;t<r;t++){const s=n.clips[t];l[4*t]=s.start,l[4*t+1]=s.duration,l[4*t+2]=s.speed,l[4*t+3]=s.loop?1:0;const[i,o]=mi(e,s.animation);u[t]=i,d[t]=o,f.push(i)}e._tl_addSpineTrack(t,i,o,a,c,h,r,n.blendIn),gi(e,i),gi(e,a),gi(e,c),gi(e,h);for(const t of f)gi(e,t)}function wi(e,t,n){if(n.type!==$s)return;const s=e,[i,o]=mi(e,n.childPath),r=n.events.length,a=s._malloc(2*r*4),l=new Float32Array(s.HEAPU8.buffer,a,2*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),h=s._malloc(4*r),d=new Int32Array(s.HEAPU8.buffer,h,r),f=[];for(let t=0;t<r;t++){const s=n.events[t];l[2*t]=s.time,l[2*t+1]=s.volume;const[i,o]=mi(e,s.clip);u[t]=i,d[t]=o,f.push(i)}e._tl_addAudioTrack(t,i,o,a,c,h,r),gi(e,i),gi(e,a),gi(e,c),gi(e,h);for(const t of f)gi(e,t)}function bi(e,t,n){if(n.type!==Ls)return;const s=e,[i,o]=mi(e,n.childPath),r=s._malloc(2*n.ranges.length*4),a=new Float32Array(s.HEAPU8.buffer,r,2*n.ranges.length);for(let e=0;e<n.ranges.length;e++)a[2*e]=n.ranges[e].start,a[2*e+1]=n.ranges[e].end;e._tl_addActivationTrack(t,i,o,r,n.ranges.length),gi(e,i),gi(e,r)}function vi(e,t,n){if(n.type!==Hs)return;const[s,i]=mi(e,n.childPath),[o,r]=mi(e,n.clip);e._tl_addSpriteAnimTrack(t,s,i,o,r,n.startTime),gi(e,s),gi(e,o)}const Si=new Map;let Mi=null;function Ci(e,t){Si.set(e,t)}function Pi(e){return Si.get(e)}function Ti(){if(Mi)for(const e of Si.values())Mi._tl_destroy(e);Si.clear()}var Ei;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Ei||(Ei={}));const Ai={model:Ei.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function ki(e,t=Ai){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case Ei.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case Ei.Inverse:a=s/Math.max(r,s);break;case Ei.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Ri(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const Ii=Ie("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Ei.Inverse,rolloff:1,priority:0,enabled:!0}),Fi=Ie("AudioListener",{enabled:!0});class Bi{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;us.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(bn.PreUpdate,Mn([At(Ft)],t=>{if(!(!ii()||ai()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,h=!1;const d=s.getEntitiesWithComponents([Fi,Ke]);for(const e of d){if(s.get(e,Fi).enabled){const t=s.get(e,Ke);i=t.position.x,u=t.position.y,h=!0;break}}const f=s.getEntitiesWithComponents([Ii]);a.clear();for(const e of f){const t=s.get(e,Ii);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=us.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,Ke),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=ki(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Ri(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),us.dispose()}}const Ui=new Bi,zi=Ie("TimelinePlayer",{timeline:"",playing:!1,speed:1,wrapMode:"once"}),Wi=new Map;function Di(e,t){Wi.set(e,t)}const Hi=new Map;function $i(e,t){return Hi.get(e)?.get(t)??0}const Li={once:Bs,loop:Us,pingPong:zs};function Oi(e,t,n){const s=t.split(".");let i=e;for(let e=0;e<s.length-1;e++)if(i=i[s[e]],null==i||"object"!=typeof i)return!1;const o=s[s.length-1];return o in i&&(i[o]=n,!0)}function Vi(e,t,n){if(!n)return t;const s=Le("Children"),i=Le("Name");if(!s||!i)return null;let o=t;const r=n.split("/");for(const t of r){const n=e.tryGet(o,s);if(!n)return null;const r=n.entities||[];let a=null;for(const n of r){const s=e.tryGet(n,i);if(s&&s.value===t){a=n;break}}if(null===a)return null;o=a}return o}class Ni{constructor(){this.name="TimelinePlugin",this.handles_=new Map,this.animFramesStates_=new Map}build(e){const t=e.world;e.addSystemToSchedule(bn.Update,Mn([At(Ft)],e=>{if(ii()&&!ai())return;const n=t.getWasmModule();if(!n)return;Mi=n;const s=t.getCppRegistry();n.uiRect_clearAnimOverrides(s);const i=t.getEntitiesWithComponents([zi]);for(const s of i){const i=t.get(s,zi);if(!i.timeline)continue;let o=this.handles_.get(s);if(!o){const e=Wi.get(i.timeline);if(!e)continue;if(o=yi(n,e),!o.handle)continue;this.resolveTrackTargets(t,n,o,s),this.handles_.set(s,o),Ci(s,o.handle);const r=e.tracks.filter(e=>e.type===Ns);r.length>0&&this.animFramesStates_.set(s,{tracks:r,lastFrameIndices:r.map(()=>-1)})}const r=o.handle;if(i.playing&&!n._tl_isPlaying(r)){const e=n._tl_getTime(r);0===e?n._tl_play(r):(n._tl_play(r),n._tl_setTime(r,e))}else!i.playing&&n._tl_isPlaying(r)&&n._tl_pause(r);const a=Li[i.wrapMode]??Bs;n._tl_setWrapMode(r,a),n._tl_advance(t.getCppRegistry(),r,s,e.delta,i.speed),this.processEvents(t,n),this.processCustomProperties(t,n,o),this.processAnimFrames(t,n,s,o.handle,i.timeline),n._tl_clearResults(),!n._tl_isPlaying(r)&&i.playing&&(i.playing=!1,t.insert(s,zi,i))}},{name:"TimelineSystem"}))}clearHandles(){this.handles_.clear(),this.animFramesStates_.clear()}cleanup(){this.handles_.clear(),this.animFramesStates_.clear(),Wi.clear()}processAnimFrames(e,t,n,s,i){const o=this.animFramesStates_.get(n);if(!o)return;const r=t._tl_getTime(s),a=Le("Sprite");if(!a||!e.has(n,a))return;const l=1/12;for(let t=0;t<o.tracks.length;t++){const s=o.tracks[t].frames;if(0===s.length)continue;let c=0,u=0;for(let e=0;e<s.length;e++){const t=s[e].duration??l;if(r<c+t){u=e;break}c+=t,e===s.length-1&&(u=s.length-1)}if(u!==o.lastFrameIndices[t]){o.lastFrameIndices[t]=u;const r=$i(i,s[u].texture);if(r){const t=e.get(n,a);t.texture=r,e.set(n,a,t)}}}}resolveTrackTargets(e,t,n,s){let i=0,o=0;for(const r of n.tracks){if(!r.childPath){"property"===r.type?i++:o++;continue}const a=Vi(e,s,r.childPath);if(null!==a){const e="property"!==r.type,s=e?o:i;t._tl_setTrackTarget(n.handle,e?1:0,s,a)}"property"===r.type?i++:o++}}decodeEventString(e,t){const n=e._tl_getEventString(t),s=e._tl_getEventStringLen(t);if(!n||s<=0)return"";const i=new Uint8Array(e.HEAPU8.buffer,n,s);return(new TextDecoder).decode(i)}processEvents(e,t){const n=t._tl_getEventCount();for(let s=0;s<n;s++){const n=t._tl_getEventType(s),i=t._tl_getEventEntity(s);switch(n){case 0:{const n=this.decodeEventString(t,s),o=0!==t._tl_getEventIntParam(s);if(e.has(i,ot)){const t=e.get(i,ot);t.animation=n,t.playing=!0,t.loop=o,e.set(i,ot,t)}break}case 1:if(e.has(i,ot)){const t=e.get(i,ot);t.playing=!1,e.set(i,ot,t)}break;case 2:{const n=this.decodeEventString(t,s);if(e.has(i,ls)){const t=e.get(i,ls);e.insert(i,ls,{...t,clip:n,playing:!0})}break}case 3:{const e=this.decodeEventString(t,s),n=t._tl_getEventFloatParam(s);e&&us.playSFX(e,{volume:n});break}case 4:{const n=0!==t._tl_getEventIntParam(s);if(e.has(i,ot)){const t=e.get(i,ot);t.enabled=n,e.set(i,ot,t)}if(e.has(i,ls)){const t=e.get(i,ls);e.insert(i,ls,{...t,enabled:n})}const o=Le("Sprite");if(o&&e.has(i,o)){const t=e.get(i,o);e.set(i,o,{...t,enabled:n})}break}}}}processCustomProperties(e,t,n){const s=t._tl_getCustomPropertyCount();if(0!==s)for(let i=0;i<s;i++){const s=t._tl_getCustomPropertyEntity(i),o=t._tl_getCustomPropertyTrackIndex(i),r=t._tl_getCustomPropertyChannelIndex(i),a=t._tl_getCustomPropertyValue(i),l=n.tracks.filter(e=>"property"===e.type)[o];if(!l?.component||!l.channelProperties)continue;const c=Le(l.component);if(!c||!e.has(s,c))continue;const u=e.get(s,c),h=l.channelProperties[r];h&&Oi(u,h,a)&&e.set(s,c,u)}}}const ji=new Ni,Xi=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["UIRenderer",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}],["TimelinePlayer",{fields:[{field:"timeline",type:"timeline"}]}]]);function Yi(e,t){Xi.set(e,t)}function Gi(e){const t=Xi.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function qi(e){return Xi.get(e)?.fields??[]}function Ki(e){return Xi.get(e)?.spine??null}function Ji(e,t){const n=Te(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function Zi(e){const t=e.components.some(e=>"UIRect"===e.type),n=e.components.findIndex(e=>"Sprite"===e.type),s=e.components.some(e=>"UIRenderer"===e.type);if(!t||-1===n||s)return;const i=e.components[n].data,o=i.texture;e.components.push({type:"UIRenderer",data:{visualType:o?2:1,texture:o??0,color:i.color??{r:1,g:1,b:1,a:1},uvOffset:i.uvOffset??{x:0,y:0},uvScale:i.uvScale??{x:1,y:1},sliceBorder:i.sliceBorder??{x:0,y:0,z:0,w:0},material:i.material??0,enabled:i.enabled??!0}}),e.components.splice(n,1)}function Qi(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,ut,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;Zi(s);const t=n.get(s.id);for(const i of s.components)Ji(i,n),so(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function eo(e,t){return Qi(e,t)}async function to(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of no.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Xi.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...no.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Xi.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=Qi(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const no=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),fs(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=ts(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);is(ns(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await us.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=Es(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=As(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),fs(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}gs(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}],["timeline",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=ei(await t.loadJson(e));Di(e,i);const o=function(e){const t=new Set,n=new Set,s=new Set;for(const i of e.tracks)if(i.type===$s)for(const e of i.events)t.add(e.clip);else if(i.type===Hs)i.clip&&n.add(i.clip);else if(i.type===Ns)for(const e of i.frames)e.texture&&s.add(e.texture);return{audio:Array.from(t),animClips:Array.from(n),textures:Array.from(s)}}(i);if(o.textures.length>0){const i=new Map,r=o.textures.map(async e=>{try{const o=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o)}catch(t){console.warn(`Failed to load animFrames texture: ${e}`,t),i.set(e,0)}});await Promise.all(r),function(e,t){Hi.set(e,t)}(e,i)}}catch(t){console.warn(`Failed to load timeline: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function so(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=Le(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function io(e,t){const n=e.getEntitiesWithComponents([Qe]);for(const s of n){const n=e.get(s,Qe);n&&(n.aspectRatio=t,e.insert(s,Qe,n))}}function oo(e,t){const n=e.getEntitiesWithComponents([ut]);for(const s of n){const n=e.get(s,ut);if(n&&n.value===t)return s}return null}class ro{constructor(e){this.textureCache_=new Qn,this.shaderCache_=new Qn,this.jsonCache_=new Qn,this.textCache_=new Qn,this.binaryCache_=new Qn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Qn,this.prefabCache_=new Qn,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(de.textCanvasSize,de.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new es(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureRefCounts_.get(s);if(void 0===i)continue;const o=this.textureCache_.get(s);if(!o)continue;const r=i-1;r<=0?(t.releaseTexture(o.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),Nn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===P(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=P(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of Gi(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=Ki(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 to(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){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=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Nn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Nn.createShader(i,o)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(W(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 ao=Et(null,"Assets");class lo{build(e){const t=e.wasmModule;t?e.insertResource(ao,new ro(t)):console.warn("AssetPlugin: No WASM module available")}}const co=new lo;class uo{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function ho(e,t){const n=e.getResource(ao);n&&n.registerEmbeddedAssets(t)}function fo(e){return e.map(e=>({type:e.type,data:JSON.parse(JSON.stringify(e.data))}))}function po(e){return JSON.parse(JSON.stringify(e))}function mo(e,t){for(const n of e){const e=Te(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function go(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:po(n.componentData.data)})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}function yo(e,t,n){const s=n.depth??0;if(s>10)throw new Error(`Prefab nesting depth exceeded 10. Check for deep or circular nesting in: ${e.name}`);if(e.basePrefab)return function(e,t,n,s){const i=e.basePrefab,o=n.visited??new Set;if(o.has(i))throw new Error(`[Prefab] Circular variant reference detected: "${i}" is already being instantiated in the current prefab chain`);const r=n.loadPrefab(i);if(!r)throw new Error(`Failed to load base prefab for variant: ${i}`);o.add(i);const a=[...e.overrides??[],...t];return yo(r,a,{...n,visited:o,depth:s+1})}(e,t,n,s);const i=n.visited??new Set,o=new Map;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,n.allocateId());const r=[];for(const a of e.entities){if(a.nestedPrefab){const e=a.nestedPrefab.prefabPath;if(i.has(e))throw new Error(`[Prefab] Circular reference detected: "${e}" is already being instantiated in the current prefab chain`);const t=n.loadPrefab(e);if(!t)throw new Error(`Failed to load nested prefab: ${e}`);i.add(e);const l=yo(t,a.nestedPrefab.overrides,{...n,visited:i,depth:s+1});o.set(a.prefabEntityId,l.rootId);const c=l.entities.find(e=>e.id===l.rootId);c&&(c.parent=null!==a.parent?o.get(a.parent)??null:null),r.push(...l.entities);continue}const l=o.get(a.prefabEntityId),c=a.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:a.prefabEntityId,name:a.name,parent:c?null:null!==a.parent?o.get(a.parent)??null:null,children:a.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:fo(a.components),visible:a.visible};mo(u.components,o),go(u,t),r.push(u)}const a=o.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:r,rootId:a}}function _o(e,t,n){const s=[],i=n??new Set;if(e.basePrefab&&!i.has(e.basePrefab)){i.add(e.basePrefab),s.push(e.basePrefab);const n=t(e.basePrefab);n&&s.push(..._o(n,t,i))}for(const n of e.entities){if(!n.nestedPrefab)continue;const e=n.nestedPrefab.prefabPath;if(i.has(e))continue;i.add(e),s.push(e);const o=t(e);o&&s.push(..._o(o,t,i))}return s}async function xo(e,t,n,s,i=0){if(i>10)return;const o=s??new Set;if(e.basePrefab&&!o.has(e.basePrefab)&&!n.has(e.basePrefab)){o.add(e.basePrefab);const s=await t(e.basePrefab);n.set(e.basePrefab,s),await xo(s,t,n,o,i+1)}for(const s of e.entities){if(!s.nestedPrefab)continue;const e=s.nestedPrefab.prefabPath;if(o.has(e)||n.has(e))continue;o.add(e);const r=await t(e);n.set(e,r),await xo(r,t,n,o,i+1)}}async function wo(e,t,n){const s=new Map;n?.assetServer&&await xo(t,e=>n.assetServer.loadPrefab(e,n.assetBaseUrl),s);let i=0;const o={allocateId:()=>i++,loadPrefab:e=>s.get(e)??null,visited:new Set},{entities:r,rootId:a}=yo(t,n?.overrides??[],o),l={version:t.version,name:t.name,entities:r.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},c=await to(e,l,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),u=c.get(a);return void 0!==n?.parent&&e.setParent(u,n.parent),{root:u,entities:c}}class bo{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return wo(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const vo=Et(null,"Prefabs");class So{constructor(){this.name="PrefabsPlugin",this.dependencies=[ao]}build(e){const t=e.getResource(ao);e.insertResource(vo,new bo(e.world,t))}}const Mo=new So;let Co=null,Po=0,To=0,Eo=0;const Ao=new Float32Array(256);function ko(e){Co=e,Po=Co._malloc(64),To=Co._malloc(64),Eo=Co._malloc(1024)}function Ro(){Co&&(Po&&(Co._free(Po),Po=0),To&&(Co._free(To),To=0),Eo&&(Co._free(Eo),Eo=0)),Co=null}function Io(){if(!Co)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Co}const Fo={r:1,g:1,b:1,a:1},Bo={begin(e){const t=Io();try{t.HEAPF32.set(e,Po/4),t.draw_begin(Po)}catch(e){Lt(e,"Draw.begin")}},end(){try{Io().draw_end()}catch(e){Lt(e,"Draw.end")}},line(e,t,n,s=1){try{Io().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Lt(e,"Draw.line")}},rect(e,t,n,s=!0){try{Io().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Lt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Io().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Lt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Io().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Lt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Io().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Lt(e,"Draw.circleOutline")}},texture(e,t,n,s=Fo){try{Io().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Lt(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Fo){try{Io().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Lt(e,"Draw.textureRotated")}},setLayer(e){Io().draw_setLayer(e)},setDepth(e){Io().draw_setDepth(e)},getDrawCallCount:()=>Co?Co.draw_getDrawCallCount():0,getPrimitiveCount:()=>Co?Co.draw_getPrimitiveCount():0,setBlendMode(e){Io().draw_setBlendMode(e)},setDepthTest(e){Io().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Io();s.HEAPF32.set(n,To/4),s.draw_mesh(e,t,To)}catch(n){Lt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Io(),i=Nn.get(t);if(!i)return;if(Bo.setBlendMode(i.blendMode),Bo.setDepthTest(i.depthTest),0===i.uniforms.size)return void Bo.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,To/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=Wo(t);if(!(s<0)){if(zn(n))Ao[o++]=10,Ao[o++]=s,Ao[o++]=n.slot??e++,Ao[o++]=n.textureId;else if("number"==typeof n)Ao[o++]=1,Ao[o++]=s,Ao[o++]=n;else if(Array.isArray(n)){Ao[o++]=n.length,Ao[o++]=s;for(let e=0;e<n.length;e++)Ao[o++]=n[e]}else"w"in n?(Ao[o++]=4,Ao[o++]=s,Ao[o++]=n.x,Ao[o++]=n.y,Ao[o++]=n.z,Ao[o++]=n.w):"z"in n?(Ao[o++]=3,Ao[o++]=s,Ao[o++]=n.x,Ao[o++]=n.y,Ao[o++]=n.z):(Ao[o++]=2,Ao[o++]=s,Ao[o++]=n.x,Ao[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(Ao.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,To);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Eo/4),s.draw_meshWithUniforms(e,i.shader,To,Eo,o)}catch(n){Lt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Uo={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},zo=new Set;function Wo(e){const t=Uo[e];return void 0!==t?t:(zo.has(e)||(zo.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Uo).join(", ")}`)),-1)}const Do=new Map;function Ho(e,t,n){Do.set(e,{fn:t,scene:n??""})}function $o(e){Do.delete(e)}function Lo(){Do.clear()}var Oo;!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"}(Oo||(Oo={}));let Vo=null,No=0,jo=0,Xo=0;function Yo(e){Vo=e,No=Vo._malloc(262144),jo=Vo._malloc(65536),Xo=Vo._malloc(256)}function Go(){Vo&&(No&&Vo._free(No),jo&&Vo._free(jo),Xo&&Vo._free(Xo),No=0,jo=0,Xo=0),Vo=null}function qo(){if(!Vo)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Vo}const Ko={create(e){const t=qo(),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,No/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Xo,i).set(o),t.geometry_init(n,No,s,Xo,i,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,jo,s).set(e.indices),t.geometry_setIndices16(n,jo,s)}else{new Uint32Array(t.HEAPU8.buffer,jo,s).set(e.indices),t.geometry_setIndices32(n,jo,s)}}return n},updateVertices(e,t,n=0){const s=qo(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,No/4),s.geometry_updateVertices(e,No,i,n)},release(e){e>0&&qo().geometry_release(e)},isValid:e=>!(!Vo||e<=0)&&Vo.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Ko.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:Oo.Float2},{name:"a_texCoord",type:Oo.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 i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Ko.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Oo.Float2},{name:"a_texCoord",type:Oo.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return Ko.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Oo.Float2},{name:"a_texCoord",type:Oo.Float2}],indices:new Uint16Array(r)})}};let Jo=1;const Zo=new Map,Qo=new Map;function er(){return Zo}function tr(){return Qo}class nr{constructor(){this.passes_=[],this.destroyed_=!1,this.id=Jo++,Zo.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}clearPasses(){return this.passes_.length=0,this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of Qo)t===this&&Qo.delete(e);Zo.delete(this.id)}}}const sr="#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";let ir=null;function or(e){ir=e}function rr(){for(const e of er().values())e.destroy();er().clear(),tr().clear(),ir&&lr.isInitialized()&&lr.shutdown(),ir=null}function ar(){if(!ir)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ir}const lr={createStack:()=>new nr,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");tr().set(e,t)},unbind(e){tr().delete(e)},getStack:e=>tr().get(e)??null,init(e,t){try{return ar().postprocess_init(e,t)}catch(n){return Lt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{ar().postprocess_shutdown()}catch(e){Lt(e,"PostProcess.shutdown")}},resize(e,t){try{ar().postprocess_resize(e,t)}catch(n){Lt(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!ir)return!1;try{return ir.postprocess_isInitialized()}catch(e){return Lt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{ar().postprocess_setBypass(e)}catch(e){Lt(e,"PostProcess.setBypass")}},begin(){try{ar().postprocess_begin()}catch(e){Lt(e,"PostProcess.begin")}},end(){try{ar().postprocess_end()}catch(e){Lt(e,"PostProcess.end")}},setOutputViewport(e,t,n,s){try{ar().postprocess_setOutputViewport(e,t,n,s)}catch(e){Lt(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=tr().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(lr.isInitialized()||lr.init(1,1),lr.setBypass(!1),function(e){const t=ar();try{t.postprocess_clearPasses()}catch(e){return void Lt(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){Lt(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){Lt(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Lt(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):lr.setBypass(!0)},_resetAfterCamera(){try{ar().postprocess_clearPasses(),ar().postprocess_setBypass(!0)}catch(e){Lt(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of tr().keys())e(t)||tr().delete(t)},screenStack:null,setScreenStack(e){lr.screenStack=e},_beginScreenCapture(){try{ar().postprocess_beginScreenCapture()}catch(e){Lt(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{ar().postprocess_endScreenCapture()}catch(e){Lt(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=lr.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=ar();try{t.postprocess_clearScreenPasses()}catch(e){return void Lt(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){Lt(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){Lt(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Lt(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{ar().postprocess_executeScreenPasses()}catch(e){Lt(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Nn.createShader(sr,"#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:()=>Nn.createShader(sr,"#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 vig = 1.0 - smoothstep(1.0 - u_softness, 1.0, dist);\n fragColor = vec4(color.rgb * mix(1.0, vig, u_intensity), color.a);\n}\n"),createGrayscale:()=>Nn.createShader(sr,"#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"),createBloomExtract:()=>Nn.createShader(sr,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_threshold;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float brightness = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float knee = u_threshold * 0.5;\n float soft = brightness - u_threshold + knee;\n soft = clamp(soft, 0.0, 2.0 * knee);\n soft = soft * soft / (4.0 * knee + 0.00001);\n float contrib = max(soft, brightness - u_threshold);\n contrib /= max(brightness, 0.00001);\n fragColor = vec4(color.rgb * contrib, 1.0);\n}\n"),createBloomKawase(e){const t=`#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n float d = (${e.toFixed(1)} + 0.5) * max(u_radius, 0.5);\n vec2 ts = 1.0 / u_resolution;\n fragColor = (\n texture(u_texture, v_texCoord + vec2(-d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2(-d, d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, d) * ts)\n ) * 0.25;\n}\n`;return Nn.createShader(sr,t)},createBloomComposite:()=>Nn.createShader(sr,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform sampler2D u_sceneTexture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 blur = texture(u_texture, v_texCoord);\n vec4 scene = texture(u_sceneTexture, v_texCoord);\n fragColor = vec4(scene.rgb + blur.rgb * u_intensity, scene.a);\n}\n"),createChromaticAberration:()=>Nn.createShader(sr,"#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")},cr=new Map;function ur(e){cr.set(e.type,e)}function hr(e){return cr.get(e)}function dr(){return Array.from(cr.keys())}function fr(){return Array.from(cr.values())}ur({type:"blur",label:"Blur",factory:()=>lr.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),ur({type:"bloom",label:"Bloom",factory:()=>lr.createBloomExtract(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:1,step:.01,defaultValue:.4},{name:"u_intensity",label:"Intensity",min:0,max:5,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:.5,max:5,step:.1,defaultValue:1}],multiPass:[{name:"bloom_extract",factory:()=>lr.createBloomExtract()},{name:"bloom_kawase_0",factory:()=>lr.createBloomKawase(0)},{name:"bloom_kawase_1",factory:()=>lr.createBloomKawase(1)},{name:"bloom_kawase_2",factory:()=>lr.createBloomKawase(2)},{name:"bloom_kawase_3",factory:()=>lr.createBloomKawase(3)},{name:"bloom_kawase_4",factory:()=>lr.createBloomKawase(4)},{name:"bloom_composite",factory:()=>lr.createBloomComposite()}]}),ur({type:"vignette",label:"Vignette",factory:()=>lr.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:.6},{name:"u_softness",label:"Softness",min:0,max:1,step:.01,defaultValue:.5}]}),ur({type:"grayscale",label:"Grayscale",factory:()=>lr.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),ur({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>lr.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const pr=new Map,mr=new Map;function gr(e,t){let n=pr.get(e),s=mr.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=lr.createStack(),pr.set(e,n)),s||(s=new Map,mr.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=hr(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}lr.bind(e,n)}else if(n&&(lr.unbind(e),n.destroy(),pr.delete(e)),s){for(const e of s.values())Nn.releaseShader(e);mr.delete(e)}}function yr(e){const t=pr.get(e);t&&(lr.unbind(e),t.destroy(),pr.delete(e));const n=mr.get(e);if(n){for(const e of n.values())Nn.releaseShader(e);mr.delete(e)}}function _r(){for(const e of pr.keys())yr(e)}const xr=Et({enabled:!0},"PostProcessVolumeConfig"),wr=new Map,br=new Map;function vr(e,t){const n=br.get(e);if(void 0!==n)return n;const s=t();return br.set(e,s),s}function Sr(e,t){if(0===t.size){const t=wr.get(e);return void(t&&(lr.unbind(e),t.destroy(),wr.delete(e)))}let n=wr.get(e);n||(n=lr.createStack(),wr.set(e,n)),n.clearPasses();for(const[e,s]of t){if(!s.enabled)continue;const t=hr(e);if(t)if(t.multiPass)for(const e of t.multiPass){const t=vr(e.name,e.factory);n.addPass(e.name,t);for(const[t,i]of s.uniforms)n.setUniform(e.name,t,i)}else{const i=vr(e,t.factory);n.addPass(e,i);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?lr.bind(e,n):lr.unbind(e)}const Mr=Mn([an(dt,Ge),an(Qe)],(e,t)=>{const n=[];for(const[t,s,i]of e)n.push({data:s,tx:{x:i.position.x,y:i.position.y}});const s=[];for(const{data:e}of n)e.isGlobal&&s.push({data:e,factor:1});const i=s.length>0?function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(s):new Map;for(const[e,n]of t)n.isActive&&Sr(e,i)},{name:"PostProcessVolumeSystem"});class Cr{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(xr,{enabled:!0}),e.addSystemToSchedule(bn.PostUpdate,Mr)}cleanup(){_r(),function(){for(const[e,t]of wr)lr.unbind(e),t.destroy();wr.clear();for(const e of br.values())Nn.releaseShader(e);br.clear()}(),lr.setScreenStack(null)}}const Pr=new Cr;var Tr,Er;!function(e){e[e.BatchFull=0]="BatchFull",e[e.TextureSlotsFull=1]="TextureSlotsFull",e[e.ScissorChange=2]="ScissorChange",e[e.StencilChange=3]="StencilChange",e[e.MaterialChange=4]="MaterialChange",e[e.BlendModeChange=5]="BlendModeChange",e[e.StageEnd=6]="StageEnd",e[e.TypeChange=7]="TypeChange",e[e.FrameEnd=8]="FrameEnd"}(Tr||(Tr={})),function(e){e[e.Sprite=0]="Sprite",e[e.Spine=1]="Spine",e[e.Mesh=2]="Mesh",e[e.ExternalMesh=3]="ExternalMesh",e[e.Text=4]="Text",e[e.Particle=5]="Particle",e[e.Shape=6]="Shape",e[e.UIElement=7]="UIElement"}(Er||(Er={}));var Ar;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ar||(Ar={}));const kr={None:0,Spine:1,Particles:2};let Rr=null,Ir=0;function Fr(e){Rr=e,Ir=Rr._malloc(64)}function Br(){Rr&&Ir&&(Rr._free(Ir),Ir=0),Rr=null}const Ur={init(e,t){Rr?.renderer_init(e,t)},resize(e,t){Rr?.renderer_resize(e,t)},beginFrame(){Rr?.renderer_beginFrame()},updateTransforms(e){if(Rr)try{Rr.renderer_updateTransforms(e._cpp)}catch(e){Lt(e,"Renderer.updateTransforms")}},begin(e,t){if(Rr&&Ir)try{Rr.HEAPF32.set(e,Ir/4),Rr.renderer_begin(Ir,t??0)}catch(e){Lt(e,"Renderer.begin")}},flush(){try{Rr?.renderer_flush()}catch(e){Lt(e,"Renderer.flush")}},end(){try{Rr?.renderer_end()}catch(e){Lt(e,"Renderer.end")}},submitAll(e,t,n,s,i,o){if(Rr)try{Rr.renderer_submitAll(e._cpp,t,n,s,i,o)}catch(e){Lt(e,"Renderer.submitAll")}},setStage(e){Rr?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Rr?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Rr?.renderer_releaseTarget(e)},getTargetTexture:e=>Rr?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rr?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Rr?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Rr?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Rr?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Rr?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Rr?Rr.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Rr?{drawCalls:Rr.renderer_getDrawCalls(),triangles:Rr.renderer_getTriangles(),sprites:Rr.renderer_getSprites(),text:Rr.renderer_getText(),spine:Rr.renderer_getSpine?.()??0,meshes:Rr.renderer_getMeshes(),culled:Rr.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0},captureNextFrame(){Rr?.renderer_captureNextFrame()},getCapturedData:()=>Rr?function(e){if(!e.renderer_hasCapturedData())return null;const t=e.renderer_getCapturedFrameSize();if(0===t)return null;const n=e.renderer_getCapturedFrameData(),s=e.renderer_getCapturedEntities(),i=e.renderer_getCapturedEntityCount(),o=e.renderer_getCapturedCameraCount(),r=e.HEAPU8,a=new DataView(r.buffer,n,76*t),l=new Uint32Array(r.buffer,s,i),c=[];for(let e=0;e<t;e++){const t=76*e,n=a.getUint32(t,!0),s=a.getUint32(t+4,!0),o=a.getUint8(t+8),r=a.getUint8(t+9),u=a.getUint8(t+10),h=a.getUint32(t+12,!0),d=a.getUint32(t+16,!0),f=a.getUint32(t+20,!0),p=a.getUint32(t+24,!0),m=a.getUint32(t+28,!0),g=a.getUint32(t+32,!0),y=a.getUint32(t+36,!0),_=a.getInt32(t+40,!0),x=a.getUint8(t+44),w=a.getInt32(t+48,!0),b=a.getInt32(t+52,!0),v=a.getInt32(t+56,!0),S=a.getInt32(t+60,!0),M=0!==a.getUint8(t+64),C=0!==a.getUint8(t+65),P=0!==a.getUint8(t+66),T=a.getInt32(t+68,!0),E=a.getUint8(t+72),A=[];for(let e=0;e<g&&y+e<i;e++)A.push(l[y+e]);c.push({index:n,cameraIndex:s,stage:o,type:r,blendMode:u,textureId:h,materialId:d,shaderId:f,vertexCount:p,triangleCount:m,entityCount:g,entityOffset:y,layer:_,flushReason:x,scissorX:w,scissorY:b,scissorW:v,scissorH:S,scissorEnabled:M,stencilWrite:C,stencilTest:P,stencilRef:T,textureSlotUsage:E,entities:A})}return{drawCalls:c,cameraCount:o}}(Rr):null,hasCapturedData:()=>Rr?.renderer_hasCapturedData()??!1,replayToDrawCall(e){Rr&&function(e,t){e.renderer_replayToDrawCall(t)}(Rr,e)},getSnapshotImageData:()=>Rr?function(e){const t=e.renderer_getSnapshotSize();if(0===t)return null;const n=e.renderer_getSnapshotWidth(),s=e.renderer_getSnapshotHeight();if(0===n||0===s)return null;const i=e.renderer_getSnapshotPtr(),o=e.HEAPU8,r=new Uint8ClampedArray(o.buffer,i,t),a=new Uint8ClampedArray(t),l=4*n;for(let e=0;e<s;e++){const t=e*l,n=(s-1-e)*l;a.set(r.subarray(t,t+l),n)}return new ImageData(a,n,s)}(Rr):null};let zr=null;function Wr(e){zr=e}function Dr(){zr=null}const Hr={enable(){zr?.gl_enableErrorCheck(!0)},disable(){zr?.gl_enableErrorCheck(!1)},check:e=>zr?.gl_checkErrors(e)??0,diagnose(){zr?.renderer_diagnose()}};class $r{constructor(){this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null,this.preFlushCallbacks_=[]}setActiveScenes(e){this.activeScenes_=e}addPreFlushCallback(e){this.preFlushCallbacks_.push(e)}beginFrame(){Ur.beginFrame()}beginScreenCapture(){lr.screenStack&&lr.screenStack.enabledPassCount>0&&(lr.isInitialized()||lr.init(1,1),lr._applyScreenStack(),lr._beginScreenCapture())}endScreenCapture(){lr.screenStack&&lr.screenStack.enabledPassCount>0&&(lr._endScreenCapture(),lr._executeScreenPasses())}submitScene(e,t,n,s){Ur.updateTransforms(e),Ur.submitAll(e,0,n.x,n.y,n.w,n.h);for(const t of this.preFlushCallbacks_)t(e);Ur.flush(),this.executeDrawCallbacks(t,s)}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Ur.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Ur.beginFrame(),Ur.setViewport(0,0,s,i),Ur.clearBuffers(3),Ur.begin(n),this.submitScene(t,n,{x:0,y:0,w:s,h:i},o),Ur.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==lr.getStack(r);a&&(lr._applyForCamera(r),lr.resize(s.w,s.h),lr.setOutputViewport(s.x,s.y,s.w,s.h),lr.begin()),Ur.setViewport(s.x,s.y,s.w,s.h),Ur.setScissor(s.x,s.y,s.w,s.h,!0),Ur.clearBuffers(i),Ur.setScissor(0,0,0,0,!1),Ur.begin(n),this.submitScene(t,n,s,o),Ur.end(),a&&(lr.end(),lr._resetAfterCamera())}executeDrawCallbacks(e,t){const n=Do;if(n.size>0){Bo.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Bo.end();for(const e of s)$o(e)}}}const Lr={None:0,SolidColor:1,Image:2,NineSlice:3},Or=Ve("UIRenderer",{visualType:Lr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),Vr="__scene_transition_overlay__";class Nr{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class jr{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,ht,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Ho(e,t,this.instance_.config.name)}bindPostProcess(e,t){lr.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){lr.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ht)){const n=this.app_.world.get(e,ht);n.persistent=t,this.app_.world.insert(e,ht,n)}}}class Xr{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())$o(t);for(const t of e.postProcessBindings.keys())lr.unbind(t)}this.transition_&&($o(Vr),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise((n,s)=>{const i=t.duration??de.sceneTransitionDuration,o=t.color??{...de.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:i,color:o,targetScene:e,options:t,resolve:n,reject:s},Ho(Vr,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;Bo.setLayer(9999),Bo.setDepth(9999),Bo.rect({x:0,y:0},{x:2e4,y:2e4},{r:o.r,g:o.g,b:o.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{reject:t}=this.transition_;this.transition_=null,$o(Vr),t(e)}})().catch(()=>{})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,$o(Vr),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Nr(t);this.scenes_.set(e,n);const s=new jr(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ao)?this.app_.getResource(ao):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Nr(t);this.scenes_.set(e,n);const s=new jr(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ao)?this.app_.getResource(ao):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,ht)){if(this.app_.world.get(e,ht).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())$o(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())lr.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(ao)&&(i.assetServer=this.app_.getResource(ao));const o=await to(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,ht,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Gr(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(ao)?this.app_.getResource(ao):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)Nn.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,Je)){const t=n.get(e,Je);s.sprite=t.color.a,t.color.a=0,n.insert(e,Je,t),i=!0}if(n.has(e,ot)){const t=n.get(e,ot);s.spine=t.color.a,t.color.a=0,n.insert(e,ot,t),i=!0}if(n.has(e,it)){const t=n.get(e,it);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,it,t),i=!0}if(n.has(e,Or)){const t=n.get(e,Or);s.uiRenderer=t.color.a,t.color.a=0,n.insert(e,Or,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,Je)){const t=n.get(e,Je);t.color.a=s.sprite,n.insert(e,Je,t)}if(void 0!==s.spine&&n.has(e,ot)){const t=n.get(e,ot);t.color.a=s.spine,n.insert(e,ot,t)}if(void 0!==s.bitmapText&&n.has(e,it)){const t=n.get(e,it);t.color.a=s.bitmapText,n.insert(e,it,t)}if(void 0!==s.uiRenderer&&n.has(e,Or)){const t=n.get(e,Or);t.color.a=s.uiRenderer,n.insert(e,Or,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Yr=Et(null,"SceneManager");function Gr(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Yr).getSceneStatus(t)&&n._fn(...s)}}}const qr=Mn([kt(Yr),At(Ft)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Kr={name:"SceneManager",build(e){const t=new Xr(e);e.insertResource(Yr,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Yr),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(bn.Startup,n),e.addSystemToSchedule(bn.Last,qr)}};class Jr{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new gn,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=async()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(bn.Last);else{await this.runSchedule(bn.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(bn.FixedPreUpdate),await this.runSchedule(bn.FixedUpdate),await this.runSchedule(bn.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(bn.PreUpdate),await this.runSchedule(bn.Update),await this.runSchedule(bn.PostUpdate),await this.runSchedule(bn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Jt,this.resources_=new It;for(const e of Object.values(bn))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Jr}getPlugin(e){return this.installed_plugins_.find(t=>t instanceof e)}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(bn.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(bn.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}async waitForPhysics(){this.physicsInitPromise_?await this.physicsInitPromise_:console.warn("[ESEngine] No PhysicsPlugin installed, waitForPhysics() is a no-op")}get isPhysicsReady(){return null!=this.physicsModule_}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return $t(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Yr).register(e),this}setInitialScene(e){return this.getResource(Yr).setInitial(e),this}async tick(e){if(this.runner_||(this.runner_=new An(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Ft)||this.resources_.insert(Ft,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_()),await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(bn.Last);else{await this.runSchedule(bn.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(bn.FixedPreUpdate),await this.runSchedule(bn.FixedUpdate),await this.runSchedule(bn.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(bn.PreUpdate),await this.runSchedule(bn.Update),await this.runSchedule(bn.PostUpdate),await this.runSchedule(bn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}async run(){this.running_||(this.running_=!0,this.runner_=new An(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Ft,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),await this.flushStartupSystems_(),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Lo();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Dr,Br,rr,Go,On,Ro];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){console.warn("[App] Shutdown despawn error:",e)}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}async flushStartupSystems_(){const e=this.systems_.get(bn.Startup);0!==e.length&&(this.sortedSystemsCache_.delete(bn.Startup),await this.runSchedule(bn.Startup),e.length=0,this.sortedSystemsCache_.delete(bn.Startup))}async runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{const t=this.runner_.run(e.system);t instanceof Promise&&await t}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(bn[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(Ft);t.delta=e,t.elapsed+=e,t.frameCount++}}function Zr(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Qr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ea(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case Xe.FixedWidth:return o;case Xe.FixedHeight:return r;case Xe.Expand:return Math.max(o,r);case Xe.Shrink:return Math.min(o,r);case Xe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const ta=[];function na(e){if(e<ta.length)return ta[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return ta.push(t),t}function sa(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,ht);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,h=0;if(i.projectionType===Ne.Orthographic){if(h=i.orthoSize,l){h=ea(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=oa(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=aa(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=ca(o.position.x,o.position.y,o.position.z),f=na(c.length);f.entity=e,f.viewProjection.set(ha(a,d)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ia=new Float32Array(16);function oa(e,t,n,s,i,o){const r=ia;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const ra=new Float32Array(16);function aa(e,t,n,s){const i=ra;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const la=new Float32Array(16);function ca(e,t,n){const s=la;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}const ua=new Float32Array(16);function ha(e,t){const n=ua;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const da={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},fa={Simple:0,Sliced:1,Tiled:2,Filled:3},pa={Horizontal:0,Vertical:1},ma={Left:0,Right:1,Bottom:2,Top:3},ga=Ie("Image",{texture:ye,color:{r:1,g:1,b:1,a:1},imageType:fa.Simple,fillMethod:pa.Horizontal,fillOrigin:ma.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),ya=Ve("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}}),_a=Ve("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0});function xa(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,g=p+i.y):(p=h+n.y,g=d+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}let wa=null,ba=null;function va(e,t){switch(e){case da.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case da.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case da.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Sa(e,t){switch(e){case da.RightToLeft:return{anchorMin:{x:1-t,y:.5},anchorMax:{x:1-t,y:.5}};case da.BottomToTop:return{anchorMin:{x:.5,y:t},anchorMax:{x:.5,y:t}};case da.TopToBottom:return{anchorMin:{x:.5,y:1-t},anchorMax:{x:.5,y:1-t}};default:return{anchorMin:{x:t,y:.5},anchorMax:{x:t,y:.5}}}}function Ma(e,t,n,s){switch(e){case da.BottomToTop:case da.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Ca(e,t,n,s){if(!e.has(t,ya))return;const i=e.get(t,ya),o=va(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,ya,i)}function Pa(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}const Ta=1.15,Ea=.75;function Aa(e,t,n,s){return t?n?{r:e.r*Ea,g:e.g*Ea,b:e.b*Ea,a:e.a}:s?{r:Math.min(1,e.r*Ta),g:Math.min(1,e.g*Ta),b:Math.min(1,e.b*Ta),a:e.a}:{...e}:{r:.5*e.r,g:.5*e.g,b:.5*e.b,a:.6*e.a}}function ka(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ra(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(ka(r.charCodeAt(0))&&s.length>0&&ka(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!ka(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Ia(e){let t=1;for(;t<e;)t*=2;return t}function Fa(e,t){let n=0,s=t;for(;e.has(s,nt);){const t=e.get(s,nt).entity;if(!e.valid(t))break;n++,s=t}return n}function Ba(e,t){if(wa&&ba){const e=wa.getUIRectComputedWidth(ba,t);if(e>0)return e}return e.size.x}function Ua(e,t){if(wa&&ba){const e=wa.getUIRectComputedHeight(ba,t);if(e>0)return e}return e.size.y}function za(e,t,n){wa&&ba&&wa.setUIRectSize(ba,e,t,n)}function Wa(e,t,n,s,i,o){if(!e.has(t,Je))return;const r=e.get(t,Je);let a,l;switch(n){case da.BottomToTop:case da.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,Je,r))}function Da(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Ha(e,t){Da(e,t,_a,{enabled:!0,blockRaycast:!0,raycastTarget:!0})}function $a(e,t,n){0!==t&&e.valid(t)&&n(t)}function La(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a}function Oa(e,t,n){if(e.has(t,ga)){const s=e.get(t,ga);La(s.color,n)||(s.color=n,e.insert(t,ga,s))}else if(e.has(t,Je)){const s=e.get(t,Je);La(s.color,n)||(s.color=n,e.insert(t,Je,s))}else if(e.has(t,Or)){const s=e.get(t,Or);La(s.color,n)||(s.color=n,e.insert(t,Or,s))}}function Va(e,t,n){if(e.has(t,ga)){const s=e.get(t,ga);s.enabled!==n&&(s.enabled=n,e.insert(t,ga,s))}else if(e.has(t,Je)){const s=e.get(t,Je);s.enabled!==n&&(s.enabled=n,e.insert(t,Je,s))}else if(e.has(t,Or)){const s=e.get(t,Or);s.enabled!==n&&(s.enabled=n,e.insert(t,Or,s))}}function Na(e,t){return{r:Math.min(1,e.r*t),g:Math.min(1,e.g*t),b:Math.min(1,e.b*t),a:e.a}}function ja(e,t){return{r:e.r,g:e.g,b:e.b,a:t}}class Xa{constructor(){this.map_=new Map}get(e){return this.map_.get(e)}set(e,t){this.map_.set(e,t)}delete(e){this.map_.delete(e)}has(e){return this.map_.has(e)}cleanup(e){for(const[t]of this.map_)e.valid(t)||this.map_.delete(t)}ensureInit(e,t){let n=this.map_.get(e);return n||(n=t(),this.map_.set(e,n)),n}clear(){this.map_.clear()}[Symbol.iterator](){return this.map_[Symbol.iterator]()}}function Ya(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Ga=.1,qa={r:.3,g:.5,b:.8,a:1},Ka={r:.9,g:.9,b:.9,a:1},Ja={r:.95,g:.95,b:.95,a:1},Za={Left:0,Center:1,Right:2},Qa={Top:0,Middle:1,Bottom:2},el={Visible:0,Clip:1,Ellipsis:2},tl=Ie("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Za.Left,verticalAlign:Qa.Top,wordWrap:!0,overflow:el.Visible,lineHeight:1.2});class nl{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(de.textCanvasSize,de.textCanvasSize);const t=this.canvas.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("TextRenderer: failed to create 2D canvas context");this.ctx=t}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ia(this.frameMaxW_)),e.height=Math.max(e.height,Ia(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ia(this.frameMaxW_),e.height=Ia(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Ra(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===el.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Ia(f)),s.height=Math.max(s.height,Ia(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===el.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case Qa.Top:w=u;break;case Qa.Middle:w=u+(p-2*u-x)/2;break;case Qa.Bottom:w=p-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let s;switch(e.align){case Za.Left:s=u;break;case Za.Center:s=f/2;break;case Za.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===el.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),M=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const P=M.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:P,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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Za.Left:return"left";case Za.Center:return"center";case Za.Right:return"right"}}}const sl=Ya({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Ba(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ua(e.uiRect,e.entity):0});function il(e,t){e.has(t,Or)||e.insert(t,Or,{visualType:Lr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class ol{build(e){$e("Text",tl);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new nl(t),s=e.world,i=new Map;e.addSystemToSchedule(bn.PreUpdate,Mn([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,tl));for(const e of i.keys())if(!s.valid(e)||!s.has(e,tl)){if(s.valid(e)&&s.has(e,Or)){const t=s.get(e,Or);t.texture=0,t.visualType=Lr.None,s.insert(e,Or,t)}i.delete(e)}const e=s.getEntitiesWithComponents([tl]);for(const t of e){const e=s.get(t,tl),o=s.has(t,ya)?s.get(t,ya):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!sl.changed(a,r)){if(s.has(t,Or)&&0!==s.get(t,Or).texture)continue}il(s,t);const l=o?{size:{x:Ba(o,t),y:Ua(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Or);u.texture=c.textureHandle,u.visualType=Lr.Image,u.color={r:1,g:1,b:1,a:1},u.uvOffset={x:0,y:0},u.uvScale={x:1,y:1},s.insert(t,Or,u),o&&za(t,c.width,c.height),i.set(t,sl.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const rl=new ol,al=0,ll=Ve("UIMask",{enabled:!0,mode:al});class cl{build(e){$e("UIMask",ll)}}const ul=new cl;function hl(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=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,i-n),h:Math.max(0,o-s)}}function dl(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=s*l-i*a,w=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,M=o*u-r*c,C=h*g-d*m,P=h*y-f*m,T=h*_-p*m,E=d*y-f*g,A=d*_-p*g,k=f*_-p*y;let R=x*k-w*A+b*E+v*T-S*P+M*C;return 0===R||(R=1/R,n[0]=(l*k-c*A+u*E)*R,n[1]=(o*A-i*k-r*E)*R,n[2]=(g*M-y*S+_*v)*R,n[3]=(f*S-d*M-p*v)*R,n[4]=(c*T-a*k-u*P)*R,n[5]=(s*k-o*T+r*P)*R,n[6]=(y*b-m*M-_*w)*R,n[7]=(h*M-f*b+p*w)*R,n[8]=(a*A-l*T+u*C)*R,n[9]=(i*T-s*A-r*C)*R,n[10]=(m*S-g*b+_*x)*R,n[11]=(d*b-h*S-p*x)*R,n[12]=(l*P-a*E-c*C)*R,n[13]=(s*E-i*P+o*C)*R,n[14]=(g*w-m*v-y*x)*R,n[15]=(h*v-d*w+f*x)*R),n}function fl(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function pl(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function ml(e,t){return 2*Math.atan2(e,t)}function gl(e,t,n,s,i,o,r,a,l,c){if(0===l&&1===c)return pl(e,t,n,s,i,o,r,a);const u=ml(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,g=f*h+p*d+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}const yl=Ve("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),_l={Normal:0,Hovered:1,Pressed:2,Disabled:3},xl=Ie("Button",{state:_l.Normal,transition:null});class wl{constructor(){this.events_=[],this.entityTypeHandlers_=new Map,this.globalHandlers_=new Map,this.activeDispatches_=new Set,this.entityValidator_=null}on(e,t,n){if(void 0!==n){const s=e,i=t;let o=this.entityTypeHandlers_.get(s);o||(o=new Map,this.entityTypeHandlers_.set(s,o));let r=o.get(i);r||(r=[],o.set(i,r)),r.push(n);let a=!1;return()=>{if(a)return;a=!0;const e=o.get(i);if(e){const t=e.indexOf(n);-1!==t&&e.splice(t,1)}}}{const n=e,s=t;let i=this.globalHandlers_.get(n);i||(i=[],this.globalHandlers_.set(n,i)),i.push(s);let o=!1;return()=>{if(o)return;o=!0;const e=this.globalHandlers_.get(n);if(e){const t=e.indexOf(s);-1!==t&&e.splice(t,1)}}}}removeAll(e){this.entityTypeHandlers_.delete(e)}setEntityValidator(e){this.entityValidator_=e}emit(e,t,n){const s={entity:e,type:t,target:n??e,currentTarget:e,propagationStopped:!1,stopPropagation(){this.propagationStopped=!0}};this.events_.push(s);const i=`${e}:${t}`;return this.activeDispatches_.has(i)||(this.activeDispatches_.add(i),this.dispatchToHandlers_(s),this.activeDispatches_.delete(i)),s}emitBubbled(e,t,n,s){const i={entity:e,type:t,target:n,currentTarget:e,propagationStopped:!1,stopPropagation(){s.propagationStopped=!0}};this.events_.push(i);const o=`${e}:${t}`;this.activeDispatches_.has(o)||(this.activeDispatches_.add(o),this.dispatchToHandlers_(i),this.activeDispatches_.delete(o))}drain(){if(this.entityValidator_)for(const e of this.entityTypeHandlers_.keys())this.entityValidator_(e)||this.entityTypeHandlers_.delete(e);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)}dispatchToHandlers_(e){const t=this.entityTypeHandlers_.get(e.entity);if(t){const n=t.get(e.type);n&&this.invokeHandlers_([...n],e)}const n=this.globalHandlers_.get(e.type);n&&this.invokeHandlers_([...n],e)}invokeHandlers_(e,t){for(const n of e)try{n(t)}catch(e){console.error(`UIEvent handler error [${t.type}]:`,e)}}}const bl=Et(new wl,"UIEvents"),vl=Et({generation:0},"UILayoutGeneration");class Sl{build(e){$e("UIRect",ya),$e("UIRenderer",Or);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){wa=e,ba=t}(n,s);const i={generation:0};e.insertResource(vl,i);e.addSystemToSchedule(bn.PreUpdate,Mn([At(Bn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.transform_update(s),i.generation++)},{name:"UILayoutSystem"})),e.addSystemToSchedule(bn.PostUpdate,Mn([At(Bn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),i.generation++)},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(bn.PostUpdate,Mn([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ml=new Sl,Cl=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(dl(t,e),n=!1),e)}}();function Pl(e,t,n,s){const i=t.emit(n,s,n);!function(e,t,n){let s=t;for(;e.has(s,nt);){const t=e.get(s,nt).entity;if(!e.valid(t))break;if(n(t))return;s=t}}(e,n,o=>{if(i.propagationStopped)return!0;if(!e.has(o,_a))return!1;const r=e.get(o,_a);return r.enabled&&t.emitBubbled(o,s,n,i),r.blockRaycast})}class Tl{build(e){$e("Interactable",_a),$e("Button",xl);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new wl;i.setEntityValidator(e=>t.valid(e)),e.insertResource(bl,i);let o=null,r=null,a=NaN,l=NaN,c=-1;e.addSystemToSchedule(bn.PreUpdate,Mn([At(Rn),At(Bn),At(vl)],(e,u,h)=>{if(i.drain(),ii()&&!ai())return;const d=t.getEntitiesWithComponents([yl]);for(const e of d){const n=t.get(e,yl);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,yl,n))}if(!u.valid)return;const p=f(),m=e.mouseX*p,g=u.screenH-e.mouseY*p;Cl.update(u.viewProjection);const y=fl(m,g,Cl.getInverse(u.viewProjection),u.vpX,u.vpY,u.vpW,u.vpH);u.worldMouseX=y.x,u.worldMouseY=y.y;const _=e.isMouseButtonDown(0),x=e.isMouseButtonPressed(0),w=e.isMouseButtonReleased(0),b=y.x!==a||y.y!==l,v=h.generation!==c,S=b||v||(x||w);a=y.x,l=y.y,c=h.generation;let M=o;if(S){n.uiHitTest_update(s,y.x,y.y,_,x,w);const e=n.uiHitTest_getHitEntity();M=4294967295===e?null:e}if(null===o||t.valid(o)||(o=null),o!==M){if(null!==o&&t.valid(o)&&t.has(o,yl)){const e=t.get(o,yl);e.hovered=!1,t.insert(o,yl,e),i.emit(o,"hover_exit")}if(null!==M){Da(t,M,yl);const e=t.get(M,yl);e.hovered=!0,t.insert(M,yl,e),i.emit(M,"hover_enter")}o=M}if(x&&null!==M){const e=t.get(M,yl);e.pressed=!0,e.justPressed=!0,t.insert(M,yl,e),r=M,Pl(t,i,M,"press")}if(w&&null!==r){if(t.valid(r)&&t.has(r,yl)){const e=t.get(r,yl);e.pressed=!1,e.justReleased=!0,t.insert(r,yl,e),Pl(t,i,r,"release"),r===o&&Pl(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const u=new Set;e.addSystemToSchedule(bn.Update,Mn([],()=>{for(const e of u)t.valid(e)||u.delete(e);const e=t.getEntitiesWithComponents([xl]);for(const n of e){if(Da(t,n,_a,{enabled:!0}),!t.has(n,yl))continue;const e=t.get(n,yl),s=t.get(n,xl),i=t.get(n,_a),o=!u.has(n),r=s.state;if(i.enabled?e.pressed?s.state=_l.Pressed:e.hovered?s.state=_l.Hovered:s.state=_l.Normal:s.state=_l.Disabled,o&&u.add(n),(o||r!==s.state)&&s.transition){const o=Pa(s.transition,i.enabled,e.pressed,e.hovered);Oa(t,n,o)}else if((o||r!==s.state)&&!s.transition&&t.has(n,ga)){const s=Aa(t.get(n,ga).color,i.enabled,e.pressed,e.hovered);Oa(t,n,s)}}},{name:"ButtonSystem"}))}}const El=new Tl,Al=Ie("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),kl=Ie("Focusable",{tabIndex:0,isFocused:!1});class Rl{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Il=Et(new Rl,"FocusManager");class Fl{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if($e("TextInput",Al),ii()&&!ai())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=t,s=e.world,i=new Map,o=h(de.textCanvasSize,64),r=o.getContext("2d",{willReadFrequently:!0});if(!r)return void console.warn("TextInputPlugin: failed to create 2D canvas context");const a=r;let l=0,c=0,u=!1,d=!0,f=0,p=0;const m=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!m)return;const g=m;function y(){const t=e.getResource(Il);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Al)?n:null}const _=()=>{u||null===y()||S()},x=()=>{u=!0},w=()=>{u=!1,S()},b=t=>{const n=y();if(null===n)return;if("Escape"===t.key)return void M();const i=s.get(n,Al);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(bl).emit(n,"submit"),void M()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,g.selectionStart=o,g.selectionEnd=o,i.dirty=!0,C())},v=()=>{const t=y();if(null!==t){const n=s.get(t,Al);n.focused=!1,n.dirty=!0;e.getResource(Il).blur()}};function S(){const t=y();if(null===t)return;const n=s.get(t,Al);if(n.readOnly)return;let i=g.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),g.value=i),i!==n.value){n.value=i;e.getResource(bl).emit(t,"change")}n.cursorPos=g.selectionStart??i.length,n.dirty=!0,C()}function M(){const t=y();if(null!==t){const e=s.get(t,Al);e.focused=!1,e.dirty=!0}e.getResource(Il).blur(),g.blur()}function C(){d=!0,f=0}g.addEventListener("input",_),g.addEventListener("compositionstart",x),g.addEventListener("compositionend",w),g.addEventListener("keydown",b),g.addEventListener("blur",v),this.cleanupListeners_=()=>{g.removeEventListener("input",_),g.removeEventListener("compositionstart",x),g.removeEventListener("compositionend",w),g.removeEventListener("keydown",b),g.removeEventListener("blur",v),g.remove();const e=n.getResourceManager();for(const t of i.values())e.releaseTexture(t);i.clear(),0!==l&&(n._free(l),l=0,c=0)};let P=null;function T(e,t,r,u){(o.width<r||o.height<u)&&(o.width=Ia(Math.max(o.width,r)),o.height=Ia(Math.max(o.height,u))),a.clearRect(0,0,o.width,o.height);const h=t.backgroundColor;a.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,a.fillRect(0,0,r,u),a.save(),a.beginPath(),a.rect(t.padding,0,r-2*t.padding,u),a.clip(),a.font=`${t.fontSize}px ${t.fontFamily}`,a.textBaseline="top",a.textAlign="left";const f=0===t.value.length,p=f?t.placeholder:t.password?"●".repeat(t.value.length):t.value,m=f?t.placeholderColor:t.color;a.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*t.fontSize),y=t.padding;if(t.multiline){const e=Ra(a,p,r-2*y);let t=y;for(const n of e)a.fillText(n,y,t),t+=g}else{const e=(u-t.fontSize)/2;a.fillText(p,y,e)}if(t.focused&&d){const e=t.password?"●".repeat(t.cursorPos):t.value.substring(0,t.cursorPos);let n,s,i;if(t.multiline){const e=Ra(a,t.value,r-2*y);let o=0,l=0,c=0;for(let n=0;n<e.length;n++){const s=e[n].length;if(o+s>=t.cursorPos){l=n,c=t.cursorPos-o;break}o+=s,n<e.length-1&&o<t.value.length&&"\n"===t.value[o]&&o++,l=n+1,c=0}const u=l<e.length?e[l].substring(0,c):"";n=y+a.measureText(u).width,s=y+l*g,i=g}else n=y+a.measureText(e).width,s=(u-t.fontSize)/2,i=t.fontSize;a.fillStyle=`rgba(${Math.round(255*t.color.r)}, ${Math.round(255*t.color.g)}, ${Math.round(255*t.color.b)}, ${t.color.a})`,a.fillRect(n,s,2,i)}a.restore();const _=a.getImageData(0,0,r,u),x=new Uint8Array(_.data.buffer),w=n.getResourceManager();x.length>c&&(0!==l&&n._free(l),l=n._malloc(x.length),c=x.length),n.HEAPU8.set(x,l);const b=i.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(r,u,l,x.length,1,!0);i.set(e,v);const S=s.get(e,Or);S.texture=v,S.visualType=Lr.Image,S.uvOffset={x:0,y:0},S.uvScale={x:1,y:1},S.color={r:1,g:1,b:1,a:1},S.enabled=!0,s.insert(e,Or,S)}e.addSystemToSchedule(bn.Update,Mn([At(Il)],e=>{const t=s.getEntitiesWithComponents([Al]);for(const e of t)Da(s,e,kl,{tabIndex:0,isFocused:!1}),Da(s,e,_a,{enabled:!0,blockRaycast:!0});const n=y();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Al)){const e=s.get(P,Al);e.focused=!1,e.dirty=!0,g.blur()}null!==n&&function(e){const t=s.get(e,Al);t.readOnly||(t.focused=!0,t.dirty=!0,g.value=t.value,g.selectionStart=t.cursorPos,g.selectionEnd=t.cursorPos,g.focus(),C())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(bn.PreUpdate,Mn([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let t=0===p?0:(e-p)/1e3;p=e,t=Math.min(t,.1);const o=y();if(null!==o&&(f+=t,f>=.5)){f-=.5,d=!d;s.get(o,Al).dirty=!0}const r=n.getResourceManager();for(const[e,t]of i)s.valid(e)&&s.has(e,Al)||(r.releaseTexture(t),i.delete(e));const a=s.getEntitiesWithComponents([Al,ya]);for(const e of a){const t=s.get(e,Al);if(!t.dirty)continue;const n=s.get(e,ya),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(s.has(e,Or)||s.insert(e,Or,{visualType:Lr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),T(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Bl=new Fl,Ul=Ya({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Ba(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ua(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});function zl(e,t){e.has(t,Or)||e.insert(t,Or,{visualType:Lr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Wl{build(e){$e("Image",ga);const t=e.world,n=new Map;e.addSystemToSchedule(bn.PreUpdate,Mn([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,ga)||n.delete(e);const e=t.getEntitiesWithComponents([ga]);for(const s of e){const e=t.get(s,ga),i=t.has(s,ya)?t.get(s,ya):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&t.has(s,Or)&&!Ul.changed(r,o))continue;zl(t,s);const a=t.get(s,Or);if(!e.enabled){a.enabled=!1,t.insert(s,Or,a),n.set(s,Ul.take(o));continue}a.enabled=!0,a.texture=e.texture,a.color={r:e.color.r,g:e.color.g,b:e.color.b,a:e.color.a},a.material=e.material,a.uvOffset={x:0,y:0},a.uvScale={x:1,y:1};if(e.texture!==ye&&0!==e.texture?e.imageType===fa.Sliced?a.visualType=Lr.NineSlice:a.visualType=Lr.Image:a.visualType=Lr.SolidColor,e.imageType===fa.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));i&&Ba(i,s),i&&Ua(i,s),e.fillMethod===pa.Horizontal?(e.fillOrigin===ma.Left||(a.uvOffset={x:1-t,y:0}),a.uvScale={x:t,y:1}):(e.fillOrigin===ma.Bottom||(a.uvOffset={x:0,y:1-t}),a.uvScale={x:1,y:t})}else if(e.imageType===fa.Tiled){const t=i?Ba(i,s):0,n=i?Ua(i,s):0;e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale={x:t/e.tileSize.x,y:n/e.tileSize.y})}t.insert(s,Or,a),n.set(s,Ul.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Dl=new Wl,Hl=Ie("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null,onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1}},{entityFields:["graphicEntity","group"]}),$l=Ie("ToggleGroup",{allowSwitchOff:!1});function Ll(e,t,n){if(!e.has(t,Or))return;const s=e.get(t,Or);s.color.r===n.r&&s.color.g===n.g&&s.color.b===n.b&&s.color.a===n.a||(s.color=n,e.insert(t,Or,s))}function Ol(e,t,n){if(!e.has(t,Or))return;const s=e.get(t,Or);s.enabled!==n&&(s.enabled=n,e.insert(t,Or,s))}class Vl{build(e){$e("Toggle",Hl),$e("ToggleGroup",$l);const t=e.world,n=new Set;e.addSystemToSchedule(bn.Update,Mn([At(bl)],e=>{const s=t.getEntitiesWithComponents([Hl]);if(!ii()||ai()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Hl);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Hl,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Hl);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Da(t,n,_a,{enabled:!0}),!t.has(n,yl))continue;const s=t.get(n,yl),i=t.get(n,Hl),r=t.get(n,_a);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,$l);if(i.isOn&&r){if(!t.get(s,$l).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Hl,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Hl);i.isOn&&(i.isOn=!1,t.insert(s,Hl,i),e.emit(s,"change"))}}e.emit(n,"change")}let a;if(i.transition)a=Pa(i.transition,r.enabled,s.pressed,s.hovered);else{a=Aa(i.isOn?i.onColor:i.offColor,r.enabled,s.pressed,s.hovered)}Ll(t,n,a)}}for(const e of s){const n=t.get(e,Hl);$a(t,n.graphicEntity,e=>{Ol(t,e,n.isOn)})}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Nl=new Vl,jl=da,Xl=Ie("ProgressBar",{value:0,fillEntity:0,direction:da.LeftToRight},{entityFields:["fillEntity"]});class Yl{build(e){$e("ProgressBar",Xl);const t=e.world;e.addSystemToSchedule(bn.PreUpdate,Mn([],()=>{const e=t.getEntitiesWithComponents([Xl,ya]);for(const n of e){const e=t.get(n,Xl),s=Math.max(0,Math.min(1,e.value));$a(t,e.fillEntity,n=>{Ca(t,n,e.direction,s)})}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Gl=new Yl,ql=Ie("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Kl=Ie("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});function Jl(e,t,n,s){if(!e.has(t,nt))return{x:n,y:s};const i=e.get(t,nt).entity;if(!e.valid(i)||!e.has(i,Ge))return{x:n,y:s};const o=e.get(i,Ge),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=ml(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}class Zl{build(e){$e("Draggable",ql),$e("DragState",Kl);const t=e.world,n=e.getResource(bl);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(bn.PreUpdate,Mn([At(Rn),At(Bn)],(e,r)=>{if(ii()&&!ai())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ql,yl]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,ql).enabled)continue;if(t.get(s,yl).hovered){let e=0;t.has(s,Je)&&(e=t.get(s,Je).layer);const i=Fa(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,Kl)||t.insert(n,Kl);const e=t.get(n,Kl),o=t.get(n,Ge);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Kl)){t.get(s,Kl).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,ql);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,Kl).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Kl))return void(o=null);const s=t.get(o,Kl),i=t.get(o,ql),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,ya)){const e=t.get(o,ya),n=Jl(t,o,s.deltaWorld.x,s.deltaWorld.y);e.offsetMin.x+=n.x,e.offsetMin.y+=n.y,t.insert(o,ya,e)}else if(t.has(o,Ge)){const e=Jl(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,Ge);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,Ge,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const Ql=new Zl,ec=Ie("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1},{entityFields:["contentEntity"]});function tc(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function nc(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class sc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){$e("ScrollView",ec);const t=e.world,n=new Xa,s={x:0,y:0};e.addSystemToSchedule(bn.PostUpdate,Mn([At(Rn),At(Bn),At(Ft)],(e,i,o)=>{const r=ii()&&!ai(),a=Math.min(o.delta,.05);n.cleanup(t),i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([ec,ya]);for(const o of l){Da(t,o,ll,{enabled:!0,mode:al});const l=t.get(o,ec),c=t.get(o,ya),u=n.ensureInit(o,()=>({isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN})),h=Ba(c,o),d=Ua(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,st)){const e=t.get(l.contentEntity,st).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,Ge))continue;const e=t.get(r,Ge);let a=0,l=0,c=.5,u=.5;if(t.has(r,ya)){const e=t.get(r,ya);a=Ba(e,r)||e.size.x,l=Ua(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Je)){const e=t.get(r,Je);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<n&&(n=h),d>s&&(s=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Da(t,o,_a,{enabled:!0,blockRaycast:!0});const n=t.has(o,yl)?t.get(o,yl):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=tc(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=tc(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=tc(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=tc(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=nc(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Ga&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Ga?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=nc(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Ga&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Ga?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}$a(t,l.contentEntity,e=>{if(!t.has(e,Ge))return;const n=t.get(e,Ge),s=n.position.x,i=n.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(i-u.lastAppliedY)>.01)&&(u.contentBaseY=i),n.position.x=u.contentBaseX-l.scrollX,n.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=n.position.x,u.lastAppliedY=n.position.y,t.insert(e,Ge,n)})}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{n.clear()}}}const ic=new sc,oc=da,rc=Ie("Slider",{value:0,minValue:0,maxValue:1,direction:da.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1},{entityFields:["fillEntity","handleEntity"]});function ac(e,t,n,s,i,o){const r=Ba(s,i)*n.worldScale.x,a=Ua(s,i)*n.worldScale.y,l=ml(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-n.worldPosition.x,d=t-n.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case da.LeftToRight:return r>0?(f-m)/r:0;case da.RightToLeft:return r>0?1-(f-m)/r:0;case da.BottomToTop:return a>0?(p-g)/a:0;case da.TopToBottom:return a>0?1-(p-g)/a:0}}function lc(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case da.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=.5,e.anchorMax.x=n,e.anchorMax.y=.5;break;case da.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=.5,e.anchorMax.x=1-n,e.anchorMax.y=.5;break;case da.BottomToTop:e.anchorMin.x=.5,e.anchorMin.y=n,e.anchorMax.x=.5,e.anchorMax.y=n;break;case da.TopToBottom:e.anchorMin.x=.5,e.anchorMin.y=1-n,e.anchorMax.x=.5,e.anchorMax.y=1-n}}class cc{build(e){$e("Slider",rc);const t=e.world;e.addSystemToSchedule(bn.PreUpdate,Mn([At(Rn),At(Bn),At(bl)],(e,n,s)=>{if(!n.valid)return;const i=t.getEntitiesWithComponents([rc,ya]);for(const o of i){const i=t.get(o,rc),r=t.get(o,ya);if(!ii()||ai()){if(t.has(o,Ge)){Da(t,o,_a,{enabled:!0,blockRaycast:!0}),$a(t,i.handleEntity,e=>{Da(t,e,_a,{enabled:!0,blockRaycast:!1})});const a=t.get(o,Ge);let l=!1;if(t.has(o,yl)&&(l=t.get(o,yl).pressed),$a(t,i.handleEntity,e=>{!l&&t.has(e,yl)&&(l=t.get(e,yl).pressed)}),l&&e.isMouseButtonDown(0)){let e=ac(n.worldMouseX,n.worldMouseY,a,r,o,i.direction);e=Math.max(0,Math.min(1,e));let l=i.minValue+e*(i.maxValue-i.minValue);i.wholeNumbers&&(l=Math.round(l));const c=i.value;i.value=Math.max(i.minValue,Math.min(i.maxValue,l)),t.insert(o,rc,i),i.value!==c&&s.emit(o,"change")}}}const a=i.maxValue-i.minValue,l=a>0?(i.value-i.minValue)/a:0;$a(t,i.fillEntity,e=>{Ca(t,e,i.direction,l)}),$a(t,i.handleEntity,e=>{if(!t.has(e,ya))return;const n=t.get(e,ya);lc(n,i.direction,l),t.insert(e,ya,n)})}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const uc=new cc;class hc{build(e){$e("Focusable",kl);const t=e.world,n=new Rl;e.insertResource(Il,n),e.addSystemToSchedule(bn.Update,Mn([At(Rn),At(bl)],(e,s)=>{if(ii()&&!ai())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([kl]);for(const e of i){if(!t.has(e,yl))continue;t.get(e,yl).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,_a)){if(!t.get(n,_a).enabled)continue}const s=t.get(n,kl);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,kl)){t.get(i,kl).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,kl).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const dc=new hc,fc=Ie("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function pc(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class mc{build(e){$e("SafeArea",fc);const t=e.world;let n=pc(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=pc(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=pc(),s=!0});e.addSystemToSchedule(bn.PreUpdate,Mn([At(Bn)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([fc,ya]);for(const e of u){const s=t.get(e,fc),i=t.get(e,ya),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,ya,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const gc=new mc,yc=Ie("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let _c=null;function xc(e,t){if(!_c)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=_c.get(e);n?n.renderer=t:_c.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class wc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null),_c=null}build(e){$e("ListView",yc);const t=e.world,n=new Map;_c=n,e.addSystemToSchedule(bn.PostUpdate,Mn([At(Rn)],e=>{const s=ii()&&!ai();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([yc,ya]);for(const o of i){Da(t,o,_a,{enabled:!0,blockRaycast:!0}),Da(t,o,ll,{enabled:!0,mode:al});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,yc),a=t.get(o,ya),l=Ua(a,o),c=Ba(a,o);if(!s){const n=t.has(o,yl)?t.get(o,yl):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<d;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,ut,{value:`ListItem_${e}`}),t.insert(n,ya,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,Ge)){const s=t.get(n,Ge);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,Ge,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{for(const[,e]of n)for(const n of e.itemEntities.values())t.valid(n)&&t.despawn(n);n.clear()}}}const bc=new wc,vc=Ie("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0},{entityFields:["listEntity","labelEntity"]});class Sc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){$e("Dropdown",vc);const t=e.world,n=new Map,s=new Set;function i(e){$a(t,e,e=>{if(!t.has(e,Ge))return;const n=t.get(e,Ge);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,Ge,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})})}function o(e){if(t.has(e,Or)){const n=t.get(e,Or);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Oa(t,e,{...Ka})}else if(t.has(e,Je)){const n=t.get(e,Je);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Oa(t,e,{...Ka})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;h(i,!0),u(s);let o=0;if(t.has(e,ya)){const n=t.get(e,ya);o=Ba(n,e)||n.size.x}else if(t.has(e,Je)){o=t.get(e,Je).size.x}s.ddWidth=o;const r=30*n.options.length;t.insert(i,ya,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:r},pivot:{x:.5,y:1}}),t.insert(i,Or,{visualType:Lr.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn();t.insert(r,ut,{value:`Option_${e}`}),t.insert(r,ya,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:30*-e},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:1}}),t.insert(r,Ge,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,Or,{visualType:Lr.SolidColor,texture:0,color:{...Ja},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),t.insert(r,_a,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const a=t.spawn();t.insert(a,Ge,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(a,tl,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Za.Left,verticalAlign:Qa.Middle,wordWrap:!1,overflow:el.Clip,lineHeight:1.2}),t.insert(a,ya,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:.5}}),t.setParent(a,r),s.textEntities.push(a)}d(s)}function a(e,t,n){t.isOpen=!1,u(n),h(t.listEntity,!1)}function l(e,t,n,s,i){t.selectedIndex=s,a(0,t,n),i.emit(e,"change")}function c(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,tl))return;const s=t.get(n,tl);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,tl,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function u(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function h(e,n){$a(t,e,e=>{t.has(e,_a)&&t.insert(e,_a,{enabled:n,blockRaycast:!0,raycastTarget:!0}),Va(t,e,n)})}function d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s))continue;const i=n===e.highlightIndex?{...qa}:{...Ja};Oa(t,s,i)}}function f(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,yl))continue;if(t.get(n,yl).hovered)return!0}return!1}e.addSystemToSchedule(bn.Update,Mn([At(Rn),At(bl)],(e,p)=>{for(const[e,i]of n)t.valid(e)||(u(i),n.delete(e),s.delete(e));const m=ii()&&!ai(),g=t.getEntitiesWithComponents([vc]);for(const u of g){const g=t.get(u,vc);let y=n.get(u);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(u,y)),i(g.listEntity),s.has(u)||(o(u),s.add(u)),g.isOpen||h(g.listEntity,!1),c(g),m)continue;Da(t,u,_a,{enabled:!0,blockRaycast:!0});const _=t.has(u,yl)?t.get(u,yl):null;if(_?.justPressed&&(g.isOpen?a(u,g,y):r(u,g,y)),g.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,yl))continue;if(t.get(n,yl).justPressed){l(u,g,y,e,p);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,yl))continue;if(t.get(s,yl).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,d(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=g.options.length-1?y.highlightIndex=0:y.highlightIndex++,d(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=g.options.length-1:y.highlightIndex--,d(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?l(u,g,y,y.highlightIndex,p):e.isKeyPressed("Escape")&&a(u,g,y),e.isMouseButtonPressed(0)&&(_?.hovered||f(y)||a(u,g,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]}),this.cleanup_=()=>{for(const[,e]of n)u(e);n.clear(),s.clear()}}}const Mc=new Sc,Cc=Ve("LayoutGroup",{direction:0,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:0,reverseOrder:!1});class Pc{build(e){$e("LayoutGroup",Cc)}}const Tc=new Pc,Ec=0,Ac=1,kc=0,Rc=1,Ic=0,Fc=0,Bc=3,Uc=Ve("FlexContainer",{direction:Ec,wrap:kc,justifyContent:Ic,alignItems:Bc,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0}}),zc=Ve("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class Wc{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(bn.PostUpdate,Mn([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Dc=new Wc,Hc={primary:{r:.25,g:.56,b:.96,a:1},secondary:{r:.4,g:.4,b:.4,a:1},background:{r:.08,g:.08,b:.08,a:1},surface:{r:.14,g:.14,b:.14,a:1},error:{r:.9,g:.2,b:.2,a:1},text:{r:.93,g:.93,b:.93,a:1},textSecondary:{r:.6,g:.6,b:.6,a:1},border:{r:.3,g:.3,b:.3,a:1},fontFamily:"Arial",fontSize:{xs:10,sm:12,md:14,lg:18,xl:24},spacing:{xs:4,sm:8,md:12,lg:16,xl:24},button:{height:36,color:{r:.25,g:.25,b:.25,a:1},textColor:{r:.93,g:.93,b:.93,a:1},transition:{normalColor:{r:.25,g:.25,b:.25,a:1},hoveredColor:{r:.3,g:.3,b:.3,a:1},pressedColor:{r:.18,g:.18,b:.18,a:1},disabledColor:{r:.15,g:.15,b:.15,a:.6}}},slider:{trackHeight:16,trackColor:{r:.15,g:.15,b:.15,a:1},fillColor:{r:.25,g:.56,b:.96,a:1},handleSize:24,handleColor:{r:1,g:1,b:1,a:1}},toggle:{size:{x:24,y:24},onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1},checkColor:{r:1,g:1,b:1,a:1}},input:{height:36,backgroundColor:{r:.15,g:.15,b:.15,a:1},textColor:{r:1,g:1,b:1,a:1},placeholderColor:{r:.6,g:.6,b:.6,a:1},fontSize:16,padding:6},dropdown:{height:32,backgroundColor:{r:.2,g:.2,b:.2,a:1},itemHeight:28},panel:{backgroundColor:{r:.14,g:.14,b:.14,a:1},padding:12},scrollView:{backgroundColor:{r:.1,g:.1,b:.1,a:1}}},$c=Et(null,"UITheme");let Lc=null;function Oc(e){e.hasResource($c)&&(Lc=e.getResource($c))}function Vc(){return Lc??Hc}function Nc(e,t){const n=e.spawn();if(t.name&&e.insert(n,ut,{value:t.name}),e.insert(n,Ge,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},...t.transform}),t.rect&&e.insert(n,ya,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:0,y:0},pivot:{x:.5,y:.5},...t.rect}),t.renderer&&e.insert(n,Or,{visualType:Lr.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0,...t.renderer}),t.interactable&&e.insert(n,_a,{enabled:!0,blockRaycast:!0,raycastTarget:!0,...t.interactable}),t.text){const s=Vc();e.insert(n,tl,{content:"",fontFamily:s.fontFamily,fontSize:s.fontSize.md,color:{r:1,g:1,b:1,a:1},align:Za.Left,verticalAlign:Qa.Top,wordWrap:!1,overflow:0,lineHeight:1.2,...t.text})}if(t.image&&e.insert(n,ga,{...ga._default,...t.image}),t.flex&&e.insert(n,Uc,{direction:Ec,wrap:kc,justifyContent:Ic,alignItems:Bc,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0},...t.flex}),t.flexItem&&e.insert(n,zc,{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,...t.flexItem}),t.mask&&e.insert(n,ll,{enabled:!0,mode:al,...t.mask}),t.components)for(const[s,i]of t.components)e.insert(n,s,i);return t.parent&&e.setParent(n,t.parent),n}function jc(e,t={}){const n=Vc(),{text:s="Button",fontSize:i=n.fontSize.md,size:o={x:120,y:n.button.height},color:r=n.button.color,textColor:a=n.button.textColor,transition:l=null,parent:c}=t,u=Nc(e,{name:"ButtonLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:s,fontSize:i,color:a,align:Za.Center,verticalAlign:Qa.Middle}}),h=Nc(e,{name:"Button",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Lr.SolidColor,color:r},interactable:{enabled:!0},components:[[xl,{state:0,transition:l}]]});if(e.setParent(u,h),t.events){if(t.onClick){const e=t.onClick;t.events.on(h,"click",()=>e(h))}if(t.onHover){const e=t.onHover;t.events.on(h,"hover_enter",()=>e(h))}}return h}function Xc(e,t={}){const n=Vc(),{value:s=0,minValue:i=0,maxValue:o=1,direction:r=da.LeftToRight,size:a={x:200,y:n.slider.trackHeight},trackColor:l=n.slider.trackColor,fillColor:c=n.slider.fillColor,handleSize:u={x:n.slider.handleSize,y:n.slider.handleSize},handleColor:h=n.slider.handleColor,wholeNumbers:d=!1,parent:f}=t,p=Nc(e,{name:"SliderFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Lr.SolidColor,color:c}}),m=Nc(e,{name:"SliderHandle",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:u},renderer:{visualType:Lr.SolidColor,color:h},interactable:{enabled:!0,blockRaycast:!0},components:[[ql,{enabled:!0,dragThreshold:5,lockX:!1,lockY:!0}]]}),g=Nc(e,{name:"Slider",parent:f,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Lr.SolidColor,color:l},interactable:{enabled:!0,blockRaycast:!0},components:[[rc,{value:s,minValue:i,maxValue:o,direction:r,wholeNumbers:d,fillEntity:p,handleEntity:m}]]});if(e.setParent(p,g),e.setParent(m,g),t.onChange&&t.events){const n=t.onChange;t.events.on(g,"change",()=>{const t=e.get(g,rc);n(t.value,g)})}return g}function Yc(e,t={}){const n=Vc(),{isOn:s=!0,size:i=n.toggle.size,onColor:o=n.toggle.onColor,offColor:r=n.toggle.offColor,checkSize:a={x:.58*n.toggle.size.x,y:.58*n.toggle.size.y},checkColor:l=n.toggle.checkColor,group:c=0,transition:u=null,label:h,parent:d}=t,f=Nc(e,{name:"ToggleCheck",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Lr.SolidColor,color:l}}),p=Nc(e,{name:"Toggle",parent:d,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Lr.SolidColor,color:s?o:r},interactable:{enabled:!0},components:[[Hl,{isOn:s,graphicEntity:f,group:c,transition:u,onColor:o,offColor:r}]]});if(e.setParent(f,p),h&&Nc(e,{name:"ToggleLabel",parent:p,rect:{anchorMin:{x:1,y:0},anchorMax:{x:1,y:1},offsetMin:{x:8,y:0},size:{x:100,y:0}},text:{content:h,fontSize:n.fontSize.md,align:Za.Left,verticalAlign:Qa.Middle}}),t.onChange&&t.events){const n=t.onChange;t.events.on(p,"change",()=>{const t=e.get(p,Hl);n(t.isOn,p)})}return p}function Gc(e,t={}){const n=Vc(),{value:s=0,size:i={x:200,y:n.slider.trackHeight},direction:o=da.LeftToRight,trackColor:r=n.slider.trackColor,fillColor:a=n.primary,parent:l}=t,c=Nc(e,{name:"ProgressFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Lr.SolidColor,color:a}}),u=Nc(e,{name:"ProgressBar",parent:l,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Lr.SolidColor,color:r},components:[[Xl,{value:s,fillEntity:c,direction:o}]]});return e.setParent(c,u),u}function qc(e,t={}){const n=Vc(),{size:s={x:300,y:400},contentSize:i={x:300,y:800},horizontal:o=!1,vertical:r=!0,elastic:a=!0,mask:l=!0,parent:c}=t,u=Nc(e,{name:"ScrollContent",rect:{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},size:{x:i.x,y:i.y},pivot:{x:.5,y:1}}}),h=Nc(e,{name:"ScrollView",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:s},renderer:{visualType:Lr.SolidColor,color:n.scrollView.backgroundColor},mask:l?{mode:al,enabled:!0}:void 0,components:[[ec,{contentEntity:u,horizontalEnabled:o,verticalEnabled:r,contentWidth:i.x,contentHeight:i.y,elastic:a,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,wheelSensitivity:.1}]]});return e.setParent(u,h),h}function Kc(e,t={}){const n=Vc(),{placeholder:s="",value:i="",size:o={x:200,y:n.input.height},fontSize:r=n.input.fontSize,backgroundColor:a=n.input.backgroundColor,textColor:l=n.input.textColor,maxLength:c=0,multiline:u=!1,password:h=!1,parent:d}=t,f=Nc(e,{name:"TextInput",parent:d,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Lr.SolidColor,color:a},interactable:{enabled:!0},components:[[Al,{value:i,placeholder:s,fontSize:r,fontFamily:n.fontFamily,color:l,backgroundColor:a,placeholderColor:n.input.placeholderColor,padding:n.input.padding,maxLength:c,multiline:u,password:h,readOnly:!1,focused:!1,cursorPos:i.length,dirty:!0}],[kl,{tabIndex:0,isFocused:!1}]]});if(t.events){if(t.onChange){const n=t.onChange;t.events.on(f,"change",()=>{const t=e.get(f,Al);n(t.value,f)})}if(t.onSubmit){const n=t.onSubmit;t.events.on(f,"submit",()=>{const t=e.get(f,Al);n(t.value,f)})}}return f}function Jc(e,t){const n=Vc(),{options:s,selectedIndex:i=-1,size:o={x:160,y:n.dropdown.height},fontSize:r=n.fontSize.md,parent:a}=t,l=Nc(e,{name:"DropdownLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:(i>=0?s[i]:s[0])??"",fontSize:r,align:Za.Left,verticalAlign:Qa.Middle}}),c=Nc(e,{name:"DropdownList",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},size:{x:o.x,y:Math.min(s.length*n.dropdown.itemHeight,200)},pivot:{x:.5,y:1}},renderer:{visualType:Lr.SolidColor,color:n.surface},mask:{mode:al,enabled:!0}}),u=Nc(e,{name:"Dropdown",parent:a,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Lr.SolidColor,color:n.dropdown.backgroundColor},interactable:{enabled:!0},components:[[vc,{options:s,selectedIndex:i,isOpen:!1,listEntity:c,labelEntity:l}]]});if(e.setParent(l,u),e.setParent(c,u),t.onChange&&t.events){const n=t.onChange;t.events.on(u,"change",()=>{const t=e.get(u,vc);n(t.selectedIndex,u)})}return u}function Zc(e,t){const n=Vc();return Nc(e,{name:"Label",parent:t.parent,rect:t.size?{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size}:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:t.text,fontSize:t.fontSize??n.fontSize.md,color:t.color??n.text,align:t.align??Za.Left,verticalAlign:t.verticalAlign??Qa.Middle}})}function Qc(e,t={}){const n=Vc();return Nc(e,{name:"Panel",parent:t.parent,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size??{x:300,y:200}},renderer:{visualType:Lr.SolidColor,color:t.color??n.panel.backgroundColor}})}function eu(e,t={}){return Nc(e,{name:"FlexRow",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:Ec,wrap:t.wrap?Rc:kc,justifyContent:t.justifyContent??Ic,alignItems:t.alignItems??Fc,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}function tu(e,t={}){return Nc(e,{name:"FlexColumn",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:Ac,wrap:t.wrap?Rc:kc,justifyContent:t.justifyContent??Ic,alignItems:t.alignItems??Fc,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}const nu={button:jc,slider:Xc,toggle:Yc,textInput:Kc,dropdown:Jc,progressBar:Gc,label:Zc,panel:Qc,flexRow:eu,flexColumn:tu,scrollView:qc};const su={spawn:Nc,destroy:function e(t,n){if(t.valid(n)){if(t.has(n,st)){const s=[...t.get(n,st).entities];for(const n of s)e(t,n)}t.despawn(n)}},build:function e(t,n,s){let i,o;if("element"===n.type)i=Nc(t,{...n,parent:s}),o=i;else{if(i=(0,nu[n.type])(t,{...n.options??{},parent:s}),"scrollView"===n.type){o=t.get(i,ec).contentEntity}else o=i}const r=n.children;if(r&&o)for(const n of r)e(t,n,o);return n.ref&&n.ref(i),i},label:Zc,panel:Qc,button:jc,slider:Xc,toggle:Yc,scrollView:qc,textInput:Kc,dropdown:Jc,progressBar:Gc,flexRow:eu,flexColumn:tu};async function iu(e,t,n){const s=e.getResource(Yr);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}class ou{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let s,i;if("string"==typeof e){const t=(new TextEncoder).encode(e);i=t.length,s=this.raw_._malloc(i+1),this.raw_.HEAPU8.set(t,s),this.raw_.HEAPU8[s+i]=0}else i=e.length,s=this.raw_._malloc(i),this.raw_.HEAPU8.set(e,s);const o=this.api_.loadSkeleton(s,i,t,t.length,n);return this.raw_._free(s),o}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,s,i){this.api_.setAtlasPageTexture(e,t,n,s,i)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,s=0){return!!this.api_.playAnimation(e,t,n,s)}addAnimation(e,t,n=!0,s=0,i=0){return!!this.api_.addAnimation(e,t,n,s,i)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse animations JSON",e),[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse skins JSON",e),[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,s))return this.raw_._free(n),this.raw_._free(s),null;const i=this.raw_.HEAPF32[n>>2],o=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:i,y:o}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,s=t>>2,i={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(t),i}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],s=this.raw_._malloc(8),i=s,o=s+4;for(let s=0;s<t;s++){const t=this.api_.getMeshBatchVertexCount(e,s),r=this.api_.getMeshBatchIndexCount(e,s);if(t<=0||r<=0)continue;const a=8*t*4,l=2*r,c=this.raw_._malloc(a),u=this.raw_._malloc(l);this.api_.getMeshBatchData(e,s,c,u,i,o);const h=new Float32Array(this.raw_.HEAPF32.buffer,c,8*t),d=new Uint16Array(this.raw_.HEAPU8.buffer,u,r);n.push({vertices:new Float32Array(h),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[i>>2],blendMode:this.raw_.HEAPU32[o>>2]}),this.raw_._free(c),this.raw_._free(u)}return this.raw_._free(s),n}setDefaultMix(e,t){this.api_.setDefaultMix(e,t)}setMixDuration(e,t,n,s){this.api_.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){this.api_.setTrackAlpha(e,t,n)}setAttachment(e,t,n){return!!this.api_.setAttachment(e,t,n)}setIKTarget(e,t,n,s,i){return!!this.api_.setIKTarget(e,t,n,s,i)}setSlotColor(e,t,n,s,i,o){return!!this.api_.setSlotColor(e,t,n,s,i,o)}enableEvents(e){this.api_.enableEvents(e)}collectEvents(e){const t=this.api_.getEventCount(e);if(0===t)return[];const n=this.api_.getEventBuffer(),s=this.raw_.HEAPF32,i=n>>2,o=[];for(let e=0;e<t;e++){const t=i+4*e;o.push({type:s[t],track:s[t+1],floatValue:s[t+2],intValue:s[t+3]})}return this.api_.clearEvents(),o}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(n)}off(e,t,n){const s=this.listeners_.get(e);if(!s)return;const i=s.get(t);i&&i.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}class ru{constructor(e){this.entities_=new Map,this.cachedFrame_=-1,this.cachedEntries_=[],this.controller_=e}get controller(){return this.controller_}get entityCount(){return this.entities_.size}loadEntity(e,t,n,s,i){const o=this.controller_.loadSkeleton(t,n,i);if(o<0)return console.error(`[ModuleBackend] Failed to load skeleton: ${this.controller_.getLastError()}`),!1;const r=this.controller_.getAtlasPageCount(o);for(let e=0;e<r;e++){const t=this.controller_.getAtlasPageTextureName(o,e),n=s.get(t);n&&this.controller_.setAtlasPageTexture(o,e,n.glId,n.w,n.h)}const a=this.controller_.createInstance(o);return this.entities_.set(e,{skelHandle:o,instanceId:a,skeletonScale:1,flipX:!1,flipY:!1,layer:0}),!0}setEntityProps(e,t){const n=this.entities_.get(e);n&&(void 0!==t.skeletonScale&&(n.skeletonScale=t.skeletonScale),void 0!==t.flipX&&(n.flipX=t.flipX),void 0!==t.flipY&&(n.flipY=t.flipY),void 0!==t.layer&&(n.layer=t.layer))}setAnimation(e,t,n){const s=this.entities_.get(e);s&&this.controller_.play(s.instanceId,t,n)}setSkin(e,t){const n=this.entities_.get(e);n&&this.controller_.setSkin(n.instanceId,t)}getBounds(e){const t=this.entities_.get(e);return t?this.controller_.getBounds(t.instanceId):null}getAnimations(e){const t=this.entities_.get(e);return t?this.controller_.getAnimations(t.instanceId):[]}getSkins(e){const t=this.entities_.get(e);return t?this.controller_.getSkins(t.instanceId):[]}setDefaultMix(e,t){const n=this.entities_.get(e);n&&this.controller_.setDefaultMix(n.skelHandle,t)}setMixDuration(e,t,n,s){const i=this.entities_.get(e);i&&this.controller_.setMixDuration(i.skelHandle,t,n,s)}setTrackAlpha(e,t,n){const s=this.entities_.get(e);s&&this.controller_.setTrackAlpha(s.instanceId,t,n)}setAttachment(e,t,n){const s=this.entities_.get(e);return!!s&&this.controller_.setAttachment(s.instanceId,t,n)}setIKTarget(e,t,n,s,i){const o=this.entities_.get(e);return!!o&&this.controller_.setIKTarget(o.instanceId,t,n,s,i)}setSlotColor(e,t,n,s,i,o){const r=this.entities_.get(e);return!!r&&this.controller_.setSlotColor(r.instanceId,t,n,s,i,o)}enableEvents(e){const t=this.entities_.get(e);t&&this.controller_.enableEvents(t.instanceId)}updateAll(e){for(const t of this.entities_.values())this.controller_.update(t.instanceId,e)}extractAndSubmitMeshes(e,t,n=-1){const s=e.renderer_submitSpineBatchByEntity;if(!s)return;if(this.cachedFrame_!==n){this.cachedEntries_.length=0;for(const[e,t]of this.entities_){const n=this.controller_.extractMeshBatches(t.instanceId);for(const s of n)0!==s.vertices.length&&0!==s.indices.length&&this.cachedEntries_.push({vertices:s.vertices,indices:s.indices,textureId:s.textureId,blendMode:s.blendMode,entity:e,info:t})}this.cachedFrame_=n}if(0===this.cachedEntries_.length)return;let i=0,o=0;for(const e of this.cachedEntries_)i+=e.vertices.byteLength,o+=e.indices.byteLength;const r=e._malloc(i),a=e._malloc(o);let l=0,c=0;for(const n of this.cachedEntries_){const i=r+l,o=a+c;e.HEAPF32.set(n.vertices,i>>2),new Uint16Array(e.HEAPU8.buffer,o,n.indices.length).set(n.indices),s.call(e,t,i,n.vertices.length/8,o,n.indices.length,n.textureId,n.blendMode,n.entity,n.info.skeletonScale,n.info.flipX,n.info.flipY,n.info.layer,0),l+=n.vertices.byteLength,c+=n.indices.byteLength}e._free(r),e._free(a)}removeEntity(e){const t=this.entities_.get(e);t&&(this.controller_.destroyInstance(t.instanceId),this.controller_.unloadSkeleton(t.skelHandle),this.entities_.delete(e))}shutdown(){for(const e of this.entities_.values())this.controller_.destroyInstance(e.instanceId),this.controller_.unloadSkeleton(e.skelHandle);this.entities_.clear()}}class au{constructor(e,t){this.backends_=new Map,this.loadingBackends_=new Map,this.entityVersions_=new Map,this.coreModule_=e,this.factories_=t}static detectVersion(e){const t=function(e){if(e.length<10)return null;let t=8;const{value:n,bytesRead:s}=lu(e,t);if(t+=s,n<=1||t+n-1>e.length)return null;const i=(new TextDecoder).decode(e.subarray(t,t+n-1));return i.startsWith("4.2")?"4.2":i.startsWith("4.1")?"4.1":null}(e);return t||function(e){if(e.length<4)return null;let t=0;const{value:n,bytesRead:s}=lu(e,t);t+=s,n>0&&(t+=n-1);if(t>=e.length)return null;const{value:i,bytesRead:o}=lu(e,t);if(t+=o,i<=1||t+i-1>e.length)return null;const r=(new TextDecoder).decode(e.subarray(t,t+i-1));return r.startsWith("3.")?"3.8":null}(e)}static detectVersionJson(e){const t=e.match(/"spine"\s*:\s*"(\d+\.\d+)/);return t?t[1].startsWith("4.2")?"4.2":t[1].startsWith("4.1")?"4.1":t[1].startsWith("3.")?"3.8":null:null}async loadEntity(e,t,n,s,i){const o="string"==typeof t?au.detectVersionJson(t):au.detectVersion(t);if(!o)return null;if("4.2"===o&&!this.factories_.has("4.2"))return this.entityVersions_.set(e,"4.2"),"4.2";this.coreModule_.spine_setNeedsReload?.(i,e,!1);const r=await this.ensureBackend(o);if(!r)return console.error(`[SpineManager] Failed to create backend for version ${o}`),null;const a=t instanceof Uint8Array;return r.loadEntity(e,t,n,s,a)?(this.entityVersions_.set(e,o),o):(console.error(`[SpineManager] Failed to load entity ${e} into backend ${o}`),null)}updateAnimations(e){for(const t of this.backends_.values())t.updateAll(e)}submitMeshes(e,t=-1){for(const n of this.backends_.values())n.extractAndSubmitMeshes(this.coreModule_,e,t)}removeEntity(e){const t=this.entityVersions_.get(e);if(!t)return void this.entityVersions_.delete(e);const n=this.backends_.get(t);n&&n.removeEntity(e),this.entityVersions_.delete(e)}getEntityVersion(e){return this.entityVersions_.get(e)}hasModuleBackend(e){return this.backends_.has(e)}getModuleBackend(e){return this.backends_.get(e)}setAnimation(e,t,n){const s=this.entityVersions_.get(e);if(!s)return;const i=this.backends_.get(s);i&&i.setAnimation(e,t,n)}setSkin(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setSkin(e,t)}setEntityProps(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setEntityProps(e,t)}getBounds(e){const t=this.entityVersions_.get(e);if(!t)return null;const n=this.backends_.get(t);return n?n.getBounds(e):null}getAnimations(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getAnimations(e):[]}getSkins(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getSkins(e):[]}setDefaultMix(e,t){const n=this.getEntityBackend_(e);n&&n.setDefaultMix(e,t)}setMixDuration(e,t,n,s){const i=this.getEntityBackend_(e);i&&i.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){const s=this.getEntityBackend_(e);s&&s.setTrackAlpha(e,t,n)}setAttachment(e,t,n){const s=this.getEntityBackend_(e);return!!s&&s.setAttachment(e,t,n)}setIKTarget(e,t,n,s,i){const o=this.getEntityBackend_(e);return!!o&&o.setIKTarget(e,t,n,s,i)}setSlotColor(e,t,n,s,i,o){const r=this.getEntityBackend_(e);return!!r&&r.setSlotColor(e,t,n,s,i,o)}enableEvents(e){const t=this.getEntityBackend_(e);t&&t.enableEvents(e)}hasInstance(e){return this.entityVersions_.has(e)}shutdown(){for(const e of this.backends_.values())e.shutdown();this.backends_.clear(),this.loadingBackends_.clear(),this.entityVersions_.clear()}getEntityBackend_(e){const t=this.entityVersions_.get(e);if(t)return this.backends_.get(t)}async ensureBackend(e){const t=this.backends_.get(e);if(t)return t;const n=this.loadingBackends_.get(e);if(n)return n;const s=this.factories_.get(e);if(!s)return console.warn(`[SpineManager] No module factory for version ${e}`),null;const i=(async()=>{try{const t=await s(),n=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"]),setDefaultMix:t("spine_setDefaultMix",null,["number","number"]),setMixDuration:t("spine_setMixDuration",null,["number","string","string","number"]),setTrackAlpha:t("spine_setTrackAlpha",null,["number","number","number"]),enableEvents:t("spine_enableEvents",null,["number"]),getEventCount:t("spine_getEventCount","number",["number"]),getEventBuffer:t("spine_getEventBuffer","number",[]),clearEvents:t("spine_clearEvents",null,[]),setAttachment:t("spine_setAttachment","number",["number","string","string"]),setIKTarget:t("spine_setIKTarget","number",["number","string","number","number","number"]),setSlotColor:t("spine_setSlotColor","number",["number","string","number","number","number","number"])}}(t),i=new ou(t,n),o=new ru(i);return this.backends_.set(e,o),o}catch(t){return console.error(`[SpineManager] Failed to load WASM module for version ${e}:`,t),null}finally{this.loadingBackends_.delete(e)}})();return this.loadingBackends_.set(e,i),i}}function lu(e,t){let n=0,s=0,i=0;do{const o=e[t+i++];if(n|=(127&o)<<s,s+=7,!(128&o))break}while(s<35);return{value:n,bytesRead:i}}async function cu(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const uu=Et({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),hu={r:.2,g:.4,b:1,a:.7},du={r:.2,g:1,b:.2,a:.7},fu={r:.2,g:1,b:1,a:.7},pu={r:1,g:1,b:.2,a:.5},mu={r:1,g:.2,b:.2,a:.8},gu={r:1,g:.2,b:.2,a:1},yu=1.5,_u=16;function xu(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function wu(e){switch(e){case Pt.Static:return hu;case Pt.Kinematic:return fu;default:return du}}function bu(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)Bo.line(l[e],l[(e+1)%4],o,yu)}function vu(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),h=l(-n,-s),d=l(n,-s);Bo.line(c,h,o,yu),Bo.line(u,d,o,yu);for(let e=0;e<_u;e++){const t=e/_u*Math.PI,i=(e+1)/_u*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));Bo.line(r,a,o,yu)}for(let e=0;e<_u;e++){const t=Math.PI+e/_u*Math.PI,i=Math.PI+(e+1)/_u*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));Bo.line(r,a,o,yu)}}function Su(e,t,n,s){const i=e+.5*n,o=t+.5*s;Bo.line({x:e,y:t},{x:i,y:o},mu,yu);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),h=o-6*(l*Math.sin(a)+c*Math.cos(a)),d=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));Bo.line({x:i,y:o},{x:u,y:h},mu,yu),Bo.line({x:i,y:o},{x:d,y:f},mu,yu)}function Mu(e,t,n){const s=e.getResource(uu);if(!s||!s.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([et]);for(const n of t){const t=e.world.get(n,et);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([pt,Ge]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,pt);if(!n.enabled)continue;const o=e.world.get(t,Ge),a=o.worldPosition.x,l=o.worldPosition.y,c=xu(o.worldRotation);if(s.showColliders){if(e.world.has(t,mt)){const s=e.world.get(t,mt),o=s.isSensor?pu:wu(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);bu(a+r*h-u*d,l+r*d+u*h,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,gt)){const s=e.world.get(t,gt),o=s.isSensor?pu:wu(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c),f=a+r*h-u*d,p=l+r*d+u*h;Bo.circleOutline({x:f,y:p},s.radius*i,o,yu,32)}if(e.world.has(t,yt)){const s=e.world.get(t,yt),o=s.isSensor?pu:wu(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);vu(a+r*h-u*d,l+r*d+u*h,s.radius*i,s.halfHeight*i,c,o)}if(e.world.has(t,_t)){const s=e.world.get(t,_t),o=s.isSensor?pu:wu(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=a+(s.point1.x*i*r-s.point1.y*i*u),d=l+(s.point1.x*i*u+s.point1.y*i*r),f=a+(s.point2.x*i*r-s.point2.y*i*u),p=l+(s.point2.x*i*u+s.point2.y*i*r);Bo.line({x:h,y:d},{x:f,y:p},o,yu)}if(e.world.has(t,xt)){const s=e.world.get(t,xt),o=s.isSensor?pu:wu(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=s.vertices;for(let e=0;e<h.length;e++){const t=h[e],n=h[(e+1)%h.length],s=a+(t.x*i*r-t.y*i*u),c=l+(t.x*i*u+t.y*i*r),d=a+(n.x*i*r-n.y*i*u),f=l+(n.x*i*u+n.y*i*r);Bo.line({x:s,y:c},{x:d,y:f},o,yu)}}if(e.world.has(t,wt)){const s=e.world.get(t,wt),o=wu(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=s.points,d=s.isLoop?h.length:h.length-1;for(let e=0;e<d;e++){const t=h[e],n=h[(e+1)%h.length],s=a+(t.x*i*r-t.y*i*u),c=l+(t.x*i*u+t.y*i*r),d=a+(n.x*i*r-n.y*i*u),f=l+(n.x*i*u+n.y*i*r);Bo.line({x:s,y:c},{x:d,y:f},o,yu)}}}if(s.showVelocity&&r&&n.bodyType===Pt.Dynamic){const e=r.getLinearVelocity(t);Su(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)Bo.circle({x:e.contactX,y:e.contactY},3,gu,!0,32)}}const Cu=Et({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Pu=Et(null,"PhysicsAPI");function Tu(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}class Eu{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/30,subStepCount:t.subStepCount??4,contactHertz:t.contactHertz??30,contactDampingRatio:t.contactDampingRatio??10,contactSpeed:t.contactSpeed??3,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(Cu,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Set,s=new Set,i=new Map;let o=-1;const r=cu(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount,this.config_.contactHertz,this.config_.contactDampingRatio,this.config_.contactSpeed);const a=function(e){const t=e.world.getEntitiesWithComponents([et]);for(const n of t){const t=e.world.get(n,et);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),l=1/a,c=e.world;c.onDespawn(e=>{n.has(e)&&(r._physics_destroyJoint(e),n.delete(e)),t.has(e)&&(r._physics_destroyBody(e),t.delete(e),i.delete(e),s.delete(e))}),e.addSystemToSchedule(bn.PostUpdate,Mn([At(Ft)],u=>{if(ii()&&!ai())return;const h=c.getEntitiesWithComponents([pt,Ge]),d=new Set;for(const n of h)if(d.add(n),t.has(n)){if(c.isChangedSince(n,pt,o)){const e=c.get(n,pt),t=i.get(n);!t||t.bodyType===e.bodyType&&t.gravityScale===e.gravityScale&&t.linearDamping===e.linearDamping&&t.angularDamping===e.angularDamping&&t.fixedRotation===e.fixedRotation&&t.bullet===e.bullet||(r._physics_updateBodyProperties(n,e.bodyType,e.gravityScale,e.linearDamping,e.angularDamping,e.fixedRotation?1:0,e.bullet?1:0),t.bodyType=e.bodyType,t.gravityScale=e.gravityScale,t.linearDamping=e.linearDamping,t.angularDamping=e.angularDamping,t.fixedRotation=e.fixedRotation,t.bullet=e.bullet)}const e=i.get(n);if(e&&e.bodyType===Pt.Kinematic){const e=c.get(n,Ge),t=Tu(e.worldRotation);r._physics_setBodyTransform(n,e.worldPosition.x*l,e.worldPosition.y*l,t)}}else{const o=c.get(n,pt);if(!o.enabled)continue;const a=c.get(n,Ge),u=c.has(n,nt),h=u?a.worldPosition.x:a.position.x,d=u?a.worldPosition.y:a.position.y,f=Tu(u?a.worldRotation:a.rotation);r._physics_createBody(n,o.bodyType,h*l,d*l,f,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),Ru(e,r,n,this.config_.collisionLayerMasks),t.add(n),c.has(n,nt)&&s.add(n),i.set(n,{bodyType:o.bodyType,gravityScale:o.gravityScale,linearDamping:o.linearDamping,angularDamping:o.angularDamping,fixedRotation:o.fixedRotation,bullet:o.bullet})}o=c.getWorldTick();for(const e of t)d.has(e)||(r._physics_destroyBody(e),t.delete(e),i.delete(e));!function(e,t,n,s,i){const o=e.getEntitiesWithComponents([bt,pt]);for(const r of o){if(s.has(r))continue;if(!n.has(r))continue;const o=e.get(r,bt);if(!o.enabled)continue;const a=o.connectedEntity;n.has(a)&&(t._physics_createRevoluteJoint(a,r,o.anchorA.x*i,o.anchorA.y*i,o.anchorB.x*i,o.anchorB.y*i,o.enableMotor?1:0,o.motorSpeed,o.maxMotorTorque,o.enableLimit?1:0,o.lowerAngle,o.upperAngle,o.collideConnected?1:0),s.add(r))}for(const o of e.getEntitiesWithComponents([vt,pt])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,vt);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createDistanceJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.length*i,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.minLength*i,r.maxLength*i,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([St,pt])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,St);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createPrismaticJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*i,r.upperTranslation*i,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([Mt,pt])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Mt);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWeldJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.linearHertz,r.angularHertz,r.linearDampingRatio,r.angularDampingRatio,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([Ct,pt])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Ct);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWheelJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*i,r.upperTranslation*i,r.enableMotor?1:0,r.maxMotorTorque,r.motorSpeed,r.collideConnected?1:0),s.add(o))}}(c,r,t,n,l),t.size>0&&u.delta>0&&r._physics_step(u.delta),function(e,t,n,s){const i=t._physics_getDynamicBodyCount();if(0===i)return;const o=t._physics_getDynamicBodyTransforms(),r=o>>2,a=t.HEAPU32,l=t.HEAPF32,c=e.world.getCppRegistry();if(!c)return;const u=e.world.getWasmModule(),h=s.size>0;if(!h&&u?.registry_batchSyncPhysicsTransforms){const e=i*Bu,s=u._malloc(e);return u.HEAPU8.set(new Uint8Array(t.HEAPU8.buffer,o,e),s),u.registry_batchSyncPhysicsTransforms(c,s,i,n),void u._free(s)}const d=u?.getTransformPtr?e=>u.getTransformPtr(c,e):null,f=u?.HEAPF32,p=d&&f?null:c.addTransform.bind(c),m=Iu;for(let t=0;t<i;t++){const i=r+t*Fu,o=a[i];let c=l[i+1]*n,u=l[i+2]*n,g=l[i+3];if(h&&s.has(o)){const t=e.world.get(o,nt);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Ge)){const n=e.world.get(t.entity,Ge),s=Tu(n.worldRotation),i=u,o=c-n.worldPosition.x,r=i-n.worldPosition.y,a=Math.cos(-s),l=Math.sin(-s);c=(o*a-r*l)/(0!==n.worldScale.x?n.worldScale.x:1),u=(o*l+r*a)/(0!==n.worldScale.y?n.worldScale.y:1),g-=s}}const y=.5*g,_=Math.cos(y),x=Math.sin(y);if(d&&f){const e=d(o);if(e){const t=e>>2;f[t]=c,f[t+1]=u,f[t+2]=0,f[t+3]=0,f[t+4]=0,f[t+5]=x,f[t+6]=_,f[t+7]=1,f[t+8]=1,f[t+9]=1,f[t+10]=c,f[t+11]=u,f[t+12]=0,f[t+13]=0,f[t+14]=0,f[t+15]=x,f[t+16]=_,f[t+17]=1,f[t+18]=1,f[t+19]=1;continue}}m.position.x=c,m.position.y=u,m.rotation.w=_,m.rotation.x=0,m.rotation.y=0,m.rotation.z=x,m.worldPosition.x=c,m.worldPosition.y=u,m.worldRotation.w=_,m.worldRotation.x=0,m.worldRotation.y=0,m.worldRotation.z=x,p(o,m)}}(e,r,a,s),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Cu,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,r,a)},{name:"PhysicsSystem"})),e.physicsModule=r,e.insertResource(Pu,Uu._fromModule(r)),function(e,t,n){e.insertResource(uu,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Ho("physics-debug-draw",()=>{Mu(e,t,n)})}(e,Pu,Cu),e.setFixedTimestep(this.config_.fixedTimestep)});r.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=r}}const Au=16;function ku(e,t,n){if(!n)return t;for(let t=0;t<Au;t++)if(e===1<<t)return n[t];return t}function Ru(e,t,n,s){const i=e.world;if(i.has(n,mt)){const e=i.get(n,mt),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s);t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.radius??.05,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,gt)){const e=i.get(n,gt),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s);t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,yt)){const e=i.get(n,yt),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,_t)){const e=i.get(n,_t),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s);t._physics_addSegmentShape(n,e.point1.x,e.point1.y,e.point2.x,e.point2.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,xt)){const e=i.get(n,xt),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s),a=e.vertices,l=Math.min(a.length,8),c=2*l*4,u=t._malloc(c),h=u>>2;for(let e=0;e<l;e++)t.HEAPF32[h+2*e]=a[e].x,t.HEAPF32[h+2*e+1]=a[e].y;t._physics_addPolygonShape(n,u,l,e.radius??0,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r),t._free(u)}if(i.has(n,wt)){const e=i.get(n,wt),s=e.points;if(s.length<4)return;const o=2*s.length*4,r=t._malloc(o),a=r>>2;for(let e=0;e<s.length;e++)t.HEAPF32[a+2*e]=s[e].x,t.HEAPF32[a+2*e+1]=s[e].y;t._physics_addChainShape(n,r,s.length,e.isLoop?1:0,e.friction,e.restitution,e.categoryBits??1,e.maskBits??65535),t._free(r)}}const Iu={position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}},Fu=4,Bu=4*Fu;class Uu{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(Uu.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)}createRevoluteJoint(e,t,n,s,i){const o=i??{};return 0!==this.module_._physics_createRevoluteJoint(e,t,n.x,n.y,s.x,s.y,o.enableMotor?1:0,o.motorSpeed??0,o.maxMotorTorque??0,o.enableLimit?1:0,o.lowerAngle??0,o.upperAngle??0,o.collideConnected?1:0)}destroyJoint(e){this.module_._physics_destroyJoint(e)}setRevoluteMotorSpeed(e,t){this.module_._physics_setRevoluteMotorSpeed(e,t)}setRevoluteMaxMotorTorque(e,t){this.module_._physics_setRevoluteMaxMotorTorque(e,t)}enableRevoluteMotor(e,t){this.module_._physics_enableRevoluteMotor(e,t?1:0)}enableRevoluteLimit(e,t){this.module_._physics_enableRevoluteLimit(e,t?1:0)}setRevoluteLimits(e,t,n){this.module_._physics_setRevoluteLimits(e,t,n)}getRevoluteAngle(e){return this.module_._physics_getRevoluteAngle(e)}getRevoluteMotorTorque(e){return this.module_._physics_getRevoluteMotorTorque(e)}raycast(e,t,n,s=65535,i=100){const o=1/i,r=this.module_._physics_raycast(e.x*o,e.y*o,t.x,t.y,n*o,s);if(0===r)return[];const a=this.module_._physics_getRaycastBuffer()>>2,l=[];for(let e=0;e<r;e++){const t=a+6*e;l.push({entity:this.module_.HEAPU32[t],point:{x:this.module_.HEAPF32[t+1]*i,y:this.module_.HEAPF32[t+2]*i},normal:{x:this.module_.HEAPF32[t+3],y:this.module_.HEAPF32[t+4]},fraction:this.module_.HEAPF32[t+5]})}return l.sort((e,t)=>e.fraction-t.fraction),l}overlapCircle(e,t,n=65535,s=100){const i=1/s,o=this.module_._physics_overlapCircle(e.x*i,e.y*i,t*i,n);if(0===o)return[];const r=this.module_._physics_getOverlapBuffer()>>2,a=[],l=new Set;for(let e=0;e<o;e++){const t=this.module_.HEAPU32[r+e];l.has(t)||(l.add(t),a.push(t))}return a}setAwake(e,t){this.module_._physics_setAwake(e,t?1:0)}isAwake(e){return 0!==this.module_._physics_isAwake(e)}static setDebugDraw(e,t){const n=e.getResource(uu);n&&(n.enabled=t,e.insertResource(uu,n))}static setDebugDrawConfig(e,t){const n=e.getResource(uu);n&&e.insertResource(uu,{...n,...t})}}const zu={nearest:0,linear:1},Wu={repeat:0,clamp:1,mirror:2};function Du(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=zu[s.filterMode??"linear"]??1,a=Wu[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function Hu(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 $u(e,t,n){const s=e.FS;if(!s)return!1;try{return function(e,t){const n=e.FS;if(!n)return;const s=t.substring(0,t.lastIndexOf("/"));if(!s)return;const i=s.split("/").filter(e=>e);let o="";for(const e of i){o+="/"+e;try{n.mkdir(o)}catch{}}}(e,t),s.writeFile(t,n),!0}catch(e){return console.warn(`[Runtime] Failed to write virtual FS: ${t}`,e),!1}}async function Lu(e){const{app:t,module:n,sceneData:s,provider:i,spineManager:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=qi(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=Du(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);const h=await async function(e,t,n,s){const i=new Set,o=new Map;for(const r of t.entities)for(const t of r.components){const r=Ki(t.type);if(!r||!t.data)continue;const a=t.data[r.skeletonField],l=t.data[r.atlasField];if(!a||!l)continue;const c=`${a}:${l}`;if(i.has(c))continue;i.add(c);const u=n.resolvePath(l);try{const t=await n.readText(l),i=n.resolvePath(a),r="binary"===P(i)?.contentType?await n.readBinary(a):await n.readText(a),h=s?"string"==typeof r?au.detectVersionJson(r):au.detectVersion(r):null,d=Hu(t),f=u.substring(0,u.lastIndexOf("/")),p=e.getResourceManager(),m=new Map;for(const t of d){const s=f+"/"+t;try{const i=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),o=Du(e,i,!1);p.registerTextureWithPath(o,s),m.set(t,{glId:p.getTextureGLId(o),w:i.width,h:i.height})}catch(e){console.warn(`[Spine] Failed to load texture: ${s}`,e)}}(!h||"4.2"===h)&&($u(e,u,t),$u(e,i,r)),o.set(c,{version:h,skelData:r,atlasText:t,textures:m})}catch(e){console.warn(`[Runtime] Failed to load spine asset: skel=${a} atlas=${l}`,e)}}return o}(n,s,i,o);if(r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??ue,subStepCount:a?.subStepCount??4,contactHertz:a?.contactHertz??120,contactDampingRatio:a?.contactDampingRatio??10,contactSpeed:a?.contactSpeed??10};new Eu("",e,()=>Promise.resolve(r)).build(t)}const d=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=qi(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=P(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Du(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch(e){console.warn(`[Runtime] Failed to load bitmap font: ${o}`,e),s[o]=0}}return s}(n,s,i),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=qi(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=Nn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Nn.createFromAsset(e,r)}catch(e){console.warn(`[Runtime] Failed to load material: ${o}`,e),n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=qi(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=ts(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,Du(e,s))}catch(e){console.warn(`[Runtime] Failed to load anim texture: ${t}`,e),r.set(t,0)}is(ns(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=qi(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=Es(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=As(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=Du(e,t),fs(r,t.width,t.height)}catch(e){console.warn(`[Runtime] Failed to load tileset texture: ${s}`,e)}o.push({textureHandle:r,columns:t.columns})}gs(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=qi(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await us.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await us.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=qi(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,d,f);const p=eo(t.world,s),m=t.world.getCppRegistry();if(m&&n.transform_update(m),o&&m&&h.size>0)for(const e of s.entities)for(const t of e.components){const n=Ki(t.type);if(!n||!t.data)continue;const s=t.data[n.skeletonField],i=t.data[n.atlasField];if(!s||!i)continue;const r=`${s}:${i}`,a=h.get(r);if(!a||!a.version||"4.2"===a.version)continue;const l=p.get(e.id);if(void 0===l)continue;await o.loadEntity(l,a.skelData,a.atlasText,a.textures,m),o.setEntityProps(l,{skeletonScale:t.data.skeletonScale??1,flipX:t.data.flipX??!1,flipY:t.data.flipY??!1,layer:t.data.layer??0});const c=t.data.skin;c&&o.setSkin(l,c);const u=t.data.animation;u&&o.setAnimation(l,u,!1!==t.data.loop)}if(c&&t.hasResource(Yr))for(const e of p.values())t.world.insert(e,ht,{scene:c,persistent:!1});if(l){const e=t.getResource(ao);e&&e.setAddressableManifest(l)}}function Ou(e,t,n){return{name:e,async setup(){await Lu({...n,sceneData:t,sceneName:e})}}}async function Vu(e){const{app:t,firstScene:n,aspectRatio:s}=e;Zr(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,spineManager:e.spineManager,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(Yr);for(const t of e.scenes)o.register(Ou(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&io(t.world,s)}class Nu{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Ki(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===P(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=qi(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=P(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}let ju=null;const Xu={update(e,t){ju?.spine_update?.(e._cpp,t)},play:(e,t,n=!0,s=0)=>ju?.spine_play?.(e,t,n,s)??!1,addAnimation:(e,t,n=!0,s=0,i=0)=>ju?.spine_addAnimation?.(e,t,n,s,i)??!1,setSkin:(e,t)=>ju?.spine_setSkin?.(e,t)??!1,getBonePosition:(e,t)=>ju?.spine_getBonePosition?.(e,t)??null,hasInstance:e=>ju?.spine_hasInstance?.(e)??!1,reloadAssets(e){ju?.spine_reloadAssets?.(e._cpp)},getAnimations:e=>ju?.spine_getAnimations?.(e)??[],getSkins:e=>ju?.spine_getSkins?.(e)??[]};class Yu{constructor(e){this.app_=null,e instanceof au?(this.spineManager_=e,this.provider_=null):(this.spineManager_=null,this.provider_=e??null)}get spineManager(){return this.spineManager_}setSpineManager(e){if(this.spineManager_=e,this.app_){const t=this.app_,n=t.pipeline;n?.addPreFlushCallback(n=>{const s=t.getResource(Ft).frameCount;e.submitMeshes(n._cpp,s)})}}build(e){this.app_=e;const t=e.wasmModule;if(ju=t,!this.spineManager_&&this.provider_){const e=function(e){const t=["3.8","4.1","4.2"],n=new Map;for(const s of t)n.set(s,async()=>{const[t,n]=await Promise.all([e.loadJs(s),e.loadWasm(s)]),i=new Blob([`${t};\nself.__ESSpineModule__ = ESSpineModule;`],{type:"application/javascript"}),o=URL.createObjectURL(i);await import(/* @vite-ignore */o),URL.revokeObjectURL(o);const r=globalThis.__ESSpineModule__;return delete globalThis.__ESSpineModule__,r({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Spine] WASM instantiation failed:",e)}),{})})});return n}(this.provider_);this.spineManager_=new au(t,e)}const n=this,s={_id:Symbol("SpineUpdateSystem"),_name:"SpineUpdateSystem",_params:[],_fn:()=>{const t=e.world.getCppRegistry();if(!t)return;const s=e.getResource(Ft);Xu.update({_cpp:t},s.delta),n.spineManager_?.updateAnimations(s.delta)}};if(e.addSystemToSchedule(bn.PreUpdate,s),this.spineManager_){const t=this.spineManager_,n=e.pipeline;n?.addPreFlushCallback(n=>{const s=e.getResource(Ft).frameCount;t.submitMeshes(n._cpp,s)})}}}const Gu="__preview__";class qu{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Yr);t.register({name:Gu,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Gu),this.loadPromise_=t.load(Gu).then(()=>{}).catch(e=>{console.error("[Preview] Failed to load preview scene:",e)}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Nu(this.baseUrl_);await n.prefetch(t);const s=this.app_.getPlugin(Yu),i=s?.spineManager??null;await Lu({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineManager:i,sceneName:Gu})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Qe]);for(const s of n){if(e.get(s,Qe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([et]);for(const i of s){const s=e.get(i,et);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(Yr).getScene(Gu),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,Ge,r);const a={isActive:!0,projectionType:Ne.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:je.ColorAndDepth};e.insert(o,Qe,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Yr);await e.switchTo(Gu),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Ku={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=Ur.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:Ur.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){Ur.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Ur.releaseRenderTarget(e._handle),Ku.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){Ur.begin(t,e._handle)},end(){Ur.end()},getDepthTexture:e=>Ur.getTargetDepthTexture(e._handle)};var Ju;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Ju||(Ju={}));class Zu{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Ju[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Ju.Debug:console.debug(t,n);break;case Ju.Info:console.log(t,n);break;case Ju.Warn:console.warn(t,n);break;case Ju.Error:console.error(t,n)}}}class Qu{constructor(){this.handlers_=[],this.minLevel_=Ju.Info,this.addHandler(new Zu)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Ju.Debug,e,t,n)}info(e,t,n){this.log(Ju.Info,e,t,n)}warn(e,t,n){this.log(Ju.Warn,e,t,n)}error(e,t,n){this.log(Ju.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const eh=new Qu;function th(){return eh}function nh(e){eh.setMinLevel(e)}function sh(e,t,n){eh.debug(e,t,n)}function ih(e,t,n){eh.info(e,t,n)}function oh(e,t,n){eh.warn(e,t,n)}function rh(e,t,n){eh.error(e,t,n)}const ah={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},lh={Running:0,Paused:1,Completed:2,Cancelled:3},ch={None:0,Restart:1,PingPong:2};const uh=1.70158,hh=2.70158,dh=2.5949095;const fh=2*Math.PI/3,ph=2*Math.PI/4.5;const mh=7.5625,gh=2.75;const yh=1e-6;function _h(e,t,n){switch(e){case ah.Linear:return t;case ah.EaseInQuad:return function(e){return e*e}(t);case ah.EaseOutQuad:return function(e){return e*(2-e)}(t);case ah.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case ah.EaseInCubic:return function(e){return e*e*e}(t);case ah.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case ah.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case ah.EaseInBack:return function(e){return hh*e*e*e-uh*e*e}(t);case ah.EaseOutBack:return function(e){const t=e-1;return 1+hh*t*t*t+uh*t*t}(t);case ah.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-dh)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+dh)+2)/2}(t);case ah.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*fh)}(t);case ah.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*fh)+1}(t);case ah.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*ph)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*ph)/2+1}(t);case ah.EaseOutBounce:return function(e){return e<1/gh?mh*e*e:e<2/gh?mh*(e-=1.5/gh)*e+.75:e<2.5/gh?mh*(e-=2.25/gh)*e+.9375:mh*(e-=2.625/gh)*e+.984375}(t);case ah.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<yh)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<yh)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case ah.Step:return function(e){return e<1?0:1}(t);default:return t}}const xh=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??ah.Linear,bezierPoints:null,state:lh.Running,loop:i?.loop??ch.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===lh.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==lh.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=_h(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==ch.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===ch.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=lh.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===lh.Running&&(t.state=lh.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===lh.Paused&&(t.state=lh.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=lh.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:lh.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class wh{constructor(e){this.id=e}get state(){return xh.getState(this.id)}bezier(e,t,n,s){return xh.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof wh?xh.setSequenceNext(this.id,e.id):xh.setSequenceNextExternal(this.id,e),this}pause(){xh.pause(this.id)}resume(){xh.resume(this.id)}cancel(){xh.cancel(this.id)}}const bh={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class vh{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof wh?(xh.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Sh=null,Mh=null;function Ch(e,t){Sh=e,Mh=t,xh.init(e,t)}function Ph(){xh.shutdown(),Sh=null,Mh=null}function Th(){if(!Sh)throw new Error("Tween API not initialized");return Sh}function Eh(){if(!Mh)throw new Error("Tween API not initialized");return Mh}const Ah={to(e,t,n,s,i,o){const r=Th(),a=Eh(),l=o?.easing??ah.Linear,c=o?.delay??0,u=o?.loop??ch.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new vh(r,a,d)},value(e,t,n,s,i){const o=xh.create(e,t,n,s,i);return new wh(o)},cancel(e){Th()._anim_cancelTween(Eh(),e.entity)},cancelAll(e){Th()._anim_cancelAllTweens(Eh(),e)},update(e){Th()._anim_updateTweens(Eh(),e),xh.update(e)}};class kh{constructor(){this.name="AnimationPlugin"}build(e){Ch(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(bn.Update,Mn([At(Ft)],e=>{ii()&&!ai()||Ah.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(bn.Update,Mn([At(Ft)],e=>{ii()&&!ai()||cs(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Ph()}}const Rh=new kh;let Ih=null,Fh=null;function Bh(e,t){Ih=e,Fh=t}function Uh(){Ih=null,Fh=null}const zh={update(e){Ih&&Fh&&Ih.particle_update?.(Fh,e)},play(e){Ih&&Fh&&Ih.particle_play?.(Fh,e)},stop(e){Ih&&Fh&&Ih.particle_stop?.(Fh,e)},reset(e){Ih&&Fh&&Ih.particle_reset?.(Fh,e)},getAliveCount:e=>Ih?Ih.particle_getAliveCount?.(e)??0:0};class Wh{constructor(){this.name="ParticlePlugin"}build(e){Bh(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(bn.Update,Mn([At(Ft)],e=>{zh.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Uh()}}const Dh=new Wh,Hh=1073741824,$h={orthogonal:0,isometric:1,staggered:2};class Lh{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.animatedLayers_=new Set,this.sourceEntityKeys_=new Map,this.layerState_=new Map}build(e){ws(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.animatedLayers_,i=this.sourceEntityKeys_,o=this.layerState_,r={_id:Symbol("TilemapSyncSystem"),_name:"TilemapSyncSystem",_params:[],_fn:()=>{const r=t.getEntitiesWithComponents([Ms,Ge]),a=new Set(r);for(const e of n)e>=Hh||a.has(e)||(vs.destroyLayer(e),n.delete(e),o.delete(e));for(const e of r){const s=t.tryGet(e,Ms);if(!s)continue;const i=s.texture;if(!i)continue;const r=ps(i);if(!r)continue;if(!n.has(e)){if(vs.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),vs.setOriginEntity(e,e),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];vs.setTiles(e,t)}n.add(e)}const a=s.tileWidth/r.width,l=s.tileHeight/r.height,c=s.tint,u=s.parallaxFactor,h=o.get(e);(!h||h.texture!==i||h.tilesetColumns!==s.tilesetColumns||h.layer!==s.layer||h.parallaxX!==u.x||h.parallaxY!==u.y||h.tintR!==c.r||h.tintG!==c.g||h.tintB!==c.b||h.tintA!==c.a||h.opacity!==s.opacity||h.visible!==s.visible)&&(vs.setRenderProps(e,i,s.tilesetColumns,a,l,s.layer,0,u.x,u.y),vs.setTint(e,c.r,c.g,c.b,c.a,s.opacity),vs.setVisible(e,s.visible),o.set(e,{texture:i,tilesetColumns:s.tilesetColumns,layer:s.layer,tintR:c.r,tintG:c.g,tintB:c.b,tintA:c.a,opacity:s.opacity,parallaxX:u.x,parallaxY:u.y,visible:s.visible}))}const l=t.getEntitiesWithComponents([Ss,Ge]);for(const e of l){if(t.tryGet(e,Ms))continue;const o=t.tryGet(e,Ss);if(!o?.source)continue;const r=ys(o.source);if(r&&!i.has(e)){const t=[],o=$h[r.orientation??"orthogonal"]??0;for(let i=0;i<r.layers.length;i++){const a=Hh+256*e+i,l=r.layers[i];if(vs.initLayer(a,l.width,l.height,r.tileWidth,r.tileHeight),vs.setOriginEntity(a,e),l.tiles.length>0&&vs.setTiles(a,l.tiles),0!==o&&vs.setGridType(a,o),r.tileAnimations){for(const[e,t]of r.tileAnimations)vs.setTileAnimation(a,e,t);r.tileAnimations.size>0&&s.add(a)}if(r.tileProperties)for(const[e,t]of r.tileProperties)for(const[n,s]of t)vs.setTileProperty(a,e,n,s);const c=r.tilesets[0];if(c){const e=ps(c.textureHandle);e&&(vs.setRenderProps(a,c.textureHandle,c.columns,r.tileWidth/e.width,r.tileHeight/e.height,i,0,1,1),vs.setTint(a,1,1,1,1,1),vs.setVisible(a,!0))}t.push(a),n.add(a)}i.set(e,t)}}const c=new Set(l);for(const[e,t]of i)if(!c.has(e)){for(const e of t)vs.destroyLayer(e),n.delete(e),s.delete(e),o.delete(e);i.delete(e)}if(s.size>0){const t=1e3*e.getResource(Ft).delta;for(const e of s)vs.advanceAnimations(e,t)}}};e.addSystemToSchedule(bn.PreUpdate,r)}cleanup(){for(const e of this.initializedLayers_)vs.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),this.layerState_.clear(),ms(),bs()}}const Oh=new Lh;function Vh(e,t){return e.toFixed(t)}function Nh(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class jh{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.lastUpdateTime_=0,this.lastStats_=null,this.accumulatedTimings_=new Map,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 220px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;this.lastStats_=e,this.accumulateTimings_(e.systemTimings);const t=performance.now();this.lastUpdateTime_>0&&t-this.lastUpdateTime_<500||(this.lastUpdateTime_=t,this.render_())}show(){this.visible_=!0,this.lastUpdateTime_=0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}accumulateTimings_(e){for(const[t,n]of e){const e=this.accumulatedTimings_.get(t);e?(e.sum+=n,e.count++,n>e.max&&(e.max=n)):this.accumulatedTimings_.set(t,{sum:n,max:n,count:1})}}render_(){const e=this.lastStats_;if(!e)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Vh(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Vh(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),this.accumulatedTimings_.size>0){const e=[];for(const[t,n]of this.accumulatedTimings_){const s=n.sum/n.count;e.push([t,s,n.max])}e.sort((e,t)=>t[2]-e[2]);const n=e.slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t,i]of n){s+=`<div>${Nh(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Vh(t,1)} / ${Vh(i,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join(""),this.accumulatedTimings_.clear()}}function Xh(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Yh=Et(Xh(),"Stats");class Gh{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const qh="StatsCollect";class Kh{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Jh{constructor(e){this.name="Stats",this.collector_=new Kh,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Yh,Xh());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new jh(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=Mn([At(Ft),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Yh);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(qh),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Ur.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:qh});e.addSystemToSchedule(bn.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Zh=new Jh;class Qh{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return ed(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}function ed(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}function td(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function nd(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await async function(e,t){try{const n=td(t),s={instantiateWasm(e,t){const s=new Response(n.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,e).then(e=>t(e.instance,e.module),()=>{WebAssembly.instantiate(n.buffer,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Playable] WASM instantiation fallback failed:",e)})}),{}}};return await e(s)}catch(e){return console.error("[Playable] WASM module init failed:",e),null}}(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}async function sd(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(ao);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));let a=null;if(e.spineModules&&Object.keys(e.spineModules).length>0){a=function(e,t){const n=new Map;for(const[e,s]of Object.entries(t)){const t=e;n.set(t,async()=>{const e=td(s.wasmBase64);return s.factory({instantiateWasm(t,n){const s=new Response(e.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,t).then(e=>n(e.instance,e.module),()=>{WebAssembly.instantiate(e.buffer,t).then(e=>n(e.instance,e.module)).catch(e=>{console.error("[Playable] Spine WASM instantiation fallback failed:",e)})}),{}}})})}return new au(e,n)}(n,e.spineModules);const s=t.getPlugin(Yu);s&&s.setSpineManager(a)}const l=e.physicsWasmBase64?await nd(e.physicsWasmBase64):null,c=new Qh(s);us.setAssetResolver(e=>{const t=s[e];return t?ed(t).buffer:null}),await Vu({app:t,module:n,provider:c,scenes:i,firstScene:o,spineManager:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const id=[rl,ul,Ml,Dl,Gl,El,Ql,ic,uc,Nl,Bl,dc,gc,bc,Mc,Tc,Dc],od=[Rh,Ui,Dh,Oh,Pr,ji];function rd(e,t){const n=new Yu(t?.spineProvider),s=[...id,...od,n,...t?.plugins??[]];return function(e,t){const n=Jr.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ko(e),Ln(e),Yo(e),or(e),Fr(e),Wr(e);const i=new $r;n.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=sa(e,s,t,i));const r=n.getResource(Bn);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(Bn,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Ur.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(Ur.resize(t,l),n.hasResource(Yr)){const e=n.getResource(Yr).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=sa(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Qr,width:t,height:l,elapsed:u});else{i.beginFrame(),i.beginScreenCapture();for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),Ur.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(bn.First,l),n.addSystemToSchedule(bn.Last,c),n.addPlugin(co),n.addPlugin(Mo),n.addPlugin(Fn),n.addPlugin(Kr),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{...t,plugins:s})}class ad{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function ld(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}).catch(e=>{console.error("[WeChat] WASM instantiation failed:",e)}),{})}async function cd(e,t){try{return await e({instantiateWasm:ld(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function ud(e){const t=await l("asset-manifest.json"),n=JSON.parse(t),s=function(e){const t={},n={};for(const s in e.groups){const i=e.groups[s];for(const e in i.assets){const s=i.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n),i=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=W(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:ld("esengine.wasm")}),c=o.getContext("webgl2")||o.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const u=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),h=rd(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(h,e.runtimeConfig);let d=null;if(e.spineFactories&&Object.keys(e.spineFactories).length>0){const t=new Map;for(const[n,s]of Object.entries(e.spineFactories)){const e=n,i=`spine_${n.replace(".","")}.wasm`;t.set(e,()=>cd(s,i))}d=new au(a,t)}let f=null;e.physicsFactory&&(f=await cd(e.physicsFactory,"physics.wasm"));const p=new ad(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await Vu({app:h,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineManager:d,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),h.run()}J||(J=!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},i=await x(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.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 w(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 i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}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 i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Z;export{en as Added,kh as AnimationPlugin,Jr as App,lo as AssetPlugin,uo as AssetRefCounter,ro as AssetServer,ao as Assets,Qn as AsyncCache,Ei as AttenuationModel,us as Audio,p as AudioBus,Fi as AudioListener,m as AudioMixer,Bi as AudioPlugin,g as AudioPool,Ii as AudioSource,it as BitmapText,Un as BlendMode,Pt as BodyType,mt as BoxCollider,xl as Button,_l as ButtonState,Qe as Camera,et as Canvas,yt as CapsuleCollider,wt as ChainCollider,tn as Changed,st as Children,gt as CircleCollider,je as ClearFlags,hn as Commands,fn as CommandsInstance,Hc as DARK_THEME,ee as DEFAULT_DESIGN_HEIGHT,Q as DEFAULT_DESIGN_WIDTH,le as DEFAULT_FALLBACK_DT,ue as DEFAULT_FIXED_TIMESTEP,ie as DEFAULT_FONT_FAMILY,oe as DEFAULT_FONT_SIZE,ce as DEFAULT_GRAVITY,re as DEFAULT_LINE_HEIGHT,ae as DEFAULT_MAX_DELTA_TIME,te as DEFAULT_PIXELS_PER_UNIT,he as DEFAULT_SPINE_SKIN,se as DEFAULT_SPRITE_SIZE,ne as DEFAULT_TEXT_CANVAS_SIZE,Oo as DataType,Zl as DragPlugin,Kl as DragState,ql as Draggable,Bo as Draw,vc as Dropdown,Sc as DropdownPlugin,ah as EasingType,rt as EmitterShape,dn as EntityCommands,Xa as EntityStateMap,_n as EventReader,wn as EventReaderInstance,gn as EventRegistry,yn as EventWriter,xn as EventWriterInstance,da as FillDirection,pa as FillMethod,ma as FillOrigin,Tr as FlushReason,Il as FocusManager,Rl as FocusManagerState,hc as FocusPlugin,kl as Focusable,Gh as FrameHistory,Hr as GLDebug,Ko as Geometry,vn as GetWorld,ge as INVALID_ENTITY,_e as INVALID_FONT,xe as INVALID_MATERIAL,ye as INVALID_TEXTURE,ga as Image,Wl as ImagePlugin,fa as ImageType,Rn as Input,In as InputPlugin,kn as InputState,_a as Interactable,Pc as LayoutGroupPlugin,yc as ListView,wc as ListViewPlugin,qe as LocalTransform,Ju as LogLevel,Qu as Logger,ch as LoopMode,Nn as Material,es as MaterialLoader,Zt as Mut,ut as Name,nt as Parent,zh as Particle,lt as ParticleEasing,ct as ParticleEmitter,Wh as ParticlePlugin,Uu as Physics,Cu as PhysicsEvents,Eu as PhysicsPlugin,xt as PolygonCollider,lr as PostProcess,Cr as PostProcessPlugin,nr as PostProcessStack,dt as PostProcessVolume,bo as PrefabServer,vo as Prefabs,So as PrefabsPlugin,qu as PreviewPlugin,Xl as ProgressBar,jl as ProgressBarDirection,Yl as ProgressBarPlugin,Ne as ProjectionType,an as Query,ln as QueryInstance,cn as Removed,un as RemovedQueryInstance,$r as RenderPipeline,Ar as RenderStage,Ku as RenderTexture,Er as RenderType,Ur as Renderer,At as Res,kt as ResMut,bt as RevoluteJoint,pt as RigidBody,de as RuntimeConfig,fc as SafeArea,mc as SafeAreaPlugin,Xe as ScaleMode,Yr as SceneManager,Xr as SceneManagerState,ht as SceneOwner,bn as Schedule,ec as ScrollView,sc as ScrollViewPlugin,_t as SegmentCollider,Zn as ShaderSources,Ze as ShapeRenderer,Ye as ShapeType,at as SimulationSpace,rc as Slider,oc as SliderDirection,cc as SliderPlugin,ot as SpineAnimation,Je as Sprite,ls as SpriteAnimator,Yh as Stats,Kh as StatsCollector,jh as StatsOverlay,Jh as StatsPlugin,Ut as Storage,kr as SubmitSkipFlags,An as SystemRunner,tl as Text,Za as TextAlign,Al as TextInput,Fl as TextInputPlugin,el as TextOverflow,ol as TextPlugin,nl as TextRenderer,Qa as TextVerticalAlign,Ss as Tilemap,vs as TilemapAPI,Ms as TilemapLayer,Lh as TilemapPlugin,Ft as Time,Ni as TimelinePlugin,Hl as Toggle,Vl as TogglePlugin,Ge as Transform,Ah as Tween,vh as TweenHandle,lh as TweenState,bh as TweenTarget,su as UI,Bn as UICameraInfo,wl as UIEventQueue,bl as UIEvents,yl as UIInteraction,Tl as UIInteractionPlugin,vl as UILayoutGeneration,Sl as UILayoutPlugin,ll as UIMask,cl as UIMaskPlugin,ya as UIRect,Wc as UIRenderOrderPlugin,Or as UIRenderer,$c as UIThemeRes,Lr as UIVisualType,tt as Velocity,ad as WeChatAssetProvider,Nu as WebAssetProvider,Jt as World,Ke as WorldTransform,Tn as addStartupSystem,Pn as addSystem,En as addSystemToSchedule,Rh as animationPlugin,me as applyBuildRuntimeConfig,Ca as applyDirectionalFill,go as applyOverrides,fe as applyRuntimeConfig,co as assetPlugin,Ui as audioPlugin,ki as calculateAttenuation,Ri as calculatePanning,_r as cleanupAllPostProcessVolumes,yr as cleanupPostProcessVolume,as as clearAnimClips,Lo as clearDrawCallbacks,ms as clearTextureDimensionsCache,_s as clearTilemapSourceCache,Ti as clearTimelineHandles,Ue as clearUserComponents,po as cloneComponentData,fo as cloneComponents,_o as collectNestedPrefabPaths,Se as color,Na as colorScale,ja as colorWithAlpha,va as computeFillAnchors,Ma as computeFillSize,Sa as computeHandleAnchors,xa as computeUIRectLayout,Ou as createRuntimeSceneConfig,rd as createWebApp,sh as debug,Xh as defaultFrameStats,Ie as defineComponent,pn as defineEvent,Et as defineResource,Mn as defineSystem,Fe as defineTag,Ql as dragPlugin,Mc as dropdownPlugin,rh as error,ts as extractAnimClipTexturePaths,oo as findEntityByName,yo as flattenPrefab,Zr as flushPendingSystems,dc as focusPlugin,E as getAddressableType,A as getAddressableTypeByEditorType,R as getAllAssetExtensions,fr as getAllEffectDefs,rs as getAnimClip,H as getAssetBuildTransform,U as getAssetMimeType,P as getAssetTypeEntry,Le as getComponent,qi as getComponentAssetFieldDescriptors,Gi as getComponentAssetFields,ft as getComponentDefaults,Te as getComponentEntityFields,Ki as getComponentSpineFieldDescriptor,F as getCustomExtensions,T as getEditorType,hr as getEffectDef,dr as getEffectTypes,th as getLogger,t as getPlatform,s as getPlatformType,ps as getTextureDimensions,ys as getTilemapSource,Pi as getTimelineHandle,Be as getUserComponent,B as getWeChatPackOptions,Dl as imagePlugin,ih as info,ko as initDrawAPI,Wr as initGLDebugAPI,Yo as initGeometryAPI,Ln as initMaterialAPI,Bh as initParticleAPI,sd as initPlayableRuntime,or as initPostProcessAPI,Fr as initRendererAPI,Vu as initRuntime,ws as initTilemapAPI,Ch as initTweenAPI,Oc as initUIBuilder,ud as initWeChatRuntime,Fn as inputPlugin,wo as instantiatePrefab,hl as intersectRects,dl as invertMatrix4,De as isBuiltinComponent,z as isCustomExtension,ii as isEditor,k as isKnownAssetExtension,n as isPlatformInitialized,ai as isPlayMode,oi as isRuntime,zn as isTextureRef,i as isWeChat,o as isWeb,Tc as layoutGroupPlugin,bc as listViewPlugin,so as loadComponent,cu as loadPhysicsModule,Lu as loadRuntimeScene,eo as loadSceneData,to as loadSceneWithAssets,Fs as loadTiledMap,I as looksLikeAssetPath,Ha as makeInteractable,ns as parseAnimClipData,ks as parseTiledMap,ei as parseTimelineAsset,Es as parseTmjJson,Dh as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,gl as pointInOBB,pl as pointInWorldRect,Pr as postProcessPlugin,Mo as prefabsPlugin,xo as preloadNestedPrefabs,Gl as progressBarPlugin,Me as quat,is as registerAnimClip,D as registerAssetBuildTransform,$e as registerComponent,Yi as registerComponentAssetFields,Pe as registerComponentEntityFields,Ho as registerDrawCallback,ho as registerEmbeddedAssets,Jn as registerMaterialCallback,fs as registerTextureDimensions,gs as registerTilemapSource,Di as registerTimelineAsset,mo as remapComponentEntityRefs,Ji as remapEntityFields,As as resolveRelativePath,gc as safeAreaPlugin,Kr as sceneManagerPlugin,fl as screenToWorld,ic as scrollViewPlugin,si as setEditorMode,Oa as setEntityColor,Va as setEntityEnabled,xc as setListViewRenderer,nh as setLogLevel,ri as setPlayMode,$t as setWasmErrorHandler,Ro as shutdownDrawAPI,Dr as shutdownGLDebugAPI,Go as shutdownGeometryAPI,On as shutdownMaterialAPI,Uh as shutdownParticleAPI,rr as shutdownPostProcessAPI,Br as shutdownRendererAPI,bs as shutdownTilemapAPI,Ph as shutdownTweenAPI,uc as sliderPlugin,cs as spriteAnimatorSystemUpdate,Zh as statsPlugin,Wa as syncFillSpriteSize,gr as syncPostProcessVolume,Bl as textInputPlugin,rl as textPlugin,Oh as tilemapPlugin,ji as timelinePlugin,W as toBuildPath,Nl as togglePlugin,iu as transitionTo,El as uiInteractionPlugin,Ml as uiLayoutPlugin,ul as uiMaskPlugin,id as uiPlugins,Dc as uiRenderOrderPlugin,os as unregisterAnimClip,ze as unregisterComponent,$o as unregisterDrawCallback,io as updateCameraAspectRatio,we as vec2,be as vec3,ve as vec4,oh as warn,$a as withChildEntity,Gr as wrapSceneSystem,j as wxFileExists,X as wxFileExistsSync,q as wxGetImagePixels,G as wxLoadImage,K as wxLoadImagePixels,V as wxReadFile,N as wxReadTextFile,Y 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 i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class y{constructor(e,t,n){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class _{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,s);const o=new y(i,s,this.contexts_);return s.onEnded(()=>{o.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(i))}),s.onError(e=>{console.error(`[WeChatAudio] Playback error for "${n}":`,e.errMsg)}),s.src=n,s.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function x(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"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 w(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}`)}}const b=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["estimeline"],contentType:"json",editorType:"timeline",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],v={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",estimeline:"application/json",bmfont:"application/json",fnt:"text/plain"},S=new Map,M=new Set;for(const e of b)for(const t of e.extensions)S.set(t,e),M.add(t);function C(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function P(e){return S.get(C(e))}function T(e){return P(e)?.editorType??"unknown"}function E(e){return P(e)?.addressableType??null}function A(e){for(const t of b)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function k(e){return M.has(e.toLowerCase())}function R(){return M}function I(e){return"string"==typeof e&&(!!e.includes("/")&&k(C(e)))}function F(){const e=[];for(const t of b)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function B(){return F().map(e=>({type:"suffix",value:e}))}function U(e){return v[e.toLowerCase()]}function z(e){const t=P(e);return t?.wechatPackInclude??!1}function W(e){const t=P(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function D(e,t){for(const n of b)n.editorType===e&&(n.buildTransform=t)}function H(e){return P(e)?.buildTransform}let $=null;function L(){return $||($=wx.getFileSystemManager()),$}function O(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(z(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function V(e){return new Promise((t,n)=>{L().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(O(e,t.errMsg)))}})})}function N(e,t="utf-8"){return new Promise((n,s)=>{L().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(O(e,t.errMsg)))}})})}function j(e){return new Promise(t=>{L().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function X(e){const t=L();try{return t.accessSync(e),!0}catch{return!1}}function Y(e,t){return new Promise((n,s)=>{L().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function G(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 q(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const i=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(i.data.buffer)}}async function K(e){return q(await G(e))}let J=!1;const Z=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return x(e,t)}async readFile(e){return function(e){return L().readFileSync(e)}(W(e))}async readTextFile(e){return function(e,t="utf-8"){return L().readFileSync(e,t)}(W(e))}async fileExists(e){return X(W(e))}async loadImagePixels(e){return K(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return w(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(n),wx.onKeyUp(s));const o=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new _}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch(e){console.warn("[WeChat] setStorageSync failed:",e)}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch(e){console.warn("[WeChat] removeStorageSync failed:",e)}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const n of t)n.startsWith(e)&&wx.removeStorageSync(n)}catch(e){console.warn("[WeChat] clearStorage failed:",e)}}},Q=1920,ee=1080,te=100,ne=512,se={x:100,y:100},ie="Arial",oe=24,re=1.2,ae=.5,le=1/60,ce={x:0,y:-9.81},ue=1/60,he="default",de={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};function fe(e){e.Text&&(e.Text._default.fontFamily=de.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=de.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=de.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=de.canvasMatchWidthOrHeight)}const pe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function me(e,t){if(void 0!==t.maxDeltaTime&&(de.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(de.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(de.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(de.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(de.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");de.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(de.canvasScaleMode=pe[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(de.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(de.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(de.assetFailureCooldown=t.assetFailureCooldown)}const ge=0,ye=4294967295,_e=4294967295,xe=0,we=(e=0,t=0)=>({x:e,y:t}),be=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ve=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),Se=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),Me=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s}),Ce=new Map;function Pe(e,t){Ce.set(e,t)}function Te(e){return Ce.get(e)}function Ee(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Ee);const t={};for(const n in e)t[n]=Ee(e[n]);return t}let Ae=0;function ke(e,t){const n=++Ae,s=function(e){const t=[],n=[],s=[];let i=!1;for(const o in e){const r=e[o];null!==r&&"object"==typeof r?(i=!0,Array.isArray(r)?s.push(o):n.push(o)):t.push(o)}return i?{flatKeys:t,objectKeys:n,arrayKeys:s}:null}(t),i=t;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create(e){if(s){const t={...i};for(const e of s.objectKeys)t[e]={...i[e]};for(const e of s.arrayKeys)t[e]=i[e].slice();return e&&Object.assign(t,e),t}return e?{...t,...e}:{...t}}}}function Re(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ie(e,t,n){const s=He.get(e)??Re().get(e);if(s)return s;const i=ke(e,t);return Re().set(e,i),He.set(e,i),We(e,t,!1),n?.entityFields&&Pe(e,n.entityFields),i}function Fe(e){const t=He.get(e)??Re().get(e);if(t)return t;const n=ke(e,{});return Re().set(e,n),He.set(e,n),We(e,{},!0),n}function Be(e){return Re().get(e)}function Ue(){const e=Re();for(const t of e.keys())He.delete(t);e.clear()}function ze(e){Re().delete(e),He.delete(e)}function We(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function De(e){return!0===e._builtin}const He=new Map;function $e(e,t){He.set(e,t)}function Le(e){return He.get(e)??Be(e)}function Oe(e){if(null===e||"object"!=typeof e)return[];const t=[];for(const n of Object.keys(e)){const s=e[n];if(null!==s&&"object"==typeof s&&!Array.isArray(s)){"r"in s&&"g"in s&&"b"in s&&"a"in s&&t.push(n)}}return t}function Ve(e,t,n){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t,_colorKeys:Oe(t)};return He.set(e,s),s}const Ne={Perspective:0,Orthographic:1},je={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Xe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Ye={Circle:0,Capsule:1,RoundedRect:2},Ge=Ve("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),qe=Ge,Ke=Ge,Je=Ve("Sprite",{texture:ye,color:{r:1,g:1,b:1,a:1},size:{x:se.x,y:se.y},pivot:{x:.5,y:.5},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Ze=Ve("ShapeRenderer",{shapeType:Ye.Circle,color:{r:1,g:1,b:1,a:1},size:{x:100,y:100},cornerRadius:0,layer:0,enabled:!0}),Qe=Ve("Camera",{projectionType:Ne.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:je.ColorAndDepth}),et=Ve("Canvas",{designResolution:{x:Q,y:ee},pixelsPerUnit:100,scaleMode:Xe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),tt=Ve("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),nt=Ve("Parent",{entity:0}),st=Ve("Children",{entities:[]}),it=Ve("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_e,enabled:!0}),ot=Ve("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,enabled:!0}),rt={Point:0,Circle:1,Rectangle:2,Cone:3},at={World:0,Local:1},lt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},ct=Ve("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:rt.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:lt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:lt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:ye,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:at.World,enabled:!0}),ut=Ie("Name",{value:""}),ht=Ie("SceneOwner",{scene:"",persistent:!1}),dt=Ie("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function ft(e){const t=Le(e);return t?Ee(t._default):null}const pt=Ve("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),mt=Ve("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},radius:.05,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),gt=Ve("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),yt=Ve("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),_t=Ve("SegmentCollider",{point1:{x:-.5,y:0},point2:{x:.5,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),xt=Ie("PolygonCollider",{vertices:[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}],radius:0,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),wt=Ie("ChainCollider",{points:[{x:-1,y:0},{x:0,y:.5},{x:1,y:0},{x:0,y:-.5}],isLoop:!0,friction:.6,restitution:0,categoryBits:1,maskBits:65535,enabled:!0}),bt=Ie("RevoluteJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},enableMotor:!1,motorSpeed:0,maxMotorTorque:0,enableLimit:!1,lowerAngle:0,upperAngle:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),vt=Ie("DistanceJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},length:1,enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,minLength:.5,maxLength:2,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),St=Ie("PrismaticJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:1,y:0},enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Mt=Ie("WeldJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},linearHertz:0,angularHertz:0,linearDampingRatio:1,angularDampingRatio:1,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Ct=Ie("WheelJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:0,y:1},enableSpring:!0,hertz:5,dampingRatio:.7,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorTorque:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Pt={Static:0,Kinematic:1,Dynamic:2};let Tt=0;function Et(e,t){const n=++Tt;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function At(e){return{_type:"res",_resource:e}}function kt(e){return{_type:"res_mut",_resource:e}}class Rt{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_)}updateValue(e){this.value_=e}}class It{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Rt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ft=Et({delta:0,elapsed:0,frameCount:0},"Time"),Bt="esengine:",Ut={getString(e,n){const s=t().getStorageItem(Bt+e);return null!==s?s:n},setString(e,n){t().setStorageItem(Bt+e,n)},getNumber(e,n){const s=t().getStorageItem(Bt+e);if(null===s)return n;const i=Number(s);return Number.isNaN(i)?n:i},setNumber(e,n){t().setStorageItem(Bt+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(Bt+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(Bt+e,String(n))},getJSON(e,n){const s=t().getStorageItem(Bt+e);if(null===s)return n;try{return JSON.parse(s)}catch(t){return console.warn(`[Storage] Failed to parse JSON for key "${e}"`,t),n}},setJSON(e,n){t().setStorageItem(Bt+e,JSON.stringify(n))},remove(e){t().removeStorageItem(Bt+e)},has:e=>null!==t().getStorageItem(Bt+e),clear(){t().clearStorage(Bt)}};function zt(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=Wt(t[e]),o=Wt(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function Wt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Dt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Ht=null;function $t(e){Ht=e}function Lt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Ht&&Ht(e,t)}function Ot(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={r:t.x,g:t.y,b:t.z,a:t.w})}return n}function Vt(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={x:t.r,y:t.g,z:t.b,w:t.a})}return n}const Nt={Transform:{ptrFn:"getTransformPtr",fields:[{name:"position",type:"vec3",offset:0},{name:"rotation",type:"quat",offset:12},{name:"scale",type:"vec3",offset:28},{name:"worldPosition",type:"vec3",offset:40},{name:"worldRotation",type:"quat",offset:52},{name:"worldScale",type:"vec3",offset:68}]},Sprite:{ptrFn:"getSpritePtr",fields:[{name:"texture",type:"u32",offset:0},{name:"color",type:"color",offset:4},{name:"size",type:"vec2",offset:20},{name:"uvOffset",type:"vec2",offset:28},{name:"uvScale",type:"vec2",offset:36},{name:"layer",type:"i32",offset:44},{name:"flipX",type:"bool",offset:48},{name:"flipY",type:"bool",offset:49},{name:"material",type:"u32",offset:52},{name:"enabled",type:"bool",offset:56}]},Velocity:{ptrFn:"getVelocityPtr",fields:[{name:"linear",type:"vec3",offset:0},{name:"angular",type:"vec3",offset:12}]},Camera:{ptrFn:"getCameraPtr",fields:[{name:"projectionType",type:"u8",offset:0},{name:"fov",type:"f32",offset:4},{name:"orthoSize",type:"f32",offset:8},{name:"nearPlane",type:"f32",offset:12},{name:"farPlane",type:"f32",offset:16},{name:"aspectRatio",type:"f32",offset:20},{name:"isActive",type:"bool",offset:24},{name:"priority",type:"i32",offset:28},{name:"viewportX",type:"f32",offset:32},{name:"viewportY",type:"f32",offset:36},{name:"viewportW",type:"f32",offset:40},{name:"viewportH",type:"f32",offset:44},{name:"clearFlags",type:"i32",offset:48}]},UIRect:{ptrFn:"getUIRectPtr",fields:[{name:"anchorMin",type:"vec2",offset:0},{name:"anchorMax",type:"vec2",offset:8},{name:"offsetMin",type:"vec2",offset:16},{name:"offsetMax",type:"vec2",offset:24},{name:"size",type:"vec2",offset:32},{name:"pivot",type:"vec2",offset:40}]},RigidBody:{ptrFn:"getRigidBodyPtr",fields:[{name:"bodyType",type:"u8",offset:0},{name:"gravityScale",type:"f32",offset:4},{name:"linearDamping",type:"f32",offset:8},{name:"angularDamping",type:"f32",offset:12},{name:"fixedRotation",type:"bool",offset:16},{name:"bullet",type:"bool",offset:17},{name:"enabled",type:"bool",offset:18}]},BoxCollider:{ptrFn:"getBoxColliderPtr",fields:[{name:"halfExtents",type:"vec2",offset:0},{name:"offset",type:"vec2",offset:8},{name:"density",type:"f32",offset:16},{name:"friction",type:"f32",offset:20},{name:"restitution",type:"f32",offset:24},{name:"isSensor",type:"bool",offset:28},{name:"enabled",type:"bool",offset:29},{name:"categoryBits",type:"u32",offset:32},{name:"maskBits",type:"u32",offset:36}]},CircleCollider:{ptrFn:"getCircleColliderPtr",fields:[{name:"radius",type:"f32",offset:0},{name:"offset",type:"vec2",offset:4},{name:"density",type:"f32",offset:12},{name:"friction",type:"f32",offset:16},{name:"restitution",type:"f32",offset:20},{name:"isSensor",type:"bool",offset:24},{name:"enabled",type:"bool",offset:25},{name:"categoryBits",type:"u32",offset:28},{name:"maskBits",type:"u32",offset:32}]}};function jt(e,t,n,s,i,o){const r=s+i.offset,a=r>>2;switch(i.type){case"f32":e[a]=o;break;case"i32":t[a]=0|o;break;case"u32":t[a]=o;break;case"bool":n[r]=o?1:0;break;case"u8":n[r]=o;break;case"vec2":e[a]=o.x,e[a+1]=o.y;break;case"vec3":e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z;break;case"quat":e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z,e[a+3]=o.w;break;case"color":e[a]=o.r,e[a+1]=o.g,e[a+2]=o.b,e[a+3]=o.a}}let Xt=1;const Yt=new WeakMap;function Gt(e){let t=Yt.get(e);return void 0===t&&(t=Xt++,Yt.set(e,t)),t}const qt=[];function Kt(e,t=[],n=[]){qt.length=0;for(const t of e)qt.push(Gt(t));qt.sort((e,t)=>e-t);let s=qt.join(",");if(t.length>0){qt.length=0;for(const e of t)qt.push(Gt(e));qt.sort((e,t)=>e-t),s+="|+"+qt.join(",")}if(n.length>0){qt.length=0;for(const e of n)qt.push(Gt(e));qt.sort((e,t)=>e-t),s+="|-"+qt.join(",")}return s}class Jt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.builtinEntitySets_=new Map,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map,this.trackedComponents_=new Set}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}getWasmModule(){return this.module_}spawn(e){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let t;if(this.cppRegistry_)try{t=this.cppRegistry_.create()}catch(e){throw Lt(e,"spawn"),e}else t=++this.nextEntityId_;let n=0;if(this.module_&&this.cppRegistry_)try{n=this.module_.registry_getGeneration(this.cppRegistry_,t)}catch{}else n=++this.nextGeneration_;this.entities_.set(t,n),this.worldVersion_++,void 0!==e&&this.insert(t,ut,{value:e});for(const e of this.spawnCallbacks_)try{e(t)}catch(e){console.warn("[World] Spawn callback error:",e)}return t}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch(e){console.warn("[World] Despawn callback error:",e)}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Lt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;for(const[,t]of this.builtinEntitySets_)t.delete(e);const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){Lt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Lt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return De(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(De(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Vt(o,t._colorKeys))}catch(n){Lt(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return De(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){if(t._builtin){if(!this.cppRegistry_)return!1;const n=t._cppName,s=this.builtinEntitySets_.get(n);return s?s.has(e):this.getBuiltinMethods(n).has(e)}return this.hasScript(e,t)}tryGet(e,t){if(De(t)){if(!this.cppRegistry_)return null;const n=this.builtinEntitySets_.get(t._cppName);if(n&&!n.has(e))return null;try{const s=this.getBuiltinMethods(t._cppName);return n||s.has(e)?Ot(s.get(e),t._colorKeys):null}catch(n){return Lt(n,`tryGet(${t._name}, entity=${e})`),null}}const n=this.tsStorage_.get(t._id);if(!n)return null;const s=n.get(e);return void 0!==s?s:null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");De(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=zt(t._name,s,i);if(e.length>0)throw new Error(Dt(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Vt(o,t._colorKeys))}catch(n){Lt(n,`insertBuiltin(${t._name}, entity=${e})`)}let a=this.builtinEntitySets_.get(t._cppName);a||(a=new Set,this.builtinEntitySets_.set(t._cppName,a));const l=a.has(e);return!r&&l||(l||a.add(e),this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return Ot(this.getBuiltinMethods(t._cppName).get(e),t._colorKeys)}catch(n){return Lt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Lt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Lt(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++,this.builtinEntitySets_.get(t._cppName)?.delete(e)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=zt(t._name,t._default,e);if(i.length>0)throw new Error(Dt(t._name,i));s=e}const i=t.create(s),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=new Set,this.entityComponents_.set(e,a)),a.add(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);s&&s.delete(t._id)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resolveGetter(e){if(De(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrGetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?e=>t.get(e):e=>Ot(t.get(e),n)}const t=this.tsStorage_.get(e._id);return t?e=>t.get(e):null}resolveHas(e){if(De(e)){if(!this.cppRegistry_)return null;const t=this.getBuiltinMethods(e._cppName);return e=>t.has(e)}const t=this.tsStorage_.get(e._id);return t?e=>t.has(e):null}resolveSetter(e){if(De(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrSetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?(e,n)=>t.add(e,n):(e,s)=>t.add(e,Vt(s,n))}const t=this.tsStorage_.get(e._id);return t?(e,n)=>t.set(e,n):null}resolvePtrFn_(e){const t=Nt[e];if(!t)return null;const n=this.module_[t.ptrFn];if(!n)return null;const s=this.cppRegistry_;return e=>n(s,e)}resolvePtrSetter_(e){const t=Nt[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,i=t.fields;return(e,t)=>{const o=n(e);if(!o)return;const r=t;for(let e=0;e<i.length;e++)jt(s.HEAPF32,s.HEAPU32,s.HEAPU8,o,i[e],r[i[e].name])}}resolvePtrGetter_(e){const t=Nt[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,i=t.fields,o=function(e){const t={};for(const n of e)switch(n.type){case"vec2":t[n.name]={x:0,y:0};break;case"vec3":t[n.name]={x:0,y:0,z:0};break;case"quat":t[n.name]={x:0,y:0,z:0,w:0};break;case"color":t[n.name]={r:0,g:0,b:0,a:0};break;default:t[n.name]=null}return t}(i);return e=>{const t=n(e);return t?(function(e,t,n,s,i,o){for(let r=0;r<i.length;r++){const a=i[r],l=s+a.offset,c=l>>2;switch(a.type){case"f32":o[a.name]=e[c];break;case"i32":o[a.name]=0|t[c];break;case"u32":o[a.name]=t[c];break;case"bool":o[a.name]=0!==n[l];break;case"u8":o[a.name]=n[l];break;case"vec2":{const t=o[a.name];t.x=e[c],t.y=e[c+1];break}case"vec3":{const t=o[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2];break}case"quat":{const t=o[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2],t.w=e[c+3];break}case"color":{const t=o[a.name];t.r=e[c],t.g=e[c+1],t.b=e[c+2],t.a=e[c+3];break}}}}(s.HEAPF32,s.HEAPU32,s.HEAPU8,t,i,o),o):null}}resetQueryPool(){}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch(e){console.warn(`[World] Component check failed for ${n}:`,e)}if(this.cppRegistry_)for(const[n,s]of He)if(De(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch(e){console.warn(`[World] Builtin check failed for ${n}:`,e)}const n=this.entityComponents_.get(e);if(n){const e=Re();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}resolveStorages_(e,t,n){for(const s of e)if(De(s)){if(!this.cppRegistry_)return!1;n.push(this.getBuiltinMethods(s._cppName))}else{const e=this.tsStorage_.get(s._id);if(!e)return!1;t.push(e)}return!0}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??Kt(e,t,n),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;const r=[],a=[],l=[];if(!this.resolveStorages_(e,a,l))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),r;let c=null,u=null;if(t.length>0&&(c=[],u=[],!this.resolveStorages_(t,c,u)))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),r;let h=null,d=null;n.length>0&&(h=[],d=[],this.resolveStorages_(n,h,d));let f=null,p=1/0;for(let e=0;e<a.length;e++){const t=a[e].size;t<p&&(p=t,f=a[e])}for(const t of e)if(De(t)){const e=this.builtinEntitySets_.get(t._cppName);e&&e.size<p&&(p=e.size,f=e)}const m=f?f.keys():this.entities_.keys(),g=a.length,y=l.length;for(const e of m){let t=!0;for(let n=0;n<g;n++)if(!a[n].has(e)){t=!1;break}if(t)for(let n=0;n<y;n++)if(!l[n].has(e)){t=!1;break}if(t&&c){for(let n=0;n<c.length;n++)if(!c[n].has(e)){t=!1;break}if(t)for(let n=0;n<u.length;n++)if(!u[n].has(e)){t=!1;break}}if(t&&h){for(let n=0;n<h.length;n++)if(h[n].has(e)){t=!1;break}if(t)for(let n=0;n<d.length;n++)if(d[n].has(e)){t=!1;break}}t&&r.push(e)}return this.queryCache_.set(i,{version:this.worldVersion_,result:r}),r}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}enableChangeTracking(e){this.trackedComponents_.add(e._id)}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}markChanged(e,t){this.recordChangedTick_(t,e)}recordChangedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Zt(e){return{_type:"mut",_component:e}}function Qt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function en(e){return{_filterType:"added",_component:e}}function tn(e){return{_filterType:"changed",_component:e}}function nn(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function sn(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function on(e){return Qt(e)||nn(e)||sn(e)?e._component:e}function rn(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Qt(e)&&s.push(t),nn(e)?i.push({index:t,component:e._component}):sn(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>rn(e,[...t,...s],n),without:(...s)=>rn(e,t,[...n,...s])}}function an(...e){return rn(e)}class ln{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(on),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Kt(this.allRequired_,t._with,t._without),this.getters_=this.actualComponents_.map(t=>e.resolveGetter(t)),this.mutSetters_=t._mutIndices.map(t=>e.resolveSetter(this.actualComponents_[t])),this.mutIsBuiltin_=t._mutIndices.map(e=>De(this.actualComponents_[e]));for(const n of t._addedFilters)e.enableChangeTracking(n.component);for(const n of t._changedFilters)e.enableChangeTracking(n.component)}resetTick(e){this.lastRunTick_=e}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,h=this.getters_,d=this;let f=0,p=null,m=!1,g=!1;const y=this.mutIsBuiltin_,_=()=>{for(let e=0;e<l;e++){const t=a[e];if(y[e]){const n=c[e];n?n(p,t.data):u.set(p,t.component,t.data)}else u.markChanged(p,t.component)}},x=()=>{g||(g=!0,u.endIteration(),null!==p&&i&&_())},w={value:r,done:!1},b={value:void 0,done:!0};return{next(){for(m||(m=!0,u.beginIteration());f<n.length;){const c=n[f++];if(!o||d.passesChangeFilters_(c)){null!==p&&i&&_(),r[0]=c;for(let e=0;e<s;e++){const n=h[e];r[e+1]=n?n(c):u.get(c,t[e])}if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];p=c}return w}}return x(),b},return:()=>(x(),b)}}forEach(e){const{_mutIndices:t}=this.descriptor_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=this.actualComponents_.length,i=t.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,h=this.getters_,d=this.actualComponents_;u.beginIteration();let f=null;for(let p=0;p<n.length;p++){const m=n[p];if(!o||this.passesChangeFilters_(m)){if(null!==f&&i)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}r[0]=m;for(let e=0;e<s;e++){const t=h[e];r[e+1]=t?t(m):u.get(m,d[e])}if(i){for(let e=0;e<l;e++)a[e].data=r[t[e]+1];f=m}switch(s){case 1:e(m,r[1]);break;case 2:e(m,r[1],r[2]);break;case 3:e(m,r[1],r[2],r[3]);break;default:e.apply(null,r)}}}if(null!==f&&i)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}u.endIteration()}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function cn(e){return{_type:"removed",_component:e}}class un{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n,e.enableChangeTracking(t)}resetTick(e){this.lastRunTick_=e}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function hn(){return{_type:"commands"}}class dn{constructor(e,t,n){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0,void 0!==n&&this.insert(ut,{value:n})):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=De(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 fn{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(e){const t=new dn(this,null,e);return this.spawned_.push(t),t}entity(e){return new dn(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function pn(e){return{_id:Symbol(`Event_${e}`),_name:e}}class mn{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class gn{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new mn)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new mn,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function yn(e){return{_type:"event_writer",_event:e}}function _n(e){return{_type:"event_reader",_event:e}}class xn{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class wn{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var bn;function vn(){return{_type:"get_world"}}!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"}(bn||(bn={}));let Sn=0;function Mn(e,t,n){const s=++Sn;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Cn(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Pn(e){Cn().push({schedule:bn.Update,system:e})}function Tn(e){Cn().push({schedule:bn.Startup,system:e})}function En(e,t){Cn().push({schedule:e,system:t})}class An{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.queryCache_=new Map,this.removedCache_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;let n=this.queryCache_.get(e._id),s=this.removedCache_.get(e._id);const i=!n;i&&(n=[],s=[],this.queryCache_.set(e._id,n),this.removedCache_.set(e._id,s));let o=0,r=0;for(let a=0;a<e._params.length;a++){const l=e._params[a];if("query"===l._type){if(i){const e=new ln(this.world_,l,this.currentLastRunTick_);n.push(e),t[a]=e}else{const e=n[o];e.resetTick(this.currentLastRunTick_),t[a]=e}o++}else if("removed"===l._type){if(i){const e=l,n=new un(this.world_,e._component,this.currentLastRunTick_);s.push(n),t[a]=n}else{const e=s[r];e.resetTick(this.currentLastRunTick_),t[a]=e}r++}else t[a]=this.resolveParam(l)}const a=this.timings_?performance.now():0;let l;try{l=e._fn(...t)}catch(n){throw this.flushSystem_(e,t,a),n}if(l instanceof Promise)return l.then(()=>{this.flushSystem_(e,t,a)},n=>{throw this.flushSystem_(e,t,a),n});this.flushSystem_(e,t,a)}flushSystem_(e,t,n){for(let e=0;e<t.length;e++)t[e]instanceof fn&&t[e].flush();this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}resolveParam(e){switch(e._type){case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new fn(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new xn(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new wn(n)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class kn{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 Rn=Et(new kn,"Input");class In{constructor(e){this.target_=e??null}build(e){const n=new kn;e.insertResource(Rn,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(bn.Last,Mn([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fn=new In,Bn=Et({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Un;function zn(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"}(Un||(Un={}));let Wn=null,Dn=null,Hn=1;const $n=new Map;function Ln(e){Wn=e,Dn=e.getResourceManager(),Jn()}function On(){0!==Xn&&Wn&&(Wn._free(Xn),Xn=0),$n.clear(),Hn=1,jn=!1,Gn.clear(),qn=null,Dn=null,Wn=null}function Vn(){if(!Dn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Dn}const Nn={createShader:(e,t)=>Vn().createShader(e,t),releaseShader(e){e>0&&Vn().releaseShader(e)},create(e){const t=Hn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Un.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return $n.set(t,n),t},get:e=>$n.get(e),setUniform(e,t,n){const s=$n.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Wn?.invalidateMaterialCache(e))},getUniform(e,t){const n=$n.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=$n.get(e);n&&(n.blendMode=t,Wn?.invalidateMaterialCache(e))},getBlendMode(e){const t=$n.get(e);return t?.blendMode??Un.Normal},setDepthTest(e,t){const n=$n.get(e);n&&(n.depthTest=t,Wn?.invalidateMaterialCache(e))},getShader(e){const t=$n.get(e);return t?.shader??0},release(e){$n.delete(e),Wn?.invalidateMaterialCache(e)},isValid:e=>$n.has(e),releaseAll(){$n.clear(),Wn?.clearMaterialCache()},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??Un.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=$n.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Hn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return $n.set(n,s),n},toAssetData(e,t){const n=$n.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=$n.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let jn=!1,Xn=0;const Yn=16384,Gn=new Map;let qn=null;function Kn(e){const t=(0===Xn&&Wn&&(Xn=Wn._malloc(Yn)),Xn);if(0===t||!Wn)return{ptr:0,count:0};let n=0,s=0;const i=Wn.HEAPU8,o=Wn.HEAPU32,r=Wn.HEAPF32;for(const[a,l]of e){if(zn(l))continue;let e=Gn.get(a);e||(qn||(qn=new TextEncoder),e=qn.encode(a),Gn.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Yn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Yn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Jn(){if(!Wn||jn)return;Wn.materialDataProvider=(e,t,n,s,i)=>{const o=$n.get(e);if(!o)return Wn.HEAPU32[t>>2]=0,Wn.HEAPU32[n>>2]=0,Wn.HEAPU32[s>>2]=0,void(Wn.HEAPU32[i>>2]=0);Wn.HEAPU32[t>>2]=o.shader,Wn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Kn(o.uniforms);Wn.HEAPU32[s>>2]=r,Wn.HEAPU32[i>>2]=a},jn=!0}const Zn={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 Qn{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=de.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+de.assetFailureCooldown}),t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`)),t}}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()}clearAll(){this.cache_.clear(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class es{constructor(e,t=""){this.cache_=new Qn,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Nn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Nn.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:Nn.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 ts(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function ns(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0,duration:e.duration};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const ss=new Map;function is(e){ss.set(e.name,e)}function os(e){ss.delete(e)}function rs(e){return ss.get(e)}function as(){ss.clear()}const ls=Ie("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function cs(e,t){const n=e.getEntitiesWithComponents([ls]);for(const s of n){const n=e.get(s,ls);if(!n.enabled||!n.playing||!n.clip)continue;const i=ss.get(n.clip);if(!i||0===i.frames.length)continue;const o=i.frames[n.currentFrame],r=o?.duration??1/(i.fps*n.speed),a=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let l=a;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),l=!0),l&&e.has(s,Je)){const t=i.frames[n.currentFrame],o=e.get(s,Je);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,Je,o)}l&&e.insert(s,ls,n)}}class us{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static setAssetResolver(e){this.assetResolver_=e}static resolveUrl_(e){return!this.baseUrl||e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}/${e}`}static async preload(e){if(this.bufferCache_.has(e))return;if(this.assetResolver_){const t=this.assetResolver_(e);if(t)return this.preloadFromData(e,t)}const t=await this.backend_.loadBuffer(this.resolveUrl_(e));this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}us.mixer_=null,us.bufferCache_=new Map,us.bgmHandle_=null,us.bgmVolume_=1,us.fadeAnimId_=0,us.disposed_=!1,us.assetResolver_=null,us.baseUrl="";const hs=new Map,ds=new Map;function fs(e,t,n){hs.set(e,{width:t,height:n})}function ps(e){return hs.get(e)}function ms(){hs.clear()}function gs(e,t){ds.set(e,t)}function ys(e){return ds.get(e)}function _s(){ds.clear()}let xs=null;function ws(e){xs=e}function bs(){xs=null}const vs={initLayer(e,t,n,s,i){xs?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){xs?.tilemap_destroyLayer(e)},setTile(e,t,n,s){xs?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>xs?xs.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){xs?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!xs)return;const n=t.byteLength,s=xs._malloc(n);new Uint16Array(xs.HEAPU8.buffer,s,t.length).set(t),xs.tilemap_setTiles(e,s,t.length),xs._free(s)},hasLayer:e=>!!xs&&xs.tilemap_hasLayer(e),setRenderProps(e,t,n,s,i,o,r,a,l){xs?.tilemap_setRenderProps(e,t,n,s,i,o,r,a,l)},setTint(e,t,n,s,i,o){xs?.tilemap_setTint(e,t,n,s,i,o)},setVisible(e,t){xs?.tilemap_setVisible(e,t)},setOriginEntity(e,t){xs?.tilemap_setOriginEntity(e,t)},submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,y,_,x){xs?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,y,_,x)},setTileAnimation(e,t,n){if(!xs||0===n.length)return;const s=new Uint32Array(2*n.length);for(let e=0;e<n.length;e++)s[2*e]=n[e].tileId,s[2*e+1]=n[e].duration;const i=s.byteLength,o=xs._malloc(i);new Uint32Array(xs.HEAPU8.buffer,o,s.length).set(s),xs.tilemap_setTileAnimation(e,t,o,n.length),xs._free(o)},advanceAnimations(e,t){xs?.tilemap_advanceAnimations(e,t)},setTileProperty(e,t,n,s){xs?.tilemap_setTileProperty(e,t,n,s)},getTileProperty:(e,t,n,s)=>xs?xs.tilemap_getTileProperty(e,t,n,s):"",flipTile(e,t,n,s,i,o){xs?.tilemap_flipTile(e,t,n,s,i,o)},rotateTile(e,t,n,s){xs?.tilemap_rotateTile(e,t,n,s)},setGridType(e,t){xs?.tilemap_setGridType(e,t)},tileToWorld(e,t,n,s,i){if(!xs)return{x:0,y:0};const o=xs.tilemap_tileToWorld(e,t,n,s,i),r=new Float32Array(xs.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}},worldToTile(e,t,n,s,i){if(!xs)return{x:0,y:0};const o=xs.tilemap_worldToTile(e,t,n,s,i),r=new Float32Array(xs.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}}},Ss=Ie("Tilemap",{source:""}),Ms=Ie("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function Cs(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function Ps(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function Ts(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function Es(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=Ts(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,h=Ps(e.tintcolor),d="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:h,parallaxX:d,parallaxY:f})}const u=[],h=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}const d=new Map,f=new Map;if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.id,s=n+1,i=e.animation;if(i&&i.length>0){const e=i.map(e=>({tileId:(e.tileid??0)+1,duration:e.duration??100}));d.set(s,e)}const o=e.properties;if(o){const e=new Map;for(const s of o){const i=s.name;"collision"===i&&!0===s.value&&h.push(n+t),e.set(i,String(s.value))}e.size>0&&f.set(s,e)}}}return{width:t,height:n,tileWidth:s,tileHeight:i,orientation:e.orientation??"orthogonal",layers:c,tilesets:r,objectGroups:u,collisionTileIds:h,tileAnimations:d,tileProperties:f}}function As(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function ks(e,t){const n=xs;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),orientation:"orthogonal",layers:[],tilesets:[],objectGroups:[],collisionTileIds:[],tileAnimations:new Map,tileProperties:new Map},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?Cs(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch(e){return console.warn("[Tiled] Failed to parse tilemap",e),n.tiled_freeMap(r),null}}const Rs=Math.PI/180;function Is(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,h=o+(u-t.row*c)-.5*s,d=e.spawn();e.insert(d,Ge,{position:{x:r,y:h,z:0}}),e.insert(d,pt,{bodyType:Pt.Static}),e.insert(d,mt,{halfExtents:{x:.5*n,y:.5*s}}),a.push(d)}return a}function Fs(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,Ge,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Ms,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,h=-t.rotation*Rs;if(e.insert(r,Ge,{position:{x:c,y:u,z:0}}),e.insert(r,pt,{bodyType:Pt.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,gt,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,mt,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,mt,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,Ge,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=Is(e,n,t,a,0,0);i.push(...s)}return i}const Bs=0,Us=1,zs=2,Ws="property",Ds="spine",Hs="spriteAnim",$s="audio",Ls="activation",Os="marker",Vs="customEvent",Ns="animFrames",js="hermite",Xs="linear",Ys="step",Gs="easeIn",qs="easeOut",Ks="easeInOut",Js=[["1.0","1.1",e=>{for(const t of e.tracks??[])if(t.type===Ws)for(const e of t.channels??[])for(const t of e.keyframes??[])t.interpolation||Math.abs(t.outTangent)>=1e5&&(t.interpolation="step",t.outTangent=0)}]];const Zs={once:Bs,loop:Us,pingPong:zs};function Qs(e){const t={name:e.name??"",childPath:e.childPath??""};switch(e.type){case Ws:return{...t,type:Ws,component:e.component??"",channels:(e.channels??[]).map(e=>({property:e.property,keyframes:e.keyframes??[]}))};case Ds:return{...t,type:Ds,clips:e.clips??[],blendIn:e.blendIn??0};case Hs:return{...t,type:Hs,clip:e.clip??"",startTime:e.startTime??0};case $s:return{...t,type:$s,events:e.events??[]};case Ls:return{...t,type:Ls,ranges:e.ranges??[]};case Os:return{...t,type:Os,markers:e.markers??[]};case Vs:return{...t,type:Vs,events:(e.events??[]).map(e=>({time:e.time??0,name:e.name??"",payload:e.payload??{}}))};case Ns:return{...t,type:Ns,frames:(e.animFrames??[]).map(e=>({texture:e.texture??"",duration:e.duration}))};default:return console.warn(`[Timeline] Unknown track type: ${e.type}, skipping`),null}}function ei(e){return function(e){let t=e.version??"1.0";for(const[n,s,i]of Js)t===n&&(i(e),t=s);e.version="1.1"}(e),{version:"1.1",type:"timeline",duration:e.duration??0,wrapMode:(t=e.wrapMode,t?Zs[t]??Bs:Bs),tracks:(e.tracks??[]).map(Qs).filter(e=>null!==e)};var t}let ti=!1,ni=!1;function si(e){ti=e}function ii(){return ti}function oi(){return!ti}function ri(e){ni=e}function ai(){return ni}var li,ci;!function(e){e[e.PositionX=0]="PositionX",e[e.PositionY=1]="PositionY",e[e.PositionZ=2]="PositionZ",e[e.ScaleX=3]="ScaleX",e[e.ScaleY=4]="ScaleY",e[e.ScaleZ=5]="ScaleZ",e[e.RotationZ=6]="RotationZ",e[e.ColorR=7]="ColorR",e[e.ColorG=8]="ColorG",e[e.ColorB=9]="ColorB",e[e.ColorA=10]="ColorA",e[e.SpriteOpacity=11]="SpriteOpacity",e[e.SpriteSizeX=12]="SpriteSizeX",e[e.SpriteSizeY=13]="SpriteSizeY",e[e.OffsetMinX=14]="OffsetMinX",e[e.OffsetMinY=15]="OffsetMinY",e[e.OffsetMaxX=16]="OffsetMaxX",e[e.OffsetMaxY=17]="OffsetMaxY",e[e.AnchorMinX=18]="AnchorMinX",e[e.AnchorMinY=19]="AnchorMinY",e[e.AnchorMaxX=20]="AnchorMaxX",e[e.AnchorMaxY=21]="AnchorMaxY",e[e.PivotX=22]="PivotX",e[e.PivotY=23]="PivotY",e[e.CameraOrthoSize=24]="CameraOrthoSize",e[e.CustomField=25]="CustomField"}(li||(li={})),function(e){e[e.Transform=0]="Transform",e[e.Sprite=1]="Sprite",e[e.UIRect=2]="UIRect",e[e.Camera=3]="Camera",e[e.Custom=4]="Custom"}(ci||(ci={}));const ui={Transform:{"position.x":li.PositionX,"position.y":li.PositionY,"position.z":li.PositionZ,"scale.x":li.ScaleX,"scale.y":li.ScaleY,"scale.z":li.ScaleZ,rotation:li.RotationZ},Sprite:{"color.r":li.ColorR,"color.g":li.ColorG,"color.b":li.ColorB,"color.a":li.ColorA,opacity:li.SpriteOpacity,"size.x":li.SpriteSizeX,"size.y":li.SpriteSizeY},UIRect:{"offsetMin.x":li.OffsetMinX,"offsetMin.y":li.OffsetMinY,"offsetMax.x":li.OffsetMaxX,"offsetMax.y":li.OffsetMaxY,"anchorMin.x":li.AnchorMinX,"anchorMin.y":li.AnchorMinY,"anchorMax.x":li.AnchorMaxX,"anchorMax.y":li.AnchorMaxY,"pivot.x":li.PivotX,"pivot.y":li.PivotY},Camera:{orthoSize:li.CameraOrthoSize}},hi={Transform:ci.Transform,Sprite:ci.Sprite,UIRect:ci.UIRect,Camera:ci.Camera},di={[js]:0,[Xs]:1,[Ys]:2,[Gs]:3,[qs]:4,[Ks]:5};function fi(e){return e?di[e]??0:0}function pi(e,t){return ui[e]?.[t]??li.CustomField}function mi(e,t){const n=(new TextEncoder).encode(t),s=e._malloc(n.length);return new Uint8Array(e.HEAPU8.buffer,s,n.length).set(n),[s,n.length]}function gi(e,t){e._free(t)}function yi(e,t){const n=e._tl_create(t.duration,t.wrapMode);if(!n)return{handle:0,tracks:[],totalPropertyChannels:0};const s=[];let i=0;for(const o of t.tracks)switch(o.type){case Ws:_i(e,n,o),s.push({type:"property",component:o.component,childPath:o.childPath,channelProperties:o.channels.map(e=>e.property)}),i+=o.channels.length;break;case Ds:xi(e,n,o),s.push({type:"spine",childPath:o.childPath});break;case $s:wi(e,n,o),s.push({type:"audio",childPath:o.childPath});break;case Ls:bi(e,n,o),s.push({type:"activation",childPath:o.childPath});break;case Hs:vi(e,n,o),s.push({type:"spriteAnim",childPath:o.childPath})}return{handle:n,tracks:s,totalPropertyChannels:i}}function _i(e,t,n){const s=e,i=n.channels.length,o=hi[n.component]??ci.Custom;if(o===ci.Custom)return void function(e,t,n){const s=e,i=n.channels.length,[o,r]=mi(e,n.childPath),[a,l]=mi(e,n.component),c=n.channels.map(e=>(new TextEncoder).encode(e.property));let u=0;for(const e of c)u+=e.length;const h=s._malloc(u);let d=0;for(const e of c)new Uint8Array(s.HEAPU8.buffer,h+d,e.length).set(e),d+=e.length;const f=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,f,i).set(c.map(e=>e.length));let p=0;const m=[];for(const e of n.channels)m.push(e.keyframes.length),p+=e.keyframes.length;const g=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,g,i).set(m);const y=s._malloc(5*p*4),_=new Float32Array(s.HEAPU8.buffer,y,5*p);let x=0;for(const e of n.channels)for(const t of e.keyframes)_[x++]=t.time,_[x++]=t.value,_[x++]=t.inTangent,_[x++]=t.outTangent,_[x++]=fi(t.interpolation);e._tl_addCustomPropertyTrack(t,o,r,a,l,h,f,i,y,g),gi(e,o),gi(e,a),gi(e,h),gi(e,f),gi(e,g),gi(e,y)}(e,t,n);const[r,a]=mi(e,n.childPath),l=s._malloc(i),c=new Uint8Array(s.HEAPU8.buffer,l,i);for(let e=0;e<i;e++)c[e]=pi(n.component,n.channels[e].property);let u=0;const h=[];for(const e of n.channels)h.push(e.keyframes.length),u+=e.keyframes.length;const d=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,d,i).set(h);const f=s._malloc(5*u*4),p=new Float32Array(s.HEAPU8.buffer,f,5*u);let m=0;for(const e of n.channels)for(const t of e.keyframes)p[m++]=t.time,p[m++]=t.value,p[m++]=t.inTangent,p[m++]=t.outTangent,p[m++]=fi(t.interpolation);e._tl_addPropertyTrack(t,r,a,o,l,i,f,d),gi(e,r),gi(e,l),gi(e,d),gi(e,f)}function xi(e,t,n){if(n.type!==Ds)return;const s=e,[i,o]=mi(e,n.childPath),r=n.clips.length,a=s._malloc(4*r*4),l=new Float32Array(s.HEAPU8.buffer,a,4*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),h=s._malloc(4*r),d=new Int32Array(s.HEAPU8.buffer,h,r),f=[];for(let t=0;t<r;t++){const s=n.clips[t];l[4*t]=s.start,l[4*t+1]=s.duration,l[4*t+2]=s.speed,l[4*t+3]=s.loop?1:0;const[i,o]=mi(e,s.animation);u[t]=i,d[t]=o,f.push(i)}e._tl_addSpineTrack(t,i,o,a,c,h,r,n.blendIn),gi(e,i),gi(e,a),gi(e,c),gi(e,h);for(const t of f)gi(e,t)}function wi(e,t,n){if(n.type!==$s)return;const s=e,[i,o]=mi(e,n.childPath),r=n.events.length,a=s._malloc(2*r*4),l=new Float32Array(s.HEAPU8.buffer,a,2*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),h=s._malloc(4*r),d=new Int32Array(s.HEAPU8.buffer,h,r),f=[];for(let t=0;t<r;t++){const s=n.events[t];l[2*t]=s.time,l[2*t+1]=s.volume;const[i,o]=mi(e,s.clip);u[t]=i,d[t]=o,f.push(i)}e._tl_addAudioTrack(t,i,o,a,c,h,r),gi(e,i),gi(e,a),gi(e,c),gi(e,h);for(const t of f)gi(e,t)}function bi(e,t,n){if(n.type!==Ls)return;const s=e,[i,o]=mi(e,n.childPath),r=s._malloc(2*n.ranges.length*4),a=new Float32Array(s.HEAPU8.buffer,r,2*n.ranges.length);for(let e=0;e<n.ranges.length;e++)a[2*e]=n.ranges[e].start,a[2*e+1]=n.ranges[e].end;e._tl_addActivationTrack(t,i,o,r,n.ranges.length),gi(e,i),gi(e,r)}function vi(e,t,n){if(n.type!==Hs)return;const[s,i]=mi(e,n.childPath),[o,r]=mi(e,n.clip);e._tl_addSpriteAnimTrack(t,s,i,o,r,n.startTime),gi(e,s),gi(e,o)}const Si=new Map;let Mi=null;function Ci(e,t){Si.set(e,t)}function Pi(e){return Si.get(e)}function Ti(){if(Mi)for(const e of Si.values())Mi._tl_destroy(e);Si.clear()}var Ei;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Ei||(Ei={}));const Ai={model:Ei.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function ki(e,t=Ai){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case Ei.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case Ei.Inverse:a=s/Math.max(r,s);break;case Ei.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Ri(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const Ii=Ie("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Ei.Inverse,rolloff:1,priority:0,enabled:!0}),Fi=Ie("AudioListener",{enabled:!0});class Bi{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;us.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(bn.PreUpdate,Mn([At(Ft)],t=>{if(!(!ii()||ai()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,h=!1;const d=s.getEntitiesWithComponents([Fi,Ke]);for(const e of d){if(s.get(e,Fi).enabled){const t=s.get(e,Ke);i=t.position.x,u=t.position.y,h=!0;break}}const f=s.getEntitiesWithComponents([Ii]);a.clear();for(const e of f){const t=s.get(e,Ii);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=us.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,Ke),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=ki(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Ri(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),us.dispose()}}const Ui=new Bi,zi=Ie("TimelinePlayer",{timeline:"",playing:!1,speed:1,wrapMode:"once"}),Wi=new Map;function Di(e,t){Wi.set(e,t)}const Hi=new Map;function $i(e,t){return Hi.get(e)?.get(t)??0}const Li={once:Bs,loop:Us,pingPong:zs};function Oi(e,t,n){const s=t.split(".");let i=e;for(let e=0;e<s.length-1;e++)if(i=i[s[e]],null==i||"object"!=typeof i)return!1;const o=s[s.length-1];return o in i&&(i[o]=n,!0)}function Vi(e,t,n){if(!n)return t;const s=Le("Children"),i=Le("Name");if(!s||!i)return null;let o=t;const r=n.split("/");for(const t of r){const n=e.tryGet(o,s);if(!n)return null;const r=n.entities||[];let a=null;for(const n of r){const s=e.tryGet(n,i);if(s&&s.value===t){a=n;break}}if(null===a)return null;o=a}return o}class Ni{constructor(){this.name="TimelinePlugin",this.handles_=new Map,this.animFramesStates_=new Map}build(e){const t=e.world;e.addSystemToSchedule(bn.Update,Mn([At(Ft)],e=>{if(ii()&&!ai())return;const n=t.getWasmModule();if(!n)return;Mi=n;const s=t.getCppRegistry();n.uiRect_clearAnimOverrides(s);const i=t.getEntitiesWithComponents([zi]);for(const s of i){const i=t.get(s,zi);if(!i.timeline)continue;let o=this.handles_.get(s);if(!o){const e=Wi.get(i.timeline);if(!e)continue;if(o=yi(n,e),!o.handle)continue;this.resolveTrackTargets(t,n,o,s),this.handles_.set(s,o),Ci(s,o.handle);const r=e.tracks.filter(e=>e.type===Ns);r.length>0&&this.animFramesStates_.set(s,{tracks:r,lastFrameIndices:r.map(()=>-1)})}const r=o.handle;if(i.playing&&!n._tl_isPlaying(r)){const e=n._tl_getTime(r);0===e?n._tl_play(r):(n._tl_play(r),n._tl_setTime(r,e))}else!i.playing&&n._tl_isPlaying(r)&&n._tl_pause(r);const a=Li[i.wrapMode]??Bs;n._tl_setWrapMode(r,a),n._tl_advance(t.getCppRegistry(),r,s,e.delta,i.speed),this.processEvents(t,n),this.processCustomProperties(t,n,o),this.processAnimFrames(t,n,s,o.handle,i.timeline),n._tl_clearResults(),!n._tl_isPlaying(r)&&i.playing&&(i.playing=!1,t.insert(s,zi,i))}},{name:"TimelineSystem"}))}clearHandles(){this.handles_.clear(),this.animFramesStates_.clear()}cleanup(){this.handles_.clear(),this.animFramesStates_.clear(),Wi.clear()}processAnimFrames(e,t,n,s,i){const o=this.animFramesStates_.get(n);if(!o)return;const r=t._tl_getTime(s),a=Le("Sprite");if(!a||!e.has(n,a))return;const l=1/12;for(let t=0;t<o.tracks.length;t++){const s=o.tracks[t].frames;if(0===s.length)continue;let c=0,u=0;for(let e=0;e<s.length;e++){const t=s[e].duration??l;if(r<c+t){u=e;break}c+=t,e===s.length-1&&(u=s.length-1)}if(u!==o.lastFrameIndices[t]){o.lastFrameIndices[t]=u;const r=$i(i,s[u].texture);if(r){const t=e.get(n,a);t.texture=r,e.set(n,a,t)}}}}resolveTrackTargets(e,t,n,s){let i=0,o=0;for(const r of n.tracks){if(!r.childPath){"property"===r.type?i++:o++;continue}const a=Vi(e,s,r.childPath);if(null!==a){const e="property"!==r.type,s=e?o:i;t._tl_setTrackTarget(n.handle,e?1:0,s,a)}"property"===r.type?i++:o++}}decodeEventString(e,t){const n=e._tl_getEventString(t),s=e._tl_getEventStringLen(t);if(!n||s<=0)return"";const i=new Uint8Array(e.HEAPU8.buffer,n,s);return(new TextDecoder).decode(i)}processEvents(e,t){const n=t._tl_getEventCount();for(let s=0;s<n;s++){const n=t._tl_getEventType(s),i=t._tl_getEventEntity(s);switch(n){case 0:{const n=this.decodeEventString(t,s),o=0!==t._tl_getEventIntParam(s);if(e.has(i,ot)){const t=e.get(i,ot);t.animation=n,t.playing=!0,t.loop=o,e.set(i,ot,t)}break}case 1:if(e.has(i,ot)){const t=e.get(i,ot);t.playing=!1,e.set(i,ot,t)}break;case 2:{const n=this.decodeEventString(t,s);if(e.has(i,ls)){const t=e.get(i,ls);e.insert(i,ls,{...t,clip:n,playing:!0})}break}case 3:{const e=this.decodeEventString(t,s),n=t._tl_getEventFloatParam(s);e&&us.playSFX(e,{volume:n});break}case 4:{const n=0!==t._tl_getEventIntParam(s);if(e.has(i,ot)){const t=e.get(i,ot);t.enabled=n,e.set(i,ot,t)}if(e.has(i,ls)){const t=e.get(i,ls);e.insert(i,ls,{...t,enabled:n})}const o=Le("Sprite");if(o&&e.has(i,o)){const t=e.get(i,o);e.set(i,o,{...t,enabled:n})}break}}}}processCustomProperties(e,t,n){const s=t._tl_getCustomPropertyCount();if(0!==s)for(let i=0;i<s;i++){const s=t._tl_getCustomPropertyEntity(i),o=t._tl_getCustomPropertyTrackIndex(i),r=t._tl_getCustomPropertyChannelIndex(i),a=t._tl_getCustomPropertyValue(i),l=n.tracks.filter(e=>"property"===e.type)[o];if(!l?.component||!l.channelProperties)continue;const c=Le(l.component);if(!c||!e.has(s,c))continue;const u=e.get(s,c),h=l.channelProperties[r];h&&Oi(u,h,a)&&e.set(s,c,u)}}}const ji=new Ni,Xi=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["UIRenderer",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}],["TimelinePlayer",{fields:[{field:"timeline",type:"timeline"}]}]]);function Yi(e,t){Xi.set(e,t)}function Gi(e){const t=Xi.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function qi(e){return Xi.get(e)?.fields??[]}function Ki(e){return Xi.get(e)?.spine??null}function Ji(e,t){const n=Te(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function Zi(e){const t=e.components.some(e=>"UIRect"===e.type),n=e.components.findIndex(e=>"Sprite"===e.type),s=e.components.some(e=>"UIRenderer"===e.type);if(!t||-1===n||s)return;const i=e.components[n].data,o=i.texture;e.components.push({type:"UIRenderer",data:{visualType:o?2:1,texture:o??0,color:i.color??{r:1,g:1,b:1,a:1},uvOffset:i.uvOffset??{x:0,y:0},uvScale:i.uvScale??{x:1,y:1},sliceBorder:i.sliceBorder??{x:0,y:0,z:0,w:0},material:i.material??0,enabled:i.enabled??!0}}),e.components.splice(n,1)}function Qi(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,ut,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;Zi(s);const t=n.get(s.id);for(const i of s.components)Ji(i,n),so(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function eo(e,t){return Qi(e,t)}async function to(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of no.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Xi.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...no.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Xi.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=Qi(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const no=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),fs(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=ts(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);is(ns(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await us.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=Es(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=As(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),fs(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}gs(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}],["timeline",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=ei(await t.loadJson(e));Di(e,i);const o=function(e){const t=new Set,n=new Set,s=new Set;for(const i of e.tracks)if(i.type===$s)for(const e of i.events)t.add(e.clip);else if(i.type===Hs)i.clip&&n.add(i.clip);else if(i.type===Ns)for(const e of i.frames)e.texture&&s.add(e.texture);return{audio:Array.from(t),animClips:Array.from(n),textures:Array.from(s)}}(i);if(o.textures.length>0){const i=new Map,r=o.textures.map(async e=>{try{const o=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o)}catch(t){console.warn(`Failed to load animFrames texture: ${e}`,t),i.set(e,0)}});await Promise.all(r),function(e,t){Hi.set(e,t)}(e,i)}}catch(t){console.warn(`Failed to load timeline: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function so(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=Le(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function io(e,t){const n=e.getEntitiesWithComponents([Qe]);for(const s of n){const n=e.get(s,Qe);n&&(n.aspectRatio=t,e.insert(s,Qe,n))}}function oo(e,t){const n=e.getEntitiesWithComponents([ut]);for(const s of n){const n=e.get(s,ut);if(n&&n.value===t)return s}return null}class ro{constructor(e){this.textureCache_=new Qn,this.shaderCache_=new Qn,this.jsonCache_=new Qn,this.textCache_=new Qn,this.binaryCache_=new Qn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Qn,this.prefabCache_=new Qn,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(de.textCanvasSize,de.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new es(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureRefCounts_.get(s);if(void 0===i)continue;const o=this.textureCache_.get(s);if(!o)continue;const r=i-1;r<=0?(t.releaseTexture(o.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),Nn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===P(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=P(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of Gi(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=Ki(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 to(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){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=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Nn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Nn.createShader(i,o)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(W(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 ao=Et(null,"Assets");class lo{build(e){const t=e.wasmModule;t?e.insertResource(ao,new ro(t)):console.warn("AssetPlugin: No WASM module available")}}const co=new lo;class uo{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function ho(e,t){const n=e.getResource(ao);n&&n.registerEmbeddedAssets(t)}function fo(e){return e.map(e=>({type:e.type,data:JSON.parse(JSON.stringify(e.data))}))}function po(e){return JSON.parse(JSON.stringify(e))}function mo(e,t){for(const n of e){const e=Te(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function go(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:po(n.componentData.data)})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}function yo(e,t,n){const s=n.depth??0;if(s>10)throw new Error(`Prefab nesting depth exceeded 10. Check for deep or circular nesting in: ${e.name}`);if(e.basePrefab)return function(e,t,n,s){const i=e.basePrefab,o=n.visited??new Set;if(o.has(i))throw new Error(`[Prefab] Circular variant reference detected: "${i}" is already being instantiated in the current prefab chain`);const r=n.loadPrefab(i);if(!r)throw new Error(`Failed to load base prefab for variant: ${i}`);o.add(i);const a=[...e.overrides??[],...t];return yo(r,a,{...n,visited:o,depth:s+1})}(e,t,n,s);const i=n.visited??new Set,o=new Map;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,n.allocateId());const r=[];for(const a of e.entities){if(a.nestedPrefab){const e=a.nestedPrefab.prefabPath;if(i.has(e))throw new Error(`[Prefab] Circular reference detected: "${e}" is already being instantiated in the current prefab chain`);const t=n.loadPrefab(e);if(!t)throw new Error(`Failed to load nested prefab: ${e}`);i.add(e);const l=yo(t,a.nestedPrefab.overrides,{...n,visited:i,depth:s+1});o.set(a.prefabEntityId,l.rootId);const c=l.entities.find(e=>e.id===l.rootId);c&&(c.parent=null!==a.parent?o.get(a.parent)??null:null),r.push(...l.entities);continue}const l=o.get(a.prefabEntityId),c=a.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:a.prefabEntityId,name:a.name,parent:c?null:null!==a.parent?o.get(a.parent)??null:null,children:a.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:fo(a.components),visible:a.visible};mo(u.components,o),go(u,t),r.push(u)}const a=o.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:r,rootId:a}}function _o(e,t,n){const s=[],i=n??new Set;if(e.basePrefab&&!i.has(e.basePrefab)){i.add(e.basePrefab),s.push(e.basePrefab);const n=t(e.basePrefab);n&&s.push(..._o(n,t,i))}for(const n of e.entities){if(!n.nestedPrefab)continue;const e=n.nestedPrefab.prefabPath;if(i.has(e))continue;i.add(e),s.push(e);const o=t(e);o&&s.push(..._o(o,t,i))}return s}async function xo(e,t,n,s,i=0){if(i>10)return;const o=s??new Set;if(e.basePrefab&&!o.has(e.basePrefab)&&!n.has(e.basePrefab)){o.add(e.basePrefab);const s=await t(e.basePrefab);n.set(e.basePrefab,s),await xo(s,t,n,o,i+1)}for(const s of e.entities){if(!s.nestedPrefab)continue;const e=s.nestedPrefab.prefabPath;if(o.has(e)||n.has(e))continue;o.add(e);const r=await t(e);n.set(e,r),await xo(r,t,n,o,i+1)}}async function wo(e,t,n){const s=new Map;n?.assetServer&&await xo(t,e=>n.assetServer.loadPrefab(e,n.assetBaseUrl),s);let i=0;const o={allocateId:()=>i++,loadPrefab:e=>s.get(e)??null,visited:new Set},{entities:r,rootId:a}=yo(t,n?.overrides??[],o),l={version:t.version,name:t.name,entities:r.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},c=await to(e,l,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),u=c.get(a);return void 0!==n?.parent&&e.setParent(u,n.parent),{root:u,entities:c}}class bo{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return wo(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const vo=Et(null,"Prefabs");class So{constructor(){this.name="PrefabsPlugin",this.dependencies=[ao]}build(e){const t=e.getResource(ao);e.insertResource(vo,new bo(e.world,t))}}const Mo=new So;let Co=null,Po=0,To=0,Eo=0;const Ao=new Float32Array(256);function ko(e){Co=e,Po=Co._malloc(64),To=Co._malloc(64),Eo=Co._malloc(1024)}function Ro(){Co&&(Po&&(Co._free(Po),Po=0),To&&(Co._free(To),To=0),Eo&&(Co._free(Eo),Eo=0)),Co=null}function Io(){if(!Co)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Co}const Fo={r:1,g:1,b:1,a:1},Bo={begin(e){const t=Io();try{t.HEAPF32.set(e,Po/4),t.draw_begin(Po)}catch(e){Lt(e,"Draw.begin")}},end(){try{Io().draw_end()}catch(e){Lt(e,"Draw.end")}},line(e,t,n,s=1){try{Io().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Lt(e,"Draw.line")}},rect(e,t,n,s=!0){try{Io().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Lt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Io().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Lt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Io().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Lt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Io().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Lt(e,"Draw.circleOutline")}},texture(e,t,n,s=Fo){try{Io().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Lt(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Fo){try{Io().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Lt(e,"Draw.textureRotated")}},setLayer(e){Io().draw_setLayer(e)},setDepth(e){Io().draw_setDepth(e)},getDrawCallCount:()=>Co?Co.draw_getDrawCallCount():0,getPrimitiveCount:()=>Co?Co.draw_getPrimitiveCount():0,setBlendMode(e){Io().draw_setBlendMode(e)},setDepthTest(e){Io().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Io();s.HEAPF32.set(n,To/4),s.draw_mesh(e,t,To)}catch(n){Lt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Io(),i=Nn.get(t);if(!i)return;if(Bo.setBlendMode(i.blendMode),Bo.setDepthTest(i.depthTest),0===i.uniforms.size)return void Bo.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,To/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=Wo(t);if(!(s<0)){if(zn(n))Ao[o++]=10,Ao[o++]=s,Ao[o++]=n.slot??e++,Ao[o++]=n.textureId;else if("number"==typeof n)Ao[o++]=1,Ao[o++]=s,Ao[o++]=n;else if(Array.isArray(n)){Ao[o++]=n.length,Ao[o++]=s;for(let e=0;e<n.length;e++)Ao[o++]=n[e]}else"w"in n?(Ao[o++]=4,Ao[o++]=s,Ao[o++]=n.x,Ao[o++]=n.y,Ao[o++]=n.z,Ao[o++]=n.w):"z"in n?(Ao[o++]=3,Ao[o++]=s,Ao[o++]=n.x,Ao[o++]=n.y,Ao[o++]=n.z):(Ao[o++]=2,Ao[o++]=s,Ao[o++]=n.x,Ao[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(Ao.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,To);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Eo/4),s.draw_meshWithUniforms(e,i.shader,To,Eo,o)}catch(n){Lt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Uo={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},zo=new Set;function Wo(e){const t=Uo[e];return void 0!==t?t:(zo.has(e)||(zo.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Uo).join(", ")}`)),-1)}const Do=new Map;function Ho(e,t,n){Do.set(e,{fn:t,scene:n??""})}function $o(e){Do.delete(e)}function Lo(){Do.clear()}var Oo;!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"}(Oo||(Oo={}));let Vo=null,No=0,jo=0,Xo=0;function Yo(e){Vo=e,No=Vo._malloc(262144),jo=Vo._malloc(65536),Xo=Vo._malloc(256)}function Go(){Vo&&(No&&Vo._free(No),jo&&Vo._free(jo),Xo&&Vo._free(Xo),No=0,jo=0,Xo=0),Vo=null}function qo(){if(!Vo)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Vo}const Ko={create(e){const t=qo(),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,No/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Xo,i).set(o),t.geometry_init(n,No,s,Xo,i,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,jo,s).set(e.indices),t.geometry_setIndices16(n,jo,s)}else{new Uint32Array(t.HEAPU8.buffer,jo,s).set(e.indices),t.geometry_setIndices32(n,jo,s)}}return n},updateVertices(e,t,n=0){const s=qo(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,No/4),s.geometry_updateVertices(e,No,i,n)},release(e){e>0&&qo().geometry_release(e)},isValid:e=>!(!Vo||e<=0)&&Vo.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Ko.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:Oo.Float2},{name:"a_texCoord",type:Oo.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 i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Ko.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Oo.Float2},{name:"a_texCoord",type:Oo.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return Ko.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Oo.Float2},{name:"a_texCoord",type:Oo.Float2}],indices:new Uint16Array(r)})}};let Jo=1;const Zo=new Map,Qo=new Map;function er(){return Zo}function tr(){return Qo}class nr{constructor(){this.passes_=[],this.destroyed_=!1,this.id=Jo++,Zo.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}clearPasses(){return this.passes_.length=0,this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of Qo)t===this&&Qo.delete(e);Zo.delete(this.id)}}}const sr="#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";let ir=null;function or(e){ir=e}function rr(){for(const e of er().values())e.destroy();er().clear(),tr().clear(),ir&&lr.isInitialized()&&lr.shutdown(),ir=null}function ar(){if(!ir)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ir}const lr={createStack:()=>new nr,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");tr().set(e,t)},unbind(e){tr().delete(e)},getStack:e=>tr().get(e)??null,init(e,t){try{return ar().postprocess_init(e,t)}catch(n){return Lt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{ar().postprocess_shutdown()}catch(e){Lt(e,"PostProcess.shutdown")}},resize(e,t){try{ar().postprocess_resize(e,t)}catch(n){Lt(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!ir)return!1;try{return ir.postprocess_isInitialized()}catch(e){return Lt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{ar().postprocess_setBypass(e)}catch(e){Lt(e,"PostProcess.setBypass")}},begin(){try{ar().postprocess_begin()}catch(e){Lt(e,"PostProcess.begin")}},end(){try{ar().postprocess_end()}catch(e){Lt(e,"PostProcess.end")}},setOutputViewport(e,t,n,s){try{ar().postprocess_setOutputViewport(e,t,n,s)}catch(e){Lt(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=tr().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(lr.isInitialized()||lr.init(1,1),lr.setBypass(!1),function(e){const t=ar();try{t.postprocess_clearPasses()}catch(e){return void Lt(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){Lt(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){Lt(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Lt(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):lr.setBypass(!0)},_resetAfterCamera(){try{ar().postprocess_clearPasses(),ar().postprocess_setBypass(!0)}catch(e){Lt(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of tr().keys())e(t)||tr().delete(t)},screenStack:null,setScreenStack(e){lr.screenStack=e},_beginScreenCapture(){try{ar().postprocess_beginScreenCapture()}catch(e){Lt(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{ar().postprocess_endScreenCapture()}catch(e){Lt(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=lr.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=ar();try{t.postprocess_clearScreenPasses()}catch(e){return void Lt(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){Lt(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){Lt(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Lt(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{ar().postprocess_executeScreenPasses()}catch(e){Lt(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Nn.createShader(sr,"#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:()=>Nn.createShader(sr,"#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 vig = 1.0 - smoothstep(1.0 - u_softness, 1.0, dist);\n fragColor = vec4(color.rgb * mix(1.0, vig, u_intensity), color.a);\n}\n"),createGrayscale:()=>Nn.createShader(sr,"#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"),createBloomExtract:()=>Nn.createShader(sr,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_threshold;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float brightness = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float knee = u_threshold * 0.5;\n float soft = brightness - u_threshold + knee;\n soft = clamp(soft, 0.0, 2.0 * knee);\n soft = soft * soft / (4.0 * knee + 0.00001);\n float contrib = max(soft, brightness - u_threshold);\n contrib /= max(brightness, 0.00001);\n fragColor = vec4(color.rgb * contrib, 1.0);\n}\n"),createBloomKawase(e){const t=`#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n float d = (${e.toFixed(1)} + 0.5) * max(u_radius, 0.5);\n vec2 ts = 1.0 / u_resolution;\n fragColor = (\n texture(u_texture, v_texCoord + vec2(-d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2(-d, d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, d) * ts)\n ) * 0.25;\n}\n`;return Nn.createShader(sr,t)},createBloomComposite:()=>Nn.createShader(sr,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform sampler2D u_sceneTexture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 blur = texture(u_texture, v_texCoord);\n vec4 scene = texture(u_sceneTexture, v_texCoord);\n fragColor = vec4(scene.rgb + blur.rgb * u_intensity, scene.a);\n}\n"),createChromaticAberration:()=>Nn.createShader(sr,"#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")},cr=new Map;function ur(e){cr.set(e.type,e)}function hr(e){return cr.get(e)}function dr(){return Array.from(cr.keys())}function fr(){return Array.from(cr.values())}ur({type:"blur",label:"Blur",factory:()=>lr.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),ur({type:"bloom",label:"Bloom",factory:()=>lr.createBloomExtract(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:1,step:.01,defaultValue:.4},{name:"u_intensity",label:"Intensity",min:0,max:5,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:.5,max:5,step:.1,defaultValue:1}],multiPass:[{name:"bloom_extract",factory:()=>lr.createBloomExtract()},{name:"bloom_kawase_0",factory:()=>lr.createBloomKawase(0)},{name:"bloom_kawase_1",factory:()=>lr.createBloomKawase(1)},{name:"bloom_kawase_2",factory:()=>lr.createBloomKawase(2)},{name:"bloom_kawase_3",factory:()=>lr.createBloomKawase(3)},{name:"bloom_kawase_4",factory:()=>lr.createBloomKawase(4)},{name:"bloom_composite",factory:()=>lr.createBloomComposite()}]}),ur({type:"vignette",label:"Vignette",factory:()=>lr.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:.6},{name:"u_softness",label:"Softness",min:0,max:1,step:.01,defaultValue:.5}]}),ur({type:"grayscale",label:"Grayscale",factory:()=>lr.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),ur({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>lr.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const pr=new Map,mr=new Map;function gr(e,t){let n=pr.get(e),s=mr.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=lr.createStack(),pr.set(e,n)),s||(s=new Map,mr.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=hr(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}lr.bind(e,n)}else if(n&&(lr.unbind(e),n.destroy(),pr.delete(e)),s){for(const e of s.values())Nn.releaseShader(e);mr.delete(e)}}function yr(e){const t=pr.get(e);t&&(lr.unbind(e),t.destroy(),pr.delete(e));const n=mr.get(e);if(n){for(const e of n.values())Nn.releaseShader(e);mr.delete(e)}}function _r(){for(const e of pr.keys())yr(e)}const xr=Et({enabled:!0},"PostProcessVolumeConfig"),wr=new Map,br=new Map;function vr(e,t){const n=br.get(e);if(void 0!==n)return n;const s=t();return br.set(e,s),s}function Sr(e,t){if(0===t.size){const t=wr.get(e);return void(t&&(lr.unbind(e),t.destroy(),wr.delete(e)))}let n=wr.get(e);n||(n=lr.createStack(),wr.set(e,n)),n.clearPasses();for(const[e,s]of t){if(!s.enabled)continue;const t=hr(e);if(t)if(t.multiPass)for(const e of t.multiPass){const t=vr(e.name,e.factory);n.addPass(e.name,t);for(const[t,i]of s.uniforms)n.setUniform(e.name,t,i)}else{const i=vr(e,t.factory);n.addPass(e,i);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?lr.bind(e,n):lr.unbind(e)}const Mr=Mn([an(dt,Ge),an(Qe)],(e,t)=>{const n=[];for(const[t,s,i]of e)n.push({data:s,tx:{x:i.position.x,y:i.position.y}});const s=[];for(const{data:e}of n)e.isGlobal&&s.push({data:e,factor:1});const i=s.length>0?function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(s):new Map;for(const[e,n]of t)n.isActive&&Sr(e,i)},{name:"PostProcessVolumeSystem"});class Cr{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(xr,{enabled:!0}),e.addSystemToSchedule(bn.PostUpdate,Mr)}cleanup(){_r(),function(){for(const[e,t]of wr)lr.unbind(e),t.destroy();wr.clear();for(const e of br.values())Nn.releaseShader(e);br.clear()}(),lr.setScreenStack(null)}}const Pr=new Cr;var Tr,Er;!function(e){e[e.BatchFull=0]="BatchFull",e[e.TextureSlotsFull=1]="TextureSlotsFull",e[e.ScissorChange=2]="ScissorChange",e[e.StencilChange=3]="StencilChange",e[e.MaterialChange=4]="MaterialChange",e[e.BlendModeChange=5]="BlendModeChange",e[e.StageEnd=6]="StageEnd",e[e.TypeChange=7]="TypeChange",e[e.FrameEnd=8]="FrameEnd"}(Tr||(Tr={})),function(e){e[e.Sprite=0]="Sprite",e[e.Spine=1]="Spine",e[e.Mesh=2]="Mesh",e[e.ExternalMesh=3]="ExternalMesh",e[e.Text=4]="Text",e[e.Particle=5]="Particle",e[e.Shape=6]="Shape",e[e.UIElement=7]="UIElement"}(Er||(Er={}));var Ar;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ar||(Ar={}));const kr={None:0,Spine:1,Particles:2};let Rr=null,Ir=0;function Fr(e){Rr=e,Ir=Rr._malloc(64)}function Br(){Rr&&Ir&&(Rr._free(Ir),Ir=0),Rr=null}const Ur={init(e,t){Rr?.renderer_init(e,t)},resize(e,t){Rr?.renderer_resize(e,t)},beginFrame(){Rr?.renderer_beginFrame()},updateTransforms(e){if(Rr)try{Rr.renderer_updateTransforms(e._cpp)}catch(e){Lt(e,"Renderer.updateTransforms")}},begin(e,t){if(Rr&&Ir)try{Rr.HEAPF32.set(e,Ir/4),Rr.renderer_begin(Ir,t??0)}catch(e){Lt(e,"Renderer.begin")}},flush(){try{Rr?.renderer_flush()}catch(e){Lt(e,"Renderer.flush")}},end(){try{Rr?.renderer_end()}catch(e){Lt(e,"Renderer.end")}},submitAll(e,t,n,s,i,o){if(Rr)try{Rr.renderer_submitAll(e._cpp,t,n,s,i,o)}catch(e){Lt(e,"Renderer.submitAll")}},setStage(e){Rr?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Rr?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Rr?.renderer_releaseTarget(e)},getTargetTexture:e=>Rr?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rr?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Rr?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Rr?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Rr?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Rr?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Rr?Rr.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Rr?{drawCalls:Rr.renderer_getDrawCalls(),triangles:Rr.renderer_getTriangles(),sprites:Rr.renderer_getSprites(),text:Rr.renderer_getText(),spine:Rr.renderer_getSpine?.()??0,meshes:Rr.renderer_getMeshes(),culled:Rr.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0},captureNextFrame(){Rr?.renderer_captureNextFrame()},getCapturedData:()=>Rr?function(e){if(!e.renderer_hasCapturedData())return null;const t=e.renderer_getCapturedFrameSize();if(0===t)return null;const n=e.renderer_getCapturedFrameData(),s=e.renderer_getCapturedEntities(),i=e.renderer_getCapturedEntityCount(),o=e.renderer_getCapturedCameraCount(),r=e.HEAPU8,a=new DataView(r.buffer,n,76*t),l=new Uint32Array(r.buffer,s,i),c=[];for(let e=0;e<t;e++){const t=76*e,n=a.getUint32(t,!0),s=a.getUint32(t+4,!0),o=a.getUint8(t+8),r=a.getUint8(t+9),u=a.getUint8(t+10),h=a.getUint32(t+12,!0),d=a.getUint32(t+16,!0),f=a.getUint32(t+20,!0),p=a.getUint32(t+24,!0),m=a.getUint32(t+28,!0),g=a.getUint32(t+32,!0),y=a.getUint32(t+36,!0),_=a.getInt32(t+40,!0),x=a.getUint8(t+44),w=a.getInt32(t+48,!0),b=a.getInt32(t+52,!0),v=a.getInt32(t+56,!0),S=a.getInt32(t+60,!0),M=0!==a.getUint8(t+64),C=0!==a.getUint8(t+65),P=0!==a.getUint8(t+66),T=a.getInt32(t+68,!0),E=a.getUint8(t+72),A=[];for(let e=0;e<g&&y+e<i;e++)A.push(l[y+e]);c.push({index:n,cameraIndex:s,stage:o,type:r,blendMode:u,textureId:h,materialId:d,shaderId:f,vertexCount:p,triangleCount:m,entityCount:g,entityOffset:y,layer:_,flushReason:x,scissorX:w,scissorY:b,scissorW:v,scissorH:S,scissorEnabled:M,stencilWrite:C,stencilTest:P,stencilRef:T,textureSlotUsage:E,entities:A})}return{drawCalls:c,cameraCount:o}}(Rr):null,hasCapturedData:()=>Rr?.renderer_hasCapturedData()??!1,replayToDrawCall(e){Rr&&function(e,t){e.renderer_replayToDrawCall(t)}(Rr,e)},getSnapshotImageData:()=>Rr?function(e){const t=e.renderer_getSnapshotSize();if(0===t)return null;const n=e.renderer_getSnapshotWidth(),s=e.renderer_getSnapshotHeight();if(0===n||0===s)return null;const i=e.renderer_getSnapshotPtr(),o=e.HEAPU8,r=new Uint8ClampedArray(o.buffer,i,t),a=new Uint8ClampedArray(t),l=4*n;for(let e=0;e<s;e++){const t=e*l,n=(s-1-e)*l;a.set(r.subarray(t,t+l),n)}return new ImageData(a,n,s)}(Rr):null};let zr=null;function Wr(e){zr=e}function Dr(){zr=null}const Hr={enable(){zr?.gl_enableErrorCheck(!0)},disable(){zr?.gl_enableErrorCheck(!1)},check:e=>zr?.gl_checkErrors(e)??0,diagnose(){zr?.renderer_diagnose()}};class $r{constructor(){this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null,this.preFlushCallbacks_=[]}setActiveScenes(e){this.activeScenes_=e}addPreFlushCallback(e){this.preFlushCallbacks_.push(e)}beginFrame(){Ur.beginFrame()}beginScreenCapture(){lr.screenStack&&lr.screenStack.enabledPassCount>0&&(lr.isInitialized()||lr.init(1,1),lr._applyScreenStack(),lr._beginScreenCapture())}endScreenCapture(){lr.screenStack&&lr.screenStack.enabledPassCount>0&&(lr._endScreenCapture(),lr._executeScreenPasses())}submitScene(e,t,n,s){Ur.updateTransforms(e),Ur.submitAll(e,0,n.x,n.y,n.w,n.h);for(const t of this.preFlushCallbacks_)t(e);Ur.flush(),this.executeDrawCallbacks(t,s)}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Ur.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Ur.beginFrame(),Ur.setViewport(0,0,s,i),Ur.clearBuffers(3),Ur.begin(n),this.submitScene(t,n,{x:0,y:0,w:s,h:i},o),Ur.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==lr.getStack(r);a&&(lr._applyForCamera(r),lr.resize(s.w,s.h),lr.setOutputViewport(s.x,s.y,s.w,s.h),lr.begin()),Ur.setViewport(s.x,s.y,s.w,s.h),Ur.setScissor(s.x,s.y,s.w,s.h,!0),Ur.clearBuffers(i),Ur.setScissor(0,0,0,0,!1),Ur.begin(n),this.submitScene(t,n,s,o),Ur.end(),a&&(lr.end(),lr._resetAfterCamera())}executeDrawCallbacks(e,t){const n=Do;if(n.size>0){Bo.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Bo.end();for(const e of s)$o(e)}}}const Lr={None:0,SolidColor:1,Image:2,NineSlice:3},Or=Ve("UIRenderer",{visualType:Lr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),Vr="__scene_transition_overlay__";class Nr{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class jr{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,ht,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Ho(e,t,this.instance_.config.name)}bindPostProcess(e,t){lr.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){lr.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ht)){const n=this.app_.world.get(e,ht);n.persistent=t,this.app_.world.insert(e,ht,n)}}}class Xr{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())$o(t);for(const t of e.postProcessBindings.keys())lr.unbind(t)}this.transition_&&($o(Vr),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise((n,s)=>{const i=t.duration??de.sceneTransitionDuration,o=t.color??{...de.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:i,color:o,targetScene:e,options:t,resolve:n,reject:s},Ho(Vr,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;Bo.setLayer(9999),Bo.setDepth(9999),Bo.rect({x:0,y:0},{x:2e4,y:2e4},{r:o.r,g:o.g,b:o.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{reject:t}=this.transition_;this.transition_=null,$o(Vr),t(e)}})().catch(()=>{})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,$o(Vr),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Nr(t);this.scenes_.set(e,n);const s=new jr(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ao)?this.app_.getResource(ao):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Nr(t);this.scenes_.set(e,n);const s=new jr(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ao)?this.app_.getResource(ao):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,ht)){if(this.app_.world.get(e,ht).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())$o(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())lr.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(ao)&&(i.assetServer=this.app_.getResource(ao));const o=await to(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,ht,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Gr(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(ao)?this.app_.getResource(ao):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)Nn.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,Je)){const t=n.get(e,Je);s.sprite=t.color.a,t.color.a=0,n.insert(e,Je,t),i=!0}if(n.has(e,ot)){const t=n.get(e,ot);s.spine=t.color.a,t.color.a=0,n.insert(e,ot,t),i=!0}if(n.has(e,it)){const t=n.get(e,it);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,it,t),i=!0}if(n.has(e,Or)){const t=n.get(e,Or);s.uiRenderer=t.color.a,t.color.a=0,n.insert(e,Or,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,Je)){const t=n.get(e,Je);t.color.a=s.sprite,n.insert(e,Je,t)}if(void 0!==s.spine&&n.has(e,ot)){const t=n.get(e,ot);t.color.a=s.spine,n.insert(e,ot,t)}if(void 0!==s.bitmapText&&n.has(e,it)){const t=n.get(e,it);t.color.a=s.bitmapText,n.insert(e,it,t)}if(void 0!==s.uiRenderer&&n.has(e,Or)){const t=n.get(e,Or);t.color.a=s.uiRenderer,n.insert(e,Or,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Yr=Et(null,"SceneManager");function Gr(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Yr).getSceneStatus(t)&&n._fn(...s)}}}const qr=Mn([kt(Yr),At(Ft)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Kr={name:"SceneManager",build(e){const t=new Xr(e);e.insertResource(Yr,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Yr),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(bn.Startup,n),e.addSystemToSchedule(bn.Last,qr)}};class Jr{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new gn,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=async()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(bn.Last);else{await this.runSchedule(bn.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(bn.FixedPreUpdate),await this.runSchedule(bn.FixedUpdate),await this.runSchedule(bn.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(bn.PreUpdate),await this.runSchedule(bn.Update),await this.runSchedule(bn.PostUpdate),await this.runSchedule(bn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Jt,this.resources_=new It;for(const e of Object.values(bn))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Jr}getPlugin(e){return this.installed_plugins_.find(t=>t instanceof e)}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(bn.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(bn.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}async waitForPhysics(){this.physicsInitPromise_?await this.physicsInitPromise_:console.warn("[ESEngine] No PhysicsPlugin installed, waitForPhysics() is a no-op")}get isPhysicsReady(){return null!=this.physicsModule_}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return $t(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Yr).register(e),this}setInitialScene(e){return this.getResource(Yr).setInitial(e),this}async tick(e){if(this.runner_||(this.runner_=new An(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Ft)||this.resources_.insert(Ft,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_()),await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(bn.Last);else{await this.runSchedule(bn.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(bn.FixedPreUpdate),await this.runSchedule(bn.FixedUpdate),await this.runSchedule(bn.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(bn.PreUpdate),await this.runSchedule(bn.Update),await this.runSchedule(bn.PostUpdate),await this.runSchedule(bn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}async run(){this.running_||(this.running_=!0,this.runner_=new An(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Ft,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),await this.flushStartupSystems_(),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Lo();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Dr,Br,rr,Go,On,Ro];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){console.warn("[App] Shutdown despawn error:",e)}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}async flushStartupSystems_(){const e=this.systems_.get(bn.Startup);0!==e.length&&(this.sortedSystemsCache_.delete(bn.Startup),await this.runSchedule(bn.Startup),e.length=0,this.sortedSystemsCache_.delete(bn.Startup))}async runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{const t=this.runner_.run(e.system);t instanceof Promise&&await t}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(bn[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(Ft);t.delta=e,t.elapsed+=e,t.frameCount++}}function Zr(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Qr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ea(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case Xe.FixedWidth:return o;case Xe.FixedHeight:return r;case Xe.Expand:return Math.max(o,r);case Xe.Shrink:return Math.min(o,r);case Xe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const ta=[];function na(e){if(e<ta.length)return ta[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return ta.push(t),t}function sa(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,ht);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,h=0;if(i.projectionType===Ne.Orthographic){if(h=i.orthoSize,l){h=ea(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=oa(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=aa(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=ca(o.position.x,o.position.y,o.position.z),f=na(c.length);f.entity=e,f.viewProjection.set(ha(a,d)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ia=new Float32Array(16);function oa(e,t,n,s,i,o){const r=ia;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const ra=new Float32Array(16);function aa(e,t,n,s){const i=ra;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const la=new Float32Array(16);function ca(e,t,n){const s=la;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}const ua=new Float32Array(16);function ha(e,t){const n=ua;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const da={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},fa={Simple:0,Sliced:1,Tiled:2,Filled:3},pa={Horizontal:0,Vertical:1},ma={Left:0,Right:1,Bottom:2,Top:3},ga=Ie("Image",{texture:ye,color:{r:1,g:1,b:1,a:1},imageType:fa.Simple,fillMethod:pa.Horizontal,fillOrigin:ma.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),ya=Ve("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}}),_a=Ve("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0});function xa(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,g=p+i.y):(p=h+n.y,g=d+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}let wa=null,ba=null;function va(e,t){switch(e){case da.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case da.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case da.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Sa(e,t){switch(e){case da.RightToLeft:return{anchorMin:{x:1-t,y:.5},anchorMax:{x:1-t,y:.5}};case da.BottomToTop:return{anchorMin:{x:.5,y:t},anchorMax:{x:.5,y:t}};case da.TopToBottom:return{anchorMin:{x:.5,y:1-t},anchorMax:{x:.5,y:1-t}};default:return{anchorMin:{x:t,y:.5},anchorMax:{x:t,y:.5}}}}function Ma(e,t,n,s){switch(e){case da.BottomToTop:case da.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Ca(e,t,n,s){if(!e.has(t,ya))return;const i=e.get(t,ya),o=va(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,ya,i)}function Pa(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}const Ta=1.15,Ea=.75;function Aa(e,t,n,s){return t?n?{r:e.r*Ea,g:e.g*Ea,b:e.b*Ea,a:e.a}:s?{r:Math.min(1,e.r*Ta),g:Math.min(1,e.g*Ta),b:Math.min(1,e.b*Ta),a:e.a}:{...e}:{r:.5*e.r,g:.5*e.g,b:.5*e.b,a:.6*e.a}}function ka(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ra(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(ka(r.charCodeAt(0))&&s.length>0&&ka(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!ka(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Ia(e){let t=1;for(;t<e;)t*=2;return t}function Fa(e,t){let n=0,s=t;for(;e.has(s,nt);){const t=e.get(s,nt).entity;if(!e.valid(t))break;n++,s=t}return n}function Ba(e,t){if(wa&&ba){const e=wa.getUIRectComputedWidth(ba,t);if(e>0)return e}return e.size.x}function Ua(e,t){if(wa&&ba){const e=wa.getUIRectComputedHeight(ba,t);if(e>0)return e}return e.size.y}function za(e,t,n){wa&&ba&&wa.setUIRectSize(ba,e,t,n)}function Wa(e,t,n,s,i,o){if(!e.has(t,Je))return;const r=e.get(t,Je);let a,l;switch(n){case da.BottomToTop:case da.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,Je,r))}function Da(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Ha(e,t){Da(e,t,_a,{enabled:!0,blockRaycast:!0,raycastTarget:!0})}function $a(e,t,n){0!==t&&e.valid(t)&&n(t)}function La(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a}function Oa(e,t,n){if(e.has(t,ga)){const s=e.get(t,ga);La(s.color,n)||(s.color=n,e.insert(t,ga,s))}else if(e.has(t,Je)){const s=e.get(t,Je);La(s.color,n)||(s.color=n,e.insert(t,Je,s))}else if(e.has(t,Or)){const s=e.get(t,Or);La(s.color,n)||(s.color=n,e.insert(t,Or,s))}}function Va(e,t,n){if(e.has(t,ga)){const s=e.get(t,ga);s.enabled!==n&&(s.enabled=n,e.insert(t,ga,s))}else if(e.has(t,Je)){const s=e.get(t,Je);s.enabled!==n&&(s.enabled=n,e.insert(t,Je,s))}else if(e.has(t,Or)){const s=e.get(t,Or);s.enabled!==n&&(s.enabled=n,e.insert(t,Or,s))}}function Na(e,t){return{r:Math.min(1,e.r*t),g:Math.min(1,e.g*t),b:Math.min(1,e.b*t),a:e.a}}function ja(e,t){return{r:e.r,g:e.g,b:e.b,a:t}}class Xa{constructor(){this.map_=new Map}get(e){return this.map_.get(e)}set(e,t){this.map_.set(e,t)}delete(e){this.map_.delete(e)}has(e){return this.map_.has(e)}cleanup(e){for(const[t]of this.map_)e.valid(t)||this.map_.delete(t)}ensureInit(e,t){let n=this.map_.get(e);return n||(n=t(),this.map_.set(e,n)),n}clear(){this.map_.clear()}[Symbol.iterator](){return this.map_[Symbol.iterator]()}}function Ya(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Ga=.1,qa={r:.3,g:.5,b:.8,a:1},Ka={r:.9,g:.9,b:.9,a:1},Ja={r:.95,g:.95,b:.95,a:1},Za={Left:0,Center:1,Right:2},Qa={Top:0,Middle:1,Bottom:2},el={Visible:0,Clip:1,Ellipsis:2},tl=Ie("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Za.Left,verticalAlign:Qa.Top,wordWrap:!0,overflow:el.Visible,lineHeight:1.2});class nl{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(de.textCanvasSize,de.textCanvasSize);const t=this.canvas.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("TextRenderer: failed to create 2D canvas context");this.ctx=t}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ia(this.frameMaxW_)),e.height=Math.max(e.height,Ia(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ia(this.frameMaxW_),e.height=Ia(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Ra(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===el.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Ia(f)),s.height=Math.max(s.height,Ia(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===el.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case Qa.Top:w=u;break;case Qa.Middle:w=u+(p-2*u-x)/2;break;case Qa.Bottom:w=p-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let s;switch(e.align){case Za.Left:s=u;break;case Za.Center:s=f/2;break;case Za.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===el.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),M=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const P=M.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:P,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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Za.Left:return"left";case Za.Center:return"center";case Za.Right:return"right"}}}const sl=Ya({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Ba(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ua(e.uiRect,e.entity):0});function il(e,t){e.has(t,Or)||e.insert(t,Or,{visualType:Lr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class ol{build(e){$e("Text",tl);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new nl(t),s=e.world,i=new Map;e.addSystemToSchedule(bn.PreUpdate,Mn([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,tl));for(const e of i.keys())if(!s.valid(e)||!s.has(e,tl)){if(s.valid(e)&&s.has(e,Or)){const t=s.get(e,Or);t.texture=0,t.visualType=Lr.None,s.insert(e,Or,t)}i.delete(e)}const e=s.getEntitiesWithComponents([tl]);for(const t of e){const e=s.get(t,tl),o=s.has(t,ya)?s.get(t,ya):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!sl.changed(a,r)){if(s.has(t,Or)&&0!==s.get(t,Or).texture)continue}il(s,t);const l=o?{size:{x:Ba(o,t),y:Ua(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Or);u.texture=c.textureHandle,u.visualType=Lr.Image,u.color={r:1,g:1,b:1,a:1},u.uvOffset={x:0,y:0},u.uvScale={x:1,y:1},s.insert(t,Or,u),o&&za(t,c.width,c.height),i.set(t,sl.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const rl=new ol,al=0,ll=Ve("UIMask",{enabled:!0,mode:al});class cl{build(e){$e("UIMask",ll)}}const ul=new cl;function hl(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=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,i-n),h:Math.max(0,o-s)}}function dl(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=s*l-i*a,w=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,M=o*u-r*c,C=h*g-d*m,P=h*y-f*m,T=h*_-p*m,E=d*y-f*g,A=d*_-p*g,k=f*_-p*y;let R=x*k-w*A+b*E+v*T-S*P+M*C;return 0===R||(R=1/R,n[0]=(l*k-c*A+u*E)*R,n[1]=(o*A-i*k-r*E)*R,n[2]=(g*M-y*S+_*v)*R,n[3]=(f*S-d*M-p*v)*R,n[4]=(c*T-a*k-u*P)*R,n[5]=(s*k-o*T+r*P)*R,n[6]=(y*b-m*M-_*w)*R,n[7]=(h*M-f*b+p*w)*R,n[8]=(a*A-l*T+u*C)*R,n[9]=(i*T-s*A-r*C)*R,n[10]=(m*S-g*b+_*x)*R,n[11]=(d*b-h*S-p*x)*R,n[12]=(l*P-a*E-c*C)*R,n[13]=(s*E-i*P+o*C)*R,n[14]=(g*w-m*v-y*x)*R,n[15]=(h*v-d*w+f*x)*R),n}function fl(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function pl(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function ml(e,t){return 2*Math.atan2(e,t)}function gl(e,t,n,s,i,o,r,a,l,c){if(0===l&&1===c)return pl(e,t,n,s,i,o,r,a);const u=ml(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,g=f*h+p*d+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}const yl=Ve("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),_l={Normal:0,Hovered:1,Pressed:2,Disabled:3},xl=Ie("Button",{state:_l.Normal,transition:null});class wl{constructor(){this.events_=[],this.entityTypeHandlers_=new Map,this.globalHandlers_=new Map,this.activeDispatches_=new Set,this.entityValidator_=null}on(e,t,n){if(void 0!==n){const s=e,i=t;let o=this.entityTypeHandlers_.get(s);o||(o=new Map,this.entityTypeHandlers_.set(s,o));let r=o.get(i);r||(r=[],o.set(i,r)),r.push(n);let a=!1;return()=>{if(a)return;a=!0;const e=o.get(i);if(e){const t=e.indexOf(n);-1!==t&&e.splice(t,1)}}}{const n=e,s=t;let i=this.globalHandlers_.get(n);i||(i=[],this.globalHandlers_.set(n,i)),i.push(s);let o=!1;return()=>{if(o)return;o=!0;const e=this.globalHandlers_.get(n);if(e){const t=e.indexOf(s);-1!==t&&e.splice(t,1)}}}}removeAll(e){this.entityTypeHandlers_.delete(e)}setEntityValidator(e){this.entityValidator_=e}emit(e,t,n){const s={entity:e,type:t,target:n??e,currentTarget:e,propagationStopped:!1,stopPropagation(){this.propagationStopped=!0}};this.events_.push(s);const i=`${e}:${t}`;return this.activeDispatches_.has(i)||(this.activeDispatches_.add(i),this.dispatchToHandlers_(s),this.activeDispatches_.delete(i)),s}emitBubbled(e,t,n,s){const i={entity:e,type:t,target:n,currentTarget:e,propagationStopped:!1,stopPropagation(){s.propagationStopped=!0}};this.events_.push(i);const o=`${e}:${t}`;this.activeDispatches_.has(o)||(this.activeDispatches_.add(o),this.dispatchToHandlers_(i),this.activeDispatches_.delete(o))}drain(){if(this.entityValidator_)for(const e of this.entityTypeHandlers_.keys())this.entityValidator_(e)||this.entityTypeHandlers_.delete(e);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)}dispatchToHandlers_(e){const t=this.entityTypeHandlers_.get(e.entity);if(t){const n=t.get(e.type);n&&this.invokeHandlers_([...n],e)}const n=this.globalHandlers_.get(e.type);n&&this.invokeHandlers_([...n],e)}invokeHandlers_(e,t){for(const n of e)try{n(t)}catch(e){console.error(`UIEvent handler error [${t.type}]:`,e)}}}const bl=Et(new wl,"UIEvents"),vl=Et({generation:0},"UILayoutGeneration");class Sl{build(e){$e("UIRect",ya),$e("UIRenderer",Or);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){wa=e,ba=t}(n,s);const i={generation:0};e.insertResource(vl,i);e.addSystemToSchedule(bn.PreUpdate,Mn([At(Bn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.transform_update(s),i.generation++)},{name:"UILayoutSystem"})),e.addSystemToSchedule(bn.PostUpdate,Mn([At(Bn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),i.generation++)},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(bn.PostUpdate,Mn([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ml=new Sl,Cl=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(dl(t,e),n=!1),e)}}();function Pl(e,t,n,s){const i=t.emit(n,s,n);!function(e,t,n){let s=t;for(;e.has(s,nt);){const t=e.get(s,nt).entity;if(!e.valid(t))break;if(n(t))return;s=t}}(e,n,o=>{if(i.propagationStopped)return!0;if(!e.has(o,_a))return!1;const r=e.get(o,_a);return r.enabled&&t.emitBubbled(o,s,n,i),r.blockRaycast})}class Tl{build(e){$e("Interactable",_a),$e("Button",xl);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new wl;i.setEntityValidator(e=>t.valid(e)),e.insertResource(bl,i);let o=null,r=null,a=NaN,l=NaN,c=-1;e.addSystemToSchedule(bn.PreUpdate,Mn([At(Rn),At(Bn),At(vl)],(e,u,h)=>{if(i.drain(),ii()&&!ai())return;const d=t.getEntitiesWithComponents([yl]);for(const e of d){const n=t.get(e,yl);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,yl,n))}if(!u.valid)return;const p=f(),m=e.mouseX*p,g=u.screenH-e.mouseY*p;Cl.update(u.viewProjection);const y=fl(m,g,Cl.getInverse(u.viewProjection),u.vpX,u.vpY,u.vpW,u.vpH);u.worldMouseX=y.x,u.worldMouseY=y.y;const _=e.isMouseButtonDown(0),x=e.isMouseButtonPressed(0),w=e.isMouseButtonReleased(0),b=y.x!==a||y.y!==l,v=h.generation!==c,S=b||v||(x||w);a=y.x,l=y.y,c=h.generation;let M=o;if(S){n.uiHitTest_update(s,y.x,y.y,_,x,w);const e=n.uiHitTest_getHitEntity();M=4294967295===e?null:e}if(null===o||t.valid(o)||(o=null),o!==M){if(null!==o&&t.valid(o)&&t.has(o,yl)){const e=t.get(o,yl);e.hovered=!1,t.insert(o,yl,e),i.emit(o,"hover_exit")}if(null!==M){Da(t,M,yl);const e=t.get(M,yl);e.hovered=!0,t.insert(M,yl,e),i.emit(M,"hover_enter")}o=M}if(x&&null!==M){const e=t.get(M,yl);e.pressed=!0,e.justPressed=!0,t.insert(M,yl,e),r=M,Pl(t,i,M,"press")}if(w&&null!==r){if(t.valid(r)&&t.has(r,yl)){const e=t.get(r,yl);e.pressed=!1,e.justReleased=!0,t.insert(r,yl,e),Pl(t,i,r,"release"),r===o&&Pl(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const u=new Set;e.addSystemToSchedule(bn.Update,Mn([],()=>{for(const e of u)t.valid(e)||u.delete(e);const e=t.getEntitiesWithComponents([xl]);for(const n of e){if(Da(t,n,_a,{enabled:!0}),!t.has(n,yl))continue;const e=t.get(n,yl),s=t.get(n,xl),i=t.get(n,_a),o=!u.has(n),r=s.state;if(i.enabled?e.pressed?s.state=_l.Pressed:e.hovered?s.state=_l.Hovered:s.state=_l.Normal:s.state=_l.Disabled,o&&u.add(n),(o||r!==s.state)&&s.transition){const o=Pa(s.transition,i.enabled,e.pressed,e.hovered);Oa(t,n,o)}else if((o||r!==s.state)&&!s.transition&&t.has(n,ga)){const s=Aa(t.get(n,ga).color,i.enabled,e.pressed,e.hovered);Oa(t,n,s)}}},{name:"ButtonSystem"}))}}const El=new Tl,Al=Ie("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),kl=Ie("Focusable",{tabIndex:0,isFocused:!1});class Rl{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Il=Et(new Rl,"FocusManager");class Fl{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if($e("TextInput",Al),ii()&&!ai())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=t,s=e.world,i=new Map,o=h(de.textCanvasSize,64),r=o.getContext("2d",{willReadFrequently:!0});if(!r)return void console.warn("TextInputPlugin: failed to create 2D canvas context");const a=r;let l=0,c=0,u=!1,d=!0,f=0,p=0;const m=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!m)return;const g=m;function y(){const t=e.getResource(Il);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Al)?n:null}const _=()=>{u||null===y()||S()},x=()=>{u=!0},w=()=>{u=!1,S()},b=t=>{const n=y();if(null===n)return;if("Escape"===t.key)return void M();const i=s.get(n,Al);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(bl).emit(n,"submit"),void M()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,g.selectionStart=o,g.selectionEnd=o,i.dirty=!0,C())},v=()=>{const t=y();if(null!==t){const n=s.get(t,Al);n.focused=!1,n.dirty=!0;e.getResource(Il).blur()}};function S(){const t=y();if(null===t)return;const n=s.get(t,Al);if(n.readOnly)return;let i=g.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),g.value=i),i!==n.value){n.value=i;e.getResource(bl).emit(t,"change")}n.cursorPos=g.selectionStart??i.length,n.dirty=!0,C()}function M(){const t=y();if(null!==t){const e=s.get(t,Al);e.focused=!1,e.dirty=!0}e.getResource(Il).blur(),g.blur()}function C(){d=!0,f=0}g.addEventListener("input",_),g.addEventListener("compositionstart",x),g.addEventListener("compositionend",w),g.addEventListener("keydown",b),g.addEventListener("blur",v),this.cleanupListeners_=()=>{g.removeEventListener("input",_),g.removeEventListener("compositionstart",x),g.removeEventListener("compositionend",w),g.removeEventListener("keydown",b),g.removeEventListener("blur",v),g.remove();const e=n.getResourceManager();for(const t of i.values())e.releaseTexture(t);i.clear(),0!==l&&(n._free(l),l=0,c=0)};let P=null;function T(e,t,r,u){(o.width<r||o.height<u)&&(o.width=Ia(Math.max(o.width,r)),o.height=Ia(Math.max(o.height,u))),a.clearRect(0,0,o.width,o.height);const h=t.backgroundColor;a.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,a.fillRect(0,0,r,u),a.save(),a.beginPath(),a.rect(t.padding,0,r-2*t.padding,u),a.clip(),a.font=`${t.fontSize}px ${t.fontFamily}`,a.textBaseline="top",a.textAlign="left";const f=0===t.value.length,p=f?t.placeholder:t.password?"●".repeat(t.value.length):t.value,m=f?t.placeholderColor:t.color;a.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*t.fontSize),y=t.padding;if(t.multiline){const e=Ra(a,p,r-2*y);let t=y;for(const n of e)a.fillText(n,y,t),t+=g}else{const e=(u-t.fontSize)/2;a.fillText(p,y,e)}if(t.focused&&d){const e=t.password?"●".repeat(t.cursorPos):t.value.substring(0,t.cursorPos);let n,s,i;if(t.multiline){const e=Ra(a,t.value,r-2*y);let o=0,l=0,c=0;for(let n=0;n<e.length;n++){const s=e[n].length;if(o+s>=t.cursorPos){l=n,c=t.cursorPos-o;break}o+=s,n<e.length-1&&o<t.value.length&&"\n"===t.value[o]&&o++,l=n+1,c=0}const u=l<e.length?e[l].substring(0,c):"";n=y+a.measureText(u).width,s=y+l*g,i=g}else n=y+a.measureText(e).width,s=(u-t.fontSize)/2,i=t.fontSize;a.fillStyle=`rgba(${Math.round(255*t.color.r)}, ${Math.round(255*t.color.g)}, ${Math.round(255*t.color.b)}, ${t.color.a})`,a.fillRect(n,s,2,i)}a.restore();const _=a.getImageData(0,0,r,u),x=new Uint8Array(_.data.buffer),w=n.getResourceManager();x.length>c&&(0!==l&&n._free(l),l=n._malloc(x.length),c=x.length),n.HEAPU8.set(x,l);const b=i.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(r,u,l,x.length,1,!0);i.set(e,v);const S=s.get(e,Or);S.texture=v,S.visualType=Lr.Image,S.uvOffset={x:0,y:0},S.uvScale={x:1,y:1},S.color={r:1,g:1,b:1,a:1},S.enabled=!0,s.insert(e,Or,S)}e.addSystemToSchedule(bn.Update,Mn([At(Il)],e=>{const t=s.getEntitiesWithComponents([Al]);for(const e of t)Da(s,e,kl,{tabIndex:0,isFocused:!1}),Da(s,e,_a,{enabled:!0,blockRaycast:!0});const n=y();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Al)){const e=s.get(P,Al);e.focused=!1,e.dirty=!0,g.blur()}null!==n&&function(e){const t=s.get(e,Al);t.readOnly||(t.focused=!0,t.dirty=!0,g.value=t.value,g.selectionStart=t.cursorPos,g.selectionEnd=t.cursorPos,g.focus(),C())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(bn.PreUpdate,Mn([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let t=0===p?0:(e-p)/1e3;p=e,t=Math.min(t,.1);const o=y();if(null!==o&&(f+=t,f>=.5)){f-=.5,d=!d;s.get(o,Al).dirty=!0}const r=n.getResourceManager();for(const[e,t]of i)s.valid(e)&&s.has(e,Al)||(r.releaseTexture(t),i.delete(e));const a=s.getEntitiesWithComponents([Al,ya]);for(const e of a){const t=s.get(e,Al);if(!t.dirty)continue;const n=s.get(e,ya),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(s.has(e,Or)||s.insert(e,Or,{visualType:Lr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),T(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Bl=new Fl,Ul=Ya({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Ba(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ua(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});function zl(e,t){e.has(t,Or)||e.insert(t,Or,{visualType:Lr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Wl{build(e){$e("Image",ga);const t=e.world,n=new Map;e.addSystemToSchedule(bn.PreUpdate,Mn([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,ga)||n.delete(e);const e=t.getEntitiesWithComponents([ga]);for(const s of e){const e=t.get(s,ga),i=t.has(s,ya)?t.get(s,ya):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&t.has(s,Or)&&!Ul.changed(r,o))continue;zl(t,s);const a=t.get(s,Or);if(!e.enabled){a.enabled=!1,t.insert(s,Or,a),n.set(s,Ul.take(o));continue}a.enabled=!0,a.texture=e.texture,a.color={r:e.color.r,g:e.color.g,b:e.color.b,a:e.color.a},a.material=e.material,a.uvOffset={x:0,y:0},a.uvScale={x:1,y:1};if(e.texture!==ye&&0!==e.texture?e.imageType===fa.Sliced?a.visualType=Lr.NineSlice:a.visualType=Lr.Image:a.visualType=Lr.SolidColor,e.imageType===fa.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));i&&Ba(i,s),i&&Ua(i,s),e.fillMethod===pa.Horizontal?(e.fillOrigin===ma.Left||(a.uvOffset={x:1-t,y:0}),a.uvScale={x:t,y:1}):(e.fillOrigin===ma.Bottom||(a.uvOffset={x:0,y:1-t}),a.uvScale={x:1,y:t})}else if(e.imageType===fa.Tiled){const t=i?Ba(i,s):0,n=i?Ua(i,s):0;e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale={x:t/e.tileSize.x,y:n/e.tileSize.y})}t.insert(s,Or,a),n.set(s,Ul.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Dl=new Wl,Hl=Ie("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null,onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1}},{entityFields:["graphicEntity","group"]}),$l=Ie("ToggleGroup",{allowSwitchOff:!1});function Ll(e,t,n){if(!e.has(t,Or))return;const s=e.get(t,Or);s.color.r===n.r&&s.color.g===n.g&&s.color.b===n.b&&s.color.a===n.a||(s.color=n,e.insert(t,Or,s))}function Ol(e,t,n){if(!e.has(t,Or))return;const s=e.get(t,Or);s.enabled!==n&&(s.enabled=n,e.insert(t,Or,s))}class Vl{build(e){$e("Toggle",Hl),$e("ToggleGroup",$l);const t=e.world,n=new Set;e.addSystemToSchedule(bn.Update,Mn([At(bl)],e=>{const s=t.getEntitiesWithComponents([Hl]);if(!ii()||ai()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Hl);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Hl,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Hl);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Da(t,n,_a,{enabled:!0}),!t.has(n,yl))continue;const s=t.get(n,yl),i=t.get(n,Hl),r=t.get(n,_a);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,$l);if(i.isOn&&r){if(!t.get(s,$l).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Hl,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Hl);i.isOn&&(i.isOn=!1,t.insert(s,Hl,i),e.emit(s,"change"))}}e.emit(n,"change")}let a;if(i.transition)a=Pa(i.transition,r.enabled,s.pressed,s.hovered);else{a=Aa(i.isOn?i.onColor:i.offColor,r.enabled,s.pressed,s.hovered)}Ll(t,n,a)}}for(const e of s){const n=t.get(e,Hl);$a(t,n.graphicEntity,e=>{Ol(t,e,n.isOn)})}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Nl=new Vl,jl=da,Xl=Ie("ProgressBar",{value:0,fillEntity:0,direction:da.LeftToRight},{entityFields:["fillEntity"]});class Yl{build(e){$e("ProgressBar",Xl);const t=e.world;e.addSystemToSchedule(bn.PreUpdate,Mn([],()=>{const e=t.getEntitiesWithComponents([Xl,ya]);for(const n of e){const e=t.get(n,Xl),s=Math.max(0,Math.min(1,e.value));$a(t,e.fillEntity,n=>{Ca(t,n,e.direction,s)})}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Gl=new Yl,ql=Ie("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Kl=Ie("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});function Jl(e,t,n,s){if(!e.has(t,nt))return{x:n,y:s};const i=e.get(t,nt).entity;if(!e.valid(i)||!e.has(i,Ge))return{x:n,y:s};const o=e.get(i,Ge),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=ml(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}class Zl{build(e){$e("Draggable",ql),$e("DragState",Kl);const t=e.world,n=e.getResource(bl);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(bn.PreUpdate,Mn([At(Rn),At(Bn)],(e,r)=>{if(ii()&&!ai())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ql,yl]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,ql).enabled)continue;if(t.get(s,yl).hovered){let e=0;t.has(s,Je)&&(e=t.get(s,Je).layer);const i=Fa(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,Kl)||t.insert(n,Kl);const e=t.get(n,Kl),o=t.get(n,Ge);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Kl)){t.get(s,Kl).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,ql);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,Kl).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Kl))return void(o=null);const s=t.get(o,Kl),i=t.get(o,ql),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,ya)){const e=t.get(o,ya),n=Jl(t,o,s.deltaWorld.x,s.deltaWorld.y);e.offsetMin.x+=n.x,e.offsetMin.y+=n.y,t.insert(o,ya,e)}else if(t.has(o,Ge)){const e=Jl(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,Ge);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,Ge,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const Ql=new Zl,ec=Ie("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1},{entityFields:["contentEntity"]});function tc(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function nc(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class sc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){$e("ScrollView",ec);const t=e.world,n=new Xa,s={x:0,y:0};e.addSystemToSchedule(bn.PostUpdate,Mn([At(Rn),At(Bn),At(Ft)],(e,i,o)=>{const r=ii()&&!ai(),a=Math.min(o.delta,.05);n.cleanup(t),i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([ec,ya]);for(const o of l){Da(t,o,ll,{enabled:!0,mode:al});const l=t.get(o,ec),c=t.get(o,ya),u=n.ensureInit(o,()=>({isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN})),h=Ba(c,o),d=Ua(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,st)){const e=t.get(l.contentEntity,st).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,Ge))continue;const e=t.get(r,Ge);let a=0,l=0,c=.5,u=.5;if(t.has(r,ya)){const e=t.get(r,ya);a=Ba(e,r)||e.size.x,l=Ua(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Je)){const e=t.get(r,Je);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<n&&(n=h),d>s&&(s=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Da(t,o,_a,{enabled:!0,blockRaycast:!0});const n=t.has(o,yl)?t.get(o,yl):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=tc(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=tc(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=tc(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=tc(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=nc(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Ga&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Ga?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=nc(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Ga&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Ga?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}$a(t,l.contentEntity,e=>{if(!t.has(e,Ge))return;const n=t.get(e,Ge),s=n.position.x,i=n.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(i-u.lastAppliedY)>.01)&&(u.contentBaseY=i),n.position.x=u.contentBaseX-l.scrollX,n.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=n.position.x,u.lastAppliedY=n.position.y,t.insert(e,Ge,n)})}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{n.clear()}}}const ic=new sc,oc=da,rc=Ie("Slider",{value:0,minValue:0,maxValue:1,direction:da.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1},{entityFields:["fillEntity","handleEntity"]});function ac(e,t,n,s,i,o){const r=Ba(s,i)*n.worldScale.x,a=Ua(s,i)*n.worldScale.y,l=ml(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-n.worldPosition.x,d=t-n.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case da.LeftToRight:return r>0?(f-m)/r:0;case da.RightToLeft:return r>0?1-(f-m)/r:0;case da.BottomToTop:return a>0?(p-g)/a:0;case da.TopToBottom:return a>0?1-(p-g)/a:0}}function lc(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case da.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=.5,e.anchorMax.x=n,e.anchorMax.y=.5;break;case da.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=.5,e.anchorMax.x=1-n,e.anchorMax.y=.5;break;case da.BottomToTop:e.anchorMin.x=.5,e.anchorMin.y=n,e.anchorMax.x=.5,e.anchorMax.y=n;break;case da.TopToBottom:e.anchorMin.x=.5,e.anchorMin.y=1-n,e.anchorMax.x=.5,e.anchorMax.y=1-n}}class cc{build(e){$e("Slider",rc);const t=e.world;e.addSystemToSchedule(bn.PreUpdate,Mn([At(Rn),At(Bn),At(bl)],(e,n,s)=>{if(!n.valid)return;const i=t.getEntitiesWithComponents([rc,ya]);for(const o of i){const i=t.get(o,rc),r=t.get(o,ya);if(!ii()||ai()){if(t.has(o,Ge)){Da(t,o,_a,{enabled:!0,blockRaycast:!0}),$a(t,i.handleEntity,e=>{Da(t,e,_a,{enabled:!0,blockRaycast:!1})});const a=t.get(o,Ge);let l=!1;if(t.has(o,yl)&&(l=t.get(o,yl).pressed),$a(t,i.handleEntity,e=>{!l&&t.has(e,yl)&&(l=t.get(e,yl).pressed)}),l&&e.isMouseButtonDown(0)){let e=ac(n.worldMouseX,n.worldMouseY,a,r,o,i.direction);e=Math.max(0,Math.min(1,e));let l=i.minValue+e*(i.maxValue-i.minValue);i.wholeNumbers&&(l=Math.round(l));const c=i.value;i.value=Math.max(i.minValue,Math.min(i.maxValue,l)),t.insert(o,rc,i),i.value!==c&&s.emit(o,"change")}}}const a=i.maxValue-i.minValue,l=a>0?(i.value-i.minValue)/a:0;$a(t,i.fillEntity,e=>{Ca(t,e,i.direction,l)}),$a(t,i.handleEntity,e=>{if(!t.has(e,ya))return;const n=t.get(e,ya);lc(n,i.direction,l),t.insert(e,ya,n)})}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const uc=new cc;class hc{build(e){$e("Focusable",kl);const t=e.world,n=new Rl;e.insertResource(Il,n),e.addSystemToSchedule(bn.Update,Mn([At(Rn),At(bl)],(e,s)=>{if(ii()&&!ai())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([kl]);for(const e of i){if(!t.has(e,yl))continue;t.get(e,yl).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,_a)){if(!t.get(n,_a).enabled)continue}const s=t.get(n,kl);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,kl)){t.get(i,kl).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,kl).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const dc=new hc,fc=Ie("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function pc(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class mc{build(e){$e("SafeArea",fc);const t=e.world;let n=pc(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=pc(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=pc(),s=!0});e.addSystemToSchedule(bn.PreUpdate,Mn([At(Bn)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([fc,ya]);for(const e of u){const s=t.get(e,fc),i=t.get(e,ya),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,ya,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const gc=new mc,yc=Ie("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let _c=null;function xc(e,t){if(!_c)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=_c.get(e);n?n.renderer=t:_c.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class wc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null),_c=null}build(e){$e("ListView",yc);const t=e.world,n=new Map;_c=n,e.addSystemToSchedule(bn.PostUpdate,Mn([At(Rn)],e=>{const s=ii()&&!ai();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([yc,ya]);for(const o of i){Da(t,o,_a,{enabled:!0,blockRaycast:!0}),Da(t,o,ll,{enabled:!0,mode:al});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,yc),a=t.get(o,ya),l=Ua(a,o),c=Ba(a,o);if(!s){const n=t.has(o,yl)?t.get(o,yl):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<d;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,ut,{value:`ListItem_${e}`}),t.insert(n,ya,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,Ge)){const s=t.get(n,Ge);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,Ge,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{for(const[,e]of n)for(const n of e.itemEntities.values())t.valid(n)&&t.despawn(n);n.clear()}}}const bc=new wc,vc=Ie("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0},{entityFields:["listEntity","labelEntity"]});class Sc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){$e("Dropdown",vc);const t=e.world,n=new Map,s=new Set;function i(e){$a(t,e,e=>{if(!t.has(e,Ge))return;const n=t.get(e,Ge);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,Ge,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})})}function o(e){if(t.has(e,Or)){const n=t.get(e,Or);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Oa(t,e,{...Ka})}else if(t.has(e,Je)){const n=t.get(e,Je);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Oa(t,e,{...Ka})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;h(i,!0),u(s);let o=0;if(t.has(e,ya)){const n=t.get(e,ya);o=Ba(n,e)||n.size.x}else if(t.has(e,Je)){o=t.get(e,Je).size.x}s.ddWidth=o;const r=30*n.options.length;t.insert(i,ya,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:r},pivot:{x:.5,y:1}}),t.insert(i,Or,{visualType:Lr.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn();t.insert(r,ut,{value:`Option_${e}`}),t.insert(r,ya,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:30*-e},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:1}}),t.insert(r,Ge,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,Or,{visualType:Lr.SolidColor,texture:0,color:{...Ja},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),t.insert(r,_a,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const a=t.spawn();t.insert(a,Ge,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(a,tl,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Za.Left,verticalAlign:Qa.Middle,wordWrap:!1,overflow:el.Clip,lineHeight:1.2}),t.insert(a,ya,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:.5}}),t.setParent(a,r),s.textEntities.push(a)}d(s)}function a(e,t,n){t.isOpen=!1,u(n),h(t.listEntity,!1)}function l(e,t,n,s,i){t.selectedIndex=s,a(0,t,n),i.emit(e,"change")}function c(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,tl))return;const s=t.get(n,tl);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,tl,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function u(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function h(e,n){$a(t,e,e=>{t.has(e,_a)&&t.insert(e,_a,{enabled:n,blockRaycast:!0,raycastTarget:!0}),Va(t,e,n)})}function d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s))continue;const i=n===e.highlightIndex?{...qa}:{...Ja};Oa(t,s,i)}}function f(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,yl))continue;if(t.get(n,yl).hovered)return!0}return!1}e.addSystemToSchedule(bn.Update,Mn([At(Rn),At(bl)],(e,p)=>{for(const[e,i]of n)t.valid(e)||(u(i),n.delete(e),s.delete(e));const m=ii()&&!ai(),g=t.getEntitiesWithComponents([vc]);for(const u of g){const g=t.get(u,vc);let y=n.get(u);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(u,y)),i(g.listEntity),s.has(u)||(o(u),s.add(u)),g.isOpen||h(g.listEntity,!1),c(g),m)continue;Da(t,u,_a,{enabled:!0,blockRaycast:!0});const _=t.has(u,yl)?t.get(u,yl):null;if(_?.justPressed&&(g.isOpen?a(u,g,y):r(u,g,y)),g.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,yl))continue;if(t.get(n,yl).justPressed){l(u,g,y,e,p);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,yl))continue;if(t.get(s,yl).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,d(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=g.options.length-1?y.highlightIndex=0:y.highlightIndex++,d(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=g.options.length-1:y.highlightIndex--,d(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?l(u,g,y,y.highlightIndex,p):e.isKeyPressed("Escape")&&a(u,g,y),e.isMouseButtonPressed(0)&&(_?.hovered||f(y)||a(u,g,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]}),this.cleanup_=()=>{for(const[,e]of n)u(e);n.clear(),s.clear()}}}const Mc=new Sc,Cc=Ve("LayoutGroup",{direction:0,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:0,reverseOrder:!1});class Pc{build(e){$e("LayoutGroup",Cc)}}const Tc=new Pc,Ec=0,Ac=1,kc=0,Rc=1,Ic=0,Fc=0,Bc=3,Uc=Ve("FlexContainer",{direction:Ec,wrap:kc,justifyContent:Ic,alignItems:Bc,alignContent:0,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0}}),zc=Ve("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,alignSelf:0,margin:{left:0,top:0,right:0,bottom:0},minWidth:-1,minHeight:-1,maxWidth:-1,maxHeight:-1,widthPercent:-1,heightPercent:-1});class Wc{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(bn.PostUpdate,Mn([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Dc=new Wc,Hc={primary:{r:.25,g:.56,b:.96,a:1},secondary:{r:.4,g:.4,b:.4,a:1},background:{r:.08,g:.08,b:.08,a:1},surface:{r:.14,g:.14,b:.14,a:1},error:{r:.9,g:.2,b:.2,a:1},text:{r:.93,g:.93,b:.93,a:1},textSecondary:{r:.6,g:.6,b:.6,a:1},border:{r:.3,g:.3,b:.3,a:1},fontFamily:"Arial",fontSize:{xs:10,sm:12,md:14,lg:18,xl:24},spacing:{xs:4,sm:8,md:12,lg:16,xl:24},button:{height:36,color:{r:.25,g:.25,b:.25,a:1},textColor:{r:.93,g:.93,b:.93,a:1},transition:{normalColor:{r:.25,g:.25,b:.25,a:1},hoveredColor:{r:.3,g:.3,b:.3,a:1},pressedColor:{r:.18,g:.18,b:.18,a:1},disabledColor:{r:.15,g:.15,b:.15,a:.6}}},slider:{trackHeight:16,trackColor:{r:.15,g:.15,b:.15,a:1},fillColor:{r:.25,g:.56,b:.96,a:1},handleSize:24,handleColor:{r:1,g:1,b:1,a:1}},toggle:{size:{x:24,y:24},onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1},checkColor:{r:1,g:1,b:1,a:1}},input:{height:36,backgroundColor:{r:.15,g:.15,b:.15,a:1},textColor:{r:1,g:1,b:1,a:1},placeholderColor:{r:.6,g:.6,b:.6,a:1},fontSize:16,padding:6},dropdown:{height:32,backgroundColor:{r:.2,g:.2,b:.2,a:1},itemHeight:28},panel:{backgroundColor:{r:.14,g:.14,b:.14,a:1},padding:12},scrollView:{backgroundColor:{r:.1,g:.1,b:.1,a:1}}},$c=Et(null,"UITheme");let Lc=null;function Oc(e){e.hasResource($c)&&(Lc=e.getResource($c))}function Vc(){return Lc??Hc}function Nc(e,t){const n=e.spawn();if(t.name&&e.insert(n,ut,{value:t.name}),e.insert(n,Ge,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},...t.transform}),t.rect&&e.insert(n,ya,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:0,y:0},pivot:{x:.5,y:.5},...t.rect}),t.renderer&&e.insert(n,Or,{visualType:Lr.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0,...t.renderer}),t.interactable&&e.insert(n,_a,{enabled:!0,blockRaycast:!0,raycastTarget:!0,...t.interactable}),t.text){const s=Vc();e.insert(n,tl,{content:"",fontFamily:s.fontFamily,fontSize:s.fontSize.md,color:{r:1,g:1,b:1,a:1},align:Za.Left,verticalAlign:Qa.Top,wordWrap:!1,overflow:0,lineHeight:1.2,...t.text})}if(t.image&&e.insert(n,ga,{...ga._default,...t.image}),t.flex&&e.insert(n,Uc,{direction:Ec,wrap:kc,justifyContent:Ic,alignItems:Bc,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0},...t.flex}),t.flexItem&&e.insert(n,zc,{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,...t.flexItem}),t.mask&&e.insert(n,ll,{enabled:!0,mode:al,...t.mask}),t.components)for(const[s,i]of t.components)e.insert(n,s,i);return t.parent&&e.setParent(n,t.parent),n}function jc(e,t={}){const n=Vc(),{text:s="Button",fontSize:i=n.fontSize.md,size:o={x:120,y:n.button.height},color:r=n.button.color,textColor:a=n.button.textColor,transition:l=null,parent:c}=t,u=Nc(e,{name:"ButtonLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:s,fontSize:i,color:a,align:Za.Center,verticalAlign:Qa.Middle}}),h=Nc(e,{name:"Button",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Lr.SolidColor,color:r},interactable:{enabled:!0},components:[[xl,{state:0,transition:l}]]});if(e.setParent(u,h),t.events){if(t.onClick){const e=t.onClick;t.events.on(h,"click",()=>e(h))}if(t.onHover){const e=t.onHover;t.events.on(h,"hover_enter",()=>e(h))}}return h}function Xc(e,t={}){const n=Vc(),{value:s=0,minValue:i=0,maxValue:o=1,direction:r=da.LeftToRight,size:a={x:200,y:n.slider.trackHeight},trackColor:l=n.slider.trackColor,fillColor:c=n.slider.fillColor,handleSize:u={x:n.slider.handleSize,y:n.slider.handleSize},handleColor:h=n.slider.handleColor,wholeNumbers:d=!1,parent:f}=t,p=Nc(e,{name:"SliderFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Lr.SolidColor,color:c}}),m=Nc(e,{name:"SliderHandle",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:u},renderer:{visualType:Lr.SolidColor,color:h},interactable:{enabled:!0,blockRaycast:!0},components:[[ql,{enabled:!0,dragThreshold:5,lockX:!1,lockY:!0}]]}),g=Nc(e,{name:"Slider",parent:f,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Lr.SolidColor,color:l},interactable:{enabled:!0,blockRaycast:!0},components:[[rc,{value:s,minValue:i,maxValue:o,direction:r,wholeNumbers:d,fillEntity:p,handleEntity:m}]]});if(e.setParent(p,g),e.setParent(m,g),t.onChange&&t.events){const n=t.onChange;t.events.on(g,"change",()=>{const t=e.get(g,rc);n(t.value,g)})}return g}function Yc(e,t={}){const n=Vc(),{isOn:s=!0,size:i=n.toggle.size,onColor:o=n.toggle.onColor,offColor:r=n.toggle.offColor,checkSize:a={x:.58*n.toggle.size.x,y:.58*n.toggle.size.y},checkColor:l=n.toggle.checkColor,group:c=0,transition:u=null,label:h,parent:d}=t,f=Nc(e,{name:"ToggleCheck",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Lr.SolidColor,color:l}}),p=Nc(e,{name:"Toggle",parent:d,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Lr.SolidColor,color:s?o:r},interactable:{enabled:!0},components:[[Hl,{isOn:s,graphicEntity:f,group:c,transition:u,onColor:o,offColor:r}]]});if(e.setParent(f,p),h&&Nc(e,{name:"ToggleLabel",parent:p,rect:{anchorMin:{x:1,y:0},anchorMax:{x:1,y:1},offsetMin:{x:8,y:0},size:{x:100,y:0}},text:{content:h,fontSize:n.fontSize.md,align:Za.Left,verticalAlign:Qa.Middle}}),t.onChange&&t.events){const n=t.onChange;t.events.on(p,"change",()=>{const t=e.get(p,Hl);n(t.isOn,p)})}return p}function Gc(e,t={}){const n=Vc(),{value:s=0,size:i={x:200,y:n.slider.trackHeight},direction:o=da.LeftToRight,trackColor:r=n.slider.trackColor,fillColor:a=n.primary,parent:l}=t,c=Nc(e,{name:"ProgressFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Lr.SolidColor,color:a}}),u=Nc(e,{name:"ProgressBar",parent:l,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Lr.SolidColor,color:r},components:[[Xl,{value:s,fillEntity:c,direction:o}]]});return e.setParent(c,u),u}function qc(e,t={}){const n=Vc(),{size:s={x:300,y:400},contentSize:i={x:300,y:800},horizontal:o=!1,vertical:r=!0,elastic:a=!0,mask:l=!0,parent:c}=t,u=Nc(e,{name:"ScrollContent",rect:{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},size:{x:i.x,y:i.y},pivot:{x:.5,y:1}}}),h=Nc(e,{name:"ScrollView",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:s},renderer:{visualType:Lr.SolidColor,color:n.scrollView.backgroundColor},mask:l?{mode:al,enabled:!0}:void 0,components:[[ec,{contentEntity:u,horizontalEnabled:o,verticalEnabled:r,contentWidth:i.x,contentHeight:i.y,elastic:a,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,wheelSensitivity:.1}]]});return e.setParent(u,h),h}function Kc(e,t={}){const n=Vc(),{placeholder:s="",value:i="",size:o={x:200,y:n.input.height},fontSize:r=n.input.fontSize,backgroundColor:a=n.input.backgroundColor,textColor:l=n.input.textColor,maxLength:c=0,multiline:u=!1,password:h=!1,parent:d}=t,f=Nc(e,{name:"TextInput",parent:d,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Lr.SolidColor,color:a},interactable:{enabled:!0},components:[[Al,{value:i,placeholder:s,fontSize:r,fontFamily:n.fontFamily,color:l,backgroundColor:a,placeholderColor:n.input.placeholderColor,padding:n.input.padding,maxLength:c,multiline:u,password:h,readOnly:!1,focused:!1,cursorPos:i.length,dirty:!0}],[kl,{tabIndex:0,isFocused:!1}]]});if(t.events){if(t.onChange){const n=t.onChange;t.events.on(f,"change",()=>{const t=e.get(f,Al);n(t.value,f)})}if(t.onSubmit){const n=t.onSubmit;t.events.on(f,"submit",()=>{const t=e.get(f,Al);n(t.value,f)})}}return f}function Jc(e,t){const n=Vc(),{options:s,selectedIndex:i=-1,size:o={x:160,y:n.dropdown.height},fontSize:r=n.fontSize.md,parent:a}=t,l=Nc(e,{name:"DropdownLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:(i>=0?s[i]:s[0])??"",fontSize:r,align:Za.Left,verticalAlign:Qa.Middle}}),c=Nc(e,{name:"DropdownList",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},size:{x:o.x,y:Math.min(s.length*n.dropdown.itemHeight,200)},pivot:{x:.5,y:1}},renderer:{visualType:Lr.SolidColor,color:n.surface},mask:{mode:al,enabled:!0}}),u=Nc(e,{name:"Dropdown",parent:a,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Lr.SolidColor,color:n.dropdown.backgroundColor},interactable:{enabled:!0},components:[[vc,{options:s,selectedIndex:i,isOpen:!1,listEntity:c,labelEntity:l}]]});if(e.setParent(l,u),e.setParent(c,u),t.onChange&&t.events){const n=t.onChange;t.events.on(u,"change",()=>{const t=e.get(u,vc);n(t.selectedIndex,u)})}return u}function Zc(e,t){const n=Vc();return Nc(e,{name:"Label",parent:t.parent,rect:t.size?{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size}:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:t.text,fontSize:t.fontSize??n.fontSize.md,color:t.color??n.text,align:t.align??Za.Left,verticalAlign:t.verticalAlign??Qa.Middle}})}function Qc(e,t={}){const n=Vc();return Nc(e,{name:"Panel",parent:t.parent,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size??{x:300,y:200}},renderer:{visualType:Lr.SolidColor,color:t.color??n.panel.backgroundColor}})}function eu(e,t={}){return Nc(e,{name:"FlexRow",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:Ec,wrap:t.wrap?Rc:kc,justifyContent:t.justifyContent??Ic,alignItems:t.alignItems??Fc,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}function tu(e,t={}){return Nc(e,{name:"FlexColumn",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:Ac,wrap:t.wrap?Rc:kc,justifyContent:t.justifyContent??Ic,alignItems:t.alignItems??Fc,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}const nu={button:jc,slider:Xc,toggle:Yc,textInput:Kc,dropdown:Jc,progressBar:Gc,label:Zc,panel:Qc,flexRow:eu,flexColumn:tu,scrollView:qc};const su={spawn:Nc,destroy:function e(t,n){if(t.valid(n)){if(t.has(n,st)){const s=[...t.get(n,st).entities];for(const n of s)e(t,n)}t.despawn(n)}},build:function e(t,n,s){let i,o;if("element"===n.type)i=Nc(t,{...n,parent:s}),o=i;else{if(i=(0,nu[n.type])(t,{...n.options??{},parent:s}),"scrollView"===n.type){o=t.get(i,ec).contentEntity}else o=i}const r=n.children;if(r&&o)for(const n of r)e(t,n,o);return n.ref&&n.ref(i),i},label:Zc,panel:Qc,button:jc,slider:Xc,toggle:Yc,scrollView:qc,textInput:Kc,dropdown:Jc,progressBar:Gc,flexRow:eu,flexColumn:tu};async function iu(e,t,n){const s=e.getResource(Yr);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}class ou{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let s,i;if("string"==typeof e){const t=(new TextEncoder).encode(e);i=t.length,s=this.raw_._malloc(i+1),this.raw_.HEAPU8.set(t,s),this.raw_.HEAPU8[s+i]=0}else i=e.length,s=this.raw_._malloc(i),this.raw_.HEAPU8.set(e,s);const o=this.api_.loadSkeleton(s,i,t,t.length,n);return this.raw_._free(s),o}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,s,i){this.api_.setAtlasPageTexture(e,t,n,s,i)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,s=0){return!!this.api_.playAnimation(e,t,n,s)}addAnimation(e,t,n=!0,s=0,i=0){return!!this.api_.addAnimation(e,t,n,s,i)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse animations JSON",e),[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse skins JSON",e),[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,s))return this.raw_._free(n),this.raw_._free(s),null;const i=this.raw_.HEAPF32[n>>2],o=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:i,y:o}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,s=t>>2,i={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(t),i}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],s=this.raw_._malloc(8),i=s,o=s+4;for(let s=0;s<t;s++){const t=this.api_.getMeshBatchVertexCount(e,s),r=this.api_.getMeshBatchIndexCount(e,s);if(t<=0||r<=0)continue;const a=8*t*4,l=2*r,c=this.raw_._malloc(a),u=this.raw_._malloc(l);this.api_.getMeshBatchData(e,s,c,u,i,o);const h=new Float32Array(this.raw_.HEAPF32.buffer,c,8*t),d=new Uint16Array(this.raw_.HEAPU8.buffer,u,r);n.push({vertices:new Float32Array(h),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[i>>2],blendMode:this.raw_.HEAPU32[o>>2]}),this.raw_._free(c),this.raw_._free(u)}return this.raw_._free(s),n}setDefaultMix(e,t){this.api_.setDefaultMix(e,t)}setMixDuration(e,t,n,s){this.api_.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){this.api_.setTrackAlpha(e,t,n)}setAttachment(e,t,n){return!!this.api_.setAttachment(e,t,n)}setIKTarget(e,t,n,s,i){return!!this.api_.setIKTarget(e,t,n,s,i)}setSlotColor(e,t,n,s,i,o){return!!this.api_.setSlotColor(e,t,n,s,i,o)}enableEvents(e){this.api_.enableEvents(e)}collectEvents(e){const t=this.api_.getEventCount(e);if(0===t)return[];const n=this.api_.getEventBuffer(),s=this.raw_.HEAPF32,i=n>>2,o=[];for(let e=0;e<t;e++){const t=i+4*e;o.push({type:s[t],track:s[t+1],floatValue:s[t+2],intValue:s[t+3]})}return this.api_.clearEvents(),o}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(n)}off(e,t,n){const s=this.listeners_.get(e);if(!s)return;const i=s.get(t);i&&i.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}class ru{constructor(e){this.entities_=new Map,this.cachedFrame_=-1,this.cachedEntries_=[],this.controller_=e}get controller(){return this.controller_}get entityCount(){return this.entities_.size}loadEntity(e,t,n,s,i){const o=this.controller_.loadSkeleton(t,n,i);if(o<0)return console.error(`[ModuleBackend] Failed to load skeleton: ${this.controller_.getLastError()}`),!1;const r=this.controller_.getAtlasPageCount(o);for(let e=0;e<r;e++){const t=this.controller_.getAtlasPageTextureName(o,e),n=s.get(t);n&&this.controller_.setAtlasPageTexture(o,e,n.glId,n.w,n.h)}const a=this.controller_.createInstance(o);return this.entities_.set(e,{skelHandle:o,instanceId:a,skeletonScale:1,flipX:!1,flipY:!1,layer:0}),!0}setEntityProps(e,t){const n=this.entities_.get(e);n&&(void 0!==t.skeletonScale&&(n.skeletonScale=t.skeletonScale),void 0!==t.flipX&&(n.flipX=t.flipX),void 0!==t.flipY&&(n.flipY=t.flipY),void 0!==t.layer&&(n.layer=t.layer))}setAnimation(e,t,n){const s=this.entities_.get(e);s&&this.controller_.play(s.instanceId,t,n)}setSkin(e,t){const n=this.entities_.get(e);n&&this.controller_.setSkin(n.instanceId,t)}getBounds(e){const t=this.entities_.get(e);return t?this.controller_.getBounds(t.instanceId):null}getAnimations(e){const t=this.entities_.get(e);return t?this.controller_.getAnimations(t.instanceId):[]}getSkins(e){const t=this.entities_.get(e);return t?this.controller_.getSkins(t.instanceId):[]}setDefaultMix(e,t){const n=this.entities_.get(e);n&&this.controller_.setDefaultMix(n.skelHandle,t)}setMixDuration(e,t,n,s){const i=this.entities_.get(e);i&&this.controller_.setMixDuration(i.skelHandle,t,n,s)}setTrackAlpha(e,t,n){const s=this.entities_.get(e);s&&this.controller_.setTrackAlpha(s.instanceId,t,n)}setAttachment(e,t,n){const s=this.entities_.get(e);return!!s&&this.controller_.setAttachment(s.instanceId,t,n)}setIKTarget(e,t,n,s,i){const o=this.entities_.get(e);return!!o&&this.controller_.setIKTarget(o.instanceId,t,n,s,i)}setSlotColor(e,t,n,s,i,o){const r=this.entities_.get(e);return!!r&&this.controller_.setSlotColor(r.instanceId,t,n,s,i,o)}enableEvents(e){const t=this.entities_.get(e);t&&this.controller_.enableEvents(t.instanceId)}updateAll(e){for(const t of this.entities_.values())this.controller_.update(t.instanceId,e)}extractAndSubmitMeshes(e,t,n=-1){const s=e.renderer_submitSpineBatchByEntity;if(!s)return;if(this.cachedFrame_!==n){this.cachedEntries_.length=0;for(const[e,t]of this.entities_){const n=this.controller_.extractMeshBatches(t.instanceId);for(const s of n)0!==s.vertices.length&&0!==s.indices.length&&this.cachedEntries_.push({vertices:s.vertices,indices:s.indices,textureId:s.textureId,blendMode:s.blendMode,entity:e,info:t})}this.cachedFrame_=n}if(0===this.cachedEntries_.length)return;let i=0,o=0;for(const e of this.cachedEntries_)i+=e.vertices.byteLength,o+=e.indices.byteLength;const r=e._malloc(i),a=e._malloc(o);let l=0,c=0;for(const n of this.cachedEntries_){const i=r+l,o=a+c;e.HEAPF32.set(n.vertices,i>>2),new Uint16Array(e.HEAPU8.buffer,o,n.indices.length).set(n.indices),s.call(e,t,i,n.vertices.length/8,o,n.indices.length,n.textureId,n.blendMode,n.entity,n.info.skeletonScale,n.info.flipX,n.info.flipY,n.info.layer,0),l+=n.vertices.byteLength,c+=n.indices.byteLength}e._free(r),e._free(a)}removeEntity(e){const t=this.entities_.get(e);t&&(this.controller_.destroyInstance(t.instanceId),this.controller_.unloadSkeleton(t.skelHandle),this.entities_.delete(e))}shutdown(){for(const e of this.entities_.values())this.controller_.destroyInstance(e.instanceId),this.controller_.unloadSkeleton(e.skelHandle);this.entities_.clear()}}class au{constructor(e,t){this.backends_=new Map,this.loadingBackends_=new Map,this.entityVersions_=new Map,this.coreModule_=e,this.factories_=t}static detectVersion(e){const t=function(e){if(e.length<10)return null;let t=8;const{value:n,bytesRead:s}=lu(e,t);if(t+=s,n<=1||t+n-1>e.length)return null;const i=(new TextDecoder).decode(e.subarray(t,t+n-1));return i.startsWith("4.2")?"4.2":i.startsWith("4.1")?"4.1":null}(e);return t||function(e){if(e.length<4)return null;let t=0;const{value:n,bytesRead:s}=lu(e,t);t+=s,n>0&&(t+=n-1);if(t>=e.length)return null;const{value:i,bytesRead:o}=lu(e,t);if(t+=o,i<=1||t+i-1>e.length)return null;const r=(new TextDecoder).decode(e.subarray(t,t+i-1));return r.startsWith("3.")?"3.8":null}(e)}static detectVersionJson(e){const t=e.match(/"spine"\s*:\s*"(\d+\.\d+)/);return t?t[1].startsWith("4.2")?"4.2":t[1].startsWith("4.1")?"4.1":t[1].startsWith("3.")?"3.8":null:null}async loadEntity(e,t,n,s,i){const o="string"==typeof t?au.detectVersionJson(t):au.detectVersion(t);if(!o)return null;if("4.2"===o&&!this.factories_.has("4.2"))return this.entityVersions_.set(e,"4.2"),"4.2";this.coreModule_.spine_setNeedsReload?.(i,e,!1);const r=await this.ensureBackend(o);if(!r)return console.error(`[SpineManager] Failed to create backend for version ${o}`),null;const a=t instanceof Uint8Array;return r.loadEntity(e,t,n,s,a)?(this.entityVersions_.set(e,o),o):(console.error(`[SpineManager] Failed to load entity ${e} into backend ${o}`),null)}updateAnimations(e){for(const t of this.backends_.values())t.updateAll(e)}submitMeshes(e,t=-1){for(const n of this.backends_.values())n.extractAndSubmitMeshes(this.coreModule_,e,t)}removeEntity(e){const t=this.entityVersions_.get(e);if(!t)return void this.entityVersions_.delete(e);const n=this.backends_.get(t);n&&n.removeEntity(e),this.entityVersions_.delete(e)}getEntityVersion(e){return this.entityVersions_.get(e)}hasModuleBackend(e){return this.backends_.has(e)}getModuleBackend(e){return this.backends_.get(e)}setAnimation(e,t,n){const s=this.entityVersions_.get(e);if(!s)return;const i=this.backends_.get(s);i&&i.setAnimation(e,t,n)}setSkin(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setSkin(e,t)}setEntityProps(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setEntityProps(e,t)}getBounds(e){const t=this.entityVersions_.get(e);if(!t)return null;const n=this.backends_.get(t);return n?n.getBounds(e):null}getAnimations(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getAnimations(e):[]}getSkins(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getSkins(e):[]}setDefaultMix(e,t){const n=this.getEntityBackend_(e);n&&n.setDefaultMix(e,t)}setMixDuration(e,t,n,s){const i=this.getEntityBackend_(e);i&&i.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){const s=this.getEntityBackend_(e);s&&s.setTrackAlpha(e,t,n)}setAttachment(e,t,n){const s=this.getEntityBackend_(e);return!!s&&s.setAttachment(e,t,n)}setIKTarget(e,t,n,s,i){const o=this.getEntityBackend_(e);return!!o&&o.setIKTarget(e,t,n,s,i)}setSlotColor(e,t,n,s,i,o){const r=this.getEntityBackend_(e);return!!r&&r.setSlotColor(e,t,n,s,i,o)}enableEvents(e){const t=this.getEntityBackend_(e);t&&t.enableEvents(e)}hasInstance(e){return this.entityVersions_.has(e)}shutdown(){for(const e of this.backends_.values())e.shutdown();this.backends_.clear(),this.loadingBackends_.clear(),this.entityVersions_.clear()}getEntityBackend_(e){const t=this.entityVersions_.get(e);if(t)return this.backends_.get(t)}async ensureBackend(e){const t=this.backends_.get(e);if(t)return t;const n=this.loadingBackends_.get(e);if(n)return n;const s=this.factories_.get(e);if(!s)return console.warn(`[SpineManager] No module factory for version ${e}`),null;const i=(async()=>{try{const t=await s(),n=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"]),setDefaultMix:t("spine_setDefaultMix",null,["number","number"]),setMixDuration:t("spine_setMixDuration",null,["number","string","string","number"]),setTrackAlpha:t("spine_setTrackAlpha",null,["number","number","number"]),enableEvents:t("spine_enableEvents",null,["number"]),getEventCount:t("spine_getEventCount","number",["number"]),getEventBuffer:t("spine_getEventBuffer","number",[]),clearEvents:t("spine_clearEvents",null,[]),setAttachment:t("spine_setAttachment","number",["number","string","string"]),setIKTarget:t("spine_setIKTarget","number",["number","string","number","number","number"]),setSlotColor:t("spine_setSlotColor","number",["number","string","number","number","number","number"])}}(t),i=new ou(t,n),o=new ru(i);return this.backends_.set(e,o),o}catch(t){return console.error(`[SpineManager] Failed to load WASM module for version ${e}:`,t),null}finally{this.loadingBackends_.delete(e)}})();return this.loadingBackends_.set(e,i),i}}function lu(e,t){let n=0,s=0,i=0;do{const o=e[t+i++];if(n|=(127&o)<<s,s+=7,!(128&o))break}while(s<35);return{value:n,bytesRead:i}}async function cu(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const uu=Et({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),hu={r:.2,g:.4,b:1,a:.7},du={r:.2,g:1,b:.2,a:.7},fu={r:.2,g:1,b:1,a:.7},pu={r:1,g:1,b:.2,a:.5},mu={r:1,g:.2,b:.2,a:.8},gu={r:1,g:.2,b:.2,a:1},yu=1.5,_u=16;function xu(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function wu(e){switch(e){case Pt.Static:return hu;case Pt.Kinematic:return fu;default:return du}}function bu(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)Bo.line(l[e],l[(e+1)%4],o,yu)}function vu(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),h=l(-n,-s),d=l(n,-s);Bo.line(c,h,o,yu),Bo.line(u,d,o,yu);for(let e=0;e<_u;e++){const t=e/_u*Math.PI,i=(e+1)/_u*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));Bo.line(r,a,o,yu)}for(let e=0;e<_u;e++){const t=Math.PI+e/_u*Math.PI,i=Math.PI+(e+1)/_u*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));Bo.line(r,a,o,yu)}}function Su(e,t,n,s){const i=e+.5*n,o=t+.5*s;Bo.line({x:e,y:t},{x:i,y:o},mu,yu);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),h=o-6*(l*Math.sin(a)+c*Math.cos(a)),d=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));Bo.line({x:i,y:o},{x:u,y:h},mu,yu),Bo.line({x:i,y:o},{x:d,y:f},mu,yu)}function Mu(e,t,n){const s=e.getResource(uu);if(!s||!s.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([et]);for(const n of t){const t=e.world.get(n,et);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([pt,Ge]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,pt);if(!n.enabled)continue;const o=e.world.get(t,Ge),a=o.worldPosition.x,l=o.worldPosition.y,c=xu(o.worldRotation);if(s.showColliders){if(e.world.has(t,mt)){const s=e.world.get(t,mt),o=s.isSensor?pu:wu(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);bu(a+r*h-u*d,l+r*d+u*h,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,gt)){const s=e.world.get(t,gt),o=s.isSensor?pu:wu(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c),f=a+r*h-u*d,p=l+r*d+u*h;Bo.circleOutline({x:f,y:p},s.radius*i,o,yu,32)}if(e.world.has(t,yt)){const s=e.world.get(t,yt),o=s.isSensor?pu:wu(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);vu(a+r*h-u*d,l+r*d+u*h,s.radius*i,s.halfHeight*i,c,o)}if(e.world.has(t,_t)){const s=e.world.get(t,_t),o=s.isSensor?pu:wu(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=a+(s.point1.x*i*r-s.point1.y*i*u),d=l+(s.point1.x*i*u+s.point1.y*i*r),f=a+(s.point2.x*i*r-s.point2.y*i*u),p=l+(s.point2.x*i*u+s.point2.y*i*r);Bo.line({x:h,y:d},{x:f,y:p},o,yu)}if(e.world.has(t,xt)){const s=e.world.get(t,xt),o=s.isSensor?pu:wu(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=s.vertices;for(let e=0;e<h.length;e++){const t=h[e],n=h[(e+1)%h.length],s=a+(t.x*i*r-t.y*i*u),c=l+(t.x*i*u+t.y*i*r),d=a+(n.x*i*r-n.y*i*u),f=l+(n.x*i*u+n.y*i*r);Bo.line({x:s,y:c},{x:d,y:f},o,yu)}}if(e.world.has(t,wt)){const s=e.world.get(t,wt),o=wu(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=s.points,d=s.isLoop?h.length:h.length-1;for(let e=0;e<d;e++){const t=h[e],n=h[(e+1)%h.length],s=a+(t.x*i*r-t.y*i*u),c=l+(t.x*i*u+t.y*i*r),d=a+(n.x*i*r-n.y*i*u),f=l+(n.x*i*u+n.y*i*r);Bo.line({x:s,y:c},{x:d,y:f},o,yu)}}}if(s.showVelocity&&r&&n.bodyType===Pt.Dynamic){const e=r.getLinearVelocity(t);Su(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)Bo.circle({x:e.contactX,y:e.contactY},3,gu,!0,32)}}const Cu=Et({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Pu=Et(null,"PhysicsAPI");function Tu(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}class Eu{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/30,subStepCount:t.subStepCount??4,contactHertz:t.contactHertz??30,contactDampingRatio:t.contactDampingRatio??10,contactSpeed:t.contactSpeed??3,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(Cu,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Set,s=new Set,i=new Map;let o=-1;const r=cu(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount,this.config_.contactHertz,this.config_.contactDampingRatio,this.config_.contactSpeed);const a=function(e){const t=e.world.getEntitiesWithComponents([et]);for(const n of t){const t=e.world.get(n,et);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),l=1/a,c=e.world;c.onDespawn(e=>{n.has(e)&&(r._physics_destroyJoint(e),n.delete(e)),t.has(e)&&(r._physics_destroyBody(e),t.delete(e),i.delete(e),s.delete(e))}),e.addSystemToSchedule(bn.PostUpdate,Mn([At(Ft)],u=>{if(ii()&&!ai())return;const h=c.getEntitiesWithComponents([pt,Ge]),d=new Set;for(const n of h)if(d.add(n),t.has(n)){if(c.isChangedSince(n,pt,o)){const e=c.get(n,pt),t=i.get(n);!t||t.bodyType===e.bodyType&&t.gravityScale===e.gravityScale&&t.linearDamping===e.linearDamping&&t.angularDamping===e.angularDamping&&t.fixedRotation===e.fixedRotation&&t.bullet===e.bullet||(r._physics_updateBodyProperties(n,e.bodyType,e.gravityScale,e.linearDamping,e.angularDamping,e.fixedRotation?1:0,e.bullet?1:0),t.bodyType=e.bodyType,t.gravityScale=e.gravityScale,t.linearDamping=e.linearDamping,t.angularDamping=e.angularDamping,t.fixedRotation=e.fixedRotation,t.bullet=e.bullet)}const e=i.get(n);if(e&&e.bodyType===Pt.Kinematic){const e=c.get(n,Ge),t=Tu(e.worldRotation);r._physics_setBodyTransform(n,e.worldPosition.x*l,e.worldPosition.y*l,t)}}else{const o=c.get(n,pt);if(!o.enabled)continue;const a=c.get(n,Ge),u=c.has(n,nt),h=u?a.worldPosition.x:a.position.x,d=u?a.worldPosition.y:a.position.y,f=Tu(u?a.worldRotation:a.rotation);r._physics_createBody(n,o.bodyType,h*l,d*l,f,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),Ru(e,r,n,this.config_.collisionLayerMasks),t.add(n),c.has(n,nt)&&s.add(n),i.set(n,{bodyType:o.bodyType,gravityScale:o.gravityScale,linearDamping:o.linearDamping,angularDamping:o.angularDamping,fixedRotation:o.fixedRotation,bullet:o.bullet})}o=c.getWorldTick();for(const e of t)d.has(e)||(r._physics_destroyBody(e),t.delete(e),i.delete(e));!function(e,t,n,s,i){const o=e.getEntitiesWithComponents([bt,pt]);for(const r of o){if(s.has(r))continue;if(!n.has(r))continue;const o=e.get(r,bt);if(!o.enabled)continue;const a=o.connectedEntity;n.has(a)&&(t._physics_createRevoluteJoint(a,r,o.anchorA.x*i,o.anchorA.y*i,o.anchorB.x*i,o.anchorB.y*i,o.enableMotor?1:0,o.motorSpeed,o.maxMotorTorque,o.enableLimit?1:0,o.lowerAngle,o.upperAngle,o.collideConnected?1:0),s.add(r))}for(const o of e.getEntitiesWithComponents([vt,pt])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,vt);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createDistanceJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.length*i,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.minLength*i,r.maxLength*i,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([St,pt])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,St);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createPrismaticJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*i,r.upperTranslation*i,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([Mt,pt])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Mt);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWeldJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.linearHertz,r.angularHertz,r.linearDampingRatio,r.angularDampingRatio,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([Ct,pt])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Ct);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWheelJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*i,r.upperTranslation*i,r.enableMotor?1:0,r.maxMotorTorque,r.motorSpeed,r.collideConnected?1:0),s.add(o))}}(c,r,t,n,l),t.size>0&&u.delta>0&&r._physics_step(u.delta),function(e,t,n,s){const i=t._physics_getDynamicBodyCount();if(0===i)return;const o=t._physics_getDynamicBodyTransforms(),r=o>>2,a=t.HEAPU32,l=t.HEAPF32,c=e.world.getCppRegistry();if(!c)return;const u=e.world.getWasmModule(),h=s.size>0;if(!h&&u?.registry_batchSyncPhysicsTransforms){const e=i*Bu,s=u._malloc(e);return u.HEAPU8.set(new Uint8Array(t.HEAPU8.buffer,o,e),s),u.registry_batchSyncPhysicsTransforms(c,s,i,n),void u._free(s)}const d=u?.getTransformPtr?e=>u.getTransformPtr(c,e):null,f=u?.HEAPF32,p=d&&f?null:c.addTransform.bind(c),m=Iu;for(let t=0;t<i;t++){const i=r+t*Fu,o=a[i];let c=l[i+1]*n,u=l[i+2]*n,g=l[i+3];if(h&&s.has(o)){const t=e.world.get(o,nt);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Ge)){const n=e.world.get(t.entity,Ge),s=Tu(n.worldRotation),i=u,o=c-n.worldPosition.x,r=i-n.worldPosition.y,a=Math.cos(-s),l=Math.sin(-s);c=(o*a-r*l)/(0!==n.worldScale.x?n.worldScale.x:1),u=(o*l+r*a)/(0!==n.worldScale.y?n.worldScale.y:1),g-=s}}const y=.5*g,_=Math.cos(y),x=Math.sin(y);if(d&&f){const e=d(o);if(e){const t=e>>2;f[t]=c,f[t+1]=u,f[t+2]=0,f[t+3]=0,f[t+4]=0,f[t+5]=x,f[t+6]=_,f[t+7]=1,f[t+8]=1,f[t+9]=1,f[t+10]=c,f[t+11]=u,f[t+12]=0,f[t+13]=0,f[t+14]=0,f[t+15]=x,f[t+16]=_,f[t+17]=1,f[t+18]=1,f[t+19]=1;continue}}m.position.x=c,m.position.y=u,m.rotation.w=_,m.rotation.x=0,m.rotation.y=0,m.rotation.z=x,m.worldPosition.x=c,m.worldPosition.y=u,m.worldRotation.w=_,m.worldRotation.x=0,m.worldRotation.y=0,m.worldRotation.z=x,p(o,m)}}(e,r,a,s),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Cu,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,r,a)},{name:"PhysicsSystem"})),e.physicsModule=r,e.insertResource(Pu,Uu._fromModule(r)),function(e,t,n){e.insertResource(uu,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Ho("physics-debug-draw",()=>{Mu(e,t,n)})}(e,Pu,Cu),e.setFixedTimestep(this.config_.fixedTimestep)});r.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=r}}const Au=16;function ku(e,t,n){if(!n)return t;for(let t=0;t<Au;t++)if(e===1<<t)return n[t];return t}function Ru(e,t,n,s){const i=e.world;if(i.has(n,mt)){const e=i.get(n,mt),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s);t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.radius??.05,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,gt)){const e=i.get(n,gt),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s);t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,yt)){const e=i.get(n,yt),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,_t)){const e=i.get(n,_t),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s);t._physics_addSegmentShape(n,e.point1.x,e.point1.y,e.point2.x,e.point2.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,xt)){const e=i.get(n,xt),o=e.categoryBits??1,r=ku(o,e.maskBits??65535,s),a=e.vertices,l=Math.min(a.length,8),c=2*l*4,u=t._malloc(c),h=u>>2;for(let e=0;e<l;e++)t.HEAPF32[h+2*e]=a[e].x,t.HEAPF32[h+2*e+1]=a[e].y;t._physics_addPolygonShape(n,u,l,e.radius??0,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r),t._free(u)}if(i.has(n,wt)){const e=i.get(n,wt),s=e.points;if(s.length<4)return;const o=2*s.length*4,r=t._malloc(o),a=r>>2;for(let e=0;e<s.length;e++)t.HEAPF32[a+2*e]=s[e].x,t.HEAPF32[a+2*e+1]=s[e].y;t._physics_addChainShape(n,r,s.length,e.isLoop?1:0,e.friction,e.restitution,e.categoryBits??1,e.maskBits??65535),t._free(r)}}const Iu={position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}},Fu=4,Bu=4*Fu;class Uu{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(Uu.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)}createRevoluteJoint(e,t,n,s,i){const o=i??{};return 0!==this.module_._physics_createRevoluteJoint(e,t,n.x,n.y,s.x,s.y,o.enableMotor?1:0,o.motorSpeed??0,o.maxMotorTorque??0,o.enableLimit?1:0,o.lowerAngle??0,o.upperAngle??0,o.collideConnected?1:0)}destroyJoint(e){this.module_._physics_destroyJoint(e)}setRevoluteMotorSpeed(e,t){this.module_._physics_setRevoluteMotorSpeed(e,t)}setRevoluteMaxMotorTorque(e,t){this.module_._physics_setRevoluteMaxMotorTorque(e,t)}enableRevoluteMotor(e,t){this.module_._physics_enableRevoluteMotor(e,t?1:0)}enableRevoluteLimit(e,t){this.module_._physics_enableRevoluteLimit(e,t?1:0)}setRevoluteLimits(e,t,n){this.module_._physics_setRevoluteLimits(e,t,n)}getRevoluteAngle(e){return this.module_._physics_getRevoluteAngle(e)}getRevoluteMotorTorque(e){return this.module_._physics_getRevoluteMotorTorque(e)}raycast(e,t,n,s=65535,i=100){const o=1/i,r=this.module_._physics_raycast(e.x*o,e.y*o,t.x,t.y,n*o,s);if(0===r)return[];const a=this.module_._physics_getRaycastBuffer()>>2,l=[];for(let e=0;e<r;e++){const t=a+6*e;l.push({entity:this.module_.HEAPU32[t],point:{x:this.module_.HEAPF32[t+1]*i,y:this.module_.HEAPF32[t+2]*i},normal:{x:this.module_.HEAPF32[t+3],y:this.module_.HEAPF32[t+4]},fraction:this.module_.HEAPF32[t+5]})}return l.sort((e,t)=>e.fraction-t.fraction),l}overlapCircle(e,t,n=65535,s=100){const i=1/s,o=this.module_._physics_overlapCircle(e.x*i,e.y*i,t*i,n);if(0===o)return[];const r=this.module_._physics_getOverlapBuffer()>>2,a=[],l=new Set;for(let e=0;e<o;e++){const t=this.module_.HEAPU32[r+e];l.has(t)||(l.add(t),a.push(t))}return a}setAwake(e,t){this.module_._physics_setAwake(e,t?1:0)}isAwake(e){return 0!==this.module_._physics_isAwake(e)}static setDebugDraw(e,t){const n=e.getResource(uu);n&&(n.enabled=t,e.insertResource(uu,n))}static setDebugDrawConfig(e,t){const n=e.getResource(uu);n&&e.insertResource(uu,{...n,...t})}}const zu={nearest:0,linear:1},Wu={repeat:0,clamp:1,mirror:2};function Du(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=zu[s.filterMode??"linear"]??1,a=Wu[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function Hu(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 $u(e,t,n){const s=e.FS;if(!s)return!1;try{return function(e,t){const n=e.FS;if(!n)return;const s=t.substring(0,t.lastIndexOf("/"));if(!s)return;const i=s.split("/").filter(e=>e);let o="";for(const e of i){o+="/"+e;try{n.mkdir(o)}catch{}}}(e,t),s.writeFile(t,n),!0}catch(e){return console.warn(`[Runtime] Failed to write virtual FS: ${t}`,e),!1}}async function Lu(e){const{app:t,module:n,sceneData:s,provider:i,spineManager:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=qi(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=Du(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);const h=await async function(e,t,n,s){const i=new Set,o=new Map;for(const r of t.entities)for(const t of r.components){const r=Ki(t.type);if(!r||!t.data)continue;const a=t.data[r.skeletonField],l=t.data[r.atlasField];if(!a||!l)continue;const c=`${a}:${l}`;if(i.has(c))continue;i.add(c);const u=n.resolvePath(l);try{const t=await n.readText(l),i=n.resolvePath(a),r="binary"===P(i)?.contentType?await n.readBinary(a):await n.readText(a),h=s?"string"==typeof r?au.detectVersionJson(r):au.detectVersion(r):null,d=Hu(t),f=u.substring(0,u.lastIndexOf("/")),p=e.getResourceManager(),m=new Map;for(const t of d){const s=f+"/"+t;try{const i=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),o=Du(e,i,!1);p.registerTextureWithPath(o,s),m.set(t,{glId:p.getTextureGLId(o),w:i.width,h:i.height})}catch(e){console.warn(`[Spine] Failed to load texture: ${s}`,e)}}(!h||"4.2"===h)&&($u(e,u,t),$u(e,i,r)),o.set(c,{version:h,skelData:r,atlasText:t,textures:m})}catch(e){console.warn(`[Runtime] Failed to load spine asset: skel=${a} atlas=${l}`,e)}}return o}(n,s,i,o);if(r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??ue,subStepCount:a?.subStepCount??4,contactHertz:a?.contactHertz??120,contactDampingRatio:a?.contactDampingRatio??10,contactSpeed:a?.contactSpeed??10};new Eu("",e,()=>Promise.resolve(r)).build(t)}const d=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=qi(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=P(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Du(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch(e){console.warn(`[Runtime] Failed to load bitmap font: ${o}`,e),s[o]=0}}return s}(n,s,i),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=qi(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=Nn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Nn.createFromAsset(e,r)}catch(e){console.warn(`[Runtime] Failed to load material: ${o}`,e),n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=qi(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=ts(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,Du(e,s))}catch(e){console.warn(`[Runtime] Failed to load anim texture: ${t}`,e),r.set(t,0)}is(ns(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=qi(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=Es(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=As(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=Du(e,t),fs(r,t.width,t.height)}catch(e){console.warn(`[Runtime] Failed to load tileset texture: ${s}`,e)}o.push({textureHandle:r,columns:t.columns})}gs(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=qi(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await us.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await us.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=qi(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,d,f);const p=eo(t.world,s),m=t.world.getCppRegistry();if(m&&n.transform_update(m),o&&m&&h.size>0)for(const e of s.entities)for(const t of e.components){const n=Ki(t.type);if(!n||!t.data)continue;const s=t.data[n.skeletonField],i=t.data[n.atlasField];if(!s||!i)continue;const r=`${s}:${i}`,a=h.get(r);if(!a||!a.version||"4.2"===a.version)continue;const l=p.get(e.id);if(void 0===l)continue;await o.loadEntity(l,a.skelData,a.atlasText,a.textures,m),o.setEntityProps(l,{skeletonScale:t.data.skeletonScale??1,flipX:t.data.flipX??!1,flipY:t.data.flipY??!1,layer:t.data.layer??0});const c=t.data.skin;c&&o.setSkin(l,c);const u=t.data.animation;u&&o.setAnimation(l,u,!1!==t.data.loop)}if(c&&t.hasResource(Yr))for(const e of p.values())t.world.insert(e,ht,{scene:c,persistent:!1});if(l){const e=t.getResource(ao);e&&e.setAddressableManifest(l)}}function Ou(e,t,n){return{name:e,async setup(){await Lu({...n,sceneData:t,sceneName:e})}}}async function Vu(e){const{app:t,firstScene:n,aspectRatio:s}=e;Zr(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,spineManager:e.spineManager,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(Yr);for(const t of e.scenes)o.register(Ou(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&io(t.world,s)}class Nu{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Ki(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===P(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=qi(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=P(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}let ju=null;const Xu={update(e,t){ju?.spine_update?.(e._cpp,t)},play:(e,t,n=!0,s=0)=>ju?.spine_play?.(e,t,n,s)??!1,addAnimation:(e,t,n=!0,s=0,i=0)=>ju?.spine_addAnimation?.(e,t,n,s,i)??!1,setSkin:(e,t)=>ju?.spine_setSkin?.(e,t)??!1,getBonePosition:(e,t)=>ju?.spine_getBonePosition?.(e,t)??null,hasInstance:e=>ju?.spine_hasInstance?.(e)??!1,reloadAssets(e){ju?.spine_reloadAssets?.(e._cpp)},getAnimations:e=>ju?.spine_getAnimations?.(e)??[],getSkins:e=>ju?.spine_getSkins?.(e)??[]};class Yu{constructor(e){this.app_=null,e instanceof au?(this.spineManager_=e,this.provider_=null):(this.spineManager_=null,this.provider_=e??null)}get spineManager(){return this.spineManager_}setSpineManager(e){if(this.spineManager_=e,this.app_){const t=this.app_,n=t.pipeline;n?.addPreFlushCallback(n=>{const s=t.getResource(Ft).frameCount;e.submitMeshes(n._cpp,s)})}}build(e){this.app_=e;const t=e.wasmModule;if(ju=t,!this.spineManager_&&this.provider_){const e=function(e){const t=["3.8","4.1","4.2"],n=new Map;for(const s of t)n.set(s,async()=>{const[t,n]=await Promise.all([e.loadJs(s),e.loadWasm(s)]),i=new Blob([`${t};\nself.__ESSpineModule__ = ESSpineModule;`],{type:"application/javascript"}),o=URL.createObjectURL(i);await import(/* @vite-ignore */o),URL.revokeObjectURL(o);const r=globalThis.__ESSpineModule__;return delete globalThis.__ESSpineModule__,r({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Spine] WASM instantiation failed:",e)}),{})})});return n}(this.provider_);this.spineManager_=new au(t,e)}const n=this,s={_id:Symbol("SpineUpdateSystem"),_name:"SpineUpdateSystem",_params:[],_fn:()=>{const t=e.world.getCppRegistry();if(!t)return;const s=e.getResource(Ft);Xu.update({_cpp:t},s.delta),n.spineManager_?.updateAnimations(s.delta)}};if(e.addSystemToSchedule(bn.PreUpdate,s),this.spineManager_){const t=this.spineManager_,n=e.pipeline;n?.addPreFlushCallback(n=>{const s=e.getResource(Ft).frameCount;t.submitMeshes(n._cpp,s)})}}}const Gu="__preview__";class qu{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Yr);t.register({name:Gu,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Gu),this.loadPromise_=t.load(Gu).then(()=>{}).catch(e=>{console.error("[Preview] Failed to load preview scene:",e)}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Nu(this.baseUrl_);await n.prefetch(t);const s=this.app_.getPlugin(Yu),i=s?.spineManager??null;await Lu({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineManager:i,sceneName:Gu})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Qe]);for(const s of n){if(e.get(s,Qe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([et]);for(const i of s){const s=e.get(i,et);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(Yr).getScene(Gu),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,Ge,r);const a={isActive:!0,projectionType:Ne.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:je.ColorAndDepth};e.insert(o,Qe,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Yr);await e.switchTo(Gu),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Ku={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=Ur.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:Ur.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){Ur.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Ur.releaseRenderTarget(e._handle),Ku.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){Ur.begin(t,e._handle)},end(){Ur.end()},getDepthTexture:e=>Ur.getTargetDepthTexture(e._handle)};var Ju;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Ju||(Ju={}));class Zu{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Ju[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Ju.Debug:console.debug(t,n);break;case Ju.Info:console.log(t,n);break;case Ju.Warn:console.warn(t,n);break;case Ju.Error:console.error(t,n)}}}class Qu{constructor(){this.handlers_=[],this.minLevel_=Ju.Info,this.addHandler(new Zu)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Ju.Debug,e,t,n)}info(e,t,n){this.log(Ju.Info,e,t,n)}warn(e,t,n){this.log(Ju.Warn,e,t,n)}error(e,t,n){this.log(Ju.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const eh=new Qu;function th(){return eh}function nh(e){eh.setMinLevel(e)}function sh(e,t,n){eh.debug(e,t,n)}function ih(e,t,n){eh.info(e,t,n)}function oh(e,t,n){eh.warn(e,t,n)}function rh(e,t,n){eh.error(e,t,n)}const ah={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},lh={Running:0,Paused:1,Completed:2,Cancelled:3},ch={None:0,Restart:1,PingPong:2};const uh=1.70158,hh=2.70158,dh=2.5949095;const fh=2*Math.PI/3,ph=2*Math.PI/4.5;const mh=7.5625,gh=2.75;const yh=1e-6;function _h(e,t,n){switch(e){case ah.Linear:return t;case ah.EaseInQuad:return function(e){return e*e}(t);case ah.EaseOutQuad:return function(e){return e*(2-e)}(t);case ah.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case ah.EaseInCubic:return function(e){return e*e*e}(t);case ah.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case ah.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case ah.EaseInBack:return function(e){return hh*e*e*e-uh*e*e}(t);case ah.EaseOutBack:return function(e){const t=e-1;return 1+hh*t*t*t+uh*t*t}(t);case ah.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-dh)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+dh)+2)/2}(t);case ah.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*fh)}(t);case ah.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*fh)+1}(t);case ah.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*ph)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*ph)/2+1}(t);case ah.EaseOutBounce:return function(e){return e<1/gh?mh*e*e:e<2/gh?mh*(e-=1.5/gh)*e+.75:e<2.5/gh?mh*(e-=2.25/gh)*e+.9375:mh*(e-=2.625/gh)*e+.984375}(t);case ah.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<yh)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<yh)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case ah.Step:return function(e){return e<1?0:1}(t);default:return t}}const xh=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??ah.Linear,bezierPoints:null,state:lh.Running,loop:i?.loop??ch.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===lh.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==lh.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=_h(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==ch.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===ch.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=lh.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===lh.Running&&(t.state=lh.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===lh.Paused&&(t.state=lh.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=lh.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:lh.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class wh{constructor(e){this.id=e}get state(){return xh.getState(this.id)}bezier(e,t,n,s){return xh.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof wh?xh.setSequenceNext(this.id,e.id):xh.setSequenceNextExternal(this.id,e),this}pause(){xh.pause(this.id)}resume(){xh.resume(this.id)}cancel(){xh.cancel(this.id)}}const bh={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class vh{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof wh?(xh.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Sh=null,Mh=null;function Ch(e,t){Sh=e,Mh=t,xh.init(e,t)}function Ph(){xh.shutdown(),Sh=null,Mh=null}function Th(){if(!Sh)throw new Error("Tween API not initialized");return Sh}function Eh(){if(!Mh)throw new Error("Tween API not initialized");return Mh}const Ah={to(e,t,n,s,i,o){const r=Th(),a=Eh(),l=o?.easing??ah.Linear,c=o?.delay??0,u=o?.loop??ch.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new vh(r,a,d)},value(e,t,n,s,i){const o=xh.create(e,t,n,s,i);return new wh(o)},cancel(e){Th()._anim_cancelTween(Eh(),e.entity)},cancelAll(e){Th()._anim_cancelAllTweens(Eh(),e)},update(e){Th()._anim_updateTweens(Eh(),e),xh.update(e)}};class kh{constructor(){this.name="AnimationPlugin"}build(e){Ch(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(bn.Update,Mn([At(Ft)],e=>{ii()&&!ai()||Ah.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(bn.Update,Mn([At(Ft)],e=>{ii()&&!ai()||cs(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Ph()}}const Rh=new kh;let Ih=null,Fh=null;function Bh(e,t){Ih=e,Fh=t}function Uh(){Ih=null,Fh=null}const zh={update(e){Ih&&Fh&&Ih.particle_update?.(Fh,e)},play(e){Ih&&Fh&&Ih.particle_play?.(Fh,e)},stop(e){Ih&&Fh&&Ih.particle_stop?.(Fh,e)},reset(e){Ih&&Fh&&Ih.particle_reset?.(Fh,e)},getAliveCount:e=>Ih?Ih.particle_getAliveCount?.(e)??0:0};class Wh{constructor(){this.name="ParticlePlugin"}build(e){Bh(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(bn.Update,Mn([At(Ft)],e=>{zh.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Uh()}}const Dh=new Wh,Hh=1073741824,$h={orthogonal:0,isometric:1,staggered:2};class Lh{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.animatedLayers_=new Set,this.sourceEntityKeys_=new Map,this.layerState_=new Map}build(e){ws(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.animatedLayers_,i=this.sourceEntityKeys_,o=this.layerState_,r={_id:Symbol("TilemapSyncSystem"),_name:"TilemapSyncSystem",_params:[],_fn:()=>{const r=t.getEntitiesWithComponents([Ms,Ge]),a=new Set(r);for(const e of n)e>=Hh||a.has(e)||(vs.destroyLayer(e),n.delete(e),o.delete(e));for(const e of r){const s=t.tryGet(e,Ms);if(!s)continue;const i=s.texture;if(!i)continue;const r=ps(i);if(!r)continue;if(!n.has(e)){if(vs.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),vs.setOriginEntity(e,e),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];vs.setTiles(e,t)}n.add(e)}const a=s.tileWidth/r.width,l=s.tileHeight/r.height,c=s.tint,u=s.parallaxFactor,h=o.get(e);(!h||h.texture!==i||h.tilesetColumns!==s.tilesetColumns||h.layer!==s.layer||h.parallaxX!==u.x||h.parallaxY!==u.y||h.tintR!==c.r||h.tintG!==c.g||h.tintB!==c.b||h.tintA!==c.a||h.opacity!==s.opacity||h.visible!==s.visible)&&(vs.setRenderProps(e,i,s.tilesetColumns,a,l,s.layer,0,u.x,u.y),vs.setTint(e,c.r,c.g,c.b,c.a,s.opacity),vs.setVisible(e,s.visible),o.set(e,{texture:i,tilesetColumns:s.tilesetColumns,layer:s.layer,tintR:c.r,tintG:c.g,tintB:c.b,tintA:c.a,opacity:s.opacity,parallaxX:u.x,parallaxY:u.y,visible:s.visible}))}const l=t.getEntitiesWithComponents([Ss,Ge]);for(const e of l){if(t.tryGet(e,Ms))continue;const o=t.tryGet(e,Ss);if(!o?.source)continue;const r=ys(o.source);if(r&&!i.has(e)){const t=[],o=$h[r.orientation??"orthogonal"]??0;for(let i=0;i<r.layers.length;i++){const a=Hh+256*e+i,l=r.layers[i];if(vs.initLayer(a,l.width,l.height,r.tileWidth,r.tileHeight),vs.setOriginEntity(a,e),l.tiles.length>0&&vs.setTiles(a,l.tiles),0!==o&&vs.setGridType(a,o),r.tileAnimations){for(const[e,t]of r.tileAnimations)vs.setTileAnimation(a,e,t);r.tileAnimations.size>0&&s.add(a)}if(r.tileProperties)for(const[e,t]of r.tileProperties)for(const[n,s]of t)vs.setTileProperty(a,e,n,s);const c=r.tilesets[0];if(c){const e=ps(c.textureHandle);e&&(vs.setRenderProps(a,c.textureHandle,c.columns,r.tileWidth/e.width,r.tileHeight/e.height,i,0,1,1),vs.setTint(a,1,1,1,1,1),vs.setVisible(a,!0))}t.push(a),n.add(a)}i.set(e,t)}}const c=new Set(l);for(const[e,t]of i)if(!c.has(e)){for(const e of t)vs.destroyLayer(e),n.delete(e),s.delete(e),o.delete(e);i.delete(e)}if(s.size>0){const t=1e3*e.getResource(Ft).delta;for(const e of s)vs.advanceAnimations(e,t)}}};e.addSystemToSchedule(bn.PreUpdate,r)}cleanup(){for(const e of this.initializedLayers_)vs.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),this.layerState_.clear(),ms(),bs()}}const Oh=new Lh;function Vh(e,t){return e.toFixed(t)}function Nh(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class jh{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.lastUpdateTime_=0,this.lastStats_=null,this.accumulatedTimings_=new Map,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 220px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;this.lastStats_=e,this.accumulateTimings_(e.systemTimings);const t=performance.now();this.lastUpdateTime_>0&&t-this.lastUpdateTime_<500||(this.lastUpdateTime_=t,this.render_())}show(){this.visible_=!0,this.lastUpdateTime_=0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}accumulateTimings_(e){for(const[t,n]of e){const e=this.accumulatedTimings_.get(t);e?(e.sum+=n,e.count++,n>e.max&&(e.max=n)):this.accumulatedTimings_.set(t,{sum:n,max:n,count:1})}}render_(){const e=this.lastStats_;if(!e)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Vh(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Vh(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),this.accumulatedTimings_.size>0){const e=[];for(const[t,n]of this.accumulatedTimings_){const s=n.sum/n.count;e.push([t,s,n.max])}e.sort((e,t)=>t[2]-e[2]);const n=e.slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t,i]of n){s+=`<div>${Nh(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Vh(t,1)} / ${Vh(i,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join(""),this.accumulatedTimings_.clear()}}function Xh(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Yh=Et(Xh(),"Stats");class Gh{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const qh="StatsCollect";class Kh{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Jh{constructor(e){this.name="Stats",this.collector_=new Kh,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Yh,Xh());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new jh(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=Mn([At(Ft),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Yh);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(qh),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Ur.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:qh});e.addSystemToSchedule(bn.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Zh=new Jh;class Qh{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return ed(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}function ed(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}function td(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function nd(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await async function(e,t){try{const n=td(t),s={instantiateWasm(e,t){const s=new Response(n.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,e).then(e=>t(e.instance,e.module),()=>{WebAssembly.instantiate(n.buffer,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Playable] WASM instantiation fallback failed:",e)})}),{}}};return await e(s)}catch(e){return console.error("[Playable] WASM module init failed:",e),null}}(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}async function sd(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(ao);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));let a=null;if(e.spineModules&&Object.keys(e.spineModules).length>0){a=function(e,t){const n=new Map;for(const[e,s]of Object.entries(t)){const t=e;n.set(t,async()=>{const e=td(s.wasmBase64);return s.factory({instantiateWasm(t,n){const s=new Response(e.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,t).then(e=>n(e.instance,e.module),()=>{WebAssembly.instantiate(e.buffer,t).then(e=>n(e.instance,e.module)).catch(e=>{console.error("[Playable] Spine WASM instantiation fallback failed:",e)})}),{}}})})}return new au(e,n)}(n,e.spineModules);const s=t.getPlugin(Yu);s&&s.setSpineManager(a)}const l=e.physicsWasmBase64?await nd(e.physicsWasmBase64):null,c=new Qh(s);us.setAssetResolver(e=>{const t=s[e];return t?ed(t).buffer:null}),await Vu({app:t,module:n,provider:c,scenes:i,firstScene:o,spineManager:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const id=[rl,ul,Ml,Dl,Gl,El,Ql,ic,uc,Nl,Bl,dc,gc,bc,Mc,Tc,Dc],od=[Rh,Ui,Dh,Oh,Pr,ji];function rd(e,t){const n=new Yu(t?.spineProvider),s=[...id,...od,n,...t?.plugins??[]];return function(e,t){const n=Jr.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ko(e),Ln(e),Yo(e),or(e),Fr(e),Wr(e);const i=new $r;n.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=sa(e,s,t,i));const r=n.getResource(Bn);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(Bn,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Ur.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(Ur.resize(t,l),n.hasResource(Yr)){const e=n.getResource(Yr).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=sa(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Qr,width:t,height:l,elapsed:u});else{i.beginFrame(),i.beginScreenCapture();for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),Ur.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(bn.First,l),n.addSystemToSchedule(bn.Last,c),n.addPlugin(co),n.addPlugin(Mo),n.addPlugin(Fn),n.addPlugin(Kr),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{...t,plugins:s})}class ad{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function ld(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}).catch(e=>{console.error("[WeChat] WASM instantiation failed:",e)}),{})}async function cd(e,t){try{return await e({instantiateWasm:ld(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function ud(e){const t=await l("asset-manifest.json"),n=JSON.parse(t),s=function(e){const t={},n={};for(const s in e.groups){const i=e.groups[s];for(const e in i.assets){const s=i.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n),i=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=W(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:ld("esengine.wasm")}),c=o.getContext("webgl2")||o.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const u=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),h=rd(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(h,e.runtimeConfig);let d=null;if(e.spineFactories&&Object.keys(e.spineFactories).length>0){const t=new Map;for(const[n,s]of Object.entries(e.spineFactories)){const e=n,i=`spine_${n.replace(".","")}.wasm`;t.set(e,()=>cd(s,i))}d=new au(a,t)}let f=null;e.physicsFactory&&(f=await cd(e.physicsFactory,"physics.wasm"));const p=new ad(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await Vu({app:h,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineManager:d,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),h.run()}J||(J=!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},i=await x(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.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 w(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 i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}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 i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Z;export{en as Added,kh as AnimationPlugin,Jr as App,lo as AssetPlugin,uo as AssetRefCounter,ro as AssetServer,ao as Assets,Qn as AsyncCache,Ei as AttenuationModel,us as Audio,p as AudioBus,Fi as AudioListener,m as AudioMixer,Bi as AudioPlugin,g as AudioPool,Ii as AudioSource,it as BitmapText,Un as BlendMode,Pt as BodyType,mt as BoxCollider,xl as Button,_l as ButtonState,Qe as Camera,et as Canvas,yt as CapsuleCollider,wt as ChainCollider,tn as Changed,st as Children,gt as CircleCollider,je as ClearFlags,hn as Commands,fn as CommandsInstance,Hc as DARK_THEME,ee as DEFAULT_DESIGN_HEIGHT,Q as DEFAULT_DESIGN_WIDTH,le as DEFAULT_FALLBACK_DT,ue as DEFAULT_FIXED_TIMESTEP,ie as DEFAULT_FONT_FAMILY,oe as DEFAULT_FONT_SIZE,ce as DEFAULT_GRAVITY,re as DEFAULT_LINE_HEIGHT,ae as DEFAULT_MAX_DELTA_TIME,te as DEFAULT_PIXELS_PER_UNIT,he as DEFAULT_SPINE_SKIN,se as DEFAULT_SPRITE_SIZE,ne as DEFAULT_TEXT_CANVAS_SIZE,Oo as DataType,Zl as DragPlugin,Kl as DragState,ql as Draggable,Bo as Draw,vc as Dropdown,Sc as DropdownPlugin,ah as EasingType,rt as EmitterShape,dn as EntityCommands,Xa as EntityStateMap,_n as EventReader,wn as EventReaderInstance,gn as EventRegistry,yn as EventWriter,xn as EventWriterInstance,da as FillDirection,pa as FillMethod,ma as FillOrigin,Tr as FlushReason,Il as FocusManager,Rl as FocusManagerState,hc as FocusPlugin,kl as Focusable,Gh as FrameHistory,Hr as GLDebug,Ko as Geometry,vn as GetWorld,ge as INVALID_ENTITY,_e as INVALID_FONT,xe as INVALID_MATERIAL,ye as INVALID_TEXTURE,ga as Image,Wl as ImagePlugin,fa as ImageType,Rn as Input,In as InputPlugin,kn as InputState,_a as Interactable,Pc as LayoutGroupPlugin,yc as ListView,wc as ListViewPlugin,qe as LocalTransform,Ju as LogLevel,Qu as Logger,ch as LoopMode,Nn as Material,es as MaterialLoader,Zt as Mut,ut as Name,nt as Parent,zh as Particle,lt as ParticleEasing,ct as ParticleEmitter,Wh as ParticlePlugin,Uu as Physics,Cu as PhysicsEvents,Eu as PhysicsPlugin,xt as PolygonCollider,lr as PostProcess,Cr as PostProcessPlugin,nr as PostProcessStack,dt as PostProcessVolume,bo as PrefabServer,vo as Prefabs,So as PrefabsPlugin,qu as PreviewPlugin,Xl as ProgressBar,jl as ProgressBarDirection,Yl as ProgressBarPlugin,Ne as ProjectionType,an as Query,ln as QueryInstance,cn as Removed,un as RemovedQueryInstance,$r as RenderPipeline,Ar as RenderStage,Ku as RenderTexture,Er as RenderType,Ur as Renderer,At as Res,kt as ResMut,bt as RevoluteJoint,pt as RigidBody,de as RuntimeConfig,fc as SafeArea,mc as SafeAreaPlugin,Xe as ScaleMode,Yr as SceneManager,Xr as SceneManagerState,ht as SceneOwner,bn as Schedule,ec as ScrollView,sc as ScrollViewPlugin,_t as SegmentCollider,Zn as ShaderSources,Ze as ShapeRenderer,Ye as ShapeType,at as SimulationSpace,rc as Slider,oc as SliderDirection,cc as SliderPlugin,ot as SpineAnimation,Je as Sprite,ls as SpriteAnimator,Yh as Stats,Kh as StatsCollector,jh as StatsOverlay,Jh as StatsPlugin,Ut as Storage,kr as SubmitSkipFlags,An as SystemRunner,tl as Text,Za as TextAlign,Al as TextInput,Fl as TextInputPlugin,el as TextOverflow,ol as TextPlugin,nl as TextRenderer,Qa as TextVerticalAlign,Ss as Tilemap,vs as TilemapAPI,Ms as TilemapLayer,Lh as TilemapPlugin,Ft as Time,Ni as TimelinePlugin,Hl as Toggle,Vl as TogglePlugin,Ge as Transform,Ah as Tween,vh as TweenHandle,lh as TweenState,bh as TweenTarget,su as UI,Bn as UICameraInfo,wl as UIEventQueue,bl as UIEvents,yl as UIInteraction,Tl as UIInteractionPlugin,vl as UILayoutGeneration,Sl as UILayoutPlugin,ll as UIMask,cl as UIMaskPlugin,ya as UIRect,Wc as UIRenderOrderPlugin,Or as UIRenderer,$c as UIThemeRes,Lr as UIVisualType,tt as Velocity,ad as WeChatAssetProvider,Nu as WebAssetProvider,Jt as World,Ke as WorldTransform,Tn as addStartupSystem,Pn as addSystem,En as addSystemToSchedule,Rh as animationPlugin,me as applyBuildRuntimeConfig,Ca as applyDirectionalFill,go as applyOverrides,fe as applyRuntimeConfig,co as assetPlugin,Ui as audioPlugin,ki as calculateAttenuation,Ri as calculatePanning,_r as cleanupAllPostProcessVolumes,yr as cleanupPostProcessVolume,as as clearAnimClips,Lo as clearDrawCallbacks,ms as clearTextureDimensionsCache,_s as clearTilemapSourceCache,Ti as clearTimelineHandles,Ue as clearUserComponents,po as cloneComponentData,fo as cloneComponents,_o as collectNestedPrefabPaths,Se as color,Na as colorScale,ja as colorWithAlpha,va as computeFillAnchors,Ma as computeFillSize,Sa as computeHandleAnchors,xa as computeUIRectLayout,Ou as createRuntimeSceneConfig,rd as createWebApp,sh as debug,Xh as defaultFrameStats,Ie as defineComponent,pn as defineEvent,Et as defineResource,Mn as defineSystem,Fe as defineTag,Ql as dragPlugin,Mc as dropdownPlugin,rh as error,ts as extractAnimClipTexturePaths,oo as findEntityByName,yo as flattenPrefab,Zr as flushPendingSystems,dc as focusPlugin,E as getAddressableType,A as getAddressableTypeByEditorType,R as getAllAssetExtensions,fr as getAllEffectDefs,rs as getAnimClip,H as getAssetBuildTransform,U as getAssetMimeType,P as getAssetTypeEntry,Le as getComponent,qi as getComponentAssetFieldDescriptors,Gi as getComponentAssetFields,ft as getComponentDefaults,Te as getComponentEntityFields,Ki as getComponentSpineFieldDescriptor,F as getCustomExtensions,T as getEditorType,hr as getEffectDef,dr as getEffectTypes,th as getLogger,t as getPlatform,s as getPlatformType,ps as getTextureDimensions,ys as getTilemapSource,Pi as getTimelineHandle,Be as getUserComponent,B as getWeChatPackOptions,Dl as imagePlugin,ih as info,ko as initDrawAPI,Wr as initGLDebugAPI,Yo as initGeometryAPI,Ln as initMaterialAPI,Bh as initParticleAPI,sd as initPlayableRuntime,or as initPostProcessAPI,Fr as initRendererAPI,Vu as initRuntime,ws as initTilemapAPI,Ch as initTweenAPI,Oc as initUIBuilder,ud as initWeChatRuntime,Fn as inputPlugin,wo as instantiatePrefab,hl as intersectRects,dl as invertMatrix4,De as isBuiltinComponent,z as isCustomExtension,ii as isEditor,k as isKnownAssetExtension,n as isPlatformInitialized,ai as isPlayMode,oi as isRuntime,zn as isTextureRef,i as isWeChat,o as isWeb,Tc as layoutGroupPlugin,bc as listViewPlugin,so as loadComponent,cu as loadPhysicsModule,Lu as loadRuntimeScene,eo as loadSceneData,to as loadSceneWithAssets,Fs as loadTiledMap,I as looksLikeAssetPath,Ha as makeInteractable,ns as parseAnimClipData,ks as parseTiledMap,ei as parseTimelineAsset,Es as parseTmjJson,Dh as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,gl as pointInOBB,pl as pointInWorldRect,Pr as postProcessPlugin,Mo as prefabsPlugin,xo as preloadNestedPrefabs,Gl as progressBarPlugin,Me as quat,is as registerAnimClip,D as registerAssetBuildTransform,$e as registerComponent,Yi as registerComponentAssetFields,Pe as registerComponentEntityFields,Ho as registerDrawCallback,ho as registerEmbeddedAssets,Jn as registerMaterialCallback,fs as registerTextureDimensions,gs as registerTilemapSource,Di as registerTimelineAsset,mo as remapComponentEntityRefs,Ji as remapEntityFields,As as resolveRelativePath,gc as safeAreaPlugin,Kr as sceneManagerPlugin,fl as screenToWorld,ic as scrollViewPlugin,si as setEditorMode,Oa as setEntityColor,Va as setEntityEnabled,xc as setListViewRenderer,nh as setLogLevel,ri as setPlayMode,$t as setWasmErrorHandler,Ro as shutdownDrawAPI,Dr as shutdownGLDebugAPI,Go as shutdownGeometryAPI,On as shutdownMaterialAPI,Uh as shutdownParticleAPI,rr as shutdownPostProcessAPI,Br as shutdownRendererAPI,bs as shutdownTilemapAPI,Ph as shutdownTweenAPI,uc as sliderPlugin,cs as spriteAnimatorSystemUpdate,Zh as statsPlugin,Wa as syncFillSpriteSize,gr as syncPostProcessVolume,Bl as textInputPlugin,rl as textPlugin,Oh as tilemapPlugin,ji as timelinePlugin,W as toBuildPath,Nl as togglePlugin,iu as transitionTo,El as uiInteractionPlugin,Ml as uiLayoutPlugin,ul as uiMaskPlugin,id as uiPlugins,Dc as uiRenderOrderPlugin,os as unregisterAnimClip,ze as unregisterComponent,$o as unregisterDrawCallback,io as updateCameraAspectRatio,we as vec2,be as vec3,ve as vec4,oh as warn,$a as withChildEntity,Gr as wrapSceneSystem,j as wxFileExists,X as wxFileExistsSync,q as wxGetImagePixels,G as wxLoadImage,K as wxLoadImagePixels,V as wxReadFile,N as wxReadTextFile,Y as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.bundled.js b/desktop/public/sdk/esm/esengine.bundled.jsindex a3e7ba37d..b0728d1b6 100644--- a/desktop/public/sdk/esm/esengine.bundled.js+++ b/desktop/public/sdk/esm/esengine.bundled.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 i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class _{constructor(e,t,n,s,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=n,this.poolNode_=s,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class y{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new g(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const n=this.loadingUrls_.get(e);if(n)return n;const s=this.doLoadBuffer_(e);this.loadingUrls_.set(e,s);try{return await s}finally{this.loadingUrls_.delete(e)}}async loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const n=this.urlToId_.get(e);if(void 0!==n&&this.buffers_.has(n)){return{id:n,duration:this.buffers_.get(n).duration}}let s;try{s=await this.context_.decodeAudioData(t)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,s),this.urlToId_.set(e,i),{id:i,duration:s.duration}}async doLoadBuffer_(e){const n=await t().readFile(e);return this.loadBufferFromData(e,n)}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const n=this.buffers_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=n,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(s.gain),s.source=i,s.gain.gain.value=t.volume??1,s.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;s.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new _(l,i,n,s,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const x=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 loadImagePixels(e){const t=this.createImage();await new Promise((n,s)=>{t.crossOrigin="anonymous",t.onload=()=>n(),t.onerror=()=>s(new Error(`Failed to load image: ${e}`)),t.src=e});const n=this.createCanvas(t.width,t.height).getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(s.data.buffer)}}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),i=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},r=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{t.preventDefault();const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{t.preventDefault();const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=t=>{t.preventDefault(),e.onPointerUp(0)},h=()=>{e.onPointerUp(0)},d=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",o),n.addEventListener("mousedown",r),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l,{passive:!1}),n.addEventListener("touchmove",c,{passive:!1}),n.addEventListener("touchend",u,{passive:!1}),n.addEventListener("touchcancel",h),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("touchcancel",h),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}getStorageItem(e){return localStorage.getItem(e)}setStorageItem(e,t){localStorage.setItem(e,t)}removeStorageItem(e){localStorage.removeItem(e)}clearStorage(e){const t=[];for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);null!==s&&s.startsWith(e)&&t.push(s)}for(const e of t)localStorage.removeItem(e)}},w=1920,b=1080,v=100,S=512,M={x:100,y:100},P="Arial",T=24,C=1.2,E=.5,A=1/60,k={x:0,y:-9.81},R=1/60,I="default",F={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};function B(e){e.Text&&(e.Text._default.fontFamily=F.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=F.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=F.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=F.canvasMatchWidthOrHeight)}const U={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function z(e,t){if(void 0!==t.maxDeltaTime&&(F.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(F.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(F.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(F.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(F.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");F.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(F.canvasScaleMode=U[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(F.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(F.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(F.assetFailureCooldown=t.assetFailureCooldown)}const L=0,H=4294967295,D=4294967295,$=0,O=(e=0,t=0)=>({x:e,y:t}),W=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),V=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),N=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),X=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s}),j=new Map;function Y(e,t){j.set(e,t)}function q(e){return j.get(e)}function G(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(G);const t={};for(const n in e)t[n]=G(e[n]);return t}let K=0;function J(e,t){const n=++K,s=function(e){const t=[],n=[],s=[];let i=!1;for(const o in e){const r=e[o];null!==r&&"object"==typeof r?(i=!0,Array.isArray(r)?s.push(o):n.push(o)):t.push(o)}return i?{flatKeys:t,objectKeys:n,arrayKeys:s}:null}(t),i=t;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create(e){if(s){const t={...i};for(const e of s.objectKeys)t[e]={...i[e]};for(const e of s.arrayKeys)t[e]=i[e].slice();return e&&Object.assign(t,e),t}return e?{...t,...e}:{...t}}}}function Z(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Q(e,t,n){const s=re.get(e)??Z().get(e);if(s)return s;const i=J(e,t);return Z().set(e,i),re.set(e,i),ie(e,t,!1),n?.entityFields&&Y(e,n.entityFields),i}function ee(e){const t=re.get(e)??Z().get(e);if(t)return t;const n=J(e,{});return Z().set(e,n),re.set(e,n),ie(e,{},!0),n}function te(e){return Z().get(e)}function ne(){const e=Z();for(const t of e.keys())re.delete(t);e.clear()}function se(e){Z().delete(e),re.delete(e)}function ie(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function oe(e){return!0===e._builtin}const re=new Map;function ae(e,t){re.set(e,t)}function le(e){return re.get(e)??te(e)}function ce(e){if(null===e||"object"!=typeof e)return[];const t=[];for(const n of Object.keys(e)){const s=e[n];if(null!==s&&"object"==typeof s&&!Array.isArray(s)){"r"in s&&"g"in s&&"b"in s&&"a"in s&&t.push(n)}}return t}function ue(e,t,n){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t,_colorKeys:ce(t)};return re.set(e,s),s}const he={Perspective:0,Orthographic:1},de={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},fe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},pe={Circle:0,Capsule:1,RoundedRect:2},me=ue("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),ge=me,_e=me,ye=ue("Sprite",{texture:H,color:{r:1,g:1,b:1,a:1},size:{x:M.x,y:M.y},pivot:{x:.5,y:.5},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),xe=ue("ShapeRenderer",{shapeType:pe.Circle,color:{r:1,g:1,b:1,a:1},size:{x:100,y:100},cornerRadius:0,layer:0,enabled:!0}),we=ue("Camera",{projectionType:he.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:de.ColorAndDepth}),be=ue("Canvas",{designResolution:{x:w,y:b},pixelsPerUnit:100,scaleMode:fe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ve=ue("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Se=ue("Parent",{entity:0}),Me=ue("Children",{entities:[]}),Pe=ue("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:D,enabled:!0}),Te=ue("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,enabled:!0}),Ce={Point:0,Circle:1,Rectangle:2,Cone:3},Ee={World:0,Local:1},Ae={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},ke=ue("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:Ce.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:Ae.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:Ae.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:H,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:Ee.World,enabled:!0}),Re=Q("Name",{value:""}),Ie=Q("SceneOwner",{scene:"",persistent:!1}),Fe=Q("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function Be(e){const t=le(e);return t?G(t._default):null}const Ue=ue("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ze=ue("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},radius:.05,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Le=ue("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),He=ue("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),De=ue("SegmentCollider",{point1:{x:-.5,y:0},point2:{x:.5,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),$e=Q("PolygonCollider",{vertices:[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}],radius:0,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Oe=Q("ChainCollider",{points:[{x:-1,y:0},{x:0,y:.5},{x:1,y:0},{x:0,y:-.5}],isLoop:!0,friction:.6,restitution:0,categoryBits:1,maskBits:65535,enabled:!0}),We=Q("RevoluteJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},enableMotor:!1,motorSpeed:0,maxMotorTorque:0,enableLimit:!1,lowerAngle:0,upperAngle:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Ve=Q("DistanceJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},length:1,enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,minLength:.5,maxLength:2,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Ne=Q("PrismaticJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:1,y:0},enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Xe=Q("WeldJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},linearHertz:0,angularHertz:0,linearDampingRatio:1,angularDampingRatio:1,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),je=Q("WheelJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:0,y:1},enableSpring:!0,hertz:5,dampingRatio:.7,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorTorque:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Ye={Static:0,Kinematic:1,Dynamic:2};let qe=0;function Ge(e,t){const n=++qe;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Ke(e){return{_type:"res",_resource:e}}function Je(e){return{_type:"res_mut",_resource:e}}class Ze{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_)}updateValue(e){this.value_=e}}class Qe{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Ze(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const et=Ge({delta:0,elapsed:0,frameCount:0},"Time"),tt="esengine:",nt={getString(e,n){const s=t().getStorageItem(tt+e);return null!==s?s:n},setString(e,n){t().setStorageItem(tt+e,n)},getNumber(e,n){const s=t().getStorageItem(tt+e);if(null===s)return n;const i=Number(s);return Number.isNaN(i)?n:i},setNumber(e,n){t().setStorageItem(tt+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(tt+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(tt+e,String(n))},getJSON(e,n){const s=t().getStorageItem(tt+e);if(null===s)return n;try{return JSON.parse(s)}catch(t){return console.warn(`[Storage] Failed to parse JSON for key "${e}"`,t),n}},setJSON(e,n){t().setStorageItem(tt+e,JSON.stringify(n))},remove(e){t().removeStorageItem(tt+e)},has:e=>null!==t().getStorageItem(tt+e),clear(){t().clearStorage(tt)}};function st(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=it(t[e]),o=it(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function it(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ot(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let rt=null;function at(e){rt=e}function lt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),rt&&rt(e,t)}function ct(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={r:t.x,g:t.y,b:t.z,a:t.w})}return n}function ut(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={x:t.r,y:t.g,z:t.b,w:t.a})}return n}const ht={Transform:{ptrFn:"getTransformPtr",fields:[{name:"position",type:"vec3",offset:0},{name:"rotation",type:"quat",offset:12},{name:"scale",type:"vec3",offset:28},{name:"worldPosition",type:"vec3",offset:40},{name:"worldRotation",type:"quat",offset:52},{name:"worldScale",type:"vec3",offset:68}]},Sprite:{ptrFn:"getSpritePtr",fields:[{name:"texture",type:"u32",offset:0},{name:"color",type:"color",offset:4},{name:"size",type:"vec2",offset:20},{name:"uvOffset",type:"vec2",offset:28},{name:"uvScale",type:"vec2",offset:36},{name:"layer",type:"i32",offset:44},{name:"flipX",type:"bool",offset:48},{name:"flipY",type:"bool",offset:49},{name:"material",type:"u32",offset:52},{name:"enabled",type:"bool",offset:56}]},Velocity:{ptrFn:"getVelocityPtr",fields:[{name:"linear",type:"vec3",offset:0},{name:"angular",type:"vec3",offset:12}]},Camera:{ptrFn:"getCameraPtr",fields:[{name:"projectionType",type:"u8",offset:0},{name:"fov",type:"f32",offset:4},{name:"orthoSize",type:"f32",offset:8},{name:"nearPlane",type:"f32",offset:12},{name:"farPlane",type:"f32",offset:16},{name:"aspectRatio",type:"f32",offset:20},{name:"isActive",type:"bool",offset:24},{name:"priority",type:"i32",offset:28},{name:"viewportX",type:"f32",offset:32},{name:"viewportY",type:"f32",offset:36},{name:"viewportW",type:"f32",offset:40},{name:"viewportH",type:"f32",offset:44},{name:"clearFlags",type:"i32",offset:48}]},UIRect:{ptrFn:"getUIRectPtr",fields:[{name:"anchorMin",type:"vec2",offset:0},{name:"anchorMax",type:"vec2",offset:8},{name:"offsetMin",type:"vec2",offset:16},{name:"offsetMax",type:"vec2",offset:24},{name:"size",type:"vec2",offset:32},{name:"pivot",type:"vec2",offset:40}]},RigidBody:{ptrFn:"getRigidBodyPtr",fields:[{name:"bodyType",type:"u8",offset:0},{name:"gravityScale",type:"f32",offset:4},{name:"linearDamping",type:"f32",offset:8},{name:"angularDamping",type:"f32",offset:12},{name:"fixedRotation",type:"bool",offset:16},{name:"bullet",type:"bool",offset:17},{name:"enabled",type:"bool",offset:18}]},BoxCollider:{ptrFn:"getBoxColliderPtr",fields:[{name:"halfExtents",type:"vec2",offset:0},{name:"offset",type:"vec2",offset:8},{name:"density",type:"f32",offset:16},{name:"friction",type:"f32",offset:20},{name:"restitution",type:"f32",offset:24},{name:"isSensor",type:"bool",offset:28},{name:"enabled",type:"bool",offset:29},{name:"categoryBits",type:"u32",offset:32},{name:"maskBits",type:"u32",offset:36}]},CircleCollider:{ptrFn:"getCircleColliderPtr",fields:[{name:"radius",type:"f32",offset:0},{name:"offset",type:"vec2",offset:4},{name:"density",type:"f32",offset:12},{name:"friction",type:"f32",offset:16},{name:"restitution",type:"f32",offset:20},{name:"isSensor",type:"bool",offset:24},{name:"enabled",type:"bool",offset:25},{name:"categoryBits",type:"u32",offset:28},{name:"maskBits",type:"u32",offset:32}]}};function dt(e,t,n,s,i,o){const r=s+i.offset,a=r>>2;switch(i.type){case"f32":e[a]=o;break;case"i32":t[a]=0|o;break;case"u32":t[a]=o;break;case"bool":n[r]=o?1:0;break;case"u8":n[r]=o;break;case"vec2":e[a]=o.x,e[a+1]=o.y;break;case"vec3":e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z;break;case"quat":e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z,e[a+3]=o.w;break;case"color":e[a]=o.r,e[a+1]=o.g,e[a+2]=o.b,e[a+3]=o.a}}let ft=1;const pt=new WeakMap;function mt(e){let t=pt.get(e);return void 0===t&&(t=ft++,pt.set(e,t)),t}const gt=[];function _t(e,t=[],n=[]){gt.length=0;for(const t of e)gt.push(mt(t));gt.sort((e,t)=>e-t);let s=gt.join(",");if(t.length>0){gt.length=0;for(const e of t)gt.push(mt(e));gt.sort((e,t)=>e-t),s+="|+"+gt.join(",")}if(n.length>0){gt.length=0;for(const e of n)gt.push(mt(e));gt.sort((e,t)=>e-t),s+="|-"+gt.join(",")}return s}class yt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.builtinEntitySets_=new Map,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map,this.trackedComponents_=new Set}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}getWasmModule(){return this.module_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw lt(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch(e){console.warn("[World] Spawn callback error:",e)}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch(e){console.warn("[World] Despawn callback error:",e)}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){lt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;for(const[,t]of this.builtinEntitySets_)t.delete(e);const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){lt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){lt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return oe(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(oe(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,ut(o,t._colorKeys))}catch(n){lt(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return oe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){if(t._builtin){if(!this.cppRegistry_)return!1;const n=t._cppName,s=this.builtinEntitySets_.get(n);return s?s.has(e):this.getBuiltinMethods(n).has(e)}return this.hasScript(e,t)}tryGet(e,t){if(oe(t)){if(!this.cppRegistry_)return null;const n=this.builtinEntitySets_.get(t._cppName);if(n&&!n.has(e))return null;try{const s=this.getBuiltinMethods(t._cppName);return n||s.has(e)?ct(s.get(e),t._colorKeys):null}catch(n){return lt(n,`tryGet(${t._name}, entity=${e})`),null}}const n=this.tsStorage_.get(t._id);if(!n)return null;const s=n.get(e);return void 0!==s?s:null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");oe(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=st(t._name,s,i);if(e.length>0)throw new Error(ot(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,ut(o,t._colorKeys))}catch(n){lt(n,`insertBuiltin(${t._name}, entity=${e})`)}let a=this.builtinEntitySets_.get(t._cppName);a||(a=new Set,this.builtinEntitySets_.set(t._cppName,a));const l=a.has(e);return!r&&l||(l||a.add(e),this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return ct(this.getBuiltinMethods(t._cppName).get(e),t._colorKeys)}catch(n){return lt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return lt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){lt(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++,this.builtinEntitySets_.get(t._cppName)?.delete(e)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=st(t._name,t._default,e);if(i.length>0)throw new Error(ot(t._name,i));s=e}const i=t.create(s),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=new Set,this.entityComponents_.set(e,a)),a.add(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);s&&s.delete(t._id)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resolveGetter(e){if(oe(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrGetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?e=>t.get(e):e=>ct(t.get(e),n)}const t=this.tsStorage_.get(e._id);return t?e=>t.get(e):null}resolveHas(e){if(oe(e)){if(!this.cppRegistry_)return null;const t=this.getBuiltinMethods(e._cppName);return e=>t.has(e)}const t=this.tsStorage_.get(e._id);return t?e=>t.has(e):null}resolveSetter(e){if(oe(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrSetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?(e,n)=>t.add(e,n):(e,s)=>t.add(e,ut(s,n))}const t=this.tsStorage_.get(e._id);return t?(e,n)=>t.set(e,n):null}resolvePtrFn_(e){const t=ht[e];if(!t)return null;const n=this.module_[t.ptrFn];if(!n)return null;const s=this.cppRegistry_;return e=>n(s,e)}resolvePtrSetter_(e){const t=ht[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,i=t.fields;return(e,t)=>{const o=n(e);if(!o)return;const r=t;for(let e=0;e<i.length;e++)dt(s.HEAPF32,s.HEAPU32,s.HEAPU8,o,i[e],r[i[e].name])}}resolvePtrGetter_(e){const t=ht[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,i=t.fields,o=function(e){const t={};for(const n of e)switch(n.type){case"vec2":t[n.name]={x:0,y:0};break;case"vec3":t[n.name]={x:0,y:0,z:0};break;case"quat":t[n.name]={x:0,y:0,z:0,w:0};break;case"color":t[n.name]={r:0,g:0,b:0,a:0};break;default:t[n.name]=null}return t}(i);return e=>{const t=n(e);return t?(function(e,t,n,s,i,o){for(let r=0;r<i.length;r++){const a=i[r],l=s+a.offset,c=l>>2;switch(a.type){case"f32":o[a.name]=e[c];break;case"i32":o[a.name]=0|t[c];break;case"u32":o[a.name]=t[c];break;case"bool":o[a.name]=0!==n[l];break;case"u8":o[a.name]=n[l];break;case"vec2":{const t=o[a.name];t.x=e[c],t.y=e[c+1];break}case"vec3":{const t=o[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2];break}case"quat":{const t=o[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2],t.w=e[c+3];break}case"color":{const t=o[a.name];t.r=e[c],t.g=e[c+1],t.b=e[c+2],t.a=e[c+3];break}}}}(s.HEAPF32,s.HEAPU32,s.HEAPU8,t,i,o),o):null}}resetQueryPool(){}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch(e){console.warn(`[World] Component check failed for ${n}:`,e)}if(this.cppRegistry_)for(const[n,s]of re)if(oe(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch(e){console.warn(`[World] Builtin check failed for ${n}:`,e)}const n=this.entityComponents_.get(e);if(n){const e=Z();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}resolveStorages_(e,t,n){for(const s of e)if(oe(s)){if(!this.cppRegistry_)return!1;n.push(this.getBuiltinMethods(s._cppName))}else{const e=this.tsStorage_.get(s._id);if(!e)return!1;t.push(e)}return!0}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??_t(e,t,n),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;const r=[],a=[],l=[];if(!this.resolveStorages_(e,a,l))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),r;let c=null,u=null;if(t.length>0&&(c=[],u=[],!this.resolveStorages_(t,c,u)))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),r;let h=null,d=null;n.length>0&&(h=[],d=[],this.resolveStorages_(n,h,d));let f=null,p=1/0;for(let e=0;e<a.length;e++){const t=a[e].size;t<p&&(p=t,f=a[e])}for(const t of e)if(oe(t)){const e=this.builtinEntitySets_.get(t._cppName);e&&e.size<p&&(p=e.size,f=e)}const m=f?f.keys():this.entities_.keys(),g=a.length,_=l.length;for(const e of m){let t=!0;for(let n=0;n<g;n++)if(!a[n].has(e)){t=!1;break}if(t)for(let n=0;n<_;n++)if(!l[n].has(e)){t=!1;break}if(t&&c){for(let n=0;n<c.length;n++)if(!c[n].has(e)){t=!1;break}if(t)for(let n=0;n<u.length;n++)if(!u[n].has(e)){t=!1;break}}if(t&&h){for(let n=0;n<h.length;n++)if(h[n].has(e)){t=!1;break}if(t)for(let n=0;n<d.length;n++)if(d[n].has(e)){t=!1;break}}t&&r.push(e)}return this.queryCache_.set(i,{version:this.worldVersion_,result:r}),r}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}enableChangeTracking(e){this.trackedComponents_.add(e._id)}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}markChanged(e,t){this.recordChangedTick_(t,e)}recordChangedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function xt(e){return{_type:"mut",_component:e}}function wt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function bt(e){return{_filterType:"added",_component:e}}function vt(e){return{_filterType:"changed",_component:e}}function St(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Mt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Pt(e){return wt(e)||St(e)||Mt(e)?e._component:e}function Tt(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{wt(e)&&s.push(t),St(e)?i.push({index:t,component:e._component}):Mt(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Tt(e,[...t,...s],n),without:(...s)=>Tt(e,t,[...n,...s])}}function Ct(...e){return Tt(e)}class Et{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Pt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=_t(this.allRequired_,t._with,t._without),this.getters_=this.actualComponents_.map(t=>e.resolveGetter(t)),this.mutSetters_=t._mutIndices.map(t=>e.resolveSetter(this.actualComponents_[t])),this.mutIsBuiltin_=t._mutIndices.map(e=>oe(this.actualComponents_[e]));for(const n of t._addedFilters)e.enableChangeTracking(n.component);for(const n of t._changedFilters)e.enableChangeTracking(n.component)}resetTick(e){this.lastRunTick_=e}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,h=this.getters_,d=this;let f=0,p=null,m=!1,g=!1;const _=this.mutIsBuiltin_,y=()=>{for(let e=0;e<l;e++){const t=a[e];if(_[e]){const n=c[e];n?n(p,t.data):u.set(p,t.component,t.data)}else u.markChanged(p,t.component)}},x=()=>{g||(g=!0,u.endIteration(),null!==p&&i&&y())},w={value:r,done:!1},b={value:void 0,done:!0};return{next(){for(m||(m=!0,u.beginIteration());f<n.length;){const c=n[f++];if(!o||d.passesChangeFilters_(c)){null!==p&&i&&y(),r[0]=c;for(let e=0;e<s;e++){const n=h[e];r[e+1]=n?n(c):u.get(c,t[e])}if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];p=c}return w}}return x(),b},return:()=>(x(),b)}}forEach(e){const{_mutIndices:t}=this.descriptor_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=this.actualComponents_.length,i=t.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,h=this.getters_,d=this.actualComponents_;u.beginIteration();let f=null;for(let p=0;p<n.length;p++){const m=n[p];if(!o||this.passesChangeFilters_(m)){if(null!==f&&i)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}r[0]=m;for(let e=0;e<s;e++){const t=h[e];r[e+1]=t?t(m):u.get(m,d[e])}if(i){for(let e=0;e<l;e++)a[e].data=r[t[e]+1];f=m}switch(s){case 1:e(m,r[1]);break;case 2:e(m,r[1],r[2]);break;case 3:e(m,r[1],r[2],r[3]);break;default:e.apply(null,r)}}}if(null!==f&&i)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}u.endIteration()}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function At(e){return{_type:"removed",_component:e}}class kt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n,e.enableChangeTracking(t)}resetTick(e){this.lastRunTick_=e}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function Rt(){return{_type:"commands"}}class It{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=oe(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 Ft{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new It(this,null);return this.spawned_.push(e),e}entity(e){return new It(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function Bt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Ut{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class zt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ut)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ut,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Lt(e){return{_type:"event_writer",_event:e}}function Ht(e){return{_type:"event_reader",_event:e}}class Dt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class $t{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Ot;function Wt(){return{_type:"get_world"}}!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"}(Ot||(Ot={}));let Vt=0;function Nt(e,t,n){const s=++Vt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Xt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function jt(e){Xt().push({schedule:Ot.Update,system:e})}function Yt(e){Xt().push({schedule:Ot.Startup,system:e})}function qt(e,t){Xt().push({schedule:e,system:t})}class Gt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.queryCache_=new Map,this.removedCache_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;let n=this.queryCache_.get(e._id),s=this.removedCache_.get(e._id);const i=!n;i&&(n=[],s=[],this.queryCache_.set(e._id,n),this.removedCache_.set(e._id,s));let o=0,r=0;for(let a=0;a<e._params.length;a++){const l=e._params[a];if("query"===l._type){if(i){const e=new Et(this.world_,l,this.currentLastRunTick_);n.push(e),t[a]=e}else{const e=n[o];e.resetTick(this.currentLastRunTick_),t[a]=e}o++}else if("removed"===l._type){if(i){const e=l,n=new kt(this.world_,e._component,this.currentLastRunTick_);s.push(n),t[a]=n}else{const e=s[r];e.resetTick(this.currentLastRunTick_),t[a]=e}r++}else t[a]=this.resolveParam(l)}const a=this.timings_?performance.now():0;let l;try{l=e._fn(...t)}catch(n){throw this.flushSystem_(e,t,a),n}if(l instanceof Promise)return l.then(()=>{this.flushSystem_(e,t,a)},n=>{throw this.flushSystem_(e,t,a),n});this.flushSystem_(e,t,a)}flushSystem_(e,t,n){for(let e=0;e<t.length;e++)t[e]instanceof Ft&&t[e].flush();this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}resolveParam(e){switch(e._type){case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ft(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Dt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new $t(n)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Kt{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 Jt=Ge(new Kt,"Input");class Zt{constructor(e){this.target_=e??null}build(e){const n=new Kt;e.insertResource(Jt,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(Ot.Last,Nt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Qt=new Zt,en=Ge({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var tn;function nn(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"}(tn||(tn={}));let sn=null,on=null,rn=1;const an=new Map;function ln(e){sn=e,on=e.getResourceManager(),yn()}function cn(){0!==fn&&sn&&(sn._free(fn),fn=0),an.clear(),rn=1,dn=!1,mn.clear(),gn=null,on=null,sn=null}function un(){if(!on)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return on}const hn={createShader:(e,t)=>un().createShader(e,t),releaseShader(e){e>0&&un().releaseShader(e)},create(e){const t=rn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??tn.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return an.set(t,n),t},get:e=>an.get(e),setUniform(e,t,n){const s=an.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,sn?.invalidateMaterialCache(e))},getUniform(e,t){const n=an.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=an.get(e);n&&(n.blendMode=t,sn?.invalidateMaterialCache(e))},getBlendMode(e){const t=an.get(e);return t?.blendMode??tn.Normal},setDepthTest(e,t){const n=an.get(e);n&&(n.depthTest=t,sn?.invalidateMaterialCache(e))},getShader(e){const t=an.get(e);return t?.shader??0},release(e){an.delete(e),sn?.invalidateMaterialCache(e)},isValid:e=>an.has(e),releaseAll(){an.clear(),sn?.clearMaterialCache()},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??tn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=an.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=rn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return an.set(n,s),n},toAssetData(e,t){const n=an.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=an.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let dn=!1,fn=0;const pn=16384,mn=new Map;let gn=null;function _n(e){const t=(0===fn&&sn&&(fn=sn._malloc(pn)),fn);if(0===t||!sn)return{ptr:0,count:0};let n=0,s=0;const i=sn.HEAPU8,o=sn.HEAPU32,r=sn.HEAPF32;for(const[a,l]of e){if(nn(l))continue;let e=mn.get(a);e||(gn||(gn=new TextEncoder),e=gn.encode(a),mn.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>pn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${pn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function yn(){if(!sn||dn)return;sn.materialDataProvider=(e,t,n,s,i)=>{const o=an.get(e);if(!o)return sn.HEAPU32[t>>2]=0,sn.HEAPU32[n>>2]=0,sn.HEAPU32[s>>2]=0,void(sn.HEAPU32[i>>2]=0);sn.HEAPU32[t>>2]=o.shader,sn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=_n(o.uniforms);sn.HEAPU32[s>>2]=r,sn.HEAPU32[i>>2]=a},dn=!0}const xn={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 wn{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=F.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+F.assetFailureCooldown}),t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`)),t}}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()}clearAll(){this.cache_.clear(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class bn{constructor(e,t=""){this.cache_=new wn,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(hn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())hn.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:hn.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 vn(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Sn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0,duration:e.duration};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const Mn=new Map;function Pn(e){Mn.set(e.name,e)}function Tn(e){Mn.delete(e)}function Cn(e){return Mn.get(e)}function En(){Mn.clear()}const An=Q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function kn(e,t){const n=e.getEntitiesWithComponents([An]);for(const s of n){const n=e.get(s,An);if(!n.enabled||!n.playing||!n.clip)continue;const i=Mn.get(n.clip);if(!i||0===i.frames.length)continue;const o=i.frames[n.currentFrame],r=o?.duration??1/(i.fps*n.speed),a=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let l=a;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),l=!0),l&&e.has(s,ye)){const t=i.frames[n.currentFrame],o=e.get(s,ye);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,ye,o)}l&&e.insert(s,An,n)}}class Rn{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static setAssetResolver(e){this.assetResolver_=e}static resolveUrl_(e){return!this.baseUrl||e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}/${e}`}static async preload(e){if(this.bufferCache_.has(e))return;if(this.assetResolver_){const t=this.assetResolver_(e);if(t)return this.preloadFromData(e,t)}const t=await this.backend_.loadBuffer(this.resolveUrl_(e));this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}Rn.mixer_=null,Rn.bufferCache_=new Map,Rn.bgmHandle_=null,Rn.bgmVolume_=1,Rn.fadeAnimId_=0,Rn.disposed_=!1,Rn.assetResolver_=null,Rn.baseUrl="";const In=new Map,Fn=new Map;function Bn(e,t,n){In.set(e,{width:t,height:n})}function Un(e){return In.get(e)}function zn(){In.clear()}function Ln(e,t){Fn.set(e,t)}function Hn(e){return Fn.get(e)}function Dn(){Fn.clear()}let $n=null;function On(e){$n=e}function Wn(){$n=null}const Vn={initLayer(e,t,n,s,i){$n?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){$n?.tilemap_destroyLayer(e)},setTile(e,t,n,s){$n?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>$n?$n.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){$n?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!$n)return;const n=t.byteLength,s=$n._malloc(n);new Uint16Array($n.HEAPU8.buffer,s,t.length).set(t),$n.tilemap_setTiles(e,s,t.length),$n._free(s)},hasLayer:e=>!!$n&&$n.tilemap_hasLayer(e),setRenderProps(e,t,n,s,i,o,r,a,l){$n?.tilemap_setRenderProps(e,t,n,s,i,o,r,a,l)},setTint(e,t,n,s,i,o){$n?.tilemap_setTint(e,t,n,s,i,o)},setVisible(e,t){$n?.tilemap_setVisible(e,t)},setOriginEntity(e,t){$n?.tilemap_setOriginEntity(e,t)},submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,x){$n?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,x)},setTileAnimation(e,t,n){if(!$n||0===n.length)return;const s=new Uint32Array(2*n.length);for(let e=0;e<n.length;e++)s[2*e]=n[e].tileId,s[2*e+1]=n[e].duration;const i=s.byteLength,o=$n._malloc(i);new Uint32Array($n.HEAPU8.buffer,o,s.length).set(s),$n.tilemap_setTileAnimation(e,t,o,n.length),$n._free(o)},advanceAnimations(e,t){$n?.tilemap_advanceAnimations(e,t)},setTileProperty(e,t,n,s){$n?.tilemap_setTileProperty(e,t,n,s)},getTileProperty:(e,t,n,s)=>$n?$n.tilemap_getTileProperty(e,t,n,s):"",flipTile(e,t,n,s,i,o){$n?.tilemap_flipTile(e,t,n,s,i,o)},rotateTile(e,t,n,s){$n?.tilemap_rotateTile(e,t,n,s)},setGridType(e,t){$n?.tilemap_setGridType(e,t)},tileToWorld(e,t,n,s,i){if(!$n)return{x:0,y:0};const o=$n.tilemap_tileToWorld(e,t,n,s,i),r=new Float32Array($n.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}},worldToTile(e,t,n,s,i){if(!$n)return{x:0,y:0};const o=$n.tilemap_worldToTile(e,t,n,s,i),r=new Float32Array($n.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}}},Nn=Q("Tilemap",{source:""}),Xn=Q("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function jn(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function Yn(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function qn(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function Gn(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=qn(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,h=Yn(e.tintcolor),d="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:h,parallaxX:d,parallaxY:f})}const u=[],h=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}const d=new Map,f=new Map;if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.id,s=n+1,i=e.animation;if(i&&i.length>0){const e=i.map(e=>({tileId:(e.tileid??0)+1,duration:e.duration??100}));d.set(s,e)}const o=e.properties;if(o){const e=new Map;for(const s of o){const i=s.name;"collision"===i&&!0===s.value&&h.push(n+t),e.set(i,String(s.value))}e.size>0&&f.set(s,e)}}}return{width:t,height:n,tileWidth:s,tileHeight:i,orientation:e.orientation??"orthogonal",layers:c,tilesets:r,objectGroups:u,collisionTileIds:h,tileAnimations:d,tileProperties:f}}function Kn(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function Jn(e,t){const n=$n;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),orientation:"orthogonal",layers:[],tilesets:[],objectGroups:[],collisionTileIds:[],tileAnimations:new Map,tileProperties:new Map},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?jn(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch(e){return console.warn("[Tiled] Failed to parse tilemap",e),n.tiled_freeMap(r),null}}const Zn=Math.PI/180;function Qn(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,h=o+(u-t.row*c)-.5*s,d=e.spawn();e.insert(d,me,{position:{x:r,y:h,z:0}}),e.insert(d,Ue,{bodyType:Ye.Static}),e.insert(d,ze,{halfExtents:{x:.5*n,y:.5*s}}),a.push(d)}return a}function es(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,me,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Xn,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,h=-t.rotation*Zn;if(e.insert(r,me,{position:{x:c,y:u,z:0}}),e.insert(r,Ue,{bodyType:Ye.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,Le,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,ze,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,ze,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,me,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=Qn(e,n,t,a,0,0);i.push(...s)}return i}const ts=0,ns=1,ss=2,is="property",os="spine",rs="spriteAnim",as="audio",ls="activation",cs="marker",us="customEvent",hs="animFrames",ds="hermite",fs="linear",ps="step",ms="easeIn",gs="easeOut",_s="easeInOut",ys=[["1.0","1.1",e=>{for(const t of e.tracks??[])if(t.type===is)for(const e of t.channels??[])for(const t of e.keyframes??[])t.interpolation||Math.abs(t.outTangent)>=1e5&&(t.interpolation="step",t.outTangent=0)}]];const xs={once:ts,loop:ns,pingPong:ss};function ws(e){const t={name:e.name??"",childPath:e.childPath??""};switch(e.type){case is:return{...t,type:is,component:e.component??"",channels:(e.channels??[]).map(e=>({property:e.property,keyframes:e.keyframes??[]}))};case os:return{...t,type:os,clips:e.clips??[],blendIn:e.blendIn??0};case rs:return{...t,type:rs,clip:e.clip??"",startTime:e.startTime??0};case as:return{...t,type:as,events:e.events??[]};case ls:return{...t,type:ls,ranges:e.ranges??[]};case cs:return{...t,type:cs,markers:e.markers??[]};case us:return{...t,type:us,events:(e.events??[]).map(e=>({time:e.time??0,name:e.name??"",payload:e.payload??{}}))};case hs:return{...t,type:hs,frames:(e.animFrames??[]).map(e=>({texture:e.texture??"",duration:e.duration}))};default:return console.warn(`[Timeline] Unknown track type: ${e.type}, skipping`),null}}function bs(e){return function(e){let t=e.version??"1.0";for(const[n,s,i]of ys)t===n&&(i(e),t=s);e.version="1.1"}(e),{version:"1.1",type:"timeline",duration:e.duration??0,wrapMode:(t=e.wrapMode,t?xs[t]??ts:ts),tracks:(e.tracks??[]).map(ws).filter(e=>null!==e)};var t}let vs=!1,Ss=!1;function Ms(e){vs=e}function Ps(){return vs}function Ts(){return!vs}function Cs(e){Ss=e}function Es(){return Ss}var As,ks;!function(e){e[e.PositionX=0]="PositionX",e[e.PositionY=1]="PositionY",e[e.PositionZ=2]="PositionZ",e[e.ScaleX=3]="ScaleX",e[e.ScaleY=4]="ScaleY",e[e.ScaleZ=5]="ScaleZ",e[e.RotationZ=6]="RotationZ",e[e.ColorR=7]="ColorR",e[e.ColorG=8]="ColorG",e[e.ColorB=9]="ColorB",e[e.ColorA=10]="ColorA",e[e.SpriteOpacity=11]="SpriteOpacity",e[e.SpriteSizeX=12]="SpriteSizeX",e[e.SpriteSizeY=13]="SpriteSizeY",e[e.OffsetMinX=14]="OffsetMinX",e[e.OffsetMinY=15]="OffsetMinY",e[e.OffsetMaxX=16]="OffsetMaxX",e[e.OffsetMaxY=17]="OffsetMaxY",e[e.AnchorMinX=18]="AnchorMinX",e[e.AnchorMinY=19]="AnchorMinY",e[e.AnchorMaxX=20]="AnchorMaxX",e[e.AnchorMaxY=21]="AnchorMaxY",e[e.PivotX=22]="PivotX",e[e.PivotY=23]="PivotY",e[e.CameraOrthoSize=24]="CameraOrthoSize",e[e.CustomField=25]="CustomField"}(As||(As={})),function(e){e[e.Transform=0]="Transform",e[e.Sprite=1]="Sprite",e[e.UIRect=2]="UIRect",e[e.Camera=3]="Camera",e[e.Custom=4]="Custom"}(ks||(ks={}));const Rs={Transform:{"position.x":As.PositionX,"position.y":As.PositionY,"position.z":As.PositionZ,"scale.x":As.ScaleX,"scale.y":As.ScaleY,"scale.z":As.ScaleZ,rotation:As.RotationZ},Sprite:{"color.r":As.ColorR,"color.g":As.ColorG,"color.b":As.ColorB,"color.a":As.ColorA,opacity:As.SpriteOpacity,"size.x":As.SpriteSizeX,"size.y":As.SpriteSizeY},UIRect:{"offsetMin.x":As.OffsetMinX,"offsetMin.y":As.OffsetMinY,"offsetMax.x":As.OffsetMaxX,"offsetMax.y":As.OffsetMaxY,"anchorMin.x":As.AnchorMinX,"anchorMin.y":As.AnchorMinY,"anchorMax.x":As.AnchorMaxX,"anchorMax.y":As.AnchorMaxY,"pivot.x":As.PivotX,"pivot.y":As.PivotY},Camera:{orthoSize:As.CameraOrthoSize}},Is={Transform:ks.Transform,Sprite:ks.Sprite,UIRect:ks.UIRect,Camera:ks.Camera},Fs={[ds]:0,[fs]:1,[ps]:2,[ms]:3,[gs]:4,[_s]:5};function Bs(e){return e?Fs[e]??0:0}function Us(e,t){return Rs[e]?.[t]??As.CustomField}function zs(e,t){const n=(new TextEncoder).encode(t),s=e._malloc(n.length);return new Uint8Array(e.HEAPU8.buffer,s,n.length).set(n),[s,n.length]}function Ls(e,t){e._free(t)}function Hs(e,t){const n=e._tl_create(t.duration,t.wrapMode);if(!n)return{handle:0,tracks:[],totalPropertyChannels:0};const s=[];let i=0;for(const o of t.tracks)switch(o.type){case is:Ds(e,n,o),s.push({type:"property",component:o.component,childPath:o.childPath,channelProperties:o.channels.map(e=>e.property)}),i+=o.channels.length;break;case os:$s(e,n,o),s.push({type:"spine",childPath:o.childPath});break;case as:Os(e,n,o),s.push({type:"audio",childPath:o.childPath});break;case ls:Ws(e,n,o),s.push({type:"activation",childPath:o.childPath});break;case rs:Vs(e,n,o),s.push({type:"spriteAnim",childPath:o.childPath})}return{handle:n,tracks:s,totalPropertyChannels:i}}function Ds(e,t,n){const s=e,i=n.channels.length,o=Is[n.component]??ks.Custom;if(o===ks.Custom)return void function(e,t,n){const s=e,i=n.channels.length,[o,r]=zs(e,n.childPath),[a,l]=zs(e,n.component),c=n.channels.map(e=>(new TextEncoder).encode(e.property));let u=0;for(const e of c)u+=e.length;const h=s._malloc(u);let d=0;for(const e of c)new Uint8Array(s.HEAPU8.buffer,h+d,e.length).set(e),d+=e.length;const f=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,f,i).set(c.map(e=>e.length));let p=0;const m=[];for(const e of n.channels)m.push(e.keyframes.length),p+=e.keyframes.length;const g=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,g,i).set(m);const _=s._malloc(5*p*4),y=new Float32Array(s.HEAPU8.buffer,_,5*p);let x=0;for(const e of n.channels)for(const t of e.keyframes)y[x++]=t.time,y[x++]=t.value,y[x++]=t.inTangent,y[x++]=t.outTangent,y[x++]=Bs(t.interpolation);e._tl_addCustomPropertyTrack(t,o,r,a,l,h,f,i,_,g),Ls(e,o),Ls(e,a),Ls(e,h),Ls(e,f),Ls(e,g),Ls(e,_)}(e,t,n);const[r,a]=zs(e,n.childPath),l=s._malloc(i),c=new Uint8Array(s.HEAPU8.buffer,l,i);for(let e=0;e<i;e++)c[e]=Us(n.component,n.channels[e].property);let u=0;const h=[];for(const e of n.channels)h.push(e.keyframes.length),u+=e.keyframes.length;const d=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,d,i).set(h);const f=s._malloc(5*u*4),p=new Float32Array(s.HEAPU8.buffer,f,5*u);let m=0;for(const e of n.channels)for(const t of e.keyframes)p[m++]=t.time,p[m++]=t.value,p[m++]=t.inTangent,p[m++]=t.outTangent,p[m++]=Bs(t.interpolation);e._tl_addPropertyTrack(t,r,a,o,l,i,f,d),Ls(e,r),Ls(e,l),Ls(e,d),Ls(e,f)}function $s(e,t,n){if(n.type!==os)return;const s=e,[i,o]=zs(e,n.childPath),r=n.clips.length,a=s._malloc(4*r*4),l=new Float32Array(s.HEAPU8.buffer,a,4*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),h=s._malloc(4*r),d=new Int32Array(s.HEAPU8.buffer,h,r),f=[];for(let t=0;t<r;t++){const s=n.clips[t];l[4*t]=s.start,l[4*t+1]=s.duration,l[4*t+2]=s.speed,l[4*t+3]=s.loop?1:0;const[i,o]=zs(e,s.animation);u[t]=i,d[t]=o,f.push(i)}e._tl_addSpineTrack(t,i,o,a,c,h,r,n.blendIn),Ls(e,i),Ls(e,a),Ls(e,c),Ls(e,h);for(const t of f)Ls(e,t)}function Os(e,t,n){if(n.type!==as)return;const s=e,[i,o]=zs(e,n.childPath),r=n.events.length,a=s._malloc(2*r*4),l=new Float32Array(s.HEAPU8.buffer,a,2*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),h=s._malloc(4*r),d=new Int32Array(s.HEAPU8.buffer,h,r),f=[];for(let t=0;t<r;t++){const s=n.events[t];l[2*t]=s.time,l[2*t+1]=s.volume;const[i,o]=zs(e,s.clip);u[t]=i,d[t]=o,f.push(i)}e._tl_addAudioTrack(t,i,o,a,c,h,r),Ls(e,i),Ls(e,a),Ls(e,c),Ls(e,h);for(const t of f)Ls(e,t)}function Ws(e,t,n){if(n.type!==ls)return;const s=e,[i,o]=zs(e,n.childPath),r=s._malloc(2*n.ranges.length*4),a=new Float32Array(s.HEAPU8.buffer,r,2*n.ranges.length);for(let e=0;e<n.ranges.length;e++)a[2*e]=n.ranges[e].start,a[2*e+1]=n.ranges[e].end;e._tl_addActivationTrack(t,i,o,r,n.ranges.length),Ls(e,i),Ls(e,r)}function Vs(e,t,n){if(n.type!==rs)return;const[s,i]=zs(e,n.childPath),[o,r]=zs(e,n.clip);e._tl_addSpriteAnimTrack(t,s,i,o,r,n.startTime),Ls(e,s),Ls(e,o)}const Ns=new Map;let Xs=null;function js(e,t){Ns.set(e,t)}function Ys(e){return Ns.get(e)}function qs(){if(Xs)for(const e of Ns.values())Xs._tl_destroy(e);Ns.clear()}var Gs;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Gs||(Gs={}));const Ks={model:Gs.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Js(e,t=Ks){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case Gs.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case Gs.Inverse:a=s/Math.max(r,s);break;case Gs.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Zs(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const Qs=Q("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Gs.Inverse,rolloff:1,priority:0,enabled:!0}),ei=Q("AudioListener",{enabled:!0});class ti{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;Rn.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(Ot.PreUpdate,Nt([Ke(et)],t=>{if(!(!Ps()||Es()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,h=!1;const d=s.getEntitiesWithComponents([ei,_e]);for(const e of d){if(s.get(e,ei).enabled){const t=s.get(e,_e);i=t.position.x,u=t.position.y,h=!0;break}}const f=s.getEntitiesWithComponents([Qs]);a.clear();for(const e of f){const t=s.get(e,Qs);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=Rn.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,_e),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=Js(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Zs(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),Rn.dispose()}}const ni=new ti,si=Q("TimelinePlayer",{timeline:"",playing:!1,speed:1,wrapMode:"once"}),ii=new Map;function oi(e,t){ii.set(e,t)}const ri=new Map;function ai(e,t){return ri.get(e)?.get(t)??0}const li={once:ts,loop:ns,pingPong:ss};function ci(e,t,n){const s=t.split(".");let i=e;for(let e=0;e<s.length-1;e++)if(i=i[s[e]],null==i||"object"!=typeof i)return!1;const o=s[s.length-1];return o in i&&(i[o]=n,!0)}function ui(e,t,n){if(!n)return t;const s=le("Children"),i=le("Name");if(!s||!i)return null;let o=t;const r=n.split("/");for(const t of r){const n=e.tryGet(o,s);if(!n)return null;const r=n.entities||[];let a=null;for(const n of r){const s=e.tryGet(n,i);if(s&&s.value===t){a=n;break}}if(null===a)return null;o=a}return o}class hi{constructor(){this.name="TimelinePlugin",this.handles_=new Map,this.animFramesStates_=new Map}build(e){const t=e.world;e.addSystemToSchedule(Ot.Update,Nt([Ke(et)],e=>{if(Ps()&&!Es())return;const n=t.getWasmModule();if(!n)return;Xs=n;const s=t.getCppRegistry();n.uiRect_clearAnimOverrides(s);const i=t.getEntitiesWithComponents([si]);for(const s of i){const i=t.get(s,si);if(!i.timeline)continue;let o=this.handles_.get(s);if(!o){const e=ii.get(i.timeline);if(!e)continue;if(o=Hs(n,e),!o.handle)continue;this.resolveTrackTargets(t,n,o,s),this.handles_.set(s,o),js(s,o.handle);const r=e.tracks.filter(e=>e.type===hs);r.length>0&&this.animFramesStates_.set(s,{tracks:r,lastFrameIndices:r.map(()=>-1)})}const r=o.handle;if(i.playing&&!n._tl_isPlaying(r)){const e=n._tl_getTime(r);0===e?n._tl_play(r):(n._tl_play(r),n._tl_setTime(r,e))}else!i.playing&&n._tl_isPlaying(r)&&n._tl_pause(r);const a=li[i.wrapMode]??ts;n._tl_setWrapMode(r,a),n._tl_advance(t.getCppRegistry(),r,s,e.delta,i.speed),this.processEvents(t,n),this.processCustomProperties(t,n,o),this.processAnimFrames(t,n,s,o.handle,i.timeline),n._tl_clearResults(),!n._tl_isPlaying(r)&&i.playing&&(i.playing=!1,t.insert(s,si,i))}},{name:"TimelineSystem"}))}clearHandles(){this.handles_.clear(),this.animFramesStates_.clear()}cleanup(){this.handles_.clear(),this.animFramesStates_.clear(),ii.clear()}processAnimFrames(e,t,n,s,i){const o=this.animFramesStates_.get(n);if(!o)return;const r=t._tl_getTime(s),a=le("Sprite");if(!a||!e.has(n,a))return;const l=1/12;for(let t=0;t<o.tracks.length;t++){const s=o.tracks[t].frames;if(0===s.length)continue;let c=0,u=0;for(let e=0;e<s.length;e++){const t=s[e].duration??l;if(r<c+t){u=e;break}c+=t,e===s.length-1&&(u=s.length-1)}if(u!==o.lastFrameIndices[t]){o.lastFrameIndices[t]=u;const r=ai(i,s[u].texture);if(r){const t=e.get(n,a);t.texture=r,e.set(n,a,t)}}}}resolveTrackTargets(e,t,n,s){let i=0,o=0;for(const r of n.tracks){if(!r.childPath){"property"===r.type?i++:o++;continue}const a=ui(e,s,r.childPath);if(null!==a){const e="property"!==r.type,s=e?o:i;t._tl_setTrackTarget(n.handle,e?1:0,s,a)}"property"===r.type?i++:o++}}decodeEventString(e,t){const n=e._tl_getEventString(t),s=e._tl_getEventStringLen(t);if(!n||s<=0)return"";const i=new Uint8Array(e.HEAPU8.buffer,n,s);return(new TextDecoder).decode(i)}processEvents(e,t){const n=t._tl_getEventCount();for(let s=0;s<n;s++){const n=t._tl_getEventType(s),i=t._tl_getEventEntity(s);switch(n){case 0:{const n=this.decodeEventString(t,s),o=0!==t._tl_getEventIntParam(s);if(e.has(i,Te)){const t=e.get(i,Te);t.animation=n,t.playing=!0,t.loop=o,e.set(i,Te,t)}break}case 1:if(e.has(i,Te)){const t=e.get(i,Te);t.playing=!1,e.set(i,Te,t)}break;case 2:{const n=this.decodeEventString(t,s);if(e.has(i,An)){const t=e.get(i,An);e.insert(i,An,{...t,clip:n,playing:!0})}break}case 3:{const e=this.decodeEventString(t,s),n=t._tl_getEventFloatParam(s);e&&Rn.playSFX(e,{volume:n});break}case 4:{const n=0!==t._tl_getEventIntParam(s);if(e.has(i,Te)){const t=e.get(i,Te);t.enabled=n,e.set(i,Te,t)}if(e.has(i,An)){const t=e.get(i,An);e.insert(i,An,{...t,enabled:n})}const o=le("Sprite");if(o&&e.has(i,o)){const t=e.get(i,o);e.set(i,o,{...t,enabled:n})}break}}}}processCustomProperties(e,t,n){const s=t._tl_getCustomPropertyCount();if(0!==s)for(let i=0;i<s;i++){const s=t._tl_getCustomPropertyEntity(i),o=t._tl_getCustomPropertyTrackIndex(i),r=t._tl_getCustomPropertyChannelIndex(i),a=t._tl_getCustomPropertyValue(i),l=n.tracks.filter(e=>"property"===e.type)[o];if(!l?.component||!l.channelProperties)continue;const c=le(l.component);if(!c||!e.has(s,c))continue;const u=e.get(s,c),h=l.channelProperties[r];h&&ci(u,h,a)&&e.set(s,c,u)}}}const di=new hi,fi=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["UIRenderer",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}],["TimelinePlayer",{fields:[{field:"timeline",type:"timeline"}]}]]);function pi(e,t){fi.set(e,t)}function mi(e){const t=fi.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function gi(e){return fi.get(e)?.fields??[]}function _i(e){return fi.get(e)?.spine??null}function yi(e,t){const n=q(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function xi(e){const t=e.components.some(e=>"UIRect"===e.type),n=e.components.findIndex(e=>"Sprite"===e.type),s=e.components.some(e=>"UIRenderer"===e.type);if(!t||-1===n||s)return;const i=e.components[n].data,o=i.texture;e.components.push({type:"UIRenderer",data:{visualType:o?2:1,texture:o??0,color:i.color??{r:1,g:1,b:1,a:1},uvOffset:i.uvOffset??{x:0,y:0},uvScale:i.uvScale??{x:1,y:1},sliceBorder:i.sliceBorder??{x:0,y:0,z:0,w:0},material:i.material??0,enabled:i.enabled??!0}}),e.components.splice(n,1)}function wi(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,Re,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;xi(s);const t=n.get(s.id);for(const i of s.components)yi(i,n),Mi(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function bi(e,t){return wi(e,t)}async function vi(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of Si.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=fi.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Si.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=fi.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=wi(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const Si=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),Bn(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=vn(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Pn(Sn(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await Rn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=Gn(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=Kn(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),Bn(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Ln(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}],["timeline",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=bs(await t.loadJson(e));oi(e,i);const o=function(e){const t=new Set,n=new Set,s=new Set;for(const i of e.tracks)if(i.type===as)for(const e of i.events)t.add(e.clip);else if(i.type===rs)i.clip&&n.add(i.clip);else if(i.type===hs)for(const e of i.frames)e.texture&&s.add(e.texture);return{audio:Array.from(t),animClips:Array.from(n),textures:Array.from(s)}}(i);if(o.textures.length>0){const i=new Map,r=o.textures.map(async e=>{try{const o=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o)}catch(t){console.warn(`Failed to load animFrames texture: ${e}`,t),i.set(e,0)}});await Promise.all(r),function(e,t){ri.set(e,t)}(e,i)}}catch(t){console.warn(`Failed to load timeline: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Mi(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=le(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Pi(e,t){const n=e.getEntitiesWithComponents([we]);for(const s of n){const n=e.get(s,we);n&&(n.aspectRatio=t,e.insert(s,we,n))}}function Ti(e,t){const n=e.getEntitiesWithComponents([Re]);for(const s of n){const n=e.get(s,Re);if(n&&n.value===t)return s}return null}const Ci=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["estimeline"],contentType:"json",editorType:"timeline",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],Ei={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",estimeline:"application/json",bmfont:"application/json",fnt:"text/plain"},Ai=new Map,ki=new Set;for(const e of Ci)for(const t of e.extensions)Ai.set(t,e),ki.add(t);function Ri(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Ii(e){return Ai.get(Ri(e))}function Fi(e){return Ii(e)?.editorType??"unknown"}function Bi(e){return Ii(e)?.addressableType??null}function Ui(e){for(const t of Ci)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function zi(e){return ki.has(e.toLowerCase())}function Li(){return ki}function Hi(e){return"string"==typeof e&&(!!e.includes("/")&&zi(Ri(e)))}function Di(){const e=[];for(const t of Ci)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function $i(){return Di().map(e=>({type:"suffix",value:e}))}function Oi(e){return Ei[e.toLowerCase()]}function Wi(e){const t=Ii(e);return t?.wechatPackInclude??!1}function Vi(e){const t=Ii(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function Ni(e,t){for(const n of Ci)n.editorType===e&&(n.buildTransform=t)}function Xi(e){return Ii(e)?.buildTransform}class ji{constructor(e){this.textureCache_=new wn,this.shaderCache_=new wn,this.jsonCache_=new wn,this.textCache_=new wn,this.binaryCache_=new wn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new wn,this.prefabCache_=new wn,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(F.textCanvasSize,F.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new bn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureRefCounts_.get(s);if(void 0===i)continue;const o=this.textureCache_.get(s);if(!o)continue;const r=i-1;r<=0?(t.releaseTexture(o.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),hn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===Ii(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=Ii(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of mi(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=_i(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 vi(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){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=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return hn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return hn.createShader(i,o)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(Vi(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 Yi=Ge(null,"Assets");class qi{build(e){const t=e.wasmModule;t?e.insertResource(Yi,new ji(t)):console.warn("AssetPlugin: No WASM module available")}}const Gi=new qi;class Ki{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ji(e,t){const n=e.getResource(Yi);n&&n.registerEmbeddedAssets(t)}function Zi(e){return e.map(e=>({type:e.type,data:JSON.parse(JSON.stringify(e.data))}))}function Qi(e){return JSON.parse(JSON.stringify(e))}function eo(e,t){for(const n of e){const e=q(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function to(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:Qi(n.componentData.data)})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}function no(e,t,n){const s=n.depth??0;if(s>10)throw new Error(`Prefab nesting depth exceeded 10. Check for deep or circular nesting in: ${e.name}`);if(e.basePrefab)return function(e,t,n,s){const i=e.basePrefab,o=n.visited??new Set;if(o.has(i))throw new Error(`[Prefab] Circular variant reference detected: "${i}" is already being instantiated in the current prefab chain`);const r=n.loadPrefab(i);if(!r)throw new Error(`Failed to load base prefab for variant: ${i}`);o.add(i);const a=[...e.overrides??[],...t];return no(r,a,{...n,visited:o,depth:s+1})}(e,t,n,s);const i=n.visited??new Set,o=new Map;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,n.allocateId());const r=[];for(const a of e.entities){if(a.nestedPrefab){const e=a.nestedPrefab.prefabPath;if(i.has(e))throw new Error(`[Prefab] Circular reference detected: "${e}" is already being instantiated in the current prefab chain`);const t=n.loadPrefab(e);if(!t)throw new Error(`Failed to load nested prefab: ${e}`);i.add(e);const l=no(t,a.nestedPrefab.overrides,{...n,visited:i,depth:s+1});o.set(a.prefabEntityId,l.rootId);const c=l.entities.find(e=>e.id===l.rootId);c&&(c.parent=null!==a.parent?o.get(a.parent)??null:null),r.push(...l.entities);continue}const l=o.get(a.prefabEntityId),c=a.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:a.prefabEntityId,name:a.name,parent:c?null:null!==a.parent?o.get(a.parent)??null:null,children:a.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:Zi(a.components),visible:a.visible};eo(u.components,o),to(u,t),r.push(u)}const a=o.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:r,rootId:a}}function so(e,t,n){const s=[],i=n??new Set;if(e.basePrefab&&!i.has(e.basePrefab)){i.add(e.basePrefab),s.push(e.basePrefab);const n=t(e.basePrefab);n&&s.push(...so(n,t,i))}for(const n of e.entities){if(!n.nestedPrefab)continue;const e=n.nestedPrefab.prefabPath;if(i.has(e))continue;i.add(e),s.push(e);const o=t(e);o&&s.push(...so(o,t,i))}return s}async function io(e,t,n,s,i=0){if(i>10)return;const o=s??new Set;if(e.basePrefab&&!o.has(e.basePrefab)&&!n.has(e.basePrefab)){o.add(e.basePrefab);const s=await t(e.basePrefab);n.set(e.basePrefab,s),await io(s,t,n,o,i+1)}for(const s of e.entities){if(!s.nestedPrefab)continue;const e=s.nestedPrefab.prefabPath;if(o.has(e)||n.has(e))continue;o.add(e);const r=await t(e);n.set(e,r),await io(r,t,n,o,i+1)}}async function oo(e,t,n){const s=new Map;n?.assetServer&&await io(t,e=>n.assetServer.loadPrefab(e,n.assetBaseUrl),s);let i=0;const o={allocateId:()=>i++,loadPrefab:e=>s.get(e)??null,visited:new Set},{entities:r,rootId:a}=no(t,n?.overrides??[],o),l={version:t.version,name:t.name,entities:r.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},c=await vi(e,l,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),u=c.get(a);return void 0!==n?.parent&&e.setParent(u,n.parent),{root:u,entities:c}}class ro{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return oo(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ao=Ge(null,"Prefabs");class lo{constructor(){this.name="PrefabsPlugin",this.dependencies=[Yi]}build(e){const t=e.getResource(Yi);e.insertResource(ao,new ro(e.world,t))}}const co=new lo;let uo=null,ho=0,fo=0,po=0;const mo=new Float32Array(256);function go(e){uo=e,ho=uo._malloc(64),fo=uo._malloc(64),po=uo._malloc(1024)}function _o(){uo&&(ho&&(uo._free(ho),ho=0),fo&&(uo._free(fo),fo=0),po&&(uo._free(po),po=0)),uo=null}function yo(){if(!uo)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return uo}const xo={r:1,g:1,b:1,a:1},wo={begin(e){const t=yo();try{t.HEAPF32.set(e,ho/4),t.draw_begin(ho)}catch(e){lt(e,"Draw.begin")}},end(){try{yo().draw_end()}catch(e){lt(e,"Draw.end")}},line(e,t,n,s=1){try{yo().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){lt(e,"Draw.line")}},rect(e,t,n,s=!0){try{yo().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){lt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{yo().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){lt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{yo().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){lt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{yo().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){lt(e,"Draw.circleOutline")}},texture(e,t,n,s=xo){try{yo().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){lt(e,"Draw.texture")}},textureRotated(e,t,n,s,i=xo){try{yo().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){lt(e,"Draw.textureRotated")}},setLayer(e){yo().draw_setLayer(e)},setDepth(e){yo().draw_setDepth(e)},getDrawCallCount:()=>uo?uo.draw_getDrawCallCount():0,getPrimitiveCount:()=>uo?uo.draw_getPrimitiveCount():0,setBlendMode(e){yo().draw_setBlendMode(e)},setDepthTest(e){yo().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=yo();s.HEAPF32.set(n,fo/4),s.draw_mesh(e,t,fo)}catch(n){lt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=yo(),i=hn.get(t);if(!i)return;if(wo.setBlendMode(i.blendMode),wo.setDepthTest(i.depthTest),0===i.uniforms.size)return void wo.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,fo/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=So(t);if(!(s<0)){if(nn(n))mo[o++]=10,mo[o++]=s,mo[o++]=n.slot??e++,mo[o++]=n.textureId;else if("number"==typeof n)mo[o++]=1,mo[o++]=s,mo[o++]=n;else if(Array.isArray(n)){mo[o++]=n.length,mo[o++]=s;for(let e=0;e<n.length;e++)mo[o++]=n[e]}else"w"in n?(mo[o++]=4,mo[o++]=s,mo[o++]=n.x,mo[o++]=n.y,mo[o++]=n.z,mo[o++]=n.w):"z"in n?(mo[o++]=3,mo[o++]=s,mo[o++]=n.x,mo[o++]=n.y,mo[o++]=n.z):(mo[o++]=2,mo[o++]=s,mo[o++]=n.x,mo[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(mo.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,fo);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),po/4),s.draw_meshWithUniforms(e,i.shader,fo,po,o)}catch(n){lt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},bo={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},vo=new Set;function So(e){const t=bo[e];return void 0!==t?t:(vo.has(e)||(vo.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(bo).join(", ")}`)),-1)}const Mo=new Map;function Po(e,t,n){Mo.set(e,{fn:t,scene:n??""})}function To(e){Mo.delete(e)}function Co(){Mo.clear()}var Eo;!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"}(Eo||(Eo={}));let Ao=null,ko=0,Ro=0,Io=0;function Fo(e){Ao=e,ko=Ao._malloc(262144),Ro=Ao._malloc(65536),Io=Ao._malloc(256)}function Bo(){Ao&&(ko&&Ao._free(ko),Ro&&Ao._free(Ro),Io&&Ao._free(Io),ko=0,Ro=0,Io=0),Ao=null}function Uo(){if(!Ao)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ao}const zo={create(e){const t=Uo(),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,ko/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Io,i).set(o),t.geometry_init(n,ko,s,Io,i,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,Ro,s).set(e.indices),t.geometry_setIndices16(n,Ro,s)}else{new Uint32Array(t.HEAPU8.buffer,Ro,s).set(e.indices),t.geometry_setIndices32(n,Ro,s)}}return n},updateVertices(e,t,n=0){const s=Uo(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,ko/4),s.geometry_updateVertices(e,ko,i,n)},release(e){e>0&&Uo().geometry_release(e)},isValid:e=>!(!Ao||e<=0)&&Ao.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return zo.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:Eo.Float2},{name:"a_texCoord",type:Eo.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 i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return zo.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Eo.Float2},{name:"a_texCoord",type:Eo.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return zo.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Eo.Float2},{name:"a_texCoord",type:Eo.Float2}],indices:new Uint16Array(r)})}};let Lo=1;const Ho=new Map,Do=new Map;function $o(){return Ho}function Oo(){return Do}class Wo{constructor(){this.passes_=[],this.destroyed_=!1,this.id=Lo++,Ho.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}clearPasses(){return this.passes_.length=0,this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of Do)t===this&&Do.delete(e);Ho.delete(this.id)}}}const Vo="#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";let No=null;function Xo(e){No=e}function jo(){for(const e of $o().values())e.destroy();$o().clear(),Oo().clear(),No&&qo.isInitialized()&&qo.shutdown(),No=null}function Yo(){if(!No)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return No}const qo={createStack:()=>new Wo,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");Oo().set(e,t)},unbind(e){Oo().delete(e)},getStack:e=>Oo().get(e)??null,init(e,t){try{return Yo().postprocess_init(e,t)}catch(n){return lt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Yo().postprocess_shutdown()}catch(e){lt(e,"PostProcess.shutdown")}},resize(e,t){try{Yo().postprocess_resize(e,t)}catch(n){lt(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!No)return!1;try{return No.postprocess_isInitialized()}catch(e){return lt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Yo().postprocess_setBypass(e)}catch(e){lt(e,"PostProcess.setBypass")}},begin(){try{Yo().postprocess_begin()}catch(e){lt(e,"PostProcess.begin")}},end(){try{Yo().postprocess_end()}catch(e){lt(e,"PostProcess.end")}},setOutputViewport(e,t,n,s){try{Yo().postprocess_setOutputViewport(e,t,n,s)}catch(e){lt(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=Oo().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(qo.isInitialized()||qo.init(1,1),qo.setBypass(!1),function(e){const t=Yo();try{t.postprocess_clearPasses()}catch(e){return void lt(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){lt(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){lt(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){lt(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):qo.setBypass(!0)},_resetAfterCamera(){try{Yo().postprocess_clearPasses(),Yo().postprocess_setBypass(!0)}catch(e){lt(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of Oo().keys())e(t)||Oo().delete(t)},screenStack:null,setScreenStack(e){qo.screenStack=e},_beginScreenCapture(){try{Yo().postprocess_beginScreenCapture()}catch(e){lt(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Yo().postprocess_endScreenCapture()}catch(e){lt(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=qo.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Yo();try{t.postprocess_clearScreenPasses()}catch(e){return void lt(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){lt(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){lt(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){lt(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{Yo().postprocess_executeScreenPasses()}catch(e){lt(e,"PostProcess._executeScreenPasses")}},createBlur:()=>hn.createShader(Vo,"#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:()=>hn.createShader(Vo,"#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 vig = 1.0 - smoothstep(1.0 - u_softness, 1.0, dist);\n fragColor = vec4(color.rgb * mix(1.0, vig, u_intensity), color.a);\n}\n"),createGrayscale:()=>hn.createShader(Vo,"#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"),createBloomExtract:()=>hn.createShader(Vo,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_threshold;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float brightness = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float knee = u_threshold * 0.5;\n float soft = brightness - u_threshold + knee;\n soft = clamp(soft, 0.0, 2.0 * knee);\n soft = soft * soft / (4.0 * knee + 0.00001);\n float contrib = max(soft, brightness - u_threshold);\n contrib /= max(brightness, 0.00001);\n fragColor = vec4(color.rgb * contrib, 1.0);\n}\n"),createBloomKawase(e){const t=`#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n float d = (${e.toFixed(1)} + 0.5) * max(u_radius, 0.5);\n vec2 ts = 1.0 / u_resolution;\n fragColor = (\n texture(u_texture, v_texCoord + vec2(-d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2(-d, d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, d) * ts)\n ) * 0.25;\n}\n`;return hn.createShader(Vo,t)},createBloomComposite:()=>hn.createShader(Vo,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform sampler2D u_sceneTexture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 blur = texture(u_texture, v_texCoord);\n vec4 scene = texture(u_sceneTexture, v_texCoord);\n fragColor = vec4(scene.rgb + blur.rgb * u_intensity, scene.a);\n}\n"),createChromaticAberration:()=>hn.createShader(Vo,"#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")},Go=new Map;function Ko(e){Go.set(e.type,e)}function Jo(e){return Go.get(e)}function Zo(){return Array.from(Go.keys())}function Qo(){return Array.from(Go.values())}Ko({type:"blur",label:"Blur",factory:()=>qo.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Ko({type:"bloom",label:"Bloom",factory:()=>qo.createBloomExtract(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:1,step:.01,defaultValue:.4},{name:"u_intensity",label:"Intensity",min:0,max:5,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:.5,max:5,step:.1,defaultValue:1}],multiPass:[{name:"bloom_extract",factory:()=>qo.createBloomExtract()},{name:"bloom_kawase_0",factory:()=>qo.createBloomKawase(0)},{name:"bloom_kawase_1",factory:()=>qo.createBloomKawase(1)},{name:"bloom_kawase_2",factory:()=>qo.createBloomKawase(2)},{name:"bloom_kawase_3",factory:()=>qo.createBloomKawase(3)},{name:"bloom_kawase_4",factory:()=>qo.createBloomKawase(4)},{name:"bloom_composite",factory:()=>qo.createBloomComposite()}]}),Ko({type:"vignette",label:"Vignette",factory:()=>qo.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:.6},{name:"u_softness",label:"Softness",min:0,max:1,step:.01,defaultValue:.5}]}),Ko({type:"grayscale",label:"Grayscale",factory:()=>qo.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Ko({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>qo.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const er=new Map,tr=new Map;function nr(e,t){let n=er.get(e),s=tr.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=qo.createStack(),er.set(e,n)),s||(s=new Map,tr.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=Jo(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}qo.bind(e,n)}else if(n&&(qo.unbind(e),n.destroy(),er.delete(e)),s){for(const e of s.values())hn.releaseShader(e);tr.delete(e)}}function sr(e){const t=er.get(e);t&&(qo.unbind(e),t.destroy(),er.delete(e));const n=tr.get(e);if(n){for(const e of n.values())hn.releaseShader(e);tr.delete(e)}}function ir(){for(const e of er.keys())sr(e)}const or=Ge({enabled:!0},"PostProcessVolumeConfig"),rr=new Map,ar=new Map;function lr(e,t){const n=ar.get(e);if(void 0!==n)return n;const s=t();return ar.set(e,s),s}function cr(e,t){if(0===t.size){const t=rr.get(e);return void(t&&(qo.unbind(e),t.destroy(),rr.delete(e)))}let n=rr.get(e);n||(n=qo.createStack(),rr.set(e,n)),n.clearPasses();for(const[e,s]of t){if(!s.enabled)continue;const t=Jo(e);if(t)if(t.multiPass)for(const e of t.multiPass){const t=lr(e.name,e.factory);n.addPass(e.name,t);for(const[t,i]of s.uniforms)n.setUniform(e.name,t,i)}else{const i=lr(e,t.factory);n.addPass(e,i);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?qo.bind(e,n):qo.unbind(e)}const ur=Nt([Ct(Fe,me),Ct(we)],(e,t)=>{const n=[];for(const[t,s,i]of e)n.push({data:s,tx:{x:i.position.x,y:i.position.y}});const s=[];for(const{data:e}of n)e.isGlobal&&s.push({data:e,factor:1});const i=s.length>0?function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(s):new Map;for(const[e,n]of t)n.isActive&&cr(e,i)},{name:"PostProcessVolumeSystem"});class hr{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(or,{enabled:!0}),e.addSystemToSchedule(Ot.PostUpdate,ur)}cleanup(){ir(),function(){for(const[e,t]of rr)qo.unbind(e),t.destroy();rr.clear();for(const e of ar.values())hn.releaseShader(e);ar.clear()}(),qo.setScreenStack(null)}}const dr=new hr;var fr,pr;!function(e){e[e.BatchFull=0]="BatchFull",e[e.TextureSlotsFull=1]="TextureSlotsFull",e[e.ScissorChange=2]="ScissorChange",e[e.StencilChange=3]="StencilChange",e[e.MaterialChange=4]="MaterialChange",e[e.BlendModeChange=5]="BlendModeChange",e[e.StageEnd=6]="StageEnd",e[e.TypeChange=7]="TypeChange",e[e.FrameEnd=8]="FrameEnd"}(fr||(fr={})),function(e){e[e.Sprite=0]="Sprite",e[e.Spine=1]="Spine",e[e.Mesh=2]="Mesh",e[e.ExternalMesh=3]="ExternalMesh",e[e.Text=4]="Text",e[e.Particle=5]="Particle",e[e.Shape=6]="Shape",e[e.UIElement=7]="UIElement"}(pr||(pr={}));var mr;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(mr||(mr={}));const gr={None:0,Spine:1,Particles:2};let _r=null,yr=0;function xr(e){_r=e,yr=_r._malloc(64)}function wr(){_r&&yr&&(_r._free(yr),yr=0),_r=null}const br={init(e,t){_r?.renderer_init(e,t)},resize(e,t){_r?.renderer_resize(e,t)},beginFrame(){_r?.renderer_beginFrame()},updateTransforms(e){if(_r)try{_r.renderer_updateTransforms(e._cpp)}catch(e){lt(e,"Renderer.updateTransforms")}},begin(e,t){if(_r&&yr)try{_r.HEAPF32.set(e,yr/4),_r.renderer_begin(yr,t??0)}catch(e){lt(e,"Renderer.begin")}},flush(){try{_r?.renderer_flush()}catch(e){lt(e,"Renderer.flush")}},end(){try{_r?.renderer_end()}catch(e){lt(e,"Renderer.end")}},submitAll(e,t,n,s,i,o){if(_r)try{_r.renderer_submitAll(e._cpp,t,n,s,i,o)}catch(e){lt(e,"Renderer.submitAll")}},setStage(e){_r?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>_r?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){_r?.renderer_releaseTarget(e)},getTargetTexture:e=>_r?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>_r?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){_r?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){_r?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){_r?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){_r?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>_r?_r.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>_r?{drawCalls:_r.renderer_getDrawCalls(),triangles:_r.renderer_getTriangles(),sprites:_r.renderer_getSprites(),text:_r.renderer_getText(),spine:_r.renderer_getSpine?.()??0,meshes:_r.renderer_getMeshes(),culled:_r.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0},captureNextFrame(){_r?.renderer_captureNextFrame()},getCapturedData:()=>_r?function(e){if(!e.renderer_hasCapturedData())return null;const t=e.renderer_getCapturedFrameSize();if(0===t)return null;const n=e.renderer_getCapturedFrameData(),s=e.renderer_getCapturedEntities(),i=e.renderer_getCapturedEntityCount(),o=e.renderer_getCapturedCameraCount(),r=e.HEAPU8,a=new DataView(r.buffer,n,76*t),l=new Uint32Array(r.buffer,s,i),c=[];for(let e=0;e<t;e++){const t=76*e,n=a.getUint32(t,!0),s=a.getUint32(t+4,!0),o=a.getUint8(t+8),r=a.getUint8(t+9),u=a.getUint8(t+10),h=a.getUint32(t+12,!0),d=a.getUint32(t+16,!0),f=a.getUint32(t+20,!0),p=a.getUint32(t+24,!0),m=a.getUint32(t+28,!0),g=a.getUint32(t+32,!0),_=a.getUint32(t+36,!0),y=a.getInt32(t+40,!0),x=a.getUint8(t+44),w=a.getInt32(t+48,!0),b=a.getInt32(t+52,!0),v=a.getInt32(t+56,!0),S=a.getInt32(t+60,!0),M=0!==a.getUint8(t+64),P=0!==a.getUint8(t+65),T=0!==a.getUint8(t+66),C=a.getInt32(t+68,!0),E=a.getUint8(t+72),A=[];for(let e=0;e<g&&_+e<i;e++)A.push(l[_+e]);c.push({index:n,cameraIndex:s,stage:o,type:r,blendMode:u,textureId:h,materialId:d,shaderId:f,vertexCount:p,triangleCount:m,entityCount:g,entityOffset:_,layer:y,flushReason:x,scissorX:w,scissorY:b,scissorW:v,scissorH:S,scissorEnabled:M,stencilWrite:P,stencilTest:T,stencilRef:C,textureSlotUsage:E,entities:A})}return{drawCalls:c,cameraCount:o}}(_r):null,hasCapturedData:()=>_r?.renderer_hasCapturedData()??!1,replayToDrawCall(e){_r&&function(e,t){e.renderer_replayToDrawCall(t)}(_r,e)},getSnapshotImageData:()=>_r?function(e){const t=e.renderer_getSnapshotSize();if(0===t)return null;const n=e.renderer_getSnapshotWidth(),s=e.renderer_getSnapshotHeight();if(0===n||0===s)return null;const i=e.renderer_getSnapshotPtr(),o=e.HEAPU8,r=new Uint8ClampedArray(o.buffer,i,t),a=new Uint8ClampedArray(t),l=4*n;for(let e=0;e<s;e++){const t=e*l,n=(s-1-e)*l;a.set(r.subarray(t,t+l),n)}return new ImageData(a,n,s)}(_r):null};let vr=null;function Sr(e){vr=e}function Mr(){vr=null}const Pr={enable(){vr?.gl_enableErrorCheck(!0)},disable(){vr?.gl_enableErrorCheck(!1)},check:e=>vr?.gl_checkErrors(e)??0,diagnose(){vr?.renderer_diagnose()}};class Tr{constructor(){this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null,this.preFlushCallbacks_=[]}setActiveScenes(e){this.activeScenes_=e}addPreFlushCallback(e){this.preFlushCallbacks_.push(e)}beginFrame(){br.beginFrame()}beginScreenCapture(){qo.screenStack&&qo.screenStack.enabledPassCount>0&&(qo.isInitialized()||qo.init(1,1),qo._applyScreenStack(),qo._beginScreenCapture())}endScreenCapture(){qo.screenStack&&qo.screenStack.enabledPassCount>0&&(qo._endScreenCapture(),qo._executeScreenPasses())}submitScene(e,t,n,s){br.updateTransforms(e),br.submitAll(e,0,n.x,n.y,n.w,n.h);for(const t of this.preFlushCallbacks_)t(e);br.flush(),this.executeDrawCallbacks(t,s)}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(br.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),br.beginFrame(),br.setViewport(0,0,s,i),br.clearBuffers(3),br.begin(n),this.submitScene(t,n,{x:0,y:0,w:s,h:i},o),br.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==qo.getStack(r);a&&(qo._applyForCamera(r),qo.resize(s.w,s.h),qo.setOutputViewport(s.x,s.y,s.w,s.h),qo.begin()),br.setViewport(s.x,s.y,s.w,s.h),br.setScissor(s.x,s.y,s.w,s.h,!0),br.clearBuffers(i),br.setScissor(0,0,0,0,!1),br.begin(n),this.submitScene(t,n,s,o),br.end(),a&&(qo.end(),qo._resetAfterCamera())}executeDrawCallbacks(e,t){const n=Mo;if(n.size>0){wo.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}wo.end();for(const e of s)To(e)}}}const Cr={None:0,SolidColor:1,Image:2,NineSlice:3},Er=ue("UIRenderer",{visualType:Cr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),Ar="__scene_transition_overlay__";class kr{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Rr{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Ie,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Po(e,t,this.instance_.config.name)}bindPostProcess(e,t){qo.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){qo.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Ie)){const n=this.app_.world.get(e,Ie);n.persistent=t,this.app_.world.insert(e,Ie,n)}}}class Ir{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())To(t);for(const t of e.postProcessBindings.keys())qo.unbind(t)}this.transition_&&(To(Ar),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise((n,s)=>{const i=t.duration??F.sceneTransitionDuration,o=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:i,color:o,targetScene:e,options:t,resolve:n,reject:s},Po(Ar,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;wo.setLayer(9999),wo.setDepth(9999),wo.rect({x:0,y:0},{x:2e4,y:2e4},{r:o.r,g:o.g,b:o.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{reject:t}=this.transition_;this.transition_=null,To(Ar),t(e)}})().catch(()=>{})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,To(Ar),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new kr(t);this.scenes_.set(e,n);const s=new Rr(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Yi)?this.app_.getResource(Yi):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new kr(t);this.scenes_.set(e,n);const s=new Rr(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Yi)?this.app_.getResource(Yi):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,Ie)){if(this.app_.world.get(e,Ie).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())To(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())qo.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Yi)&&(i.assetServer=this.app_.getResource(Yi));const o=await vi(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,Ie,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Br(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(Yi)?this.app_.getResource(Yi):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)hn.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,ye)){const t=n.get(e,ye);s.sprite=t.color.a,t.color.a=0,n.insert(e,ye,t),i=!0}if(n.has(e,Te)){const t=n.get(e,Te);s.spine=t.color.a,t.color.a=0,n.insert(e,Te,t),i=!0}if(n.has(e,Pe)){const t=n.get(e,Pe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Pe,t),i=!0}if(n.has(e,Er)){const t=n.get(e,Er);s.uiRenderer=t.color.a,t.color.a=0,n.insert(e,Er,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,ye)){const t=n.get(e,ye);t.color.a=s.sprite,n.insert(e,ye,t)}if(void 0!==s.spine&&n.has(e,Te)){const t=n.get(e,Te);t.color.a=s.spine,n.insert(e,Te,t)}if(void 0!==s.bitmapText&&n.has(e,Pe)){const t=n.get(e,Pe);t.color.a=s.bitmapText,n.insert(e,Pe,t)}if(void 0!==s.uiRenderer&&n.has(e,Er)){const t=n.get(e,Er);t.color.a=s.uiRenderer,n.insert(e,Er,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Fr=Ge(null,"SceneManager");function Br(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Fr).getSceneStatus(t)&&n._fn(...s)}}}const Ur=Nt([Je(Fr),Ke(et)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),zr={name:"SceneManager",build(e){const t=new Ir(e);e.insertResource(Fr,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Fr),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Ot.Startup,n),e.addSystemToSchedule(Ot.Last,Ur)}};class Lr{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new zt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=async()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(Ot.Last);else{await this.runSchedule(Ot.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(Ot.FixedPreUpdate),await this.runSchedule(Ot.FixedUpdate),await this.runSchedule(Ot.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(Ot.PreUpdate),await this.runSchedule(Ot.Update),await this.runSchedule(Ot.PostUpdate),await this.runSchedule(Ot.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new yt,this.resources_=new Qe;for(const e of Object.values(Ot))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Lr}getPlugin(e){return this.installed_plugins_.find(t=>t instanceof e)}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Ot.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ot.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}async waitForPhysics(){this.physicsInitPromise_?await this.physicsInitPromise_:console.warn("[ESEngine] No PhysicsPlugin installed, waitForPhysics() is a no-op")}get isPhysicsReady(){return null!=this.physicsModule_}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return at(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Fr).register(e),this}setInitialScene(e){return this.getResource(Fr).setInitial(e),this}async tick(e){if(this.runner_||(this.runner_=new Gt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(et)||this.resources_.insert(et,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_()),await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(Ot.Last);else{await this.runSchedule(Ot.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(Ot.FixedPreUpdate),await this.runSchedule(Ot.FixedUpdate),await this.runSchedule(Ot.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(Ot.PreUpdate),await this.runSchedule(Ot.Update),await this.runSchedule(Ot.PostUpdate),await this.runSchedule(Ot.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}async run(){this.running_||(this.running_=!0,this.runner_=new Gt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(et,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),await this.flushStartupSystems_(),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Co();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Mr,wr,jo,Bo,cn,_o];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){console.warn("[App] Shutdown despawn error:",e)}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}async flushStartupSystems_(){const e=this.systems_.get(Ot.Startup);0!==e.length&&(this.sortedSystemsCache_.delete(Ot.Startup),await this.runSchedule(Ot.Startup),e.length=0,this.sortedSystemsCache_.delete(Ot.Startup))}async runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{const t=this.runner_.run(e.system);t instanceof Promise&&await t}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(Ot[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(et);t.delta=e,t.elapsed+=e,t.frameCount++}}function Hr(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Dr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function $r(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case fe.FixedWidth:return o;case fe.FixedHeight:return r;case fe.Expand:return Math.max(o,r);case fe.Shrink:return Math.min(o,r);case fe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const Or=[];function Wr(e){if(e<Or.length)return Or[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return Or.push(t),t}function Vr(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,Ie);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,h=0;if(i.projectionType===he.Orthographic){if(h=i.orthoSize,l){h=$r(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=Xr(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=Yr(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=Gr(o.position.x,o.position.y,o.position.z),f=Wr(c.length);f.entity=e,f.viewProjection.set(Jr(a,d)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const Nr=new Float32Array(16);function Xr(e,t,n,s,i,o){const r=Nr;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const jr=new Float32Array(16);function Yr(e,t,n,s){const i=jr;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const qr=new Float32Array(16);function Gr(e,t,n){const s=qr;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}const Kr=new Float32Array(16);function Jr(e,t){const n=Kr;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const Zr={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},Qr={Simple:0,Sliced:1,Tiled:2,Filled:3},ea={Horizontal:0,Vertical:1},ta={Left:0,Right:1,Bottom:2,Top:3},na=Q("Image",{texture:H,color:{r:1,g:1,b:1,a:1},imageType:Qr.Simple,fillMethod:ea.Horizontal,fillOrigin:ta.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),sa=ue("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}}),ia=ue("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0});function oa(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,g=p+i.y):(p=h+n.y,g=d+s.y);const _=Math.max(0,m-f),y=Math.max(0,g-p);return{originX:f+r.x*_,originY:p+r.y*y,width:_,height:y,rect:{left:f,bottom:p,right:m,top:g}}}let ra=null,aa=null;function la(e,t){switch(e){case Zr.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Zr.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Zr.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function ca(e,t){switch(e){case Zr.RightToLeft:return{anchorMin:{x:1-t,y:.5},anchorMax:{x:1-t,y:.5}};case Zr.BottomToTop:return{anchorMin:{x:.5,y:t},anchorMax:{x:.5,y:t}};case Zr.TopToBottom:return{anchorMin:{x:.5,y:1-t},anchorMax:{x:.5,y:1-t}};default:return{anchorMin:{x:t,y:.5},anchorMax:{x:t,y:.5}}}}function ua(e,t,n,s){switch(e){case Zr.BottomToTop:case Zr.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function ha(e,t,n,s){if(!e.has(t,sa))return;const i=e.get(t,sa),o=la(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,sa,i)}function da(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}const fa=1.15,pa=.75;function ma(e,t,n,s){return t?n?{r:e.r*pa,g:e.g*pa,b:e.b*pa,a:e.a}:s?{r:Math.min(1,e.r*fa),g:Math.min(1,e.g*fa),b:Math.min(1,e.b*fa),a:e.a}:{...e}:{r:.5*e.r,g:.5*e.g,b:.5*e.b,a:.6*e.a}}function ga(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function _a(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(ga(r.charCodeAt(0))&&s.length>0&&ga(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!ga(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function ya(e){let t=1;for(;t<e;)t*=2;return t}function xa(e,t){let n=0,s=t;for(;e.has(s,Se);){const t=e.get(s,Se).entity;if(!e.valid(t))break;n++,s=t}return n}function wa(e,t){if(ra&&aa){const e=ra.getUIRectComputedWidth(aa,t);if(e>0)return e}return e.size.x}function ba(e,t){if(ra&&aa){const e=ra.getUIRectComputedHeight(aa,t);if(e>0)return e}return e.size.y}function va(e,t,n){ra&&aa&&ra.setUIRectSize(aa,e,t,n)}function Sa(e,t,n,s,i,o){if(!e.has(t,ye))return;const r=e.get(t,ye);let a,l;switch(n){case Zr.BottomToTop:case Zr.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,ye,r))}function Ma(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Pa(e,t){Ma(e,t,ia,{enabled:!0,blockRaycast:!0,raycastTarget:!0})}function Ta(e,t,n){0!==t&&e.valid(t)&&n(t)}function Ca(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a}function Ea(e,t,n){if(e.has(t,na)){const s=e.get(t,na);Ca(s.color,n)||(s.color=n,e.insert(t,na,s))}else if(e.has(t,ye)){const s=e.get(t,ye);Ca(s.color,n)||(s.color=n,e.insert(t,ye,s))}else if(e.has(t,Er)){const s=e.get(t,Er);Ca(s.color,n)||(s.color=n,e.insert(t,Er,s))}}function Aa(e,t,n){if(e.has(t,na)){const s=e.get(t,na);s.enabled!==n&&(s.enabled=n,e.insert(t,na,s))}else if(e.has(t,ye)){const s=e.get(t,ye);s.enabled!==n&&(s.enabled=n,e.insert(t,ye,s))}else if(e.has(t,Er)){const s=e.get(t,Er);s.enabled!==n&&(s.enabled=n,e.insert(t,Er,s))}}function ka(e,t){return{r:Math.min(1,e.r*t),g:Math.min(1,e.g*t),b:Math.min(1,e.b*t),a:e.a}}function Ra(e,t){return{r:e.r,g:e.g,b:e.b,a:t}}class Ia{constructor(){this.map_=new Map}get(e){return this.map_.get(e)}set(e,t){this.map_.set(e,t)}delete(e){this.map_.delete(e)}has(e){return this.map_.has(e)}cleanup(e){for(const[t]of this.map_)e.valid(t)||this.map_.delete(t)}ensureInit(e,t){let n=this.map_.get(e);return n||(n=t(),this.map_.set(e,n)),n}clear(){this.map_.clear()}[Symbol.iterator](){return this.map_[Symbol.iterator]()}}function Fa(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Ba=.1,Ua={r:.3,g:.5,b:.8,a:1},za={r:.9,g:.9,b:.9,a:1},La={r:.95,g:.95,b:.95,a:1},Ha={Left:0,Center:1,Right:2},Da={Top:0,Middle:1,Bottom:2},$a={Visible:0,Clip:1,Ellipsis:2},Oa=Q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ha.Left,verticalAlign:Da.Top,wordWrap:!0,overflow:$a.Visible,lineHeight:1.2});class Wa{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(F.textCanvasSize,F.textCanvasSize);const t=this.canvas.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("TextRenderer: failed to create 2D canvas context");this.ctx=t}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,ya(this.frameMaxW_)),e.height=Math.max(e.height,ya(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=ya(this.frameMaxW_),e.height=ya(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=_a(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===$a.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,ya(f)),s.height=Math.max(s.height,ya(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),_=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${_}, ${y})`,i&&e.overflow===$a.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case Da.Top:w=u;break;case Da.Middle:w=u+(p-2*u-x)/2;break;case Da.Bottom:w=p-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let s;switch(e.align){case Ha.Left:s=u;break;case Ha.Center:s=f/2;break;case Ha.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===$a.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Ha.Left:return"left";case Ha.Center:return"center";case Ha.Right:return"right"}}}const Va=Fa({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?wa(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?ba(e.uiRect,e.entity):0});function Na(e,t){e.has(t,Er)||e.insert(t,Er,{visualType:Cr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Xa{build(e){ae("Text",Oa);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Wa(t),s=e.world,i=new Map;e.addSystemToSchedule(Ot.PreUpdate,Nt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Oa));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Oa)){if(s.valid(e)&&s.has(e,Er)){const t=s.get(e,Er);t.texture=0,t.visualType=Cr.None,s.insert(e,Er,t)}i.delete(e)}const e=s.getEntitiesWithComponents([Oa]);for(const t of e){const e=s.get(t,Oa),o=s.has(t,sa)?s.get(t,sa):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Va.changed(a,r)){if(s.has(t,Er)&&0!==s.get(t,Er).texture)continue}Na(s,t);const l=o?{size:{x:wa(o,t),y:ba(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Er);u.texture=c.textureHandle,u.visualType=Cr.Image,u.color={r:1,g:1,b:1,a:1},u.uvOffset={x:0,y:0},u.uvScale={x:1,y:1},s.insert(t,Er,u),o&&va(t,c.width,c.height),i.set(t,Va.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const ja=new Xa,Ya=0,qa=ue("UIMask",{enabled:!0,mode:Ya});class Ga{build(e){ae("UIMask",qa)}}const Ka=new Ga;function Ja(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=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,i-n),h:Math.max(0,o-s)}}function Za(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],x=s*l-i*a,w=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*g-d*m,T=h*_-f*m,C=h*y-p*m,E=d*_-f*g,A=d*y-p*g,k=f*y-p*_;let R=x*k-w*A+b*E+v*C-S*T+M*P;return 0===R||(R=1/R,n[0]=(l*k-c*A+u*E)*R,n[1]=(o*A-i*k-r*E)*R,n[2]=(g*M-_*S+y*v)*R,n[3]=(f*S-d*M-p*v)*R,n[4]=(c*C-a*k-u*T)*R,n[5]=(s*k-o*C+r*T)*R,n[6]=(_*b-m*M-y*w)*R,n[7]=(h*M-f*b+p*w)*R,n[8]=(a*A-l*C+u*P)*R,n[9]=(i*C-s*A-r*P)*R,n[10]=(m*S-g*b+y*x)*R,n[11]=(d*b-h*S-p*x)*R,n[12]=(l*T-a*E-c*P)*R,n[13]=(s*E-i*T+o*P)*R,n[14]=(g*w-m*v-_*x)*R,n[15]=(h*v-d*w+f*x)*R),n}function Qa(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function el(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function tl(e,t){return 2*Math.atan2(e,t)}function nl(e,t,n,s,i,o,r,a,l,c){if(0===l&&1===c)return el(e,t,n,s,i,o,r,a);const u=tl(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,g=f*h+p*d+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}const sl=ue("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),il={Normal:0,Hovered:1,Pressed:2,Disabled:3},ol=Q("Button",{state:il.Normal,transition:null});class rl{constructor(){this.events_=[],this.entityTypeHandlers_=new Map,this.globalHandlers_=new Map,this.activeDispatches_=new Set,this.entityValidator_=null}on(e,t,n){if(void 0!==n){const s=e,i=t;let o=this.entityTypeHandlers_.get(s);o||(o=new Map,this.entityTypeHandlers_.set(s,o));let r=o.get(i);r||(r=[],o.set(i,r)),r.push(n);let a=!1;return()=>{if(a)return;a=!0;const e=o.get(i);if(e){const t=e.indexOf(n);-1!==t&&e.splice(t,1)}}}{const n=e,s=t;let i=this.globalHandlers_.get(n);i||(i=[],this.globalHandlers_.set(n,i)),i.push(s);let o=!1;return()=>{if(o)return;o=!0;const e=this.globalHandlers_.get(n);if(e){const t=e.indexOf(s);-1!==t&&e.splice(t,1)}}}}removeAll(e){this.entityTypeHandlers_.delete(e)}setEntityValidator(e){this.entityValidator_=e}emit(e,t,n){const s={entity:e,type:t,target:n??e,currentTarget:e,propagationStopped:!1,stopPropagation(){this.propagationStopped=!0}};this.events_.push(s);const i=`${e}:${t}`;return this.activeDispatches_.has(i)||(this.activeDispatches_.add(i),this.dispatchToHandlers_(s),this.activeDispatches_.delete(i)),s}emitBubbled(e,t,n,s){const i={entity:e,type:t,target:n,currentTarget:e,propagationStopped:!1,stopPropagation(){s.propagationStopped=!0}};this.events_.push(i);const o=`${e}:${t}`;this.activeDispatches_.has(o)||(this.activeDispatches_.add(o),this.dispatchToHandlers_(i),this.activeDispatches_.delete(o))}drain(){if(this.entityValidator_)for(const e of this.entityTypeHandlers_.keys())this.entityValidator_(e)||this.entityTypeHandlers_.delete(e);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)}dispatchToHandlers_(e){const t=this.entityTypeHandlers_.get(e.entity);if(t){const n=t.get(e.type);n&&this.invokeHandlers_([...n],e)}const n=this.globalHandlers_.get(e.type);n&&this.invokeHandlers_([...n],e)}invokeHandlers_(e,t){for(const n of e)try{n(t)}catch(e){console.error(`UIEvent handler error [${t.type}]:`,e)}}}const al=Ge(new rl,"UIEvents"),ll=Ge({generation:0},"UILayoutGeneration");class cl{build(e){ae("UIRect",sa),ae("UIRenderer",Er);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){ra=e,aa=t}(n,s);const i={generation:0};e.insertResource(ll,i);e.addSystemToSchedule(Ot.PreUpdate,Nt([Ke(en)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.transform_update(s),i.generation++)},{name:"UILayoutSystem"})),e.addSystemToSchedule(Ot.PostUpdate,Nt([Ke(en)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),i.generation++)},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(Ot.PostUpdate,Nt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const ul=new cl,hl=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(Za(t,e),n=!1),e)}}();function dl(e,t,n,s){const i=t.emit(n,s,n);!function(e,t,n){let s=t;for(;e.has(s,Se);){const t=e.get(s,Se).entity;if(!e.valid(t))break;if(n(t))return;s=t}}(e,n,o=>{if(i.propagationStopped)return!0;if(!e.has(o,ia))return!1;const r=e.get(o,ia);return r.enabled&&t.emitBubbled(o,s,n,i),r.blockRaycast})}class fl{build(e){ae("Interactable",ia),ae("Button",ol);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new rl;i.setEntityValidator(e=>t.valid(e)),e.insertResource(al,i);let o=null,r=null,a=NaN,l=NaN,c=-1;e.addSystemToSchedule(Ot.PreUpdate,Nt([Ke(Jt),Ke(en),Ke(ll)],(e,u,h)=>{if(i.drain(),Ps()&&!Es())return;const d=t.getEntitiesWithComponents([sl]);for(const e of d){const n=t.get(e,sl);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,sl,n))}if(!u.valid)return;const p=f(),m=e.mouseX*p,g=u.screenH-e.mouseY*p;hl.update(u.viewProjection);const _=Qa(m,g,hl.getInverse(u.viewProjection),u.vpX,u.vpY,u.vpW,u.vpH);u.worldMouseX=_.x,u.worldMouseY=_.y;const y=e.isMouseButtonDown(0),x=e.isMouseButtonPressed(0),w=e.isMouseButtonReleased(0),b=_.x!==a||_.y!==l,v=h.generation!==c,S=b||v||(x||w);a=_.x,l=_.y,c=h.generation;let M=o;if(S){n.uiHitTest_update(s,_.x,_.y,y,x,w);const e=n.uiHitTest_getHitEntity();M=4294967295===e?null:e}if(null===o||t.valid(o)||(o=null),o!==M){if(null!==o&&t.valid(o)&&t.has(o,sl)){const e=t.get(o,sl);e.hovered=!1,t.insert(o,sl,e),i.emit(o,"hover_exit")}if(null!==M){Ma(t,M,sl);const e=t.get(M,sl);e.hovered=!0,t.insert(M,sl,e),i.emit(M,"hover_enter")}o=M}if(x&&null!==M){const e=t.get(M,sl);e.pressed=!0,e.justPressed=!0,t.insert(M,sl,e),r=M,dl(t,i,M,"press")}if(w&&null!==r){if(t.valid(r)&&t.has(r,sl)){const e=t.get(r,sl);e.pressed=!1,e.justReleased=!0,t.insert(r,sl,e),dl(t,i,r,"release"),r===o&&dl(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const u=new Set;e.addSystemToSchedule(Ot.Update,Nt([],()=>{for(const e of u)t.valid(e)||u.delete(e);const e=t.getEntitiesWithComponents([ol]);for(const n of e){if(Ma(t,n,ia,{enabled:!0}),!t.has(n,sl))continue;const e=t.get(n,sl),s=t.get(n,ol),i=t.get(n,ia),o=!u.has(n),r=s.state;if(i.enabled?e.pressed?s.state=il.Pressed:e.hovered?s.state=il.Hovered:s.state=il.Normal:s.state=il.Disabled,o&&u.add(n),(o||r!==s.state)&&s.transition){const o=da(s.transition,i.enabled,e.pressed,e.hovered);Ea(t,n,o)}else if((o||r!==s.state)&&!s.transition&&t.has(n,na)){const s=ma(t.get(n,na).color,i.enabled,e.pressed,e.hovered);Ea(t,n,s)}}},{name:"ButtonSystem"}))}}const pl=new fl,ml=Q("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),gl=Q("Focusable",{tabIndex:0,isFocused:!1});class _l{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const yl=Ge(new _l,"FocusManager");class xl{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ae("TextInput",ml),Ps()&&!Es())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=t,s=e.world,i=new Map,o=h(F.textCanvasSize,64),r=o.getContext("2d",{willReadFrequently:!0});if(!r)return void console.warn("TextInputPlugin: failed to create 2D canvas context");const a=r;let l=0,c=0,u=!1,d=!0,f=0,p=0;const m=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!m)return;const g=m;function _(){const t=e.getResource(yl);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,ml)?n:null}const y=()=>{u||null===_()||S()},x=()=>{u=!0},w=()=>{u=!1,S()},b=t=>{const n=_();if(null===n)return;if("Escape"===t.key)return void M();const i=s.get(n,ml);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(al).emit(n,"submit"),void M()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,g.selectionStart=o,g.selectionEnd=o,i.dirty=!0,P())},v=()=>{const t=_();if(null!==t){const n=s.get(t,ml);n.focused=!1,n.dirty=!0;e.getResource(yl).blur()}};function S(){const t=_();if(null===t)return;const n=s.get(t,ml);if(n.readOnly)return;let i=g.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),g.value=i),i!==n.value){n.value=i;e.getResource(al).emit(t,"change")}n.cursorPos=g.selectionStart??i.length,n.dirty=!0,P()}function M(){const t=_();if(null!==t){const e=s.get(t,ml);e.focused=!1,e.dirty=!0}e.getResource(yl).blur(),g.blur()}function P(){d=!0,f=0}g.addEventListener("input",y),g.addEventListener("compositionstart",x),g.addEventListener("compositionend",w),g.addEventListener("keydown",b),g.addEventListener("blur",v),this.cleanupListeners_=()=>{g.removeEventListener("input",y),g.removeEventListener("compositionstart",x),g.removeEventListener("compositionend",w),g.removeEventListener("keydown",b),g.removeEventListener("blur",v),g.remove();const e=n.getResourceManager();for(const t of i.values())e.releaseTexture(t);i.clear(),0!==l&&(n._free(l),l=0,c=0)};let T=null;function C(e,t,r,u){(o.width<r||o.height<u)&&(o.width=ya(Math.max(o.width,r)),o.height=ya(Math.max(o.height,u))),a.clearRect(0,0,o.width,o.height);const h=t.backgroundColor;a.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,a.fillRect(0,0,r,u),a.save(),a.beginPath(),a.rect(t.padding,0,r-2*t.padding,u),a.clip(),a.font=`${t.fontSize}px ${t.fontFamily}`,a.textBaseline="top",a.textAlign="left";const f=0===t.value.length,p=f?t.placeholder:t.password?"●".repeat(t.value.length):t.value,m=f?t.placeholderColor:t.color;a.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*t.fontSize),_=t.padding;if(t.multiline){const e=_a(a,p,r-2*_);let t=_;for(const n of e)a.fillText(n,_,t),t+=g}else{const e=(u-t.fontSize)/2;a.fillText(p,_,e)}if(t.focused&&d){const e=t.password?"●".repeat(t.cursorPos):t.value.substring(0,t.cursorPos);let n,s,i;if(t.multiline){const e=_a(a,t.value,r-2*_);let o=0,l=0,c=0;for(let n=0;n<e.length;n++){const s=e[n].length;if(o+s>=t.cursorPos){l=n,c=t.cursorPos-o;break}o+=s,n<e.length-1&&o<t.value.length&&"\n"===t.value[o]&&o++,l=n+1,c=0}const u=l<e.length?e[l].substring(0,c):"";n=_+a.measureText(u).width,s=_+l*g,i=g}else n=_+a.measureText(e).width,s=(u-t.fontSize)/2,i=t.fontSize;a.fillStyle=`rgba(${Math.round(255*t.color.r)}, ${Math.round(255*t.color.g)}, ${Math.round(255*t.color.b)}, ${t.color.a})`,a.fillRect(n,s,2,i)}a.restore();const y=a.getImageData(0,0,r,u),x=new Uint8Array(y.data.buffer),w=n.getResourceManager();x.length>c&&(0!==l&&n._free(l),l=n._malloc(x.length),c=x.length),n.HEAPU8.set(x,l);const b=i.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(r,u,l,x.length,1,!0);i.set(e,v);const S=s.get(e,Er);S.texture=v,S.visualType=Cr.Image,S.uvOffset={x:0,y:0},S.uvScale={x:1,y:1},S.color={r:1,g:1,b:1,a:1},S.enabled=!0,s.insert(e,Er,S)}e.addSystemToSchedule(Ot.Update,Nt([Ke(yl)],e=>{const t=s.getEntitiesWithComponents([ml]);for(const e of t)Ma(s,e,gl,{tabIndex:0,isFocused:!1}),Ma(s,e,ia,{enabled:!0,blockRaycast:!0});const n=_();if(n!==T){if(null!==T&&s.valid(T)&&s.has(T,ml)){const e=s.get(T,ml);e.focused=!1,e.dirty=!0,g.blur()}null!==n&&function(e){const t=s.get(e,ml);t.readOnly||(t.focused=!0,t.dirty=!0,g.value=t.value,g.selectionStart=t.cursorPos,g.selectionEnd=t.cursorPos,g.focus(),P())}(n),T=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(Ot.PreUpdate,Nt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let t=0===p?0:(e-p)/1e3;p=e,t=Math.min(t,.1);const o=_();if(null!==o&&(f+=t,f>=.5)){f-=.5,d=!d;s.get(o,ml).dirty=!0}const r=n.getResourceManager();for(const[e,t]of i)s.valid(e)&&s.has(e,ml)||(r.releaseTexture(t),i.delete(e));const a=s.getEntitiesWithComponents([ml,sa]);for(const e of a){const t=s.get(e,ml);if(!t.dirty)continue;const n=s.get(e,sa),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(s.has(e,Er)||s.insert(e,Er,{visualType:Cr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),C(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const wl=new xl,bl=Fa({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?wa(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?ba(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});function vl(e,t){e.has(t,Er)||e.insert(t,Er,{visualType:Cr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Sl{build(e){ae("Image",na);const t=e.world,n=new Map;e.addSystemToSchedule(Ot.PreUpdate,Nt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,na)||n.delete(e);const e=t.getEntitiesWithComponents([na]);for(const s of e){const e=t.get(s,na),i=t.has(s,sa)?t.get(s,sa):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&t.has(s,Er)&&!bl.changed(r,o))continue;vl(t,s);const a=t.get(s,Er);if(!e.enabled){a.enabled=!1,t.insert(s,Er,a),n.set(s,bl.take(o));continue}a.enabled=!0,a.texture=e.texture,a.color={r:e.color.r,g:e.color.g,b:e.color.b,a:e.color.a},a.material=e.material,a.uvOffset={x:0,y:0},a.uvScale={x:1,y:1};if(e.texture!==H&&0!==e.texture?e.imageType===Qr.Sliced?a.visualType=Cr.NineSlice:a.visualType=Cr.Image:a.visualType=Cr.SolidColor,e.imageType===Qr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));i&&wa(i,s),i&&ba(i,s),e.fillMethod===ea.Horizontal?(e.fillOrigin===ta.Left||(a.uvOffset={x:1-t,y:0}),a.uvScale={x:t,y:1}):(e.fillOrigin===ta.Bottom||(a.uvOffset={x:0,y:1-t}),a.uvScale={x:1,y:t})}else if(e.imageType===Qr.Tiled){const t=i?wa(i,s):0,n=i?ba(i,s):0;e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale={x:t/e.tileSize.x,y:n/e.tileSize.y})}t.insert(s,Er,a),n.set(s,bl.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Ml=new Sl,Pl=Q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null,onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1}},{entityFields:["graphicEntity","group"]}),Tl=Q("ToggleGroup",{allowSwitchOff:!1});function Cl(e,t,n){if(!e.has(t,Er))return;const s=e.get(t,Er);s.color.r===n.r&&s.color.g===n.g&&s.color.b===n.b&&s.color.a===n.a||(s.color=n,e.insert(t,Er,s))}function El(e,t,n){if(!e.has(t,Er))return;const s=e.get(t,Er);s.enabled!==n&&(s.enabled=n,e.insert(t,Er,s))}class Al{build(e){ae("Toggle",Pl),ae("ToggleGroup",Tl);const t=e.world,n=new Set;e.addSystemToSchedule(Ot.Update,Nt([Ke(al)],e=>{const s=t.getEntitiesWithComponents([Pl]);if(!Ps()||Es()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Pl);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Pl,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Pl);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Ma(t,n,ia,{enabled:!0}),!t.has(n,sl))continue;const s=t.get(n,sl),i=t.get(n,Pl),r=t.get(n,ia);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,Tl);if(i.isOn&&r){if(!t.get(s,Tl).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Pl,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Pl);i.isOn&&(i.isOn=!1,t.insert(s,Pl,i),e.emit(s,"change"))}}e.emit(n,"change")}let a;if(i.transition)a=da(i.transition,r.enabled,s.pressed,s.hovered);else{a=ma(i.isOn?i.onColor:i.offColor,r.enabled,s.pressed,s.hovered)}Cl(t,n,a)}}for(const e of s){const n=t.get(e,Pl);Ta(t,n.graphicEntity,e=>{El(t,e,n.isOn)})}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const kl=new Al,Rl=Zr,Il=Q("ProgressBar",{value:0,fillEntity:0,direction:Zr.LeftToRight},{entityFields:["fillEntity"]});class Fl{build(e){ae("ProgressBar",Il);const t=e.world;e.addSystemToSchedule(Ot.PreUpdate,Nt([],()=>{const e=t.getEntitiesWithComponents([Il,sa]);for(const n of e){const e=t.get(n,Il),s=Math.max(0,Math.min(1,e.value));Ta(t,e.fillEntity,n=>{ha(t,n,e.direction,s)})}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Bl=new Fl,Ul=Q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),zl=Q("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});function Ll(e,t,n,s){if(!e.has(t,Se))return{x:n,y:s};const i=e.get(t,Se).entity;if(!e.valid(i)||!e.has(i,me))return{x:n,y:s};const o=e.get(i,me),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=tl(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}class Hl{build(e){ae("Draggable",Ul),ae("DragState",zl);const t=e.world,n=e.getResource(al);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(Ot.PreUpdate,Nt([Ke(Jt),Ke(en)],(e,r)=>{if(Ps()&&!Es())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ul,sl]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,Ul).enabled)continue;if(t.get(s,sl).hovered){let e=0;t.has(s,ye)&&(e=t.get(s,ye).layer);const i=xa(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,zl)||t.insert(n,zl);const e=t.get(n,zl),o=t.get(n,me);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,zl)){t.get(s,zl).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,Ul);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,zl).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,zl))return void(o=null);const s=t.get(o,zl),i=t.get(o,Ul),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,sa)){const e=t.get(o,sa),n=Ll(t,o,s.deltaWorld.x,s.deltaWorld.y);e.offsetMin.x+=n.x,e.offsetMin.y+=n.y,t.insert(o,sa,e)}else if(t.has(o,me)){const e=Ll(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,me);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,me,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const Dl=new Hl,$l=Q("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1},{entityFields:["contentEntity"]});function Ol(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function Wl(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class Vl{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){ae("ScrollView",$l);const t=e.world,n=new Ia,s={x:0,y:0};e.addSystemToSchedule(Ot.PostUpdate,Nt([Ke(Jt),Ke(en),Ke(et)],(e,i,o)=>{const r=Ps()&&!Es(),a=Math.min(o.delta,.05);n.cleanup(t),i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([$l,sa]);for(const o of l){Ma(t,o,qa,{enabled:!0,mode:Ya});const l=t.get(o,$l),c=t.get(o,sa),u=n.ensureInit(o,()=>({isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN})),h=wa(c,o),d=ba(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Me)){const e=t.get(l.contentEntity,Me).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,me))continue;const e=t.get(r,me);let a=0,l=0,c=.5,u=.5;if(t.has(r,sa)){const e=t.get(r,sa);a=wa(e,r)||e.size.x,l=ba(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,ye)){const e=t.get(r,ye);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<n&&(n=h),d>s&&(s=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Ma(t,o,ia,{enabled:!0,blockRaycast:!0});const n=t.has(o,sl)?t.get(o,sl):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=Ol(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=Ol(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Ol(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Ol(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=Wl(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Ba&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Ba?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=Wl(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Ba&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Ba?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}Ta(t,l.contentEntity,e=>{if(!t.has(e,me))return;const n=t.get(e,me),s=n.position.x,i=n.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(i-u.lastAppliedY)>.01)&&(u.contentBaseY=i),n.position.x=u.contentBaseX-l.scrollX,n.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=n.position.x,u.lastAppliedY=n.position.y,t.insert(e,me,n)})}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{n.clear()}}}const Nl=new Vl,Xl=Zr,jl=Q("Slider",{value:0,minValue:0,maxValue:1,direction:Zr.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1},{entityFields:["fillEntity","handleEntity"]});function Yl(e,t,n,s,i,o){const r=wa(s,i)*n.worldScale.x,a=ba(s,i)*n.worldScale.y,l=tl(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-n.worldPosition.x,d=t-n.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case Zr.LeftToRight:return r>0?(f-m)/r:0;case Zr.RightToLeft:return r>0?1-(f-m)/r:0;case Zr.BottomToTop:return a>0?(p-g)/a:0;case Zr.TopToBottom:return a>0?1-(p-g)/a:0}}function ql(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Zr.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=.5,e.anchorMax.x=n,e.anchorMax.y=.5;break;case Zr.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=.5,e.anchorMax.x=1-n,e.anchorMax.y=.5;break;case Zr.BottomToTop:e.anchorMin.x=.5,e.anchorMin.y=n,e.anchorMax.x=.5,e.anchorMax.y=n;break;case Zr.TopToBottom:e.anchorMin.x=.5,e.anchorMin.y=1-n,e.anchorMax.x=.5,e.anchorMax.y=1-n}}class Gl{build(e){ae("Slider",jl);const t=e.world;e.addSystemToSchedule(Ot.PreUpdate,Nt([Ke(Jt),Ke(en),Ke(al)],(e,n,s)=>{if(!n.valid)return;const i=t.getEntitiesWithComponents([jl,sa]);for(const o of i){const i=t.get(o,jl),r=t.get(o,sa);if(!Ps()||Es()){if(t.has(o,me)){Ma(t,o,ia,{enabled:!0,blockRaycast:!0}),Ta(t,i.handleEntity,e=>{Ma(t,e,ia,{enabled:!0,blockRaycast:!1})});const a=t.get(o,me);let l=!1;if(t.has(o,sl)&&(l=t.get(o,sl).pressed),Ta(t,i.handleEntity,e=>{!l&&t.has(e,sl)&&(l=t.get(e,sl).pressed)}),l&&e.isMouseButtonDown(0)){let e=Yl(n.worldMouseX,n.worldMouseY,a,r,o,i.direction);e=Math.max(0,Math.min(1,e));let l=i.minValue+e*(i.maxValue-i.minValue);i.wholeNumbers&&(l=Math.round(l));const c=i.value;i.value=Math.max(i.minValue,Math.min(i.maxValue,l)),t.insert(o,jl,i),i.value!==c&&s.emit(o,"change")}}}const a=i.maxValue-i.minValue,l=a>0?(i.value-i.minValue)/a:0;Ta(t,i.fillEntity,e=>{ha(t,e,i.direction,l)}),Ta(t,i.handleEntity,e=>{if(!t.has(e,sa))return;const n=t.get(e,sa);ql(n,i.direction,l),t.insert(e,sa,n)})}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Kl=new Gl;class Jl{build(e){ae("Focusable",gl);const t=e.world,n=new _l;e.insertResource(yl,n),e.addSystemToSchedule(Ot.Update,Nt([Ke(Jt),Ke(al)],(e,s)=>{if(Ps()&&!Es())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([gl]);for(const e of i){if(!t.has(e,sl))continue;t.get(e,sl).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,ia)){if(!t.get(n,ia).enabled)continue}const s=t.get(n,gl);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,gl)){t.get(i,gl).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,gl).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Zl=new Jl,Ql=Q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function ec(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class tc{build(e){ae("SafeArea",Ql);const t=e.world;let n=ec(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=ec(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=ec(),s=!0});e.addSystemToSchedule(Ot.PreUpdate,Nt([Ke(en)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Ql,sa]);for(const e of u){const s=t.get(e,Ql),i=t.get(e,sa),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,sa,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const nc=new tc,sc=Q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let ic=null;function oc(e,t){if(!ic)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=ic.get(e);n?n.renderer=t:ic.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class rc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null),ic=null}build(e){ae("ListView",sc);const t=e.world,n=new Map;ic=n,e.addSystemToSchedule(Ot.PostUpdate,Nt([Ke(Jt)],e=>{const s=Ps()&&!Es();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([sc,sa]);for(const o of i){Ma(t,o,ia,{enabled:!0,blockRaycast:!0}),Ma(t,o,qa,{enabled:!0,mode:Ya});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,sc),a=t.get(o,sa),l=ba(a,o),c=wa(a,o);if(!s){const n=t.has(o,sl)?t.get(o,sl):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<d;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Re,{value:`ListItem_${e}`}),t.insert(n,sa,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,me)){const s=t.get(n,me);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,me,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{for(const[,e]of n)for(const n of e.itemEntities.values())t.valid(n)&&t.despawn(n);n.clear()}}}const ac=new rc,lc=Q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0},{entityFields:["listEntity","labelEntity"]});class cc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){ae("Dropdown",lc);const t=e.world,n=new Map,s=new Set;function i(e){Ta(t,e,e=>{if(!t.has(e,me))return;const n=t.get(e,me);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,me,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})})}function o(e){if(t.has(e,Er)){const n=t.get(e,Er);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Ea(t,e,{...za})}else if(t.has(e,ye)){const n=t.get(e,ye);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Ea(t,e,{...za})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;h(i,!0),u(s);let o=0;if(t.has(e,sa)){const n=t.get(e,sa);o=wa(n,e)||n.size.x}else if(t.has(e,ye)){o=t.get(e,ye).size.x}s.ddWidth=o;const r=30*n.options.length;t.insert(i,sa,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:r},pivot:{x:.5,y:1}}),t.insert(i,Er,{visualType:Cr.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn();t.insert(r,Re,{value:`Option_${e}`}),t.insert(r,sa,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:30*-e},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:1}}),t.insert(r,me,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,Er,{visualType:Cr.SolidColor,texture:0,color:{...La},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),t.insert(r,ia,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const a=t.spawn();t.insert(a,me,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(a,Oa,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Ha.Left,verticalAlign:Da.Middle,wordWrap:!1,overflow:$a.Clip,lineHeight:1.2}),t.insert(a,sa,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:.5}}),t.setParent(a,r),s.textEntities.push(a)}d(s)}function a(e,t,n){t.isOpen=!1,u(n),h(t.listEntity,!1)}function l(e,t,n,s,i){t.selectedIndex=s,a(0,t,n),i.emit(e,"change")}function c(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Oa))return;const s=t.get(n,Oa);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,Oa,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function u(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function h(e,n){Ta(t,e,e=>{t.has(e,ia)&&t.insert(e,ia,{enabled:n,blockRaycast:!0,raycastTarget:!0}),Aa(t,e,n)})}function d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s))continue;const i=n===e.highlightIndex?{...Ua}:{...La};Ea(t,s,i)}}function f(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,sl))continue;if(t.get(n,sl).hovered)return!0}return!1}e.addSystemToSchedule(Ot.Update,Nt([Ke(Jt),Ke(al)],(e,p)=>{for(const[e,i]of n)t.valid(e)||(u(i),n.delete(e),s.delete(e));const m=Ps()&&!Es(),g=t.getEntitiesWithComponents([lc]);for(const u of g){const g=t.get(u,lc);let _=n.get(u);if(_||(_={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(u,_)),i(g.listEntity),s.has(u)||(o(u),s.add(u)),g.isOpen||h(g.listEntity,!1),c(g),m)continue;Ma(t,u,ia,{enabled:!0,blockRaycast:!0});const y=t.has(u,sl)?t.get(u,sl):null;if(y?.justPressed&&(g.isOpen?a(u,g,_):r(u,g,_)),g.isOpen){for(let e=0;e<_.optionEntities.length;e++){const n=_.optionEntities[e];if(!t.valid(n)||!t.has(n,sl))continue;if(t.get(n,sl).justPressed){l(u,g,_,e,p);break}}let n=-1;for(let e=0;e<_.optionEntities.length;e++){const s=_.optionEntities[e];if(!t.valid(s)||!t.has(s,sl))continue;if(t.get(s,sl).hovered){n=e;break}}n>=0&&n!==_.highlightIndex&&(_.highlightIndex=n,d(_)),e.isKeyPressed("ArrowDown")?(_.highlightIndex>=g.options.length-1?_.highlightIndex=0:_.highlightIndex++,d(_)):e.isKeyPressed("ArrowUp")?(_.highlightIndex<=0?_.highlightIndex=g.options.length-1:_.highlightIndex--,d(_)):e.isKeyPressed("Enter")&&_.highlightIndex>=0?l(u,g,_,_.highlightIndex,p):e.isKeyPressed("Escape")&&a(u,g,_),e.isMouseButtonPressed(0)&&(y?.hovered||f(_)||a(u,g,_))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]}),this.cleanup_=()=>{for(const[,e]of n)u(e);n.clear(),s.clear()}}}const uc=new cc,hc=ue("LayoutGroup",{direction:0,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:0,reverseOrder:!1});class dc{build(e){ae("LayoutGroup",hc)}}const fc=new dc,pc=0,mc=1,gc=0,_c=1,yc=0,xc=0,wc=3,bc=ue("FlexContainer",{direction:pc,wrap:gc,justifyContent:yc,alignItems:wc,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0}}),vc=ue("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class Sc{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Ot.PostUpdate,Nt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Mc=new Sc,Pc={primary:{r:.25,g:.56,b:.96,a:1},secondary:{r:.4,g:.4,b:.4,a:1},background:{r:.08,g:.08,b:.08,a:1},surface:{r:.14,g:.14,b:.14,a:1},error:{r:.9,g:.2,b:.2,a:1},text:{r:.93,g:.93,b:.93,a:1},textSecondary:{r:.6,g:.6,b:.6,a:1},border:{r:.3,g:.3,b:.3,a:1},fontFamily:"Arial",fontSize:{xs:10,sm:12,md:14,lg:18,xl:24},spacing:{xs:4,sm:8,md:12,lg:16,xl:24},button:{height:36,color:{r:.25,g:.25,b:.25,a:1},textColor:{r:.93,g:.93,b:.93,a:1},transition:{normalColor:{r:.25,g:.25,b:.25,a:1},hoveredColor:{r:.3,g:.3,b:.3,a:1},pressedColor:{r:.18,g:.18,b:.18,a:1},disabledColor:{r:.15,g:.15,b:.15,a:.6}}},slider:{trackHeight:16,trackColor:{r:.15,g:.15,b:.15,a:1},fillColor:{r:.25,g:.56,b:.96,a:1},handleSize:24,handleColor:{r:1,g:1,b:1,a:1}},toggle:{size:{x:24,y:24},onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1},checkColor:{r:1,g:1,b:1,a:1}},input:{height:36,backgroundColor:{r:.15,g:.15,b:.15,a:1},textColor:{r:1,g:1,b:1,a:1},placeholderColor:{r:.6,g:.6,b:.6,a:1},fontSize:16,padding:6},dropdown:{height:32,backgroundColor:{r:.2,g:.2,b:.2,a:1},itemHeight:28},panel:{backgroundColor:{r:.14,g:.14,b:.14,a:1},padding:12},scrollView:{backgroundColor:{r:.1,g:.1,b:.1,a:1}}},Tc=Ge(null,"UITheme");let Cc=null;function Ec(e){e.hasResource(Tc)&&(Cc=e.getResource(Tc))}function Ac(){return Cc??Pc}function kc(e,t){const n=e.spawn();if(t.name&&e.insert(n,Re,{value:t.name}),e.insert(n,me,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},...t.transform}),t.rect&&e.insert(n,sa,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:0,y:0},pivot:{x:.5,y:.5},...t.rect}),t.renderer&&e.insert(n,Er,{visualType:Cr.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0,...t.renderer}),t.interactable&&e.insert(n,ia,{enabled:!0,blockRaycast:!0,raycastTarget:!0,...t.interactable}),t.text){const s=Ac();e.insert(n,Oa,{content:"",fontFamily:s.fontFamily,fontSize:s.fontSize.md,color:{r:1,g:1,b:1,a:1},align:Ha.Left,verticalAlign:Da.Top,wordWrap:!1,overflow:0,lineHeight:1.2,...t.text})}if(t.image&&e.insert(n,na,{...na._default,...t.image}),t.flex&&e.insert(n,bc,{direction:pc,wrap:gc,justifyContent:yc,alignItems:wc,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0},...t.flex}),t.flexItem&&e.insert(n,vc,{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,...t.flexItem}),t.mask&&e.insert(n,qa,{enabled:!0,mode:Ya,...t.mask}),t.components)for(const[s,i]of t.components)e.insert(n,s,i);return t.parent&&e.setParent(n,t.parent),n}function Rc(e,t={}){const n=Ac(),{text:s="Button",fontSize:i=n.fontSize.md,size:o={x:120,y:n.button.height},color:r=n.button.color,textColor:a=n.button.textColor,transition:l=null,parent:c}=t,u=kc(e,{name:"ButtonLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:s,fontSize:i,color:a,align:Ha.Center,verticalAlign:Da.Middle}}),h=kc(e,{name:"Button",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Cr.SolidColor,color:r},interactable:{enabled:!0},components:[[ol,{state:0,transition:l}]]});if(e.setParent(u,h),t.events){if(t.onClick){const e=t.onClick;t.events.on(h,"click",()=>e(h))}if(t.onHover){const e=t.onHover;t.events.on(h,"hover_enter",()=>e(h))}}return h}function Ic(e,t={}){const n=Ac(),{value:s=0,minValue:i=0,maxValue:o=1,direction:r=Zr.LeftToRight,size:a={x:200,y:n.slider.trackHeight},trackColor:l=n.slider.trackColor,fillColor:c=n.slider.fillColor,handleSize:u={x:n.slider.handleSize,y:n.slider.handleSize},handleColor:h=n.slider.handleColor,wholeNumbers:d=!1,parent:f}=t,p=kc(e,{name:"SliderFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Cr.SolidColor,color:c}}),m=kc(e,{name:"SliderHandle",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:u},renderer:{visualType:Cr.SolidColor,color:h},interactable:{enabled:!0,blockRaycast:!0},components:[[Ul,{enabled:!0,dragThreshold:5,lockX:!1,lockY:!0}]]}),g=kc(e,{name:"Slider",parent:f,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Cr.SolidColor,color:l},interactable:{enabled:!0,blockRaycast:!0},components:[[jl,{value:s,minValue:i,maxValue:o,direction:r,wholeNumbers:d,fillEntity:p,handleEntity:m}]]});if(e.setParent(p,g),e.setParent(m,g),t.onChange&&t.events){const n=t.onChange;t.events.on(g,"change",()=>{const t=e.get(g,jl);n(t.value,g)})}return g}function Fc(e,t={}){const n=Ac(),{isOn:s=!0,size:i=n.toggle.size,onColor:o=n.toggle.onColor,offColor:r=n.toggle.offColor,checkSize:a={x:.58*n.toggle.size.x,y:.58*n.toggle.size.y},checkColor:l=n.toggle.checkColor,group:c=0,transition:u=null,label:h,parent:d}=t,f=kc(e,{name:"ToggleCheck",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Cr.SolidColor,color:l}}),p=kc(e,{name:"Toggle",parent:d,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Cr.SolidColor,color:s?o:r},interactable:{enabled:!0},components:[[Pl,{isOn:s,graphicEntity:f,group:c,transition:u,onColor:o,offColor:r}]]});if(e.setParent(f,p),h&&kc(e,{name:"ToggleLabel",parent:p,rect:{anchorMin:{x:1,y:0},anchorMax:{x:1,y:1},offsetMin:{x:8,y:0},size:{x:100,y:0}},text:{content:h,fontSize:n.fontSize.md,align:Ha.Left,verticalAlign:Da.Middle}}),t.onChange&&t.events){const n=t.onChange;t.events.on(p,"change",()=>{const t=e.get(p,Pl);n(t.isOn,p)})}return p}function Bc(e,t={}){const n=Ac(),{value:s=0,size:i={x:200,y:n.slider.trackHeight},direction:o=Zr.LeftToRight,trackColor:r=n.slider.trackColor,fillColor:a=n.primary,parent:l}=t,c=kc(e,{name:"ProgressFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Cr.SolidColor,color:a}}),u=kc(e,{name:"ProgressBar",parent:l,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Cr.SolidColor,color:r},components:[[Il,{value:s,fillEntity:c,direction:o}]]});return e.setParent(c,u),u}function Uc(e,t={}){const n=Ac(),{size:s={x:300,y:400},contentSize:i={x:300,y:800},horizontal:o=!1,vertical:r=!0,elastic:a=!0,mask:l=!0,parent:c}=t,u=kc(e,{name:"ScrollContent",rect:{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},size:{x:i.x,y:i.y},pivot:{x:.5,y:1}}}),h=kc(e,{name:"ScrollView",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:s},renderer:{visualType:Cr.SolidColor,color:n.scrollView.backgroundColor},mask:l?{mode:Ya,enabled:!0}:void 0,components:[[$l,{contentEntity:u,horizontalEnabled:o,verticalEnabled:r,contentWidth:i.x,contentHeight:i.y,elastic:a,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,wheelSensitivity:.1}]]});return e.setParent(u,h),h}function zc(e,t={}){const n=Ac(),{placeholder:s="",value:i="",size:o={x:200,y:n.input.height},fontSize:r=n.input.fontSize,backgroundColor:a=n.input.backgroundColor,textColor:l=n.input.textColor,maxLength:c=0,multiline:u=!1,password:h=!1,parent:d}=t,f=kc(e,{name:"TextInput",parent:d,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Cr.SolidColor,color:a},interactable:{enabled:!0},components:[[ml,{value:i,placeholder:s,fontSize:r,fontFamily:n.fontFamily,color:l,backgroundColor:a,placeholderColor:n.input.placeholderColor,padding:n.input.padding,maxLength:c,multiline:u,password:h,readOnly:!1,focused:!1,cursorPos:i.length,dirty:!0}],[gl,{tabIndex:0,isFocused:!1}]]});if(t.events){if(t.onChange){const n=t.onChange;t.events.on(f,"change",()=>{const t=e.get(f,ml);n(t.value,f)})}if(t.onSubmit){const n=t.onSubmit;t.events.on(f,"submit",()=>{const t=e.get(f,ml);n(t.value,f)})}}return f}function Lc(e,t){const n=Ac(),{options:s,selectedIndex:i=-1,size:o={x:160,y:n.dropdown.height},fontSize:r=n.fontSize.md,parent:a}=t,l=kc(e,{name:"DropdownLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:(i>=0?s[i]:s[0])??"",fontSize:r,align:Ha.Left,verticalAlign:Da.Middle}}),c=kc(e,{name:"DropdownList",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},size:{x:o.x,y:Math.min(s.length*n.dropdown.itemHeight,200)},pivot:{x:.5,y:1}},renderer:{visualType:Cr.SolidColor,color:n.surface},mask:{mode:Ya,enabled:!0}}),u=kc(e,{name:"Dropdown",parent:a,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Cr.SolidColor,color:n.dropdown.backgroundColor},interactable:{enabled:!0},components:[[lc,{options:s,selectedIndex:i,isOpen:!1,listEntity:c,labelEntity:l}]]});if(e.setParent(l,u),e.setParent(c,u),t.onChange&&t.events){const n=t.onChange;t.events.on(u,"change",()=>{const t=e.get(u,lc);n(t.selectedIndex,u)})}return u}function Hc(e,t){const n=Ac();return kc(e,{name:"Label",parent:t.parent,rect:t.size?{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size}:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:t.text,fontSize:t.fontSize??n.fontSize.md,color:t.color??n.text,align:t.align??Ha.Left,verticalAlign:t.verticalAlign??Da.Middle}})}function Dc(e,t={}){const n=Ac();return kc(e,{name:"Panel",parent:t.parent,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size??{x:300,y:200}},renderer:{visualType:Cr.SolidColor,color:t.color??n.panel.backgroundColor}})}function $c(e,t={}){return kc(e,{name:"FlexRow",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:pc,wrap:t.wrap?_c:gc,justifyContent:t.justifyContent??yc,alignItems:t.alignItems??xc,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}function Oc(e,t={}){return kc(e,{name:"FlexColumn",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:mc,wrap:t.wrap?_c:gc,justifyContent:t.justifyContent??yc,alignItems:t.alignItems??xc,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}const Wc={button:Rc,slider:Ic,toggle:Fc,textInput:zc,dropdown:Lc,progressBar:Bc,label:Hc,panel:Dc,flexRow:$c,flexColumn:Oc,scrollView:Uc};const Vc={spawn:kc,destroy:function e(t,n){if(t.valid(n)){if(t.has(n,Me)){const s=[...t.get(n,Me).entities];for(const n of s)e(t,n)}t.despawn(n)}},build:function e(t,n,s){let i,o;if("element"===n.type)i=kc(t,{...n,parent:s}),o=i;else{if(i=(0,Wc[n.type])(t,{...n.options??{},parent:s}),"scrollView"===n.type){o=t.get(i,$l).contentEntity}else o=i}const r=n.children;if(r&&o)for(const n of r)e(t,n,o);return n.ref&&n.ref(i),i},label:Hc,panel:Dc,button:Rc,slider:Ic,toggle:Fc,scrollView:Uc,textInput:zc,dropdown:Lc,progressBar:Bc,flexRow:$c,flexColumn:Oc};async function Nc(e,t,n){const s=e.getResource(Fr);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}class Xc{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let s,i;if("string"==typeof e){const t=(new TextEncoder).encode(e);i=t.length,s=this.raw_._malloc(i+1),this.raw_.HEAPU8.set(t,s),this.raw_.HEAPU8[s+i]=0}else i=e.length,s=this.raw_._malloc(i),this.raw_.HEAPU8.set(e,s);const o=this.api_.loadSkeleton(s,i,t,t.length,n);return this.raw_._free(s),o}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,s,i){this.api_.setAtlasPageTexture(e,t,n,s,i)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,s=0){return!!this.api_.playAnimation(e,t,n,s)}addAnimation(e,t,n=!0,s=0,i=0){return!!this.api_.addAnimation(e,t,n,s,i)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse animations JSON",e),[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse skins JSON",e),[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,s))return this.raw_._free(n),this.raw_._free(s),null;const i=this.raw_.HEAPF32[n>>2],o=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:i,y:o}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,s=t>>2,i={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(t),i}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],s=this.raw_._malloc(8),i=s,o=s+4;for(let s=0;s<t;s++){const t=this.api_.getMeshBatchVertexCount(e,s),r=this.api_.getMeshBatchIndexCount(e,s);if(t<=0||r<=0)continue;const a=8*t*4,l=2*r,c=this.raw_._malloc(a),u=this.raw_._malloc(l);this.api_.getMeshBatchData(e,s,c,u,i,o);const h=new Float32Array(this.raw_.HEAPF32.buffer,c,8*t),d=new Uint16Array(this.raw_.HEAPU8.buffer,u,r);n.push({vertices:new Float32Array(h),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[i>>2],blendMode:this.raw_.HEAPU32[o>>2]}),this.raw_._free(c),this.raw_._free(u)}return this.raw_._free(s),n}setDefaultMix(e,t){this.api_.setDefaultMix(e,t)}setMixDuration(e,t,n,s){this.api_.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){this.api_.setTrackAlpha(e,t,n)}setAttachment(e,t,n){return!!this.api_.setAttachment(e,t,n)}setIKTarget(e,t,n,s,i){return!!this.api_.setIKTarget(e,t,n,s,i)}setSlotColor(e,t,n,s,i,o){return!!this.api_.setSlotColor(e,t,n,s,i,o)}enableEvents(e){this.api_.enableEvents(e)}collectEvents(e){const t=this.api_.getEventCount(e);if(0===t)return[];const n=this.api_.getEventBuffer(),s=this.raw_.HEAPF32,i=n>>2,o=[];for(let e=0;e<t;e++){const t=i+4*e;o.push({type:s[t],track:s[t+1],floatValue:s[t+2],intValue:s[t+3]})}return this.api_.clearEvents(),o}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(n)}off(e,t,n){const s=this.listeners_.get(e);if(!s)return;const i=s.get(t);i&&i.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}class jc{constructor(e){this.entities_=new Map,this.cachedFrame_=-1,this.cachedEntries_=[],this.controller_=e}get controller(){return this.controller_}get entityCount(){return this.entities_.size}loadEntity(e,t,n,s,i){const o=this.controller_.loadSkeleton(t,n,i);if(o<0)return console.error(`[ModuleBackend] Failed to load skeleton: ${this.controller_.getLastError()}`),!1;const r=this.controller_.getAtlasPageCount(o);for(let e=0;e<r;e++){const t=this.controller_.getAtlasPageTextureName(o,e),n=s.get(t);n&&this.controller_.setAtlasPageTexture(o,e,n.glId,n.w,n.h)}const a=this.controller_.createInstance(o);return this.entities_.set(e,{skelHandle:o,instanceId:a,skeletonScale:1,flipX:!1,flipY:!1,layer:0}),!0}setEntityProps(e,t){const n=this.entities_.get(e);n&&(void 0!==t.skeletonScale&&(n.skeletonScale=t.skeletonScale),void 0!==t.flipX&&(n.flipX=t.flipX),void 0!==t.flipY&&(n.flipY=t.flipY),void 0!==t.layer&&(n.layer=t.layer))}setAnimation(e,t,n){const s=this.entities_.get(e);s&&this.controller_.play(s.instanceId,t,n)}setSkin(e,t){const n=this.entities_.get(e);n&&this.controller_.setSkin(n.instanceId,t)}getBounds(e){const t=this.entities_.get(e);return t?this.controller_.getBounds(t.instanceId):null}getAnimations(e){const t=this.entities_.get(e);return t?this.controller_.getAnimations(t.instanceId):[]}getSkins(e){const t=this.entities_.get(e);return t?this.controller_.getSkins(t.instanceId):[]}setDefaultMix(e,t){const n=this.entities_.get(e);n&&this.controller_.setDefaultMix(n.skelHandle,t)}setMixDuration(e,t,n,s){const i=this.entities_.get(e);i&&this.controller_.setMixDuration(i.skelHandle,t,n,s)}setTrackAlpha(e,t,n){const s=this.entities_.get(e);s&&this.controller_.setTrackAlpha(s.instanceId,t,n)}setAttachment(e,t,n){const s=this.entities_.get(e);return!!s&&this.controller_.setAttachment(s.instanceId,t,n)}setIKTarget(e,t,n,s,i){const o=this.entities_.get(e);return!!o&&this.controller_.setIKTarget(o.instanceId,t,n,s,i)}setSlotColor(e,t,n,s,i,o){const r=this.entities_.get(e);return!!r&&this.controller_.setSlotColor(r.instanceId,t,n,s,i,o)}enableEvents(e){const t=this.entities_.get(e);t&&this.controller_.enableEvents(t.instanceId)}updateAll(e){for(const t of this.entities_.values())this.controller_.update(t.instanceId,e)}extractAndSubmitMeshes(e,t,n=-1){const s=e.renderer_submitSpineBatchByEntity;if(!s)return;if(this.cachedFrame_!==n){this.cachedEntries_.length=0;for(const[e,t]of this.entities_){const n=this.controller_.extractMeshBatches(t.instanceId);for(const s of n)0!==s.vertices.length&&0!==s.indices.length&&this.cachedEntries_.push({vertices:s.vertices,indices:s.indices,textureId:s.textureId,blendMode:s.blendMode,entity:e,info:t})}this.cachedFrame_=n}if(0===this.cachedEntries_.length)return;let i=0,o=0;for(const e of this.cachedEntries_)i+=e.vertices.byteLength,o+=e.indices.byteLength;const r=e._malloc(i),a=e._malloc(o);let l=0,c=0;for(const n of this.cachedEntries_){const i=r+l,o=a+c;e.HEAPF32.set(n.vertices,i>>2),new Uint16Array(e.HEAPU8.buffer,o,n.indices.length).set(n.indices),s.call(e,t,i,n.vertices.length/8,o,n.indices.length,n.textureId,n.blendMode,n.entity,n.info.skeletonScale,n.info.flipX,n.info.flipY,n.info.layer,0),l+=n.vertices.byteLength,c+=n.indices.byteLength}e._free(r),e._free(a)}removeEntity(e){const t=this.entities_.get(e);t&&(this.controller_.destroyInstance(t.instanceId),this.controller_.unloadSkeleton(t.skelHandle),this.entities_.delete(e))}shutdown(){for(const e of this.entities_.values())this.controller_.destroyInstance(e.instanceId),this.controller_.unloadSkeleton(e.skelHandle);this.entities_.clear()}}class Yc{constructor(e,t){this.backends_=new Map,this.loadingBackends_=new Map,this.entityVersions_=new Map,this.coreModule_=e,this.factories_=t}static detectVersion(e){const t=function(e){if(e.length<10)return null;let t=8;const{value:n,bytesRead:s}=qc(e,t);if(t+=s,n<=1||t+n-1>e.length)return null;const i=(new TextDecoder).decode(e.subarray(t,t+n-1));return i.startsWith("4.2")?"4.2":i.startsWith("4.1")?"4.1":null}(e);return t||function(e){if(e.length<4)return null;let t=0;const{value:n,bytesRead:s}=qc(e,t);t+=s,n>0&&(t+=n-1);if(t>=e.length)return null;const{value:i,bytesRead:o}=qc(e,t);if(t+=o,i<=1||t+i-1>e.length)return null;const r=(new TextDecoder).decode(e.subarray(t,t+i-1));return r.startsWith("3.")?"3.8":null}(e)}static detectVersionJson(e){const t=e.match(/"spine"\s*:\s*"(\d+\.\d+)/);return t?t[1].startsWith("4.2")?"4.2":t[1].startsWith("4.1")?"4.1":t[1].startsWith("3.")?"3.8":null:null}async loadEntity(e,t,n,s,i){const o="string"==typeof t?Yc.detectVersionJson(t):Yc.detectVersion(t);if(!o)return null;if("4.2"===o&&!this.factories_.has("4.2"))return this.entityVersions_.set(e,"4.2"),"4.2";this.coreModule_.spine_setNeedsReload?.(i,e,!1);const r=await this.ensureBackend(o);if(!r)return console.error(`[SpineManager] Failed to create backend for version ${o}`),null;const a=t instanceof Uint8Array;return r.loadEntity(e,t,n,s,a)?(this.entityVersions_.set(e,o),o):(console.error(`[SpineManager] Failed to load entity ${e} into backend ${o}`),null)}updateAnimations(e){for(const t of this.backends_.values())t.updateAll(e)}submitMeshes(e,t=-1){for(const n of this.backends_.values())n.extractAndSubmitMeshes(this.coreModule_,e,t)}removeEntity(e){const t=this.entityVersions_.get(e);if(!t)return void this.entityVersions_.delete(e);const n=this.backends_.get(t);n&&n.removeEntity(e),this.entityVersions_.delete(e)}getEntityVersion(e){return this.entityVersions_.get(e)}hasModuleBackend(e){return this.backends_.has(e)}getModuleBackend(e){return this.backends_.get(e)}setAnimation(e,t,n){const s=this.entityVersions_.get(e);if(!s)return;const i=this.backends_.get(s);i&&i.setAnimation(e,t,n)}setSkin(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setSkin(e,t)}setEntityProps(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setEntityProps(e,t)}getBounds(e){const t=this.entityVersions_.get(e);if(!t)return null;const n=this.backends_.get(t);return n?n.getBounds(e):null}getAnimations(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getAnimations(e):[]}getSkins(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getSkins(e):[]}setDefaultMix(e,t){const n=this.getEntityBackend_(e);n&&n.setDefaultMix(e,t)}setMixDuration(e,t,n,s){const i=this.getEntityBackend_(e);i&&i.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){const s=this.getEntityBackend_(e);s&&s.setTrackAlpha(e,t,n)}setAttachment(e,t,n){const s=this.getEntityBackend_(e);return!!s&&s.setAttachment(e,t,n)}setIKTarget(e,t,n,s,i){const o=this.getEntityBackend_(e);return!!o&&o.setIKTarget(e,t,n,s,i)}setSlotColor(e,t,n,s,i,o){const r=this.getEntityBackend_(e);return!!r&&r.setSlotColor(e,t,n,s,i,o)}enableEvents(e){const t=this.getEntityBackend_(e);t&&t.enableEvents(e)}hasInstance(e){return this.entityVersions_.has(e)}shutdown(){for(const e of this.backends_.values())e.shutdown();this.backends_.clear(),this.loadingBackends_.clear(),this.entityVersions_.clear()}getEntityBackend_(e){const t=this.entityVersions_.get(e);if(t)return this.backends_.get(t)}async ensureBackend(e){const t=this.backends_.get(e);if(t)return t;const n=this.loadingBackends_.get(e);if(n)return n;const s=this.factories_.get(e);if(!s)return console.warn(`[SpineManager] No module factory for version ${e}`),null;const i=(async()=>{try{const t=await s(),n=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"]),setDefaultMix:t("spine_setDefaultMix",null,["number","number"]),setMixDuration:t("spine_setMixDuration",null,["number","string","string","number"]),setTrackAlpha:t("spine_setTrackAlpha",null,["number","number","number"]),enableEvents:t("spine_enableEvents",null,["number"]),getEventCount:t("spine_getEventCount","number",["number"]),getEventBuffer:t("spine_getEventBuffer","number",[]),clearEvents:t("spine_clearEvents",null,[]),setAttachment:t("spine_setAttachment","number",["number","string","string"]),setIKTarget:t("spine_setIKTarget","number",["number","string","number","number","number"]),setSlotColor:t("spine_setSlotColor","number",["number","string","number","number","number","number"])}}(t),i=new Xc(t,n),o=new jc(i);return this.backends_.set(e,o),o}catch(t){return console.error(`[SpineManager] Failed to load WASM module for version ${e}:`,t),null}finally{this.loadingBackends_.delete(e)}})();return this.loadingBackends_.set(e,i),i}}function qc(e,t){let n=0,s=0,i=0;do{const o=e[t+i++];if(n|=(127&o)<<s,s+=7,!(128&o))break}while(s<35);return{value:n,bytesRead:i}}async function Gc(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Kc=Ge({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Jc={r:.2,g:.4,b:1,a:.7},Zc={r:.2,g:1,b:.2,a:.7},Qc={r:.2,g:1,b:1,a:.7},eu={r:1,g:1,b:.2,a:.5},tu={r:1,g:.2,b:.2,a:.8},nu={r:1,g:.2,b:.2,a:1},su=1.5,iu=16;function ou(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ru(e){switch(e){case Ye.Static:return Jc;case Ye.Kinematic:return Qc;default:return Zc}}function au(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)wo.line(l[e],l[(e+1)%4],o,su)}function lu(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),h=l(-n,-s),d=l(n,-s);wo.line(c,h,o,su),wo.line(u,d,o,su);for(let e=0;e<iu;e++){const t=e/iu*Math.PI,i=(e+1)/iu*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));wo.line(r,a,o,su)}for(let e=0;e<iu;e++){const t=Math.PI+e/iu*Math.PI,i=Math.PI+(e+1)/iu*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));wo.line(r,a,o,su)}}function cu(e,t,n,s){const i=e+.5*n,o=t+.5*s;wo.line({x:e,y:t},{x:i,y:o},tu,su);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),h=o-6*(l*Math.sin(a)+c*Math.cos(a)),d=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));wo.line({x:i,y:o},{x:u,y:h},tu,su),wo.line({x:i,y:o},{x:d,y:f},tu,su)}function uu(e,t,n){const s=e.getResource(Kc);if(!s||!s.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([be]);for(const n of t){const t=e.world.get(n,be);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([Ue,me]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,Ue);if(!n.enabled)continue;const o=e.world.get(t,me),a=o.worldPosition.x,l=o.worldPosition.y,c=ou(o.worldRotation);if(s.showColliders){if(e.world.has(t,ze)){const s=e.world.get(t,ze),o=s.isSensor?eu:ru(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);au(a+r*h-u*d,l+r*d+u*h,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,Le)){const s=e.world.get(t,Le),o=s.isSensor?eu:ru(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c),f=a+r*h-u*d,p=l+r*d+u*h;wo.circleOutline({x:f,y:p},s.radius*i,o,su,32)}if(e.world.has(t,He)){const s=e.world.get(t,He),o=s.isSensor?eu:ru(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);lu(a+r*h-u*d,l+r*d+u*h,s.radius*i,s.halfHeight*i,c,o)}if(e.world.has(t,De)){const s=e.world.get(t,De),o=s.isSensor?eu:ru(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=a+(s.point1.x*i*r-s.point1.y*i*u),d=l+(s.point1.x*i*u+s.point1.y*i*r),f=a+(s.point2.x*i*r-s.point2.y*i*u),p=l+(s.point2.x*i*u+s.point2.y*i*r);wo.line({x:h,y:d},{x:f,y:p},o,su)}if(e.world.has(t,$e)){const s=e.world.get(t,$e),o=s.isSensor?eu:ru(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=s.vertices;for(let e=0;e<h.length;e++){const t=h[e],n=h[(e+1)%h.length],s=a+(t.x*i*r-t.y*i*u),c=l+(t.x*i*u+t.y*i*r),d=a+(n.x*i*r-n.y*i*u),f=l+(n.x*i*u+n.y*i*r);wo.line({x:s,y:c},{x:d,y:f},o,su)}}if(e.world.has(t,Oe)){const s=e.world.get(t,Oe),o=ru(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=s.points,d=s.isLoop?h.length:h.length-1;for(let e=0;e<d;e++){const t=h[e],n=h[(e+1)%h.length],s=a+(t.x*i*r-t.y*i*u),c=l+(t.x*i*u+t.y*i*r),d=a+(n.x*i*r-n.y*i*u),f=l+(n.x*i*u+n.y*i*r);wo.line({x:s,y:c},{x:d,y:f},o,su)}}}if(s.showVelocity&&r&&n.bodyType===Ye.Dynamic){const e=r.getLinearVelocity(t);cu(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)wo.circle({x:e.contactX,y:e.contactY},3,nu,!0,32)}}const hu=Ge({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),du=Ge(null,"PhysicsAPI");function fu(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}class pu{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/30,subStepCount:t.subStepCount??4,contactHertz:t.contactHertz??30,contactDampingRatio:t.contactDampingRatio??10,contactSpeed:t.contactSpeed??3,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(hu,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Set,s=new Set,i=new Map;let o=-1;const r=Gc(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount,this.config_.contactHertz,this.config_.contactDampingRatio,this.config_.contactSpeed);const a=function(e){const t=e.world.getEntitiesWithComponents([be]);for(const n of t){const t=e.world.get(n,be);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),l=1/a,c=e.world;c.onDespawn(e=>{n.has(e)&&(r._physics_destroyJoint(e),n.delete(e)),t.has(e)&&(r._physics_destroyBody(e),t.delete(e),i.delete(e),s.delete(e))}),e.addSystemToSchedule(Ot.PostUpdate,Nt([Ke(et)],u=>{if(Ps()&&!Es())return;const h=c.getEntitiesWithComponents([Ue,me]),d=new Set;for(const n of h)if(d.add(n),t.has(n)){if(c.isChangedSince(n,Ue,o)){const e=c.get(n,Ue),t=i.get(n);!t||t.bodyType===e.bodyType&&t.gravityScale===e.gravityScale&&t.linearDamping===e.linearDamping&&t.angularDamping===e.angularDamping&&t.fixedRotation===e.fixedRotation&&t.bullet===e.bullet||(r._physics_updateBodyProperties(n,e.bodyType,e.gravityScale,e.linearDamping,e.angularDamping,e.fixedRotation?1:0,e.bullet?1:0),t.bodyType=e.bodyType,t.gravityScale=e.gravityScale,t.linearDamping=e.linearDamping,t.angularDamping=e.angularDamping,t.fixedRotation=e.fixedRotation,t.bullet=e.bullet)}const e=i.get(n);if(e&&e.bodyType===Ye.Kinematic){const e=c.get(n,me),t=fu(e.worldRotation);r._physics_setBodyTransform(n,e.worldPosition.x*l,e.worldPosition.y*l,t)}}else{const o=c.get(n,Ue);if(!o.enabled)continue;const a=c.get(n,me),u=c.has(n,Se),h=u?a.worldPosition.x:a.position.x,d=u?a.worldPosition.y:a.position.y,f=fu(u?a.worldRotation:a.rotation);r._physics_createBody(n,o.bodyType,h*l,d*l,f,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),_u(e,r,n,this.config_.collisionLayerMasks),t.add(n),c.has(n,Se)&&s.add(n),i.set(n,{bodyType:o.bodyType,gravityScale:o.gravityScale,linearDamping:o.linearDamping,angularDamping:o.angularDamping,fixedRotation:o.fixedRotation,bullet:o.bullet})}o=c.getWorldTick();for(const e of t)d.has(e)||(r._physics_destroyBody(e),t.delete(e),i.delete(e));!function(e,t,n,s,i){const o=e.getEntitiesWithComponents([We,Ue]);for(const r of o){if(s.has(r))continue;if(!n.has(r))continue;const o=e.get(r,We);if(!o.enabled)continue;const a=o.connectedEntity;n.has(a)&&(t._physics_createRevoluteJoint(a,r,o.anchorA.x*i,o.anchorA.y*i,o.anchorB.x*i,o.anchorB.y*i,o.enableMotor?1:0,o.motorSpeed,o.maxMotorTorque,o.enableLimit?1:0,o.lowerAngle,o.upperAngle,o.collideConnected?1:0),s.add(r))}for(const o of e.getEntitiesWithComponents([Ve,Ue])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Ve);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createDistanceJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.length*i,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.minLength*i,r.maxLength*i,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([Ne,Ue])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Ne);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createPrismaticJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*i,r.upperTranslation*i,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([Xe,Ue])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Xe);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWeldJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.linearHertz,r.angularHertz,r.linearDampingRatio,r.angularDampingRatio,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([je,Ue])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,je);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWheelJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*i,r.upperTranslation*i,r.enableMotor?1:0,r.maxMotorTorque,r.motorSpeed,r.collideConnected?1:0),s.add(o))}}(c,r,t,n,l),t.size>0&&u.delta>0&&r._physics_step(u.delta),function(e,t,n,s){const i=t._physics_getDynamicBodyCount();if(0===i)return;const o=t._physics_getDynamicBodyTransforms(),r=o>>2,a=t.HEAPU32,l=t.HEAPF32,c=e.world.getCppRegistry();if(!c)return;const u=e.world.getWasmModule(),h=s.size>0;if(!h&&u?.registry_batchSyncPhysicsTransforms){const e=i*wu,s=u._malloc(e);return u.HEAPU8.set(new Uint8Array(t.HEAPU8.buffer,o,e),s),u.registry_batchSyncPhysicsTransforms(c,s,i,n),void u._free(s)}const d=u?.getTransformPtr?e=>u.getTransformPtr(c,e):null,f=u?.HEAPF32,p=d&&f?null:c.addTransform.bind(c),m=yu;for(let t=0;t<i;t++){const i=r+t*xu,o=a[i];let c=l[i+1]*n,u=l[i+2]*n,g=l[i+3];if(h&&s.has(o)){const t=e.world.get(o,Se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,me)){const n=e.world.get(t.entity,me),s=fu(n.worldRotation),i=u,o=c-n.worldPosition.x,r=i-n.worldPosition.y,a=Math.cos(-s),l=Math.sin(-s);c=(o*a-r*l)/(0!==n.worldScale.x?n.worldScale.x:1),u=(o*l+r*a)/(0!==n.worldScale.y?n.worldScale.y:1),g-=s}}const _=.5*g,y=Math.cos(_),x=Math.sin(_);if(d&&f){const e=d(o);if(e){const t=e>>2;f[t]=c,f[t+1]=u,f[t+2]=0,f[t+3]=0,f[t+4]=0,f[t+5]=x,f[t+6]=y,f[t+7]=1,f[t+8]=1,f[t+9]=1,f[t+10]=c,f[t+11]=u,f[t+12]=0,f[t+13]=0,f[t+14]=0,f[t+15]=x,f[t+16]=y,f[t+17]=1,f[t+18]=1,f[t+19]=1;continue}}m.position.x=c,m.position.y=u,m.rotation.w=y,m.rotation.x=0,m.rotation.y=0,m.rotation.z=x,m.worldPosition.x=c,m.worldPosition.y=u,m.worldRotation.w=y,m.worldRotation.x=0,m.worldRotation.y=0,m.worldRotation.z=x,p(o,m)}}(e,r,a,s),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(hu,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,r,a)},{name:"PhysicsSystem"})),e.physicsModule=r,e.insertResource(du,bu._fromModule(r)),function(e,t,n){e.insertResource(Kc,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Po("physics-debug-draw",()=>{uu(e,t,n)})}(e,du,hu),e.setFixedTimestep(this.config_.fixedTimestep)});r.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=r}}const mu=16;function gu(e,t,n){if(!n)return t;for(let t=0;t<mu;t++)if(e===1<<t)return n[t];return t}function _u(e,t,n,s){const i=e.world;if(i.has(n,ze)){const e=i.get(n,ze),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s);t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.radius??.05,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,Le)){const e=i.get(n,Le),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s);t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,He)){const e=i.get(n,He),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,De)){const e=i.get(n,De),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s);t._physics_addSegmentShape(n,e.point1.x,e.point1.y,e.point2.x,e.point2.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,$e)){const e=i.get(n,$e),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s),a=e.vertices,l=Math.min(a.length,8),c=2*l*4,u=t._malloc(c),h=u>>2;for(let e=0;e<l;e++)t.HEAPF32[h+2*e]=a[e].x,t.HEAPF32[h+2*e+1]=a[e].y;t._physics_addPolygonShape(n,u,l,e.radius??0,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r),t._free(u)}if(i.has(n,Oe)){const e=i.get(n,Oe),s=e.points;if(s.length<4)return;const o=2*s.length*4,r=t._malloc(o),a=r>>2;for(let e=0;e<s.length;e++)t.HEAPF32[a+2*e]=s[e].x,t.HEAPF32[a+2*e+1]=s[e].y;t._physics_addChainShape(n,r,s.length,e.isLoop?1:0,e.friction,e.restitution,e.categoryBits??1,e.maskBits??65535),t._free(r)}}const yu={position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}},xu=4,wu=4*xu;class bu{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(bu.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)}createRevoluteJoint(e,t,n,s,i){const o=i??{};return 0!==this.module_._physics_createRevoluteJoint(e,t,n.x,n.y,s.x,s.y,o.enableMotor?1:0,o.motorSpeed??0,o.maxMotorTorque??0,o.enableLimit?1:0,o.lowerAngle??0,o.upperAngle??0,o.collideConnected?1:0)}destroyJoint(e){this.module_._physics_destroyJoint(e)}setRevoluteMotorSpeed(e,t){this.module_._physics_setRevoluteMotorSpeed(e,t)}setRevoluteMaxMotorTorque(e,t){this.module_._physics_setRevoluteMaxMotorTorque(e,t)}enableRevoluteMotor(e,t){this.module_._physics_enableRevoluteMotor(e,t?1:0)}enableRevoluteLimit(e,t){this.module_._physics_enableRevoluteLimit(e,t?1:0)}setRevoluteLimits(e,t,n){this.module_._physics_setRevoluteLimits(e,t,n)}getRevoluteAngle(e){return this.module_._physics_getRevoluteAngle(e)}getRevoluteMotorTorque(e){return this.module_._physics_getRevoluteMotorTorque(e)}raycast(e,t,n,s=65535,i=100){const o=1/i,r=this.module_._physics_raycast(e.x*o,e.y*o,t.x,t.y,n*o,s);if(0===r)return[];const a=this.module_._physics_getRaycastBuffer()>>2,l=[];for(let e=0;e<r;e++){const t=a+6*e;l.push({entity:this.module_.HEAPU32[t],point:{x:this.module_.HEAPF32[t+1]*i,y:this.module_.HEAPF32[t+2]*i},normal:{x:this.module_.HEAPF32[t+3],y:this.module_.HEAPF32[t+4]},fraction:this.module_.HEAPF32[t+5]})}return l.sort((e,t)=>e.fraction-t.fraction),l}overlapCircle(e,t,n=65535,s=100){const i=1/s,o=this.module_._physics_overlapCircle(e.x*i,e.y*i,t*i,n);if(0===o)return[];const r=this.module_._physics_getOverlapBuffer()>>2,a=[],l=new Set;for(let e=0;e<o;e++){const t=this.module_.HEAPU32[r+e];l.has(t)||(l.add(t),a.push(t))}return a}setAwake(e,t){this.module_._physics_setAwake(e,t?1:0)}isAwake(e){return 0!==this.module_._physics_isAwake(e)}static setDebugDraw(e,t){const n=e.getResource(Kc);n&&(n.enabled=t,e.insertResource(Kc,n))}static setDebugDrawConfig(e,t){const n=e.getResource(Kc);n&&e.insertResource(Kc,{...n,...t})}}const vu={nearest:0,linear:1},Su={repeat:0,clamp:1,mirror:2};function Mu(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=vu[s.filterMode??"linear"]??1,a=Su[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function Pu(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 Tu(e,t,n){const s=e.FS;if(!s)return!1;try{return function(e,t){const n=e.FS;if(!n)return;const s=t.substring(0,t.lastIndexOf("/"));if(!s)return;const i=s.split("/").filter(e=>e);let o="";for(const e of i){o+="/"+e;try{n.mkdir(o)}catch{}}}(e,t),s.writeFile(t,n),!0}catch(e){return console.warn(`[Runtime] Failed to write virtual FS: ${t}`,e),!1}}async function Cu(e){const{app:t,module:n,sceneData:s,provider:i,spineManager:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=gi(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=Mu(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);const h=await async function(e,t,n,s){const i=new Set,o=new Map;for(const r of t.entities)for(const t of r.components){const r=_i(t.type);if(!r||!t.data)continue;const a=t.data[r.skeletonField],l=t.data[r.atlasField];if(!a||!l)continue;const c=`${a}:${l}`;if(i.has(c))continue;i.add(c);const u=n.resolvePath(l);try{const t=await n.readText(l),i=n.resolvePath(a),r="binary"===Ii(i)?.contentType?await n.readBinary(a):await n.readText(a),h=s?"string"==typeof r?Yc.detectVersionJson(r):Yc.detectVersion(r):null,d=Pu(t),f=u.substring(0,u.lastIndexOf("/")),p=e.getResourceManager(),m=new Map;for(const t of d){const s=f+"/"+t;try{const i=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),o=Mu(e,i,!1);p.registerTextureWithPath(o,s),m.set(t,{glId:p.getTextureGLId(o),w:i.width,h:i.height})}catch(e){console.warn(`[Spine] Failed to load texture: ${s}`,e)}}(!h||"4.2"===h)&&(Tu(e,u,t),Tu(e,i,r)),o.set(c,{version:h,skelData:r,atlasText:t,textures:m})}catch(e){console.warn(`[Runtime] Failed to load spine asset: skel=${a} atlas=${l}`,e)}}return o}(n,s,i,o);if(r){const e={gravity:a?.gravity??{...k},fixedTimestep:a?.fixedTimestep??R,subStepCount:a?.subStepCount??4,contactHertz:a?.contactHertz??120,contactDampingRatio:a?.contactDampingRatio??10,contactSpeed:a?.contactSpeed??10};new pu("",e,()=>Promise.resolve(r)).build(t)}const d=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=gi(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=Ii(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Mu(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch(e){console.warn(`[Runtime] Failed to load bitmap font: ${o}`,e),s[o]=0}}return s}(n,s,i),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=gi(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=hn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=hn.createFromAsset(e,r)}catch(e){console.warn(`[Runtime] Failed to load material: ${o}`,e),n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=gi(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=vn(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,Mu(e,s))}catch(e){console.warn(`[Runtime] Failed to load anim texture: ${t}`,e),r.set(t,0)}Pn(Sn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=gi(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=Gn(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=Kn(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=Mu(e,t),Bn(r,t.width,t.height)}catch(e){console.warn(`[Runtime] Failed to load tileset texture: ${s}`,e)}o.push({textureHandle:r,columns:t.columns})}Ln(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=gi(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await Rn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Rn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=gi(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,d,f);const p=bi(t.world,s),m=t.world.getCppRegistry();if(m&&n.transform_update(m),o&&m&&h.size>0)for(const e of s.entities)for(const t of e.components){const n=_i(t.type);if(!n||!t.data)continue;const s=t.data[n.skeletonField],i=t.data[n.atlasField];if(!s||!i)continue;const r=`${s}:${i}`,a=h.get(r);if(!a||!a.version||"4.2"===a.version)continue;const l=p.get(e.id);if(void 0===l)continue;await o.loadEntity(l,a.skelData,a.atlasText,a.textures,m),o.setEntityProps(l,{skeletonScale:t.data.skeletonScale??1,flipX:t.data.flipX??!1,flipY:t.data.flipY??!1,layer:t.data.layer??0});const c=t.data.skin;c&&o.setSkin(l,c);const u=t.data.animation;u&&o.setAnimation(l,u,!1!==t.data.loop)}if(c&&t.hasResource(Fr))for(const e of p.values())t.world.insert(e,Ie,{scene:c,persistent:!1});if(l){const e=t.getResource(Yi);e&&e.setAddressableManifest(l)}}function Eu(e,t,n){return{name:e,async setup(){await Cu({...n,sceneData:t,sceneName:e})}}}async function Au(e){const{app:t,firstScene:n,aspectRatio:s}=e;Hr(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,spineManager:e.spineManager,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(Fr);for(const t of e.scenes)o.register(Eu(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&Pi(t.world,s)}class ku{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=_i(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===Ii(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=gi(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=Ii(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}let Ru=null;const Iu={update(e,t){Ru?.spine_update?.(e._cpp,t)},play:(e,t,n=!0,s=0)=>Ru?.spine_play?.(e,t,n,s)??!1,addAnimation:(e,t,n=!0,s=0,i=0)=>Ru?.spine_addAnimation?.(e,t,n,s,i)??!1,setSkin:(e,t)=>Ru?.spine_setSkin?.(e,t)??!1,getBonePosition:(e,t)=>Ru?.spine_getBonePosition?.(e,t)??null,hasInstance:e=>Ru?.spine_hasInstance?.(e)??!1,reloadAssets(e){Ru?.spine_reloadAssets?.(e._cpp)},getAnimations:e=>Ru?.spine_getAnimations?.(e)??[],getSkins:e=>Ru?.spine_getSkins?.(e)??[]};class Fu{constructor(e){this.app_=null,e instanceof Yc?(this.spineManager_=e,this.provider_=null):(this.spineManager_=null,this.provider_=e??null)}get spineManager(){return this.spineManager_}setSpineManager(e){if(this.spineManager_=e,this.app_){const t=this.app_,n=t.pipeline;n?.addPreFlushCallback(n=>{const s=t.getResource(et).frameCount;e.submitMeshes(n._cpp,s)})}}build(e){this.app_=e;const t=e.wasmModule;if(Ru=t,!this.spineManager_&&this.provider_){const e=function(e){const t=["3.8","4.1","4.2"],n=new Map;for(const s of t)n.set(s,async()=>{const[t,n]=await Promise.all([e.loadJs(s),e.loadWasm(s)]),i=new Blob([`${t};\nself.__ESSpineModule__ = ESSpineModule;`],{type:"application/javascript"}),o=URL.createObjectURL(i);await import(/* @vite-ignore */o),URL.revokeObjectURL(o);const r=globalThis.__ESSpineModule__;return delete globalThis.__ESSpineModule__,r({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Spine] WASM instantiation failed:",e)}),{})})});return n}(this.provider_);this.spineManager_=new Yc(t,e)}const n=this,s={_id:Symbol("SpineUpdateSystem"),_name:"SpineUpdateSystem",_params:[],_fn:()=>{const t=e.world.getCppRegistry();if(!t)return;const s=e.getResource(et);Iu.update({_cpp:t},s.delta),n.spineManager_?.updateAnimations(s.delta)}};if(e.addSystemToSchedule(Ot.PreUpdate,s),this.spineManager_){const t=this.spineManager_,n=e.pipeline;n?.addPreFlushCallback(n=>{const s=e.getResource(et).frameCount;t.submitMeshes(n._cpp,s)})}}}const Bu="__preview__";class Uu{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Fr);t.register({name:Bu,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Bu),this.loadPromise_=t.load(Bu).then(()=>{}).catch(e=>{console.error("[Preview] Failed to load preview scene:",e)}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new ku(this.baseUrl_);await n.prefetch(t);const s=this.app_.getPlugin(Fu),i=s?.spineManager??null;await Cu({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineManager:i,sceneName:Bu})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([we]);for(const s of n){if(e.get(s,we).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([be]);for(const i of s){const s=e.get(i,be);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(Fr).getScene(Bu),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,me,r);const a={isActive:!0,projectionType:he.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:de.ColorAndDepth};e.insert(o,we,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Fr);await e.switchTo(Bu),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const zu={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=br.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:br.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){br.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(br.releaseRenderTarget(e._handle),zu.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){br.begin(t,e._handle)},end(){br.end()},getDepthTexture:e=>br.getTargetDepthTexture(e._handle)};var Lu;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Lu||(Lu={}));class Hu{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Lu[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Lu.Debug:console.debug(t,n);break;case Lu.Info:console.log(t,n);break;case Lu.Warn:console.warn(t,n);break;case Lu.Error:console.error(t,n)}}}class Du{constructor(){this.handlers_=[],this.minLevel_=Lu.Info,this.addHandler(new Hu)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Lu.Debug,e,t,n)}info(e,t,n){this.log(Lu.Info,e,t,n)}warn(e,t,n){this.log(Lu.Warn,e,t,n)}error(e,t,n){this.log(Lu.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const $u=new Du;function Ou(){return $u}function Wu(e){$u.setMinLevel(e)}function Vu(e,t,n){$u.debug(e,t,n)}function Nu(e,t,n){$u.info(e,t,n)}function Xu(e,t,n){$u.warn(e,t,n)}function ju(e,t,n){$u.error(e,t,n)}const Yu={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},qu={Running:0,Paused:1,Completed:2,Cancelled:3},Gu={None:0,Restart:1,PingPong:2};const Ku=1.70158,Ju=2.70158,Zu=2.5949095;const Qu=2*Math.PI/3,eh=2*Math.PI/4.5;const th=7.5625,nh=2.75;const sh=1e-6;function ih(e,t,n){switch(e){case Yu.Linear:return t;case Yu.EaseInQuad:return function(e){return e*e}(t);case Yu.EaseOutQuad:return function(e){return e*(2-e)}(t);case Yu.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Yu.EaseInCubic:return function(e){return e*e*e}(t);case Yu.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Yu.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Yu.EaseInBack:return function(e){return Ju*e*e*e-Ku*e*e}(t);case Yu.EaseOutBack:return function(e){const t=e-1;return 1+Ju*t*t*t+Ku*t*t}(t);case Yu.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Zu)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Zu)+2)/2}(t);case Yu.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Qu)}(t);case Yu.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Qu)+1}(t);case Yu.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*eh)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*eh)/2+1}(t);case Yu.EaseOutBounce:return function(e){return e<1/nh?th*e*e:e<2/nh?th*(e-=1.5/nh)*e+.75:e<2.5/nh?th*(e-=2.25/nh)*e+.9375:th*(e-=2.625/nh)*e+.984375}(t);case Yu.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<sh)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<sh)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case Yu.Step:return function(e){return e<1?0:1}(t);default:return t}}const oh=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??Yu.Linear,bezierPoints:null,state:qu.Running,loop:i?.loop??Gu.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===qu.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==qu.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=ih(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Gu.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Gu.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=qu.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===qu.Running&&(t.state=qu.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===qu.Paused&&(t.state=qu.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=qu.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:qu.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class rh{constructor(e){this.id=e}get state(){return oh.getState(this.id)}bezier(e,t,n,s){return oh.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof rh?oh.setSequenceNext(this.id,e.id):oh.setSequenceNextExternal(this.id,e),this}pause(){oh.pause(this.id)}resume(){oh.resume(this.id)}cancel(){oh.cancel(this.id)}}const ah={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class lh{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof rh?(oh.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let ch=null,uh=null;function hh(e,t){ch=e,uh=t,oh.init(e,t)}function dh(){oh.shutdown(),ch=null,uh=null}function fh(){if(!ch)throw new Error("Tween API not initialized");return ch}function ph(){if(!uh)throw new Error("Tween API not initialized");return uh}const mh={to(e,t,n,s,i,o){const r=fh(),a=ph(),l=o?.easing??Yu.Linear,c=o?.delay??0,u=o?.loop??Gu.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new lh(r,a,d)},value(e,t,n,s,i){const o=oh.create(e,t,n,s,i);return new rh(o)},cancel(e){fh()._anim_cancelTween(ph(),e.entity)},cancelAll(e){fh()._anim_cancelAllTweens(ph(),e)},update(e){fh()._anim_updateTweens(ph(),e),oh.update(e)}};class gh{constructor(){this.name="AnimationPlugin"}build(e){hh(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(Ot.Update,Nt([Ke(et)],e=>{Ps()&&!Es()||mh.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(Ot.Update,Nt([Ke(et)],e=>{Ps()&&!Es()||kn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){dh()}}const _h=new gh;let yh=null,xh=null;function wh(e,t){yh=e,xh=t}function bh(){yh=null,xh=null}const vh={update(e){yh&&xh&&yh.particle_update?.(xh,e)},play(e){yh&&xh&&yh.particle_play?.(xh,e)},stop(e){yh&&xh&&yh.particle_stop?.(xh,e)},reset(e){yh&&xh&&yh.particle_reset?.(xh,e)},getAliveCount:e=>yh?yh.particle_getAliveCount?.(e)??0:0};class Sh{constructor(){this.name="ParticlePlugin"}build(e){wh(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(Ot.Update,Nt([Ke(et)],e=>{vh.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){bh()}}const Mh=new Sh,Ph=1073741824,Th={orthogonal:0,isometric:1,staggered:2};class Ch{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.animatedLayers_=new Set,this.sourceEntityKeys_=new Map,this.layerState_=new Map}build(e){On(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.animatedLayers_,i=this.sourceEntityKeys_,o=this.layerState_,r={_id:Symbol("TilemapSyncSystem"),_name:"TilemapSyncSystem",_params:[],_fn:()=>{const r=t.getEntitiesWithComponents([Xn,me]),a=new Set(r);for(const e of n)e>=Ph||a.has(e)||(Vn.destroyLayer(e),n.delete(e),o.delete(e));for(const e of r){const s=t.tryGet(e,Xn);if(!s)continue;const i=s.texture;if(!i)continue;const r=Un(i);if(!r)continue;if(!n.has(e)){if(Vn.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),Vn.setOriginEntity(e,e),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];Vn.setTiles(e,t)}n.add(e)}const a=s.tileWidth/r.width,l=s.tileHeight/r.height,c=s.tint,u=s.parallaxFactor,h=o.get(e);(!h||h.texture!==i||h.tilesetColumns!==s.tilesetColumns||h.layer!==s.layer||h.parallaxX!==u.x||h.parallaxY!==u.y||h.tintR!==c.r||h.tintG!==c.g||h.tintB!==c.b||h.tintA!==c.a||h.opacity!==s.opacity||h.visible!==s.visible)&&(Vn.setRenderProps(e,i,s.tilesetColumns,a,l,s.layer,0,u.x,u.y),Vn.setTint(e,c.r,c.g,c.b,c.a,s.opacity),Vn.setVisible(e,s.visible),o.set(e,{texture:i,tilesetColumns:s.tilesetColumns,layer:s.layer,tintR:c.r,tintG:c.g,tintB:c.b,tintA:c.a,opacity:s.opacity,parallaxX:u.x,parallaxY:u.y,visible:s.visible}))}const l=t.getEntitiesWithComponents([Nn,me]);for(const e of l){if(t.tryGet(e,Xn))continue;const o=t.tryGet(e,Nn);if(!o?.source)continue;const r=Hn(o.source);if(r&&!i.has(e)){const t=[],o=Th[r.orientation??"orthogonal"]??0;for(let i=0;i<r.layers.length;i++){const a=Ph+256*e+i,l=r.layers[i];if(Vn.initLayer(a,l.width,l.height,r.tileWidth,r.tileHeight),Vn.setOriginEntity(a,e),l.tiles.length>0&&Vn.setTiles(a,l.tiles),0!==o&&Vn.setGridType(a,o),r.tileAnimations){for(const[e,t]of r.tileAnimations)Vn.setTileAnimation(a,e,t);r.tileAnimations.size>0&&s.add(a)}if(r.tileProperties)for(const[e,t]of r.tileProperties)for(const[n,s]of t)Vn.setTileProperty(a,e,n,s);const c=r.tilesets[0];if(c){const e=Un(c.textureHandle);e&&(Vn.setRenderProps(a,c.textureHandle,c.columns,r.tileWidth/e.width,r.tileHeight/e.height,i,0,1,1),Vn.setTint(a,1,1,1,1,1),Vn.setVisible(a,!0))}t.push(a),n.add(a)}i.set(e,t)}}const c=new Set(l);for(const[e,t]of i)if(!c.has(e)){for(const e of t)Vn.destroyLayer(e),n.delete(e),s.delete(e),o.delete(e);i.delete(e)}if(s.size>0){const t=1e3*e.getResource(et).delta;for(const e of s)Vn.advanceAnimations(e,t)}}};e.addSystemToSchedule(Ot.PreUpdate,r)}cleanup(){for(const e of this.initializedLayers_)Vn.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),this.layerState_.clear(),zn(),Wn()}}const Eh=new Ch;function Ah(e,t){return e.toFixed(t)}function kh(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Rh{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.lastUpdateTime_=0,this.lastStats_=null,this.accumulatedTimings_=new Map,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 220px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;this.lastStats_=e,this.accumulateTimings_(e.systemTimings);const t=performance.now();this.lastUpdateTime_>0&&t-this.lastUpdateTime_<500||(this.lastUpdateTime_=t,this.render_())}show(){this.visible_=!0,this.lastUpdateTime_=0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}accumulateTimings_(e){for(const[t,n]of e){const e=this.accumulatedTimings_.get(t);e?(e.sum+=n,e.count++,n>e.max&&(e.max=n)):this.accumulatedTimings_.set(t,{sum:n,max:n,count:1})}}render_(){const e=this.lastStats_;if(!e)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Ah(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ah(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),this.accumulatedTimings_.size>0){const e=[];for(const[t,n]of this.accumulatedTimings_){const s=n.sum/n.count;e.push([t,s,n.max])}e.sort((e,t)=>t[2]-e[2]);const n=e.slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t,i]of n){s+=`<div>${kh(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ah(t,1)} / ${Ah(i,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join(""),this.accumulatedTimings_.clear()}}function Ih(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Fh=Ge(Ih(),"Stats");class Bh{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const Uh="StatsCollect";class zh{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Lh{constructor(e){this.name="Stats",this.collector_=new zh,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Fh,Ih());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Rh(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=Nt([Ke(et),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Fh);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Uh),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=br.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:Uh});e.addSystemToSchedule(Ot.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Hh=new Lh;class Dh{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return $h(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}function $h(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}function Oh(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function Wh(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await async function(e,t){try{const n=Oh(t),s={instantiateWasm(e,t){const s=new Response(n.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,e).then(e=>t(e.instance,e.module),()=>{WebAssembly.instantiate(n.buffer,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Playable] WASM instantiation fallback failed:",e)})}),{}}};return await e(s)}catch(e){return console.error("[Playable] WASM module init failed:",e),null}}(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}async function Vh(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(Yi);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));let a=null;if(e.spineModules&&Object.keys(e.spineModules).length>0){a=function(e,t){const n=new Map;for(const[e,s]of Object.entries(t)){const t=e;n.set(t,async()=>{const e=Oh(s.wasmBase64);return s.factory({instantiateWasm(t,n){const s=new Response(e.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,t).then(e=>n(e.instance,e.module),()=>{WebAssembly.instantiate(e.buffer,t).then(e=>n(e.instance,e.module)).catch(e=>{console.error("[Playable] Spine WASM instantiation fallback failed:",e)})}),{}}})})}return new Yc(e,n)}(n,e.spineModules);const s=t.getPlugin(Fu);s&&s.setSpineManager(a)}const l=e.physicsWasmBase64?await Wh(e.physicsWasmBase64):null,c=new Dh(s);Rn.setAssetResolver(e=>{const t=s[e];return t?$h(t).buffer:null}),await Au({app:t,module:n,provider:c,scenes:i,firstScene:o,spineManager:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Nh=[ja,Ka,ul,Ml,Bl,pl,Dl,Nl,Kl,kl,wl,Zl,nc,ac,uc,fc,Mc],Xh=[_h,ni,Mh,Eh,dr,di];function jh(e,t){const n=new Fu(t?.spineProvider),s=[...Nh,...Xh,n,...t?.plugins??[]];return function(e,t){const n=Lr.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),go(e),ln(e),Fo(e),Xo(e),xr(e),Sr(e);const i=new Tr;n.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=Vr(e,s,t,i));const r=n.getResource(en);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(en,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;br.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(br.resize(t,l),n.hasResource(Fr)){const e=n.getResource(Fr).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Vr(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Dr,width:t,height:l,elapsed:u});else{i.beginFrame(),i.beginScreenCapture();for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),br.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Ot.First,l),n.addSystemToSchedule(Ot.Last,c),n.addPlugin(Gi),n.addPlugin(co),n.addPlugin(Qt),n.addPlugin(zr),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{...t,plugins:s})}e=x;export{bt as Added,gh as AnimationPlugin,Lr as App,qi as AssetPlugin,Ki as AssetRefCounter,ji as AssetServer,Yi as Assets,wn as AsyncCache,Gs as AttenuationModel,Rn as Audio,p as AudioBus,ei as AudioListener,m as AudioMixer,ti as AudioPlugin,g as AudioPool,Qs as AudioSource,Pe as BitmapText,tn as BlendMode,Ye as BodyType,ze as BoxCollider,ol as Button,il as ButtonState,we as Camera,be as Canvas,He as CapsuleCollider,Oe as ChainCollider,vt as Changed,Me as Children,Le as CircleCollider,de as ClearFlags,Rt as Commands,Ft as CommandsInstance,Pc as DARK_THEME,b as DEFAULT_DESIGN_HEIGHT,w as DEFAULT_DESIGN_WIDTH,A as DEFAULT_FALLBACK_DT,R as DEFAULT_FIXED_TIMESTEP,P as DEFAULT_FONT_FAMILY,T as DEFAULT_FONT_SIZE,k as DEFAULT_GRAVITY,C as DEFAULT_LINE_HEIGHT,E as DEFAULT_MAX_DELTA_TIME,v as DEFAULT_PIXELS_PER_UNIT,I as DEFAULT_SPINE_SKIN,M as DEFAULT_SPRITE_SIZE,S as DEFAULT_TEXT_CANVAS_SIZE,Eo as DataType,Hl as DragPlugin,zl as DragState,Ul as Draggable,wo as Draw,lc as Dropdown,cc as DropdownPlugin,Yu as EasingType,Ce as EmitterShape,It as EntityCommands,Ia as EntityStateMap,Ht as EventReader,$t as EventReaderInstance,zt as EventRegistry,Lt as EventWriter,Dt as EventWriterInstance,Zr as FillDirection,ea as FillMethod,ta as FillOrigin,fr as FlushReason,yl as FocusManager,_l as FocusManagerState,Jl as FocusPlugin,gl as Focusable,Bh as FrameHistory,Pr as GLDebug,zo as Geometry,Wt as GetWorld,L as INVALID_ENTITY,D as INVALID_FONT,$ as INVALID_MATERIAL,H as INVALID_TEXTURE,na as Image,Sl as ImagePlugin,Qr as ImageType,Jt as Input,Zt as InputPlugin,Kt as InputState,ia as Interactable,dc as LayoutGroupPlugin,sc as ListView,rc as ListViewPlugin,ge as LocalTransform,Lu as LogLevel,Du as Logger,Gu as LoopMode,hn as Material,bn as MaterialLoader,xt as Mut,Re as Name,Se as Parent,vh as Particle,Ae as ParticleEasing,ke as ParticleEmitter,Sh as ParticlePlugin,bu as Physics,hu as PhysicsEvents,pu as PhysicsPlugin,$e as PolygonCollider,qo as PostProcess,hr as PostProcessPlugin,Wo as PostProcessStack,Fe as PostProcessVolume,ro as PrefabServer,ao as Prefabs,lo as PrefabsPlugin,Uu as PreviewPlugin,Il as ProgressBar,Rl as ProgressBarDirection,Fl as ProgressBarPlugin,he as ProjectionType,Ct as Query,Et as QueryInstance,At as Removed,kt as RemovedQueryInstance,Tr as RenderPipeline,mr as RenderStage,zu as RenderTexture,pr as RenderType,br as Renderer,Ke as Res,Je as ResMut,We as RevoluteJoint,Ue as RigidBody,F as RuntimeConfig,Ql as SafeArea,tc as SafeAreaPlugin,fe as ScaleMode,Fr as SceneManager,Ir as SceneManagerState,Ie as SceneOwner,Ot as Schedule,$l as ScrollView,Vl as ScrollViewPlugin,De as SegmentCollider,xn as ShaderSources,xe as ShapeRenderer,pe as ShapeType,Ee as SimulationSpace,jl as Slider,Xl as SliderDirection,Gl as SliderPlugin,Te as SpineAnimation,ye as Sprite,An as SpriteAnimator,Fh as Stats,zh as StatsCollector,Rh as StatsOverlay,Lh as StatsPlugin,nt as Storage,gr as SubmitSkipFlags,Gt as SystemRunner,Oa as Text,Ha as TextAlign,ml as TextInput,xl as TextInputPlugin,$a as TextOverflow,Xa as TextPlugin,Wa as TextRenderer,Da as TextVerticalAlign,Nn as Tilemap,Vn as TilemapAPI,Xn as TilemapLayer,Ch as TilemapPlugin,et as Time,hi as TimelinePlugin,Pl as Toggle,Al as TogglePlugin,me as Transform,mh as Tween,lh as TweenHandle,qu as TweenState,ah as TweenTarget,Vc as UI,en as UICameraInfo,rl as UIEventQueue,al as UIEvents,sl as UIInteraction,fl as UIInteractionPlugin,ll as UILayoutGeneration,cl as UILayoutPlugin,qa as UIMask,Ga as UIMaskPlugin,sa as UIRect,Sc as UIRenderOrderPlugin,Er as UIRenderer,Tc as UIThemeRes,Cr as UIVisualType,ve as Velocity,ku as WebAssetProvider,yt as World,_e as WorldTransform,Yt as addStartupSystem,jt as addSystem,qt as addSystemToSchedule,_h as animationPlugin,z as applyBuildRuntimeConfig,ha as applyDirectionalFill,to as applyOverrides,B as applyRuntimeConfig,Gi as assetPlugin,ni as audioPlugin,Js as calculateAttenuation,Zs as calculatePanning,ir as cleanupAllPostProcessVolumes,sr as cleanupPostProcessVolume,En as clearAnimClips,Co as clearDrawCallbacks,zn as clearTextureDimensionsCache,Dn as clearTilemapSourceCache,qs as clearTimelineHandles,ne as clearUserComponents,Qi as cloneComponentData,Zi as cloneComponents,so as collectNestedPrefabPaths,N as color,ka as colorScale,Ra as colorWithAlpha,la as computeFillAnchors,ua as computeFillSize,ca as computeHandleAnchors,oa as computeUIRectLayout,Eu as createRuntimeSceneConfig,jh as createWebApp,Vu as debug,Ih as defaultFrameStats,Q as defineComponent,Bt as defineEvent,Ge as defineResource,Nt as defineSystem,ee as defineTag,Dl as dragPlugin,uc as dropdownPlugin,ju as error,vn as extractAnimClipTexturePaths,Ti as findEntityByName,no as flattenPrefab,Hr as flushPendingSystems,Zl as focusPlugin,Bi as getAddressableType,Ui as getAddressableTypeByEditorType,Li as getAllAssetExtensions,Qo as getAllEffectDefs,Cn as getAnimClip,Xi as getAssetBuildTransform,Oi as getAssetMimeType,Ii as getAssetTypeEntry,le as getComponent,gi as getComponentAssetFieldDescriptors,mi as getComponentAssetFields,Be as getComponentDefaults,q as getComponentEntityFields,_i as getComponentSpineFieldDescriptor,Di as getCustomExtensions,Fi as getEditorType,Jo as getEffectDef,Zo as getEffectTypes,Ou as getLogger,t as getPlatform,s as getPlatformType,Un as getTextureDimensions,Hn as getTilemapSource,Ys as getTimelineHandle,te as getUserComponent,$i as getWeChatPackOptions,Ml as imagePlugin,Nu as info,go as initDrawAPI,Sr as initGLDebugAPI,Fo as initGeometryAPI,ln as initMaterialAPI,wh as initParticleAPI,Vh as initPlayableRuntime,Xo as initPostProcessAPI,xr as initRendererAPI,Au as initRuntime,On as initTilemapAPI,hh as initTweenAPI,Ec as initUIBuilder,Qt as inputPlugin,oo as instantiatePrefab,Ja as intersectRects,Za as invertMatrix4,oe as isBuiltinComponent,Wi as isCustomExtension,Ps as isEditor,zi as isKnownAssetExtension,n as isPlatformInitialized,Es as isPlayMode,Ts as isRuntime,nn as isTextureRef,i as isWeChat,o as isWeb,fc as layoutGroupPlugin,ac as listViewPlugin,Mi as loadComponent,Gc as loadPhysicsModule,Cu as loadRuntimeScene,bi as loadSceneData,vi as loadSceneWithAssets,es as loadTiledMap,Hi as looksLikeAssetPath,Pa as makeInteractable,Sn as parseAnimClipData,Jn as parseTiledMap,bs as parseTimelineAsset,Gn as parseTmjJson,Mh as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,nl as pointInOBB,el as pointInWorldRect,dr as postProcessPlugin,co as prefabsPlugin,io as preloadNestedPrefabs,Bl as progressBarPlugin,X as quat,Pn as registerAnimClip,Ni as registerAssetBuildTransform,ae as registerComponent,pi as registerComponentAssetFields,Y as registerComponentEntityFields,Po as registerDrawCallback,Ji as registerEmbeddedAssets,yn as registerMaterialCallback,Bn as registerTextureDimensions,Ln as registerTilemapSource,oi as registerTimelineAsset,eo as remapComponentEntityRefs,yi as remapEntityFields,Kn as resolveRelativePath,nc as safeAreaPlugin,zr as sceneManagerPlugin,Qa as screenToWorld,Nl as scrollViewPlugin,Ms as setEditorMode,Ea as setEntityColor,Aa as setEntityEnabled,oc as setListViewRenderer,Wu as setLogLevel,Cs as setPlayMode,at as setWasmErrorHandler,_o as shutdownDrawAPI,Mr as shutdownGLDebugAPI,Bo as shutdownGeometryAPI,cn as shutdownMaterialAPI,bh as shutdownParticleAPI,jo as shutdownPostProcessAPI,wr as shutdownRendererAPI,Wn as shutdownTilemapAPI,dh as shutdownTweenAPI,Kl as sliderPlugin,kn as spriteAnimatorSystemUpdate,Hh as statsPlugin,Sa as syncFillSpriteSize,nr as syncPostProcessVolume,wl as textInputPlugin,ja as textPlugin,Eh as tilemapPlugin,di as timelinePlugin,Vi as toBuildPath,kl as togglePlugin,Nc as transitionTo,pl as uiInteractionPlugin,ul as uiLayoutPlugin,Ka as uiMaskPlugin,Nh as uiPlugins,Mc as uiRenderOrderPlugin,Tn as unregisterAnimClip,se as unregisterComponent,To as unregisterDrawCallback,Pi as updateCameraAspectRatio,O as vec2,W as vec3,V as vec4,Xu as warn,Ta as withChildEntity,Br as wrapSceneSystem};+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 i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class _{constructor(e,t,n,s,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=n,this.poolNode_=s,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class y{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new g(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const n=this.loadingUrls_.get(e);if(n)return n;const s=this.doLoadBuffer_(e);this.loadingUrls_.set(e,s);try{return await s}finally{this.loadingUrls_.delete(e)}}async loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const n=this.urlToId_.get(e);if(void 0!==n&&this.buffers_.has(n)){return{id:n,duration:this.buffers_.get(n).duration}}let s;try{s=await this.context_.decodeAudioData(t)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,s),this.urlToId_.set(e,i),{id:i,duration:s.duration}}async doLoadBuffer_(e){const n=await t().readFile(e);return this.loadBufferFromData(e,n)}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const n=this.buffers_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=n,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(s.gain),s.source=i,s.gain.gain.value=t.volume??1,s.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;s.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new _(l,i,n,s,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const x=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 loadImagePixels(e){const t=this.createImage();await new Promise((n,s)=>{t.crossOrigin="anonymous",t.onload=()=>n(),t.onerror=()=>s(new Error(`Failed to load image: ${e}`)),t.src=e});const n=this.createCanvas(t.width,t.height).getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(s.data.buffer)}}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),i=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},r=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{t.preventDefault();const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{t.preventDefault();const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=t=>{t.preventDefault(),e.onPointerUp(0)},h=()=>{e.onPointerUp(0)},d=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",o),n.addEventListener("mousedown",r),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l,{passive:!1}),n.addEventListener("touchmove",c,{passive:!1}),n.addEventListener("touchend",u,{passive:!1}),n.addEventListener("touchcancel",h),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("touchcancel",h),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}getStorageItem(e){return localStorage.getItem(e)}setStorageItem(e,t){localStorage.setItem(e,t)}removeStorageItem(e){localStorage.removeItem(e)}clearStorage(e){const t=[];for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);null!==s&&s.startsWith(e)&&t.push(s)}for(const e of t)localStorage.removeItem(e)}},w=1920,b=1080,v=100,S=512,M={x:100,y:100},P="Arial",T=24,C=1.2,E=.5,A=1/60,k={x:0,y:-9.81},R=1/60,I="default",F={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};function B(e){e.Text&&(e.Text._default.fontFamily=F.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=F.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=F.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=F.canvasMatchWidthOrHeight)}const U={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function z(e,t){if(void 0!==t.maxDeltaTime&&(F.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(F.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(F.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(F.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(F.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");F.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(F.canvasScaleMode=U[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(F.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(F.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(F.assetFailureCooldown=t.assetFailureCooldown)}const H=0,L=4294967295,D=4294967295,$=0,W=(e=0,t=0)=>({x:e,y:t}),O=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),V=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),N=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),X=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s}),j=new Map;function Y(e,t){j.set(e,t)}function q(e){return j.get(e)}function G(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(G);const t={};for(const n in e)t[n]=G(e[n]);return t}let K=0;function J(e,t){const n=++K,s=function(e){const t=[],n=[],s=[];let i=!1;for(const o in e){const r=e[o];null!==r&&"object"==typeof r?(i=!0,Array.isArray(r)?s.push(o):n.push(o)):t.push(o)}return i?{flatKeys:t,objectKeys:n,arrayKeys:s}:null}(t),i=t;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create(e){if(s){const t={...i};for(const e of s.objectKeys)t[e]={...i[e]};for(const e of s.arrayKeys)t[e]=i[e].slice();return e&&Object.assign(t,e),t}return e?{...t,...e}:{...t}}}}function Z(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Q(e,t,n){const s=re.get(e)??Z().get(e);if(s)return s;const i=J(e,t);return Z().set(e,i),re.set(e,i),ie(e,t,!1),n?.entityFields&&Y(e,n.entityFields),i}function ee(e){const t=re.get(e)??Z().get(e);if(t)return t;const n=J(e,{});return Z().set(e,n),re.set(e,n),ie(e,{},!0),n}function te(e){return Z().get(e)}function ne(){const e=Z();for(const t of e.keys())re.delete(t);e.clear()}function se(e){Z().delete(e),re.delete(e)}function ie(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function oe(e){return!0===e._builtin}const re=new Map;function ae(e,t){re.set(e,t)}function le(e){return re.get(e)??te(e)}function ce(e){if(null===e||"object"!=typeof e)return[];const t=[];for(const n of Object.keys(e)){const s=e[n];if(null!==s&&"object"==typeof s&&!Array.isArray(s)){"r"in s&&"g"in s&&"b"in s&&"a"in s&&t.push(n)}}return t}function ue(e,t,n){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t,_colorKeys:ce(t)};return re.set(e,s),s}const he={Perspective:0,Orthographic:1},de={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},fe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},pe={Circle:0,Capsule:1,RoundedRect:2},me=ue("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),ge=me,_e=me,ye=ue("Sprite",{texture:L,color:{r:1,g:1,b:1,a:1},size:{x:M.x,y:M.y},pivot:{x:.5,y:.5},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),xe=ue("ShapeRenderer",{shapeType:pe.Circle,color:{r:1,g:1,b:1,a:1},size:{x:100,y:100},cornerRadius:0,layer:0,enabled:!0}),we=ue("Camera",{projectionType:he.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:de.ColorAndDepth}),be=ue("Canvas",{designResolution:{x:w,y:b},pixelsPerUnit:100,scaleMode:fe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ve=ue("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Se=ue("Parent",{entity:0}),Me=ue("Children",{entities:[]}),Pe=ue("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:D,enabled:!0}),Te=ue("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,enabled:!0}),Ce={Point:0,Circle:1,Rectangle:2,Cone:3},Ee={World:0,Local:1},Ae={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},ke=ue("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:Ce.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:Ae.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:Ae.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:L,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:Ee.World,enabled:!0}),Re=Q("Name",{value:""}),Ie=Q("SceneOwner",{scene:"",persistent:!1}),Fe=Q("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function Be(e){const t=le(e);return t?G(t._default):null}const Ue=ue("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ze=ue("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},radius:.05,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),He=ue("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Le=ue("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),De=ue("SegmentCollider",{point1:{x:-.5,y:0},point2:{x:.5,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),$e=Q("PolygonCollider",{vertices:[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}],radius:0,density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),We=Q("ChainCollider",{points:[{x:-1,y:0},{x:0,y:.5},{x:1,y:0},{x:0,y:-.5}],isLoop:!0,friction:.6,restitution:0,categoryBits:1,maskBits:65535,enabled:!0}),Oe=Q("RevoluteJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},enableMotor:!1,motorSpeed:0,maxMotorTorque:0,enableLimit:!1,lowerAngle:0,upperAngle:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Ve=Q("DistanceJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},length:1,enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,minLength:.5,maxLength:2,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Ne=Q("PrismaticJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:1,y:0},enableSpring:!1,hertz:1,dampingRatio:.5,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorForce:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Xe=Q("WeldJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},linearHertz:0,angularHertz:0,linearDampingRatio:1,angularDampingRatio:1,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),je=Q("WheelJoint",{connectedEntity:-1,anchorA:{x:0,y:0},anchorB:{x:0,y:0},axis:{x:0,y:1},enableSpring:!0,hertz:5,dampingRatio:.7,enableLimit:!1,lowerTranslation:0,upperTranslation:0,enableMotor:!1,maxMotorTorque:0,motorSpeed:0,collideConnected:!1,enabled:!0},{entityFields:["connectedEntity"]}),Ye={Static:0,Kinematic:1,Dynamic:2};let qe=0;function Ge(e,t){const n=++qe;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Ke(e){return{_type:"res",_resource:e}}function Je(e){return{_type:"res_mut",_resource:e}}class Ze{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_)}updateValue(e){this.value_=e}}class Qe{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Ze(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const et=Ge({delta:0,elapsed:0,frameCount:0},"Time"),tt="esengine:",nt={getString(e,n){const s=t().getStorageItem(tt+e);return null!==s?s:n},setString(e,n){t().setStorageItem(tt+e,n)},getNumber(e,n){const s=t().getStorageItem(tt+e);if(null===s)return n;const i=Number(s);return Number.isNaN(i)?n:i},setNumber(e,n){t().setStorageItem(tt+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(tt+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(tt+e,String(n))},getJSON(e,n){const s=t().getStorageItem(tt+e);if(null===s)return n;try{return JSON.parse(s)}catch(t){return console.warn(`[Storage] Failed to parse JSON for key "${e}"`,t),n}},setJSON(e,n){t().setStorageItem(tt+e,JSON.stringify(n))},remove(e){t().removeStorageItem(tt+e)},has:e=>null!==t().getStorageItem(tt+e),clear(){t().clearStorage(tt)}};function st(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=it(t[e]),o=it(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function it(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ot(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let rt=null;function at(e){rt=e}function lt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),rt&&rt(e,t)}function ct(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={r:t.x,g:t.y,b:t.z,a:t.w})}return n}function ut(e,t){if(0===t.length)return e;const n={...e};for(const e of t){const t=n[e];t&&"object"==typeof t&&(n[e]={x:t.r,y:t.g,z:t.b,w:t.a})}return n}const ht={Transform:{ptrFn:"getTransformPtr",fields:[{name:"position",type:"vec3",offset:0},{name:"rotation",type:"quat",offset:12},{name:"scale",type:"vec3",offset:28},{name:"worldPosition",type:"vec3",offset:40},{name:"worldRotation",type:"quat",offset:52},{name:"worldScale",type:"vec3",offset:68}]},Sprite:{ptrFn:"getSpritePtr",fields:[{name:"texture",type:"u32",offset:0},{name:"color",type:"color",offset:4},{name:"size",type:"vec2",offset:20},{name:"uvOffset",type:"vec2",offset:28},{name:"uvScale",type:"vec2",offset:36},{name:"layer",type:"i32",offset:44},{name:"flipX",type:"bool",offset:48},{name:"flipY",type:"bool",offset:49},{name:"material",type:"u32",offset:52},{name:"enabled",type:"bool",offset:56}]},Velocity:{ptrFn:"getVelocityPtr",fields:[{name:"linear",type:"vec3",offset:0},{name:"angular",type:"vec3",offset:12}]},Camera:{ptrFn:"getCameraPtr",fields:[{name:"projectionType",type:"u8",offset:0},{name:"fov",type:"f32",offset:4},{name:"orthoSize",type:"f32",offset:8},{name:"nearPlane",type:"f32",offset:12},{name:"farPlane",type:"f32",offset:16},{name:"aspectRatio",type:"f32",offset:20},{name:"isActive",type:"bool",offset:24},{name:"priority",type:"i32",offset:28},{name:"viewportX",type:"f32",offset:32},{name:"viewportY",type:"f32",offset:36},{name:"viewportW",type:"f32",offset:40},{name:"viewportH",type:"f32",offset:44},{name:"clearFlags",type:"i32",offset:48}]},UIRect:{ptrFn:"getUIRectPtr",fields:[{name:"anchorMin",type:"vec2",offset:0},{name:"anchorMax",type:"vec2",offset:8},{name:"offsetMin",type:"vec2",offset:16},{name:"offsetMax",type:"vec2",offset:24},{name:"size",type:"vec2",offset:32},{name:"pivot",type:"vec2",offset:40}]},RigidBody:{ptrFn:"getRigidBodyPtr",fields:[{name:"bodyType",type:"u8",offset:0},{name:"gravityScale",type:"f32",offset:4},{name:"linearDamping",type:"f32",offset:8},{name:"angularDamping",type:"f32",offset:12},{name:"fixedRotation",type:"bool",offset:16},{name:"bullet",type:"bool",offset:17},{name:"enabled",type:"bool",offset:18}]},BoxCollider:{ptrFn:"getBoxColliderPtr",fields:[{name:"halfExtents",type:"vec2",offset:0},{name:"offset",type:"vec2",offset:8},{name:"density",type:"f32",offset:16},{name:"friction",type:"f32",offset:20},{name:"restitution",type:"f32",offset:24},{name:"isSensor",type:"bool",offset:28},{name:"enabled",type:"bool",offset:29},{name:"categoryBits",type:"u32",offset:32},{name:"maskBits",type:"u32",offset:36}]},CircleCollider:{ptrFn:"getCircleColliderPtr",fields:[{name:"radius",type:"f32",offset:0},{name:"offset",type:"vec2",offset:4},{name:"density",type:"f32",offset:12},{name:"friction",type:"f32",offset:16},{name:"restitution",type:"f32",offset:20},{name:"isSensor",type:"bool",offset:24},{name:"enabled",type:"bool",offset:25},{name:"categoryBits",type:"u32",offset:28},{name:"maskBits",type:"u32",offset:32}]}};function dt(e,t,n,s,i,o){const r=s+i.offset,a=r>>2;switch(i.type){case"f32":e[a]=o;break;case"i32":t[a]=0|o;break;case"u32":t[a]=o;break;case"bool":n[r]=o?1:0;break;case"u8":n[r]=o;break;case"vec2":e[a]=o.x,e[a+1]=o.y;break;case"vec3":e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z;break;case"quat":e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z,e[a+3]=o.w;break;case"color":e[a]=o.r,e[a+1]=o.g,e[a+2]=o.b,e[a+3]=o.a}}let ft=1;const pt=new WeakMap;function mt(e){let t=pt.get(e);return void 0===t&&(t=ft++,pt.set(e,t)),t}const gt=[];function _t(e,t=[],n=[]){gt.length=0;for(const t of e)gt.push(mt(t));gt.sort((e,t)=>e-t);let s=gt.join(",");if(t.length>0){gt.length=0;for(const e of t)gt.push(mt(e));gt.sort((e,t)=>e-t),s+="|+"+gt.join(",")}if(n.length>0){gt.length=0;for(const e of n)gt.push(mt(e));gt.sort((e,t)=>e-t),s+="|-"+gt.join(",")}return s}class yt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.builtinEntitySets_=new Map,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map,this.trackedComponents_=new Set}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}getWasmModule(){return this.module_}spawn(e){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let t;if(this.cppRegistry_)try{t=this.cppRegistry_.create()}catch(e){throw lt(e,"spawn"),e}else t=++this.nextEntityId_;let n=0;if(this.module_&&this.cppRegistry_)try{n=this.module_.registry_getGeneration(this.cppRegistry_,t)}catch{}else n=++this.nextGeneration_;this.entities_.set(t,n),this.worldVersion_++,void 0!==e&&this.insert(t,Re,{value:e});for(const e of this.spawnCallbacks_)try{e(t)}catch(e){console.warn("[World] Spawn callback error:",e)}return t}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch(e){console.warn("[World] Despawn callback error:",e)}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){lt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;for(const[,t]of this.builtinEntitySets_)t.delete(e);const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){lt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){lt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return oe(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(oe(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,ut(o,t._colorKeys))}catch(n){lt(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return oe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){if(t._builtin){if(!this.cppRegistry_)return!1;const n=t._cppName,s=this.builtinEntitySets_.get(n);return s?s.has(e):this.getBuiltinMethods(n).has(e)}return this.hasScript(e,t)}tryGet(e,t){if(oe(t)){if(!this.cppRegistry_)return null;const n=this.builtinEntitySets_.get(t._cppName);if(n&&!n.has(e))return null;try{const s=this.getBuiltinMethods(t._cppName);return n||s.has(e)?ct(s.get(e),t._colorKeys):null}catch(n){return lt(n,`tryGet(${t._name}, entity=${e})`),null}}const n=this.tsStorage_.get(t._id);if(!n)return null;const s=n.get(e);return void 0!==s?s:null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");oe(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=st(t._name,s,i);if(e.length>0)throw new Error(ot(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,ut(o,t._colorKeys))}catch(n){lt(n,`insertBuiltin(${t._name}, entity=${e})`)}let a=this.builtinEntitySets_.get(t._cppName);a||(a=new Set,this.builtinEntitySets_.set(t._cppName,a));const l=a.has(e);return!r&&l||(l||a.add(e),this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return ct(this.getBuiltinMethods(t._cppName).get(e),t._colorKeys)}catch(n){return lt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return lt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){lt(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++,this.builtinEntitySets_.get(t._cppName)?.delete(e)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=st(t._name,t._default,e);if(i.length>0)throw new Error(ot(t._name,i));s=e}const i=t.create(s),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=new Set,this.entityComponents_.set(e,a)),a.add(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);s&&s.delete(t._id)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resolveGetter(e){if(oe(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrGetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?e=>t.get(e):e=>ct(t.get(e),n)}const t=this.tsStorage_.get(e._id);return t?e=>t.get(e):null}resolveHas(e){if(oe(e)){if(!this.cppRegistry_)return null;const t=this.getBuiltinMethods(e._cppName);return e=>t.has(e)}const t=this.tsStorage_.get(e._id);return t?e=>t.has(e):null}resolveSetter(e){if(oe(e)){if(!this.cppRegistry_)return null;if(this.module_){const t=this.resolvePtrSetter_(e._cppName);if(t)return t}const t=this.getBuiltinMethods(e._cppName),n=e._colorKeys;return 0===n.length?(e,n)=>t.add(e,n):(e,s)=>t.add(e,ut(s,n))}const t=this.tsStorage_.get(e._id);return t?(e,n)=>t.set(e,n):null}resolvePtrFn_(e){const t=ht[e];if(!t)return null;const n=this.module_[t.ptrFn];if(!n)return null;const s=this.cppRegistry_;return e=>n(s,e)}resolvePtrSetter_(e){const t=ht[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,i=t.fields;return(e,t)=>{const o=n(e);if(!o)return;const r=t;for(let e=0;e<i.length;e++)dt(s.HEAPF32,s.HEAPU32,s.HEAPU8,o,i[e],r[i[e].name])}}resolvePtrGetter_(e){const t=ht[e];if(!t)return null;const n=this.resolvePtrFn_(e);if(!n)return null;const s=this.module_,i=t.fields,o=function(e){const t={};for(const n of e)switch(n.type){case"vec2":t[n.name]={x:0,y:0};break;case"vec3":t[n.name]={x:0,y:0,z:0};break;case"quat":t[n.name]={x:0,y:0,z:0,w:0};break;case"color":t[n.name]={r:0,g:0,b:0,a:0};break;default:t[n.name]=null}return t}(i);return e=>{const t=n(e);return t?(function(e,t,n,s,i,o){for(let r=0;r<i.length;r++){const a=i[r],l=s+a.offset,c=l>>2;switch(a.type){case"f32":o[a.name]=e[c];break;case"i32":o[a.name]=0|t[c];break;case"u32":o[a.name]=t[c];break;case"bool":o[a.name]=0!==n[l];break;case"u8":o[a.name]=n[l];break;case"vec2":{const t=o[a.name];t.x=e[c],t.y=e[c+1];break}case"vec3":{const t=o[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2];break}case"quat":{const t=o[a.name];t.x=e[c],t.y=e[c+1],t.z=e[c+2],t.w=e[c+3];break}case"color":{const t=o[a.name];t.r=e[c],t.g=e[c+1],t.b=e[c+2],t.a=e[c+3];break}}}}(s.HEAPF32,s.HEAPU32,s.HEAPU8,t,i,o),o):null}}resetQueryPool(){}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch(e){console.warn(`[World] Component check failed for ${n}:`,e)}if(this.cppRegistry_)for(const[n,s]of re)if(oe(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch(e){console.warn(`[World] Builtin check failed for ${n}:`,e)}const n=this.entityComponents_.get(e);if(n){const e=Z();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}resolveStorages_(e,t,n){for(const s of e)if(oe(s)){if(!this.cppRegistry_)return!1;n.push(this.getBuiltinMethods(s._cppName))}else{const e=this.tsStorage_.get(s._id);if(!e)return!1;t.push(e)}return!0}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??_t(e,t,n),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;const r=[],a=[],l=[];if(!this.resolveStorages_(e,a,l))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),r;let c=null,u=null;if(t.length>0&&(c=[],u=[],!this.resolveStorages_(t,c,u)))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),r;let h=null,d=null;n.length>0&&(h=[],d=[],this.resolveStorages_(n,h,d));let f=null,p=1/0;for(let e=0;e<a.length;e++){const t=a[e].size;t<p&&(p=t,f=a[e])}for(const t of e)if(oe(t)){const e=this.builtinEntitySets_.get(t._cppName);e&&e.size<p&&(p=e.size,f=e)}const m=f?f.keys():this.entities_.keys(),g=a.length,_=l.length;for(const e of m){let t=!0;for(let n=0;n<g;n++)if(!a[n].has(e)){t=!1;break}if(t)for(let n=0;n<_;n++)if(!l[n].has(e)){t=!1;break}if(t&&c){for(let n=0;n<c.length;n++)if(!c[n].has(e)){t=!1;break}if(t)for(let n=0;n<u.length;n++)if(!u[n].has(e)){t=!1;break}}if(t&&h){for(let n=0;n<h.length;n++)if(h[n].has(e)){t=!1;break}if(t)for(let n=0;n<d.length;n++)if(d[n].has(e)){t=!1;break}}t&&r.push(e)}return this.queryCache_.set(i,{version:this.worldVersion_,result:r}),r}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}enableChangeTracking(e){this.trackedComponents_.add(e._id)}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}markChanged(e,t){this.recordChangedTick_(t,e)}recordChangedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){if(!this.trackedComponents_.has(e._id))return;let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function xt(e){return{_type:"mut",_component:e}}function wt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function bt(e){return{_filterType:"added",_component:e}}function vt(e){return{_filterType:"changed",_component:e}}function St(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Mt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Pt(e){return wt(e)||St(e)||Mt(e)?e._component:e}function Tt(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{wt(e)&&s.push(t),St(e)?i.push({index:t,component:e._component}):Mt(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Tt(e,[...t,...s],n),without:(...s)=>Tt(e,t,[...n,...s])}}function Ct(...e){return Tt(e)}class Et{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Pt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=_t(this.allRequired_,t._with,t._without),this.getters_=this.actualComponents_.map(t=>e.resolveGetter(t)),this.mutSetters_=t._mutIndices.map(t=>e.resolveSetter(this.actualComponents_[t])),this.mutIsBuiltin_=t._mutIndices.map(e=>oe(this.actualComponents_[e]));for(const n of t._addedFilters)e.enableChangeTracking(n.component);for(const n of t._changedFilters)e.enableChangeTracking(n.component)}resetTick(e){this.lastRunTick_=e}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,h=this.getters_,d=this;let f=0,p=null,m=!1,g=!1;const _=this.mutIsBuiltin_,y=()=>{for(let e=0;e<l;e++){const t=a[e];if(_[e]){const n=c[e];n?n(p,t.data):u.set(p,t.component,t.data)}else u.markChanged(p,t.component)}},x=()=>{g||(g=!0,u.endIteration(),null!==p&&i&&y())},w={value:r,done:!1},b={value:void 0,done:!0};return{next(){for(m||(m=!0,u.beginIteration());f<n.length;){const c=n[f++];if(!o||d.passesChangeFilters_(c)){null!==p&&i&&y(),r[0]=c;for(let e=0;e<s;e++){const n=h[e];r[e+1]=n?n(c):u.get(c,t[e])}if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];p=c}return w}}return x(),b},return:()=>(x(),b)}}forEach(e){const{_mutIndices:t}=this.descriptor_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=this.actualComponents_.length,i=t.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length,c=this.mutSetters_,u=this.world_,h=this.getters_,d=this.actualComponents_;u.beginIteration();let f=null;for(let p=0;p<n.length;p++){const m=n[p];if(!o||this.passesChangeFilters_(m)){if(null!==f&&i)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}r[0]=m;for(let e=0;e<s;e++){const t=h[e];r[e+1]=t?t(m):u.get(m,d[e])}if(i){for(let e=0;e<l;e++)a[e].data=r[t[e]+1];f=m}switch(s){case 1:e(m,r[1]);break;case 2:e(m,r[1],r[2]);break;case 3:e(m,r[1],r[2],r[3]);break;default:e.apply(null,r)}}}if(null!==f&&i)for(let e=0;e<l;e++){const t=a[e];if(this.mutIsBuiltin_[e]){const n=c[e];n?n(f,t.data):u.set(f,t.component,t.data)}else u.markChanged(f,t.component)}u.endIteration()}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function At(e){return{_type:"removed",_component:e}}class kt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n,e.enableChangeTracking(t)}resetTick(e){this.lastRunTick_=e}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function Rt(){return{_type:"commands"}}class It{constructor(e,t,n){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0,void 0!==n&&this.insert(Re,{value:n})):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=oe(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 Ft{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(e){const t=new It(this,null,e);return this.spawned_.push(t),t}entity(e){return new It(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function Bt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Ut{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class zt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ut)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ut,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Ht(e){return{_type:"event_writer",_event:e}}function Lt(e){return{_type:"event_reader",_event:e}}class Dt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class $t{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Wt;function Ot(){return{_type:"get_world"}}!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"}(Wt||(Wt={}));let Vt=0;function Nt(e,t,n){const s=++Vt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Xt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function jt(e){Xt().push({schedule:Wt.Update,system:e})}function Yt(e){Xt().push({schedule:Wt.Startup,system:e})}function qt(e,t){Xt().push({schedule:e,system:t})}class Gt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.queryCache_=new Map,this.removedCache_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;let n=this.queryCache_.get(e._id),s=this.removedCache_.get(e._id);const i=!n;i&&(n=[],s=[],this.queryCache_.set(e._id,n),this.removedCache_.set(e._id,s));let o=0,r=0;for(let a=0;a<e._params.length;a++){const l=e._params[a];if("query"===l._type){if(i){const e=new Et(this.world_,l,this.currentLastRunTick_);n.push(e),t[a]=e}else{const e=n[o];e.resetTick(this.currentLastRunTick_),t[a]=e}o++}else if("removed"===l._type){if(i){const e=l,n=new kt(this.world_,e._component,this.currentLastRunTick_);s.push(n),t[a]=n}else{const e=s[r];e.resetTick(this.currentLastRunTick_),t[a]=e}r++}else t[a]=this.resolveParam(l)}const a=this.timings_?performance.now():0;let l;try{l=e._fn(...t)}catch(n){throw this.flushSystem_(e,t,a),n}if(l instanceof Promise)return l.then(()=>{this.flushSystem_(e,t,a)},n=>{throw this.flushSystem_(e,t,a),n});this.flushSystem_(e,t,a)}flushSystem_(e,t,n){for(let e=0;e<t.length;e++)t[e]instanceof Ft&&t[e].flush();this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}resolveParam(e){switch(e._type){case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ft(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Dt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new $t(n)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Kt{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 Jt=Ge(new Kt,"Input");class Zt{constructor(e){this.target_=e??null}build(e){const n=new Kt;e.insertResource(Jt,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(Wt.Last,Nt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Qt=new Zt,en=Ge({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var tn;function nn(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"}(tn||(tn={}));let sn=null,on=null,rn=1;const an=new Map;function ln(e){sn=e,on=e.getResourceManager(),yn()}function cn(){0!==fn&&sn&&(sn._free(fn),fn=0),an.clear(),rn=1,dn=!1,mn.clear(),gn=null,on=null,sn=null}function un(){if(!on)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return on}const hn={createShader:(e,t)=>un().createShader(e,t),releaseShader(e){e>0&&un().releaseShader(e)},create(e){const t=rn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??tn.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return an.set(t,n),t},get:e=>an.get(e),setUniform(e,t,n){const s=an.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,sn?.invalidateMaterialCache(e))},getUniform(e,t){const n=an.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=an.get(e);n&&(n.blendMode=t,sn?.invalidateMaterialCache(e))},getBlendMode(e){const t=an.get(e);return t?.blendMode??tn.Normal},setDepthTest(e,t){const n=an.get(e);n&&(n.depthTest=t,sn?.invalidateMaterialCache(e))},getShader(e){const t=an.get(e);return t?.shader??0},release(e){an.delete(e),sn?.invalidateMaterialCache(e)},isValid:e=>an.has(e),releaseAll(){an.clear(),sn?.clearMaterialCache()},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??tn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=an.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=rn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return an.set(n,s),n},toAssetData(e,t){const n=an.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=an.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let dn=!1,fn=0;const pn=16384,mn=new Map;let gn=null;function _n(e){const t=(0===fn&&sn&&(fn=sn._malloc(pn)),fn);if(0===t||!sn)return{ptr:0,count:0};let n=0,s=0;const i=sn.HEAPU8,o=sn.HEAPU32,r=sn.HEAPF32;for(const[a,l]of e){if(nn(l))continue;let e=mn.get(a);e||(gn||(gn=new TextEncoder),e=gn.encode(a),mn.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>pn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${pn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function yn(){if(!sn||dn)return;sn.materialDataProvider=(e,t,n,s,i)=>{const o=an.get(e);if(!o)return sn.HEAPU32[t>>2]=0,sn.HEAPU32[n>>2]=0,sn.HEAPU32[s>>2]=0,void(sn.HEAPU32[i>>2]=0);sn.HEAPU32[t>>2]=o.shader,sn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=_n(o.uniforms);sn.HEAPU32[s>>2]=r,sn.HEAPU32[i>>2]=a},dn=!0}const xn={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 wn{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=F.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+F.assetFailureCooldown}),t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`)),t}}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()}clearAll(){this.cache_.clear(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class bn{constructor(e,t=""){this.cache_=new wn,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(hn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())hn.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:hn.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 vn(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Sn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0,duration:e.duration};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const Mn=new Map;function Pn(e){Mn.set(e.name,e)}function Tn(e){Mn.delete(e)}function Cn(e){return Mn.get(e)}function En(){Mn.clear()}const An=Q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function kn(e,t){const n=e.getEntitiesWithComponents([An]);for(const s of n){const n=e.get(s,An);if(!n.enabled||!n.playing||!n.clip)continue;const i=Mn.get(n.clip);if(!i||0===i.frames.length)continue;const o=i.frames[n.currentFrame],r=o?.duration??1/(i.fps*n.speed),a=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let l=a;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),l=!0),l&&e.has(s,ye)){const t=i.frames[n.currentFrame],o=e.get(s,ye);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,ye,o)}l&&e.insert(s,An,n)}}class Rn{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static setAssetResolver(e){this.assetResolver_=e}static resolveUrl_(e){return!this.baseUrl||e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}/${e}`}static async preload(e){if(this.bufferCache_.has(e))return;if(this.assetResolver_){const t=this.assetResolver_(e);if(t)return this.preloadFromData(e,t)}const t=await this.backend_.loadBuffer(this.resolveUrl_(e));this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}Rn.mixer_=null,Rn.bufferCache_=new Map,Rn.bgmHandle_=null,Rn.bgmVolume_=1,Rn.fadeAnimId_=0,Rn.disposed_=!1,Rn.assetResolver_=null,Rn.baseUrl="";const In=new Map,Fn=new Map;function Bn(e,t,n){In.set(e,{width:t,height:n})}function Un(e){return In.get(e)}function zn(){In.clear()}function Hn(e,t){Fn.set(e,t)}function Ln(e){return Fn.get(e)}function Dn(){Fn.clear()}let $n=null;function Wn(e){$n=e}function On(){$n=null}const Vn={initLayer(e,t,n,s,i){$n?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){$n?.tilemap_destroyLayer(e)},setTile(e,t,n,s){$n?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>$n?$n.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){$n?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!$n)return;const n=t.byteLength,s=$n._malloc(n);new Uint16Array($n.HEAPU8.buffer,s,t.length).set(t),$n.tilemap_setTiles(e,s,t.length),$n._free(s)},hasLayer:e=>!!$n&&$n.tilemap_hasLayer(e),setRenderProps(e,t,n,s,i,o,r,a,l){$n?.tilemap_setRenderProps(e,t,n,s,i,o,r,a,l)},setTint(e,t,n,s,i,o){$n?.tilemap_setTint(e,t,n,s,i,o)},setVisible(e,t){$n?.tilemap_setVisible(e,t)},setOriginEntity(e,t){$n?.tilemap_setOriginEntity(e,t)},submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,x){$n?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,x)},setTileAnimation(e,t,n){if(!$n||0===n.length)return;const s=new Uint32Array(2*n.length);for(let e=0;e<n.length;e++)s[2*e]=n[e].tileId,s[2*e+1]=n[e].duration;const i=s.byteLength,o=$n._malloc(i);new Uint32Array($n.HEAPU8.buffer,o,s.length).set(s),$n.tilemap_setTileAnimation(e,t,o,n.length),$n._free(o)},advanceAnimations(e,t){$n?.tilemap_advanceAnimations(e,t)},setTileProperty(e,t,n,s){$n?.tilemap_setTileProperty(e,t,n,s)},getTileProperty:(e,t,n,s)=>$n?$n.tilemap_getTileProperty(e,t,n,s):"",flipTile(e,t,n,s,i,o){$n?.tilemap_flipTile(e,t,n,s,i,o)},rotateTile(e,t,n,s){$n?.tilemap_rotateTile(e,t,n,s)},setGridType(e,t){$n?.tilemap_setGridType(e,t)},tileToWorld(e,t,n,s,i){if(!$n)return{x:0,y:0};const o=$n.tilemap_tileToWorld(e,t,n,s,i),r=new Float32Array($n.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}},worldToTile(e,t,n,s,i){if(!$n)return{x:0,y:0};const o=$n.tilemap_worldToTile(e,t,n,s,i),r=new Float32Array($n.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}}},Nn=Q("Tilemap",{source:""}),Xn=Q("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function jn(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function Yn(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function qn(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function Gn(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=qn(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,h=Yn(e.tintcolor),d="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:h,parallaxX:d,parallaxY:f})}const u=[],h=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}const d=new Map,f=new Map;if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.id,s=n+1,i=e.animation;if(i&&i.length>0){const e=i.map(e=>({tileId:(e.tileid??0)+1,duration:e.duration??100}));d.set(s,e)}const o=e.properties;if(o){const e=new Map;for(const s of o){const i=s.name;"collision"===i&&!0===s.value&&h.push(n+t),e.set(i,String(s.value))}e.size>0&&f.set(s,e)}}}return{width:t,height:n,tileWidth:s,tileHeight:i,orientation:e.orientation??"orthogonal",layers:c,tilesets:r,objectGroups:u,collisionTileIds:h,tileAnimations:d,tileProperties:f}}function Kn(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function Jn(e,t){const n=$n;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),orientation:"orthogonal",layers:[],tilesets:[],objectGroups:[],collisionTileIds:[],tileAnimations:new Map,tileProperties:new Map},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?jn(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch(e){return console.warn("[Tiled] Failed to parse tilemap",e),n.tiled_freeMap(r),null}}const Zn=Math.PI/180;function Qn(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,h=o+(u-t.row*c)-.5*s,d=e.spawn();e.insert(d,me,{position:{x:r,y:h,z:0}}),e.insert(d,Ue,{bodyType:Ye.Static}),e.insert(d,ze,{halfExtents:{x:.5*n,y:.5*s}}),a.push(d)}return a}function es(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,me,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Xn,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,h=-t.rotation*Zn;if(e.insert(r,me,{position:{x:c,y:u,z:0}}),e.insert(r,Ue,{bodyType:Ye.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,He,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,ze,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,ze,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,me,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=Qn(e,n,t,a,0,0);i.push(...s)}return i}const ts=0,ns=1,ss=2,is="property",os="spine",rs="spriteAnim",as="audio",ls="activation",cs="marker",us="customEvent",hs="animFrames",ds="hermite",fs="linear",ps="step",ms="easeIn",gs="easeOut",_s="easeInOut",ys=[["1.0","1.1",e=>{for(const t of e.tracks??[])if(t.type===is)for(const e of t.channels??[])for(const t of e.keyframes??[])t.interpolation||Math.abs(t.outTangent)>=1e5&&(t.interpolation="step",t.outTangent=0)}]];const xs={once:ts,loop:ns,pingPong:ss};function ws(e){const t={name:e.name??"",childPath:e.childPath??""};switch(e.type){case is:return{...t,type:is,component:e.component??"",channels:(e.channels??[]).map(e=>({property:e.property,keyframes:e.keyframes??[]}))};case os:return{...t,type:os,clips:e.clips??[],blendIn:e.blendIn??0};case rs:return{...t,type:rs,clip:e.clip??"",startTime:e.startTime??0};case as:return{...t,type:as,events:e.events??[]};case ls:return{...t,type:ls,ranges:e.ranges??[]};case cs:return{...t,type:cs,markers:e.markers??[]};case us:return{...t,type:us,events:(e.events??[]).map(e=>({time:e.time??0,name:e.name??"",payload:e.payload??{}}))};case hs:return{...t,type:hs,frames:(e.animFrames??[]).map(e=>({texture:e.texture??"",duration:e.duration}))};default:return console.warn(`[Timeline] Unknown track type: ${e.type}, skipping`),null}}function bs(e){return function(e){let t=e.version??"1.0";for(const[n,s,i]of ys)t===n&&(i(e),t=s);e.version="1.1"}(e),{version:"1.1",type:"timeline",duration:e.duration??0,wrapMode:(t=e.wrapMode,t?xs[t]??ts:ts),tracks:(e.tracks??[]).map(ws).filter(e=>null!==e)};var t}let vs=!1,Ss=!1;function Ms(e){vs=e}function Ps(){return vs}function Ts(){return!vs}function Cs(e){Ss=e}function Es(){return Ss}var As,ks;!function(e){e[e.PositionX=0]="PositionX",e[e.PositionY=1]="PositionY",e[e.PositionZ=2]="PositionZ",e[e.ScaleX=3]="ScaleX",e[e.ScaleY=4]="ScaleY",e[e.ScaleZ=5]="ScaleZ",e[e.RotationZ=6]="RotationZ",e[e.ColorR=7]="ColorR",e[e.ColorG=8]="ColorG",e[e.ColorB=9]="ColorB",e[e.ColorA=10]="ColorA",e[e.SpriteOpacity=11]="SpriteOpacity",e[e.SpriteSizeX=12]="SpriteSizeX",e[e.SpriteSizeY=13]="SpriteSizeY",e[e.OffsetMinX=14]="OffsetMinX",e[e.OffsetMinY=15]="OffsetMinY",e[e.OffsetMaxX=16]="OffsetMaxX",e[e.OffsetMaxY=17]="OffsetMaxY",e[e.AnchorMinX=18]="AnchorMinX",e[e.AnchorMinY=19]="AnchorMinY",e[e.AnchorMaxX=20]="AnchorMaxX",e[e.AnchorMaxY=21]="AnchorMaxY",e[e.PivotX=22]="PivotX",e[e.PivotY=23]="PivotY",e[e.CameraOrthoSize=24]="CameraOrthoSize",e[e.CustomField=25]="CustomField"}(As||(As={})),function(e){e[e.Transform=0]="Transform",e[e.Sprite=1]="Sprite",e[e.UIRect=2]="UIRect",e[e.Camera=3]="Camera",e[e.Custom=4]="Custom"}(ks||(ks={}));const Rs={Transform:{"position.x":As.PositionX,"position.y":As.PositionY,"position.z":As.PositionZ,"scale.x":As.ScaleX,"scale.y":As.ScaleY,"scale.z":As.ScaleZ,rotation:As.RotationZ},Sprite:{"color.r":As.ColorR,"color.g":As.ColorG,"color.b":As.ColorB,"color.a":As.ColorA,opacity:As.SpriteOpacity,"size.x":As.SpriteSizeX,"size.y":As.SpriteSizeY},UIRect:{"offsetMin.x":As.OffsetMinX,"offsetMin.y":As.OffsetMinY,"offsetMax.x":As.OffsetMaxX,"offsetMax.y":As.OffsetMaxY,"anchorMin.x":As.AnchorMinX,"anchorMin.y":As.AnchorMinY,"anchorMax.x":As.AnchorMaxX,"anchorMax.y":As.AnchorMaxY,"pivot.x":As.PivotX,"pivot.y":As.PivotY},Camera:{orthoSize:As.CameraOrthoSize}},Is={Transform:ks.Transform,Sprite:ks.Sprite,UIRect:ks.UIRect,Camera:ks.Camera},Fs={[ds]:0,[fs]:1,[ps]:2,[ms]:3,[gs]:4,[_s]:5};function Bs(e){return e?Fs[e]??0:0}function Us(e,t){return Rs[e]?.[t]??As.CustomField}function zs(e,t){const n=(new TextEncoder).encode(t),s=e._malloc(n.length);return new Uint8Array(e.HEAPU8.buffer,s,n.length).set(n),[s,n.length]}function Hs(e,t){e._free(t)}function Ls(e,t){const n=e._tl_create(t.duration,t.wrapMode);if(!n)return{handle:0,tracks:[],totalPropertyChannels:0};const s=[];let i=0;for(const o of t.tracks)switch(o.type){case is:Ds(e,n,o),s.push({type:"property",component:o.component,childPath:o.childPath,channelProperties:o.channels.map(e=>e.property)}),i+=o.channels.length;break;case os:$s(e,n,o),s.push({type:"spine",childPath:o.childPath});break;case as:Ws(e,n,o),s.push({type:"audio",childPath:o.childPath});break;case ls:Os(e,n,o),s.push({type:"activation",childPath:o.childPath});break;case rs:Vs(e,n,o),s.push({type:"spriteAnim",childPath:o.childPath})}return{handle:n,tracks:s,totalPropertyChannels:i}}function Ds(e,t,n){const s=e,i=n.channels.length,o=Is[n.component]??ks.Custom;if(o===ks.Custom)return void function(e,t,n){const s=e,i=n.channels.length,[o,r]=zs(e,n.childPath),[a,l]=zs(e,n.component),c=n.channels.map(e=>(new TextEncoder).encode(e.property));let u=0;for(const e of c)u+=e.length;const h=s._malloc(u);let d=0;for(const e of c)new Uint8Array(s.HEAPU8.buffer,h+d,e.length).set(e),d+=e.length;const f=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,f,i).set(c.map(e=>e.length));let p=0;const m=[];for(const e of n.channels)m.push(e.keyframes.length),p+=e.keyframes.length;const g=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,g,i).set(m);const _=s._malloc(5*p*4),y=new Float32Array(s.HEAPU8.buffer,_,5*p);let x=0;for(const e of n.channels)for(const t of e.keyframes)y[x++]=t.time,y[x++]=t.value,y[x++]=t.inTangent,y[x++]=t.outTangent,y[x++]=Bs(t.interpolation);e._tl_addCustomPropertyTrack(t,o,r,a,l,h,f,i,_,g),Hs(e,o),Hs(e,a),Hs(e,h),Hs(e,f),Hs(e,g),Hs(e,_)}(e,t,n);const[r,a]=zs(e,n.childPath),l=s._malloc(i),c=new Uint8Array(s.HEAPU8.buffer,l,i);for(let e=0;e<i;e++)c[e]=Us(n.component,n.channels[e].property);let u=0;const h=[];for(const e of n.channels)h.push(e.keyframes.length),u+=e.keyframes.length;const d=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,d,i).set(h);const f=s._malloc(5*u*4),p=new Float32Array(s.HEAPU8.buffer,f,5*u);let m=0;for(const e of n.channels)for(const t of e.keyframes)p[m++]=t.time,p[m++]=t.value,p[m++]=t.inTangent,p[m++]=t.outTangent,p[m++]=Bs(t.interpolation);e._tl_addPropertyTrack(t,r,a,o,l,i,f,d),Hs(e,r),Hs(e,l),Hs(e,d),Hs(e,f)}function $s(e,t,n){if(n.type!==os)return;const s=e,[i,o]=zs(e,n.childPath),r=n.clips.length,a=s._malloc(4*r*4),l=new Float32Array(s.HEAPU8.buffer,a,4*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),h=s._malloc(4*r),d=new Int32Array(s.HEAPU8.buffer,h,r),f=[];for(let t=0;t<r;t++){const s=n.clips[t];l[4*t]=s.start,l[4*t+1]=s.duration,l[4*t+2]=s.speed,l[4*t+3]=s.loop?1:0;const[i,o]=zs(e,s.animation);u[t]=i,d[t]=o,f.push(i)}e._tl_addSpineTrack(t,i,o,a,c,h,r,n.blendIn),Hs(e,i),Hs(e,a),Hs(e,c),Hs(e,h);for(const t of f)Hs(e,t)}function Ws(e,t,n){if(n.type!==as)return;const s=e,[i,o]=zs(e,n.childPath),r=n.events.length,a=s._malloc(2*r*4),l=new Float32Array(s.HEAPU8.buffer,a,2*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),h=s._malloc(4*r),d=new Int32Array(s.HEAPU8.buffer,h,r),f=[];for(let t=0;t<r;t++){const s=n.events[t];l[2*t]=s.time,l[2*t+1]=s.volume;const[i,o]=zs(e,s.clip);u[t]=i,d[t]=o,f.push(i)}e._tl_addAudioTrack(t,i,o,a,c,h,r),Hs(e,i),Hs(e,a),Hs(e,c),Hs(e,h);for(const t of f)Hs(e,t)}function Os(e,t,n){if(n.type!==ls)return;const s=e,[i,o]=zs(e,n.childPath),r=s._malloc(2*n.ranges.length*4),a=new Float32Array(s.HEAPU8.buffer,r,2*n.ranges.length);for(let e=0;e<n.ranges.length;e++)a[2*e]=n.ranges[e].start,a[2*e+1]=n.ranges[e].end;e._tl_addActivationTrack(t,i,o,r,n.ranges.length),Hs(e,i),Hs(e,r)}function Vs(e,t,n){if(n.type!==rs)return;const[s,i]=zs(e,n.childPath),[o,r]=zs(e,n.clip);e._tl_addSpriteAnimTrack(t,s,i,o,r,n.startTime),Hs(e,s),Hs(e,o)}const Ns=new Map;let Xs=null;function js(e,t){Ns.set(e,t)}function Ys(e){return Ns.get(e)}function qs(){if(Xs)for(const e of Ns.values())Xs._tl_destroy(e);Ns.clear()}var Gs;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Gs||(Gs={}));const Ks={model:Gs.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Js(e,t=Ks){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case Gs.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case Gs.Inverse:a=s/Math.max(r,s);break;case Gs.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Zs(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const Qs=Q("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Gs.Inverse,rolloff:1,priority:0,enabled:!0}),ei=Q("AudioListener",{enabled:!0});class ti{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;Rn.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(Wt.PreUpdate,Nt([Ke(et)],t=>{if(!(!Ps()||Es()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,h=!1;const d=s.getEntitiesWithComponents([ei,_e]);for(const e of d){if(s.get(e,ei).enabled){const t=s.get(e,_e);i=t.position.x,u=t.position.y,h=!0;break}}const f=s.getEntitiesWithComponents([Qs]);a.clear();for(const e of f){const t=s.get(e,Qs);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=Rn.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,_e),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=Js(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Zs(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),Rn.dispose()}}const ni=new ti,si=Q("TimelinePlayer",{timeline:"",playing:!1,speed:1,wrapMode:"once"}),ii=new Map;function oi(e,t){ii.set(e,t)}const ri=new Map;function ai(e,t){return ri.get(e)?.get(t)??0}const li={once:ts,loop:ns,pingPong:ss};function ci(e,t,n){const s=t.split(".");let i=e;for(let e=0;e<s.length-1;e++)if(i=i[s[e]],null==i||"object"!=typeof i)return!1;const o=s[s.length-1];return o in i&&(i[o]=n,!0)}function ui(e,t,n){if(!n)return t;const s=le("Children"),i=le("Name");if(!s||!i)return null;let o=t;const r=n.split("/");for(const t of r){const n=e.tryGet(o,s);if(!n)return null;const r=n.entities||[];let a=null;for(const n of r){const s=e.tryGet(n,i);if(s&&s.value===t){a=n;break}}if(null===a)return null;o=a}return o}class hi{constructor(){this.name="TimelinePlugin",this.handles_=new Map,this.animFramesStates_=new Map}build(e){const t=e.world;e.addSystemToSchedule(Wt.Update,Nt([Ke(et)],e=>{if(Ps()&&!Es())return;const n=t.getWasmModule();if(!n)return;Xs=n;const s=t.getCppRegistry();n.uiRect_clearAnimOverrides(s);const i=t.getEntitiesWithComponents([si]);for(const s of i){const i=t.get(s,si);if(!i.timeline)continue;let o=this.handles_.get(s);if(!o){const e=ii.get(i.timeline);if(!e)continue;if(o=Ls(n,e),!o.handle)continue;this.resolveTrackTargets(t,n,o,s),this.handles_.set(s,o),js(s,o.handle);const r=e.tracks.filter(e=>e.type===hs);r.length>0&&this.animFramesStates_.set(s,{tracks:r,lastFrameIndices:r.map(()=>-1)})}const r=o.handle;if(i.playing&&!n._tl_isPlaying(r)){const e=n._tl_getTime(r);0===e?n._tl_play(r):(n._tl_play(r),n._tl_setTime(r,e))}else!i.playing&&n._tl_isPlaying(r)&&n._tl_pause(r);const a=li[i.wrapMode]??ts;n._tl_setWrapMode(r,a),n._tl_advance(t.getCppRegistry(),r,s,e.delta,i.speed),this.processEvents(t,n),this.processCustomProperties(t,n,o),this.processAnimFrames(t,n,s,o.handle,i.timeline),n._tl_clearResults(),!n._tl_isPlaying(r)&&i.playing&&(i.playing=!1,t.insert(s,si,i))}},{name:"TimelineSystem"}))}clearHandles(){this.handles_.clear(),this.animFramesStates_.clear()}cleanup(){this.handles_.clear(),this.animFramesStates_.clear(),ii.clear()}processAnimFrames(e,t,n,s,i){const o=this.animFramesStates_.get(n);if(!o)return;const r=t._tl_getTime(s),a=le("Sprite");if(!a||!e.has(n,a))return;const l=1/12;for(let t=0;t<o.tracks.length;t++){const s=o.tracks[t].frames;if(0===s.length)continue;let c=0,u=0;for(let e=0;e<s.length;e++){const t=s[e].duration??l;if(r<c+t){u=e;break}c+=t,e===s.length-1&&(u=s.length-1)}if(u!==o.lastFrameIndices[t]){o.lastFrameIndices[t]=u;const r=ai(i,s[u].texture);if(r){const t=e.get(n,a);t.texture=r,e.set(n,a,t)}}}}resolveTrackTargets(e,t,n,s){let i=0,o=0;for(const r of n.tracks){if(!r.childPath){"property"===r.type?i++:o++;continue}const a=ui(e,s,r.childPath);if(null!==a){const e="property"!==r.type,s=e?o:i;t._tl_setTrackTarget(n.handle,e?1:0,s,a)}"property"===r.type?i++:o++}}decodeEventString(e,t){const n=e._tl_getEventString(t),s=e._tl_getEventStringLen(t);if(!n||s<=0)return"";const i=new Uint8Array(e.HEAPU8.buffer,n,s);return(new TextDecoder).decode(i)}processEvents(e,t){const n=t._tl_getEventCount();for(let s=0;s<n;s++){const n=t._tl_getEventType(s),i=t._tl_getEventEntity(s);switch(n){case 0:{const n=this.decodeEventString(t,s),o=0!==t._tl_getEventIntParam(s);if(e.has(i,Te)){const t=e.get(i,Te);t.animation=n,t.playing=!0,t.loop=o,e.set(i,Te,t)}break}case 1:if(e.has(i,Te)){const t=e.get(i,Te);t.playing=!1,e.set(i,Te,t)}break;case 2:{const n=this.decodeEventString(t,s);if(e.has(i,An)){const t=e.get(i,An);e.insert(i,An,{...t,clip:n,playing:!0})}break}case 3:{const e=this.decodeEventString(t,s),n=t._tl_getEventFloatParam(s);e&&Rn.playSFX(e,{volume:n});break}case 4:{const n=0!==t._tl_getEventIntParam(s);if(e.has(i,Te)){const t=e.get(i,Te);t.enabled=n,e.set(i,Te,t)}if(e.has(i,An)){const t=e.get(i,An);e.insert(i,An,{...t,enabled:n})}const o=le("Sprite");if(o&&e.has(i,o)){const t=e.get(i,o);e.set(i,o,{...t,enabled:n})}break}}}}processCustomProperties(e,t,n){const s=t._tl_getCustomPropertyCount();if(0!==s)for(let i=0;i<s;i++){const s=t._tl_getCustomPropertyEntity(i),o=t._tl_getCustomPropertyTrackIndex(i),r=t._tl_getCustomPropertyChannelIndex(i),a=t._tl_getCustomPropertyValue(i),l=n.tracks.filter(e=>"property"===e.type)[o];if(!l?.component||!l.channelProperties)continue;const c=le(l.component);if(!c||!e.has(s,c))continue;const u=e.get(s,c),h=l.channelProperties[r];h&&ci(u,h,a)&&e.set(s,c,u)}}}const di=new hi,fi=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["UIRenderer",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}],["TimelinePlayer",{fields:[{field:"timeline",type:"timeline"}]}]]);function pi(e,t){fi.set(e,t)}function mi(e){const t=fi.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function gi(e){return fi.get(e)?.fields??[]}function _i(e){return fi.get(e)?.spine??null}function yi(e,t){const n=q(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function xi(e){const t=e.components.some(e=>"UIRect"===e.type),n=e.components.findIndex(e=>"Sprite"===e.type),s=e.components.some(e=>"UIRenderer"===e.type);if(!t||-1===n||s)return;const i=e.components[n].data,o=i.texture;e.components.push({type:"UIRenderer",data:{visualType:o?2:1,texture:o??0,color:i.color??{r:1,g:1,b:1,a:1},uvOffset:i.uvOffset??{x:0,y:0},uvScale:i.uvScale??{x:1,y:1},sliceBorder:i.sliceBorder??{x:0,y:0,z:0,w:0},material:i.material??0,enabled:i.enabled??!0}}),e.components.splice(n,1)}function wi(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,Re,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;xi(s);const t=n.get(s.id);for(const i of s.components)yi(i,n),Mi(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function bi(e,t){return wi(e,t)}async function vi(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of Si.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=fi.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Si.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=fi.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=wi(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const Si=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),Bn(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=vn(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Pn(Sn(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await Rn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=Gn(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=Kn(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),Bn(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Hn(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}],["timeline",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=bs(await t.loadJson(e));oi(e,i);const o=function(e){const t=new Set,n=new Set,s=new Set;for(const i of e.tracks)if(i.type===as)for(const e of i.events)t.add(e.clip);else if(i.type===rs)i.clip&&n.add(i.clip);else if(i.type===hs)for(const e of i.frames)e.texture&&s.add(e.texture);return{audio:Array.from(t),animClips:Array.from(n),textures:Array.from(s)}}(i);if(o.textures.length>0){const i=new Map,r=o.textures.map(async e=>{try{const o=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o)}catch(t){console.warn(`Failed to load animFrames texture: ${e}`,t),i.set(e,0)}});await Promise.all(r),function(e,t){ri.set(e,t)}(e,i)}}catch(t){console.warn(`Failed to load timeline: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Mi(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=le(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Pi(e,t){const n=e.getEntitiesWithComponents([we]);for(const s of n){const n=e.get(s,we);n&&(n.aspectRatio=t,e.insert(s,we,n))}}function Ti(e,t){const n=e.getEntitiesWithComponents([Re]);for(const s of n){const n=e.get(s,Re);if(n&&n.value===t)return s}return null}const Ci=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["estimeline"],contentType:"json",editorType:"timeline",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],Ei={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",estimeline:"application/json",bmfont:"application/json",fnt:"text/plain"},Ai=new Map,ki=new Set;for(const e of Ci)for(const t of e.extensions)Ai.set(t,e),ki.add(t);function Ri(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Ii(e){return Ai.get(Ri(e))}function Fi(e){return Ii(e)?.editorType??"unknown"}function Bi(e){return Ii(e)?.addressableType??null}function Ui(e){for(const t of Ci)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function zi(e){return ki.has(e.toLowerCase())}function Hi(){return ki}function Li(e){return"string"==typeof e&&(!!e.includes("/")&&zi(Ri(e)))}function Di(){const e=[];for(const t of Ci)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function $i(){return Di().map(e=>({type:"suffix",value:e}))}function Wi(e){return Ei[e.toLowerCase()]}function Oi(e){const t=Ii(e);return t?.wechatPackInclude??!1}function Vi(e){const t=Ii(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function Ni(e,t){for(const n of Ci)n.editorType===e&&(n.buildTransform=t)}function Xi(e){return Ii(e)?.buildTransform}class ji{constructor(e){this.textureCache_=new wn,this.shaderCache_=new wn,this.jsonCache_=new wn,this.textCache_=new wn,this.binaryCache_=new wn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new wn,this.prefabCache_=new wn,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(F.textCanvasSize,F.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new bn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureRefCounts_.get(s);if(void 0===i)continue;const o=this.textureCache_.get(s);if(!o)continue;const r=i-1;r<=0?(t.releaseTexture(o.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),hn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===Ii(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=Ii(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of mi(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=_i(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 vi(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){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=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return hn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return hn.createShader(i,o)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(Vi(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 Yi=Ge(null,"Assets");class qi{build(e){const t=e.wasmModule;t?e.insertResource(Yi,new ji(t)):console.warn("AssetPlugin: No WASM module available")}}const Gi=new qi;class Ki{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ji(e,t){const n=e.getResource(Yi);n&&n.registerEmbeddedAssets(t)}function Zi(e){return e.map(e=>({type:e.type,data:JSON.parse(JSON.stringify(e.data))}))}function Qi(e){return JSON.parse(JSON.stringify(e))}function eo(e,t){for(const n of e){const e=q(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function to(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:Qi(n.componentData.data)})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}function no(e,t,n){const s=n.depth??0;if(s>10)throw new Error(`Prefab nesting depth exceeded 10. Check for deep or circular nesting in: ${e.name}`);if(e.basePrefab)return function(e,t,n,s){const i=e.basePrefab,o=n.visited??new Set;if(o.has(i))throw new Error(`[Prefab] Circular variant reference detected: "${i}" is already being instantiated in the current prefab chain`);const r=n.loadPrefab(i);if(!r)throw new Error(`Failed to load base prefab for variant: ${i}`);o.add(i);const a=[...e.overrides??[],...t];return no(r,a,{...n,visited:o,depth:s+1})}(e,t,n,s);const i=n.visited??new Set,o=new Map;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,n.allocateId());const r=[];for(const a of e.entities){if(a.nestedPrefab){const e=a.nestedPrefab.prefabPath;if(i.has(e))throw new Error(`[Prefab] Circular reference detected: "${e}" is already being instantiated in the current prefab chain`);const t=n.loadPrefab(e);if(!t)throw new Error(`Failed to load nested prefab: ${e}`);i.add(e);const l=no(t,a.nestedPrefab.overrides,{...n,visited:i,depth:s+1});o.set(a.prefabEntityId,l.rootId);const c=l.entities.find(e=>e.id===l.rootId);c&&(c.parent=null!==a.parent?o.get(a.parent)??null:null),r.push(...l.entities);continue}const l=o.get(a.prefabEntityId),c=a.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:a.prefabEntityId,name:a.name,parent:c?null:null!==a.parent?o.get(a.parent)??null:null,children:a.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:Zi(a.components),visible:a.visible};eo(u.components,o),to(u,t),r.push(u)}const a=o.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:r,rootId:a}}function so(e,t,n){const s=[],i=n??new Set;if(e.basePrefab&&!i.has(e.basePrefab)){i.add(e.basePrefab),s.push(e.basePrefab);const n=t(e.basePrefab);n&&s.push(...so(n,t,i))}for(const n of e.entities){if(!n.nestedPrefab)continue;const e=n.nestedPrefab.prefabPath;if(i.has(e))continue;i.add(e),s.push(e);const o=t(e);o&&s.push(...so(o,t,i))}return s}async function io(e,t,n,s,i=0){if(i>10)return;const o=s??new Set;if(e.basePrefab&&!o.has(e.basePrefab)&&!n.has(e.basePrefab)){o.add(e.basePrefab);const s=await t(e.basePrefab);n.set(e.basePrefab,s),await io(s,t,n,o,i+1)}for(const s of e.entities){if(!s.nestedPrefab)continue;const e=s.nestedPrefab.prefabPath;if(o.has(e)||n.has(e))continue;o.add(e);const r=await t(e);n.set(e,r),await io(r,t,n,o,i+1)}}async function oo(e,t,n){const s=new Map;n?.assetServer&&await io(t,e=>n.assetServer.loadPrefab(e,n.assetBaseUrl),s);let i=0;const o={allocateId:()=>i++,loadPrefab:e=>s.get(e)??null,visited:new Set},{entities:r,rootId:a}=no(t,n?.overrides??[],o),l={version:t.version,name:t.name,entities:r.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},c=await vi(e,l,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),u=c.get(a);return void 0!==n?.parent&&e.setParent(u,n.parent),{root:u,entities:c}}class ro{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return oo(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ao=Ge(null,"Prefabs");class lo{constructor(){this.name="PrefabsPlugin",this.dependencies=[Yi]}build(e){const t=e.getResource(Yi);e.insertResource(ao,new ro(e.world,t))}}const co=new lo;let uo=null,ho=0,fo=0,po=0;const mo=new Float32Array(256);function go(e){uo=e,ho=uo._malloc(64),fo=uo._malloc(64),po=uo._malloc(1024)}function _o(){uo&&(ho&&(uo._free(ho),ho=0),fo&&(uo._free(fo),fo=0),po&&(uo._free(po),po=0)),uo=null}function yo(){if(!uo)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return uo}const xo={r:1,g:1,b:1,a:1},wo={begin(e){const t=yo();try{t.HEAPF32.set(e,ho/4),t.draw_begin(ho)}catch(e){lt(e,"Draw.begin")}},end(){try{yo().draw_end()}catch(e){lt(e,"Draw.end")}},line(e,t,n,s=1){try{yo().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){lt(e,"Draw.line")}},rect(e,t,n,s=!0){try{yo().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){lt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{yo().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){lt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{yo().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){lt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{yo().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){lt(e,"Draw.circleOutline")}},texture(e,t,n,s=xo){try{yo().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){lt(e,"Draw.texture")}},textureRotated(e,t,n,s,i=xo){try{yo().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){lt(e,"Draw.textureRotated")}},setLayer(e){yo().draw_setLayer(e)},setDepth(e){yo().draw_setDepth(e)},getDrawCallCount:()=>uo?uo.draw_getDrawCallCount():0,getPrimitiveCount:()=>uo?uo.draw_getPrimitiveCount():0,setBlendMode(e){yo().draw_setBlendMode(e)},setDepthTest(e){yo().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=yo();s.HEAPF32.set(n,fo/4),s.draw_mesh(e,t,fo)}catch(n){lt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=yo(),i=hn.get(t);if(!i)return;if(wo.setBlendMode(i.blendMode),wo.setDepthTest(i.depthTest),0===i.uniforms.size)return void wo.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,fo/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=So(t);if(!(s<0)){if(nn(n))mo[o++]=10,mo[o++]=s,mo[o++]=n.slot??e++,mo[o++]=n.textureId;else if("number"==typeof n)mo[o++]=1,mo[o++]=s,mo[o++]=n;else if(Array.isArray(n)){mo[o++]=n.length,mo[o++]=s;for(let e=0;e<n.length;e++)mo[o++]=n[e]}else"w"in n?(mo[o++]=4,mo[o++]=s,mo[o++]=n.x,mo[o++]=n.y,mo[o++]=n.z,mo[o++]=n.w):"z"in n?(mo[o++]=3,mo[o++]=s,mo[o++]=n.x,mo[o++]=n.y,mo[o++]=n.z):(mo[o++]=2,mo[o++]=s,mo[o++]=n.x,mo[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(mo.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,fo);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),po/4),s.draw_meshWithUniforms(e,i.shader,fo,po,o)}catch(n){lt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},bo={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},vo=new Set;function So(e){const t=bo[e];return void 0!==t?t:(vo.has(e)||(vo.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(bo).join(", ")}`)),-1)}const Mo=new Map;function Po(e,t,n){Mo.set(e,{fn:t,scene:n??""})}function To(e){Mo.delete(e)}function Co(){Mo.clear()}var Eo;!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"}(Eo||(Eo={}));let Ao=null,ko=0,Ro=0,Io=0;function Fo(e){Ao=e,ko=Ao._malloc(262144),Ro=Ao._malloc(65536),Io=Ao._malloc(256)}function Bo(){Ao&&(ko&&Ao._free(ko),Ro&&Ao._free(Ro),Io&&Ao._free(Io),ko=0,Ro=0,Io=0),Ao=null}function Uo(){if(!Ao)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ao}const zo={create(e){const t=Uo(),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,ko/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Io,i).set(o),t.geometry_init(n,ko,s,Io,i,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,Ro,s).set(e.indices),t.geometry_setIndices16(n,Ro,s)}else{new Uint32Array(t.HEAPU8.buffer,Ro,s).set(e.indices),t.geometry_setIndices32(n,Ro,s)}}return n},updateVertices(e,t,n=0){const s=Uo(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,ko/4),s.geometry_updateVertices(e,ko,i,n)},release(e){e>0&&Uo().geometry_release(e)},isValid:e=>!(!Ao||e<=0)&&Ao.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return zo.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:Eo.Float2},{name:"a_texCoord",type:Eo.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 i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return zo.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Eo.Float2},{name:"a_texCoord",type:Eo.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return zo.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Eo.Float2},{name:"a_texCoord",type:Eo.Float2}],indices:new Uint16Array(r)})}};let Ho=1;const Lo=new Map,Do=new Map;function $o(){return Lo}function Wo(){return Do}class Oo{constructor(){this.passes_=[],this.destroyed_=!1,this.id=Ho++,Lo.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}clearPasses(){return this.passes_.length=0,this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of Do)t===this&&Do.delete(e);Lo.delete(this.id)}}}const Vo="#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";let No=null;function Xo(e){No=e}function jo(){for(const e of $o().values())e.destroy();$o().clear(),Wo().clear(),No&&qo.isInitialized()&&qo.shutdown(),No=null}function Yo(){if(!No)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return No}const qo={createStack:()=>new Oo,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");Wo().set(e,t)},unbind(e){Wo().delete(e)},getStack:e=>Wo().get(e)??null,init(e,t){try{return Yo().postprocess_init(e,t)}catch(n){return lt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Yo().postprocess_shutdown()}catch(e){lt(e,"PostProcess.shutdown")}},resize(e,t){try{Yo().postprocess_resize(e,t)}catch(n){lt(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!No)return!1;try{return No.postprocess_isInitialized()}catch(e){return lt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Yo().postprocess_setBypass(e)}catch(e){lt(e,"PostProcess.setBypass")}},begin(){try{Yo().postprocess_begin()}catch(e){lt(e,"PostProcess.begin")}},end(){try{Yo().postprocess_end()}catch(e){lt(e,"PostProcess.end")}},setOutputViewport(e,t,n,s){try{Yo().postprocess_setOutputViewport(e,t,n,s)}catch(e){lt(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=Wo().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(qo.isInitialized()||qo.init(1,1),qo.setBypass(!1),function(e){const t=Yo();try{t.postprocess_clearPasses()}catch(e){return void lt(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){lt(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){lt(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){lt(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):qo.setBypass(!0)},_resetAfterCamera(){try{Yo().postprocess_clearPasses(),Yo().postprocess_setBypass(!0)}catch(e){lt(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of Wo().keys())e(t)||Wo().delete(t)},screenStack:null,setScreenStack(e){qo.screenStack=e},_beginScreenCapture(){try{Yo().postprocess_beginScreenCapture()}catch(e){lt(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Yo().postprocess_endScreenCapture()}catch(e){lt(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=qo.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Yo();try{t.postprocess_clearScreenPasses()}catch(e){return void lt(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){lt(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){lt(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){lt(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{Yo().postprocess_executeScreenPasses()}catch(e){lt(e,"PostProcess._executeScreenPasses")}},createBlur:()=>hn.createShader(Vo,"#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:()=>hn.createShader(Vo,"#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 vig = 1.0 - smoothstep(1.0 - u_softness, 1.0, dist);\n fragColor = vec4(color.rgb * mix(1.0, vig, u_intensity), color.a);\n}\n"),createGrayscale:()=>hn.createShader(Vo,"#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"),createBloomExtract:()=>hn.createShader(Vo,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_threshold;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float brightness = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float knee = u_threshold * 0.5;\n float soft = brightness - u_threshold + knee;\n soft = clamp(soft, 0.0, 2.0 * knee);\n soft = soft * soft / (4.0 * knee + 0.00001);\n float contrib = max(soft, brightness - u_threshold);\n contrib /= max(brightness, 0.00001);\n fragColor = vec4(color.rgb * contrib, 1.0);\n}\n"),createBloomKawase(e){const t=`#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n float d = (${e.toFixed(1)} + 0.5) * max(u_radius, 0.5);\n vec2 ts = 1.0 / u_resolution;\n fragColor = (\n texture(u_texture, v_texCoord + vec2(-d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2(-d, d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, d) * ts)\n ) * 0.25;\n}\n`;return hn.createShader(Vo,t)},createBloomComposite:()=>hn.createShader(Vo,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform sampler2D u_sceneTexture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 blur = texture(u_texture, v_texCoord);\n vec4 scene = texture(u_sceneTexture, v_texCoord);\n fragColor = vec4(scene.rgb + blur.rgb * u_intensity, scene.a);\n}\n"),createChromaticAberration:()=>hn.createShader(Vo,"#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")},Go=new Map;function Ko(e){Go.set(e.type,e)}function Jo(e){return Go.get(e)}function Zo(){return Array.from(Go.keys())}function Qo(){return Array.from(Go.values())}Ko({type:"blur",label:"Blur",factory:()=>qo.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Ko({type:"bloom",label:"Bloom",factory:()=>qo.createBloomExtract(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:1,step:.01,defaultValue:.4},{name:"u_intensity",label:"Intensity",min:0,max:5,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:.5,max:5,step:.1,defaultValue:1}],multiPass:[{name:"bloom_extract",factory:()=>qo.createBloomExtract()},{name:"bloom_kawase_0",factory:()=>qo.createBloomKawase(0)},{name:"bloom_kawase_1",factory:()=>qo.createBloomKawase(1)},{name:"bloom_kawase_2",factory:()=>qo.createBloomKawase(2)},{name:"bloom_kawase_3",factory:()=>qo.createBloomKawase(3)},{name:"bloom_kawase_4",factory:()=>qo.createBloomKawase(4)},{name:"bloom_composite",factory:()=>qo.createBloomComposite()}]}),Ko({type:"vignette",label:"Vignette",factory:()=>qo.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:.6},{name:"u_softness",label:"Softness",min:0,max:1,step:.01,defaultValue:.5}]}),Ko({type:"grayscale",label:"Grayscale",factory:()=>qo.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Ko({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>qo.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const er=new Map,tr=new Map;function nr(e,t){let n=er.get(e),s=tr.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=qo.createStack(),er.set(e,n)),s||(s=new Map,tr.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=Jo(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}qo.bind(e,n)}else if(n&&(qo.unbind(e),n.destroy(),er.delete(e)),s){for(const e of s.values())hn.releaseShader(e);tr.delete(e)}}function sr(e){const t=er.get(e);t&&(qo.unbind(e),t.destroy(),er.delete(e));const n=tr.get(e);if(n){for(const e of n.values())hn.releaseShader(e);tr.delete(e)}}function ir(){for(const e of er.keys())sr(e)}const or=Ge({enabled:!0},"PostProcessVolumeConfig"),rr=new Map,ar=new Map;function lr(e,t){const n=ar.get(e);if(void 0!==n)return n;const s=t();return ar.set(e,s),s}function cr(e,t){if(0===t.size){const t=rr.get(e);return void(t&&(qo.unbind(e),t.destroy(),rr.delete(e)))}let n=rr.get(e);n||(n=qo.createStack(),rr.set(e,n)),n.clearPasses();for(const[e,s]of t){if(!s.enabled)continue;const t=Jo(e);if(t)if(t.multiPass)for(const e of t.multiPass){const t=lr(e.name,e.factory);n.addPass(e.name,t);for(const[t,i]of s.uniforms)n.setUniform(e.name,t,i)}else{const i=lr(e,t.factory);n.addPass(e,i);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?qo.bind(e,n):qo.unbind(e)}const ur=Nt([Ct(Fe,me),Ct(we)],(e,t)=>{const n=[];for(const[t,s,i]of e)n.push({data:s,tx:{x:i.position.x,y:i.position.y}});const s=[];for(const{data:e}of n)e.isGlobal&&s.push({data:e,factor:1});const i=s.length>0?function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(s):new Map;for(const[e,n]of t)n.isActive&&cr(e,i)},{name:"PostProcessVolumeSystem"});class hr{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(or,{enabled:!0}),e.addSystemToSchedule(Wt.PostUpdate,ur)}cleanup(){ir(),function(){for(const[e,t]of rr)qo.unbind(e),t.destroy();rr.clear();for(const e of ar.values())hn.releaseShader(e);ar.clear()}(),qo.setScreenStack(null)}}const dr=new hr;var fr,pr;!function(e){e[e.BatchFull=0]="BatchFull",e[e.TextureSlotsFull=1]="TextureSlotsFull",e[e.ScissorChange=2]="ScissorChange",e[e.StencilChange=3]="StencilChange",e[e.MaterialChange=4]="MaterialChange",e[e.BlendModeChange=5]="BlendModeChange",e[e.StageEnd=6]="StageEnd",e[e.TypeChange=7]="TypeChange",e[e.FrameEnd=8]="FrameEnd"}(fr||(fr={})),function(e){e[e.Sprite=0]="Sprite",e[e.Spine=1]="Spine",e[e.Mesh=2]="Mesh",e[e.ExternalMesh=3]="ExternalMesh",e[e.Text=4]="Text",e[e.Particle=5]="Particle",e[e.Shape=6]="Shape",e[e.UIElement=7]="UIElement"}(pr||(pr={}));var mr;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(mr||(mr={}));const gr={None:0,Spine:1,Particles:2};let _r=null,yr=0;function xr(e){_r=e,yr=_r._malloc(64)}function wr(){_r&&yr&&(_r._free(yr),yr=0),_r=null}const br={init(e,t){_r?.renderer_init(e,t)},resize(e,t){_r?.renderer_resize(e,t)},beginFrame(){_r?.renderer_beginFrame()},updateTransforms(e){if(_r)try{_r.renderer_updateTransforms(e._cpp)}catch(e){lt(e,"Renderer.updateTransforms")}},begin(e,t){if(_r&&yr)try{_r.HEAPF32.set(e,yr/4),_r.renderer_begin(yr,t??0)}catch(e){lt(e,"Renderer.begin")}},flush(){try{_r?.renderer_flush()}catch(e){lt(e,"Renderer.flush")}},end(){try{_r?.renderer_end()}catch(e){lt(e,"Renderer.end")}},submitAll(e,t,n,s,i,o){if(_r)try{_r.renderer_submitAll(e._cpp,t,n,s,i,o)}catch(e){lt(e,"Renderer.submitAll")}},setStage(e){_r?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>_r?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){_r?.renderer_releaseTarget(e)},getTargetTexture:e=>_r?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>_r?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){_r?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){_r?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){_r?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){_r?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>_r?_r.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>_r?{drawCalls:_r.renderer_getDrawCalls(),triangles:_r.renderer_getTriangles(),sprites:_r.renderer_getSprites(),text:_r.renderer_getText(),spine:_r.renderer_getSpine?.()??0,meshes:_r.renderer_getMeshes(),culled:_r.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0},captureNextFrame(){_r?.renderer_captureNextFrame()},getCapturedData:()=>_r?function(e){if(!e.renderer_hasCapturedData())return null;const t=e.renderer_getCapturedFrameSize();if(0===t)return null;const n=e.renderer_getCapturedFrameData(),s=e.renderer_getCapturedEntities(),i=e.renderer_getCapturedEntityCount(),o=e.renderer_getCapturedCameraCount(),r=e.HEAPU8,a=new DataView(r.buffer,n,76*t),l=new Uint32Array(r.buffer,s,i),c=[];for(let e=0;e<t;e++){const t=76*e,n=a.getUint32(t,!0),s=a.getUint32(t+4,!0),o=a.getUint8(t+8),r=a.getUint8(t+9),u=a.getUint8(t+10),h=a.getUint32(t+12,!0),d=a.getUint32(t+16,!0),f=a.getUint32(t+20,!0),p=a.getUint32(t+24,!0),m=a.getUint32(t+28,!0),g=a.getUint32(t+32,!0),_=a.getUint32(t+36,!0),y=a.getInt32(t+40,!0),x=a.getUint8(t+44),w=a.getInt32(t+48,!0),b=a.getInt32(t+52,!0),v=a.getInt32(t+56,!0),S=a.getInt32(t+60,!0),M=0!==a.getUint8(t+64),P=0!==a.getUint8(t+65),T=0!==a.getUint8(t+66),C=a.getInt32(t+68,!0),E=a.getUint8(t+72),A=[];for(let e=0;e<g&&_+e<i;e++)A.push(l[_+e]);c.push({index:n,cameraIndex:s,stage:o,type:r,blendMode:u,textureId:h,materialId:d,shaderId:f,vertexCount:p,triangleCount:m,entityCount:g,entityOffset:_,layer:y,flushReason:x,scissorX:w,scissorY:b,scissorW:v,scissorH:S,scissorEnabled:M,stencilWrite:P,stencilTest:T,stencilRef:C,textureSlotUsage:E,entities:A})}return{drawCalls:c,cameraCount:o}}(_r):null,hasCapturedData:()=>_r?.renderer_hasCapturedData()??!1,replayToDrawCall(e){_r&&function(e,t){e.renderer_replayToDrawCall(t)}(_r,e)},getSnapshotImageData:()=>_r?function(e){const t=e.renderer_getSnapshotSize();if(0===t)return null;const n=e.renderer_getSnapshotWidth(),s=e.renderer_getSnapshotHeight();if(0===n||0===s)return null;const i=e.renderer_getSnapshotPtr(),o=e.HEAPU8,r=new Uint8ClampedArray(o.buffer,i,t),a=new Uint8ClampedArray(t),l=4*n;for(let e=0;e<s;e++){const t=e*l,n=(s-1-e)*l;a.set(r.subarray(t,t+l),n)}return new ImageData(a,n,s)}(_r):null};let vr=null;function Sr(e){vr=e}function Mr(){vr=null}const Pr={enable(){vr?.gl_enableErrorCheck(!0)},disable(){vr?.gl_enableErrorCheck(!1)},check:e=>vr?.gl_checkErrors(e)??0,diagnose(){vr?.renderer_diagnose()}};class Tr{constructor(){this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null,this.preFlushCallbacks_=[]}setActiveScenes(e){this.activeScenes_=e}addPreFlushCallback(e){this.preFlushCallbacks_.push(e)}beginFrame(){br.beginFrame()}beginScreenCapture(){qo.screenStack&&qo.screenStack.enabledPassCount>0&&(qo.isInitialized()||qo.init(1,1),qo._applyScreenStack(),qo._beginScreenCapture())}endScreenCapture(){qo.screenStack&&qo.screenStack.enabledPassCount>0&&(qo._endScreenCapture(),qo._executeScreenPasses())}submitScene(e,t,n,s){br.updateTransforms(e),br.submitAll(e,0,n.x,n.y,n.w,n.h);for(const t of this.preFlushCallbacks_)t(e);br.flush(),this.executeDrawCallbacks(t,s)}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(br.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),br.beginFrame(),br.setViewport(0,0,s,i),br.clearBuffers(3),br.begin(n),this.submitScene(t,n,{x:0,y:0,w:s,h:i},o),br.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==qo.getStack(r);a&&(qo._applyForCamera(r),qo.resize(s.w,s.h),qo.setOutputViewport(s.x,s.y,s.w,s.h),qo.begin()),br.setViewport(s.x,s.y,s.w,s.h),br.setScissor(s.x,s.y,s.w,s.h,!0),br.clearBuffers(i),br.setScissor(0,0,0,0,!1),br.begin(n),this.submitScene(t,n,s,o),br.end(),a&&(qo.end(),qo._resetAfterCamera())}executeDrawCallbacks(e,t){const n=Mo;if(n.size>0){wo.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}wo.end();for(const e of s)To(e)}}}const Cr={None:0,SolidColor:1,Image:2,NineSlice:3},Er=ue("UIRenderer",{visualType:Cr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),Ar="__scene_transition_overlay__";class kr{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Rr{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Ie,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Po(e,t,this.instance_.config.name)}bindPostProcess(e,t){qo.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){qo.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Ie)){const n=this.app_.world.get(e,Ie);n.persistent=t,this.app_.world.insert(e,Ie,n)}}}class Ir{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())To(t);for(const t of e.postProcessBindings.keys())qo.unbind(t)}this.transition_&&(To(Ar),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise((n,s)=>{const i=t.duration??F.sceneTransitionDuration,o=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:i,color:o,targetScene:e,options:t,resolve:n,reject:s},Po(Ar,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;wo.setLayer(9999),wo.setDepth(9999),wo.rect({x:0,y:0},{x:2e4,y:2e4},{r:o.r,g:o.g,b:o.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{reject:t}=this.transition_;this.transition_=null,To(Ar),t(e)}})().catch(()=>{})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,To(Ar),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new kr(t);this.scenes_.set(e,n);const s=new Rr(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Yi)?this.app_.getResource(Yi):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new kr(t);this.scenes_.set(e,n);const s=new Rr(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Yi)?this.app_.getResource(Yi):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,Ie)){if(this.app_.world.get(e,Ie).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())To(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())qo.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Yi)&&(i.assetServer=this.app_.getResource(Yi));const o=await vi(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,Ie,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Br(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(Yi)?this.app_.getResource(Yi):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)hn.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,ye)){const t=n.get(e,ye);s.sprite=t.color.a,t.color.a=0,n.insert(e,ye,t),i=!0}if(n.has(e,Te)){const t=n.get(e,Te);s.spine=t.color.a,t.color.a=0,n.insert(e,Te,t),i=!0}if(n.has(e,Pe)){const t=n.get(e,Pe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Pe,t),i=!0}if(n.has(e,Er)){const t=n.get(e,Er);s.uiRenderer=t.color.a,t.color.a=0,n.insert(e,Er,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,ye)){const t=n.get(e,ye);t.color.a=s.sprite,n.insert(e,ye,t)}if(void 0!==s.spine&&n.has(e,Te)){const t=n.get(e,Te);t.color.a=s.spine,n.insert(e,Te,t)}if(void 0!==s.bitmapText&&n.has(e,Pe)){const t=n.get(e,Pe);t.color.a=s.bitmapText,n.insert(e,Pe,t)}if(void 0!==s.uiRenderer&&n.has(e,Er)){const t=n.get(e,Er);t.color.a=s.uiRenderer,n.insert(e,Er,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Fr=Ge(null,"SceneManager");function Br(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Fr).getSceneStatus(t)&&n._fn(...s)}}}const Ur=Nt([Je(Fr),Ke(et)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),zr={name:"SceneManager",build(e){const t=new Ir(e);e.insertResource(Fr,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Fr),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Wt.Startup,n),e.addSystemToSchedule(Wt.Last,Ur)}};class Hr{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new zt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=async()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(Wt.Last);else{await this.runSchedule(Wt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(Wt.FixedPreUpdate),await this.runSchedule(Wt.FixedUpdate),await this.runSchedule(Wt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(Wt.PreUpdate),await this.runSchedule(Wt.Update),await this.runSchedule(Wt.PostUpdate),await this.runSchedule(Wt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new yt,this.resources_=new Qe;for(const e of Object.values(Wt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Hr}getPlugin(e){return this.installed_plugins_.find(t=>t instanceof e)}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Wt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Wt.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}async waitForPhysics(){this.physicsInitPromise_?await this.physicsInitPromise_:console.warn("[ESEngine] No PhysicsPlugin installed, waitForPhysics() is a no-op")}get isPhysicsReady(){return null!=this.physicsModule_}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return at(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Fr).register(e),this}setInitialScene(e){return this.getResource(Fr).setInitial(e),this}async tick(e){if(this.runner_||(this.runner_=new Gt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(et)||this.resources_.insert(et,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_()),await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(Wt.Last);else{await this.runSchedule(Wt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(Wt.FixedPreUpdate),await this.runSchedule(Wt.FixedUpdate),await this.runSchedule(Wt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(Wt.PreUpdate),await this.runSchedule(Wt.Update),await this.runSchedule(Wt.PostUpdate),await this.runSchedule(Wt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}async run(){this.running_||(this.running_=!0,this.runner_=new Gt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(et,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),await this.flushStartupSystems_(),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Co();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Mr,wr,jo,Bo,cn,_o];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){console.warn("[App] Shutdown despawn error:",e)}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}async flushStartupSystems_(){const e=this.systems_.get(Wt.Startup);0!==e.length&&(this.sortedSystemsCache_.delete(Wt.Startup),await this.runSchedule(Wt.Startup),e.length=0,this.sortedSystemsCache_.delete(Wt.Startup))}async runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{const t=this.runner_.run(e.system);t instanceof Promise&&await t}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(Wt[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(et);t.delta=e,t.elapsed+=e,t.frameCount++}}function Lr(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Dr=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function $r(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case fe.FixedWidth:return o;case fe.FixedHeight:return r;case fe.Expand:return Math.max(o,r);case fe.Shrink:return Math.min(o,r);case fe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const Wr=[];function Or(e){if(e<Wr.length)return Wr[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return Wr.push(t),t}function Vr(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,Ie);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,h=0;if(i.projectionType===he.Orthographic){if(h=i.orthoSize,l){h=$r(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=Xr(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=Yr(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=Gr(o.position.x,o.position.y,o.position.z),f=Or(c.length);f.entity=e,f.viewProjection.set(Jr(a,d)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const Nr=new Float32Array(16);function Xr(e,t,n,s,i,o){const r=Nr;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const jr=new Float32Array(16);function Yr(e,t,n,s){const i=jr;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const qr=new Float32Array(16);function Gr(e,t,n){const s=qr;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}const Kr=new Float32Array(16);function Jr(e,t){const n=Kr;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const Zr={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},Qr={Simple:0,Sliced:1,Tiled:2,Filled:3},ea={Horizontal:0,Vertical:1},ta={Left:0,Right:1,Bottom:2,Top:3},na=Q("Image",{texture:L,color:{r:1,g:1,b:1,a:1},imageType:Qr.Simple,fillMethod:ea.Horizontal,fillOrigin:ta.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),sa=ue("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}}),ia=ue("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0});function oa(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,g=p+i.y):(p=h+n.y,g=d+s.y);const _=Math.max(0,m-f),y=Math.max(0,g-p);return{originX:f+r.x*_,originY:p+r.y*y,width:_,height:y,rect:{left:f,bottom:p,right:m,top:g}}}let ra=null,aa=null;function la(e,t){switch(e){case Zr.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Zr.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Zr.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function ca(e,t){switch(e){case Zr.RightToLeft:return{anchorMin:{x:1-t,y:.5},anchorMax:{x:1-t,y:.5}};case Zr.BottomToTop:return{anchorMin:{x:.5,y:t},anchorMax:{x:.5,y:t}};case Zr.TopToBottom:return{anchorMin:{x:.5,y:1-t},anchorMax:{x:.5,y:1-t}};default:return{anchorMin:{x:t,y:.5},anchorMax:{x:t,y:.5}}}}function ua(e,t,n,s){switch(e){case Zr.BottomToTop:case Zr.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function ha(e,t,n,s){if(!e.has(t,sa))return;const i=e.get(t,sa),o=la(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,sa,i)}function da(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}const fa=1.15,pa=.75;function ma(e,t,n,s){return t?n?{r:e.r*pa,g:e.g*pa,b:e.b*pa,a:e.a}:s?{r:Math.min(1,e.r*fa),g:Math.min(1,e.g*fa),b:Math.min(1,e.b*fa),a:e.a}:{...e}:{r:.5*e.r,g:.5*e.g,b:.5*e.b,a:.6*e.a}}function ga(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function _a(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(ga(r.charCodeAt(0))&&s.length>0&&ga(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!ga(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function ya(e){let t=1;for(;t<e;)t*=2;return t}function xa(e,t){let n=0,s=t;for(;e.has(s,Se);){const t=e.get(s,Se).entity;if(!e.valid(t))break;n++,s=t}return n}function wa(e,t){if(ra&&aa){const e=ra.getUIRectComputedWidth(aa,t);if(e>0)return e}return e.size.x}function ba(e,t){if(ra&&aa){const e=ra.getUIRectComputedHeight(aa,t);if(e>0)return e}return e.size.y}function va(e,t,n){ra&&aa&&ra.setUIRectSize(aa,e,t,n)}function Sa(e,t,n,s,i,o){if(!e.has(t,ye))return;const r=e.get(t,ye);let a,l;switch(n){case Zr.BottomToTop:case Zr.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,ye,r))}function Ma(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Pa(e,t){Ma(e,t,ia,{enabled:!0,blockRaycast:!0,raycastTarget:!0})}function Ta(e,t,n){0!==t&&e.valid(t)&&n(t)}function Ca(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a}function Ea(e,t,n){if(e.has(t,na)){const s=e.get(t,na);Ca(s.color,n)||(s.color=n,e.insert(t,na,s))}else if(e.has(t,ye)){const s=e.get(t,ye);Ca(s.color,n)||(s.color=n,e.insert(t,ye,s))}else if(e.has(t,Er)){const s=e.get(t,Er);Ca(s.color,n)||(s.color=n,e.insert(t,Er,s))}}function Aa(e,t,n){if(e.has(t,na)){const s=e.get(t,na);s.enabled!==n&&(s.enabled=n,e.insert(t,na,s))}else if(e.has(t,ye)){const s=e.get(t,ye);s.enabled!==n&&(s.enabled=n,e.insert(t,ye,s))}else if(e.has(t,Er)){const s=e.get(t,Er);s.enabled!==n&&(s.enabled=n,e.insert(t,Er,s))}}function ka(e,t){return{r:Math.min(1,e.r*t),g:Math.min(1,e.g*t),b:Math.min(1,e.b*t),a:e.a}}function Ra(e,t){return{r:e.r,g:e.g,b:e.b,a:t}}class Ia{constructor(){this.map_=new Map}get(e){return this.map_.get(e)}set(e,t){this.map_.set(e,t)}delete(e){this.map_.delete(e)}has(e){return this.map_.has(e)}cleanup(e){for(const[t]of this.map_)e.valid(t)||this.map_.delete(t)}ensureInit(e,t){let n=this.map_.get(e);return n||(n=t(),this.map_.set(e,n)),n}clear(){this.map_.clear()}[Symbol.iterator](){return this.map_[Symbol.iterator]()}}function Fa(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Ba=.1,Ua={r:.3,g:.5,b:.8,a:1},za={r:.9,g:.9,b:.9,a:1},Ha={r:.95,g:.95,b:.95,a:1},La={Left:0,Center:1,Right:2},Da={Top:0,Middle:1,Bottom:2},$a={Visible:0,Clip:1,Ellipsis:2},Wa=Q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:La.Left,verticalAlign:Da.Top,wordWrap:!0,overflow:$a.Visible,lineHeight:1.2});class Oa{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(F.textCanvasSize,F.textCanvasSize);const t=this.canvas.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("TextRenderer: failed to create 2D canvas context");this.ctx=t}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,ya(this.frameMaxW_)),e.height=Math.max(e.height,ya(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=ya(this.frameMaxW_),e.height=ya(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=_a(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===$a.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,ya(f)),s.height=Math.max(s.height,ya(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),_=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${_}, ${y})`,i&&e.overflow===$a.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case Da.Top:w=u;break;case Da.Middle:w=u+(p-2*u-x)/2;break;case Da.Bottom:w=p-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let s;switch(e.align){case La.Left:s=u;break;case La.Center:s=f/2;break;case La.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===$a.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case La.Left:return"left";case La.Center:return"center";case La.Right:return"right"}}}const Va=Fa({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?wa(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?ba(e.uiRect,e.entity):0});function Na(e,t){e.has(t,Er)||e.insert(t,Er,{visualType:Cr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Xa{build(e){ae("Text",Wa);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Oa(t),s=e.world,i=new Map;e.addSystemToSchedule(Wt.PreUpdate,Nt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Wa));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Wa)){if(s.valid(e)&&s.has(e,Er)){const t=s.get(e,Er);t.texture=0,t.visualType=Cr.None,s.insert(e,Er,t)}i.delete(e)}const e=s.getEntitiesWithComponents([Wa]);for(const t of e){const e=s.get(t,Wa),o=s.has(t,sa)?s.get(t,sa):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Va.changed(a,r)){if(s.has(t,Er)&&0!==s.get(t,Er).texture)continue}Na(s,t);const l=o?{size:{x:wa(o,t),y:ba(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Er);u.texture=c.textureHandle,u.visualType=Cr.Image,u.color={r:1,g:1,b:1,a:1},u.uvOffset={x:0,y:0},u.uvScale={x:1,y:1},s.insert(t,Er,u),o&&va(t,c.width,c.height),i.set(t,Va.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const ja=new Xa,Ya=0,qa=ue("UIMask",{enabled:!0,mode:Ya});class Ga{build(e){ae("UIMask",qa)}}const Ka=new Ga;function Ja(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=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,i-n),h:Math.max(0,o-s)}}function Za(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],x=s*l-i*a,w=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*g-d*m,T=h*_-f*m,C=h*y-p*m,E=d*_-f*g,A=d*y-p*g,k=f*y-p*_;let R=x*k-w*A+b*E+v*C-S*T+M*P;return 0===R||(R=1/R,n[0]=(l*k-c*A+u*E)*R,n[1]=(o*A-i*k-r*E)*R,n[2]=(g*M-_*S+y*v)*R,n[3]=(f*S-d*M-p*v)*R,n[4]=(c*C-a*k-u*T)*R,n[5]=(s*k-o*C+r*T)*R,n[6]=(_*b-m*M-y*w)*R,n[7]=(h*M-f*b+p*w)*R,n[8]=(a*A-l*C+u*P)*R,n[9]=(i*C-s*A-r*P)*R,n[10]=(m*S-g*b+y*x)*R,n[11]=(d*b-h*S-p*x)*R,n[12]=(l*T-a*E-c*P)*R,n[13]=(s*E-i*T+o*P)*R,n[14]=(g*w-m*v-_*x)*R,n[15]=(h*v-d*w+f*x)*R),n}function Qa(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function el(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function tl(e,t){return 2*Math.atan2(e,t)}function nl(e,t,n,s,i,o,r,a,l,c){if(0===l&&1===c)return el(e,t,n,s,i,o,r,a);const u=tl(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,g=f*h+p*d+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}const sl=ue("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),il={Normal:0,Hovered:1,Pressed:2,Disabled:3},ol=Q("Button",{state:il.Normal,transition:null});class rl{constructor(){this.events_=[],this.entityTypeHandlers_=new Map,this.globalHandlers_=new Map,this.activeDispatches_=new Set,this.entityValidator_=null}on(e,t,n){if(void 0!==n){const s=e,i=t;let o=this.entityTypeHandlers_.get(s);o||(o=new Map,this.entityTypeHandlers_.set(s,o));let r=o.get(i);r||(r=[],o.set(i,r)),r.push(n);let a=!1;return()=>{if(a)return;a=!0;const e=o.get(i);if(e){const t=e.indexOf(n);-1!==t&&e.splice(t,1)}}}{const n=e,s=t;let i=this.globalHandlers_.get(n);i||(i=[],this.globalHandlers_.set(n,i)),i.push(s);let o=!1;return()=>{if(o)return;o=!0;const e=this.globalHandlers_.get(n);if(e){const t=e.indexOf(s);-1!==t&&e.splice(t,1)}}}}removeAll(e){this.entityTypeHandlers_.delete(e)}setEntityValidator(e){this.entityValidator_=e}emit(e,t,n){const s={entity:e,type:t,target:n??e,currentTarget:e,propagationStopped:!1,stopPropagation(){this.propagationStopped=!0}};this.events_.push(s);const i=`${e}:${t}`;return this.activeDispatches_.has(i)||(this.activeDispatches_.add(i),this.dispatchToHandlers_(s),this.activeDispatches_.delete(i)),s}emitBubbled(e,t,n,s){const i={entity:e,type:t,target:n,currentTarget:e,propagationStopped:!1,stopPropagation(){s.propagationStopped=!0}};this.events_.push(i);const o=`${e}:${t}`;this.activeDispatches_.has(o)||(this.activeDispatches_.add(o),this.dispatchToHandlers_(i),this.activeDispatches_.delete(o))}drain(){if(this.entityValidator_)for(const e of this.entityTypeHandlers_.keys())this.entityValidator_(e)||this.entityTypeHandlers_.delete(e);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)}dispatchToHandlers_(e){const t=this.entityTypeHandlers_.get(e.entity);if(t){const n=t.get(e.type);n&&this.invokeHandlers_([...n],e)}const n=this.globalHandlers_.get(e.type);n&&this.invokeHandlers_([...n],e)}invokeHandlers_(e,t){for(const n of e)try{n(t)}catch(e){console.error(`UIEvent handler error [${t.type}]:`,e)}}}const al=Ge(new rl,"UIEvents"),ll=Ge({generation:0},"UILayoutGeneration");class cl{build(e){ae("UIRect",sa),ae("UIRenderer",Er);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){ra=e,aa=t}(n,s);const i={generation:0};e.insertResource(ll,i);e.addSystemToSchedule(Wt.PreUpdate,Nt([Ke(en)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.transform_update(s),i.generation++)},{name:"UILayoutSystem"})),e.addSystemToSchedule(Wt.PostUpdate,Nt([Ke(en)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),i.generation++)},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(Wt.PostUpdate,Nt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const ul=new cl,hl=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(Za(t,e),n=!1),e)}}();function dl(e,t,n,s){const i=t.emit(n,s,n);!function(e,t,n){let s=t;for(;e.has(s,Se);){const t=e.get(s,Se).entity;if(!e.valid(t))break;if(n(t))return;s=t}}(e,n,o=>{if(i.propagationStopped)return!0;if(!e.has(o,ia))return!1;const r=e.get(o,ia);return r.enabled&&t.emitBubbled(o,s,n,i),r.blockRaycast})}class fl{build(e){ae("Interactable",ia),ae("Button",ol);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new rl;i.setEntityValidator(e=>t.valid(e)),e.insertResource(al,i);let o=null,r=null,a=NaN,l=NaN,c=-1;e.addSystemToSchedule(Wt.PreUpdate,Nt([Ke(Jt),Ke(en),Ke(ll)],(e,u,h)=>{if(i.drain(),Ps()&&!Es())return;const d=t.getEntitiesWithComponents([sl]);for(const e of d){const n=t.get(e,sl);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,sl,n))}if(!u.valid)return;const p=f(),m=e.mouseX*p,g=u.screenH-e.mouseY*p;hl.update(u.viewProjection);const _=Qa(m,g,hl.getInverse(u.viewProjection),u.vpX,u.vpY,u.vpW,u.vpH);u.worldMouseX=_.x,u.worldMouseY=_.y;const y=e.isMouseButtonDown(0),x=e.isMouseButtonPressed(0),w=e.isMouseButtonReleased(0),b=_.x!==a||_.y!==l,v=h.generation!==c,S=b||v||(x||w);a=_.x,l=_.y,c=h.generation;let M=o;if(S){n.uiHitTest_update(s,_.x,_.y,y,x,w);const e=n.uiHitTest_getHitEntity();M=4294967295===e?null:e}if(null===o||t.valid(o)||(o=null),o!==M){if(null!==o&&t.valid(o)&&t.has(o,sl)){const e=t.get(o,sl);e.hovered=!1,t.insert(o,sl,e),i.emit(o,"hover_exit")}if(null!==M){Ma(t,M,sl);const e=t.get(M,sl);e.hovered=!0,t.insert(M,sl,e),i.emit(M,"hover_enter")}o=M}if(x&&null!==M){const e=t.get(M,sl);e.pressed=!0,e.justPressed=!0,t.insert(M,sl,e),r=M,dl(t,i,M,"press")}if(w&&null!==r){if(t.valid(r)&&t.has(r,sl)){const e=t.get(r,sl);e.pressed=!1,e.justReleased=!0,t.insert(r,sl,e),dl(t,i,r,"release"),r===o&&dl(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const u=new Set;e.addSystemToSchedule(Wt.Update,Nt([],()=>{for(const e of u)t.valid(e)||u.delete(e);const e=t.getEntitiesWithComponents([ol]);for(const n of e){if(Ma(t,n,ia,{enabled:!0}),!t.has(n,sl))continue;const e=t.get(n,sl),s=t.get(n,ol),i=t.get(n,ia),o=!u.has(n),r=s.state;if(i.enabled?e.pressed?s.state=il.Pressed:e.hovered?s.state=il.Hovered:s.state=il.Normal:s.state=il.Disabled,o&&u.add(n),(o||r!==s.state)&&s.transition){const o=da(s.transition,i.enabled,e.pressed,e.hovered);Ea(t,n,o)}else if((o||r!==s.state)&&!s.transition&&t.has(n,na)){const s=ma(t.get(n,na).color,i.enabled,e.pressed,e.hovered);Ea(t,n,s)}}},{name:"ButtonSystem"}))}}const pl=new fl,ml=Q("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),gl=Q("Focusable",{tabIndex:0,isFocused:!1});class _l{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const yl=Ge(new _l,"FocusManager");class xl{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ae("TextInput",ml),Ps()&&!Es())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=t,s=e.world,i=new Map,o=h(F.textCanvasSize,64),r=o.getContext("2d",{willReadFrequently:!0});if(!r)return void console.warn("TextInputPlugin: failed to create 2D canvas context");const a=r;let l=0,c=0,u=!1,d=!0,f=0,p=0;const m=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!m)return;const g=m;function _(){const t=e.getResource(yl);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,ml)?n:null}const y=()=>{u||null===_()||S()},x=()=>{u=!0},w=()=>{u=!1,S()},b=t=>{const n=_();if(null===n)return;if("Escape"===t.key)return void M();const i=s.get(n,ml);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(al).emit(n,"submit"),void M()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,g.selectionStart=o,g.selectionEnd=o,i.dirty=!0,P())},v=()=>{const t=_();if(null!==t){const n=s.get(t,ml);n.focused=!1,n.dirty=!0;e.getResource(yl).blur()}};function S(){const t=_();if(null===t)return;const n=s.get(t,ml);if(n.readOnly)return;let i=g.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),g.value=i),i!==n.value){n.value=i;e.getResource(al).emit(t,"change")}n.cursorPos=g.selectionStart??i.length,n.dirty=!0,P()}function M(){const t=_();if(null!==t){const e=s.get(t,ml);e.focused=!1,e.dirty=!0}e.getResource(yl).blur(),g.blur()}function P(){d=!0,f=0}g.addEventListener("input",y),g.addEventListener("compositionstart",x),g.addEventListener("compositionend",w),g.addEventListener("keydown",b),g.addEventListener("blur",v),this.cleanupListeners_=()=>{g.removeEventListener("input",y),g.removeEventListener("compositionstart",x),g.removeEventListener("compositionend",w),g.removeEventListener("keydown",b),g.removeEventListener("blur",v),g.remove();const e=n.getResourceManager();for(const t of i.values())e.releaseTexture(t);i.clear(),0!==l&&(n._free(l),l=0,c=0)};let T=null;function C(e,t,r,u){(o.width<r||o.height<u)&&(o.width=ya(Math.max(o.width,r)),o.height=ya(Math.max(o.height,u))),a.clearRect(0,0,o.width,o.height);const h=t.backgroundColor;a.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,a.fillRect(0,0,r,u),a.save(),a.beginPath(),a.rect(t.padding,0,r-2*t.padding,u),a.clip(),a.font=`${t.fontSize}px ${t.fontFamily}`,a.textBaseline="top",a.textAlign="left";const f=0===t.value.length,p=f?t.placeholder:t.password?"●".repeat(t.value.length):t.value,m=f?t.placeholderColor:t.color;a.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*t.fontSize),_=t.padding;if(t.multiline){const e=_a(a,p,r-2*_);let t=_;for(const n of e)a.fillText(n,_,t),t+=g}else{const e=(u-t.fontSize)/2;a.fillText(p,_,e)}if(t.focused&&d){const e=t.password?"●".repeat(t.cursorPos):t.value.substring(0,t.cursorPos);let n,s,i;if(t.multiline){const e=_a(a,t.value,r-2*_);let o=0,l=0,c=0;for(let n=0;n<e.length;n++){const s=e[n].length;if(o+s>=t.cursorPos){l=n,c=t.cursorPos-o;break}o+=s,n<e.length-1&&o<t.value.length&&"\n"===t.value[o]&&o++,l=n+1,c=0}const u=l<e.length?e[l].substring(0,c):"";n=_+a.measureText(u).width,s=_+l*g,i=g}else n=_+a.measureText(e).width,s=(u-t.fontSize)/2,i=t.fontSize;a.fillStyle=`rgba(${Math.round(255*t.color.r)}, ${Math.round(255*t.color.g)}, ${Math.round(255*t.color.b)}, ${t.color.a})`,a.fillRect(n,s,2,i)}a.restore();const y=a.getImageData(0,0,r,u),x=new Uint8Array(y.data.buffer),w=n.getResourceManager();x.length>c&&(0!==l&&n._free(l),l=n._malloc(x.length),c=x.length),n.HEAPU8.set(x,l);const b=i.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(r,u,l,x.length,1,!0);i.set(e,v);const S=s.get(e,Er);S.texture=v,S.visualType=Cr.Image,S.uvOffset={x:0,y:0},S.uvScale={x:1,y:1},S.color={r:1,g:1,b:1,a:1},S.enabled=!0,s.insert(e,Er,S)}e.addSystemToSchedule(Wt.Update,Nt([Ke(yl)],e=>{const t=s.getEntitiesWithComponents([ml]);for(const e of t)Ma(s,e,gl,{tabIndex:0,isFocused:!1}),Ma(s,e,ia,{enabled:!0,blockRaycast:!0});const n=_();if(n!==T){if(null!==T&&s.valid(T)&&s.has(T,ml)){const e=s.get(T,ml);e.focused=!1,e.dirty=!0,g.blur()}null!==n&&function(e){const t=s.get(e,ml);t.readOnly||(t.focused=!0,t.dirty=!0,g.value=t.value,g.selectionStart=t.cursorPos,g.selectionEnd=t.cursorPos,g.focus(),P())}(n),T=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(Wt.PreUpdate,Nt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let t=0===p?0:(e-p)/1e3;p=e,t=Math.min(t,.1);const o=_();if(null!==o&&(f+=t,f>=.5)){f-=.5,d=!d;s.get(o,ml).dirty=!0}const r=n.getResourceManager();for(const[e,t]of i)s.valid(e)&&s.has(e,ml)||(r.releaseTexture(t),i.delete(e));const a=s.getEntitiesWithComponents([ml,sa]);for(const e of a){const t=s.get(e,ml);if(!t.dirty)continue;const n=s.get(e,sa),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(s.has(e,Er)||s.insert(e,Er,{visualType:Cr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),C(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const wl=new xl,bl=Fa({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?wa(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?ba(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});function vl(e,t){e.has(t,Er)||e.insert(t,Er,{visualType:Cr.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Sl{build(e){ae("Image",na);const t=e.world,n=new Map;e.addSystemToSchedule(Wt.PreUpdate,Nt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,na)||n.delete(e);const e=t.getEntitiesWithComponents([na]);for(const s of e){const e=t.get(s,na),i=t.has(s,sa)?t.get(s,sa):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&t.has(s,Er)&&!bl.changed(r,o))continue;vl(t,s);const a=t.get(s,Er);if(!e.enabled){a.enabled=!1,t.insert(s,Er,a),n.set(s,bl.take(o));continue}a.enabled=!0,a.texture=e.texture,a.color={r:e.color.r,g:e.color.g,b:e.color.b,a:e.color.a},a.material=e.material,a.uvOffset={x:0,y:0},a.uvScale={x:1,y:1};if(e.texture!==L&&0!==e.texture?e.imageType===Qr.Sliced?a.visualType=Cr.NineSlice:a.visualType=Cr.Image:a.visualType=Cr.SolidColor,e.imageType===Qr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));i&&wa(i,s),i&&ba(i,s),e.fillMethod===ea.Horizontal?(e.fillOrigin===ta.Left||(a.uvOffset={x:1-t,y:0}),a.uvScale={x:t,y:1}):(e.fillOrigin===ta.Bottom||(a.uvOffset={x:0,y:1-t}),a.uvScale={x:1,y:t})}else if(e.imageType===Qr.Tiled){const t=i?wa(i,s):0,n=i?ba(i,s):0;e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale={x:t/e.tileSize.x,y:n/e.tileSize.y})}t.insert(s,Er,a),n.set(s,bl.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Ml=new Sl,Pl=Q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null,onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1}},{entityFields:["graphicEntity","group"]}),Tl=Q("ToggleGroup",{allowSwitchOff:!1});function Cl(e,t,n){if(!e.has(t,Er))return;const s=e.get(t,Er);s.color.r===n.r&&s.color.g===n.g&&s.color.b===n.b&&s.color.a===n.a||(s.color=n,e.insert(t,Er,s))}function El(e,t,n){if(!e.has(t,Er))return;const s=e.get(t,Er);s.enabled!==n&&(s.enabled=n,e.insert(t,Er,s))}class Al{build(e){ae("Toggle",Pl),ae("ToggleGroup",Tl);const t=e.world,n=new Set;e.addSystemToSchedule(Wt.Update,Nt([Ke(al)],e=>{const s=t.getEntitiesWithComponents([Pl]);if(!Ps()||Es()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Pl);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Pl,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Pl);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Ma(t,n,ia,{enabled:!0}),!t.has(n,sl))continue;const s=t.get(n,sl),i=t.get(n,Pl),r=t.get(n,ia);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,Tl);if(i.isOn&&r){if(!t.get(s,Tl).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Pl,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Pl);i.isOn&&(i.isOn=!1,t.insert(s,Pl,i),e.emit(s,"change"))}}e.emit(n,"change")}let a;if(i.transition)a=da(i.transition,r.enabled,s.pressed,s.hovered);else{a=ma(i.isOn?i.onColor:i.offColor,r.enabled,s.pressed,s.hovered)}Cl(t,n,a)}}for(const e of s){const n=t.get(e,Pl);Ta(t,n.graphicEntity,e=>{El(t,e,n.isOn)})}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const kl=new Al,Rl=Zr,Il=Q("ProgressBar",{value:0,fillEntity:0,direction:Zr.LeftToRight},{entityFields:["fillEntity"]});class Fl{build(e){ae("ProgressBar",Il);const t=e.world;e.addSystemToSchedule(Wt.PreUpdate,Nt([],()=>{const e=t.getEntitiesWithComponents([Il,sa]);for(const n of e){const e=t.get(n,Il),s=Math.max(0,Math.min(1,e.value));Ta(t,e.fillEntity,n=>{ha(t,n,e.direction,s)})}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Bl=new Fl,Ul=Q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),zl=Q("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});function Hl(e,t,n,s){if(!e.has(t,Se))return{x:n,y:s};const i=e.get(t,Se).entity;if(!e.valid(i)||!e.has(i,me))return{x:n,y:s};const o=e.get(i,me),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=tl(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}class Ll{build(e){ae("Draggable",Ul),ae("DragState",zl);const t=e.world,n=e.getResource(al);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(Wt.PreUpdate,Nt([Ke(Jt),Ke(en)],(e,r)=>{if(Ps()&&!Es())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ul,sl]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,Ul).enabled)continue;if(t.get(s,sl).hovered){let e=0;t.has(s,ye)&&(e=t.get(s,ye).layer);const i=xa(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,zl)||t.insert(n,zl);const e=t.get(n,zl),o=t.get(n,me);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,zl)){t.get(s,zl).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,Ul);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,zl).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,zl))return void(o=null);const s=t.get(o,zl),i=t.get(o,Ul),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,sa)){const e=t.get(o,sa),n=Hl(t,o,s.deltaWorld.x,s.deltaWorld.y);e.offsetMin.x+=n.x,e.offsetMin.y+=n.y,t.insert(o,sa,e)}else if(t.has(o,me)){const e=Hl(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,me);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,me,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const Dl=new Ll,$l=Q("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1},{entityFields:["contentEntity"]});function Wl(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function Ol(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class Vl{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){ae("ScrollView",$l);const t=e.world,n=new Ia,s={x:0,y:0};e.addSystemToSchedule(Wt.PostUpdate,Nt([Ke(Jt),Ke(en),Ke(et)],(e,i,o)=>{const r=Ps()&&!Es(),a=Math.min(o.delta,.05);n.cleanup(t),i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([$l,sa]);for(const o of l){Ma(t,o,qa,{enabled:!0,mode:Ya});const l=t.get(o,$l),c=t.get(o,sa),u=n.ensureInit(o,()=>({isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN})),h=wa(c,o),d=ba(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Me)){const e=t.get(l.contentEntity,Me).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,me))continue;const e=t.get(r,me);let a=0,l=0,c=.5,u=.5;if(t.has(r,sa)){const e=t.get(r,sa);a=wa(e,r)||e.size.x,l=ba(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,ye)){const e=t.get(r,ye);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<n&&(n=h),d>s&&(s=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Ma(t,o,ia,{enabled:!0,blockRaycast:!0});const n=t.has(o,sl)?t.get(o,sl):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=Wl(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=Wl(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Wl(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Wl(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=Ol(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Ba&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Ba?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=Ol(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Ba&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Ba?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}Ta(t,l.contentEntity,e=>{if(!t.has(e,me))return;const n=t.get(e,me),s=n.position.x,i=n.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(i-u.lastAppliedY)>.01)&&(u.contentBaseY=i),n.position.x=u.contentBaseX-l.scrollX,n.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=n.position.x,u.lastAppliedY=n.position.y,t.insert(e,me,n)})}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{n.clear()}}}const Nl=new Vl,Xl=Zr,jl=Q("Slider",{value:0,minValue:0,maxValue:1,direction:Zr.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1},{entityFields:["fillEntity","handleEntity"]});function Yl(e,t,n,s,i,o){const r=wa(s,i)*n.worldScale.x,a=ba(s,i)*n.worldScale.y,l=tl(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-n.worldPosition.x,d=t-n.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case Zr.LeftToRight:return r>0?(f-m)/r:0;case Zr.RightToLeft:return r>0?1-(f-m)/r:0;case Zr.BottomToTop:return a>0?(p-g)/a:0;case Zr.TopToBottom:return a>0?1-(p-g)/a:0}}function ql(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Zr.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=.5,e.anchorMax.x=n,e.anchorMax.y=.5;break;case Zr.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=.5,e.anchorMax.x=1-n,e.anchorMax.y=.5;break;case Zr.BottomToTop:e.anchorMin.x=.5,e.anchorMin.y=n,e.anchorMax.x=.5,e.anchorMax.y=n;break;case Zr.TopToBottom:e.anchorMin.x=.5,e.anchorMin.y=1-n,e.anchorMax.x=.5,e.anchorMax.y=1-n}}class Gl{build(e){ae("Slider",jl);const t=e.world;e.addSystemToSchedule(Wt.PreUpdate,Nt([Ke(Jt),Ke(en),Ke(al)],(e,n,s)=>{if(!n.valid)return;const i=t.getEntitiesWithComponents([jl,sa]);for(const o of i){const i=t.get(o,jl),r=t.get(o,sa);if(!Ps()||Es()){if(t.has(o,me)){Ma(t,o,ia,{enabled:!0,blockRaycast:!0}),Ta(t,i.handleEntity,e=>{Ma(t,e,ia,{enabled:!0,blockRaycast:!1})});const a=t.get(o,me);let l=!1;if(t.has(o,sl)&&(l=t.get(o,sl).pressed),Ta(t,i.handleEntity,e=>{!l&&t.has(e,sl)&&(l=t.get(e,sl).pressed)}),l&&e.isMouseButtonDown(0)){let e=Yl(n.worldMouseX,n.worldMouseY,a,r,o,i.direction);e=Math.max(0,Math.min(1,e));let l=i.minValue+e*(i.maxValue-i.minValue);i.wholeNumbers&&(l=Math.round(l));const c=i.value;i.value=Math.max(i.minValue,Math.min(i.maxValue,l)),t.insert(o,jl,i),i.value!==c&&s.emit(o,"change")}}}const a=i.maxValue-i.minValue,l=a>0?(i.value-i.minValue)/a:0;Ta(t,i.fillEntity,e=>{ha(t,e,i.direction,l)}),Ta(t,i.handleEntity,e=>{if(!t.has(e,sa))return;const n=t.get(e,sa);ql(n,i.direction,l),t.insert(e,sa,n)})}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Kl=new Gl;class Jl{build(e){ae("Focusable",gl);const t=e.world,n=new _l;e.insertResource(yl,n),e.addSystemToSchedule(Wt.Update,Nt([Ke(Jt),Ke(al)],(e,s)=>{if(Ps()&&!Es())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([gl]);for(const e of i){if(!t.has(e,sl))continue;t.get(e,sl).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,ia)){if(!t.get(n,ia).enabled)continue}const s=t.get(n,gl);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,gl)){t.get(i,gl).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,gl).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Zl=new Jl,Ql=Q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function ec(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class tc{build(e){ae("SafeArea",Ql);const t=e.world;let n=ec(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=ec(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=ec(),s=!0});e.addSystemToSchedule(Wt.PreUpdate,Nt([Ke(en)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Ql,sa]);for(const e of u){const s=t.get(e,Ql),i=t.get(e,sa),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,sa,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const nc=new tc,sc=Q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let ic=null;function oc(e,t){if(!ic)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=ic.get(e);n?n.renderer=t:ic.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class rc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null),ic=null}build(e){ae("ListView",sc);const t=e.world,n=new Map;ic=n,e.addSystemToSchedule(Wt.PostUpdate,Nt([Ke(Jt)],e=>{const s=Ps()&&!Es();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([sc,sa]);for(const o of i){Ma(t,o,ia,{enabled:!0,blockRaycast:!0}),Ma(t,o,qa,{enabled:!0,mode:Ya});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,sc),a=t.get(o,sa),l=ba(a,o),c=wa(a,o);if(!s){const n=t.has(o,sl)?t.get(o,sl):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<d;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Re,{value:`ListItem_${e}`}),t.insert(n,sa,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,me)){const s=t.get(n,me);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,me,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{for(const[,e]of n)for(const n of e.itemEntities.values())t.valid(n)&&t.despawn(n);n.clear()}}}const ac=new rc,lc=Q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0},{entityFields:["listEntity","labelEntity"]});class cc{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){ae("Dropdown",lc);const t=e.world,n=new Map,s=new Set;function i(e){Ta(t,e,e=>{if(!t.has(e,me))return;const n=t.get(e,me);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,me,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})})}function o(e){if(t.has(e,Er)){const n=t.get(e,Er);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Ea(t,e,{...za})}else if(t.has(e,ye)){const n=t.get(e,ye);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Ea(t,e,{...za})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;h(i,!0),u(s);let o=0;if(t.has(e,sa)){const n=t.get(e,sa);o=wa(n,e)||n.size.x}else if(t.has(e,ye)){o=t.get(e,ye).size.x}s.ddWidth=o;const r=30*n.options.length;t.insert(i,sa,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:r},pivot:{x:.5,y:1}}),t.insert(i,Er,{visualType:Cr.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn();t.insert(r,Re,{value:`Option_${e}`}),t.insert(r,sa,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:30*-e},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:1}}),t.insert(r,me,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,Er,{visualType:Cr.SolidColor,texture:0,color:{...Ha},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),t.insert(r,ia,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const a=t.spawn();t.insert(a,me,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(a,Wa,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:La.Left,verticalAlign:Da.Middle,wordWrap:!1,overflow:$a.Clip,lineHeight:1.2}),t.insert(a,sa,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:.5}}),t.setParent(a,r),s.textEntities.push(a)}d(s)}function a(e,t,n){t.isOpen=!1,u(n),h(t.listEntity,!1)}function l(e,t,n,s,i){t.selectedIndex=s,a(0,t,n),i.emit(e,"change")}function c(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Wa))return;const s=t.get(n,Wa);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,Wa,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function u(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function h(e,n){Ta(t,e,e=>{t.has(e,ia)&&t.insert(e,ia,{enabled:n,blockRaycast:!0,raycastTarget:!0}),Aa(t,e,n)})}function d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s))continue;const i=n===e.highlightIndex?{...Ua}:{...Ha};Ea(t,s,i)}}function f(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,sl))continue;if(t.get(n,sl).hovered)return!0}return!1}e.addSystemToSchedule(Wt.Update,Nt([Ke(Jt),Ke(al)],(e,p)=>{for(const[e,i]of n)t.valid(e)||(u(i),n.delete(e),s.delete(e));const m=Ps()&&!Es(),g=t.getEntitiesWithComponents([lc]);for(const u of g){const g=t.get(u,lc);let _=n.get(u);if(_||(_={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(u,_)),i(g.listEntity),s.has(u)||(o(u),s.add(u)),g.isOpen||h(g.listEntity,!1),c(g),m)continue;Ma(t,u,ia,{enabled:!0,blockRaycast:!0});const y=t.has(u,sl)?t.get(u,sl):null;if(y?.justPressed&&(g.isOpen?a(u,g,_):r(u,g,_)),g.isOpen){for(let e=0;e<_.optionEntities.length;e++){const n=_.optionEntities[e];if(!t.valid(n)||!t.has(n,sl))continue;if(t.get(n,sl).justPressed){l(u,g,_,e,p);break}}let n=-1;for(let e=0;e<_.optionEntities.length;e++){const s=_.optionEntities[e];if(!t.valid(s)||!t.has(s,sl))continue;if(t.get(s,sl).hovered){n=e;break}}n>=0&&n!==_.highlightIndex&&(_.highlightIndex=n,d(_)),e.isKeyPressed("ArrowDown")?(_.highlightIndex>=g.options.length-1?_.highlightIndex=0:_.highlightIndex++,d(_)):e.isKeyPressed("ArrowUp")?(_.highlightIndex<=0?_.highlightIndex=g.options.length-1:_.highlightIndex--,d(_)):e.isKeyPressed("Enter")&&_.highlightIndex>=0?l(u,g,_,_.highlightIndex,p):e.isKeyPressed("Escape")&&a(u,g,_),e.isMouseButtonPressed(0)&&(y?.hovered||f(_)||a(u,g,_))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]}),this.cleanup_=()=>{for(const[,e]of n)u(e);n.clear(),s.clear()}}}const uc=new cc,hc=ue("LayoutGroup",{direction:0,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:0,reverseOrder:!1});class dc{build(e){ae("LayoutGroup",hc)}}const fc=new dc,pc=0,mc=1,gc=0,_c=1,yc=0,xc=0,wc=3,bc=ue("FlexContainer",{direction:pc,wrap:gc,justifyContent:yc,alignItems:wc,alignContent:0,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0}}),vc=ue("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,alignSelf:0,margin:{left:0,top:0,right:0,bottom:0},minWidth:-1,minHeight:-1,maxWidth:-1,maxHeight:-1,widthPercent:-1,heightPercent:-1});class Sc{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Wt.PostUpdate,Nt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Mc=new Sc,Pc={primary:{r:.25,g:.56,b:.96,a:1},secondary:{r:.4,g:.4,b:.4,a:1},background:{r:.08,g:.08,b:.08,a:1},surface:{r:.14,g:.14,b:.14,a:1},error:{r:.9,g:.2,b:.2,a:1},text:{r:.93,g:.93,b:.93,a:1},textSecondary:{r:.6,g:.6,b:.6,a:1},border:{r:.3,g:.3,b:.3,a:1},fontFamily:"Arial",fontSize:{xs:10,sm:12,md:14,lg:18,xl:24},spacing:{xs:4,sm:8,md:12,lg:16,xl:24},button:{height:36,color:{r:.25,g:.25,b:.25,a:1},textColor:{r:.93,g:.93,b:.93,a:1},transition:{normalColor:{r:.25,g:.25,b:.25,a:1},hoveredColor:{r:.3,g:.3,b:.3,a:1},pressedColor:{r:.18,g:.18,b:.18,a:1},disabledColor:{r:.15,g:.15,b:.15,a:.6}}},slider:{trackHeight:16,trackColor:{r:.15,g:.15,b:.15,a:1},fillColor:{r:.25,g:.56,b:.96,a:1},handleSize:24,handleColor:{r:1,g:1,b:1,a:1}},toggle:{size:{x:24,y:24},onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1},checkColor:{r:1,g:1,b:1,a:1}},input:{height:36,backgroundColor:{r:.15,g:.15,b:.15,a:1},textColor:{r:1,g:1,b:1,a:1},placeholderColor:{r:.6,g:.6,b:.6,a:1},fontSize:16,padding:6},dropdown:{height:32,backgroundColor:{r:.2,g:.2,b:.2,a:1},itemHeight:28},panel:{backgroundColor:{r:.14,g:.14,b:.14,a:1},padding:12},scrollView:{backgroundColor:{r:.1,g:.1,b:.1,a:1}}},Tc=Ge(null,"UITheme");let Cc=null;function Ec(e){e.hasResource(Tc)&&(Cc=e.getResource(Tc))}function Ac(){return Cc??Pc}function kc(e,t){const n=e.spawn();if(t.name&&e.insert(n,Re,{value:t.name}),e.insert(n,me,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},...t.transform}),t.rect&&e.insert(n,sa,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:0,y:0},pivot:{x:.5,y:.5},...t.rect}),t.renderer&&e.insert(n,Er,{visualType:Cr.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0,...t.renderer}),t.interactable&&e.insert(n,ia,{enabled:!0,blockRaycast:!0,raycastTarget:!0,...t.interactable}),t.text){const s=Ac();e.insert(n,Wa,{content:"",fontFamily:s.fontFamily,fontSize:s.fontSize.md,color:{r:1,g:1,b:1,a:1},align:La.Left,verticalAlign:Da.Top,wordWrap:!1,overflow:0,lineHeight:1.2,...t.text})}if(t.image&&e.insert(n,na,{...na._default,...t.image}),t.flex&&e.insert(n,bc,{direction:pc,wrap:gc,justifyContent:yc,alignItems:wc,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0},...t.flex}),t.flexItem&&e.insert(n,vc,{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,...t.flexItem}),t.mask&&e.insert(n,qa,{enabled:!0,mode:Ya,...t.mask}),t.components)for(const[s,i]of t.components)e.insert(n,s,i);return t.parent&&e.setParent(n,t.parent),n}function Rc(e,t={}){const n=Ac(),{text:s="Button",fontSize:i=n.fontSize.md,size:o={x:120,y:n.button.height},color:r=n.button.color,textColor:a=n.button.textColor,transition:l=null,parent:c}=t,u=kc(e,{name:"ButtonLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:s,fontSize:i,color:a,align:La.Center,verticalAlign:Da.Middle}}),h=kc(e,{name:"Button",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Cr.SolidColor,color:r},interactable:{enabled:!0},components:[[ol,{state:0,transition:l}]]});if(e.setParent(u,h),t.events){if(t.onClick){const e=t.onClick;t.events.on(h,"click",()=>e(h))}if(t.onHover){const e=t.onHover;t.events.on(h,"hover_enter",()=>e(h))}}return h}function Ic(e,t={}){const n=Ac(),{value:s=0,minValue:i=0,maxValue:o=1,direction:r=Zr.LeftToRight,size:a={x:200,y:n.slider.trackHeight},trackColor:l=n.slider.trackColor,fillColor:c=n.slider.fillColor,handleSize:u={x:n.slider.handleSize,y:n.slider.handleSize},handleColor:h=n.slider.handleColor,wholeNumbers:d=!1,parent:f}=t,p=kc(e,{name:"SliderFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Cr.SolidColor,color:c}}),m=kc(e,{name:"SliderHandle",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:u},renderer:{visualType:Cr.SolidColor,color:h},interactable:{enabled:!0,blockRaycast:!0},components:[[Ul,{enabled:!0,dragThreshold:5,lockX:!1,lockY:!0}]]}),g=kc(e,{name:"Slider",parent:f,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Cr.SolidColor,color:l},interactable:{enabled:!0,blockRaycast:!0},components:[[jl,{value:s,minValue:i,maxValue:o,direction:r,wholeNumbers:d,fillEntity:p,handleEntity:m}]]});if(e.setParent(p,g),e.setParent(m,g),t.onChange&&t.events){const n=t.onChange;t.events.on(g,"change",()=>{const t=e.get(g,jl);n(t.value,g)})}return g}function Fc(e,t={}){const n=Ac(),{isOn:s=!0,size:i=n.toggle.size,onColor:o=n.toggle.onColor,offColor:r=n.toggle.offColor,checkSize:a={x:.58*n.toggle.size.x,y:.58*n.toggle.size.y},checkColor:l=n.toggle.checkColor,group:c=0,transition:u=null,label:h,parent:d}=t,f=kc(e,{name:"ToggleCheck",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:Cr.SolidColor,color:l}}),p=kc(e,{name:"Toggle",parent:d,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Cr.SolidColor,color:s?o:r},interactable:{enabled:!0},components:[[Pl,{isOn:s,graphicEntity:f,group:c,transition:u,onColor:o,offColor:r}]]});if(e.setParent(f,p),h&&kc(e,{name:"ToggleLabel",parent:p,rect:{anchorMin:{x:1,y:0},anchorMax:{x:1,y:1},offsetMin:{x:8,y:0},size:{x:100,y:0}},text:{content:h,fontSize:n.fontSize.md,align:La.Left,verticalAlign:Da.Middle}}),t.onChange&&t.events){const n=t.onChange;t.events.on(p,"change",()=>{const t=e.get(p,Pl);n(t.isOn,p)})}return p}function Bc(e,t={}){const n=Ac(),{value:s=0,size:i={x:200,y:n.slider.trackHeight},direction:o=Zr.LeftToRight,trackColor:r=n.slider.trackColor,fillColor:a=n.primary,parent:l}=t,c=kc(e,{name:"ProgressFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:Cr.SolidColor,color:a}}),u=kc(e,{name:"ProgressBar",parent:l,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:Cr.SolidColor,color:r},components:[[Il,{value:s,fillEntity:c,direction:o}]]});return e.setParent(c,u),u}function Uc(e,t={}){const n=Ac(),{size:s={x:300,y:400},contentSize:i={x:300,y:800},horizontal:o=!1,vertical:r=!0,elastic:a=!0,mask:l=!0,parent:c}=t,u=kc(e,{name:"ScrollContent",rect:{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},size:{x:i.x,y:i.y},pivot:{x:.5,y:1}}}),h=kc(e,{name:"ScrollView",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:s},renderer:{visualType:Cr.SolidColor,color:n.scrollView.backgroundColor},mask:l?{mode:Ya,enabled:!0}:void 0,components:[[$l,{contentEntity:u,horizontalEnabled:o,verticalEnabled:r,contentWidth:i.x,contentHeight:i.y,elastic:a,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,wheelSensitivity:.1}]]});return e.setParent(u,h),h}function zc(e,t={}){const n=Ac(),{placeholder:s="",value:i="",size:o={x:200,y:n.input.height},fontSize:r=n.input.fontSize,backgroundColor:a=n.input.backgroundColor,textColor:l=n.input.textColor,maxLength:c=0,multiline:u=!1,password:h=!1,parent:d}=t,f=kc(e,{name:"TextInput",parent:d,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Cr.SolidColor,color:a},interactable:{enabled:!0},components:[[ml,{value:i,placeholder:s,fontSize:r,fontFamily:n.fontFamily,color:l,backgroundColor:a,placeholderColor:n.input.placeholderColor,padding:n.input.padding,maxLength:c,multiline:u,password:h,readOnly:!1,focused:!1,cursorPos:i.length,dirty:!0}],[gl,{tabIndex:0,isFocused:!1}]]});if(t.events){if(t.onChange){const n=t.onChange;t.events.on(f,"change",()=>{const t=e.get(f,ml);n(t.value,f)})}if(t.onSubmit){const n=t.onSubmit;t.events.on(f,"submit",()=>{const t=e.get(f,ml);n(t.value,f)})}}return f}function Hc(e,t){const n=Ac(),{options:s,selectedIndex:i=-1,size:o={x:160,y:n.dropdown.height},fontSize:r=n.fontSize.md,parent:a}=t,l=kc(e,{name:"DropdownLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:(i>=0?s[i]:s[0])??"",fontSize:r,align:La.Left,verticalAlign:Da.Middle}}),c=kc(e,{name:"DropdownList",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},size:{x:o.x,y:Math.min(s.length*n.dropdown.itemHeight,200)},pivot:{x:.5,y:1}},renderer:{visualType:Cr.SolidColor,color:n.surface},mask:{mode:Ya,enabled:!0}}),u=kc(e,{name:"Dropdown",parent:a,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:Cr.SolidColor,color:n.dropdown.backgroundColor},interactable:{enabled:!0},components:[[lc,{options:s,selectedIndex:i,isOpen:!1,listEntity:c,labelEntity:l}]]});if(e.setParent(l,u),e.setParent(c,u),t.onChange&&t.events){const n=t.onChange;t.events.on(u,"change",()=>{const t=e.get(u,lc);n(t.selectedIndex,u)})}return u}function Lc(e,t){const n=Ac();return kc(e,{name:"Label",parent:t.parent,rect:t.size?{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size}:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:t.text,fontSize:t.fontSize??n.fontSize.md,color:t.color??n.text,align:t.align??La.Left,verticalAlign:t.verticalAlign??Da.Middle}})}function Dc(e,t={}){const n=Ac();return kc(e,{name:"Panel",parent:t.parent,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size??{x:300,y:200}},renderer:{visualType:Cr.SolidColor,color:t.color??n.panel.backgroundColor}})}function $c(e,t={}){return kc(e,{name:"FlexRow",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:pc,wrap:t.wrap?_c:gc,justifyContent:t.justifyContent??yc,alignItems:t.alignItems??xc,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}function Wc(e,t={}){return kc(e,{name:"FlexColumn",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:mc,wrap:t.wrap?_c:gc,justifyContent:t.justifyContent??yc,alignItems:t.alignItems??xc,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}const Oc={button:Rc,slider:Ic,toggle:Fc,textInput:zc,dropdown:Hc,progressBar:Bc,label:Lc,panel:Dc,flexRow:$c,flexColumn:Wc,scrollView:Uc};const Vc={spawn:kc,destroy:function e(t,n){if(t.valid(n)){if(t.has(n,Me)){const s=[...t.get(n,Me).entities];for(const n of s)e(t,n)}t.despawn(n)}},build:function e(t,n,s){let i,o;if("element"===n.type)i=kc(t,{...n,parent:s}),o=i;else{if(i=(0,Oc[n.type])(t,{...n.options??{},parent:s}),"scrollView"===n.type){o=t.get(i,$l).contentEntity}else o=i}const r=n.children;if(r&&o)for(const n of r)e(t,n,o);return n.ref&&n.ref(i),i},label:Lc,panel:Dc,button:Rc,slider:Ic,toggle:Fc,scrollView:Uc,textInput:zc,dropdown:Hc,progressBar:Bc,flexRow:$c,flexColumn:Wc};async function Nc(e,t,n){const s=e.getResource(Fr);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}class Xc{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let s,i;if("string"==typeof e){const t=(new TextEncoder).encode(e);i=t.length,s=this.raw_._malloc(i+1),this.raw_.HEAPU8.set(t,s),this.raw_.HEAPU8[s+i]=0}else i=e.length,s=this.raw_._malloc(i),this.raw_.HEAPU8.set(e,s);const o=this.api_.loadSkeleton(s,i,t,t.length,n);return this.raw_._free(s),o}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,s,i){this.api_.setAtlasPageTexture(e,t,n,s,i)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,s=0){return!!this.api_.playAnimation(e,t,n,s)}addAnimation(e,t,n=!0,s=0,i=0){return!!this.api_.addAnimation(e,t,n,s,i)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse animations JSON",e),[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch(e){return console.warn("[Spine] Failed to parse skins JSON",e),[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,s))return this.raw_._free(n),this.raw_._free(s),null;const i=this.raw_.HEAPF32[n>>2],o=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:i,y:o}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,s=t>>2,i={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(t),i}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],s=this.raw_._malloc(8),i=s,o=s+4;for(let s=0;s<t;s++){const t=this.api_.getMeshBatchVertexCount(e,s),r=this.api_.getMeshBatchIndexCount(e,s);if(t<=0||r<=0)continue;const a=8*t*4,l=2*r,c=this.raw_._malloc(a),u=this.raw_._malloc(l);this.api_.getMeshBatchData(e,s,c,u,i,o);const h=new Float32Array(this.raw_.HEAPF32.buffer,c,8*t),d=new Uint16Array(this.raw_.HEAPU8.buffer,u,r);n.push({vertices:new Float32Array(h),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[i>>2],blendMode:this.raw_.HEAPU32[o>>2]}),this.raw_._free(c),this.raw_._free(u)}return this.raw_._free(s),n}setDefaultMix(e,t){this.api_.setDefaultMix(e,t)}setMixDuration(e,t,n,s){this.api_.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){this.api_.setTrackAlpha(e,t,n)}setAttachment(e,t,n){return!!this.api_.setAttachment(e,t,n)}setIKTarget(e,t,n,s,i){return!!this.api_.setIKTarget(e,t,n,s,i)}setSlotColor(e,t,n,s,i,o){return!!this.api_.setSlotColor(e,t,n,s,i,o)}enableEvents(e){this.api_.enableEvents(e)}collectEvents(e){const t=this.api_.getEventCount(e);if(0===t)return[];const n=this.api_.getEventBuffer(),s=this.raw_.HEAPF32,i=n>>2,o=[];for(let e=0;e<t;e++){const t=i+4*e;o.push({type:s[t],track:s[t+1],floatValue:s[t+2],intValue:s[t+3]})}return this.api_.clearEvents(),o}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const s=this.listeners_.get(e);s.has(t)||s.set(t,new Set),s.get(t).add(n)}off(e,t,n){const s=this.listeners_.get(e);if(!s)return;const i=s.get(t);i&&i.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}class jc{constructor(e){this.entities_=new Map,this.cachedFrame_=-1,this.cachedEntries_=[],this.controller_=e}get controller(){return this.controller_}get entityCount(){return this.entities_.size}loadEntity(e,t,n,s,i){const o=this.controller_.loadSkeleton(t,n,i);if(o<0)return console.error(`[ModuleBackend] Failed to load skeleton: ${this.controller_.getLastError()}`),!1;const r=this.controller_.getAtlasPageCount(o);for(let e=0;e<r;e++){const t=this.controller_.getAtlasPageTextureName(o,e),n=s.get(t);n&&this.controller_.setAtlasPageTexture(o,e,n.glId,n.w,n.h)}const a=this.controller_.createInstance(o);return this.entities_.set(e,{skelHandle:o,instanceId:a,skeletonScale:1,flipX:!1,flipY:!1,layer:0}),!0}setEntityProps(e,t){const n=this.entities_.get(e);n&&(void 0!==t.skeletonScale&&(n.skeletonScale=t.skeletonScale),void 0!==t.flipX&&(n.flipX=t.flipX),void 0!==t.flipY&&(n.flipY=t.flipY),void 0!==t.layer&&(n.layer=t.layer))}setAnimation(e,t,n){const s=this.entities_.get(e);s&&this.controller_.play(s.instanceId,t,n)}setSkin(e,t){const n=this.entities_.get(e);n&&this.controller_.setSkin(n.instanceId,t)}getBounds(e){const t=this.entities_.get(e);return t?this.controller_.getBounds(t.instanceId):null}getAnimations(e){const t=this.entities_.get(e);return t?this.controller_.getAnimations(t.instanceId):[]}getSkins(e){const t=this.entities_.get(e);return t?this.controller_.getSkins(t.instanceId):[]}setDefaultMix(e,t){const n=this.entities_.get(e);n&&this.controller_.setDefaultMix(n.skelHandle,t)}setMixDuration(e,t,n,s){const i=this.entities_.get(e);i&&this.controller_.setMixDuration(i.skelHandle,t,n,s)}setTrackAlpha(e,t,n){const s=this.entities_.get(e);s&&this.controller_.setTrackAlpha(s.instanceId,t,n)}setAttachment(e,t,n){const s=this.entities_.get(e);return!!s&&this.controller_.setAttachment(s.instanceId,t,n)}setIKTarget(e,t,n,s,i){const o=this.entities_.get(e);return!!o&&this.controller_.setIKTarget(o.instanceId,t,n,s,i)}setSlotColor(e,t,n,s,i,o){const r=this.entities_.get(e);return!!r&&this.controller_.setSlotColor(r.instanceId,t,n,s,i,o)}enableEvents(e){const t=this.entities_.get(e);t&&this.controller_.enableEvents(t.instanceId)}updateAll(e){for(const t of this.entities_.values())this.controller_.update(t.instanceId,e)}extractAndSubmitMeshes(e,t,n=-1){const s=e.renderer_submitSpineBatchByEntity;if(!s)return;if(this.cachedFrame_!==n){this.cachedEntries_.length=0;for(const[e,t]of this.entities_){const n=this.controller_.extractMeshBatches(t.instanceId);for(const s of n)0!==s.vertices.length&&0!==s.indices.length&&this.cachedEntries_.push({vertices:s.vertices,indices:s.indices,textureId:s.textureId,blendMode:s.blendMode,entity:e,info:t})}this.cachedFrame_=n}if(0===this.cachedEntries_.length)return;let i=0,o=0;for(const e of this.cachedEntries_)i+=e.vertices.byteLength,o+=e.indices.byteLength;const r=e._malloc(i),a=e._malloc(o);let l=0,c=0;for(const n of this.cachedEntries_){const i=r+l,o=a+c;e.HEAPF32.set(n.vertices,i>>2),new Uint16Array(e.HEAPU8.buffer,o,n.indices.length).set(n.indices),s.call(e,t,i,n.vertices.length/8,o,n.indices.length,n.textureId,n.blendMode,n.entity,n.info.skeletonScale,n.info.flipX,n.info.flipY,n.info.layer,0),l+=n.vertices.byteLength,c+=n.indices.byteLength}e._free(r),e._free(a)}removeEntity(e){const t=this.entities_.get(e);t&&(this.controller_.destroyInstance(t.instanceId),this.controller_.unloadSkeleton(t.skelHandle),this.entities_.delete(e))}shutdown(){for(const e of this.entities_.values())this.controller_.destroyInstance(e.instanceId),this.controller_.unloadSkeleton(e.skelHandle);this.entities_.clear()}}class Yc{constructor(e,t){this.backends_=new Map,this.loadingBackends_=new Map,this.entityVersions_=new Map,this.coreModule_=e,this.factories_=t}static detectVersion(e){const t=function(e){if(e.length<10)return null;let t=8;const{value:n,bytesRead:s}=qc(e,t);if(t+=s,n<=1||t+n-1>e.length)return null;const i=(new TextDecoder).decode(e.subarray(t,t+n-1));return i.startsWith("4.2")?"4.2":i.startsWith("4.1")?"4.1":null}(e);return t||function(e){if(e.length<4)return null;let t=0;const{value:n,bytesRead:s}=qc(e,t);t+=s,n>0&&(t+=n-1);if(t>=e.length)return null;const{value:i,bytesRead:o}=qc(e,t);if(t+=o,i<=1||t+i-1>e.length)return null;const r=(new TextDecoder).decode(e.subarray(t,t+i-1));return r.startsWith("3.")?"3.8":null}(e)}static detectVersionJson(e){const t=e.match(/"spine"\s*:\s*"(\d+\.\d+)/);return t?t[1].startsWith("4.2")?"4.2":t[1].startsWith("4.1")?"4.1":t[1].startsWith("3.")?"3.8":null:null}async loadEntity(e,t,n,s,i){const o="string"==typeof t?Yc.detectVersionJson(t):Yc.detectVersion(t);if(!o)return null;if("4.2"===o&&!this.factories_.has("4.2"))return this.entityVersions_.set(e,"4.2"),"4.2";this.coreModule_.spine_setNeedsReload?.(i,e,!1);const r=await this.ensureBackend(o);if(!r)return console.error(`[SpineManager] Failed to create backend for version ${o}`),null;const a=t instanceof Uint8Array;return r.loadEntity(e,t,n,s,a)?(this.entityVersions_.set(e,o),o):(console.error(`[SpineManager] Failed to load entity ${e} into backend ${o}`),null)}updateAnimations(e){for(const t of this.backends_.values())t.updateAll(e)}submitMeshes(e,t=-1){for(const n of this.backends_.values())n.extractAndSubmitMeshes(this.coreModule_,e,t)}removeEntity(e){const t=this.entityVersions_.get(e);if(!t)return void this.entityVersions_.delete(e);const n=this.backends_.get(t);n&&n.removeEntity(e),this.entityVersions_.delete(e)}getEntityVersion(e){return this.entityVersions_.get(e)}hasModuleBackend(e){return this.backends_.has(e)}getModuleBackend(e){return this.backends_.get(e)}setAnimation(e,t,n){const s=this.entityVersions_.get(e);if(!s)return;const i=this.backends_.get(s);i&&i.setAnimation(e,t,n)}setSkin(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setSkin(e,t)}setEntityProps(e,t){const n=this.entityVersions_.get(e);if(!n)return;const s=this.backends_.get(n);s&&s.setEntityProps(e,t)}getBounds(e){const t=this.entityVersions_.get(e);if(!t)return null;const n=this.backends_.get(t);return n?n.getBounds(e):null}getAnimations(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getAnimations(e):[]}getSkins(e){const t=this.entityVersions_.get(e);if(!t)return[];const n=this.backends_.get(t);return n?n.getSkins(e):[]}setDefaultMix(e,t){const n=this.getEntityBackend_(e);n&&n.setDefaultMix(e,t)}setMixDuration(e,t,n,s){const i=this.getEntityBackend_(e);i&&i.setMixDuration(e,t,n,s)}setTrackAlpha(e,t,n){const s=this.getEntityBackend_(e);s&&s.setTrackAlpha(e,t,n)}setAttachment(e,t,n){const s=this.getEntityBackend_(e);return!!s&&s.setAttachment(e,t,n)}setIKTarget(e,t,n,s,i){const o=this.getEntityBackend_(e);return!!o&&o.setIKTarget(e,t,n,s,i)}setSlotColor(e,t,n,s,i,o){const r=this.getEntityBackend_(e);return!!r&&r.setSlotColor(e,t,n,s,i,o)}enableEvents(e){const t=this.getEntityBackend_(e);t&&t.enableEvents(e)}hasInstance(e){return this.entityVersions_.has(e)}shutdown(){for(const e of this.backends_.values())e.shutdown();this.backends_.clear(),this.loadingBackends_.clear(),this.entityVersions_.clear()}getEntityBackend_(e){const t=this.entityVersions_.get(e);if(t)return this.backends_.get(t)}async ensureBackend(e){const t=this.backends_.get(e);if(t)return t;const n=this.loadingBackends_.get(e);if(n)return n;const s=this.factories_.get(e);if(!s)return console.warn(`[SpineManager] No module factory for version ${e}`),null;const i=(async()=>{try{const t=await s(),n=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"]),setDefaultMix:t("spine_setDefaultMix",null,["number","number"]),setMixDuration:t("spine_setMixDuration",null,["number","string","string","number"]),setTrackAlpha:t("spine_setTrackAlpha",null,["number","number","number"]),enableEvents:t("spine_enableEvents",null,["number"]),getEventCount:t("spine_getEventCount","number",["number"]),getEventBuffer:t("spine_getEventBuffer","number",[]),clearEvents:t("spine_clearEvents",null,[]),setAttachment:t("spine_setAttachment","number",["number","string","string"]),setIKTarget:t("spine_setIKTarget","number",["number","string","number","number","number"]),setSlotColor:t("spine_setSlotColor","number",["number","string","number","number","number","number"])}}(t),i=new Xc(t,n),o=new jc(i);return this.backends_.set(e,o),o}catch(t){return console.error(`[SpineManager] Failed to load WASM module for version ${e}:`,t),null}finally{this.loadingBackends_.delete(e)}})();return this.loadingBackends_.set(e,i),i}}function qc(e,t){let n=0,s=0,i=0;do{const o=e[t+i++];if(n|=(127&o)<<s,s+=7,!(128&o))break}while(s<35);return{value:n,bytesRead:i}}async function Gc(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Kc=Ge({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Jc={r:.2,g:.4,b:1,a:.7},Zc={r:.2,g:1,b:.2,a:.7},Qc={r:.2,g:1,b:1,a:.7},eu={r:1,g:1,b:.2,a:.5},tu={r:1,g:.2,b:.2,a:.8},nu={r:1,g:.2,b:.2,a:1},su=1.5,iu=16;function ou(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ru(e){switch(e){case Ye.Static:return Jc;case Ye.Kinematic:return Qc;default:return Zc}}function au(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)wo.line(l[e],l[(e+1)%4],o,su)}function lu(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),h=l(-n,-s),d=l(n,-s);wo.line(c,h,o,su),wo.line(u,d,o,su);for(let e=0;e<iu;e++){const t=e/iu*Math.PI,i=(e+1)/iu*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));wo.line(r,a,o,su)}for(let e=0;e<iu;e++){const t=Math.PI+e/iu*Math.PI,i=Math.PI+(e+1)/iu*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));wo.line(r,a,o,su)}}function cu(e,t,n,s){const i=e+.5*n,o=t+.5*s;wo.line({x:e,y:t},{x:i,y:o},tu,su);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),h=o-6*(l*Math.sin(a)+c*Math.cos(a)),d=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));wo.line({x:i,y:o},{x:u,y:h},tu,su),wo.line({x:i,y:o},{x:d,y:f},tu,su)}function uu(e,t,n){const s=e.getResource(Kc);if(!s||!s.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([be]);for(const n of t){const t=e.world.get(n,be);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([Ue,me]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,Ue);if(!n.enabled)continue;const o=e.world.get(t,me),a=o.worldPosition.x,l=o.worldPosition.y,c=ou(o.worldRotation);if(s.showColliders){if(e.world.has(t,ze)){const s=e.world.get(t,ze),o=s.isSensor?eu:ru(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);au(a+r*h-u*d,l+r*d+u*h,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,He)){const s=e.world.get(t,He),o=s.isSensor?eu:ru(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c),f=a+r*h-u*d,p=l+r*d+u*h;wo.circleOutline({x:f,y:p},s.radius*i,o,su,32)}if(e.world.has(t,Le)){const s=e.world.get(t,Le),o=s.isSensor?eu:ru(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);lu(a+r*h-u*d,l+r*d+u*h,s.radius*i,s.halfHeight*i,c,o)}if(e.world.has(t,De)){const s=e.world.get(t,De),o=s.isSensor?eu:ru(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=a+(s.point1.x*i*r-s.point1.y*i*u),d=l+(s.point1.x*i*u+s.point1.y*i*r),f=a+(s.point2.x*i*r-s.point2.y*i*u),p=l+(s.point2.x*i*u+s.point2.y*i*r);wo.line({x:h,y:d},{x:f,y:p},o,su)}if(e.world.has(t,$e)){const s=e.world.get(t,$e),o=s.isSensor?eu:ru(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=s.vertices;for(let e=0;e<h.length;e++){const t=h[e],n=h[(e+1)%h.length],s=a+(t.x*i*r-t.y*i*u),c=l+(t.x*i*u+t.y*i*r),d=a+(n.x*i*r-n.y*i*u),f=l+(n.x*i*u+n.y*i*r);wo.line({x:s,y:c},{x:d,y:f},o,su)}}if(e.world.has(t,We)){const s=e.world.get(t,We),o=ru(n.bodyType),r=Math.cos(c),u=Math.sin(c),h=s.points,d=s.isLoop?h.length:h.length-1;for(let e=0;e<d;e++){const t=h[e],n=h[(e+1)%h.length],s=a+(t.x*i*r-t.y*i*u),c=l+(t.x*i*u+t.y*i*r),d=a+(n.x*i*r-n.y*i*u),f=l+(n.x*i*u+n.y*i*r);wo.line({x:s,y:c},{x:d,y:f},o,su)}}}if(s.showVelocity&&r&&n.bodyType===Ye.Dynamic){const e=r.getLinearVelocity(t);cu(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)wo.circle({x:e.contactX,y:e.contactY},3,nu,!0,32)}}const hu=Ge({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),du=Ge(null,"PhysicsAPI");function fu(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}class pu{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/30,subStepCount:t.subStepCount??4,contactHertz:t.contactHertz??30,contactDampingRatio:t.contactDampingRatio??10,contactSpeed:t.contactSpeed??3,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(hu,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Set,s=new Set,i=new Map;let o=-1;const r=Gc(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount,this.config_.contactHertz,this.config_.contactDampingRatio,this.config_.contactSpeed);const a=function(e){const t=e.world.getEntitiesWithComponents([be]);for(const n of t){const t=e.world.get(n,be);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),l=1/a,c=e.world;c.onDespawn(e=>{n.has(e)&&(r._physics_destroyJoint(e),n.delete(e)),t.has(e)&&(r._physics_destroyBody(e),t.delete(e),i.delete(e),s.delete(e))}),e.addSystemToSchedule(Wt.PostUpdate,Nt([Ke(et)],u=>{if(Ps()&&!Es())return;const h=c.getEntitiesWithComponents([Ue,me]),d=new Set;for(const n of h)if(d.add(n),t.has(n)){if(c.isChangedSince(n,Ue,o)){const e=c.get(n,Ue),t=i.get(n);!t||t.bodyType===e.bodyType&&t.gravityScale===e.gravityScale&&t.linearDamping===e.linearDamping&&t.angularDamping===e.angularDamping&&t.fixedRotation===e.fixedRotation&&t.bullet===e.bullet||(r._physics_updateBodyProperties(n,e.bodyType,e.gravityScale,e.linearDamping,e.angularDamping,e.fixedRotation?1:0,e.bullet?1:0),t.bodyType=e.bodyType,t.gravityScale=e.gravityScale,t.linearDamping=e.linearDamping,t.angularDamping=e.angularDamping,t.fixedRotation=e.fixedRotation,t.bullet=e.bullet)}const e=i.get(n);if(e&&e.bodyType===Ye.Kinematic){const e=c.get(n,me),t=fu(e.worldRotation);r._physics_setBodyTransform(n,e.worldPosition.x*l,e.worldPosition.y*l,t)}}else{const o=c.get(n,Ue);if(!o.enabled)continue;const a=c.get(n,me),u=c.has(n,Se),h=u?a.worldPosition.x:a.position.x,d=u?a.worldPosition.y:a.position.y,f=fu(u?a.worldRotation:a.rotation);r._physics_createBody(n,o.bodyType,h*l,d*l,f,o.gravityScale,o.linearDamping,o.angularDamping,o.fixedRotation?1:0,o.bullet?1:0),_u(e,r,n,this.config_.collisionLayerMasks),t.add(n),c.has(n,Se)&&s.add(n),i.set(n,{bodyType:o.bodyType,gravityScale:o.gravityScale,linearDamping:o.linearDamping,angularDamping:o.angularDamping,fixedRotation:o.fixedRotation,bullet:o.bullet})}o=c.getWorldTick();for(const e of t)d.has(e)||(r._physics_destroyBody(e),t.delete(e),i.delete(e));!function(e,t,n,s,i){const o=e.getEntitiesWithComponents([Oe,Ue]);for(const r of o){if(s.has(r))continue;if(!n.has(r))continue;const o=e.get(r,Oe);if(!o.enabled)continue;const a=o.connectedEntity;n.has(a)&&(t._physics_createRevoluteJoint(a,r,o.anchorA.x*i,o.anchorA.y*i,o.anchorB.x*i,o.anchorB.y*i,o.enableMotor?1:0,o.motorSpeed,o.maxMotorTorque,o.enableLimit?1:0,o.lowerAngle,o.upperAngle,o.collideConnected?1:0),s.add(r))}for(const o of e.getEntitiesWithComponents([Ve,Ue])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Ve);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createDistanceJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.length*i,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.minLength*i,r.maxLength*i,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([Ne,Ue])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Ne);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createPrismaticJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*i,r.upperTranslation*i,r.enableMotor?1:0,r.maxMotorForce,r.motorSpeed,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([Xe,Ue])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,Xe);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWeldJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.linearHertz,r.angularHertz,r.linearDampingRatio,r.angularDampingRatio,r.collideConnected?1:0),s.add(o))}for(const o of e.getEntitiesWithComponents([je,Ue])){if(s.has(o))continue;if(!n.has(o))continue;const r=e.get(o,je);if(!r.enabled)continue;const a=r.connectedEntity;n.has(a)&&(t._physics_createWheelJoint(a,o,r.anchorA.x*i,r.anchorA.y*i,r.anchorB.x*i,r.anchorB.y*i,r.axis.x,r.axis.y,r.enableSpring?1:0,r.hertz,r.dampingRatio,r.enableLimit?1:0,r.lowerTranslation*i,r.upperTranslation*i,r.enableMotor?1:0,r.maxMotorTorque,r.motorSpeed,r.collideConnected?1:0),s.add(o))}}(c,r,t,n,l),t.size>0&&u.delta>0&&r._physics_step(u.delta),function(e,t,n,s){const i=t._physics_getDynamicBodyCount();if(0===i)return;const o=t._physics_getDynamicBodyTransforms(),r=o>>2,a=t.HEAPU32,l=t.HEAPF32,c=e.world.getCppRegistry();if(!c)return;const u=e.world.getWasmModule(),h=s.size>0;if(!h&&u?.registry_batchSyncPhysicsTransforms){const e=i*wu,s=u._malloc(e);return u.HEAPU8.set(new Uint8Array(t.HEAPU8.buffer,o,e),s),u.registry_batchSyncPhysicsTransforms(c,s,i,n),void u._free(s)}const d=u?.getTransformPtr?e=>u.getTransformPtr(c,e):null,f=u?.HEAPF32,p=d&&f?null:c.addTransform.bind(c),m=yu;for(let t=0;t<i;t++){const i=r+t*xu,o=a[i];let c=l[i+1]*n,u=l[i+2]*n,g=l[i+3];if(h&&s.has(o)){const t=e.world.get(o,Se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,me)){const n=e.world.get(t.entity,me),s=fu(n.worldRotation),i=u,o=c-n.worldPosition.x,r=i-n.worldPosition.y,a=Math.cos(-s),l=Math.sin(-s);c=(o*a-r*l)/(0!==n.worldScale.x?n.worldScale.x:1),u=(o*l+r*a)/(0!==n.worldScale.y?n.worldScale.y:1),g-=s}}const _=.5*g,y=Math.cos(_),x=Math.sin(_);if(d&&f){const e=d(o);if(e){const t=e>>2;f[t]=c,f[t+1]=u,f[t+2]=0,f[t+3]=0,f[t+4]=0,f[t+5]=x,f[t+6]=y,f[t+7]=1,f[t+8]=1,f[t+9]=1,f[t+10]=c,f[t+11]=u,f[t+12]=0,f[t+13]=0,f[t+14]=0,f[t+15]=x,f[t+16]=y,f[t+17]=1,f[t+18]=1,f[t+19]=1;continue}}m.position.x=c,m.position.y=u,m.rotation.w=y,m.rotation.x=0,m.rotation.y=0,m.rotation.z=x,m.worldPosition.x=c,m.worldPosition.y=u,m.worldRotation.w=y,m.worldRotation.x=0,m.worldRotation.y=0,m.worldRotation.z=x,p(o,m)}}(e,r,a,s),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(hu,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,r,a)},{name:"PhysicsSystem"})),e.physicsModule=r,e.insertResource(du,bu._fromModule(r)),function(e,t,n){e.insertResource(Kc,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Po("physics-debug-draw",()=>{uu(e,t,n)})}(e,du,hu),e.setFixedTimestep(this.config_.fixedTimestep)});r.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=r}}const mu=16;function gu(e,t,n){if(!n)return t;for(let t=0;t<mu;t++)if(e===1<<t)return n[t];return t}function _u(e,t,n,s){const i=e.world;if(i.has(n,ze)){const e=i.get(n,ze),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s);t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.radius??.05,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,He)){const e=i.get(n,He),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s);t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,Le)){const e=i.get(n,Le),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,De)){const e=i.get(n,De),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s);t._physics_addSegmentShape(n,e.point1.x,e.point1.y,e.point2.x,e.point2.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,$e)){const e=i.get(n,$e),o=e.categoryBits??1,r=gu(o,e.maskBits??65535,s),a=e.vertices,l=Math.min(a.length,8),c=2*l*4,u=t._malloc(c),h=u>>2;for(let e=0;e<l;e++)t.HEAPF32[h+2*e]=a[e].x,t.HEAPF32[h+2*e+1]=a[e].y;t._physics_addPolygonShape(n,u,l,e.radius??0,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r),t._free(u)}if(i.has(n,We)){const e=i.get(n,We),s=e.points;if(s.length<4)return;const o=2*s.length*4,r=t._malloc(o),a=r>>2;for(let e=0;e<s.length;e++)t.HEAPF32[a+2*e]=s[e].x,t.HEAPF32[a+2*e+1]=s[e].y;t._physics_addChainShape(n,r,s.length,e.isLoop?1:0,e.friction,e.restitution,e.categoryBits??1,e.maskBits??65535),t._free(r)}}const yu={position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}},xu=4,wu=4*xu;class bu{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(bu.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)}createRevoluteJoint(e,t,n,s,i){const o=i??{};return 0!==this.module_._physics_createRevoluteJoint(e,t,n.x,n.y,s.x,s.y,o.enableMotor?1:0,o.motorSpeed??0,o.maxMotorTorque??0,o.enableLimit?1:0,o.lowerAngle??0,o.upperAngle??0,o.collideConnected?1:0)}destroyJoint(e){this.module_._physics_destroyJoint(e)}setRevoluteMotorSpeed(e,t){this.module_._physics_setRevoluteMotorSpeed(e,t)}setRevoluteMaxMotorTorque(e,t){this.module_._physics_setRevoluteMaxMotorTorque(e,t)}enableRevoluteMotor(e,t){this.module_._physics_enableRevoluteMotor(e,t?1:0)}enableRevoluteLimit(e,t){this.module_._physics_enableRevoluteLimit(e,t?1:0)}setRevoluteLimits(e,t,n){this.module_._physics_setRevoluteLimits(e,t,n)}getRevoluteAngle(e){return this.module_._physics_getRevoluteAngle(e)}getRevoluteMotorTorque(e){return this.module_._physics_getRevoluteMotorTorque(e)}raycast(e,t,n,s=65535,i=100){const o=1/i,r=this.module_._physics_raycast(e.x*o,e.y*o,t.x,t.y,n*o,s);if(0===r)return[];const a=this.module_._physics_getRaycastBuffer()>>2,l=[];for(let e=0;e<r;e++){const t=a+6*e;l.push({entity:this.module_.HEAPU32[t],point:{x:this.module_.HEAPF32[t+1]*i,y:this.module_.HEAPF32[t+2]*i},normal:{x:this.module_.HEAPF32[t+3],y:this.module_.HEAPF32[t+4]},fraction:this.module_.HEAPF32[t+5]})}return l.sort((e,t)=>e.fraction-t.fraction),l}overlapCircle(e,t,n=65535,s=100){const i=1/s,o=this.module_._physics_overlapCircle(e.x*i,e.y*i,t*i,n);if(0===o)return[];const r=this.module_._physics_getOverlapBuffer()>>2,a=[],l=new Set;for(let e=0;e<o;e++){const t=this.module_.HEAPU32[r+e];l.has(t)||(l.add(t),a.push(t))}return a}setAwake(e,t){this.module_._physics_setAwake(e,t?1:0)}isAwake(e){return 0!==this.module_._physics_isAwake(e)}static setDebugDraw(e,t){const n=e.getResource(Kc);n&&(n.enabled=t,e.insertResource(Kc,n))}static setDebugDrawConfig(e,t){const n=e.getResource(Kc);n&&e.insertResource(Kc,{...n,...t})}}const vu={nearest:0,linear:1},Su={repeat:0,clamp:1,mirror:2};function Mu(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=vu[s.filterMode??"linear"]??1,a=Su[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function Pu(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 Tu(e,t,n){const s=e.FS;if(!s)return!1;try{return function(e,t){const n=e.FS;if(!n)return;const s=t.substring(0,t.lastIndexOf("/"));if(!s)return;const i=s.split("/").filter(e=>e);let o="";for(const e of i){o+="/"+e;try{n.mkdir(o)}catch{}}}(e,t),s.writeFile(t,n),!0}catch(e){return console.warn(`[Runtime] Failed to write virtual FS: ${t}`,e),!1}}async function Cu(e){const{app:t,module:n,sceneData:s,provider:i,spineManager:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=gi(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=Mu(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);const h=await async function(e,t,n,s){const i=new Set,o=new Map;for(const r of t.entities)for(const t of r.components){const r=_i(t.type);if(!r||!t.data)continue;const a=t.data[r.skeletonField],l=t.data[r.atlasField];if(!a||!l)continue;const c=`${a}:${l}`;if(i.has(c))continue;i.add(c);const u=n.resolvePath(l);try{const t=await n.readText(l),i=n.resolvePath(a),r="binary"===Ii(i)?.contentType?await n.readBinary(a):await n.readText(a),h=s?"string"==typeof r?Yc.detectVersionJson(r):Yc.detectVersion(r):null,d=Pu(t),f=u.substring(0,u.lastIndexOf("/")),p=e.getResourceManager(),m=new Map;for(const t of d){const s=f+"/"+t;try{const i=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),o=Mu(e,i,!1);p.registerTextureWithPath(o,s),m.set(t,{glId:p.getTextureGLId(o),w:i.width,h:i.height})}catch(e){console.warn(`[Spine] Failed to load texture: ${s}`,e)}}(!h||"4.2"===h)&&(Tu(e,u,t),Tu(e,i,r)),o.set(c,{version:h,skelData:r,atlasText:t,textures:m})}catch(e){console.warn(`[Runtime] Failed to load spine asset: skel=${a} atlas=${l}`,e)}}return o}(n,s,i,o);if(r){const e={gravity:a?.gravity??{...k},fixedTimestep:a?.fixedTimestep??R,subStepCount:a?.subStepCount??4,contactHertz:a?.contactHertz??120,contactDampingRatio:a?.contactDampingRatio??10,contactSpeed:a?.contactSpeed??10};new pu("",e,()=>Promise.resolve(r)).build(t)}const d=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=gi(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=Ii(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Mu(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch(e){console.warn(`[Runtime] Failed to load bitmap font: ${o}`,e),s[o]=0}}return s}(n,s,i),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=gi(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=hn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=hn.createFromAsset(e,r)}catch(e){console.warn(`[Runtime] Failed to load material: ${o}`,e),n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=gi(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=vn(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,Mu(e,s))}catch(e){console.warn(`[Runtime] Failed to load anim texture: ${t}`,e),r.set(t,0)}Pn(Sn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=gi(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=Gn(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=Kn(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=Mu(e,t),Bn(r,t.width,t.height)}catch(e){console.warn(`[Runtime] Failed to load tileset texture: ${s}`,e)}o.push({textureHandle:r,columns:t.columns})}Hn(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=gi(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await Rn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Rn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=gi(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,d,f);const p=bi(t.world,s),m=t.world.getCppRegistry();if(m&&n.transform_update(m),o&&m&&h.size>0)for(const e of s.entities)for(const t of e.components){const n=_i(t.type);if(!n||!t.data)continue;const s=t.data[n.skeletonField],i=t.data[n.atlasField];if(!s||!i)continue;const r=`${s}:${i}`,a=h.get(r);if(!a||!a.version||"4.2"===a.version)continue;const l=p.get(e.id);if(void 0===l)continue;await o.loadEntity(l,a.skelData,a.atlasText,a.textures,m),o.setEntityProps(l,{skeletonScale:t.data.skeletonScale??1,flipX:t.data.flipX??!1,flipY:t.data.flipY??!1,layer:t.data.layer??0});const c=t.data.skin;c&&o.setSkin(l,c);const u=t.data.animation;u&&o.setAnimation(l,u,!1!==t.data.loop)}if(c&&t.hasResource(Fr))for(const e of p.values())t.world.insert(e,Ie,{scene:c,persistent:!1});if(l){const e=t.getResource(Yi);e&&e.setAddressableManifest(l)}}function Eu(e,t,n){return{name:e,async setup(){await Cu({...n,sceneData:t,sceneName:e})}}}async function Au(e){const{app:t,firstScene:n,aspectRatio:s}=e;Lr(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,spineManager:e.spineManager,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(Fr);for(const t of e.scenes)o.register(Eu(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&Pi(t.world,s)}class ku{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=_i(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===Ii(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=gi(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=Ii(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}let Ru=null;const Iu={update(e,t){Ru?.spine_update?.(e._cpp,t)},play:(e,t,n=!0,s=0)=>Ru?.spine_play?.(e,t,n,s)??!1,addAnimation:(e,t,n=!0,s=0,i=0)=>Ru?.spine_addAnimation?.(e,t,n,s,i)??!1,setSkin:(e,t)=>Ru?.spine_setSkin?.(e,t)??!1,getBonePosition:(e,t)=>Ru?.spine_getBonePosition?.(e,t)??null,hasInstance:e=>Ru?.spine_hasInstance?.(e)??!1,reloadAssets(e){Ru?.spine_reloadAssets?.(e._cpp)},getAnimations:e=>Ru?.spine_getAnimations?.(e)??[],getSkins:e=>Ru?.spine_getSkins?.(e)??[]};class Fu{constructor(e){this.app_=null,e instanceof Yc?(this.spineManager_=e,this.provider_=null):(this.spineManager_=null,this.provider_=e??null)}get spineManager(){return this.spineManager_}setSpineManager(e){if(this.spineManager_=e,this.app_){const t=this.app_,n=t.pipeline;n?.addPreFlushCallback(n=>{const s=t.getResource(et).frameCount;e.submitMeshes(n._cpp,s)})}}build(e){this.app_=e;const t=e.wasmModule;if(Ru=t,!this.spineManager_&&this.provider_){const e=function(e){const t=["3.8","4.1","4.2"],n=new Map;for(const s of t)n.set(s,async()=>{const[t,n]=await Promise.all([e.loadJs(s),e.loadWasm(s)]),i=new Blob([`${t};\nself.__ESSpineModule__ = ESSpineModule;`],{type:"application/javascript"}),o=URL.createObjectURL(i);await import(/* @vite-ignore */o),URL.revokeObjectURL(o);const r=globalThis.__ESSpineModule__;return delete globalThis.__ESSpineModule__,r({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Spine] WASM instantiation failed:",e)}),{})})});return n}(this.provider_);this.spineManager_=new Yc(t,e)}const n=this,s={_id:Symbol("SpineUpdateSystem"),_name:"SpineUpdateSystem",_params:[],_fn:()=>{const t=e.world.getCppRegistry();if(!t)return;const s=e.getResource(et);Iu.update({_cpp:t},s.delta),n.spineManager_?.updateAnimations(s.delta)}};if(e.addSystemToSchedule(Wt.PreUpdate,s),this.spineManager_){const t=this.spineManager_,n=e.pipeline;n?.addPreFlushCallback(n=>{const s=e.getResource(et).frameCount;t.submitMeshes(n._cpp,s)})}}}const Bu="__preview__";class Uu{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Fr);t.register({name:Bu,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Bu),this.loadPromise_=t.load(Bu).then(()=>{}).catch(e=>{console.error("[Preview] Failed to load preview scene:",e)}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new ku(this.baseUrl_);await n.prefetch(t);const s=this.app_.getPlugin(Fu),i=s?.spineManager??null;await Cu({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineManager:i,sceneName:Bu})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([we]);for(const s of n){if(e.get(s,we).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([be]);for(const i of s){const s=e.get(i,be);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(Fr).getScene(Bu),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,me,r);const a={isActive:!0,projectionType:he.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:de.ColorAndDepth};e.insert(o,we,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Fr);await e.switchTo(Bu),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const zu={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=br.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:br.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){br.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(br.releaseRenderTarget(e._handle),zu.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){br.begin(t,e._handle)},end(){br.end()},getDepthTexture:e=>br.getTargetDepthTexture(e._handle)};var Hu;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Hu||(Hu={}));class Lu{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Hu[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Hu.Debug:console.debug(t,n);break;case Hu.Info:console.log(t,n);break;case Hu.Warn:console.warn(t,n);break;case Hu.Error:console.error(t,n)}}}class Du{constructor(){this.handlers_=[],this.minLevel_=Hu.Info,this.addHandler(new Lu)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Hu.Debug,e,t,n)}info(e,t,n){this.log(Hu.Info,e,t,n)}warn(e,t,n){this.log(Hu.Warn,e,t,n)}error(e,t,n){this.log(Hu.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const $u=new Du;function Wu(){return $u}function Ou(e){$u.setMinLevel(e)}function Vu(e,t,n){$u.debug(e,t,n)}function Nu(e,t,n){$u.info(e,t,n)}function Xu(e,t,n){$u.warn(e,t,n)}function ju(e,t,n){$u.error(e,t,n)}const Yu={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},qu={Running:0,Paused:1,Completed:2,Cancelled:3},Gu={None:0,Restart:1,PingPong:2};const Ku=1.70158,Ju=2.70158,Zu=2.5949095;const Qu=2*Math.PI/3,eh=2*Math.PI/4.5;const th=7.5625,nh=2.75;const sh=1e-6;function ih(e,t,n){switch(e){case Yu.Linear:return t;case Yu.EaseInQuad:return function(e){return e*e}(t);case Yu.EaseOutQuad:return function(e){return e*(2-e)}(t);case Yu.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Yu.EaseInCubic:return function(e){return e*e*e}(t);case Yu.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Yu.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Yu.EaseInBack:return function(e){return Ju*e*e*e-Ku*e*e}(t);case Yu.EaseOutBack:return function(e){const t=e-1;return 1+Ju*t*t*t+Ku*t*t}(t);case Yu.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Zu)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Zu)+2)/2}(t);case Yu.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Qu)}(t);case Yu.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Qu)+1}(t);case Yu.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*eh)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*eh)/2+1}(t);case Yu.EaseOutBounce:return function(e){return e<1/nh?th*e*e:e<2/nh?th*(e-=1.5/nh)*e+.75:e<2.5/nh?th*(e-=2.25/nh)*e+.9375:th*(e-=2.625/nh)*e+.984375}(t);case Yu.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<sh)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<sh)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case Yu.Step:return function(e){return e<1?0:1}(t);default:return t}}const oh=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??Yu.Linear,bezierPoints:null,state:qu.Running,loop:i?.loop??Gu.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===qu.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==qu.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=ih(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Gu.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Gu.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=qu.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===qu.Running&&(t.state=qu.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===qu.Paused&&(t.state=qu.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=qu.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:qu.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class rh{constructor(e){this.id=e}get state(){return oh.getState(this.id)}bezier(e,t,n,s){return oh.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof rh?oh.setSequenceNext(this.id,e.id):oh.setSequenceNextExternal(this.id,e),this}pause(){oh.pause(this.id)}resume(){oh.resume(this.id)}cancel(){oh.cancel(this.id)}}const ah={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class lh{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof rh?(oh.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let ch=null,uh=null;function hh(e,t){ch=e,uh=t,oh.init(e,t)}function dh(){oh.shutdown(),ch=null,uh=null}function fh(){if(!ch)throw new Error("Tween API not initialized");return ch}function ph(){if(!uh)throw new Error("Tween API not initialized");return uh}const mh={to(e,t,n,s,i,o){const r=fh(),a=ph(),l=o?.easing??Yu.Linear,c=o?.delay??0,u=o?.loop??Gu.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new lh(r,a,d)},value(e,t,n,s,i){const o=oh.create(e,t,n,s,i);return new rh(o)},cancel(e){fh()._anim_cancelTween(ph(),e.entity)},cancelAll(e){fh()._anim_cancelAllTweens(ph(),e)},update(e){fh()._anim_updateTweens(ph(),e),oh.update(e)}};class gh{constructor(){this.name="AnimationPlugin"}build(e){hh(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(Wt.Update,Nt([Ke(et)],e=>{Ps()&&!Es()||mh.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(Wt.Update,Nt([Ke(et)],e=>{Ps()&&!Es()||kn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){dh()}}const _h=new gh;let yh=null,xh=null;function wh(e,t){yh=e,xh=t}function bh(){yh=null,xh=null}const vh={update(e){yh&&xh&&yh.particle_update?.(xh,e)},play(e){yh&&xh&&yh.particle_play?.(xh,e)},stop(e){yh&&xh&&yh.particle_stop?.(xh,e)},reset(e){yh&&xh&&yh.particle_reset?.(xh,e)},getAliveCount:e=>yh?yh.particle_getAliveCount?.(e)??0:0};class Sh{constructor(){this.name="ParticlePlugin"}build(e){wh(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(Wt.Update,Nt([Ke(et)],e=>{vh.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){bh()}}const Mh=new Sh,Ph=1073741824,Th={orthogonal:0,isometric:1,staggered:2};class Ch{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.animatedLayers_=new Set,this.sourceEntityKeys_=new Map,this.layerState_=new Map}build(e){Wn(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.animatedLayers_,i=this.sourceEntityKeys_,o=this.layerState_,r={_id:Symbol("TilemapSyncSystem"),_name:"TilemapSyncSystem",_params:[],_fn:()=>{const r=t.getEntitiesWithComponents([Xn,me]),a=new Set(r);for(const e of n)e>=Ph||a.has(e)||(Vn.destroyLayer(e),n.delete(e),o.delete(e));for(const e of r){const s=t.tryGet(e,Xn);if(!s)continue;const i=s.texture;if(!i)continue;const r=Un(i);if(!r)continue;if(!n.has(e)){if(Vn.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),Vn.setOriginEntity(e,e),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];Vn.setTiles(e,t)}n.add(e)}const a=s.tileWidth/r.width,l=s.tileHeight/r.height,c=s.tint,u=s.parallaxFactor,h=o.get(e);(!h||h.texture!==i||h.tilesetColumns!==s.tilesetColumns||h.layer!==s.layer||h.parallaxX!==u.x||h.parallaxY!==u.y||h.tintR!==c.r||h.tintG!==c.g||h.tintB!==c.b||h.tintA!==c.a||h.opacity!==s.opacity||h.visible!==s.visible)&&(Vn.setRenderProps(e,i,s.tilesetColumns,a,l,s.layer,0,u.x,u.y),Vn.setTint(e,c.r,c.g,c.b,c.a,s.opacity),Vn.setVisible(e,s.visible),o.set(e,{texture:i,tilesetColumns:s.tilesetColumns,layer:s.layer,tintR:c.r,tintG:c.g,tintB:c.b,tintA:c.a,opacity:s.opacity,parallaxX:u.x,parallaxY:u.y,visible:s.visible}))}const l=t.getEntitiesWithComponents([Nn,me]);for(const e of l){if(t.tryGet(e,Xn))continue;const o=t.tryGet(e,Nn);if(!o?.source)continue;const r=Ln(o.source);if(r&&!i.has(e)){const t=[],o=Th[r.orientation??"orthogonal"]??0;for(let i=0;i<r.layers.length;i++){const a=Ph+256*e+i,l=r.layers[i];if(Vn.initLayer(a,l.width,l.height,r.tileWidth,r.tileHeight),Vn.setOriginEntity(a,e),l.tiles.length>0&&Vn.setTiles(a,l.tiles),0!==o&&Vn.setGridType(a,o),r.tileAnimations){for(const[e,t]of r.tileAnimations)Vn.setTileAnimation(a,e,t);r.tileAnimations.size>0&&s.add(a)}if(r.tileProperties)for(const[e,t]of r.tileProperties)for(const[n,s]of t)Vn.setTileProperty(a,e,n,s);const c=r.tilesets[0];if(c){const e=Un(c.textureHandle);e&&(Vn.setRenderProps(a,c.textureHandle,c.columns,r.tileWidth/e.width,r.tileHeight/e.height,i,0,1,1),Vn.setTint(a,1,1,1,1,1),Vn.setVisible(a,!0))}t.push(a),n.add(a)}i.set(e,t)}}const c=new Set(l);for(const[e,t]of i)if(!c.has(e)){for(const e of t)Vn.destroyLayer(e),n.delete(e),s.delete(e),o.delete(e);i.delete(e)}if(s.size>0){const t=1e3*e.getResource(et).delta;for(const e of s)Vn.advanceAnimations(e,t)}}};e.addSystemToSchedule(Wt.PreUpdate,r)}cleanup(){for(const e of this.initializedLayers_)Vn.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),this.layerState_.clear(),zn(),On()}}const Eh=new Ch;function Ah(e,t){return e.toFixed(t)}function kh(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Rh{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.lastUpdateTime_=0,this.lastStats_=null,this.accumulatedTimings_=new Map,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 220px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;this.lastStats_=e,this.accumulateTimings_(e.systemTimings);const t=performance.now();this.lastUpdateTime_>0&&t-this.lastUpdateTime_<500||(this.lastUpdateTime_=t,this.render_())}show(){this.visible_=!0,this.lastUpdateTime_=0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}accumulateTimings_(e){for(const[t,n]of e){const e=this.accumulatedTimings_.get(t);e?(e.sum+=n,e.count++,n>e.max&&(e.max=n)):this.accumulatedTimings_.set(t,{sum:n,max:n,count:1})}}render_(){const e=this.lastStats_;if(!e)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Ah(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ah(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),this.accumulatedTimings_.size>0){const e=[];for(const[t,n]of this.accumulatedTimings_){const s=n.sum/n.count;e.push([t,s,n.max])}e.sort((e,t)=>t[2]-e[2]);const n=e.slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t,i]of n){s+=`<div>${kh(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ah(t,1)} / ${Ah(i,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join(""),this.accumulatedTimings_.clear()}}function Ih(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Fh=Ge(Ih(),"Stats");class Bh{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const Uh="StatsCollect";class zh{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Hh{constructor(e){this.name="Stats",this.collector_=new zh,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Fh,Ih());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Rh(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=Nt([Ke(et),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Fh);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Uh),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=br.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:Uh});e.addSystemToSchedule(Wt.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Lh=new Hh;class Dh{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return $h(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}function $h(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}function Wh(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function Oh(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await async function(e,t){try{const n=Wh(t),s={instantiateWasm(e,t){const s=new Response(n.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,e).then(e=>t(e.instance,e.module),()=>{WebAssembly.instantiate(n.buffer,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Playable] WASM instantiation fallback failed:",e)})}),{}}};return await e(s)}catch(e){return console.error("[Playable] WASM module init failed:",e),null}}(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}async function Vh(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(Yi);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));let a=null;if(e.spineModules&&Object.keys(e.spineModules).length>0){a=function(e,t){const n=new Map;for(const[e,s]of Object.entries(t)){const t=e;n.set(t,async()=>{const e=Wh(s.wasmBase64);return s.factory({instantiateWasm(t,n){const s=new Response(e.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,t).then(e=>n(e.instance,e.module),()=>{WebAssembly.instantiate(e.buffer,t).then(e=>n(e.instance,e.module)).catch(e=>{console.error("[Playable] Spine WASM instantiation fallback failed:",e)})}),{}}})})}return new Yc(e,n)}(n,e.spineModules);const s=t.getPlugin(Fu);s&&s.setSpineManager(a)}const l=e.physicsWasmBase64?await Oh(e.physicsWasmBase64):null,c=new Dh(s);Rn.setAssetResolver(e=>{const t=s[e];return t?$h(t).buffer:null}),await Au({app:t,module:n,provider:c,scenes:i,firstScene:o,spineManager:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Nh=[ja,Ka,ul,Ml,Bl,pl,Dl,Nl,Kl,kl,wl,Zl,nc,ac,uc,fc,Mc],Xh=[_h,ni,Mh,Eh,dr,di];function jh(e,t){const n=new Fu(t?.spineProvider),s=[...Nh,...Xh,n,...t?.plugins??[]];return function(e,t){const n=Hr.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),go(e),ln(e),Fo(e),Xo(e),xr(e),Sr(e);const i=new Tr;n.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=Vr(e,s,t,i));const r=n.getResource(en);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(en,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;br.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(br.resize(t,l),n.hasResource(Fr)){const e=n.getResource(Fr).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Vr(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Dr,width:t,height:l,elapsed:u});else{i.beginFrame(),i.beginScreenCapture();for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),br.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Wt.First,l),n.addSystemToSchedule(Wt.Last,c),n.addPlugin(Gi),n.addPlugin(co),n.addPlugin(Qt),n.addPlugin(zr),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{...t,plugins:s})}e=x;export{bt as Added,gh as AnimationPlugin,Hr as App,qi as AssetPlugin,Ki as AssetRefCounter,ji as AssetServer,Yi as Assets,wn as AsyncCache,Gs as AttenuationModel,Rn as Audio,p as AudioBus,ei as AudioListener,m as AudioMixer,ti as AudioPlugin,g as AudioPool,Qs as AudioSource,Pe as BitmapText,tn as BlendMode,Ye as BodyType,ze as BoxCollider,ol as Button,il as ButtonState,we as Camera,be as Canvas,Le as CapsuleCollider,We as ChainCollider,vt as Changed,Me as Children,He as CircleCollider,de as ClearFlags,Rt as Commands,Ft as CommandsInstance,Pc as DARK_THEME,b as DEFAULT_DESIGN_HEIGHT,w as DEFAULT_DESIGN_WIDTH,A as DEFAULT_FALLBACK_DT,R as DEFAULT_FIXED_TIMESTEP,P as DEFAULT_FONT_FAMILY,T as DEFAULT_FONT_SIZE,k as DEFAULT_GRAVITY,C as DEFAULT_LINE_HEIGHT,E as DEFAULT_MAX_DELTA_TIME,v as DEFAULT_PIXELS_PER_UNIT,I as DEFAULT_SPINE_SKIN,M as DEFAULT_SPRITE_SIZE,S as DEFAULT_TEXT_CANVAS_SIZE,Eo as DataType,Ll as DragPlugin,zl as DragState,Ul as Draggable,wo as Draw,lc as Dropdown,cc as DropdownPlugin,Yu as EasingType,Ce as EmitterShape,It as EntityCommands,Ia as EntityStateMap,Lt as EventReader,$t as EventReaderInstance,zt as EventRegistry,Ht as EventWriter,Dt as EventWriterInstance,Zr as FillDirection,ea as FillMethod,ta as FillOrigin,fr as FlushReason,yl as FocusManager,_l as FocusManagerState,Jl as FocusPlugin,gl as Focusable,Bh as FrameHistory,Pr as GLDebug,zo as Geometry,Ot as GetWorld,H as INVALID_ENTITY,D as INVALID_FONT,$ as INVALID_MATERIAL,L as INVALID_TEXTURE,na as Image,Sl as ImagePlugin,Qr as ImageType,Jt as Input,Zt as InputPlugin,Kt as InputState,ia as Interactable,dc as LayoutGroupPlugin,sc as ListView,rc as ListViewPlugin,ge as LocalTransform,Hu as LogLevel,Du as Logger,Gu as LoopMode,hn as Material,bn as MaterialLoader,xt as Mut,Re as Name,Se as Parent,vh as Particle,Ae as ParticleEasing,ke as ParticleEmitter,Sh as ParticlePlugin,bu as Physics,hu as PhysicsEvents,pu as PhysicsPlugin,$e as PolygonCollider,qo as PostProcess,hr as PostProcessPlugin,Oo as PostProcessStack,Fe as PostProcessVolume,ro as PrefabServer,ao as Prefabs,lo as PrefabsPlugin,Uu as PreviewPlugin,Il as ProgressBar,Rl as ProgressBarDirection,Fl as ProgressBarPlugin,he as ProjectionType,Ct as Query,Et as QueryInstance,At as Removed,kt as RemovedQueryInstance,Tr as RenderPipeline,mr as RenderStage,zu as RenderTexture,pr as RenderType,br as Renderer,Ke as Res,Je as ResMut,Oe as RevoluteJoint,Ue as RigidBody,F as RuntimeConfig,Ql as SafeArea,tc as SafeAreaPlugin,fe as ScaleMode,Fr as SceneManager,Ir as SceneManagerState,Ie as SceneOwner,Wt as Schedule,$l as ScrollView,Vl as ScrollViewPlugin,De as SegmentCollider,xn as ShaderSources,xe as ShapeRenderer,pe as ShapeType,Ee as SimulationSpace,jl as Slider,Xl as SliderDirection,Gl as SliderPlugin,Te as SpineAnimation,ye as Sprite,An as SpriteAnimator,Fh as Stats,zh as StatsCollector,Rh as StatsOverlay,Hh as StatsPlugin,nt as Storage,gr as SubmitSkipFlags,Gt as SystemRunner,Wa as Text,La as TextAlign,ml as TextInput,xl as TextInputPlugin,$a as TextOverflow,Xa as TextPlugin,Oa as TextRenderer,Da as TextVerticalAlign,Nn as Tilemap,Vn as TilemapAPI,Xn as TilemapLayer,Ch as TilemapPlugin,et as Time,hi as TimelinePlugin,Pl as Toggle,Al as TogglePlugin,me as Transform,mh as Tween,lh as TweenHandle,qu as TweenState,ah as TweenTarget,Vc as UI,en as UICameraInfo,rl as UIEventQueue,al as UIEvents,sl as UIInteraction,fl as UIInteractionPlugin,ll as UILayoutGeneration,cl as UILayoutPlugin,qa as UIMask,Ga as UIMaskPlugin,sa as UIRect,Sc as UIRenderOrderPlugin,Er as UIRenderer,Tc as UIThemeRes,Cr as UIVisualType,ve as Velocity,ku as WebAssetProvider,yt as World,_e as WorldTransform,Yt as addStartupSystem,jt as addSystem,qt as addSystemToSchedule,_h as animationPlugin,z as applyBuildRuntimeConfig,ha as applyDirectionalFill,to as applyOverrides,B as applyRuntimeConfig,Gi as assetPlugin,ni as audioPlugin,Js as calculateAttenuation,Zs as calculatePanning,ir as cleanupAllPostProcessVolumes,sr as cleanupPostProcessVolume,En as clearAnimClips,Co as clearDrawCallbacks,zn as clearTextureDimensionsCache,Dn as clearTilemapSourceCache,qs as clearTimelineHandles,ne as clearUserComponents,Qi as cloneComponentData,Zi as cloneComponents,so as collectNestedPrefabPaths,N as color,ka as colorScale,Ra as colorWithAlpha,la as computeFillAnchors,ua as computeFillSize,ca as computeHandleAnchors,oa as computeUIRectLayout,Eu as createRuntimeSceneConfig,jh as createWebApp,Vu as debug,Ih as defaultFrameStats,Q as defineComponent,Bt as defineEvent,Ge as defineResource,Nt as defineSystem,ee as defineTag,Dl as dragPlugin,uc as dropdownPlugin,ju as error,vn as extractAnimClipTexturePaths,Ti as findEntityByName,no as flattenPrefab,Lr as flushPendingSystems,Zl as focusPlugin,Bi as getAddressableType,Ui as getAddressableTypeByEditorType,Hi as getAllAssetExtensions,Qo as getAllEffectDefs,Cn as getAnimClip,Xi as getAssetBuildTransform,Wi as getAssetMimeType,Ii as getAssetTypeEntry,le as getComponent,gi as getComponentAssetFieldDescriptors,mi as getComponentAssetFields,Be as getComponentDefaults,q as getComponentEntityFields,_i as getComponentSpineFieldDescriptor,Di as getCustomExtensions,Fi as getEditorType,Jo as getEffectDef,Zo as getEffectTypes,Wu as getLogger,t as getPlatform,s as getPlatformType,Un as getTextureDimensions,Ln as getTilemapSource,Ys as getTimelineHandle,te as getUserComponent,$i as getWeChatPackOptions,Ml as imagePlugin,Nu as info,go as initDrawAPI,Sr as initGLDebugAPI,Fo as initGeometryAPI,ln as initMaterialAPI,wh as initParticleAPI,Vh as initPlayableRuntime,Xo as initPostProcessAPI,xr as initRendererAPI,Au as initRuntime,Wn as initTilemapAPI,hh as initTweenAPI,Ec as initUIBuilder,Qt as inputPlugin,oo as instantiatePrefab,Ja as intersectRects,Za as invertMatrix4,oe as isBuiltinComponent,Oi as isCustomExtension,Ps as isEditor,zi as isKnownAssetExtension,n as isPlatformInitialized,Es as isPlayMode,Ts as isRuntime,nn as isTextureRef,i as isWeChat,o as isWeb,fc as layoutGroupPlugin,ac as listViewPlugin,Mi as loadComponent,Gc as loadPhysicsModule,Cu as loadRuntimeScene,bi as loadSceneData,vi as loadSceneWithAssets,es as loadTiledMap,Li as looksLikeAssetPath,Pa as makeInteractable,Sn as parseAnimClipData,Jn as parseTiledMap,bs as parseTimelineAsset,Gn as parseTmjJson,Mh as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,nl as pointInOBB,el as pointInWorldRect,dr as postProcessPlugin,co as prefabsPlugin,io as preloadNestedPrefabs,Bl as progressBarPlugin,X as quat,Pn as registerAnimClip,Ni as registerAssetBuildTransform,ae as registerComponent,pi as registerComponentAssetFields,Y as registerComponentEntityFields,Po as registerDrawCallback,Ji as registerEmbeddedAssets,yn as registerMaterialCallback,Bn as registerTextureDimensions,Hn as registerTilemapSource,oi as registerTimelineAsset,eo as remapComponentEntityRefs,yi as remapEntityFields,Kn as resolveRelativePath,nc as safeAreaPlugin,zr as sceneManagerPlugin,Qa as screenToWorld,Nl as scrollViewPlugin,Ms as setEditorMode,Ea as setEntityColor,Aa as setEntityEnabled,oc as setListViewRenderer,Ou as setLogLevel,Cs as setPlayMode,at as setWasmErrorHandler,_o as shutdownDrawAPI,Mr as shutdownGLDebugAPI,Bo as shutdownGeometryAPI,cn as shutdownMaterialAPI,bh as shutdownParticleAPI,jo as shutdownPostProcessAPI,wr as shutdownRendererAPI,On as shutdownTilemapAPI,dh as shutdownTweenAPI,Kl as sliderPlugin,kn as spriteAnimatorSystemUpdate,Lh as statsPlugin,Sa as syncFillSpriteSize,nr as syncPostProcessVolume,wl as textInputPlugin,ja as textPlugin,Eh as tilemapPlugin,di as timelinePlugin,Vi as toBuildPath,kl as togglePlugin,Nc as transitionTo,pl as uiInteractionPlugin,ul as uiLayoutPlugin,Ka as uiMaskPlugin,Nh as uiPlugins,Mc as uiRenderOrderPlugin,Tn as unregisterAnimClip,se as unregisterComponent,To as unregisterDrawCallback,Pi as updateCameraAspectRatio,W as vec2,O as vec3,V as vec4,Xu as warn,Ta as withChildEntity,Br as wrapSceneSystem};//# sourceMappingURL=index.bundled.js.mapdiff --git a/desktop/public/sdk/esm/esengine.bundled.js.map b/desktop/public/sdk/esm/esengine.bundled.js.mapindex c49d40e99..585a30f46 100644--- a/desktop/public/sdk/esm/esengine.bundled.js.map+++ b/desktop/public/sdk/esm/esengine.bundled.js.map@@ -1 +1 @@-{"version":3,"file":"index.bundled.js","sources":["../src/platform/base.ts","../src/audio/AudioBus.ts","../src/audio/AudioMixer.ts","../src/audio/AudioPool.ts","../src/audio/WebAudioBackend.ts","../src/platform/web.ts","../src/defaults.ts","../src/types.ts","../src/componentEntityFields.ts","../src/component.ts","../src/physics/PhysicsComponents.ts","../src/resource.ts","../src/storage.ts","../src/validation.ts","../src/wasmError.ts","../src/world.ts","../src/query.ts","../src/commands.ts","../src/event.ts","../src/system.ts","../src/input.ts","../src/ui/UICameraInfo.ts","../src/blend.ts","../src/material.ts","../src/asset/AsyncCache.ts","../src/asset/MaterialLoader.ts","../src/animation/AnimClipLoader.ts","../src/animation/SpriteAnimator.ts","../src/audio/Audio.ts","../src/tilemap/tilesetCache.ts","../src/tilemap/tilemapAPI.ts","../src/tilemap/components.ts","../src/tilemap/tiledLoader.ts","../src/tilemap/collisionMerge.ts","../src/timeline/TimelineTypes.ts","../src/timeline/TimelineLoader.ts","../src/env.ts","../src/timeline/TimelineUploader.ts","../src/timeline/TimelineControl.ts","../src/audio/SpatialAudio.ts","../src/audio/AudioComponents.ts","../src/audio/AudioPlugin.ts","../src/timeline/TimelinePlugin.ts","../src/scene.ts","../src/assetTypes.ts","../src/asset/AssetServer.ts","../src/asset/AssetPlugin.ts","../src/asset/AssetRefCounter.ts","../src/asset/index.ts","../src/prefab/clone.ts","../src/prefab/entityRef.ts","../src/prefab/override.ts","../src/prefab/flatten.ts","../src/prefab/collect.ts","../src/prefab.ts","../src/prefabServer.ts","../src/draw.ts","../src/customDraw.ts","../src/geometry.ts","../src/postprocess/PostProcessStack.ts","../src/postprocess/shaders.ts","../src/postprocess/PostProcessAPI.ts","../src/postprocess/effects.ts","../src/postprocess/sync.ts","../src/postprocess/volumeSystem.ts","../src/postprocess/volumeBlending.ts","../src/postprocess/PostProcessPlugin.ts","../src/frameCapture.ts","../src/renderer.ts","../src/glDebug.ts","../src/renderPipeline.ts","../src/ui/UIRenderer.ts","../src/sceneManager.ts","../src/scenePlugin.ts","../src/app.ts","../src/ui/uiTypes.ts","../src/ui/Image.ts","../src/ui/UIRect.ts","../src/ui/Interactable.ts","../src/ui/uiHelpers.ts","../src/ui/uiSnapshot.ts","../src/ui/uiConstants.ts","../src/ui/text.ts","../src/ui/TextRenderer.ts","../src/ui/TextPlugin.ts","../src/ui/UIMask.ts","../src/ui/UIMaskPlugin.ts","../src/ui/uiMath.ts","../src/ui/UIInteraction.ts","../src/ui/Button.ts","../src/ui/UIEvents.ts","../src/ui/UILayoutGeneration.ts","../src/ui/UILayoutPlugin.ts","../src/ui/UIInteractionPlugin.ts","../src/ui/TextInput.ts","../src/ui/Focusable.ts","../src/ui/TextInputPlugin.ts","../src/ui/ImagePlugin.ts","../src/ui/Toggle.ts","../src/ui/ToggleGroup.ts","../src/ui/TogglePlugin.ts","../src/ui/ProgressBar.ts","../src/ui/ProgressBarPlugin.ts","../src/ui/Draggable.ts","../src/ui/DragPlugin.ts","../src/ui/ScrollView.ts","../src/ui/ScrollViewPlugin.ts","../src/ui/Slider.ts","../src/ui/SliderPlugin.ts","../src/ui/FocusPlugin.ts","../src/ui/SafeArea.ts","../src/ui/SafeAreaPlugin.ts","../src/ui/ListView.ts","../src/ui/ListViewPlugin.ts","../src/ui/Dropdown.ts","../src/ui/DropdownPlugin.ts","../src/ui/LayoutGroup.ts","../src/ui/LayoutGroupPlugin.ts","../src/ui/FlexContainer.ts","../src/ui/FlexItem.ts","../src/ui/UIRenderOrderPlugin.ts","../src/ui/UITheme.ts","../src/ui/UIBuilder.ts","../src/sceneTransition.ts","../src/spine/SpineController.ts","../src/spine/ModuleBackend.ts","../src/spine/SpineManager.ts","../src/spine/SpineModuleLoader.ts","../src/physics/PhysicsModuleLoader.ts","../src/physics/PhysicsDebugDraw.ts","../src/physics/PhysicsPlugin.ts","../src/runtimeLoader.ts","../src/preview/WebAssetProvider.ts","../src/spine/SpineCppAPI.ts","../src/spine/SpinePlugin.ts","../src/preview/PreviewPlugin.ts","../src/renderTexture.ts","../src/logger.ts","../src/animation/ValueTween.ts","../src/animation/Tween.ts","../src/animation/AnimationPlugin.ts","../src/particle/ParticleAPI.ts","../src/particle/ParticlePlugin.ts","../src/tilemap/tilemapPlugin.ts","../src/stats-overlay.ts","../src/stats.ts","../src/playableRuntime.ts","../src/uiPlugins.ts","../src/webAppFactory.ts","../src/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["currentPlatform","getPlatform","Error","isPlatformInitialized","getPlatformType","name","isWeChat","isWeb","async","platformFetch","url","options","fetch","platformReadFile","path","readFile","platformReadTextFile","readTextFile","platformFileExists","fileExists","platformInstantiateWasm","pathOrBuffer","imports","instantiateWasm","platformCreateCanvas","width","height","createCanvas","platformNow","now","platformDevicePixelRatio","g","globalThis","wx","getSystemInfoSync","pixelRatio","window","devicePixelRatio","AudioBus","constructor","context","config","this","muted_","volume_","children_","name_","gainNode_","createGain","Math","max","min","volume","muted","gain","value","node","v","setTargetAtTime","currentTime","m","connect","destination","addChild","child","push","AudioMixer","buses_","Map","context_","master","masterVolume","music","musicVolume","sfx","sfxVolume","ui","uiVolume","voice","voiceVolume","set","getBus","get","createBus","bus","parent","AudioPool","initialSize","pool_","activeCount_","i","createNode","panner","createStereoPanner","source","inUse","startTime","acquire","freeNode","find","n","pan","release","stop","_","disconnect","activeCount","capacity","length","WebAudioHandle","id","buffer","poolNode","pool","startOffset","playing_","stopped_","pausedAt_","source_","buffer_","poolNode_","startOffset_","startedAt_","playbackRate_","playbackRate","loop_","loop","bindOnEnded_","onended","onEnd","pause","elapsed","duration","resume","createBufferSource","start","setVolume","setPan","setLoop","setPlaybackRate","rate","isPlaying","WebAudioBackend","mixer_","buffers_","urlToId_","loadingUrls_","nextBufferId_","nextHandleId_","resumeHandler_","mixer","isReady","state","initialize","AudioContext","mixerConfig","initialPoolSize","document","removeEventListener","addEventListener","ensureResumed","loadBuffer","existingId","undefined","has","inFlight","promise","doLoadBuffer_","delete","loadBufferFromData","data","audioBuffer","decodeAudioData","err","message","arrayBuffer","unloadBuffer","handle","play","busName","handleId","suspend","dispose","clear","close","webAdapter","inputCleanup_","response","method","headers","body","forEach","key","ok","status","statusText","json","text","loadImagePixels","img","createImage","Promise","resolve","reject","crossOrigin","onload","onerror","src","ctx","getContext","drawImage","getImageData","pixels","Uint8Array","result","WebAssembly","instantiate","instance","module","Image","canvas","OffscreenCanvas","createElement","performance","bindInputEvents","callbacks","target","el","querySelector","onKeyDown","e","code","onKeyUp","onMouseMove","me","onPointerMove","offsetX","offsetY","onMouseDown","onPointerDown","button","onMouseUp","onPointerUp","onTouchStart","preventDefault","touch","touches","rect","getBoundingClientRect","clientX","left","clientY","top","onTouchMove","onTouchEnd","onTouchCancel","onWheel","we","dx","deltaX","dy","deltaY","deltaMode","innerWidth","innerHeight","passive","unbindInputEvents","createAudioBackend","getStorageItem","localStorage","getItem","setStorageItem","setItem","removeStorageItem","removeItem","clearStorage","prefix","toRemove","k","startsWith","DEFAULT_DESIGN_WIDTH","DEFAULT_DESIGN_HEIGHT","DEFAULT_PIXELS_PER_UNIT","DEFAULT_TEXT_CANVAS_SIZE","DEFAULT_SPRITE_SIZE","x","y","DEFAULT_FONT_FAMILY","DEFAULT_FONT_SIZE","DEFAULT_LINE_HEIGHT","DEFAULT_MAX_DELTA_TIME","DEFAULT_FALLBACK_DT","DEFAULT_GRAVITY","DEFAULT_FIXED_TIMESTEP","DEFAULT_SPINE_SKIN","RuntimeConfig","sceneTransitionDuration","sceneTransitionColor","r","b","a","defaultFontFamily","canvasScaleMode","canvasMatchWidthOrHeight","maxDeltaTime","maxFixedSteps","textCanvasSize","assetLoadTimeout","assetFailureCooldown","applyRuntimeConfig","components","Text","_default","fontFamily","TextInput","Canvas","scaleMode","matchWidthOrHeight","CANVAS_SCALE_MODE_MAP","FixedWidth","FixedHeight","Expand","Shrink","Match","applyBuildRuntimeConfig","app","setMaxDeltaTime","setMaxFixedSteps","hex","replace","parseInt","substring","INVALID_ENTITY","INVALID_TEXTURE","INVALID_FONT","INVALID_MATERIAL","vec2","vec3","z","vec4","w","color","quat","COMPONENT_ENTITY_FIELDS","registerComponentEntityFields","componentType","fields","getComponentEntityFields","deepClone","Array","isArray","map","componentCounter","createComponentDef","defaults","keyInfo","obj","flatKeys","objectKeys","arrayKeys","hasNested","val","classifyKeys","defaultsRec","_id","Symbol","_name","_builtin","create","slice","Object","assign","getComponentRegistry","__esengine_componentRegistry","defineComponent","metadata","existing","componentRegistry","def","registerToEditor","entityFields","defineTag","getUserComponent","clearUserComponents","userRegistry","keys","unregisterComponent","isTag","__esengine_registerComponent","isBuiltinComponent","comp","registerComponent","getComponent","detectColorKeys","defineBuiltin","_cppName","_colorKeys","ProjectionType","Perspective","Orthographic","ClearFlags","None","ColorOnly","DepthOnly","ColorAndDepth","ScaleMode","ShapeType","Circle","Capsule","RoundedRect","Transform","position","rotation","scale","worldPosition","worldRotation","worldScale","LocalTransform","WorldTransform","Sprite","texture","size","pivot","uvOffset","uvScale","layer","flipX","flipY","material","enabled","ShapeRenderer","shapeType","cornerRadius","Camera","projectionType","fov","orthoSize","nearPlane","farPlane","aspectRatio","isActive","priority","showFrustum","viewportX","viewportY","viewportW","viewportH","clearFlags","designResolution","pixelsPerUnit","backgroundColor","Velocity","linear","angular","Parent","entity","Children","entities","BitmapText","fontSize","align","spacing","font","SpineAnimation","skeletonPath","atlasPath","skin","animation","timeScale","playing","skeletonScale","EmitterShape","Point","Rectangle","Cone","SimulationSpace","World","Local","ParticleEasing","Linear","EaseIn","EaseOut","EaseInOut","ParticleEmitter","burstCount","burstInterval","looping","playOnStart","maxParticles","lifetimeMin","lifetimeMax","shape","shapeRadius","shapeSize","shapeAngle","speedMin","speedMax","angleSpreadMin","angleSpreadMax","startSizeMin","startSizeMax","endSizeMin","endSizeMax","sizeEasing","startColor","endColor","colorEasing","rotationMin","rotationMax","angularVelocityMin","angularVelocityMax","gravity","damping","spriteColumns","spriteRows","spriteFPS","spriteLoop","blendMode","simulationSpace","Name","SceneOwner","scene","persistent","PostProcessVolume","effects","isGlobal","weight","blendDistance","getComponentDefaults","typeName","RigidBody","bodyType","gravityScale","linearDamping","angularDamping","fixedRotation","bullet","BoxCollider","halfExtents","offset","radius","density","friction","restitution","isSensor","categoryBits","maskBits","CircleCollider","CapsuleCollider","halfHeight","SegmentCollider","point1","point2","PolygonCollider","vertices","ChainCollider","points","isLoop","RevoluteJoint","connectedEntity","anchorA","anchorB","enableMotor","motorSpeed","maxMotorTorque","enableLimit","lowerAngle","upperAngle","collideConnected","DistanceJoint","enableSpring","hertz","dampingRatio","minLength","maxLength","maxMotorForce","PrismaticJoint","axis","lowerTranslation","upperTranslation","WeldJoint","linearHertz","angularHertz","linearDampingRatio","angularDampingRatio","WheelJoint","BodyType","Static","Kinematic","Dynamic","resourceCounter","defineResource","defaultValue","Res","resource","_type","_resource","ResMut","ResMutInstance","setter","value_","setter_","modify","fn","updateValue","ResourceStorage","resources_","resMutPool_","insert","remove","getResMut","Time","delta","frameCount","KEY_PREFIX","Storage","getString","raw","setString","getNumber","num","Number","isNaN","setNumber","String","getBoolean","setBoolean","getJSON","JSON","parse","console","warn","setJSON","stringify","validateComponentData","componentName","errors","field","entries","expected","actual","expectedType","getType","actualType","formatValidationErrors","lines","join","errorHandler","setWasmErrorHandler","handler","handleWasmError","error","convertFromWasm","colorKeys","convertForWasm","PTR_LAYOUTS","ptrFn","type","UIRect","writePtrField","f32","u32","u8","ptr","byteOff","idx","nextCompNumId_","compNumIds_","WeakMap","getCompNumId","_keyIds","computeQueryCacheKey","withFilters","withoutFilters","c","sort","cppRegistry_","module_","entities_","tsStorage_","entityComponents_","builtinEntitySets_","worldVersion_","queryCache_","builtinMethodCache_","iterationDepth_","nextEntityId_","nextGeneration_","spawnCallbacks_","despawnCallbacks_","worldTick_","componentAddedTicks_","componentChangedTicks_","componentRemovedBuffer_","trackedComponents_","Set","connectCpp","cppRegistry","disconnectCpp","hasCpp","getCppRegistry","getWasmModule","spawn","isIterating","generation","registry_getGeneration","cb","despawn","destroy","ids","tick","onSpawn","callback","indexOf","splice","onDespawn","valid","entityCount","getWorldVersion","beginIteration","endIteration","resetIterationDepth","getAllEntities","from","setParent","removeParent","component","insertBuiltin","insertScript","wasmData","getBuiltinMethods","add","recordChangedTick_","getStorage","getBuiltin","getScript","cppName","bset","hasScript","tryGet","methods","storage","removeBuiltin","removeScript","reg","addFn","getFn","hasFn","removeFn","bind","filtered","merged","isNew","tracked","recordAddedTick_","hasBuiltin","recordRemovedTick_","clean","resolveGetter","ptrGetter","resolvePtrGetter_","resolveHas","resolveSetter","ptrSetter","resolvePtrSetter_","d","resolvePtrFn_","layout","getPtrFn","mod","HEAPF32","HEAPU32","HEAPU8","cached","f","createPreallocatedResult","fillPtrFields","resetQueryPool","getComponentTypes","types","registry","resolveStorages_","comps","scriptOut","builtinOut","getEntitiesWithComponents","precomputedKey","cacheKey","version","reqScript","reqBuiltin","withScript","withBuiltin","woScript","woBuiltin","smallestSet","smallestSize","Infinity","candidates","rsLen","rbLen","match","advanceTick","getWorldTick","enableChangeTracking","isAddedSince","sinceTick","isChangedSince","getRemovedEntitiesSince","entry","cleanRemovedBuffer","beforeTick","writeIdx","markChanged","Mut","_component","isMutWrapper","Added","_filterType","Changed","isAddedWrapper","isChangedWrapper","unwrapComponent","createQueryDescriptor","mutIndices","addedFilters","changedFilters","index","_components","_mutIndices","_with","_without","_addedFilters","_changedFilters","with","extraWith","without","extraWithout","Query","QueryInstance","world","descriptor","lastRunTick","world_","descriptor_","lastRunTick_","actualComponents_","allRequired_","concat","result_","mutData_","cacheKey_","getters_","mutSetters_","mutIsBuiltin_","resetTick","passesChangeFilters_","iterator","actualComponents","compCount","hasMut","hasChangeFilters","mutData","mutCount","mutSetters","getters","self","prevEntity","started","done","mutIsBuiltin","writeMut","mut","finalize","iterResult","doneResult","next","getter","return","apply","single","isEmpty","count","toArray","arr","row","Removed","RemovedQueryInstance","component_","Commands","EntityCommands","commands","components_","commands_","entityRef_","isNew_","queueInsert","queueRemove","spawnImmediate","CommandsInstance","resources","pending_","spawned_","ec","insertResource","entityRef","flush","cmd","executeCommand","defineEvent","EventBus","readBuffer_","writeBuffer_","send","event","getReadBuffer","swap","tmp","EventRegistry","register","swapAll","values","EventWriter","_event","EventReader","EventWriterInstance","bus_","EventReaderInstance","Schedule","GetWorld","systemCounter","defineSystem","params","_params","_fn","getPendingSystems","__esengine_pendingSystems","addSystem","system","schedule","Update","addStartupSystem","Startup","addSystemToSchedule","SystemRunner","eventRegistry","argsCache_","systemTicks_","removedCache_","currentLastRunTick_","timings_","eventRegistry_","setTimingEnabled","getTimings","run","args","queries","removeds","firstRun","qi","ri","param","inst","desc","resolveParam","t0","flushSystem_","then","InputState","keysDown","keysPressed","keysReleased","mouseX","mouseY","mouseButtons","mouseButtonsPressed","mouseButtonsReleased","scrollDeltaX","scrollDeltaY","isKeyDown","isKeyPressed","isKeyReleased","getMousePosition","isMouseButtonDown","isMouseButtonPressed","isMouseButtonReleased","getScrollDelta","Input","InputPlugin","target_","build","Last","inputPlugin","UICameraInfo","viewProjection","Float32Array","vpX","vpY","vpW","vpH","screenW","screenH","worldLeft","worldBottom","worldRight","worldTop","worldMouseX","worldMouseY","BlendMode","isTextureRef","resourceManager","nextMaterialId","materials","initMaterialAPI","wasmModule","getResourceManager","registerMaterialCallback","shutdownMaterialAPI","uniformBuffer","_free","materialCallbackRegistered","encodedNameCache","encoder","Material","createShader","vertexSrc","fragmentSrc","releaseShader","shader","uniforms","Normal","depthTest","dirty_","cachedBuffer_","cachedIdx_","setUniform","invalidateMaterialCache","getUniform","setBlendMode","mode","getBlendMode","setDepthTest","getShader","isValid","releaseAll","clearMaterialCache","createFromAsset","shaderHandle","properties","createInstance","sourceData","toAssetData","shaderPath","getUniforms","tex","textureId","slot","__textureRef","UNIFORM_BUFFER_SIZE","serializeUniforms","bufferPtr","_malloc","heap8","heap32","heapF32","nameBytes","TextEncoder","encode","nameLen","namePadded","ceil","materialDataProvider","materialId","outShaderIdPtr","outBlendModePtr","outUniformBufferPtr","outUniformCountPtr","ShaderSources","SPRITE_VERTEX","SPRITE_FRAGMENT","COLOR_VERTEX","COLOR_FRAGMENT","AsyncCache","cache_","failed_","getOrLoad","loader","timeout","failed","Date","expiry","aborted","loaderPromise","race","setTimeout","clearAll","MaterialLoader","shaderLoader","basePath","shaderLoader_","basePath_","load","loadInternal","loaded","fullPath","resolvePath","content","resolveShaderPath","materialPath","dir","lastIndexOf","extractAnimClipTexturePaths","paths","frame","frames","parseAnimClipData","clipPath","textureHandles","fps","atlasFrame","af","pageWidth","pageHeight","clipRegistry","registerAnimClip","clip","unregisterAnimClip","getAnimClip","clearAnimClips","SpriteAnimator","speed","currentFrame","frameTimer","spriteAnimatorSystemUpdate","deltaTime","animator","frameDuration","needsInitialApply","frameChanged","sprite","Audio","init","backend","backend_","bufferCache_","bgmHandle_","bgmVolume_","disposed_","fadeAnimId_","cancelAnimationFrame","setAssetResolver","resolver","assetResolver_","resolveUrl_","baseUrl","preload","preloadFromData","preloadAll","urls","all","playSFX","playConfig","pitch","pending","createDeferredHandle","buf","catch","playBGM","targetVolume","oldVolume","crossFade","fadeOut","fadeInDuration","fadeIn","stopAll","stopBGM","setMasterVolume","setMusicVolume","setSFXVolume","setUIVolume","muteBus","getBufferHandle","t","requestAnimationFrame","startVolume","real","p","l","texDimsCache_","tilemapCache_","registerTextureDimensions","getTextureDimensions","clearTextureDimensionsCache","registerTilemapSource","getTilemapSource","clearTilemapSourceCache","initTilemapAPI","shutdownTilemapAPI","TilemapAPI","initLayer","tileWidth","tileHeight","tilemap_initLayer","destroyLayer","tilemap_destroyLayer","setTile","tileId","tilemap_setTile","getTile","tilemap_getTile","fillRect","h","tilemap_fillRect","setTiles","tiles","bytes","byteLength","Uint16Array","tilemap_setTiles","hasLayer","tilemap_hasLayer","setRenderProps","textureHandle","tilesetColumns","uvTileW","uvTileH","sortLayer","depth","parallaxX","parallaxY","tilemap_setRenderProps","setTint","opacity","tilemap_setTint","setVisible","visible","tilemap_setVisible","setOriginEntity","layerKey","originEntity","tilemap_setOriginEntity","submitLayer","uvTileWidth","uvTileHeight","originX","originY","camLeft","camBottom","camRight","camTop","tintR","tintG","tintB","tintA","tilemap_submitLayer","setTileAnimation","Uint32Array","tilemap_setTileAnimation","advanceAnimations","dtMs","tilemap_advanceAnimations","setTileProperty","tilemap_setTileProperty","getTileProperty","tilemap_getTileProperty","flipTile","flipH","flipV","flipD","tilemap_flipTile","rotateTile","degrees","tilemap_rotateTile","setGridType","tilemap_setGridType","tileToWorld","tx","ty","tilemap_tileToWorld","floats","worldToTile","wy","tilemap_worldToTile","Tilemap","TilemapLayer","tint","parallaxFactor","parseTintColorU32","parseTintColor","s","convertGid","gid","firstGid","flags","parseTmjJson","tilewidth","tileheight","rawTilesets","tilesets","firstGids","ts","firstgid","image","columns","tileCount","tilecount","rawLayers","layers","lw","lh","rawData","tintColor","tintcolor","parallaxx","parallaxy","objectGroups","collisionTileIds","objs","objects","parsed","props","rawProps","ellipse","point","polygon","polyPts","pt","polyline","linePts","tileAnimations","tileProperties","rawTiles","tile","localId","engineId","rawAnim","tileid","tileProps","propMap","orientation","resolveRelativePath","relativePath","lastSlash","parts","split","resolved","part","pop","parseTiledMap","jsonString","resolveExternal","api","encoded","tiled_loadMap","extCount","tiled_getExternalTilesetCount","tiled_getExternalTilesetSource","tiled_freeMap","tsjContent","tsjEncoded","tsjPtr","tiled_loadExternalTileset","tiled_finalize","tiled_getMapWidth","tiled_getMapHeight","tiled_getMapTileWidth","tiled_getMapTileHeight","layerCount","tiled_getLayerCount","tiled_getLayerWidth","tiled_getLayerHeight","tileBytes","tilePtr","tiled_getLayerTiles","tiled_getLayerName","tiled_getLayerVisible","tiled_getLayerOpacity","tiled_getLayerTintColor","tiled_getLayerParallaxX","tiled_getLayerParallaxY","tilesetCount","tiled_getTilesetCount","tiled_getTilesetName","tiled_getTilesetImage","tiled_getTilesetTileWidth","tiled_getTilesetTileHeight","tiled_getTilesetColumns","tiled_getTilesetTileCount","DEG_TO_RAD","PI","generateTileCollision","mapData","collisionIds","mapWidth","mapHeight","visited","results","isCollision","col","canExpand","nextRow","mergeCollisionTiles","tileW","tileH","mapPixelH","mergedW","mergedH","worldX","worldY","loadTiledMap","firstTileset","layerIndex","generateObjectCollision","collisionEntities","mapOriginX","mapOriginY","group","tiledX","tiledY","angle","minX","minY","maxX","maxY","vx","vy","polyW","polyH","polyCX","polyCY","half","cos","sin","loadTiledCollisionObjects","tileCollisionIds","tileEntities","WrapMode","TrackType","InterpType","MIGRATIONS","track","tracks","ch","channels","kf","keyframes","interpolation","abs","outTangent","WRAP_MODE_MAP","once","pingPong","parseTrack","base","childPath","property","clips","blendIn","events","ranges","markers","time","payload","animFrames","parseTimelineAsset","to","migrateAsset","wrapMode","filter","editorMode","playMode","setEditorMode","active","isEditor","isRuntime","setPlayMode","isPlayMode","AnimTargetField","AnimTargetComponent","FIELD_MAP","PositionX","PositionY","PositionZ","ScaleX","ScaleY","ScaleZ","RotationZ","ColorR","ColorG","ColorB","ColorA","SpriteOpacity","SpriteSizeX","SpriteSizeY","OffsetMinX","OffsetMinY","OffsetMaxX","OffsetMaxY","AnchorMinX","AnchorMinY","AnchorMaxX","AnchorMaxY","PivotX","PivotY","CameraOrthoSize","COMPONENT_MAP","INTERP_TYPE_MAP","InterpType_Hermite","InterpType_Linear","InterpType_Step","InterpType_EaseIn","InterpType_EaseOut","InterpType_EaseInOut","interpTypeToNum","interp","resolveField","CustomField","allocString","str","freePtr","uploadTimelineToWasm","asset","_tl_create","totalPropertyChannels","trackInfos","uploadPropertyTrack","channelProperties","uploadSpineTrack","uploadAudioTrack","uploadActivationTrack","uploadSpriteAnimTrack","channelCount","Custom","childPtr","childLen","compPtr","compLen","pathStrings","totalPathBytes","fieldPathsPtr","pathOffset","fieldPathLensPtr","Int32Array","totalKeyframes","counts","countsPtr","dataPtr","dataArr","dOffset","inTangent","_tl_addCustomPropertyTrack","uploadCustomPropertyTrack","fieldsPtr","fieldsArr","_tl_addPropertyTrack","clipCount","floatsPtr","animPtrsPtr","animPtrs","animLensPtr","animLens","animStrPtrs","aPtr","aLen","_tl_addSpineTrack","eventCount","clipPtrsPtr","clipPtrs","clipLensPtr","clipLens","strPtrs","evt","cPtr","cLen","_tl_addAudioTrack","rangesPtr","rangesArr","end","_tl_addActivationTrack","clipPtr","clipLen","_tl_addSpriteAnimTrack","handles_","setTimelineHandle","getTimelineHandle","clearTimelineHandles","_tl_destroy","AttenuationModel","DEFAULT_SPATIAL_CONFIG","model","Inverse","refDistance","maxDistance","rolloff","calculateAttenuation","distance","range","Exponential","pow","calculatePanning","sourceX","sourceY","listenerX","listenerY","AudioSource","playOnAwake","spatial","minDistance","attenuationModel","AudioListener","AudioPlugin","activeSourceHandles_","playedEntities_","config_","activeSourceHandles","playedEntities","liveEntities","spatialListenerWarned","wasPlayMode","PreUpdate","_time","hasListener","listeners","wt","sources","srcX","srcY","attenuation","sqrt","entityId","stopAllSources","cleanup","audioPlugin","TimelinePlayer","timeline","loadedAssets_","registerTimelineAsset","textureHandles_","getTimelineTextureHandle","timelinePath","textureUuid","setNestedProperty","lastKey","resolveChildEntity","rootEntity","current","segments","segment","childrenData","childEntities","found","childId","nameData","TimelinePlugin","animFramesStates_","uiRect_clearAnimOverrides","playerData","uploadResult","resolveTrackTargets","afTracks","lastFrameIndices","_tl_isPlaying","_tl_getTime","_tl_play","_tl_setTime","_tl_pause","wrapModeNum","_tl_setWrapMode","_tl_advance","processEvents","processCustomProperties","processAnimFrames","_tl_clearResults","clearHandles","DEFAULT_DURATION","frameIndex","dur","propertyIndex","eventIndex","isEvent","_tl_setTrackTarget","decodeEventString","_tl_getEventString","len","_tl_getEventStringLen","TextDecoder","decode","_tl_getEventCount","_tl_getEventType","_tl_getEventEntity","animName","_tl_getEventIntParam","clipName","_tl_getEventFloatParam","_tl_getCustomPropertyCount","_tl_getCustomPropertyEntity","trackIndex","_tl_getCustomPropertyTrackIndex","channelIndex","_tl_getCustomPropertyChannelIndex","_tl_getCustomPropertyValue","trackInfo","componentDef","propPath","timelinePlugin","COMPONENT_ASSET_FIELDS","spine","skeletonField","atlasField","registerComponentAssetFields","getComponentAssetFields","getComponentAssetFieldDescriptors","getComponentSpineFieldDescriptor","remapEntityFields","compData","entityMap","editorId","runtimeId","migrateToUIRenderer","entityData","hasUIRect","some","spriteIdx","findIndex","hasUIRenderer","visualType","sliceBorder","spawnAndLoadEntities","sceneData","loadComponent","parentEntity","loadSceneData","loadSceneWithAssets","assetServer","assetBaseUrl","texturePathToUrl","collectAssets","assetPaths","ASSET_FIELD_HANDLERS","spines","spineKeys","skelPath","skeleton","atlas","assetHandles","loadPromises","handles","spinePromises","loadSpine","success","textureUrls","materialHandles","fontPaths","preloadSceneAssets","textureMetadata","texturePath","setTextureMetadataByPath","promises","info","loadTexture","loadMaterial","fontPath","loadBitmapFont","loadJson","texturePaths","texPromises","texPath","_assetServer","tmjPath","imagePath","tlPath","audio","animClips","textures","extractTimelineAssetPaths","registerTimelineTextureHandles","entityName","rectData","anchor","anchorMin","anchorMax","maskData","updateCameraAspectRatio","cameraEntities","camera","findEntityByName","ASSET_TYPE_REGISTRY","extensions","contentType","editorType","addressableType","wechatPackInclude","hasTransitiveDeps","MIME_MAP","png","jpg","jpeg","gif","webp","svg","bmp","mp3","wav","ogg","aac","flac","webm","skel","esmaterial","esshader","esprefab","esanim","estimeline","bmfont","fnt","extToEntry","allExtensions","ext","extractExtension","extensionOrPath","dotIndex","toLowerCase","getAssetTypeEntry","getEditorType","getAddressableType","getAddressableTypeByEditorType","isKnownAssetExtension","getAllAssetExtensions","looksLikeAssetPath","includes","getCustomExtensions","getWeChatPackOptions","getAssetMimeType","isCustomExtension","toBuildPath","registerAssetBuildTransform","transform","buildTransform","getAssetBuildTransform","AssetServer","textureCache_","shaderCache_","jsonCache_","textCache_","binaryCache_","loadedSpines_","virtualFSPaths_","fontCache_","prefabCache_","embedded_","embeddedOnly_","addressableManifest_","addressIndex_","labelIndex_","groupAssets_","spineController_","spineSkeletons_","textureRefCounts_","assetRefResolver_","canvas_","ctx_","willReadFrequently","loadShader","materialLoader_","registerEmbeddedAssets","assets","location","protocol","setEmbeddedOnly","loadTextureWithFlip","loadTextureRaw","getTexture","textureCacheKey","hasTexture","getTextureRefCount","total","flip","releaseTexture","rm","refCount","releaseBitmapFont","unloadSkeleton","cleanupVirtualFS","fs","FS","unlink","setTextureMetadata","border","right","bottom","setSpineController","controller","getSpineSkeletonHandle","atlasUrl","resolveUrl","atlasContent","fetchText","writeToVirtualFS","atlasDir","textureNames","parseAtlasTextures","loadedTextures","texName","texUrl","registerTextureWithPath","skelUrl","isBinary","skelData","fetchBinary","skelHandle","loadSkeleton","pageCount","getAtlasPageCount","pageName","getAtlasPageTextureName","glId","getTextureGLId","setAtlasPageTexture","isSpineLoaded","releaseSpine","fontEntry","loadBmfontAsset","loadFntFile","getFont","releaseFont","fetchJson","fntFile","generatedFnt","fntUrl","fntContent","pageMatch","fntDir","texInfo","setAssetRefResolver","loadPrefab","resolvePrefabRefs_","prefab","nestedPrefab","prefabPath","getMaterial","hasMaterial","loadShaderInternal","noCache","loadText","loadBinary","loadScene","loadAll","manifest","setAddressableManifest","allAssets","groups","loadAddressableAssets","groupName","groupList","address","label","labels","list","resolveAddress","loadAddressableAsset","loadByLabel","loadGroup","bundle","fonts","prefabs","binary","mat","allSettled","reason","loadTextureInternal","loadImage","createTextureFromImage","localPath","isLocalPath","toLocalPath","embedded","getEmbedded","loadImageFromSrc","imgSrc","createImageBitmap","bitmap","premultiplyAlpha","colorSpaceConversion","gl","getWebGL2Context","createTextureWebGL2","createTextureFallback","glObj","GL","currentContext","GLctx","WebGL2RenderingContext","createTexture","bindTexture","TEXTURE_2D","pixelStorei","UNPACK_FLIP_Y_WEBGL","UNPACK_PREMULTIPLY_ALPHA_WEBGL","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","REPEAT","TEXTURE_WRAP_T","generateMipmap","glTextureId","getNewId","registerExternalTexture","nextPowerOf2","clearRect","imageData","unpremultiplyAlpha","round","decodeDataUrlText","vertex","fragment","parseEsShader","vertexMatch","fragmentMatch","trim","dataUrl","atob","decodeDataUrlBinary","charCodeAt","virtualPath","ensureVirtualDir","writeFile","currentPath","analyzePath","exists","mkdir","line","trimmed","endsWith","Assets","AssetPlugin","assetPlugin","AssetRefCounter","textureRefs_","fontRefs_","materialRefs_","addTextureRef","refs","removeTextureRef","getTextureRefs","addFontRef","removeFontRef","getFontRefCount","getFontRefs","addMaterialRef","removeMaterialRef","getMaterialRefCount","getMaterialRefs","getAllTextureRefs","assetPath","getAllFontRefs","getAllMaterialRefs","removeAllRefsForEntity","getTotalRefCount","getResource","cloneComponents","cloneComponentData","remapComponentEntityRefs","idMapping","mapped","applyOverrides","overrides","override","prefabEntityId","propertyName","componentData","flattenPrefab","basePrefab","variant","instanceOverrides","combinedOverrides","flattenVariant","pe","allocateId","nestedPath","nested","rootId","nestedRoot","isRoot","rootEntityId","children","collectNestedPrefabPaths","seen","preloadNestedPrefabs","cache","instantiatePrefab","prefabCache","nextId","processed","root","PrefabServer","assetServer_","pathOrAddress","Prefabs","PrefabsPlugin","dependencies","prefabsPlugin","viewProjectionPtr","transformPtr","uniformsPtr","initDrawAPI","UNIFORMS_BUFFER_SIZE","shutdownDrawAPI","getModule","WHITE","Draw","begin","draw_begin","draw_end","thickness","draw_line","filled","draw_rect","rectOutline","draw_rectOutline","circle","center","draw_circle","circleOutline","draw_circleOutline","draw_texture","textureRotated","draw_textureRotated","setLayer","draw_setLayer","setDepth","draw_setDepth","getDrawCallCount","draw_getDrawCallCount","getPrimitiveCount","draw_getPrimitiveCount","draw_setBlendMode","draw_setDepthTest","drawMesh","geometry","draw_mesh","drawMeshWithMaterial","matData","autoTextureSlot","nameId","getUniformNameId","subarray","draw_meshWithUniforms","UNIFORM_NAME_MAP","u_time","u_color","u_intensity","u_scale","u_offset","u_param0","u_param1","u_param2","u_param3","u_param4","u_vec0","u_vec1","u_vec2","u_vec3","u_texture0","u_texture1","u_texture2","u_texture3","warnedUniforms","registerDrawCallback","unregisterDrawCallback","clearDrawCallbacks","DataType","vertexPtr","indexPtr","layoutPtr","initGeometryAPI","VERTEX_BUFFER_SIZE","INDEX_BUFFER_SIZE","LAYOUT_BUFFER_SIZE","shutdownGeometryAPI","Geometry","geometry_create","vertexCount","layoutCount","layoutArray","geometry_init","dynamic","indices","indexCount","geometry_setIndices16","geometry_setIndices32","updateVertices","geometry_updateVertices","geometry_release","geometry_isValid","createQuad","hw","hh","Float2","createCircle","u","createPolygon","nextStackId","stacks","cameraBindings","getStacks","getCameraBindings","PostProcessStack","passes_","destroyed_","addPass","floatUniforms","vec4Uniforms","removePass","clearPasses","setEnabled","pass","passName","uniform","setUniformVec4","setAllPassesEnabled","passCount","enabledPassCount","passes","isDestroyed","stack","POSTPROCESS_VERTEX","initPostProcessAPI","shutdownPostProcessAPI","PostProcess","isInitialized","shutdown","createStack","unbind","getStack","postprocess_init","postprocess_shutdown","resize","postprocess_resize","postprocess_isInitialized","setBypass","bypass","postprocess_setBypass","postprocess_begin","postprocess_end","setOutputViewport","postprocess_setOutputViewport","_applyForCamera","postprocess_clearPasses","postprocess_addPass","postprocess_setUniformFloat","postprocess_setUniformVec4","syncStackToWasm","_resetAfterCamera","_cleanupDestroyedCameras","screenStack","setScreenStack","_beginScreenCapture","postprocess_beginScreenCapture","_endScreenCapture","postprocess_endScreenCapture","_applyScreenStack","postprocess_clearScreenPasses","postprocess_addScreenPass","postprocess_setScreenUniformFloat","postprocess_setScreenUniformVec4","_executeScreenPasses","postprocess_executeScreenPasses","createBlur","createVignette","createGrayscale","createBloomExtract","createBloomKawase","iteration","toFixed","createBloomComposite","createChromaticAberration","effectRegistry","registerEffect","getEffectDef","getEffectTypes","getAllEffectDefs","factory","step","multiPass","volumeStacks","volumeShaders","syncPostProcessVolume","shaders","activeEffects","effect","uDef","cleanupPostProcessVolume","cleanupAllPostProcessVolumes","PostProcessVolumeConfigResource","getOrCreateShader","applyBlendedEffects","effectType","effectData","subPass","uniformName","uniformValue","postProcessVolumeSystem","volumeQuery","cameraQuery","volumes","_entity","volumeData","activeVolumes","factor","blended","sorted","prev","blendVolumeEffects","cameraEntity","cameraData","PostProcessPlugin","PostUpdate","cleanupVolumeSystem","postProcessPlugin","FlushReason","RenderType","RenderStage","SubmitSkipFlags","Spine","Particles","initRendererAPI","shutdownRendererAPI","Renderer","renderer_init","renderer_resize","beginFrame","renderer_beginFrame","updateTransforms","renderer_updateTransforms","_cpp","renderer_begin","renderer_flush","renderer_end","submitAll","skipFlags","renderer_submitAll","setStage","stage","renderer_setStage","createRenderTarget","renderer_createTarget","releaseRenderTarget","renderer_releaseTarget","getTargetTexture","renderer_getTargetTexture","getTargetDepthTexture","renderer_getTargetDepthTexture","setClearColor","renderer_setClearColor","setViewport","renderer_setViewport","setScissor","enable","renderer_setScissor","clearBuffers","renderer_clearBuffers","measureBitmapText","fontHandle","getStats","drawCalls","renderer_getDrawCalls","triangles","renderer_getTriangles","sprites","renderer_getSprites","renderer_getText","renderer_getSpine","meshes","renderer_getMeshes","culled","renderer_getCulled","captureNextFrame","renderer_captureNextFrame","getCapturedData","renderer_hasCapturedData","renderer_getCapturedFrameSize","renderer_getCapturedFrameData","entitiesPtr","renderer_getCapturedEntities","renderer_getCapturedEntityCount","cameraCount","renderer_getCapturedCameraCount","heap","view","DataView","entityHeap","off","getUint32","cameraIndex","getUint8","shaderId","triangleCount","dcEntityCount","entityOffset","getInt32","flushReason","scissorX","scissorY","scissorW","scissorH","scissorEnabled","stencilWrite","stencilTest","stencilRef","textureSlotUsage","decodeFrameCapture","hasCapturedData","replayToDrawCall","drawCallIndex","renderer_replayToDrawCall","replayToDrawCallImpl","getSnapshotImageData","renderer_getSnapshotSize","renderer_getSnapshotWidth","renderer_getSnapshotHeight","renderer_getSnapshotPtr","Uint8ClampedArray","flipped","rowBytes","srcOff","dstOff","ImageData","getSnapshotImpl","initGLDebugAPI","shutdownGLDebugAPI","GLDebug","gl_enableErrorCheck","disable","check","gl_checkErrors","diagnose","renderer_diagnose","RenderPipeline","lastWidth_","lastHeight_","activeScenes_","preFlushCallbacks_","setActiveScenes","scenes","addPreFlushCallback","beginScreenCapture","endScreenCapture","submitScene","viewport","_elapsed","executeDrawCallbacks","render","renderCamera","viewportPixels","vp","hasPostProcess","cbs","UIVisualType","SolidColor","NineSlice","UIRenderer","TRANSITION_CALLBACK_ID","SceneInstance","drawCallbacks","postProcessBindings","savedAlphas","loadedAssets","SceneContextImpl","instance_","app_","bindPostProcess","unbindPostProcess","setPersistent","SceneManagerState","configs_","scenes_","contexts_","additiveScenes_","pausedScenes_","sleepingScenes_","loadOrder_","activeScene_","initialScene_","transition_","switching_","loadPromises_","reset","setInitial","getInitial","isTransitioning","switchTo","transition","unload","startFadeTransition","targetScene","onStart","phase","halfDuration","alpha","updateTransition","dt","oldScene","rejectTransition","doSwitch","onComplete","loadPromise","hasResource","loadSceneData_","loadAdditive","keepPersistent","releaseSceneAssets_","orderIdx","loadOptions","systems","wrapped","wrapSceneSystem","setup","setPostProcessPassesEnabled","sleep","saved","hasSaved","bt","bitmapText","uiRenderer","wake","isPaused","isSleeping","isLoaded","getActive","getActiveScenes","getLoaded","getLoadOrder","bringToTop","getScene","getSceneStatus","SceneManager","sceneName","sceneTransitionSystem","scenesRes","sceneManagerPlugin","initSystem","manager","initial","App","systems_","runner_","running_","lastTime_","fixedTimestep_","fixedAccumulator_","maxDeltaTime_","maxFixedSteps_","pipeline_","installed_plugins_","installedPluginSet_","installedPluginNames_","pluginsFinished_","sortedSystemsCache_","error_handler_","system_error_handler_","statsEnabled_","phaseTimings_","frame_paused_","user_paused_","step_pending_","play_speed_","mainLoop","deltaMs","flushStartupSystems_","updateTime","runSchedule","First","fixedSteps","FixedPreUpdate","FixedUpdate","FixedPostUpdate","getPlugin","ctor","addPlugin","plugin","dep","addEvent","runBefore","runAfter","removeSystem","systemId","removed","pipeline","setPipeline","spineInitPromise","spineInitPromise_","physicsInitPromise","physicsInitPromise_","physicsModule","physicsModule_","waitForPhysics","isPhysicsReady","setFixedTimestep","timestep","onError","onSystemError","onWasmError","setPaused","paused","stepFrame","setPlaySpeed","getPlaySpeed","enableStats","getSystemTimings","getPhaseTimings","getEntityCount","registerScene","setInitialScene","finishPlugins_","quit","shutdowns","finish","sortSystems","nameToIndex","targetName","targetIndex","targetEntry","visiting","visit","depName","depIndex","startup","rawSystems","flushPendingSystems","IDENTITY","computeEffectiveOrthoSize","baseOrthoSize","designAspect","actualAspect","orthoForWidth","orthoForHeight","cameraInfoPool_","acquireCameraInfo","viewportRect","halfW","halfH","cameraX","cameraY","collectCameras","activeScenes","registry_getCameraEntities","owner","registry_getCanvasEntity","getCanvas","findCanvasData","cameras","getCamera","getTransform","aspect","projection","camHalfW","camHalfH","ortho","perspective","invertTranslation","cam","multiply","_orthoM","near","far","fill","rl","tb","_perspM","fovRad","tan","nf","_invTransM","_mulM","j","FillDirection","LeftToRight","RightToLeft","BottomToTop","TopToBottom","ImageType","Simple","Sliced","Tiled","Filled","FillMethod","Horizontal","Vertical","FillOrigin","Left","Right","Bottom","Top","imageType","fillMethod","fillOrigin","fillAmount","preserveAspect","tileSize","offsetMin","offsetMax","Interactable","blockRaycast","raycastTarget","computeUIRectLayout","parentRect","parentW","parentH","aLeft","aRight","aBottom","aTop","myLeft","myBottom","myRight","myTop","nativeRegistry_","computeFillAnchors","direction","computeHandleAnchors","computeFillSize","applyDirectionalFill","fillEntity","anchors","applyColorTransition","pressed","hovered","pressedColor","hoveredColor","normalColor","disabledColor","TINT_HOVER","TINT_PRESSED","applyDefaultTint","baseColor","isWordChar","wrapText","maxWidth","paragraphs","paragraph","currentLine","char","testLine","measureText","breakPos","getEntityDepth","getEffectiveWidth","getUIRectComputedWidth","getEffectiveHeight","getUIRectComputedHeight","setUIRectSizeNative","setUIRectSize","syncFillSpriteSize","normalizedValue","sliderW","sliderH","ensureComponent","makeInteractable","withChildEntity","colorEquals","setEntityColor","setEntityEnabled","colorScale","colorWithAlpha","EntityStateMap","map_","ensureInit","createSnapshotUtils","spec","extractors","take","snap","changed","snapshot","update","SCROLL_VELOCITY_THRESHOLD","DROPDOWN_HIGHLIGHT_COLOR","DROPDOWN_DEFAULT_COLOR","DROPDOWN_OPTION_COLOR","TextAlign","Center","TextVerticalAlign","Middle","TextOverflow","Visible","Clip","Ellipsis","verticalAlign","wordWrap","overflow","lineHeight","TextRenderer","shrinkCounter_","frameMaxW_","frameMaxH_","renderText","uiRect","renderTextInner","hasContainer","containerWidth","containerHeight","shouldWrap","lineHeightPx","padding","measuredWidth","measureWidth","measuredHeight","maxLines","floor","lastLine","truncateWithEllipsis","textAlign","mapAlign","textBaseline","fillStyle","save","beginPath","textBlockHeight","startY","fillText","restore","truncated","renderForEntity","getCached","cleanupOrphaned","isAlive","textSnapshot","colorR","colorG","colorB","colorA","ensureUIRenderer","TextPlugin","renderer","snapshots","effectiveRect","textPlugin","MaskMode","UIMask","UIMaskPlugin","uiMaskPlugin","intersectRects","invertMatrix4","out","a00","a01","a02","a03","a10","a11","a12","a13","a20","a21","a22","a23","a30","a31","a32","a33","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","det","screenToWorld","screenX","screenY","inverseVP","ndcX","ndcY","ww","pointInWorldRect","px","py","worldW","worldH","pivotX","pivotY","quaternionToAngle2D","rz","rw","atan2","pointInOBB","rotationZ","rotationW","localX","localY","UIInteraction","justPressed","justReleased","ButtonState","Hovered","Pressed","Disabled","Button","UIEventQueue","events_","entityTypeHandlers_","globalHandlers_","activeDispatches_","entityValidator_","on","entityOrType","typeOrHandler","typeMap","handlers","removeAll","setEntityValidator","validator","emit","currentTarget","propagationStopped","stopPropagation","dispatchToHandlers_","emitBubbled","shared","drain","query","hasEvent","invokeHandlers_","globalHandlers","UIEvents","UILayoutGeneration","UILayoutPlugin","initUIHelpers","layoutGen","uiLayout_update","transform_update","uiLayoutPlugin","vpCache","invVP","cachedVP","dirty","getInverse","createInvVPCache","emitWithBubbling","walkParentChain","ancestor","interactable","UIInteractionPlugin","hoveredEntity","pressedEntity","lastPointerX","NaN","lastPointerY","lastLayoutGen","input","interactionEntities","interaction","dpr","mouseGLX","mouseGLY","worldMouse","mouseDown","mousePressed","mouseReleased","pointerMoved","layoutChanged","needsHitTest","hitEntity","uiHitTest_update","hitEntityRaw","uiHitTest_getHitEntity","curr","buttonInitialized","buttonEntities","isFirstFrame","prevState","tinted","uiInteractionPlugin","placeholder","placeholderColor","multiline","password","readOnly","focused","cursorPos","Focusable","tabIndex","isFocused","FocusManagerState","focusedEntity","focus","blur","FocusManager","TextInputPlugin","cleanupListeners_","moduleOrNull","textureCache","ctxOrNull","wasmPixelPtr","wasmPixelSize","composing","cursorVisible","cursorTimer","lastTime","textareaOrNull","textarea","style","zIndex","autocomplete","setAttribute","appendChild","createHiddenTextarea","getFocusedTextInput","fm","onInput","syncFromTextarea","onCompositionStart","onCompositionEnd","blurCurrent","ti","newPos","selectionStart","selectionEnd","resetCursorBlink","onBlur","prevFocusedTextInput","renderTextInput","bg","displayText","repeat","textColor","textY","cursorText","cursorX","cursorY","cursorH","charCount","cursorLine","cursorCol","lineLen","partialLine","existingTex","focusManager","textInputEntities","currentFocused","activateTextarea","textInputPlugin","imageSnapshot","tileSizeX","tileSizeY","rectWidth","rectHeight","ImagePlugin","amount","imagePlugin","Toggle","isOn","graphicEntity","onColor","offColor","ToggleGroup","allowSwitchOff","setRendererColor","setRendererEnabled","TogglePlugin","initializedEntities","toggleEntities","groupFirstOn","toggle","togglesByGroup","groupEntity","hasGroup","siblings","other","otherToggle","graphic","togglePlugin","ProgressBarDirection","ProgressBar","ProgressBarPlugin","bar","progressBarPlugin","Draggable","dragThreshold","lockX","lockY","constraintMin","constraintMax","DragState","isDragging","startWorldPos","currentWorldPos","deltaWorld","totalDeltaWorld","pointerStartWorld","worldToLocalDelta","parentWt","sx","sy","DragPlugin","pendingEntity","pendingStartWorld","activeEntity","draggableEntities","bestEntity","bestLayer","bestDepth","dragState","dist","draggable","pointerDeltaX","pointerDeltaY","newWorldX","newWorldY","constrained","newX","newY","applyConstraints","prevX","prevY","localDelta","lt","dragPlugin","ScrollView","contentEntity","horizontalEnabled","verticalEnabled","contentWidth","contentHeight","scrollX","scrollY","inertia","decelerationRate","elastic","wheelSensitivity","rubberBand","pos","viewSize","smoothDamp","currentVelocity","smoothTime","omega","exp","change","temp","newValue","velocity","ScrollViewPlugin","cleanup_","states","editorSceneView","sv","lastWorldX","lastWorldY","velocityX","velocityY","contentBaseX","contentBaseY","lastAppliedX","lastAppliedY","viewW","viewH","effectiveContentW","effectiveContentH","kids","ct","cw","cr","sp","maxScrollX","maxScrollY","lerpFactor","rbX","instantVx","rbY","instantVy","maxVelX","maxVelY","scroll","overX","overY","targetX","targetY","maxOverX","maxOverY","curX","curY","scrollViewPlugin","SliderDirection","Slider","minValue","maxValue","handleEntity","wholeNumbers","computeSliderValue","localMouseX","localMouseY","syncHandleRect","handleRect","SliderPlugin","slider","oldValue","sliderPlugin","FocusPlugin","focusableEntities","setFocus","getSortedFocusables","currentIdx","reverse","nextIdx","focusPlugin","SafeArea","applyTop","applyBottom","applyLeft","applyRight","getSafeAreaInsets","safeArea","screenWidth","screenHeight","getWeChatSafeAreaInsets","getComputedStyle","documentElement","parseFloat","getPropertyValue","getWebSafeAreaInsets","SafeAreaPlugin","cachedInsets","prevScreenH","prevWorldH","onWindowResize","insetScale","sa","safeAreaPlugin","ListView","itemHeight","itemCount","overscan","activeListViewStates","setListViewRenderer","visibleStart","visibleEnd","itemEntities","ListViewPlugin","listViewStates","st","itemEntity","lv","viewHeight","viewWidth","maxScroll","startIdx","endIdx","listViewPlugin","Dropdown","selectedIndex","isOpen","listEntity","labelEntity","DropdownPlugin","dropdownStates","appearanceInitialized","normalizeListTransform","initDropdownAppearance","openDropdown","dropdown","highlightIndex","setListVisible","destroyOptions","ddWidth","ddRect","totalHeight","optEntity","optionEntities","textEntity","textEntities","updateHighlight","closeDropdown","selectOption","syncLabel","newColor","newContent","selectedText","isAnyOptionHovered","hoveredIndex","dropdownPlugin","LayoutGroup","childAlignment","reverseOrder","LayoutGroupPlugin","layoutGroupPlugin","FlexDirection","FlexWrap","JustifyContent","AlignItems","FlexContainer","wrap","justifyContent","alignItems","gap","FlexItem","flexGrow","flexShrink","flexBasis","order","UIRenderOrderPlugin","uiRenderOrder_update","uiRenderOrderPlugin","DARK_THEME","primary","secondary","background","surface","textSecondary","xs","sm","md","lg","xl","trackHeight","trackColor","fillColor","handleSize","handleColor","checkColor","panel","scrollView","UIThemeRes","activeTheme","initUIBuilder","getTheme","spawnUI","theme","flex","flexItem","mask","createButton","btn","onClick","onHover","createSlider","onChange","createToggle","checkSize","createProgressBar","createScrollView","contentSize","horizontal","vertical","createTextInput","onSubmit","createDropdown","items","dd","createLabel","createPanel","createFlexRow","createFlexColumn","widgetFactories","textInput","progressBar","flexRow","flexColumn","UI","destroyUI","childList","buildUI","childrenTarget","ref","transitionTo","SpineModuleController","raw_","api_","listeners_","atlasText","getLastError","pageIndex","skeletonHandle","destroyInstance","instanceId","playAnimation","addAnimation","delay","setSkin","skinName","getAnimations","getSkins","getBonePosition","boneName","xPtr","yPtr","getBoneRotation","getBounds","extractMeshBatches","batchCount","getMeshBatchCount","batches","metaPtr","texIdPtr","blendPtr","getMeshBatchVertexCount","getMeshBatchIndexCount","vertBytes","idxBytes","vertPtr","idxPtr","getMeshBatchData","setDefaultMix","setMixDuration","fromAnim","toAnim","setTrackAlpha","setAttachment","slotName","attachmentName","setIKTarget","constraintName","mix","setSlotColor","enableEvents","collectEvents","getEventCount","getEventBuffer","floatValue","intValue","clearEvents","entityListeners","typeListeners","removeAllListeners","ModuleBackend","cachedFrame_","cachedEntries_","controller_","loadEntity","setEntityProps","setAnimation","updateAll","extractAndSubmitMeshes","coreModule","submitFn","renderer_submitSpineBatchByEntity","batch","totalVertBytes","totalIdxBytes","vertBase","idxBase","vOff","iOff","call","removeEntity","SpineManager","moduleFactories","backends_","loadingBackends_","entityVersions_","coreModule_","factories_","detectVersion","ver4x","bytesRead","readVarint","ver","tryRead4xVersion","hashLen","hb","verLen","vb","tryRead3xVersion","detectVersionJson","spine_setNeedsReload","ensureBackend","updateAnimations","submitMeshes","getEntityVersion","hasModuleBackend","getModuleBackend","getEntityBackend_","hasInstance","loading","cwrap","wrapSpineModule","shift","loadPhysicsModule","wasmUrl","PhysicsDebugDraw","showColliders","showVelocity","showContacts","STATIC_COLOR","DYNAMIC_COLOR","KINEMATIC_COLOR","SENSOR_COLOR","VELOCITY_COLOR","CONTACT_COLOR","DEBUG_LINE_THICKNESS","CAPSULE_ARC_SEGMENTS","quatToAngleZ","q","bodyTypeColor","drawRotatedBox","cx","cy","pts","drawCapsule","toWorld","lx","ly","topLeft","topRight","bottomLeft","bottomRight","a0","a1","p0","p1","drawVelocityArrow","endX","endY","ARROWHEAD_ANGLE","dirX","dirY","leftX","leftY","rightX","rightY","drawPhysicsDebug","physicsApiRes","physicsEventsRes","ppu","readPixelsPerUnit","physics","rb","box","cosA","sinA","capsule","seg","p1x","p1y","p2x","p2y","poly","verts","vi","v0","v1","x0","y0","x1","y1","chain","pi","vel","getLinearVelocity","collision","collisionEnters","contactX","contactY","PhysicsEvents","collisionExits","sensorEnters","sensorExits","PhysicsAPI","PhysicsPlugin","wasmUrl_","factory_","fixedTimestep","subStepCount","contactHertz","contactDampingRatio","contactSpeed","collisionLayerMasks","trackedEntities","trackedJoints","parentedBodies","cachedProps","lastEntitySyncTick","initPromise","_physics_init","invPpu","_physics_destroyJoint","_physics_destroyBody","currentEntities","_physics_updateBodyProperties","_physics_setBodyTransform","hasParent","posX","posY","_physics_createBody","addShapeForEntity","jointEntities","joint","connected","_physics_createRevoluteJoint","_physics_createDistanceJoint","_physics_createPrismaticJoint","_physics_createWeldJoint","_physics_createWheelJoint","createPendingJoints","_physics_step","_physics_getDynamicBodyCount","_physics_getDynamicBodyTransforms","baseU32","physU32","physF32","engineMod","hasParented","registry_batchSyncPhysicsTransforms","byteLen","PHYSICS_BODY_BYTES","engineBuf","getTransformPtr","engF32","addTransform","syncTransformBuf_","PHYSICS_BODY_STRIDE","localAngle","parentData","pwt","parentAngleZ","cosH","sinH","tPtr","fi","syncDynamicTransforms","_physics_collectEvents","enterCount","_physics_getCollisionEnterCount","enterPtr","_physics_getCollisionEnterBuffer","entityA","entityB","normalX","normalY","exitCount","_physics_getCollisionExitCount","exitPtr","_physics_getCollisionExitBuffer","sensorEnterCount","_physics_getSensorEnterCount","sensorEnterPtr","_physics_getSensorEnterBuffer","sensorEntity","visitorEntity","sensorExitCount","_physics_getSensorExitCount","sensorExitPtr","_physics_getSensorExitBuffer","Physics","_fromModule","setupPhysicsDebugDraw","MAX_COLLISION_LAYERS","resolveCollisionMask","layerMasks","category","_physics_addBoxShape","_physics_addCircleShape","_physics_addCapsuleShape","_physics_addSegmentShape","byteSize","_physics_addPolygonShape","_physics_addChainShape","prototype","applyForce","force","_physics_applyForce","applyImpulse","impulse","_physics_applyImpulse","setLinearVelocity","_physics_setLinearVelocity","_physics_getLinearVelocity","setGravity","_physics_setGravity","getGravity","_physics_getGravity","setAngularVelocity","_physics_setAngularVelocity","getAngularVelocity","_physics_getAngularVelocity","applyTorque","torque","_physics_applyTorque","applyAngularImpulse","_physics_applyAngularImpulse","createRevoluteJoint","o","destroyJoint","setRevoluteMotorSpeed","_physics_setRevoluteMotorSpeed","setRevoluteMaxMotorTorque","_physics_setRevoluteMaxMotorTorque","enableRevoluteMotor","_physics_enableRevoluteMotor","enableRevoluteLimit","_physics_enableRevoluteLimit","setRevoluteLimits","lower","upper","_physics_setRevoluteLimits","getRevoluteAngle","_physics_getRevoluteAngle","getRevoluteMotorTorque","_physics_getRevoluteMotorTorque","raycast","origin","_physics_raycast","_physics_getRaycastBuffer","normal","fraction","overlapCircle","_physics_overlapCircle","_physics_getOverlapBuffer","setAwake","awake","_physics_setAwake","isAwake","_physics_isAwake","setDebugDraw","setDebugDrawConfig","FILTER_MODE_MAP","nearest","clamp","mirror","createTextureFromPixels","filterMode","createTextureEx","test","loadRuntimeScene","provider","spineManager","physicsConfig","texSettings","textureImporterSettings","descriptors","loadPixels","loadTextures","applyTextureMetadata","spineAssetInfo","assetInfoMap","spineDesc","skelRef","atlasRef","readText","readBinary","texNames","loadPixelsRaw","loadSpineAssetsToVirtualFS","fontCache","fontDesc","fntRef","texRef","texHandle","loadBitmapFonts","materialCache","shaderCache","matDesc","matRef","vertexSource","fragmentSource","shaderKey","loadMaterials","clipText","clipData","loadAnimClips","jsonText","loadTilemaps","preloadAudioClips","cacheByType","resolveSceneAssetPaths","sceneEntity","createRuntimeSceneConfig","initRuntime","firstScene","sceneOpts","spineModule","mgr","WebAssetProvider","baseUrl_","prefetch","textRefs","binaryRefs","bmfontRefs","fetches","fntFetches","resp","blob","SpineCpp","spine_update","spine_play","spine_addAnimation","spine_setSkin","spine_getBonePosition","spine_hasInstance","reloadAssets","spine_reloadAssets","spine_getAnimations","spine_getSkins","SpinePlugin","managerOrProvider","spineManager_","provider_","setSpineManager","fc","factories","versions","jsSource","wasmBytes","loadJs","loadWasm","Blob","URL","createObjectURL","import","revokeObjectURL","moduleFactory","__ESSpineModule__","createSpineFactories","spineUpdateSystem","PREVIEW_SCENE","PreviewPlugin","sceneUrl","loadPromise_","eventSource_","onMessage_","onError_","sceneUrl_","loadRuntimeData","ensureCamera","setupHotReload","waitForReady","spinePlugin","hasActiveCamera","canvasEntities","sceneCtx","transformData","href","eventsUrl","host","EventSource","log","reloadScene","msg","RenderTexture","_handle","_depth","_filter","rt","getDepthTexture","LogLevel","ConsoleLogHandler","timestamp","toISOString","level","toUpperCase","padEnd","Debug","debug","Info","Warn","Logger","handlers_","minLevel_","addHandler","setMinLevel","removeHandler","clearHandlers","defaultLogger","getLogger","setLogLevel","EasingType","EaseInQuad","EaseOutQuad","EaseInOutQuad","EaseInCubic","EaseOutCubic","EaseInOutCubic","EaseInBack","EaseOutBack","EaseInOutBack","EaseInElastic","EaseOutElastic","EaseInOutElastic","EaseOutBounce","CubicBezier","Step","TweenState","Running","Paused","Completed","Cancelled","LoopMode","Restart","PingPong","BACK_C1","BACK_C3","BACK_C2","ELASTIC_C4","ELASTIC_C5","BOUNCE_N1","BOUNCE_D1","BEZIER_EPSILON","applyEasing","bezier","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","t1","easeOutCubic","easeInOutCubic","easeInBack","easeOutBack","easeInOutBack","easeInElastic","easeOutElastic","easeInOutElastic","easeOutBounce","ix","cubicBezier","valueTweenManager","entries_","nextId_","cppSequences_","registry_","easing","bezierPoints","loopCount","loopsRemaining","sequenceNext","sequenceNextExternal","cppEntity","jsTweenId","_anim_getTweenState","easedT","infinite","cancel","getState","setBezier","setSequenceNext","setSequenceNextExternal","external","registerCppSequence","ValueTweenHandle","TweenTarget","SizeX","SizeY","TweenHandle","_anim_setTweenBezier","_anim_setSequenceNext","_anim_pauseTween","_anim_resumeTween","_anim_cancelTween","_module","_registry","initTweenAPI","shutdownTweenAPI","getRegistry","Tween","tweenEntity","_anim_createTween","tweenHandle","cancelAll","_anim_cancelAllTweens","_anim_updateTweens","AnimationPlugin","animationPlugin","initParticleAPI","shutdownParticleAPI","Particle","particle_update","particle_play","particle_stop","particle_reset","getAliveCount","particle_getAliveCount","ParticlePlugin","particlePlugin","SYNTHETIC_KEY_BASE","GRID_TYPE_MAP","orthogonal","isometric","staggered","TilemapPlugin","initializedLayers_","animatedLayers_","sourceEntityKeys_","layerState_","initializedLayers","animatedLayers","sourceEntityKeys","layerState","tilemapSyncSystem","layerEntities","currentLayerSet","layerData","dims","u16","pf","tilemapEntities","tilemap","gridType","tileset","currentTilemapSet","tilemapPlugin","formatNumber","decimals","escapeHtml","StatsOverlay","container","visible_","lastUpdateTime_","lastStats_","accumulatedTimings_","el_","cssText","positionStyle","stats","accumulateTimings_","systemTimings","render_","show","display","hide","parentElement","removeChild","timings","ms","acc","sum","sections","frameTimeMs","avg","systemsHtml","innerHTML","defaultFrameStats","phaseTimings","Stats","FrameHistory","cursor_","count_","capacity_","getLatest","getAll","STATS_COLLECT_SYSTEM_NAME","StatsCollector","deltas_","sum_","pushFrame","deltaSeconds","isFinite","getFps","getFrameTimeMs","StatsPlugin","collector_","overlay_","options_","overlay","collector","statsCollectSystem","copy","renderStats","statsPlugin","EmbeddedAssetProvider","assets_","cv","getAsset","decodeBase64ToWasm","base64","initPhysicsModule","wasmBase64","ESPhysicsModule","opts","Response","instantiateStreaming","instantiateWasmModule","initPlayableRuntime","spineModules","buildSpineManager","physicsWasmBase64","uiPlugins","basePlugins","createWebApp","spineProvider","plugins","new","Registry","glContextHandle","initRendererWithContext","initRenderer","getViewportSize","syncUICameraInfo","uiCam","vr","uiCameraSyncSystem","renderSystem","canvasEntity","running","pw","ph","_createWebApp"],"mappings":"AAWA,IAAIA,EAA0C,cAa9BC,IACZ,IAAKD,EACD,MAAM,IAAIE,MACN,8HAIR,OAAOF,CACX,UAKgBG,IACZ,OAA2B,OAApBH,CACX,UAKgBI,IACZ,OAAOJ,GAAiBK,MAAQ,IACpC,UAKgBC,IACZ,MAAiC,WAA1BN,GAAiBK,IAC5B,UAKgBE,IACZ,MAAiC,QAA1BP,GAAiBK,IAC5B,CAMOG,eAAeC,EAClBC,EACAC,GAEA,OAAOV,IAAcW,MAAMF,EAAKC,EACpC,CAEOH,eAAeK,EAAiBC,GACnC,OAAOb,IAAcc,SAASD,EAClC,CAEON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B,CAAE7nE,EAAGyiF,EAAIxiF,EAAGyiF,EAAIn/E,EAAGorH,EAAI70F,EAAG80F,GAC1C1kH,WAAY0qE,EAAI1qE,WAChB5T,UACA2oE,aAAc2V,EAAIlqE,QAE1B,CACAylE,EAAS7I,mBACTvH,GAAS2B,YAAY,EAAG,EAAG9xE,EAAOC,EACtC,IAWR,GAPA2S,EAAI0mB,oBAAoBf,GAASgnD,MAAOo/C,GACxC/rH,EAAI0mB,oBAAoBf,GAAS+D,KAAMsiG,GAEvChsH,EAAIktE,UAAU/hB,IACdnrD,EAAIktE,UAAU9d,IACdpvD,EAAIktE,UAAUvjD,IACd3pB,EAAIktE,UAAUvC,IACVr+E,GAAS++H,QACT,IAAK,MAAMl+C,KAAU7gF,EAAQ++H,QACzBrrH,EAAIktE,UAAUC,GAItB,OAAOntE,CACX,C0E/wBWqsH,CAAchzH,EAAQ,IAAK/M,EAAS++H,WAC/C,CpJjCI1/H,EqJXQyL"}\ No newline at end of file+{"version":3,"file":"index.bundled.js","sources":["../src/platform/base.ts","../src/audio/AudioBus.ts","../src/audio/AudioMixer.ts","../src/audio/AudioPool.ts","../src/audio/WebAudioBackend.ts","../src/platform/web.ts","../src/defaults.ts","../src/types.ts","../src/componentEntityFields.ts","../src/component.ts","../src/physics/PhysicsComponents.ts","../src/resource.ts","../src/storage.ts","../src/validation.ts","../src/wasmError.ts","../src/world.ts","../src/query.ts","../src/commands.ts","../src/event.ts","../src/system.ts","../src/input.ts","../src/ui/UICameraInfo.ts","../src/blend.ts","../src/material.ts","../src/asset/AsyncCache.ts","../src/asset/MaterialLoader.ts","../src/animation/AnimClipLoader.ts","../src/animation/SpriteAnimator.ts","../src/audio/Audio.ts","../src/tilemap/tilesetCache.ts","../src/tilemap/tilemapAPI.ts","../src/tilemap/components.ts","../src/tilemap/tiledLoader.ts","../src/tilemap/collisionMerge.ts","../src/timeline/TimelineTypes.ts","../src/timeline/TimelineLoader.ts","../src/env.ts","../src/timeline/TimelineUploader.ts","../src/timeline/TimelineControl.ts","../src/audio/SpatialAudio.ts","../src/audio/AudioComponents.ts","../src/audio/AudioPlugin.ts","../src/timeline/TimelinePlugin.ts","../src/scene.ts","../src/assetTypes.ts","../src/asset/AssetServer.ts","../src/asset/AssetPlugin.ts","../src/asset/AssetRefCounter.ts","../src/asset/index.ts","../src/prefab/clone.ts","../src/prefab/entityRef.ts","../src/prefab/override.ts","../src/prefab/flatten.ts","../src/prefab/collect.ts","../src/prefab.ts","../src/prefabServer.ts","../src/draw.ts","../src/customDraw.ts","../src/geometry.ts","../src/postprocess/PostProcessStack.ts","../src/postprocess/shaders.ts","../src/postprocess/PostProcessAPI.ts","../src/postprocess/effects.ts","../src/postprocess/sync.ts","../src/postprocess/volumeSystem.ts","../src/postprocess/volumeBlending.ts","../src/postprocess/PostProcessPlugin.ts","../src/frameCapture.ts","../src/renderer.ts","../src/glDebug.ts","../src/renderPipeline.ts","../src/ui/UIRenderer.ts","../src/sceneManager.ts","../src/scenePlugin.ts","../src/app.ts","../src/ui/uiTypes.ts","../src/ui/Image.ts","../src/ui/UIRect.ts","../src/ui/Interactable.ts","../src/ui/uiHelpers.ts","../src/ui/uiSnapshot.ts","../src/ui/uiConstants.ts","../src/ui/text.ts","../src/ui/TextRenderer.ts","../src/ui/TextPlugin.ts","../src/ui/UIMask.ts","../src/ui/UIMaskPlugin.ts","../src/ui/uiMath.ts","../src/ui/UIInteraction.ts","../src/ui/Button.ts","../src/ui/UIEvents.ts","../src/ui/UILayoutGeneration.ts","../src/ui/UILayoutPlugin.ts","../src/ui/UIInteractionPlugin.ts","../src/ui/TextInput.ts","../src/ui/Focusable.ts","../src/ui/TextInputPlugin.ts","../src/ui/ImagePlugin.ts","../src/ui/Toggle.ts","../src/ui/ToggleGroup.ts","../src/ui/TogglePlugin.ts","../src/ui/ProgressBar.ts","../src/ui/ProgressBarPlugin.ts","../src/ui/Draggable.ts","../src/ui/DragPlugin.ts","../src/ui/ScrollView.ts","../src/ui/ScrollViewPlugin.ts","../src/ui/Slider.ts","../src/ui/SliderPlugin.ts","../src/ui/FocusPlugin.ts","../src/ui/SafeArea.ts","../src/ui/SafeAreaPlugin.ts","../src/ui/ListView.ts","../src/ui/ListViewPlugin.ts","../src/ui/Dropdown.ts","../src/ui/DropdownPlugin.ts","../src/ui/LayoutGroup.ts","../src/ui/LayoutGroupPlugin.ts","../src/ui/FlexContainer.ts","../src/ui/FlexItem.ts","../src/ui/UIRenderOrderPlugin.ts","../src/ui/UITheme.ts","../src/ui/UIBuilder.ts","../src/sceneTransition.ts","../src/spine/SpineController.ts","../src/spine/ModuleBackend.ts","../src/spine/SpineManager.ts","../src/spine/SpineModuleLoader.ts","../src/physics/PhysicsModuleLoader.ts","../src/physics/PhysicsDebugDraw.ts","../src/physics/PhysicsPlugin.ts","../src/runtimeLoader.ts","../src/preview/WebAssetProvider.ts","../src/spine/SpineCppAPI.ts","../src/spine/SpinePlugin.ts","../src/preview/PreviewPlugin.ts","../src/renderTexture.ts","../src/logger.ts","../src/animation/ValueTween.ts","../src/animation/Tween.ts","../src/animation/AnimationPlugin.ts","../src/particle/ParticleAPI.ts","../src/particle/ParticlePlugin.ts","../src/tilemap/tilemapPlugin.ts","../src/stats-overlay.ts","../src/stats.ts","../src/playableRuntime.ts","../src/uiPlugins.ts","../src/webAppFactory.ts","../src/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["currentPlatform","getPlatform","Error","isPlatformInitialized","getPlatformType","name","isWeChat","isWeb","async","platformFetch","url","options","fetch","platformReadFile","path","readFile","platformReadTextFile","readTextFile","platformFileExists","fileExists","platformInstantiateWasm","pathOrBuffer","imports","instantiateWasm","platformCreateCanvas","width","height","createCanvas","platformNow","now","platformDevicePixelRatio","g","globalThis","wx","getSystemInfoSync","pixelRatio","window","devicePixelRatio","AudioBus","constructor","context","config","this","muted_","volume_","children_","name_","gainNode_","createGain","Math","max","min","volume","muted","gain","value","node","v","setTargetAtTime","currentTime","m","connect","destination","addChild","child","push","AudioMixer","buses_","Map","context_","master","masterVolume","music","musicVolume","sfx","sfxVolume","ui","uiVolume","voice","voiceVolume","set","getBus","get","createBus","bus","parent","AudioPool","initialSize","pool_","activeCount_","i","createNode","panner","createStereoPanner","source","inUse","startTime","acquire","freeNode","find","n","pan","release","stop","_","disconnect","activeCount","capacity","length","WebAudioHandle","id","buffer","poolNode","pool","startOffset","playing_","stopped_","pausedAt_","source_","buffer_","poolNode_","startOffset_","startedAt_","playbackRate_","playbackRate","loop_","loop","bindOnEnded_","onended","onEnd","pause","elapsed","duration","resume","createBufferSource","start","setVolume","setPan","setLoop","setPlaybackRate","rate","isPlaying","WebAudioBackend","mixer_","buffers_","urlToId_","loadingUrls_","nextBufferId_","nextHandleId_","resumeHandler_","mixer","isReady","state","initialize","AudioContext","mixerConfig","initialPoolSize","document","removeEventListener","addEventListener","ensureResumed","loadBuffer","existingId","undefined","has","inFlight","promise","doLoadBuffer_","delete","loadBufferFromData","data","audioBuffer","decodeAudioData","err","message","arrayBuffer","unloadBuffer","handle","play","busName","handleId","suspend","dispose","clear","close","webAdapter","inputCleanup_","response","method","headers","body","forEach","key","ok","status","statusText","json","text","loadImagePixels","img","createImage","Promise","resolve","reject","crossOrigin","onload","onerror","src","ctx","getContext","drawImage","getImageData","pixels","Uint8Array","result","WebAssembly","instantiate","instance","module","Image","canvas","OffscreenCanvas","createElement","performance","bindInputEvents","callbacks","target","el","querySelector","onKeyDown","e","code","onKeyUp","onMouseMove","me","onPointerMove","offsetX","offsetY","onMouseDown","onPointerDown","button","onMouseUp","onPointerUp","onTouchStart","preventDefault","touch","touches","rect","getBoundingClientRect","clientX","left","clientY","top","onTouchMove","onTouchEnd","onTouchCancel","onWheel","we","dx","deltaX","dy","deltaY","deltaMode","innerWidth","innerHeight","passive","unbindInputEvents","createAudioBackend","getStorageItem","localStorage","getItem","setStorageItem","setItem","removeStorageItem","removeItem","clearStorage","prefix","toRemove","k","startsWith","DEFAULT_DESIGN_WIDTH","DEFAULT_DESIGN_HEIGHT","DEFAULT_PIXELS_PER_UNIT","DEFAULT_TEXT_CANVAS_SIZE","DEFAULT_SPRITE_SIZE","x","y","DEFAULT_FONT_FAMILY","DEFAULT_FONT_SIZE","DEFAULT_LINE_HEIGHT","DEFAULT_MAX_DELTA_TIME","DEFAULT_FALLBACK_DT","DEFAULT_GRAVITY","DEFAULT_FIXED_TIMESTEP","DEFAULT_SPINE_SKIN","RuntimeConfig","sceneTransitionDuration","sceneTransitionColor","r","b","a","defaultFontFamily","canvasScaleMode","canvasMatchWidthOrHeight","maxDeltaTime","maxFixedSteps","textCanvasSize","assetLoadTimeout","assetFailureCooldown","applyRuntimeConfig","components","Text","_default","fontFamily","TextInput","Canvas","scaleMode","matchWidthOrHeight","CANVAS_SCALE_MODE_MAP","FixedWidth","FixedHeight","Expand","Shrink","Match","applyBuildRuntimeConfig","app","setMaxDeltaTime","setMaxFixedSteps","hex","replace","parseInt","substring","INVALID_ENTITY","INVALID_TEXTURE","INVALID_FONT","INVALID_MATERIAL","vec2","vec3","z","vec4","w","color","quat","COMPONENT_ENTITY_FIELDS","registerComponentEntityFields","componentType","fields","getComponentEntityFields","deepClone","Array","isArray","map","componentCounter","createComponentDef","defaults","keyInfo","obj","flatKeys","objectKeys","arrayKeys","hasNested","val","classifyKeys","defaultsRec","_id","Symbol","_name","_builtin","create","slice","Object","assign","getComponentRegistry","__esengine_componentRegistry","defineComponent","metadata","existing","componentRegistry","def","registerToEditor","entityFields","defineTag","getUserComponent","clearUserComponents","userRegistry","keys","unregisterComponent","isTag","__esengine_registerComponent","isBuiltinComponent","comp","registerComponent","getComponent","detectColorKeys","defineBuiltin","_cppName","_colorKeys","ProjectionType","Perspective","Orthographic","ClearFlags","None","ColorOnly","DepthOnly","ColorAndDepth","ScaleMode","ShapeType","Circle","Capsule","RoundedRect","Transform","position","rotation","scale","worldPosition","worldRotation","worldScale","LocalTransform","WorldTransform","Sprite","texture","size","pivot","uvOffset","uvScale","layer","flipX","flipY","material","enabled","ShapeRenderer","shapeType","cornerRadius","Camera","projectionType","fov","orthoSize","nearPlane","farPlane","aspectRatio","isActive","priority","showFrustum","viewportX","viewportY","viewportW","viewportH","clearFlags","designResolution","pixelsPerUnit","backgroundColor","Velocity","linear","angular","Parent","entity","Children","entities","BitmapText","fontSize","align","spacing","font","SpineAnimation","skeletonPath","atlasPath","skin","animation","timeScale","playing","skeletonScale","EmitterShape","Point","Rectangle","Cone","SimulationSpace","World","Local","ParticleEasing","Linear","EaseIn","EaseOut","EaseInOut","ParticleEmitter","burstCount","burstInterval","looping","playOnStart","maxParticles","lifetimeMin","lifetimeMax","shape","shapeRadius","shapeSize","shapeAngle","speedMin","speedMax","angleSpreadMin","angleSpreadMax","startSizeMin","startSizeMax","endSizeMin","endSizeMax","sizeEasing","startColor","endColor","colorEasing","rotationMin","rotationMax","angularVelocityMin","angularVelocityMax","gravity","damping","spriteColumns","spriteRows","spriteFPS","spriteLoop","blendMode","simulationSpace","Name","SceneOwner","scene","persistent","PostProcessVolume","effects","isGlobal","weight","blendDistance","getComponentDefaults","typeName","RigidBody","bodyType","gravityScale","linearDamping","angularDamping","fixedRotation","bullet","BoxCollider","halfExtents","offset","radius","density","friction","restitution","isSensor","categoryBits","maskBits","CircleCollider","CapsuleCollider","halfHeight","SegmentCollider","point1","point2","PolygonCollider","vertices","ChainCollider","points","isLoop","RevoluteJoint","connectedEntity","anchorA","anchorB","enableMotor","motorSpeed","maxMotorTorque","enableLimit","lowerAngle","upperAngle","collideConnected","DistanceJoint","enableSpring","hertz","dampingRatio","minLength","maxLength","maxMotorForce","PrismaticJoint","axis","lowerTranslation","upperTranslation","WeldJoint","linearHertz","angularHertz","linearDampingRatio","angularDampingRatio","WheelJoint","BodyType","Static","Kinematic","Dynamic","resourceCounter","defineResource","defaultValue","Res","resource","_type","_resource","ResMut","ResMutInstance","setter","value_","setter_","modify","fn","updateValue","ResourceStorage","resources_","resMutPool_","insert","remove","getResMut","Time","delta","frameCount","KEY_PREFIX","Storage","getString","raw","setString","getNumber","num","Number","isNaN","setNumber","String","getBoolean","setBoolean","getJSON","JSON","parse","console","warn","setJSON","stringify","validateComponentData","componentName","errors","field","entries","expected","actual","expectedType","getType","actualType","formatValidationErrors","lines","join","errorHandler","setWasmErrorHandler","handler","handleWasmError","error","convertFromWasm","colorKeys","convertForWasm","PTR_LAYOUTS","ptrFn","type","UIRect","writePtrField","f32","u32","u8","ptr","byteOff","idx","nextCompNumId_","compNumIds_","WeakMap","getCompNumId","_keyIds","computeQueryCacheKey","withFilters","withoutFilters","c","sort","cppRegistry_","module_","entities_","tsStorage_","entityComponents_","builtinEntitySets_","worldVersion_","queryCache_","builtinMethodCache_","iterationDepth_","nextEntityId_","nextGeneration_","spawnCallbacks_","despawnCallbacks_","worldTick_","componentAddedTicks_","componentChangedTicks_","componentRemovedBuffer_","trackedComponents_","Set","connectCpp","cppRegistry","disconnectCpp","hasCpp","getCppRegistry","getWasmModule","spawn","isIterating","generation","registry_getGeneration","cb","despawn","destroy","ids","tick","onSpawn","callback","indexOf","splice","onDespawn","valid","entityCount","getWorldVersion","beginIteration","endIteration","resetIterationDepth","getAllEntities","from","setParent","removeParent","component","insertBuiltin","insertScript","wasmData","getBuiltinMethods","add","recordChangedTick_","getStorage","getBuiltin","getScript","cppName","bset","hasScript","tryGet","methods","storage","removeBuiltin","removeScript","reg","addFn","getFn","hasFn","removeFn","bind","filtered","merged","isNew","tracked","recordAddedTick_","hasBuiltin","recordRemovedTick_","clean","resolveGetter","ptrGetter","resolvePtrGetter_","resolveHas","resolveSetter","ptrSetter","resolvePtrSetter_","d","resolvePtrFn_","layout","getPtrFn","mod","HEAPF32","HEAPU32","HEAPU8","cached","f","createPreallocatedResult","fillPtrFields","resetQueryPool","getComponentTypes","types","registry","resolveStorages_","comps","scriptOut","builtinOut","getEntitiesWithComponents","precomputedKey","cacheKey","version","reqScript","reqBuiltin","withScript","withBuiltin","woScript","woBuiltin","smallestSet","smallestSize","Infinity","candidates","rsLen","rbLen","match","advanceTick","getWorldTick","enableChangeTracking","isAddedSince","sinceTick","isChangedSince","getRemovedEntitiesSince","entry","cleanRemovedBuffer","beforeTick","writeIdx","markChanged","Mut","_component","isMutWrapper","Added","_filterType","Changed","isAddedWrapper","isChangedWrapper","unwrapComponent","createQueryDescriptor","mutIndices","addedFilters","changedFilters","index","_components","_mutIndices","_with","_without","_addedFilters","_changedFilters","with","extraWith","without","extraWithout","Query","QueryInstance","world","descriptor","lastRunTick","world_","descriptor_","lastRunTick_","actualComponents_","allRequired_","concat","result_","mutData_","cacheKey_","getters_","mutSetters_","mutIsBuiltin_","resetTick","passesChangeFilters_","iterator","actualComponents","compCount","hasMut","hasChangeFilters","mutData","mutCount","mutSetters","getters","self","prevEntity","started","done","mutIsBuiltin","writeMut","mut","finalize","iterResult","doneResult","next","getter","return","apply","single","isEmpty","count","toArray","arr","row","Removed","RemovedQueryInstance","component_","Commands","EntityCommands","commands","components_","commands_","entityRef_","isNew_","queueInsert","queueRemove","spawnImmediate","CommandsInstance","resources","pending_","spawned_","ec","insertResource","entityRef","flush","cmd","executeCommand","defineEvent","EventBus","readBuffer_","writeBuffer_","send","event","getReadBuffer","swap","tmp","EventRegistry","register","swapAll","values","EventWriter","_event","EventReader","EventWriterInstance","bus_","EventReaderInstance","Schedule","GetWorld","systemCounter","defineSystem","params","_params","_fn","getPendingSystems","__esengine_pendingSystems","addSystem","system","schedule","Update","addStartupSystem","Startup","addSystemToSchedule","SystemRunner","eventRegistry","argsCache_","systemTicks_","removedCache_","currentLastRunTick_","timings_","eventRegistry_","setTimingEnabled","getTimings","run","args","queries","removeds","firstRun","qi","ri","param","inst","desc","resolveParam","t0","flushSystem_","then","InputState","keysDown","keysPressed","keysReleased","mouseX","mouseY","mouseButtons","mouseButtonsPressed","mouseButtonsReleased","scrollDeltaX","scrollDeltaY","isKeyDown","isKeyPressed","isKeyReleased","getMousePosition","isMouseButtonDown","isMouseButtonPressed","isMouseButtonReleased","getScrollDelta","Input","InputPlugin","target_","build","Last","inputPlugin","UICameraInfo","viewProjection","Float32Array","vpX","vpY","vpW","vpH","screenW","screenH","worldLeft","worldBottom","worldRight","worldTop","worldMouseX","worldMouseY","BlendMode","isTextureRef","resourceManager","nextMaterialId","materials","initMaterialAPI","wasmModule","getResourceManager","registerMaterialCallback","shutdownMaterialAPI","uniformBuffer","_free","materialCallbackRegistered","encodedNameCache","encoder","Material","createShader","vertexSrc","fragmentSrc","releaseShader","shader","uniforms","Normal","depthTest","dirty_","cachedBuffer_","cachedIdx_","setUniform","invalidateMaterialCache","getUniform","setBlendMode","mode","getBlendMode","setDepthTest","getShader","isValid","releaseAll","clearMaterialCache","createFromAsset","shaderHandle","properties","createInstance","sourceData","toAssetData","shaderPath","getUniforms","tex","textureId","slot","__textureRef","UNIFORM_BUFFER_SIZE","serializeUniforms","bufferPtr","_malloc","heap8","heap32","heapF32","nameBytes","TextEncoder","encode","nameLen","namePadded","ceil","materialDataProvider","materialId","outShaderIdPtr","outBlendModePtr","outUniformBufferPtr","outUniformCountPtr","ShaderSources","SPRITE_VERTEX","SPRITE_FRAGMENT","COLOR_VERTEX","COLOR_FRAGMENT","AsyncCache","cache_","failed_","getOrLoad","loader","timeout","failed","Date","expiry","aborted","loaderPromise","race","setTimeout","clearAll","MaterialLoader","shaderLoader","basePath","shaderLoader_","basePath_","load","loadInternal","loaded","fullPath","resolvePath","content","resolveShaderPath","materialPath","dir","lastIndexOf","extractAnimClipTexturePaths","paths","frame","frames","parseAnimClipData","clipPath","textureHandles","fps","atlasFrame","af","pageWidth","pageHeight","clipRegistry","registerAnimClip","clip","unregisterAnimClip","getAnimClip","clearAnimClips","SpriteAnimator","speed","currentFrame","frameTimer","spriteAnimatorSystemUpdate","deltaTime","animator","frameDuration","needsInitialApply","frameChanged","sprite","Audio","init","backend","backend_","bufferCache_","bgmHandle_","bgmVolume_","disposed_","fadeAnimId_","cancelAnimationFrame","setAssetResolver","resolver","assetResolver_","resolveUrl_","baseUrl","preload","preloadFromData","preloadAll","urls","all","playSFX","playConfig","pitch","pending","createDeferredHandle","buf","catch","playBGM","targetVolume","oldVolume","crossFade","fadeOut","fadeInDuration","fadeIn","stopAll","stopBGM","setMasterVolume","setMusicVolume","setSFXVolume","setUIVolume","muteBus","getBufferHandle","t","requestAnimationFrame","startVolume","real","p","l","texDimsCache_","tilemapCache_","registerTextureDimensions","getTextureDimensions","clearTextureDimensionsCache","registerTilemapSource","getTilemapSource","clearTilemapSourceCache","initTilemapAPI","shutdownTilemapAPI","TilemapAPI","initLayer","tileWidth","tileHeight","tilemap_initLayer","destroyLayer","tilemap_destroyLayer","setTile","tileId","tilemap_setTile","getTile","tilemap_getTile","fillRect","h","tilemap_fillRect","setTiles","tiles","bytes","byteLength","Uint16Array","tilemap_setTiles","hasLayer","tilemap_hasLayer","setRenderProps","textureHandle","tilesetColumns","uvTileW","uvTileH","sortLayer","depth","parallaxX","parallaxY","tilemap_setRenderProps","setTint","opacity","tilemap_setTint","setVisible","visible","tilemap_setVisible","setOriginEntity","layerKey","originEntity","tilemap_setOriginEntity","submitLayer","uvTileWidth","uvTileHeight","originX","originY","camLeft","camBottom","camRight","camTop","tintR","tintG","tintB","tintA","tilemap_submitLayer","setTileAnimation","Uint32Array","tilemap_setTileAnimation","advanceAnimations","dtMs","tilemap_advanceAnimations","setTileProperty","tilemap_setTileProperty","getTileProperty","tilemap_getTileProperty","flipTile","flipH","flipV","flipD","tilemap_flipTile","rotateTile","degrees","tilemap_rotateTile","setGridType","tilemap_setGridType","tileToWorld","tx","ty","tilemap_tileToWorld","floats","worldToTile","wy","tilemap_worldToTile","Tilemap","TilemapLayer","tint","parallaxFactor","parseTintColorU32","parseTintColor","s","convertGid","gid","firstGid","flags","parseTmjJson","tilewidth","tileheight","rawTilesets","tilesets","firstGids","ts","firstgid","image","columns","tileCount","tilecount","rawLayers","layers","lw","lh","rawData","tintColor","tintcolor","parallaxx","parallaxy","objectGroups","collisionTileIds","objs","objects","parsed","props","rawProps","ellipse","point","polygon","polyPts","pt","polyline","linePts","tileAnimations","tileProperties","rawTiles","tile","localId","engineId","rawAnim","tileid","tileProps","propMap","orientation","resolveRelativePath","relativePath","lastSlash","parts","split","resolved","part","pop","parseTiledMap","jsonString","resolveExternal","api","encoded","tiled_loadMap","extCount","tiled_getExternalTilesetCount","tiled_getExternalTilesetSource","tiled_freeMap","tsjContent","tsjEncoded","tsjPtr","tiled_loadExternalTileset","tiled_finalize","tiled_getMapWidth","tiled_getMapHeight","tiled_getMapTileWidth","tiled_getMapTileHeight","layerCount","tiled_getLayerCount","tiled_getLayerWidth","tiled_getLayerHeight","tileBytes","tilePtr","tiled_getLayerTiles","tiled_getLayerName","tiled_getLayerVisible","tiled_getLayerOpacity","tiled_getLayerTintColor","tiled_getLayerParallaxX","tiled_getLayerParallaxY","tilesetCount","tiled_getTilesetCount","tiled_getTilesetName","tiled_getTilesetImage","tiled_getTilesetTileWidth","tiled_getTilesetTileHeight","tiled_getTilesetColumns","tiled_getTilesetTileCount","DEG_TO_RAD","PI","generateTileCollision","mapData","collisionIds","mapWidth","mapHeight","visited","results","isCollision","col","canExpand","nextRow","mergeCollisionTiles","tileW","tileH","mapPixelH","mergedW","mergedH","worldX","worldY","loadTiledMap","firstTileset","layerIndex","generateObjectCollision","collisionEntities","mapOriginX","mapOriginY","group","tiledX","tiledY","angle","minX","minY","maxX","maxY","vx","vy","polyW","polyH","polyCX","polyCY","half","cos","sin","loadTiledCollisionObjects","tileCollisionIds","tileEntities","WrapMode","TrackType","InterpType","MIGRATIONS","track","tracks","ch","channels","kf","keyframes","interpolation","abs","outTangent","WRAP_MODE_MAP","once","pingPong","parseTrack","base","childPath","property","clips","blendIn","events","ranges","markers","time","payload","animFrames","parseTimelineAsset","to","migrateAsset","wrapMode","filter","editorMode","playMode","setEditorMode","active","isEditor","isRuntime","setPlayMode","isPlayMode","AnimTargetField","AnimTargetComponent","FIELD_MAP","PositionX","PositionY","PositionZ","ScaleX","ScaleY","ScaleZ","RotationZ","ColorR","ColorG","ColorB","ColorA","SpriteOpacity","SpriteSizeX","SpriteSizeY","OffsetMinX","OffsetMinY","OffsetMaxX","OffsetMaxY","AnchorMinX","AnchorMinY","AnchorMaxX","AnchorMaxY","PivotX","PivotY","CameraOrthoSize","COMPONENT_MAP","INTERP_TYPE_MAP","InterpType_Hermite","InterpType_Linear","InterpType_Step","InterpType_EaseIn","InterpType_EaseOut","InterpType_EaseInOut","interpTypeToNum","interp","resolveField","CustomField","allocString","str","freePtr","uploadTimelineToWasm","asset","_tl_create","totalPropertyChannels","trackInfos","uploadPropertyTrack","channelProperties","uploadSpineTrack","uploadAudioTrack","uploadActivationTrack","uploadSpriteAnimTrack","channelCount","Custom","childPtr","childLen","compPtr","compLen","pathStrings","totalPathBytes","fieldPathsPtr","pathOffset","fieldPathLensPtr","Int32Array","totalKeyframes","counts","countsPtr","dataPtr","dataArr","dOffset","inTangent","_tl_addCustomPropertyTrack","uploadCustomPropertyTrack","fieldsPtr","fieldsArr","_tl_addPropertyTrack","clipCount","floatsPtr","animPtrsPtr","animPtrs","animLensPtr","animLens","animStrPtrs","aPtr","aLen","_tl_addSpineTrack","eventCount","clipPtrsPtr","clipPtrs","clipLensPtr","clipLens","strPtrs","evt","cPtr","cLen","_tl_addAudioTrack","rangesPtr","rangesArr","end","_tl_addActivationTrack","clipPtr","clipLen","_tl_addSpriteAnimTrack","handles_","setTimelineHandle","getTimelineHandle","clearTimelineHandles","_tl_destroy","AttenuationModel","DEFAULT_SPATIAL_CONFIG","model","Inverse","refDistance","maxDistance","rolloff","calculateAttenuation","distance","range","Exponential","pow","calculatePanning","sourceX","sourceY","listenerX","listenerY","AudioSource","playOnAwake","spatial","minDistance","attenuationModel","AudioListener","AudioPlugin","activeSourceHandles_","playedEntities_","config_","activeSourceHandles","playedEntities","liveEntities","spatialListenerWarned","wasPlayMode","PreUpdate","_time","hasListener","listeners","wt","sources","srcX","srcY","attenuation","sqrt","entityId","stopAllSources","cleanup","audioPlugin","TimelinePlayer","timeline","loadedAssets_","registerTimelineAsset","textureHandles_","getTimelineTextureHandle","timelinePath","textureUuid","setNestedProperty","lastKey","resolveChildEntity","rootEntity","current","segments","segment","childrenData","childEntities","found","childId","nameData","TimelinePlugin","animFramesStates_","uiRect_clearAnimOverrides","playerData","uploadResult","resolveTrackTargets","afTracks","lastFrameIndices","_tl_isPlaying","_tl_getTime","_tl_play","_tl_setTime","_tl_pause","wrapModeNum","_tl_setWrapMode","_tl_advance","processEvents","processCustomProperties","processAnimFrames","_tl_clearResults","clearHandles","DEFAULT_DURATION","frameIndex","dur","propertyIndex","eventIndex","isEvent","_tl_setTrackTarget","decodeEventString","_tl_getEventString","len","_tl_getEventStringLen","TextDecoder","decode","_tl_getEventCount","_tl_getEventType","_tl_getEventEntity","animName","_tl_getEventIntParam","clipName","_tl_getEventFloatParam","_tl_getCustomPropertyCount","_tl_getCustomPropertyEntity","trackIndex","_tl_getCustomPropertyTrackIndex","channelIndex","_tl_getCustomPropertyChannelIndex","_tl_getCustomPropertyValue","trackInfo","componentDef","propPath","timelinePlugin","COMPONENT_ASSET_FIELDS","spine","skeletonField","atlasField","registerComponentAssetFields","getComponentAssetFields","getComponentAssetFieldDescriptors","getComponentSpineFieldDescriptor","remapEntityFields","compData","entityMap","editorId","runtimeId","migrateToUIRenderer","entityData","hasUIRect","some","spriteIdx","findIndex","hasUIRenderer","visualType","sliceBorder","spawnAndLoadEntities","sceneData","loadComponent","parentEntity","loadSceneData","loadSceneWithAssets","assetServer","assetBaseUrl","texturePathToUrl","collectAssets","assetPaths","ASSET_FIELD_HANDLERS","spines","spineKeys","skelPath","skeleton","atlas","assetHandles","loadPromises","handles","spinePromises","loadSpine","success","textureUrls","materialHandles","fontPaths","preloadSceneAssets","textureMetadata","texturePath","setTextureMetadataByPath","promises","info","loadTexture","loadMaterial","fontPath","loadBitmapFont","loadJson","texturePaths","texPromises","texPath","_assetServer","tmjPath","imagePath","tlPath","audio","animClips","textures","extractTimelineAssetPaths","registerTimelineTextureHandles","entityName","rectData","anchor","anchorMin","anchorMax","maskData","updateCameraAspectRatio","cameraEntities","camera","findEntityByName","ASSET_TYPE_REGISTRY","extensions","contentType","editorType","addressableType","wechatPackInclude","hasTransitiveDeps","MIME_MAP","png","jpg","jpeg","gif","webp","svg","bmp","mp3","wav","ogg","aac","flac","webm","skel","esmaterial","esshader","esprefab","esanim","estimeline","bmfont","fnt","extToEntry","allExtensions","ext","extractExtension","extensionOrPath","dotIndex","toLowerCase","getAssetTypeEntry","getEditorType","getAddressableType","getAddressableTypeByEditorType","isKnownAssetExtension","getAllAssetExtensions","looksLikeAssetPath","includes","getCustomExtensions","getWeChatPackOptions","getAssetMimeType","isCustomExtension","toBuildPath","registerAssetBuildTransform","transform","buildTransform","getAssetBuildTransform","AssetServer","textureCache_","shaderCache_","jsonCache_","textCache_","binaryCache_","loadedSpines_","virtualFSPaths_","fontCache_","prefabCache_","embedded_","embeddedOnly_","addressableManifest_","addressIndex_","labelIndex_","groupAssets_","spineController_","spineSkeletons_","textureRefCounts_","assetRefResolver_","canvas_","ctx_","willReadFrequently","loadShader","materialLoader_","registerEmbeddedAssets","assets","location","protocol","setEmbeddedOnly","loadTextureWithFlip","loadTextureRaw","getTexture","textureCacheKey","hasTexture","getTextureRefCount","total","flip","releaseTexture","rm","refCount","releaseBitmapFont","unloadSkeleton","cleanupVirtualFS","fs","FS","unlink","setTextureMetadata","border","right","bottom","setSpineController","controller","getSpineSkeletonHandle","atlasUrl","resolveUrl","atlasContent","fetchText","writeToVirtualFS","atlasDir","textureNames","parseAtlasTextures","loadedTextures","texName","texUrl","registerTextureWithPath","skelUrl","isBinary","skelData","fetchBinary","skelHandle","loadSkeleton","pageCount","getAtlasPageCount","pageName","getAtlasPageTextureName","glId","getTextureGLId","setAtlasPageTexture","isSpineLoaded","releaseSpine","fontEntry","loadBmfontAsset","loadFntFile","getFont","releaseFont","fetchJson","fntFile","generatedFnt","fntUrl","fntContent","pageMatch","fntDir","texInfo","setAssetRefResolver","loadPrefab","resolvePrefabRefs_","prefab","nestedPrefab","prefabPath","getMaterial","hasMaterial","loadShaderInternal","noCache","loadText","loadBinary","loadScene","loadAll","manifest","setAddressableManifest","allAssets","groups","loadAddressableAssets","groupName","groupList","address","label","labels","list","resolveAddress","loadAddressableAsset","loadByLabel","loadGroup","bundle","fonts","prefabs","binary","mat","allSettled","reason","loadTextureInternal","loadImage","createTextureFromImage","localPath","isLocalPath","toLocalPath","embedded","getEmbedded","loadImageFromSrc","imgSrc","createImageBitmap","bitmap","premultiplyAlpha","colorSpaceConversion","gl","getWebGL2Context","createTextureWebGL2","createTextureFallback","glObj","GL","currentContext","GLctx","WebGL2RenderingContext","createTexture","bindTexture","TEXTURE_2D","pixelStorei","UNPACK_FLIP_Y_WEBGL","UNPACK_PREMULTIPLY_ALPHA_WEBGL","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","REPEAT","TEXTURE_WRAP_T","generateMipmap","glTextureId","getNewId","registerExternalTexture","nextPowerOf2","clearRect","imageData","unpremultiplyAlpha","round","decodeDataUrlText","vertex","fragment","parseEsShader","vertexMatch","fragmentMatch","trim","dataUrl","atob","decodeDataUrlBinary","charCodeAt","virtualPath","ensureVirtualDir","writeFile","currentPath","analyzePath","exists","mkdir","line","trimmed","endsWith","Assets","AssetPlugin","assetPlugin","AssetRefCounter","textureRefs_","fontRefs_","materialRefs_","addTextureRef","refs","removeTextureRef","getTextureRefs","addFontRef","removeFontRef","getFontRefCount","getFontRefs","addMaterialRef","removeMaterialRef","getMaterialRefCount","getMaterialRefs","getAllTextureRefs","assetPath","getAllFontRefs","getAllMaterialRefs","removeAllRefsForEntity","getTotalRefCount","getResource","cloneComponents","cloneComponentData","remapComponentEntityRefs","idMapping","mapped","applyOverrides","overrides","override","prefabEntityId","propertyName","componentData","flattenPrefab","basePrefab","variant","instanceOverrides","combinedOverrides","flattenVariant","pe","allocateId","nestedPath","nested","rootId","nestedRoot","isRoot","rootEntityId","children","collectNestedPrefabPaths","seen","preloadNestedPrefabs","cache","instantiatePrefab","prefabCache","nextId","processed","root","PrefabServer","assetServer_","pathOrAddress","Prefabs","PrefabsPlugin","dependencies","prefabsPlugin","viewProjectionPtr","transformPtr","uniformsPtr","initDrawAPI","UNIFORMS_BUFFER_SIZE","shutdownDrawAPI","getModule","WHITE","Draw","begin","draw_begin","draw_end","thickness","draw_line","filled","draw_rect","rectOutline","draw_rectOutline","circle","center","draw_circle","circleOutline","draw_circleOutline","draw_texture","textureRotated","draw_textureRotated","setLayer","draw_setLayer","setDepth","draw_setDepth","getDrawCallCount","draw_getDrawCallCount","getPrimitiveCount","draw_getPrimitiveCount","draw_setBlendMode","draw_setDepthTest","drawMesh","geometry","draw_mesh","drawMeshWithMaterial","matData","autoTextureSlot","nameId","getUniformNameId","subarray","draw_meshWithUniforms","UNIFORM_NAME_MAP","u_time","u_color","u_intensity","u_scale","u_offset","u_param0","u_param1","u_param2","u_param3","u_param4","u_vec0","u_vec1","u_vec2","u_vec3","u_texture0","u_texture1","u_texture2","u_texture3","warnedUniforms","registerDrawCallback","unregisterDrawCallback","clearDrawCallbacks","DataType","vertexPtr","indexPtr","layoutPtr","initGeometryAPI","VERTEX_BUFFER_SIZE","INDEX_BUFFER_SIZE","LAYOUT_BUFFER_SIZE","shutdownGeometryAPI","Geometry","geometry_create","vertexCount","layoutCount","layoutArray","geometry_init","dynamic","indices","indexCount","geometry_setIndices16","geometry_setIndices32","updateVertices","geometry_updateVertices","geometry_release","geometry_isValid","createQuad","hw","hh","Float2","createCircle","u","createPolygon","nextStackId","stacks","cameraBindings","getStacks","getCameraBindings","PostProcessStack","passes_","destroyed_","addPass","floatUniforms","vec4Uniforms","removePass","clearPasses","setEnabled","pass","passName","uniform","setUniformVec4","setAllPassesEnabled","passCount","enabledPassCount","passes","isDestroyed","stack","POSTPROCESS_VERTEX","initPostProcessAPI","shutdownPostProcessAPI","PostProcess","isInitialized","shutdown","createStack","unbind","getStack","postprocess_init","postprocess_shutdown","resize","postprocess_resize","postprocess_isInitialized","setBypass","bypass","postprocess_setBypass","postprocess_begin","postprocess_end","setOutputViewport","postprocess_setOutputViewport","_applyForCamera","postprocess_clearPasses","postprocess_addPass","postprocess_setUniformFloat","postprocess_setUniformVec4","syncStackToWasm","_resetAfterCamera","_cleanupDestroyedCameras","screenStack","setScreenStack","_beginScreenCapture","postprocess_beginScreenCapture","_endScreenCapture","postprocess_endScreenCapture","_applyScreenStack","postprocess_clearScreenPasses","postprocess_addScreenPass","postprocess_setScreenUniformFloat","postprocess_setScreenUniformVec4","_executeScreenPasses","postprocess_executeScreenPasses","createBlur","createVignette","createGrayscale","createBloomExtract","createBloomKawase","iteration","toFixed","createBloomComposite","createChromaticAberration","effectRegistry","registerEffect","getEffectDef","getEffectTypes","getAllEffectDefs","factory","step","multiPass","volumeStacks","volumeShaders","syncPostProcessVolume","shaders","activeEffects","effect","uDef","cleanupPostProcessVolume","cleanupAllPostProcessVolumes","PostProcessVolumeConfigResource","getOrCreateShader","applyBlendedEffects","effectType","effectData","subPass","uniformName","uniformValue","postProcessVolumeSystem","volumeQuery","cameraQuery","volumes","_entity","volumeData","activeVolumes","factor","blended","sorted","prev","blendVolumeEffects","cameraEntity","cameraData","PostProcessPlugin","PostUpdate","cleanupVolumeSystem","postProcessPlugin","FlushReason","RenderType","RenderStage","SubmitSkipFlags","Spine","Particles","initRendererAPI","shutdownRendererAPI","Renderer","renderer_init","renderer_resize","beginFrame","renderer_beginFrame","updateTransforms","renderer_updateTransforms","_cpp","renderer_begin","renderer_flush","renderer_end","submitAll","skipFlags","renderer_submitAll","setStage","stage","renderer_setStage","createRenderTarget","renderer_createTarget","releaseRenderTarget","renderer_releaseTarget","getTargetTexture","renderer_getTargetTexture","getTargetDepthTexture","renderer_getTargetDepthTexture","setClearColor","renderer_setClearColor","setViewport","renderer_setViewport","setScissor","enable","renderer_setScissor","clearBuffers","renderer_clearBuffers","measureBitmapText","fontHandle","getStats","drawCalls","renderer_getDrawCalls","triangles","renderer_getTriangles","sprites","renderer_getSprites","renderer_getText","renderer_getSpine","meshes","renderer_getMeshes","culled","renderer_getCulled","captureNextFrame","renderer_captureNextFrame","getCapturedData","renderer_hasCapturedData","renderer_getCapturedFrameSize","renderer_getCapturedFrameData","entitiesPtr","renderer_getCapturedEntities","renderer_getCapturedEntityCount","cameraCount","renderer_getCapturedCameraCount","heap","view","DataView","entityHeap","off","getUint32","cameraIndex","getUint8","shaderId","triangleCount","dcEntityCount","entityOffset","getInt32","flushReason","scissorX","scissorY","scissorW","scissorH","scissorEnabled","stencilWrite","stencilTest","stencilRef","textureSlotUsage","decodeFrameCapture","hasCapturedData","replayToDrawCall","drawCallIndex","renderer_replayToDrawCall","replayToDrawCallImpl","getSnapshotImageData","renderer_getSnapshotSize","renderer_getSnapshotWidth","renderer_getSnapshotHeight","renderer_getSnapshotPtr","Uint8ClampedArray","flipped","rowBytes","srcOff","dstOff","ImageData","getSnapshotImpl","initGLDebugAPI","shutdownGLDebugAPI","GLDebug","gl_enableErrorCheck","disable","check","gl_checkErrors","diagnose","renderer_diagnose","RenderPipeline","lastWidth_","lastHeight_","activeScenes_","preFlushCallbacks_","setActiveScenes","scenes","addPreFlushCallback","beginScreenCapture","endScreenCapture","submitScene","viewport","_elapsed","executeDrawCallbacks","render","renderCamera","viewportPixels","vp","hasPostProcess","cbs","UIVisualType","SolidColor","NineSlice","UIRenderer","TRANSITION_CALLBACK_ID","SceneInstance","drawCallbacks","postProcessBindings","savedAlphas","loadedAssets","SceneContextImpl","instance_","app_","bindPostProcess","unbindPostProcess","setPersistent","SceneManagerState","configs_","scenes_","contexts_","additiveScenes_","pausedScenes_","sleepingScenes_","loadOrder_","activeScene_","initialScene_","transition_","switching_","loadPromises_","reset","setInitial","getInitial","isTransitioning","switchTo","transition","unload","startFadeTransition","targetScene","onStart","phase","halfDuration","alpha","updateTransition","dt","oldScene","rejectTransition","doSwitch","onComplete","loadPromise","hasResource","loadSceneData_","loadAdditive","keepPersistent","releaseSceneAssets_","orderIdx","loadOptions","systems","wrapped","wrapSceneSystem","setup","setPostProcessPassesEnabled","sleep","saved","hasSaved","bt","bitmapText","uiRenderer","wake","isPaused","isSleeping","isLoaded","getActive","getActiveScenes","getLoaded","getLoadOrder","bringToTop","getScene","getSceneStatus","SceneManager","sceneName","sceneTransitionSystem","scenesRes","sceneManagerPlugin","initSystem","manager","initial","App","systems_","runner_","running_","lastTime_","fixedTimestep_","fixedAccumulator_","maxDeltaTime_","maxFixedSteps_","pipeline_","installed_plugins_","installedPluginSet_","installedPluginNames_","pluginsFinished_","sortedSystemsCache_","error_handler_","system_error_handler_","statsEnabled_","phaseTimings_","frame_paused_","user_paused_","step_pending_","play_speed_","mainLoop","deltaMs","flushStartupSystems_","updateTime","runSchedule","First","fixedSteps","FixedPreUpdate","FixedUpdate","FixedPostUpdate","getPlugin","ctor","addPlugin","plugin","dep","addEvent","runBefore","runAfter","removeSystem","systemId","removed","pipeline","setPipeline","spineInitPromise","spineInitPromise_","physicsInitPromise","physicsInitPromise_","physicsModule","physicsModule_","waitForPhysics","isPhysicsReady","setFixedTimestep","timestep","onError","onSystemError","onWasmError","setPaused","paused","stepFrame","setPlaySpeed","getPlaySpeed","enableStats","getSystemTimings","getPhaseTimings","getEntityCount","registerScene","setInitialScene","finishPlugins_","quit","shutdowns","finish","sortSystems","nameToIndex","targetName","targetIndex","targetEntry","visiting","visit","depName","depIndex","startup","rawSystems","flushPendingSystems","IDENTITY","computeEffectiveOrthoSize","baseOrthoSize","designAspect","actualAspect","orthoForWidth","orthoForHeight","cameraInfoPool_","acquireCameraInfo","viewportRect","halfW","halfH","cameraX","cameraY","collectCameras","activeScenes","registry_getCameraEntities","owner","registry_getCanvasEntity","getCanvas","findCanvasData","cameras","getCamera","getTransform","aspect","projection","camHalfW","camHalfH","ortho","perspective","invertTranslation","cam","multiply","_orthoM","near","far","fill","rl","tb","_perspM","fovRad","tan","nf","_invTransM","_mulM","j","FillDirection","LeftToRight","RightToLeft","BottomToTop","TopToBottom","ImageType","Simple","Sliced","Tiled","Filled","FillMethod","Horizontal","Vertical","FillOrigin","Left","Right","Bottom","Top","imageType","fillMethod","fillOrigin","fillAmount","preserveAspect","tileSize","offsetMin","offsetMax","Interactable","blockRaycast","raycastTarget","computeUIRectLayout","parentRect","parentW","parentH","aLeft","aRight","aBottom","aTop","myLeft","myBottom","myRight","myTop","nativeRegistry_","computeFillAnchors","direction","computeHandleAnchors","computeFillSize","applyDirectionalFill","fillEntity","anchors","applyColorTransition","pressed","hovered","pressedColor","hoveredColor","normalColor","disabledColor","TINT_HOVER","TINT_PRESSED","applyDefaultTint","baseColor","isWordChar","wrapText","maxWidth","paragraphs","paragraph","currentLine","char","testLine","measureText","breakPos","getEntityDepth","getEffectiveWidth","getUIRectComputedWidth","getEffectiveHeight","getUIRectComputedHeight","setUIRectSizeNative","setUIRectSize","syncFillSpriteSize","normalizedValue","sliderW","sliderH","ensureComponent","makeInteractable","withChildEntity","colorEquals","setEntityColor","setEntityEnabled","colorScale","colorWithAlpha","EntityStateMap","map_","ensureInit","createSnapshotUtils","spec","extractors","take","snap","changed","snapshot","update","SCROLL_VELOCITY_THRESHOLD","DROPDOWN_HIGHLIGHT_COLOR","DROPDOWN_DEFAULT_COLOR","DROPDOWN_OPTION_COLOR","TextAlign","Center","TextVerticalAlign","Middle","TextOverflow","Visible","Clip","Ellipsis","verticalAlign","wordWrap","overflow","lineHeight","TextRenderer","shrinkCounter_","frameMaxW_","frameMaxH_","renderText","uiRect","renderTextInner","hasContainer","containerWidth","containerHeight","shouldWrap","lineHeightPx","padding","measuredWidth","measureWidth","measuredHeight","maxLines","floor","lastLine","truncateWithEllipsis","textAlign","mapAlign","textBaseline","fillStyle","save","beginPath","textBlockHeight","startY","fillText","restore","truncated","renderForEntity","getCached","cleanupOrphaned","isAlive","textSnapshot","colorR","colorG","colorB","colorA","ensureUIRenderer","TextPlugin","renderer","snapshots","effectiveRect","textPlugin","MaskMode","UIMask","UIMaskPlugin","uiMaskPlugin","intersectRects","invertMatrix4","out","a00","a01","a02","a03","a10","a11","a12","a13","a20","a21","a22","a23","a30","a31","a32","a33","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","det","screenToWorld","screenX","screenY","inverseVP","ndcX","ndcY","ww","pointInWorldRect","px","py","worldW","worldH","pivotX","pivotY","quaternionToAngle2D","rz","rw","atan2","pointInOBB","rotationZ","rotationW","localX","localY","UIInteraction","justPressed","justReleased","ButtonState","Hovered","Pressed","Disabled","Button","UIEventQueue","events_","entityTypeHandlers_","globalHandlers_","activeDispatches_","entityValidator_","on","entityOrType","typeOrHandler","typeMap","handlers","removeAll","setEntityValidator","validator","emit","currentTarget","propagationStopped","stopPropagation","dispatchToHandlers_","emitBubbled","shared","drain","query","hasEvent","invokeHandlers_","globalHandlers","UIEvents","UILayoutGeneration","UILayoutPlugin","initUIHelpers","layoutGen","uiLayout_update","transform_update","uiLayoutPlugin","vpCache","invVP","cachedVP","dirty","getInverse","createInvVPCache","emitWithBubbling","walkParentChain","ancestor","interactable","UIInteractionPlugin","hoveredEntity","pressedEntity","lastPointerX","NaN","lastPointerY","lastLayoutGen","input","interactionEntities","interaction","dpr","mouseGLX","mouseGLY","worldMouse","mouseDown","mousePressed","mouseReleased","pointerMoved","layoutChanged","needsHitTest","hitEntity","uiHitTest_update","hitEntityRaw","uiHitTest_getHitEntity","curr","buttonInitialized","buttonEntities","isFirstFrame","prevState","tinted","uiInteractionPlugin","placeholder","placeholderColor","multiline","password","readOnly","focused","cursorPos","Focusable","tabIndex","isFocused","FocusManagerState","focusedEntity","focus","blur","FocusManager","TextInputPlugin","cleanupListeners_","moduleOrNull","textureCache","ctxOrNull","wasmPixelPtr","wasmPixelSize","composing","cursorVisible","cursorTimer","lastTime","textareaOrNull","textarea","style","zIndex","autocomplete","setAttribute","appendChild","createHiddenTextarea","getFocusedTextInput","fm","onInput","syncFromTextarea","onCompositionStart","onCompositionEnd","blurCurrent","ti","newPos","selectionStart","selectionEnd","resetCursorBlink","onBlur","prevFocusedTextInput","renderTextInput","bg","displayText","repeat","textColor","textY","cursorText","cursorX","cursorY","cursorH","charCount","cursorLine","cursorCol","lineLen","partialLine","existingTex","focusManager","textInputEntities","currentFocused","activateTextarea","textInputPlugin","imageSnapshot","tileSizeX","tileSizeY","rectWidth","rectHeight","ImagePlugin","amount","imagePlugin","Toggle","isOn","graphicEntity","onColor","offColor","ToggleGroup","allowSwitchOff","setRendererColor","setRendererEnabled","TogglePlugin","initializedEntities","toggleEntities","groupFirstOn","toggle","togglesByGroup","groupEntity","hasGroup","siblings","other","otherToggle","graphic","togglePlugin","ProgressBarDirection","ProgressBar","ProgressBarPlugin","bar","progressBarPlugin","Draggable","dragThreshold","lockX","lockY","constraintMin","constraintMax","DragState","isDragging","startWorldPos","currentWorldPos","deltaWorld","totalDeltaWorld","pointerStartWorld","worldToLocalDelta","parentWt","sx","sy","DragPlugin","pendingEntity","pendingStartWorld","activeEntity","draggableEntities","bestEntity","bestLayer","bestDepth","dragState","dist","draggable","pointerDeltaX","pointerDeltaY","newWorldX","newWorldY","constrained","newX","newY","applyConstraints","prevX","prevY","localDelta","lt","dragPlugin","ScrollView","contentEntity","horizontalEnabled","verticalEnabled","contentWidth","contentHeight","scrollX","scrollY","inertia","decelerationRate","elastic","wheelSensitivity","rubberBand","pos","viewSize","smoothDamp","currentVelocity","smoothTime","omega","exp","change","temp","newValue","velocity","ScrollViewPlugin","cleanup_","states","editorSceneView","sv","lastWorldX","lastWorldY","velocityX","velocityY","contentBaseX","contentBaseY","lastAppliedX","lastAppliedY","viewW","viewH","effectiveContentW","effectiveContentH","kids","ct","cw","cr","sp","maxScrollX","maxScrollY","lerpFactor","rbX","instantVx","rbY","instantVy","maxVelX","maxVelY","scroll","overX","overY","targetX","targetY","maxOverX","maxOverY","curX","curY","scrollViewPlugin","SliderDirection","Slider","minValue","maxValue","handleEntity","wholeNumbers","computeSliderValue","localMouseX","localMouseY","syncHandleRect","handleRect","SliderPlugin","slider","oldValue","sliderPlugin","FocusPlugin","focusableEntities","setFocus","getSortedFocusables","currentIdx","reverse","nextIdx","focusPlugin","SafeArea","applyTop","applyBottom","applyLeft","applyRight","getSafeAreaInsets","safeArea","screenWidth","screenHeight","getWeChatSafeAreaInsets","getComputedStyle","documentElement","parseFloat","getPropertyValue","getWebSafeAreaInsets","SafeAreaPlugin","cachedInsets","prevScreenH","prevWorldH","onWindowResize","insetScale","sa","safeAreaPlugin","ListView","itemHeight","itemCount","overscan","activeListViewStates","setListViewRenderer","visibleStart","visibleEnd","itemEntities","ListViewPlugin","listViewStates","st","itemEntity","lv","viewHeight","viewWidth","maxScroll","startIdx","endIdx","listViewPlugin","Dropdown","selectedIndex","isOpen","listEntity","labelEntity","DropdownPlugin","dropdownStates","appearanceInitialized","normalizeListTransform","initDropdownAppearance","openDropdown","dropdown","highlightIndex","setListVisible","destroyOptions","ddWidth","ddRect","totalHeight","optEntity","optionEntities","textEntity","textEntities","updateHighlight","closeDropdown","selectOption","syncLabel","newColor","newContent","selectedText","isAnyOptionHovered","hoveredIndex","dropdownPlugin","LayoutGroup","childAlignment","reverseOrder","LayoutGroupPlugin","layoutGroupPlugin","FlexDirection","FlexWrap","JustifyContent","AlignItems","FlexContainer","wrap","justifyContent","alignItems","alignContent","gap","FlexItem","flexGrow","flexShrink","flexBasis","order","alignSelf","margin","minWidth","minHeight","maxHeight","widthPercent","heightPercent","UIRenderOrderPlugin","uiRenderOrder_update","uiRenderOrderPlugin","DARK_THEME","primary","secondary","background","surface","textSecondary","xs","sm","md","lg","xl","trackHeight","trackColor","fillColor","handleSize","handleColor","checkColor","panel","scrollView","UIThemeRes","activeTheme","initUIBuilder","getTheme","spawnUI","theme","flex","flexItem","mask","createButton","btn","onClick","onHover","createSlider","onChange","createToggle","checkSize","createProgressBar","createScrollView","contentSize","horizontal","vertical","createTextInput","onSubmit","createDropdown","items","dd","createLabel","createPanel","createFlexRow","createFlexColumn","widgetFactories","textInput","progressBar","flexRow","flexColumn","UI","destroyUI","childList","buildUI","childrenTarget","ref","transitionTo","SpineModuleController","raw_","api_","listeners_","atlasText","getLastError","pageIndex","skeletonHandle","destroyInstance","instanceId","playAnimation","addAnimation","delay","setSkin","skinName","getAnimations","getSkins","getBonePosition","boneName","xPtr","yPtr","getBoneRotation","getBounds","extractMeshBatches","batchCount","getMeshBatchCount","batches","metaPtr","texIdPtr","blendPtr","getMeshBatchVertexCount","getMeshBatchIndexCount","vertBytes","idxBytes","vertPtr","idxPtr","getMeshBatchData","setDefaultMix","setMixDuration","fromAnim","toAnim","setTrackAlpha","setAttachment","slotName","attachmentName","setIKTarget","constraintName","mix","setSlotColor","enableEvents","collectEvents","getEventCount","getEventBuffer","floatValue","intValue","clearEvents","entityListeners","typeListeners","removeAllListeners","ModuleBackend","cachedFrame_","cachedEntries_","controller_","loadEntity","setEntityProps","setAnimation","updateAll","extractAndSubmitMeshes","coreModule","submitFn","renderer_submitSpineBatchByEntity","batch","totalVertBytes","totalIdxBytes","vertBase","idxBase","vOff","iOff","call","removeEntity","SpineManager","moduleFactories","backends_","loadingBackends_","entityVersions_","coreModule_","factories_","detectVersion","ver4x","bytesRead","readVarint","ver","tryRead4xVersion","hashLen","hb","verLen","vb","tryRead3xVersion","detectVersionJson","spine_setNeedsReload","ensureBackend","updateAnimations","submitMeshes","getEntityVersion","hasModuleBackend","getModuleBackend","getEntityBackend_","hasInstance","loading","cwrap","wrapSpineModule","shift","loadPhysicsModule","wasmUrl","PhysicsDebugDraw","showColliders","showVelocity","showContacts","STATIC_COLOR","DYNAMIC_COLOR","KINEMATIC_COLOR","SENSOR_COLOR","VELOCITY_COLOR","CONTACT_COLOR","DEBUG_LINE_THICKNESS","CAPSULE_ARC_SEGMENTS","quatToAngleZ","q","bodyTypeColor","drawRotatedBox","cx","cy","pts","drawCapsule","toWorld","lx","ly","topLeft","topRight","bottomLeft","bottomRight","a0","a1","p0","p1","drawVelocityArrow","endX","endY","ARROWHEAD_ANGLE","dirX","dirY","leftX","leftY","rightX","rightY","drawPhysicsDebug","physicsApiRes","physicsEventsRes","ppu","readPixelsPerUnit","physics","rb","box","cosA","sinA","capsule","seg","p1x","p1y","p2x","p2y","poly","verts","vi","v0","v1","x0","y0","x1","y1","chain","pi","vel","getLinearVelocity","collision","collisionEnters","contactX","contactY","PhysicsEvents","collisionExits","sensorEnters","sensorExits","PhysicsAPI","PhysicsPlugin","wasmUrl_","factory_","fixedTimestep","subStepCount","contactHertz","contactDampingRatio","contactSpeed","collisionLayerMasks","trackedEntities","trackedJoints","parentedBodies","cachedProps","lastEntitySyncTick","initPromise","_physics_init","invPpu","_physics_destroyJoint","_physics_destroyBody","currentEntities","_physics_updateBodyProperties","_physics_setBodyTransform","hasParent","posX","posY","_physics_createBody","addShapeForEntity","jointEntities","joint","connected","_physics_createRevoluteJoint","_physics_createDistanceJoint","_physics_createPrismaticJoint","_physics_createWeldJoint","_physics_createWheelJoint","createPendingJoints","_physics_step","_physics_getDynamicBodyCount","_physics_getDynamicBodyTransforms","baseU32","physU32","physF32","engineMod","hasParented","registry_batchSyncPhysicsTransforms","byteLen","PHYSICS_BODY_BYTES","engineBuf","getTransformPtr","engF32","addTransform","syncTransformBuf_","PHYSICS_BODY_STRIDE","localAngle","parentData","pwt","parentAngleZ","cosH","sinH","tPtr","fi","syncDynamicTransforms","_physics_collectEvents","enterCount","_physics_getCollisionEnterCount","enterPtr","_physics_getCollisionEnterBuffer","entityA","entityB","normalX","normalY","exitCount","_physics_getCollisionExitCount","exitPtr","_physics_getCollisionExitBuffer","sensorEnterCount","_physics_getSensorEnterCount","sensorEnterPtr","_physics_getSensorEnterBuffer","sensorEntity","visitorEntity","sensorExitCount","_physics_getSensorExitCount","sensorExitPtr","_physics_getSensorExitBuffer","Physics","_fromModule","setupPhysicsDebugDraw","MAX_COLLISION_LAYERS","resolveCollisionMask","layerMasks","category","_physics_addBoxShape","_physics_addCircleShape","_physics_addCapsuleShape","_physics_addSegmentShape","byteSize","_physics_addPolygonShape","_physics_addChainShape","prototype","applyForce","force","_physics_applyForce","applyImpulse","impulse","_physics_applyImpulse","setLinearVelocity","_physics_setLinearVelocity","_physics_getLinearVelocity","setGravity","_physics_setGravity","getGravity","_physics_getGravity","setAngularVelocity","_physics_setAngularVelocity","getAngularVelocity","_physics_getAngularVelocity","applyTorque","torque","_physics_applyTorque","applyAngularImpulse","_physics_applyAngularImpulse","createRevoluteJoint","o","destroyJoint","setRevoluteMotorSpeed","_physics_setRevoluteMotorSpeed","setRevoluteMaxMotorTorque","_physics_setRevoluteMaxMotorTorque","enableRevoluteMotor","_physics_enableRevoluteMotor","enableRevoluteLimit","_physics_enableRevoluteLimit","setRevoluteLimits","lower","upper","_physics_setRevoluteLimits","getRevoluteAngle","_physics_getRevoluteAngle","getRevoluteMotorTorque","_physics_getRevoluteMotorTorque","raycast","origin","_physics_raycast","_physics_getRaycastBuffer","normal","fraction","overlapCircle","_physics_overlapCircle","_physics_getOverlapBuffer","setAwake","awake","_physics_setAwake","isAwake","_physics_isAwake","setDebugDraw","setDebugDrawConfig","FILTER_MODE_MAP","nearest","clamp","mirror","createTextureFromPixels","filterMode","createTextureEx","test","loadRuntimeScene","provider","spineManager","physicsConfig","texSettings","textureImporterSettings","descriptors","loadPixels","loadTextures","applyTextureMetadata","spineAssetInfo","assetInfoMap","spineDesc","skelRef","atlasRef","readText","readBinary","texNames","loadPixelsRaw","loadSpineAssetsToVirtualFS","fontCache","fontDesc","fntRef","texRef","texHandle","loadBitmapFonts","materialCache","shaderCache","matDesc","matRef","vertexSource","fragmentSource","shaderKey","loadMaterials","clipText","clipData","loadAnimClips","jsonText","loadTilemaps","preloadAudioClips","cacheByType","resolveSceneAssetPaths","sceneEntity","createRuntimeSceneConfig","initRuntime","firstScene","sceneOpts","spineModule","mgr","WebAssetProvider","baseUrl_","prefetch","textRefs","binaryRefs","bmfontRefs","fetches","fntFetches","resp","blob","SpineCpp","spine_update","spine_play","spine_addAnimation","spine_setSkin","spine_getBonePosition","spine_hasInstance","reloadAssets","spine_reloadAssets","spine_getAnimations","spine_getSkins","SpinePlugin","managerOrProvider","spineManager_","provider_","setSpineManager","fc","factories","versions","jsSource","wasmBytes","loadJs","loadWasm","Blob","URL","createObjectURL","import","revokeObjectURL","moduleFactory","__ESSpineModule__","createSpineFactories","spineUpdateSystem","PREVIEW_SCENE","PreviewPlugin","sceneUrl","loadPromise_","eventSource_","onMessage_","onError_","sceneUrl_","loadRuntimeData","ensureCamera","setupHotReload","waitForReady","spinePlugin","hasActiveCamera","canvasEntities","sceneCtx","transformData","href","eventsUrl","host","EventSource","log","reloadScene","msg","RenderTexture","_handle","_depth","_filter","rt","getDepthTexture","LogLevel","ConsoleLogHandler","timestamp","toISOString","level","toUpperCase","padEnd","Debug","debug","Info","Warn","Logger","handlers_","minLevel_","addHandler","setMinLevel","removeHandler","clearHandlers","defaultLogger","getLogger","setLogLevel","EasingType","EaseInQuad","EaseOutQuad","EaseInOutQuad","EaseInCubic","EaseOutCubic","EaseInOutCubic","EaseInBack","EaseOutBack","EaseInOutBack","EaseInElastic","EaseOutElastic","EaseInOutElastic","EaseOutBounce","CubicBezier","Step","TweenState","Running","Paused","Completed","Cancelled","LoopMode","Restart","PingPong","BACK_C1","BACK_C3","BACK_C2","ELASTIC_C4","ELASTIC_C5","BOUNCE_N1","BOUNCE_D1","BEZIER_EPSILON","applyEasing","bezier","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","t1","easeOutCubic","easeInOutCubic","easeInBack","easeOutBack","easeInOutBack","easeInElastic","easeOutElastic","easeInOutElastic","easeOutBounce","ix","cubicBezier","valueTweenManager","entries_","nextId_","cppSequences_","registry_","easing","bezierPoints","loopCount","loopsRemaining","sequenceNext","sequenceNextExternal","cppEntity","jsTweenId","_anim_getTweenState","easedT","infinite","cancel","getState","setBezier","setSequenceNext","setSequenceNextExternal","external","registerCppSequence","ValueTweenHandle","TweenTarget","SizeX","SizeY","TweenHandle","_anim_setTweenBezier","_anim_setSequenceNext","_anim_pauseTween","_anim_resumeTween","_anim_cancelTween","_module","_registry","initTweenAPI","shutdownTweenAPI","getRegistry","Tween","tweenEntity","_anim_createTween","tweenHandle","cancelAll","_anim_cancelAllTweens","_anim_updateTweens","AnimationPlugin","animationPlugin","initParticleAPI","shutdownParticleAPI","Particle","particle_update","particle_play","particle_stop","particle_reset","getAliveCount","particle_getAliveCount","ParticlePlugin","particlePlugin","SYNTHETIC_KEY_BASE","GRID_TYPE_MAP","orthogonal","isometric","staggered","TilemapPlugin","initializedLayers_","animatedLayers_","sourceEntityKeys_","layerState_","initializedLayers","animatedLayers","sourceEntityKeys","layerState","tilemapSyncSystem","layerEntities","currentLayerSet","layerData","dims","u16","pf","tilemapEntities","tilemap","gridType","tileset","currentTilemapSet","tilemapPlugin","formatNumber","decimals","escapeHtml","StatsOverlay","container","visible_","lastUpdateTime_","lastStats_","accumulatedTimings_","el_","cssText","positionStyle","stats","accumulateTimings_","systemTimings","render_","show","display","hide","parentElement","removeChild","timings","ms","acc","sum","sections","frameTimeMs","avg","systemsHtml","innerHTML","defaultFrameStats","phaseTimings","Stats","FrameHistory","cursor_","count_","capacity_","getLatest","getAll","STATS_COLLECT_SYSTEM_NAME","StatsCollector","deltas_","sum_","pushFrame","deltaSeconds","isFinite","getFps","getFrameTimeMs","StatsPlugin","collector_","overlay_","options_","overlay","collector","statsCollectSystem","copy","renderStats","statsPlugin","EmbeddedAssetProvider","assets_","cv","getAsset","decodeBase64ToWasm","base64","initPhysicsModule","wasmBase64","ESPhysicsModule","opts","Response","instantiateStreaming","instantiateWasmModule","initPlayableRuntime","spineModules","buildSpineManager","physicsWasmBase64","uiPlugins","basePlugins","createWebApp","spineProvider","plugins","new","Registry","glContextHandle","initRendererWithContext","initRenderer","getViewportSize","syncUICameraInfo","uiCam","vr","uiCameraSyncSystem","renderSystem","canvasEntity","running","pw","ph","_createWebApp"],"mappings":"AAWA,IAAIA,EAA0C,cAa9BC,IACZ,IAAKD,EACD,MAAM,IAAIE,MACN,8HAIR,OAAOF,CACX,UAKgBG,IACZ,OAA2B,OAApBH,CACX,UAKgBI,IACZ,OAAOJ,GAAiBK,MAAQ,IACpC,UAKgBC,IACZ,MAAiC,WAA1BN,GAAiBK,IAC5B,UAKgBE,IACZ,MAAiC,QAA1BP,GAAiBK,IAC5B,CAMOG,eAAeC,EAClBC,EACAC,GAEA,OAAOV,IAAcW,MAAMF,EAAKC,EACpC,CAEOH,eAAeK,EAAiBC,GACnC,OAAOb,IAAcc,SAASD,EAClC,CAEON,eAAeQ,EAAqBF,GACvC,OAAOb,IAAcgB,aAAaH,EACtC,CAEON,eAAeU,EAAmBJ,GACrC,OAAOb,IAAckB,WAAWL,EACpC,CAMON,eAAeY,EAClBC,EACAC,GAEA,OAAOrB,IAAcsB,gBAAgBF,EAAcC,EACvD,CAEM,SAAUE,EAAqBC,EAAeC,GAChD,OAAOzB,IAAc0B,aAAaF,EAAOC,EAC7C,UAMgBE,IACZ,OAAO3B,IAAc4B,KACzB,UAMgBC,IACZ,GAA8B,WAA1B9B,GAAiBK,KAAmB,CACpC,MAAM0B,EAAIC,WACV,OAAOD,EAAEE,IAAIC,uBAAuBC,YAAc,CACtD,CACA,MAAyB,oBAAXC,QAA0BA,OAAOC,kBAAyB,CAC5E,OC7GaC,EAOT,WAAAC,CAAYC,EAAuBC,GAJ3BC,KAAAC,QAAkB,EAClBD,KAAAE,QAAkB,EAClBF,KAAAG,UAAwB,GAG5BH,KAAKI,MAAQL,EAAOpC,KACpBqC,K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CvsH,EAAI0mB,oBAAoBf,GAAS+D,KAAM8iG,GAEvCxsH,EAAIktE,UAAU/hB,IACdnrD,EAAIktE,UAAU9d,IACdpvD,EAAIktE,UAAUvjD,IACd3pB,EAAIktE,UAAUvC,IACVr+E,GAASu/H,QACT,IAAK,MAAM1+C,KAAU7gF,EAAQu/H,QACzB7rH,EAAIktE,UAAUC,GAItB,OAAOntE,CACX,C0E/wBW6sH,CAAcxzH,EAAQ,IAAK/M,EAASu/H,WAC/C,CpJjCIlgI,EqJXQyL"}\ No newline at end of filediff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex aada7d00a..3ecb0bd62 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -856,20 +856,46 @@ declare const AlignItems: {readonly Stretch: 3;};type AlignItems = (typeof AlignItems)[keyof typeof AlignItems];+declare const AlignContent: {+ readonly Start: 0;+ readonly Center: 1;+ readonly End: 2;+ readonly Stretch: 3;+ readonly SpaceBetween: 4;+ readonly SpaceAround: 5;+};+type AlignContent = (typeof AlignContent)[keyof typeof AlignContent];interface FlexContainerData {direction: FlexDirection;wrap: FlexWrap;justifyContent: JustifyContent;alignItems: AlignItems;+ alignContent: AlignContent;gap: Vec2;padding: Padding;}+declare const AlignSelf: {+ readonly Auto: 0;+ readonly Start: 1;+ readonly Center: 2;+ readonly End: 3;+ readonly Stretch: 4;+};+type AlignSelf = (typeof AlignSelf)[keyof typeof AlignSelf];interface FlexItemData {flexGrow: number;flexShrink: number;flexBasis: number;order: number;+ alignSelf: AlignSelf;+ margin: Padding;+ minWidth: number;+ minHeight: number;+ maxWidth: number;+ maxHeight: number;+ widthPercent: number;+ heightPercent: number;}declare class UIRenderOrderPlugin implements Plugin {diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex 520a172dc..2224fa268 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -1,2 +1,2 @@-import{d as e,S as s,a as i,R as r,b as a,c,T as u,W as d,e as f,f as g,g as b,h as T,N as P,i as C,I as E,C as A,j as I,Q as R,P as F,k as z,l as B,B as H,m as W,E as D,n as N,o as G,p as Q,q as ee,r as te,s as ne,t as se,u as ie,v as oe,w as re,D as le,x as ce,y as ue,z as de,A as he,F as fe,G as pe,H as me}from"./shared/system.js";export{J as Added,K as Changed,L as Commands,M as CommandsInstance,O as DEFAULT_FALLBACK_DT,U as DEFAULT_FONT_FAMILY,V as DEFAULT_FONT_SIZE,X as DEFAULT_LINE_HEIGHT,Y as DEFAULT_MAX_DELTA_TIME,Z as DEFAULT_SPINE_SKIN,_ as DEFAULT_SPRITE_SIZE,$ as DEFAULT_TEXT_CANVAS_SIZE,a0 as EmitterShape,a1 as EntityCommands,a2 as EventReader,a3 as EventReaderInstance,a4 as EventWriter,a5 as EventWriterInstance,a6 as INVALID_FONT,a7 as INVALID_MATERIAL,a8 as LocalTransform,a9 as Mut,aa as ParticleEasing,ab as ParticleEmitter,ac as QueryInstance,ad as Removed,ae as RemovedQueryInstance,af as ShapeRenderer,ag as ShapeType,ah as SimulationSpace,ai as Velocity,aj as addStartupSystem,ak as addSystem,al as addSystemToSchedule,am as applyBuildRuntimeConfig,an as applyRuntimeConfig,ao as clearUserComponents,ap as color,aq as defineEvent,ar as defineTag,as as getComponentDefaults,at as getUserComponent,au as isBuiltinComponent,av as quat,aw as registerComponentEntityFields,ax as unregisterComponent,ay as vec2,az as vec3,aA as vec4}from"./shared/system.js";import{M as ge,R as ye,B as _e,C as xe,a as we,i as be,b as ve,D as Se,u as Te,g as Pe,r as Me,c as Ce,s as Ee,d as Ae,e as Ie,f as Re,P as ke}from"./shared/index.js";export{h as BlendMode,j as CapsuleCollider,k as ChainCollider,l as Physics,m as PhysicsEvents,n as PolygonCollider,o as RevoluteJoint,S as SegmentCollider,p as ShaderSources,q as isRuntime,t as isTextureRef,v as loadPhysicsModule,w as registerMaterialCallback,x as setEditorMode,y as setPlayMode}from"./shared/index.js";import{SpineManager as Fe,SpinePlugin as Ue}from"./spine/index.js";let Le=null;function ze(){if(!Le)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return Le}function Be(){return null!==Le}function Oe(){return Le?.name??null}function He(){return"wechat"===Le?.name}function $e(){return"web"===Le?.name}async function We(e,t){return ze().fetch(e,t)}async function De(e){return ze().readFile(e)}async function Xe(e){return ze().readTextFile(e)}async function Ne(e){return ze().fileExists(e)}async function Ye(e,t){return ze().instantiateWasm(e,t)}function Ve(e,t){return ze().createCanvas(e,t)}function je(){return ze().now()}function Ge(){if("wechat"===Le?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class qe{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof qe?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class Ke{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new qe(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new qe(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new qe(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new qe(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new qe(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new qe(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class Je{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class Ze{constructor(e,t,n,s,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=n,this.poolNode_=s,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class Qe{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new Ke(this.context_,e.mixerConfig),this.pool_=new Je(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const n=this.loadingUrls_.get(e);if(n)return n;const s=this.doLoadBuffer_(e);this.loadingUrls_.set(e,s);try{return await s}finally{this.loadingUrls_.delete(e)}}async loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const n=this.urlToId_.get(e);if(void 0!==n&&this.buffers_.has(n)){return{id:n,duration:this.buffers_.get(n).duration}}let s;try{s=await this.context_.decodeAudioData(t)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,s),this.urlToId_.set(e,i),{id:i,duration:s.duration}}async doLoadBuffer_(e){const t=await ze().readFile(e);return this.loadBufferFromData(e,t)}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const n=this.buffers_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=n,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(s.gain),s.source=i,s.gain.gain.value=t.volume??1,s.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;s.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new Ze(l,i,n,s,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const et=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 loadImagePixels(e){const t=this.createImage();await new Promise((n,s)=>{t.crossOrigin="anonymous",t.onload=()=>n(),t.onerror=()=>s(new Error(`Failed to load image: ${e}`)),t.src=e});const n=this.createCanvas(t.width,t.height).getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(s.data.buffer)}}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),i=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},r=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{t.preventDefault();const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{t.preventDefault();const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=t=>{t.preventDefault(),e.onPointerUp(0)},d=()=>{e.onPointerUp(0)},h=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",o),n.addEventListener("mousedown",r),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l,{passive:!1}),n.addEventListener("touchmove",c,{passive:!1}),n.addEventListener("touchend",u,{passive:!1}),n.addEventListener("touchcancel",d),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("touchcancel",d),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new Qe}getStorageItem(e){return localStorage.getItem(e)}setStorageItem(e,t){localStorage.setItem(e,t)}removeStorageItem(e){localStorage.removeItem(e)}clearStorage(e){const t=[];for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);null!==s&&s.startsWith(e)&&t.push(s)}for(const e of t)localStorage.removeItem(e)}},tt="esengine:",nt={getString(e,t){const n=ze().getStorageItem(tt+e);return null!==n?n:t},setString(e,t){ze().setStorageItem(tt+e,t)},getNumber(e,t){const n=ze().getStorageItem(tt+e);if(null===n)return t;const s=Number(n);return Number.isNaN(s)?t:s},setNumber(e,t){ze().setStorageItem(tt+e,String(t))},getBoolean(e,t){const n=ze().getStorageItem(tt+e);return null===n?t:"true"===n},setBoolean(e,t){ze().setStorageItem(tt+e,String(t))},getJSON(e,t){const n=ze().getStorageItem(tt+e);if(null===n)return t;try{return JSON.parse(n)}catch(n){return console.warn(`[Storage] Failed to parse JSON for key "${e}"`,n),t}},setJSON(e,t){ze().setStorageItem(tt+e,JSON.stringify(t))},remove(e){ze().removeStorageItem(tt+e)},has:e=>null!==ze().getStorageItem(tt+e),clear(){ze().clearStorage(tt)}};class st{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 it=e(new st,"Input");class ot{constructor(e){this.target_=e??null}build(e){const t=new st;e.insertResource(it,t),ze().bindInputEvents({onKeyDown(e){t.keysDown.has(e)||t.keysPressed.add(e),t.keysDown.add(e)},onKeyUp(e){t.keysDown.delete(e),t.keysReleased.add(e)},onPointerMove(e,n){t.mouseX=e,t.mouseY=n},onPointerDown(e,n,s){t.mouseX=n,t.mouseY=s,t.mouseButtons.add(e),t.mouseButtonsPressed.add(e)},onPointerUp(e){t.mouseButtons.delete(e),t.mouseButtonsReleased.add(e)},onWheel(e,n){t.scrollDeltaX+=e,t.scrollDeltaY+=n}},this.target_??void 0),e.addSystemToSchedule(s.Last,i([],()=>{t.keysPressed.clear(),t.keysReleased.clear(),t.mouseButtonsPressed.clear(),t.mouseButtonsReleased.clear(),t.scrollDeltaX=0,t.scrollDeltaY=0},{name:"InputClearSystem"}))}}const rt=new ot,lt=e({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");class ct{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=r.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const a={promise:null,aborted:!1};a.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{a.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return a.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,a);try{return await a.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+r.assetFailureCooldown}),t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`)),t}}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()}clearAll(){this.cache_.clear(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class ut{constructor(e,t=""){this.cache_=new ct,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(ge.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ge.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await Ne(t))throw new Error(`Material file not found: ${t}`);const n=await Xe(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:ge.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){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function ht(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0,duration:e.duration};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const ft=new Map;function pt(e){ft.set(e.name,e)}function mt(e){ft.delete(e)}function gt(e){return ft.get(e)}function yt(){ft.clear()}const _t=a("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function xt(e,t){const n=e.getEntitiesWithComponents([_t]);for(const s of n){const n=e.get(s,_t);if(!n.enabled||!n.playing||!n.clip)continue;const i=ft.get(n.clip);if(!i||0===i.frames.length)continue;const o=i.frames[n.currentFrame],r=o?.duration??1/(i.fps*n.speed),a=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let l=a;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),l=!0),l&&e.has(s,c)){const t=i.frames[n.currentFrame],o=e.get(s,c);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,c,o)}l&&e.insert(s,_t,n)}}class wt{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static setAssetResolver(e){this.assetResolver_=e}static resolveUrl_(e){return!this.baseUrl||e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}/${e}`}static async preload(e){if(this.bufferCache_.has(e))return;if(this.assetResolver_){const t=this.assetResolver_(e);if(t)return this.preloadFromData(e,t)}const t=await this.backend_.loadBuffer(this.resolveUrl_(e));this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}wt.mixer_=null,wt.bufferCache_=new Map,wt.bgmHandle_=null,wt.bgmVolume_=1,wt.fadeAnimId_=0,wt.disposed_=!1,wt.assetResolver_=null,wt.baseUrl="";const bt=new Map,vt=new Map;function St(e,t,n){bt.set(e,{width:t,height:n})}function Tt(e){return bt.get(e)}function Pt(){bt.clear()}function Mt(e,t){vt.set(e,t)}function Ct(e){return vt.get(e)}function Et(){vt.clear()}let At=null;function It(e){At=e}function Rt(){At=null}const kt={initLayer(e,t,n,s,i){At?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){At?.tilemap_destroyLayer(e)},setTile(e,t,n,s){At?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>At?At.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){At?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!At)return;const n=t.byteLength,s=At._malloc(n);new Uint16Array(At.HEAPU8.buffer,s,t.length).set(t),At.tilemap_setTiles(e,s,t.length),At._free(s)},hasLayer:e=>!!At&&At.tilemap_hasLayer(e),setRenderProps(e,t,n,s,i,o,r,a,l){At?.tilemap_setRenderProps(e,t,n,s,i,o,r,a,l)},setTint(e,t,n,s,i,o){At?.tilemap_setTint(e,t,n,s,i,o)},setVisible(e,t){At?.tilemap_setVisible(e,t)},setOriginEntity(e,t){At?.tilemap_setOriginEntity(e,t)},submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,x){At?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,x)},setTileAnimation(e,t,n){if(!At||0===n.length)return;const s=new Uint32Array(2*n.length);for(let e=0;e<n.length;e++)s[2*e]=n[e].tileId,s[2*e+1]=n[e].duration;const i=s.byteLength,o=At._malloc(i);new Uint32Array(At.HEAPU8.buffer,o,s.length).set(s),At.tilemap_setTileAnimation(e,t,o,n.length),At._free(o)},advanceAnimations(e,t){At?.tilemap_advanceAnimations(e,t)},setTileProperty(e,t,n,s){At?.tilemap_setTileProperty(e,t,n,s)},getTileProperty:(e,t,n,s)=>At?At.tilemap_getTileProperty(e,t,n,s):"",flipTile(e,t,n,s,i,o){At?.tilemap_flipTile(e,t,n,s,i,o)},rotateTile(e,t,n,s){At?.tilemap_rotateTile(e,t,n,s)},setGridType(e,t){At?.tilemap_setGridType(e,t)},tileToWorld(e,t,n,s,i){if(!At)return{x:0,y:0};const o=At.tilemap_tileToWorld(e,t,n,s,i),r=new Float32Array(At.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}},worldToTile(e,t,n,s,i){if(!At)return{x:0,y:0};const o=At.tilemap_worldToTile(e,t,n,s,i),r=new Float32Array(At.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}}},Ft=a("Tilemap",{source:""}),Ut=a("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function Lt(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function zt(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function Bt(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function Ot(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=Bt(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=zt(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:f})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}const h=new Map,f=new Map;if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.id,s=n+1,i=e.animation;if(i&&i.length>0){const e=i.map(e=>({tileId:(e.tileid??0)+1,duration:e.duration??100}));h.set(s,e)}const o=e.properties;if(o){const e=new Map;for(const s of o){const i=s.name;"collision"===i&&!0===s.value&&d.push(n+t),e.set(i,String(s.value))}e.size>0&&f.set(s,e)}}}return{width:t,height:n,tileWidth:s,tileHeight:i,orientation:e.orientation??"orthogonal",layers:c,tilesets:r,objectGroups:u,collisionTileIds:d,tileAnimations:h,tileProperties:f}}function Ht(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function $t(e,t){const n=At;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),orientation:"orthogonal",layers:[],tilesets:[],objectGroups:[],collisionTileIds:[],tileAnimations:new Map,tileProperties:new Map},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?Lt(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch(e){return console.warn("[Tiled] Failed to parse tilemap",e),n.tiled_freeMap(r),null}}const Wt=Math.PI/180;function Dt(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,d=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,h=o+(d-t.row*c)-.5*s,f=e.spawn();e.insert(f,u,{position:{x:r,y:h,z:0}}),e.insert(f,ye,{bodyType:_e.Static}),e.insert(f,we,{halfExtents:{x:.5*n,y:.5*s}}),a.push(f)}return a}function Xt(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,u,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Ut,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,d=s+(o-l)-.5*t.height,h=-t.rotation*Wt;if(e.insert(r,u,{position:{x:c,y:d,z:0}}),e.insert(r,ye,{bodyType:_e.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,xe,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,we,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,we,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,u,{position:{x:c,y:d,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=Dt(e,n,t,a,0,0);i.push(...s)}return i}const Nt=0,Yt=1,Vt=2,jt="property",Gt="spine",qt="spriteAnim",Kt="audio",Jt="activation",Zt="marker",Qt="customEvent",en="animFrames",tn="hermite",nn="linear",sn="step",on="easeIn",rn="easeOut",ln="easeInOut",cn=[["1.0","1.1",e=>{for(const t of e.tracks??[])if(t.type===jt)for(const e of t.channels??[])for(const t of e.keyframes??[])t.interpolation||Math.abs(t.outTangent)>=1e5&&(t.interpolation="step",t.outTangent=0)}]];const un={once:Nt,loop:Yt,pingPong:Vt};function dn(e){const t={name:e.name??"",childPath:e.childPath??""};switch(e.type){case jt:return{...t,type:jt,component:e.component??"",channels:(e.channels??[]).map(e=>({property:e.property,keyframes:e.keyframes??[]}))};case Gt:return{...t,type:Gt,clips:e.clips??[],blendIn:e.blendIn??0};case qt:return{...t,type:qt,clip:e.clip??"",startTime:e.startTime??0};case Kt:return{...t,type:Kt,events:e.events??[]};case Jt:return{...t,type:Jt,ranges:e.ranges??[]};case Zt:return{...t,type:Zt,markers:e.markers??[]};case Qt:return{...t,type:Qt,events:(e.events??[]).map(e=>({time:e.time??0,name:e.name??"",payload:e.payload??{}}))};case en:return{...t,type:en,frames:(e.animFrames??[]).map(e=>({texture:e.texture??"",duration:e.duration}))};default:return console.warn(`[Timeline] Unknown track type: ${e.type}, skipping`),null}}function hn(e){return function(e){let t=e.version??"1.0";for(const[n,s,i]of cn)t===n&&(i(e),t=s);e.version="1.1"}(e),{version:"1.1",type:"timeline",duration:e.duration??0,wrapMode:(t=e.wrapMode,t?un[t]??Nt:Nt),tracks:(e.tracks??[]).map(dn).filter(e=>null!==e)};var t}var fn,pn;!function(e){e[e.PositionX=0]="PositionX",e[e.PositionY=1]="PositionY",e[e.PositionZ=2]="PositionZ",e[e.ScaleX=3]="ScaleX",e[e.ScaleY=4]="ScaleY",e[e.ScaleZ=5]="ScaleZ",e[e.RotationZ=6]="RotationZ",e[e.ColorR=7]="ColorR",e[e.ColorG=8]="ColorG",e[e.ColorB=9]="ColorB",e[e.ColorA=10]="ColorA",e[e.SpriteOpacity=11]="SpriteOpacity",e[e.SpriteSizeX=12]="SpriteSizeX",e[e.SpriteSizeY=13]="SpriteSizeY",e[e.OffsetMinX=14]="OffsetMinX",e[e.OffsetMinY=15]="OffsetMinY",e[e.OffsetMaxX=16]="OffsetMaxX",e[e.OffsetMaxY=17]="OffsetMaxY",e[e.AnchorMinX=18]="AnchorMinX",e[e.AnchorMinY=19]="AnchorMinY",e[e.AnchorMaxX=20]="AnchorMaxX",e[e.AnchorMaxY=21]="AnchorMaxY",e[e.PivotX=22]="PivotX",e[e.PivotY=23]="PivotY",e[e.CameraOrthoSize=24]="CameraOrthoSize",e[e.CustomField=25]="CustomField"}(fn||(fn={})),function(e){e[e.Transform=0]="Transform",e[e.Sprite=1]="Sprite",e[e.UIRect=2]="UIRect",e[e.Camera=3]="Camera",e[e.Custom=4]="Custom"}(pn||(pn={}));const mn={Transform:{"position.x":fn.PositionX,"position.y":fn.PositionY,"position.z":fn.PositionZ,"scale.x":fn.ScaleX,"scale.y":fn.ScaleY,"scale.z":fn.ScaleZ,rotation:fn.RotationZ},Sprite:{"color.r":fn.ColorR,"color.g":fn.ColorG,"color.b":fn.ColorB,"color.a":fn.ColorA,opacity:fn.SpriteOpacity,"size.x":fn.SpriteSizeX,"size.y":fn.SpriteSizeY},UIRect:{"offsetMin.x":fn.OffsetMinX,"offsetMin.y":fn.OffsetMinY,"offsetMax.x":fn.OffsetMaxX,"offsetMax.y":fn.OffsetMaxY,"anchorMin.x":fn.AnchorMinX,"anchorMin.y":fn.AnchorMinY,"anchorMax.x":fn.AnchorMaxX,"anchorMax.y":fn.AnchorMaxY,"pivot.x":fn.PivotX,"pivot.y":fn.PivotY},Camera:{orthoSize:fn.CameraOrthoSize}},gn={Transform:pn.Transform,Sprite:pn.Sprite,UIRect:pn.UIRect,Camera:pn.Camera},yn={[tn]:0,[nn]:1,[sn]:2,[on]:3,[rn]:4,[ln]:5};function _n(e){return e?yn[e]??0:0}function xn(e,t){return mn[e]?.[t]??fn.CustomField}function wn(e,t){const n=(new TextEncoder).encode(t),s=e._malloc(n.length);return new Uint8Array(e.HEAPU8.buffer,s,n.length).set(n),[s,n.length]}function bn(e,t){e._free(t)}function vn(e,t){const n=e._tl_create(t.duration,t.wrapMode);if(!n)return{handle:0,tracks:[],totalPropertyChannels:0};const s=[];let i=0;for(const o of t.tracks)switch(o.type){case jt:Sn(e,n,o),s.push({type:"property",component:o.component,childPath:o.childPath,channelProperties:o.channels.map(e=>e.property)}),i+=o.channels.length;break;case Gt:Tn(e,n,o),s.push({type:"spine",childPath:o.childPath});break;case Kt:Pn(e,n,o),s.push({type:"audio",childPath:o.childPath});break;case Jt:Mn(e,n,o),s.push({type:"activation",childPath:o.childPath});break;case qt:Cn(e,n,o),s.push({type:"spriteAnim",childPath:o.childPath})}return{handle:n,tracks:s,totalPropertyChannels:i}}function Sn(e,t,n){const s=e,i=n.channels.length,o=gn[n.component]??pn.Custom;if(o===pn.Custom)return void function(e,t,n){const s=e,i=n.channels.length,[o,r]=wn(e,n.childPath),[a,l]=wn(e,n.component),c=n.channels.map(e=>(new TextEncoder).encode(e.property));let u=0;for(const e of c)u+=e.length;const d=s._malloc(u);let h=0;for(const e of c)new Uint8Array(s.HEAPU8.buffer,d+h,e.length).set(e),h+=e.length;const f=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,f,i).set(c.map(e=>e.length));let p=0;const m=[];for(const e of n.channels)m.push(e.keyframes.length),p+=e.keyframes.length;const g=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,g,i).set(m);const y=s._malloc(5*p*4),_=new Float32Array(s.HEAPU8.buffer,y,5*p);let x=0;for(const e of n.channels)for(const t of e.keyframes)_[x++]=t.time,_[x++]=t.value,_[x++]=t.inTangent,_[x++]=t.outTangent,_[x++]=_n(t.interpolation);e._tl_addCustomPropertyTrack(t,o,r,a,l,d,f,i,y,g),bn(e,o),bn(e,a),bn(e,d),bn(e,f),bn(e,g),bn(e,y)}(e,t,n);const[r,a]=wn(e,n.childPath),l=s._malloc(i),c=new Uint8Array(s.HEAPU8.buffer,l,i);for(let e=0;e<i;e++)c[e]=xn(n.component,n.channels[e].property);let u=0;const d=[];for(const e of n.channels)d.push(e.keyframes.length),u+=e.keyframes.length;const h=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,h,i).set(d);const f=s._malloc(5*u*4),p=new Float32Array(s.HEAPU8.buffer,f,5*u);let m=0;for(const e of n.channels)for(const t of e.keyframes)p[m++]=t.time,p[m++]=t.value,p[m++]=t.inTangent,p[m++]=t.outTangent,p[m++]=_n(t.interpolation);e._tl_addPropertyTrack(t,r,a,o,l,i,f,h),bn(e,r),bn(e,l),bn(e,h),bn(e,f)}function Tn(e,t,n){if(n.type!==Gt)return;const s=e,[i,o]=wn(e,n.childPath),r=n.clips.length,a=s._malloc(4*r*4),l=new Float32Array(s.HEAPU8.buffer,a,4*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),d=s._malloc(4*r),h=new Int32Array(s.HEAPU8.buffer,d,r),f=[];for(let t=0;t<r;t++){const s=n.clips[t];l[4*t]=s.start,l[4*t+1]=s.duration,l[4*t+2]=s.speed,l[4*t+3]=s.loop?1:0;const[i,o]=wn(e,s.animation);u[t]=i,h[t]=o,f.push(i)}e._tl_addSpineTrack(t,i,o,a,c,d,r,n.blendIn),bn(e,i),bn(e,a),bn(e,c),bn(e,d);for(const t of f)bn(e,t)}function Pn(e,t,n){if(n.type!==Kt)return;const s=e,[i,o]=wn(e,n.childPath),r=n.events.length,a=s._malloc(2*r*4),l=new Float32Array(s.HEAPU8.buffer,a,2*r),c=s._malloc(4*r),u=new Uint32Array(s.HEAPU8.buffer,c,r),d=s._malloc(4*r),h=new Int32Array(s.HEAPU8.buffer,d,r),f=[];for(let t=0;t<r;t++){const s=n.events[t];l[2*t]=s.time,l[2*t+1]=s.volume;const[i,o]=wn(e,s.clip);u[t]=i,h[t]=o,f.push(i)}e._tl_addAudioTrack(t,i,o,a,c,d,r),bn(e,i),bn(e,a),bn(e,c),bn(e,d);for(const t of f)bn(e,t)}function Mn(e,t,n){if(n.type!==Jt)return;const s=e,[i,o]=wn(e,n.childPath),r=s._malloc(2*n.ranges.length*4),a=new Float32Array(s.HEAPU8.buffer,r,2*n.ranges.length);for(let e=0;e<n.ranges.length;e++)a[2*e]=n.ranges[e].start,a[2*e+1]=n.ranges[e].end;e._tl_addActivationTrack(t,i,o,r,n.ranges.length),bn(e,i),bn(e,r)}function Cn(e,t,n){if(n.type!==qt)return;const[s,i]=wn(e,n.childPath),[o,r]=wn(e,n.clip);e._tl_addSpriteAnimTrack(t,s,i,o,r,n.startTime),bn(e,s),bn(e,o)}const En=new Map;let An=null;function In(e,t){En.set(e,t)}function Rn(e){return En.get(e)}function kn(){if(An)for(const e of En.values())An._tl_destroy(e);En.clear()}var Fn;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Fn||(Fn={}));const Un={model:Fn.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Ln(e,t=Un){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case Fn.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case Fn.Inverse:a=s/Math.max(r,s);break;case Fn.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function zn(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const Bn=a("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Fn.Inverse,rolloff:1,priority:0,enabled:!0}),On=a("AudioListener",{enabled:!0});class Hn{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const t=ze().createAudioBackend(),n=this.config_;t.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const o=t.mixer;wt.init(t,o),o&&(void 0!==n.masterVolume&&(o.master.volume=n.masterVolume),void 0!==n.musicVolume&&(o.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(o.sfx.volume=n.sfxVolume));const r=new Map;this.activeSourceHandles_=r;const a=new Set;this.playedEntities_=a;const l=new Set;let c=!1,u=!1;e.addSystemToSchedule(s.PreUpdate,i([f(g)],n=>{if(!(!be()||ve()))return void(u&&(c=!1,u=!1));u=!0;const s=e.world;let i=0,o=0,h=!1;const f=s.getEntitiesWithComponents([On,d]);for(const e of f){if(s.get(e,On).enabled){const t=s.get(e,d);i=t.position.x,o=t.position.y,h=!0;break}}const p=s.getEntitiesWithComponents([Bn]);l.clear();for(const e of p){const n=s.get(e,Bn);if(!n.enabled||!n.clip)continue;const u=e;if(l.add(u),n.playOnAwake&&!a.has(u)&&!r.has(u)&&t.isReady){const e=wt.getBufferHandle(n.clip);if(e){const s=t.play(e,{bus:n.bus,volume:n.volume,loop:n.loop,playbackRate:n.pitch});r.set(u,s),a.add(u)}else console.warn(`[AudioPlugin] playOnAwake: clip "${n.clip}" not preloaded`)}if(n.spatial&&r.has(u)){const t=r.get(u);if(!t.isPlaying){r.delete(u);continue}h||c||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),c=!0);const a=s.tryGet?.(e,d),l=a?.position.x??0,f=a?.position.y??0,p=l-i,m=f-o,g=Ln(Math.sqrt(p*p+m*m),{model:n.attenuationModel,refDistance:n.minDistance,maxDistance:n.maxDistance,rolloff:n.rolloff}),y=zn(l,0,i,0,n.maxDistance);t.setVolume(n.volume*g),t.setPan(y)}}for(const[e,t]of r)l.has(e)&&t.isPlaying||r.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),wt.dispose()}}const $n=new Hn,Wn=a("TimelinePlayer",{timeline:"",playing:!1,speed:1,wrapMode:"once"}),Dn=new Map;function Xn(e,t){Dn.set(e,t)}const Nn=new Map;function Yn(e,t){return Nn.get(e)?.get(t)??0}const Vn={once:Nt,loop:Yt,pingPong:Vt};function jn(e,t,n){const s=t.split(".");let i=e;for(let e=0;e<s.length-1;e++)if(i=i[s[e]],null==i||"object"!=typeof i)return!1;const o=s[s.length-1];return o in i&&(i[o]=n,!0)}function Gn(e,t,n){if(!n)return t;const s=b("Children"),i=b("Name");if(!s||!i)return null;let o=t;const r=n.split("/");for(const t of r){const n=e.tryGet(o,s);if(!n)return null;const r=n.entities||[];let a=null;for(const n of r){const s=e.tryGet(n,i);if(s&&s.value===t){a=n;break}}if(null===a)return null;o=a}return o}class qn{constructor(){this.name="TimelinePlugin",this.handles_=new Map,this.animFramesStates_=new Map}build(e){const t=e.world;e.addSystemToSchedule(s.Update,i([f(g)],e=>{if(be()&&!ve())return;const n=t.getWasmModule();if(!n)return;An=n;const s=t.getCppRegistry();n.uiRect_clearAnimOverrides(s);const i=t.getEntitiesWithComponents([Wn]);for(const s of i){const i=t.get(s,Wn);if(!i.timeline)continue;let o=this.handles_.get(s);if(!o){const e=Dn.get(i.timeline);if(!e)continue;if(o=vn(n,e),!o.handle)continue;this.resolveTrackTargets(t,n,o,s),this.handles_.set(s,o),In(s,o.handle);const r=e.tracks.filter(e=>e.type===en);r.length>0&&this.animFramesStates_.set(s,{tracks:r,lastFrameIndices:r.map(()=>-1)})}const r=o.handle;if(i.playing&&!n._tl_isPlaying(r)){const e=n._tl_getTime(r);0===e?n._tl_play(r):(n._tl_play(r),n._tl_setTime(r,e))}else!i.playing&&n._tl_isPlaying(r)&&n._tl_pause(r);const a=Vn[i.wrapMode]??Nt;n._tl_setWrapMode(r,a),n._tl_advance(t.getCppRegistry(),r,s,e.delta,i.speed),this.processEvents(t,n),this.processCustomProperties(t,n,o),this.processAnimFrames(t,n,s,o.handle,i.timeline),n._tl_clearResults(),!n._tl_isPlaying(r)&&i.playing&&(i.playing=!1,t.insert(s,Wn,i))}},{name:"TimelineSystem"}))}clearHandles(){this.handles_.clear(),this.animFramesStates_.clear()}cleanup(){this.handles_.clear(),this.animFramesStates_.clear(),Dn.clear()}processAnimFrames(e,t,n,s,i){const o=this.animFramesStates_.get(n);if(!o)return;const r=t._tl_getTime(s),a=b("Sprite");if(!a||!e.has(n,a))return;const l=1/12;for(let t=0;t<o.tracks.length;t++){const s=o.tracks[t].frames;if(0===s.length)continue;let c=0,u=0;for(let e=0;e<s.length;e++){const t=s[e].duration??l;if(r<c+t){u=e;break}c+=t,e===s.length-1&&(u=s.length-1)}if(u!==o.lastFrameIndices[t]){o.lastFrameIndices[t]=u;const r=Yn(i,s[u].texture);if(r){const t=e.get(n,a);t.texture=r,e.set(n,a,t)}}}}resolveTrackTargets(e,t,n,s){let i=0,o=0;for(const r of n.tracks){if(!r.childPath){"property"===r.type?i++:o++;continue}const a=Gn(e,s,r.childPath);if(null!==a){const e="property"!==r.type,s=e?o:i;t._tl_setTrackTarget(n.handle,e?1:0,s,a)}"property"===r.type?i++:o++}}decodeEventString(e,t){const n=e._tl_getEventString(t),s=e._tl_getEventStringLen(t);if(!n||s<=0)return"";const i=new Uint8Array(e.HEAPU8.buffer,n,s);return(new TextDecoder).decode(i)}processEvents(e,t){const n=t._tl_getEventCount();for(let s=0;s<n;s++){const n=t._tl_getEventType(s),i=t._tl_getEventEntity(s);switch(n){case 0:{const n=this.decodeEventString(t,s),o=0!==t._tl_getEventIntParam(s);if(e.has(i,T)){const t=e.get(i,T);t.animation=n,t.playing=!0,t.loop=o,e.set(i,T,t)}break}case 1:if(e.has(i,T)){const t=e.get(i,T);t.playing=!1,e.set(i,T,t)}break;case 2:{const n=this.decodeEventString(t,s);if(e.has(i,_t)){const t=e.get(i,_t);e.insert(i,_t,{...t,clip:n,playing:!0})}break}case 3:{const e=this.decodeEventString(t,s),n=t._tl_getEventFloatParam(s);e&&wt.playSFX(e,{volume:n});break}case 4:{const n=0!==t._tl_getEventIntParam(s);if(e.has(i,T)){const t=e.get(i,T);t.enabled=n,e.set(i,T,t)}if(e.has(i,_t)){const t=e.get(i,_t);e.insert(i,_t,{...t,enabled:n})}const o=b("Sprite");if(o&&e.has(i,o)){const t=e.get(i,o);e.set(i,o,{...t,enabled:n})}break}}}}processCustomProperties(e,t,n){const s=t._tl_getCustomPropertyCount();if(0!==s)for(let i=0;i<s;i++){const s=t._tl_getCustomPropertyEntity(i),o=t._tl_getCustomPropertyTrackIndex(i),r=t._tl_getCustomPropertyChannelIndex(i),a=t._tl_getCustomPropertyValue(i),l=n.tracks.filter(e=>"property"===e.type)[o];if(!l?.component||!l.channelProperties)continue;const c=b(l.component);if(!c||!e.has(s,c))continue;const u=e.get(s,c),d=l.channelProperties[r];d&&jn(u,d,a)&&e.set(s,c,u)}}}const Kn=new qn,Jn=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["UIRenderer",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}],["TimelinePlayer",{fields:[{field:"timeline",type:"timeline"}]}]]);function Zn(e,t){Jn.set(e,t)}function Qn(e){const t=Jn.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function es(e){return Jn.get(e)?.fields??[]}function ts(e){return Jn.get(e)?.spine??null}function ns(e,t){const n=C(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&n!==E){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:E}}}function ss(e){const t=e.components.some(e=>"UIRect"===e.type),n=e.components.findIndex(e=>"Sprite"===e.type),s=e.components.some(e=>"UIRenderer"===e.type);if(!t||-1===n||s)return;const i=e.components[n].data,o=i.texture;e.components.push({type:"UIRenderer",data:{visualType:o?2:1,texture:o??0,color:i.color??{r:1,g:1,b:1,a:1},uvOffset:i.uvOffset??{x:0,y:0},uvScale:i.uvScale??{x:1,y:1},sliceBorder:i.sliceBorder??{x:0,y:0,z:0,w:0},material:i.material??0,enabled:i.enabled??!0}}),e.components.splice(n,1)}function is(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,P,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;ss(s);const t=n.get(s.id);for(const i of s.components)ns(i,n),cs(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function os(e,t){return is(e,t)}async function rs(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of ls.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Jn.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...ls.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Jn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=is(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const ls=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),St(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=dt(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);pt(ht(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await wt.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=Ot(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=Ht(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),St(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Mt(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}],["timeline",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=hn(await t.loadJson(e));Xn(e,i);const o=function(e){const t=new Set,n=new Set,s=new Set;for(const i of e.tracks)if(i.type===Kt)for(const e of i.events)t.add(e.clip);else if(i.type===qt)i.clip&&n.add(i.clip);else if(i.type===en)for(const e of i.frames)e.texture&&s.add(e.texture);return{audio:Array.from(t),animClips:Array.from(n),textures:Array.from(s)}}(i);if(o.textures.length>0){const i=new Map,r=o.textures.map(async e=>{try{const o=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o)}catch(t){console.warn(`Failed to load animFrames texture: ${e}`,t),i.set(e,0)}});await Promise.all(r),function(e,t){Nn.set(e,t)}(e,i)}}catch(t){console.warn(`Failed to load timeline: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function cs(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=b(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function us(e,t){const n=e.getEntitiesWithComponents([A]);for(const s of n){const n=e.get(s,A);n&&(n.aspectRatio=t,e.insert(s,A,n))}}function ds(e,t){const n=e.getEntitiesWithComponents([P]);for(const s of n){const n=e.get(s,P);if(n&&n.value===t)return s}return null}const hs=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["estimeline"],contentType:"json",editorType:"timeline",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],fs={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",estimeline:"application/json",bmfont:"application/json",fnt:"text/plain"},ps=new Map,ms=new Set;for(const e of hs)for(const t of e.extensions)ps.set(t,e),ms.add(t);function gs(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function ys(e){return ps.get(gs(e))}function _s(e){return ys(e)?.editorType??"unknown"}function xs(e){return ys(e)?.addressableType??null}function ws(e){for(const t of hs)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function bs(e){return ms.has(e.toLowerCase())}function vs(){return ms}function Ss(e){return"string"==typeof e&&(!!e.includes("/")&&bs(gs(e)))}function Ts(){const e=[];for(const t of hs)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function Ps(){return Ts().map(e=>({type:"suffix",value:e}))}function Ms(e){return fs[e.toLowerCase()]}function Cs(e){const t=ys(e);return t?.wechatPackInclude??!1}function Es(e){const t=ys(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function As(e,t){for(const n of hs)n.editorType===e&&(n.buildTransform=t)}function Is(e){return ys(e)?.buildTransform}class Rs{constructor(e){this.textureCache_=new ct,this.shaderCache_=new ct,this.jsonCache_=new ct,this.textCache_=new ct,this.binaryCache_=new ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ct,this.prefabCache_=new ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=Ve(r.textCanvasSize,r.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ut(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureRefCounts_.get(s);if(void 0===i)continue;const o=this.textureCache_.get(s);if(!o)continue;const r=i-1;r<=0?(t.releaseTexture(o.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),ge.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===ys(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=ys(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of Qn(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=ts(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 rs(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((t,n)=>{const s=ze().createImage();s.crossOrigin="anonymous",s.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(s,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(s)},s.onerror=()=>n(new Error(`Failed to load image: ${e}`)),s.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return ge.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await Ne(t))throw new Error(`Shader file not found: ${e}`);const s=await Xe(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return ge.createShader(i,o)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(Es(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await Xe(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await We(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 n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return Xe(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await We(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 n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return De(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await We(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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 ks=e(null,"Assets");class Fs{build(e){const t=e.wasmModule;t?e.insertResource(ks,new Rs(t)):console.warn("AssetPlugin: No WASM module available")}}const Us=new Fs;class Ls{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function zs(e,t){const n=e.getResource(ks);n&&n.registerEmbeddedAssets(t)}function Bs(e){return e.map(e=>({type:e.type,data:JSON.parse(JSON.stringify(e.data))}))}function Os(e){return JSON.parse(JSON.stringify(e))}function Hs(e,t){for(const n of e){const e=C(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function $s(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:Os(n.componentData.data)})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}function Ws(e,t,n){const s=n.depth??0;if(s>10)throw new Error(`Prefab nesting depth exceeded 10. Check for deep or circular nesting in: ${e.name}`);if(e.basePrefab)return function(e,t,n,s){const i=e.basePrefab,o=n.visited??new Set;if(o.has(i))throw new Error(`[Prefab] Circular variant reference detected: "${i}" is already being instantiated in the current prefab chain`);const r=n.loadPrefab(i);if(!r)throw new Error(`Failed to load base prefab for variant: ${i}`);o.add(i);const a=[...e.overrides??[],...t];return Ws(r,a,{...n,visited:o,depth:s+1})}(e,t,n,s);const i=n.visited??new Set,o=new Map;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,n.allocateId());const r=[];for(const a of e.entities){if(a.nestedPrefab){const e=a.nestedPrefab.prefabPath;if(i.has(e))throw new Error(`[Prefab] Circular reference detected: "${e}" is already being instantiated in the current prefab chain`);const t=n.loadPrefab(e);if(!t)throw new Error(`Failed to load nested prefab: ${e}`);i.add(e);const l=Ws(t,a.nestedPrefab.overrides,{...n,visited:i,depth:s+1});o.set(a.prefabEntityId,l.rootId);const c=l.entities.find(e=>e.id===l.rootId);c&&(c.parent=null!==a.parent?o.get(a.parent)??null:null),r.push(...l.entities);continue}const l=o.get(a.prefabEntityId),c=a.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:a.prefabEntityId,name:a.name,parent:c?null:null!==a.parent?o.get(a.parent)??null:null,children:a.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:Bs(a.components),visible:a.visible};Hs(u.components,o),$s(u,t),r.push(u)}const a=o.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:r,rootId:a}}function Ds(e,t,n){const s=[],i=n??new Set;if(e.basePrefab&&!i.has(e.basePrefab)){i.add(e.basePrefab),s.push(e.basePrefab);const n=t(e.basePrefab);n&&s.push(...Ds(n,t,i))}for(const n of e.entities){if(!n.nestedPrefab)continue;const e=n.nestedPrefab.prefabPath;if(i.has(e))continue;i.add(e),s.push(e);const o=t(e);o&&s.push(...Ds(o,t,i))}return s}async function Xs(e,t,n,s,i=0){if(i>10)return;const o=s??new Set;if(e.basePrefab&&!o.has(e.basePrefab)&&!n.has(e.basePrefab)){o.add(e.basePrefab);const s=await t(e.basePrefab);n.set(e.basePrefab,s),await Xs(s,t,n,o,i+1)}for(const s of e.entities){if(!s.nestedPrefab)continue;const e=s.nestedPrefab.prefabPath;if(o.has(e)||n.has(e))continue;o.add(e);const r=await t(e);n.set(e,r),await Xs(r,t,n,o,i+1)}}async function Ns(e,t,n){const s=new Map;n?.assetServer&&await Xs(t,e=>n.assetServer.loadPrefab(e,n.assetBaseUrl),s);let i=0;const o={allocateId:()=>i++,loadPrefab:e=>s.get(e)??null,visited:new Set},{entities:r,rootId:a}=Ws(t,n?.overrides??[],o),l={version:t.version,name:t.name,entities:r.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},c=await rs(e,l,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),u=c.get(a);return void 0!==n?.parent&&e.setParent(u,n.parent),{root:u,entities:c}}class Ys{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ns(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vs=e(null,"Prefabs");class js{constructor(){this.name="PrefabsPlugin",this.dependencies=[ks]}build(e){const t=e.getResource(ks);e.insertResource(Vs,new Ys(e.world,t))}}const Gs=new js;var qs;!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"}(qs||(qs={}));let Ks=null,Js=0,Zs=0,Qs=0;function ei(e){Ks=e,Js=Ks._malloc(262144),Zs=Ks._malloc(65536),Qs=Ks._malloc(256)}function ti(){Ks&&(Js&&Ks._free(Js),Zs&&Ks._free(Zs),Qs&&Ks._free(Qs),Js=0,Zs=0,Qs=0),Ks=null}function ni(){if(!Ks)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ks}const si={create(e){const t=ni(),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,Js/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Qs,i).set(o),t.geometry_init(n,Js,s,Qs,i,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,Zs,s).set(e.indices),t.geometry_setIndices16(n,Zs,s)}else{new Uint32Array(t.HEAPU8.buffer,Zs,s).set(e.indices),t.geometry_setIndices32(n,Zs,s)}}return n},updateVertices(e,t,n=0){const s=ni(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,Js/4),s.geometry_updateVertices(e,Js,i,n)},release(e){e>0&&ni().geometry_release(e)},isValid:e=>!(!Ks||e<=0)&&Ks.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return si.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:qs.Float2},{name:"a_texCoord",type:qs.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 i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return si.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:qs.Float2},{name:"a_texCoord",type:qs.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return si.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:qs.Float2},{name:"a_texCoord",type:qs.Float2}],indices:new Uint16Array(r)})}};let ii=1;const oi=new Map,ri=new Map;function li(){return oi}function ci(){return ri}class ui{constructor(){this.passes_=[],this.destroyed_=!1,this.id=ii++,oi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}clearPasses(){return this.passes_.length=0,this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of ri)t===this&&ri.delete(e);oi.delete(this.id)}}}const di="#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";let hi=null;function fi(e){hi=e}function pi(){for(const e of li().values())e.destroy();li().clear(),ci().clear(),hi&&gi.isInitialized()&&gi.shutdown(),hi=null}function mi(){if(!hi)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return hi}const gi={createStack:()=>new ui,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");ci().set(e,t)},unbind(e){ci().delete(e)},getStack:e=>ci().get(e)??null,init(e,t){try{return mi().postprocess_init(e,t)}catch(n){return I(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{mi().postprocess_shutdown()}catch(e){I(e,"PostProcess.shutdown")}},resize(e,t){try{mi().postprocess_resize(e,t)}catch(n){I(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!hi)return!1;try{return hi.postprocess_isInitialized()}catch(e){return I(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{mi().postprocess_setBypass(e)}catch(e){I(e,"PostProcess.setBypass")}},begin(){try{mi().postprocess_begin()}catch(e){I(e,"PostProcess.begin")}},end(){try{mi().postprocess_end()}catch(e){I(e,"PostProcess.end")}},setOutputViewport(e,t,n,s){try{mi().postprocess_setOutputViewport(e,t,n,s)}catch(e){I(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=ci().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(gi.isInitialized()||gi.init(1,1),gi.setBypass(!1),function(e){const t=mi();try{t.postprocess_clearPasses()}catch(e){return void I(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){I(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){I(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){I(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):gi.setBypass(!0)},_resetAfterCamera(){try{mi().postprocess_clearPasses(),mi().postprocess_setBypass(!0)}catch(e){I(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of ci().keys())e(t)||ci().delete(t)},screenStack:null,setScreenStack(e){gi.screenStack=e},_beginScreenCapture(){try{mi().postprocess_beginScreenCapture()}catch(e){I(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{mi().postprocess_endScreenCapture()}catch(e){I(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=gi.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=mi();try{t.postprocess_clearScreenPasses()}catch(e){return void I(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){I(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){I(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){I(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{mi().postprocess_executeScreenPasses()}catch(e){I(e,"PostProcess._executeScreenPasses")}},createBlur:()=>ge.createShader(di,"#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:()=>ge.createShader(di,"#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 vig = 1.0 - smoothstep(1.0 - u_softness, 1.0, dist);\n fragColor = vec4(color.rgb * mix(1.0, vig, u_intensity), color.a);\n}\n"),createGrayscale:()=>ge.createShader(di,"#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"),createBloomExtract:()=>ge.createShader(di,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_threshold;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float brightness = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float knee = u_threshold * 0.5;\n float soft = brightness - u_threshold + knee;\n soft = clamp(soft, 0.0, 2.0 * knee);\n soft = soft * soft / (4.0 * knee + 0.00001);\n float contrib = max(soft, brightness - u_threshold);\n contrib /= max(brightness, 0.00001);\n fragColor = vec4(color.rgb * contrib, 1.0);\n}\n"),createBloomKawase(e){const t=`#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n float d = (${e.toFixed(1)} + 0.5) * max(u_radius, 0.5);\n vec2 ts = 1.0 / u_resolution;\n fragColor = (\n texture(u_texture, v_texCoord + vec2(-d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2(-d, d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, d) * ts)\n ) * 0.25;\n}\n`;return ge.createShader(di,t)},createBloomComposite:()=>ge.createShader(di,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform sampler2D u_sceneTexture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 blur = texture(u_texture, v_texCoord);\n vec4 scene = texture(u_sceneTexture, v_texCoord);\n fragColor = vec4(scene.rgb + blur.rgb * u_intensity, scene.a);\n}\n"),createChromaticAberration:()=>ge.createShader(di,"#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")},yi=new Map;function _i(e){yi.set(e.type,e)}function xi(e){return yi.get(e)}function wi(){return Array.from(yi.keys())}function bi(){return Array.from(yi.values())}_i({type:"blur",label:"Blur",factory:()=>gi.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),_i({type:"bloom",label:"Bloom",factory:()=>gi.createBloomExtract(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:1,step:.01,defaultValue:.4},{name:"u_intensity",label:"Intensity",min:0,max:5,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:.5,max:5,step:.1,defaultValue:1}],multiPass:[{name:"bloom_extract",factory:()=>gi.createBloomExtract()},{name:"bloom_kawase_0",factory:()=>gi.createBloomKawase(0)},{name:"bloom_kawase_1",factory:()=>gi.createBloomKawase(1)},{name:"bloom_kawase_2",factory:()=>gi.createBloomKawase(2)},{name:"bloom_kawase_3",factory:()=>gi.createBloomKawase(3)},{name:"bloom_kawase_4",factory:()=>gi.createBloomKawase(4)},{name:"bloom_composite",factory:()=>gi.createBloomComposite()}]}),_i({type:"vignette",label:"Vignette",factory:()=>gi.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:.6},{name:"u_softness",label:"Softness",min:0,max:1,step:.01,defaultValue:.5}]}),_i({type:"grayscale",label:"Grayscale",factory:()=>gi.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),_i({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>gi.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const vi=new Map,Si=new Map;function Ti(e,t){let n=vi.get(e),s=Si.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=gi.createStack(),vi.set(e,n)),s||(s=new Map,Si.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=xi(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}gi.bind(e,n)}else if(n&&(gi.unbind(e),n.destroy(),vi.delete(e)),s){for(const e of s.values())ge.releaseShader(e);Si.delete(e)}}function Pi(e){const t=vi.get(e);t&&(gi.unbind(e),t.destroy(),vi.delete(e));const n=Si.get(e);if(n){for(const e of n.values())ge.releaseShader(e);Si.delete(e)}}function Mi(){for(const e of vi.keys())Pi(e)}const Ci=e({enabled:!0},"PostProcessVolumeConfig"),Ei=new Map,Ai=new Map;function Ii(e,t){const n=Ai.get(e);if(void 0!==n)return n;const s=t();return Ai.set(e,s),s}function Ri(e,t){if(0===t.size){const t=Ei.get(e);return void(t&&(gi.unbind(e),t.destroy(),Ei.delete(e)))}let n=Ei.get(e);n||(n=gi.createStack(),Ei.set(e,n)),n.clearPasses();for(const[e,s]of t){if(!s.enabled)continue;const t=xi(e);if(t)if(t.multiPass)for(const e of t.multiPass){const t=Ii(e.name,e.factory);n.addPass(e.name,t);for(const[t,i]of s.uniforms)n.setUniform(e.name,t,i)}else{const i=Ii(e,t.factory);n.addPass(e,i);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?gi.bind(e,n):gi.unbind(e)}const ki=i([R(F,u),R(A)],(e,t)=>{const n=[];for(const[t,s,i]of e)n.push({data:s,tx:{x:i.position.x,y:i.position.y}});const s=[];for(const{data:e}of n)e.isGlobal&&s.push({data:e,factor:1});const i=s.length>0?function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(s):new Map;for(const[e,n]of t)n.isActive&&Ri(e,i)},{name:"PostProcessVolumeSystem"});class Fi{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Ci,{enabled:!0}),e.addSystemToSchedule(s.PostUpdate,ki)}cleanup(){Mi(),function(){for(const[e,t]of Ei)gi.unbind(e),t.destroy();Ei.clear();for(const e of Ai.values())ge.releaseShader(e);Ai.clear()}(),gi.setScreenStack(null)}}const Ui=new Fi;var Li,zi;!function(e){e[e.BatchFull=0]="BatchFull",e[e.TextureSlotsFull=1]="TextureSlotsFull",e[e.ScissorChange=2]="ScissorChange",e[e.StencilChange=3]="StencilChange",e[e.MaterialChange=4]="MaterialChange",e[e.BlendModeChange=5]="BlendModeChange",e[e.StageEnd=6]="StageEnd",e[e.TypeChange=7]="TypeChange",e[e.FrameEnd=8]="FrameEnd"}(Li||(Li={})),function(e){e[e.Sprite=0]="Sprite",e[e.Spine=1]="Spine",e[e.Mesh=2]="Mesh",e[e.ExternalMesh=3]="ExternalMesh",e[e.Text=4]="Text",e[e.Particle=5]="Particle",e[e.Shape=6]="Shape",e[e.UIElement=7]="UIElement"}(zi||(zi={}));var Bi;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bi||(Bi={}));const Oi={None:0,Spine:1,Particles:2};let Hi=null,$i=0;function Wi(e){Hi=e,$i=Hi._malloc(64)}function Di(){Hi&&$i&&(Hi._free($i),$i=0),Hi=null}const Xi={init(e,t){Hi?.renderer_init(e,t)},resize(e,t){Hi?.renderer_resize(e,t)},beginFrame(){Hi?.renderer_beginFrame()},updateTransforms(e){if(Hi)try{Hi.renderer_updateTransforms(e._cpp)}catch(e){I(e,"Renderer.updateTransforms")}},begin(e,t){if(Hi&&$i)try{Hi.HEAPF32.set(e,$i/4),Hi.renderer_begin($i,t??0)}catch(e){I(e,"Renderer.begin")}},flush(){try{Hi?.renderer_flush()}catch(e){I(e,"Renderer.flush")}},end(){try{Hi?.renderer_end()}catch(e){I(e,"Renderer.end")}},submitAll(e,t,n,s,i,o){if(Hi)try{Hi.renderer_submitAll(e._cpp,t,n,s,i,o)}catch(e){I(e,"Renderer.submitAll")}},setStage(e){Hi?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Hi?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Hi?.renderer_releaseTarget(e)},getTargetTexture:e=>Hi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Hi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Hi?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Hi?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Hi?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Hi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Hi?Hi.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Hi?{drawCalls:Hi.renderer_getDrawCalls(),triangles:Hi.renderer_getTriangles(),sprites:Hi.renderer_getSprites(),text:Hi.renderer_getText(),spine:Hi.renderer_getSpine?.()??0,meshes:Hi.renderer_getMeshes(),culled:Hi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0},captureNextFrame(){Hi?.renderer_captureNextFrame()},getCapturedData:()=>Hi?function(e){if(!e.renderer_hasCapturedData())return null;const t=e.renderer_getCapturedFrameSize();if(0===t)return null;const n=e.renderer_getCapturedFrameData(),s=e.renderer_getCapturedEntities(),i=e.renderer_getCapturedEntityCount(),o=e.renderer_getCapturedCameraCount(),r=e.HEAPU8,a=new DataView(r.buffer,n,76*t),l=new Uint32Array(r.buffer,s,i),c=[];for(let e=0;e<t;e++){const t=76*e,n=a.getUint32(t,!0),s=a.getUint32(t+4,!0),o=a.getUint8(t+8),r=a.getUint8(t+9),u=a.getUint8(t+10),d=a.getUint32(t+12,!0),h=a.getUint32(t+16,!0),f=a.getUint32(t+20,!0),p=a.getUint32(t+24,!0),m=a.getUint32(t+28,!0),g=a.getUint32(t+32,!0),y=a.getUint32(t+36,!0),_=a.getInt32(t+40,!0),x=a.getUint8(t+44),w=a.getInt32(t+48,!0),b=a.getInt32(t+52,!0),v=a.getInt32(t+56,!0),S=a.getInt32(t+60,!0),T=0!==a.getUint8(t+64),P=0!==a.getUint8(t+65),M=0!==a.getUint8(t+66),C=a.getInt32(t+68,!0),E=a.getUint8(t+72),A=[];for(let e=0;e<g&&y+e<i;e++)A.push(l[y+e]);c.push({index:n,cameraIndex:s,stage:o,type:r,blendMode:u,textureId:d,materialId:h,shaderId:f,vertexCount:p,triangleCount:m,entityCount:g,entityOffset:y,layer:_,flushReason:x,scissorX:w,scissorY:b,scissorW:v,scissorH:S,scissorEnabled:T,stencilWrite:P,stencilTest:M,stencilRef:C,textureSlotUsage:E,entities:A})}return{drawCalls:c,cameraCount:o}}(Hi):null,hasCapturedData:()=>Hi?.renderer_hasCapturedData()??!1,replayToDrawCall(e){Hi&&function(e,t){e.renderer_replayToDrawCall(t)}(Hi,e)},getSnapshotImageData:()=>Hi?function(e){const t=e.renderer_getSnapshotSize();if(0===t)return null;const n=e.renderer_getSnapshotWidth(),s=e.renderer_getSnapshotHeight();if(0===n||0===s)return null;const i=e.renderer_getSnapshotPtr(),o=e.HEAPU8,r=new Uint8ClampedArray(o.buffer,i,t),a=new Uint8ClampedArray(t),l=4*n;for(let e=0;e<s;e++){const t=e*l,n=(s-1-e)*l;a.set(r.subarray(t,t+l),n)}return new ImageData(a,n,s)}(Hi):null};let Ni=null;function Yi(e){Ni=e}function Vi(){Ni=null}const ji={enable(){Ni?.gl_enableErrorCheck(!0)},disable(){Ni?.gl_enableErrorCheck(!1)},check:e=>Ni?.gl_checkErrors(e)??0,diagnose(){Ni?.renderer_diagnose()}};class Gi{constructor(){this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null,this.preFlushCallbacks_=[]}setActiveScenes(e){this.activeScenes_=e}addPreFlushCallback(e){this.preFlushCallbacks_.push(e)}beginFrame(){Xi.beginFrame()}beginScreenCapture(){gi.screenStack&&gi.screenStack.enabledPassCount>0&&(gi.isInitialized()||gi.init(1,1),gi._applyScreenStack(),gi._beginScreenCapture())}endScreenCapture(){gi.screenStack&&gi.screenStack.enabledPassCount>0&&(gi._endScreenCapture(),gi._executeScreenPasses())}submitScene(e,t,n,s){Xi.updateTransforms(e),Xi.submitAll(e,0,n.x,n.y,n.w,n.h);for(const t of this.preFlushCallbacks_)t(e);Xi.flush(),this.executeDrawCallbacks(t,s)}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Xi.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Xi.beginFrame(),Xi.setViewport(0,0,s,i),Xi.clearBuffers(3),Xi.begin(n),this.submitScene(t,n,{x:0,y:0,w:s,h:i},o),Xi.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==gi.getStack(r);a&&(gi._applyForCamera(r),gi.resize(s.w,s.h),gi.setOutputViewport(s.x,s.y,s.w,s.h),gi.begin()),Xi.setViewport(s.x,s.y,s.w,s.h),Xi.setScissor(s.x,s.y,s.w,s.h,!0),Xi.clearBuffers(i),Xi.setScissor(0,0,0,0,!1),Xi.begin(n),this.submitScene(t,n,s,o),Xi.end(),a&&(gi.end(),gi._resetAfterCamera())}executeDrawCallbacks(e,t){const n=Pe();if(n.size>0){Se.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Se.end();for(const e of s)Te(e)}}}const qi={None:0,SolidColor:1,Image:2,NineSlice:3},Ki=z("UIRenderer",{visualType:qi.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),Ji="__scene_transition_overlay__";class Zi{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Qi{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,B,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Me(e,t,this.instance_.config.name)}bindPostProcess(e,t){gi.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){gi.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,B)){const n=this.app_.world.get(e,B);n.persistent=t,this.app_.world.insert(e,B,n)}}}class eo{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())Te(t);for(const t of e.postProcessBindings.keys())gi.unbind(t)}this.transition_&&(Te(Ji),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise((n,s)=>{const i=t.duration??r.sceneTransitionDuration,o=t.color??{...r.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:i,color:o,targetScene:e,options:t,resolve:n,reject:s},Me(Ji,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;Se.setLayer(9999),Se.setDepth(9999),Se.rect({x:0,y:0},{x:2e4,y:2e4},{r:o.r,g:o.g,b:o.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{reject:t}=this.transition_;this.transition_=null,Te(Ji),t(e)}})().catch(()=>{})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Te(Ji),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Zi(t);this.scenes_.set(e,n);const s=new Qi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ks)?this.app_.getResource(ks):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Zi(t);this.scenes_.set(e,n);const s=new Qi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ks)?this.app_.getResource(ks):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,B)){if(this.app_.world.get(e,B).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Te(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())gi.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(ks)&&(i.assetServer=this.app_.getResource(ks));const o=await rs(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,B,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=no(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(ks)?this.app_.getResource(ks):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)ge.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,c)){const t=n.get(e,c);s.sprite=t.color.a,t.color.a=0,n.insert(e,c,t),i=!0}if(n.has(e,T)){const t=n.get(e,T);s.spine=t.color.a,t.color.a=0,n.insert(e,T,t),i=!0}if(n.has(e,H)){const t=n.get(e,H);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,H,t),i=!0}if(n.has(e,Ki)){const t=n.get(e,Ki);s.uiRenderer=t.color.a,t.color.a=0,n.insert(e,Ki,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,c)){const t=n.get(e,c);t.color.a=s.sprite,n.insert(e,c,t)}if(void 0!==s.spine&&n.has(e,T)){const t=n.get(e,T);t.color.a=s.spine,n.insert(e,T,t)}if(void 0!==s.bitmapText&&n.has(e,H)){const t=n.get(e,H);t.color.a=s.bitmapText,n.insert(e,H,t)}if(void 0!==s.uiRenderer&&n.has(e,Ki)){const t=n.get(e,Ki);t.color.a=s.uiRenderer,n.insert(e,Ki,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const to=e(null,"SceneManager");function no(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(to).getSceneStatus(t)&&n._fn(...s)}}}const so=i([W(to),f(g)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),io={name:"SceneManager",build(e){const t=new eo(e);e.insertResource(to,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(to),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(s.Startup,n),e.addSystemToSchedule(s.Last,so)}};class oo{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new D,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=async()=>{if(!this.running_)return;const e=je(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(s.Last);else{await this.runSchedule(s.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(s.FixedPreUpdate),await this.runSchedule(s.FixedUpdate),await this.runSchedule(s.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(s.PreUpdate),await this.runSchedule(s.Update),await this.runSchedule(s.PostUpdate),await this.runSchedule(s.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new N,this.resources_=new G;for(const e of Object.values(s))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new oo}getPlugin(e){return this.installed_plugins_.find(t=>t instanceof e)}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(s.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(s.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}async waitForPhysics(){this.physicsInitPromise_?await this.physicsInitPromise_:console.warn("[ESEngine] No PhysicsPlugin installed, waitForPhysics() is a no-op")}get isPhysicsReady(){return null!=this.physicsModule_}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return ne(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(to).register(e),this}setInitialScene(e){return this.getResource(to).setInitial(e),this}async tick(e){if(this.runner_||(this.runner_=new Q(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(g)||this.resources_.insert(g,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_()),await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(s.Last);else{await this.runSchedule(s.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(s.FixedPreUpdate),await this.runSchedule(s.FixedUpdate),await this.runSchedule(s.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(s.PreUpdate),await this.runSchedule(s.Update),await this.runSchedule(s.PostUpdate),await this.runSchedule(s.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}async run(){this.running_||(this.running_=!0,this.runner_=new Q(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(g,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),await this.flushStartupSystems_(),this.lastTime_=je(),this.mainLoop())}quit(){this.running_=!1,Ce();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Vi,Di,pi,ti,Ee,Ae];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){console.warn("[App] Shutdown despawn error:",e)}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}async flushStartupSystems_(){const e=this.systems_.get(s.Startup);0!==e.length&&(this.sortedSystemsCache_.delete(s.Startup),await this.runSchedule(s.Startup),e.length=0,this.sortedSystemsCache_.delete(s.Startup))}async runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const i=this.phaseTimings_?performance.now():0;for(const e of n)try{const t=this.runner_.run(e.system);t instanceof Promise&&await t}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(s[e],performance.now()-i)}updateTime(e){const t=this.resources_.get(g);t.delta=e,t.elapsed+=e,t.frameCount++}}function ro(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const lo=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function co(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case te.FixedWidth:return o;case te.FixedHeight:return r;case te.Expand:return Math.max(o,r);case te.Shrink:return Math.min(o,r);case te.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const uo=[];function ho(e){if(e<uo.length)return uo[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return uo.push(t),t}function fo(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,B);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,d=0;if(i.projectionType===ee.Orthographic){if(d=i.orthoSize,l){d=co(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=mo(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=yo(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=xo(o.position.x,o.position.y,o.position.z),f=ho(c.length);f.entity=e,f.viewProjection.set(bo(a,h)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=d,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const po=new Float32Array(16);function mo(e,t,n,s,i,o){const r=po;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const go=new Float32Array(16);function yo(e,t,n,s){const i=go;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const _o=new Float32Array(16);function xo(e,t,n){const s=_o;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}const wo=new Float32Array(16);function bo(e,t){const n=wo;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const vo={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},So={Simple:0,Sliced:1,Tiled:2,Filled:3},To={Horizontal:0,Vertical:1},Po={Left:0,Right:1,Bottom:2,Top:3},Mo=a("Image",{texture:se,color:{r:1,g:1,b:1,a:1},imageType:So.Simple,fillMethod:To.Horizontal,fillOrigin:Po.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Co=z("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}}),Eo=z("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0});function Ao(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=d+n.y-i.y*r.y,g=p+i.y):(p=d+n.y,g=h+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}let Io=null,Ro=null;function ko(e,t){switch(e){case vo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vo.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vo.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Fo(e,t){switch(e){case vo.RightToLeft:return{anchorMin:{x:1-t,y:.5},anchorMax:{x:1-t,y:.5}};case vo.BottomToTop:return{anchorMin:{x:.5,y:t},anchorMax:{x:.5,y:t}};case vo.TopToBottom:return{anchorMin:{x:.5,y:1-t},anchorMax:{x:.5,y:1-t}};default:return{anchorMin:{x:t,y:.5},anchorMax:{x:t,y:.5}}}}function Uo(e,t,n,s){switch(e){case vo.BottomToTop:case vo.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Lo(e,t,n,s){if(!e.has(t,Co))return;const i=e.get(t,Co),o=ko(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Co,i)}function zo(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}const Bo=1.15,Oo=.75;function Ho(e,t,n,s){return t?n?{r:e.r*Oo,g:e.g*Oo,b:e.b*Oo,a:e.a}:s?{r:Math.min(1,e.r*Bo),g:Math.min(1,e.g*Bo),b:Math.min(1,e.b*Bo),a:e.a}:{...e}:{r:.5*e.r,g:.5*e.g,b:.5*e.b,a:.6*e.a}}function $o(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Wo(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if($o(r.charCodeAt(0))&&s.length>0&&$o(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!$o(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Do(e){let t=1;for(;t<e;)t*=2;return t}function Xo(e,t){let n=0,s=t;for(;e.has(s,ie);){const t=e.get(s,ie).entity;if(!e.valid(t))break;n++,s=t}return n}function No(e,t){if(Io&&Ro){const e=Io.getUIRectComputedWidth(Ro,t);if(e>0)return e}return e.size.x}function Yo(e,t){if(Io&&Ro){const e=Io.getUIRectComputedHeight(Ro,t);if(e>0)return e}return e.size.y}function Vo(e,t,n){Io&&Ro&&Io.setUIRectSize(Ro,e,t,n)}function jo(e,t,n,s,i,o){if(!e.has(t,c))return;const r=e.get(t,c);let a,l;switch(n){case vo.BottomToTop:case vo.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,c,r))}function Go(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function qo(e,t){Go(e,t,Eo,{enabled:!0,blockRaycast:!0,raycastTarget:!0})}function Ko(e,t,n){0!==t&&e.valid(t)&&n(t)}function Jo(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a}function Zo(e,t,n){if(e.has(t,Mo)){const s=e.get(t,Mo);Jo(s.color,n)||(s.color=n,e.insert(t,Mo,s))}else if(e.has(t,c)){const s=e.get(t,c);Jo(s.color,n)||(s.color=n,e.insert(t,c,s))}else if(e.has(t,Ki)){const s=e.get(t,Ki);Jo(s.color,n)||(s.color=n,e.insert(t,Ki,s))}}function Qo(e,t,n){if(e.has(t,Mo)){const s=e.get(t,Mo);s.enabled!==n&&(s.enabled=n,e.insert(t,Mo,s))}else if(e.has(t,c)){const s=e.get(t,c);s.enabled!==n&&(s.enabled=n,e.insert(t,c,s))}else if(e.has(t,Ki)){const s=e.get(t,Ki);s.enabled!==n&&(s.enabled=n,e.insert(t,Ki,s))}}function er(e,t){return{r:Math.min(1,e.r*t),g:Math.min(1,e.g*t),b:Math.min(1,e.b*t),a:e.a}}function tr(e,t){return{r:e.r,g:e.g,b:e.b,a:t}}class nr{constructor(){this.map_=new Map}get(e){return this.map_.get(e)}set(e,t){this.map_.set(e,t)}delete(e){this.map_.delete(e)}has(e){return this.map_.has(e)}cleanup(e){for(const[t]of this.map_)e.valid(t)||this.map_.delete(t)}ensureInit(e,t){let n=this.map_.get(e);return n||(n=t(),this.map_.set(e,n)),n}clear(){this.map_.clear()}[Symbol.iterator](){return this.map_[Symbol.iterator]()}}function sr(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const ir=.1,or={r:.3,g:.5,b:.8,a:1},rr={r:.9,g:.9,b:.9,a:1},lr={r:.95,g:.95,b:.95,a:1},cr={Left:0,Center:1,Right:2},ur={Top:0,Middle:1,Bottom:2},dr={Visible:0,Clip:1,Ellipsis:2},hr=a("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:cr.Left,verticalAlign:ur.Top,wordWrap:!0,overflow:dr.Visible,lineHeight:1.2});class fr{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=Ve(r.textCanvasSize,r.textCanvasSize);const t=this.canvas.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("TextRenderer: failed to create 2D canvas context");this.ctx=t}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Do(this.frameMaxW_)),e.height=Math.max(e.height,Do(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Do(this.frameMaxW_),e.height=Do(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Wo(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=i?Math.ceil(o):d+2*u,p=i?Math.ceil(r):h+2*u;if(i&&e.overflow===dr.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Do(f)),s.height=Math.max(s.height,Do(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===dr.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case ur.Top:w=u;break;case ur.Middle:w=u+(p-2*u-x)/2;break;case ur.Bottom:w=p-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let s;switch(e.align){case cr.Left:s=u;break;case cr.Center:s=f/2;break;case cr.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===dr.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),T=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const M=T.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case cr.Left:return"left";case cr.Center:return"center";case cr.Right:return"right"}}}const pr=sr({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?No(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0});function mr(e,t){e.has(t,Ki)||e.insert(t,Ki,{visualType:qi.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class gr{build(e){oe("Text",hr);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new fr(t),o=e.world,r=new Map;e.addSystemToSchedule(s.PreUpdate,i([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>o.valid(e)&&o.has(e,hr));for(const e of r.keys())if(!o.valid(e)||!o.has(e,hr)){if(o.valid(e)&&o.has(e,Ki)){const t=o.get(e,Ki);t.texture=0,t.visualType=qi.None,o.insert(e,Ki,t)}r.delete(e)}const e=o.getEntitiesWithComponents([hr]);for(const t of e){const e=o.get(t,hr),s=o.has(t,Co)?o.get(t,Co):null,i={text:e,uiRect:s,entity:t},a=r.get(t);if(a&&!pr.changed(a,i)){if(o.has(t,Ki)&&0!==o.get(t,Ki).texture)continue}mr(o,t);const l=s?{size:{x:No(s,t),y:Yo(s,t)}}:null,c=n.renderForEntity(t,e,l),u=o.get(t,Ki);u.texture=c.textureHandle,u.visualType=qi.Image,u.color={r:1,g:1,b:1,a:1},u.uvOffset={x:0,y:0},u.uvScale={x:1,y:1},o.insert(t,Ki,u),s&&Vo(t,c.width,c.height),r.set(t,pr.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const yr=new gr,_r=0,xr=z("UIMask",{enabled:!0,mode:_r});class wr{build(e){oe("UIMask",xr)}}const br=new wr;function vr(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=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,i-n),h:Math.max(0,o-s)}}function Sr(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=s*l-i*a,w=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,T=o*u-r*c,P=d*g-h*m,M=d*y-f*m,C=d*_-p*m,E=h*y-f*g,A=h*_-p*g,I=f*_-p*y;let R=x*I-w*A+b*E+v*C-S*M+T*P;return 0===R||(R=1/R,n[0]=(l*I-c*A+u*E)*R,n[1]=(o*A-i*I-r*E)*R,n[2]=(g*T-y*S+_*v)*R,n[3]=(f*S-h*T-p*v)*R,n[4]=(c*C-a*I-u*M)*R,n[5]=(s*I-o*C+r*M)*R,n[6]=(y*b-m*T-_*w)*R,n[7]=(d*T-f*b+p*w)*R,n[8]=(a*A-l*C+u*P)*R,n[9]=(i*C-s*A-r*P)*R,n[10]=(m*S-g*b+_*x)*R,n[11]=(h*b-d*S-p*x)*R,n[12]=(l*M-a*E-c*P)*R,n[13]=(s*E-i*M+o*P)*R,n[14]=(g*w-m*v-y*x)*R,n[15]=(d*v-h*w+f*x)*R),n}function Tr(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function Pr(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function Mr(e,t){return 2*Math.atan2(e,t)}function Cr(e,t,n,s,i,o,r,a,l,c){if(0===l&&1===c)return Pr(e,t,n,s,i,o,r,a);const u=Mr(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-n,p=t-s,m=f*h-p*d+n,g=f*d+p*h+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}const Er=z("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Ar={Normal:0,Hovered:1,Pressed:2,Disabled:3},Ir=a("Button",{state:Ar.Normal,transition:null});class Rr{constructor(){this.events_=[],this.entityTypeHandlers_=new Map,this.globalHandlers_=new Map,this.activeDispatches_=new Set,this.entityValidator_=null}on(e,t,n){if(void 0!==n){const s=e,i=t;let o=this.entityTypeHandlers_.get(s);o||(o=new Map,this.entityTypeHandlers_.set(s,o));let r=o.get(i);r||(r=[],o.set(i,r)),r.push(n);let a=!1;return()=>{if(a)return;a=!0;const e=o.get(i);if(e){const t=e.indexOf(n);-1!==t&&e.splice(t,1)}}}{const n=e,s=t;let i=this.globalHandlers_.get(n);i||(i=[],this.globalHandlers_.set(n,i)),i.push(s);let o=!1;return()=>{if(o)return;o=!0;const e=this.globalHandlers_.get(n);if(e){const t=e.indexOf(s);-1!==t&&e.splice(t,1)}}}}removeAll(e){this.entityTypeHandlers_.delete(e)}setEntityValidator(e){this.entityValidator_=e}emit(e,t,n){const s={entity:e,type:t,target:n??e,currentTarget:e,propagationStopped:!1,stopPropagation(){this.propagationStopped=!0}};this.events_.push(s);const i=`${e}:${t}`;return this.activeDispatches_.has(i)||(this.activeDispatches_.add(i),this.dispatchToHandlers_(s),this.activeDispatches_.delete(i)),s}emitBubbled(e,t,n,s){const i={entity:e,type:t,target:n,currentTarget:e,propagationStopped:!1,stopPropagation(){s.propagationStopped=!0}};this.events_.push(i);const o=`${e}:${t}`;this.activeDispatches_.has(o)||(this.activeDispatches_.add(o),this.dispatchToHandlers_(i),this.activeDispatches_.delete(o))}drain(){if(this.entityValidator_)for(const e of this.entityTypeHandlers_.keys())this.entityValidator_(e)||this.entityTypeHandlers_.delete(e);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)}dispatchToHandlers_(e){const t=this.entityTypeHandlers_.get(e.entity);if(t){const n=t.get(e.type);n&&this.invokeHandlers_([...n],e)}const n=this.globalHandlers_.get(e.type);n&&this.invokeHandlers_([...n],e)}invokeHandlers_(e,t){for(const n of e)try{n(t)}catch(e){console.error(`UIEvent handler error [${t.type}]:`,e)}}}const kr=e(new Rr,"UIEvents"),Fr=e({generation:0},"UILayoutGeneration");class Ur{build(e){oe("UIRect",Co),oe("UIRenderer",Ki);const t=e.world,n=e.wasmModule,o=t.getCppRegistry();!function(e,t){Io=e,Ro=t}(n,o);const r={generation:0};e.insertResource(Fr,r);e.addSystemToSchedule(s.PreUpdate,i([f(lt)],e=>{e.valid&&(n.uiLayout_update(o,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.transform_update(o),r.generation++)},{name:"UILayoutSystem"})),e.addSystemToSchedule(s.PostUpdate,i([f(lt)],e=>{e.valid&&(n.uiLayout_update(o,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),r.generation++)},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(s.PostUpdate,i([],()=>{n.transform_update(o)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Lr=new Ur,zr=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(Sr(t,e),n=!1),e)}}();function Br(e,t,n,s){const i=t.emit(n,s,n);!function(e,t,n){let s=t;for(;e.has(s,ie);){const t=e.get(s,ie).entity;if(!e.valid(t))break;if(n(t))return;s=t}}(e,n,o=>{if(i.propagationStopped)return!0;if(!e.has(o,Eo))return!1;const r=e.get(o,Eo);return r.enabled&&t.emitBubbled(o,s,n,i),r.blockRaycast})}class Or{build(e){oe("Interactable",Eo),oe("Button",Ir);const t=e.world,n=e.wasmModule,o=t.getCppRegistry(),r=new Rr;r.setEntityValidator(e=>t.valid(e)),e.insertResource(kr,r);let a=null,l=null,c=NaN,u=NaN,d=-1;e.addSystemToSchedule(s.PreUpdate,i([f(it),f(lt),f(Fr)],(e,s,i)=>{if(r.drain(),be()&&!ve())return;const h=t.getEntitiesWithComponents([Er]);for(const e of h){const n=t.get(e,Er);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Er,n))}if(!s.valid)return;const f=Ge(),p=e.mouseX*f,m=s.screenH-e.mouseY*f;zr.update(s.viewProjection);const g=Tr(p,m,zr.getInverse(s.viewProjection),s.vpX,s.vpY,s.vpW,s.vpH);s.worldMouseX=g.x,s.worldMouseY=g.y;const y=e.isMouseButtonDown(0),_=e.isMouseButtonPressed(0),x=e.isMouseButtonReleased(0),w=g.x!==c||g.y!==u,b=i.generation!==d,v=w||b||(_||x);c=g.x,u=g.y,d=i.generation;let S=a;if(v){n.uiHitTest_update(o,g.x,g.y,y,_,x);const e=n.uiHitTest_getHitEntity();S=4294967295===e?null:e}if(null===a||t.valid(a)||(a=null),a!==S){if(null!==a&&t.valid(a)&&t.has(a,Er)){const e=t.get(a,Er);e.hovered=!1,t.insert(a,Er,e),r.emit(a,"hover_exit")}if(null!==S){Go(t,S,Er);const e=t.get(S,Er);e.hovered=!0,t.insert(S,Er,e),r.emit(S,"hover_enter")}a=S}if(_&&null!==S){const e=t.get(S,Er);e.pressed=!0,e.justPressed=!0,t.insert(S,Er,e),l=S,Br(t,r,S,"press")}if(x&&null!==l){if(t.valid(l)&&t.has(l,Er)){const e=t.get(l,Er);e.pressed=!1,e.justReleased=!0,t.insert(l,Er,e),Br(t,r,l,"release"),l===a&&Br(t,r,l,"click")}l=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const h=new Set;e.addSystemToSchedule(s.Update,i([],()=>{for(const e of h)t.valid(e)||h.delete(e);const e=t.getEntitiesWithComponents([Ir]);for(const n of e){if(Go(t,n,Eo,{enabled:!0}),!t.has(n,Er))continue;const e=t.get(n,Er),s=t.get(n,Ir),i=t.get(n,Eo),o=!h.has(n),r=s.state;if(i.enabled?e.pressed?s.state=Ar.Pressed:e.hovered?s.state=Ar.Hovered:s.state=Ar.Normal:s.state=Ar.Disabled,o&&h.add(n),(o||r!==s.state)&&s.transition){const o=zo(s.transition,i.enabled,e.pressed,e.hovered);Zo(t,n,o)}else if((o||r!==s.state)&&!s.transition&&t.has(n,Mo)){const s=Ho(t.get(n,Mo).color,i.enabled,e.pressed,e.hovered);Zo(t,n,s)}}},{name:"ButtonSystem"}))}}const Hr=new Or,$r=a("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Wr=a("Focusable",{tabIndex:0,isFocused:!1});class Dr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Xr=e(new Dr,"FocusManager");class Nr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(oe("TextInput",$r),be()&&!ve())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=t,o=e.world,a=new Map,l=Ve(r.textCanvasSize,64),c=l.getContext("2d",{willReadFrequently:!0});if(!c)return void console.warn("TextInputPlugin: failed to create 2D canvas context");const u=c;let d=0,h=0,p=!1,m=!0,g=0,y=0;const _=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!_)return;const x=_;function w(){const t=e.getResource(Xr);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return o.valid(n)&&o.has(n,$r)?n:null}const b=()=>{p||null===w()||M()},v=()=>{p=!0},S=()=>{p=!1,M()},T=t=>{const n=w();if(null===n)return;if("Escape"===t.key)return void C();const s=o.get(n,$r);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(kr).emit(n,"submit"),void C()}let i=s.cursorPos;"ArrowLeft"===t.key?i=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?i=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?i=0:"End"===t.key&&(i=s.value.length),i!==s.cursorPos&&(s.cursorPos=i,x.selectionStart=i,x.selectionEnd=i,s.dirty=!0,E())},P=()=>{const t=w();if(null!==t){const n=o.get(t,$r);n.focused=!1,n.dirty=!0;e.getResource(Xr).blur()}};function M(){const t=w();if(null===t)return;const n=o.get(t,$r);if(n.readOnly)return;let s=x.value;if(n.maxLength>0&&s.length>n.maxLength&&(s=s.substring(0,n.maxLength),x.value=s),s!==n.value){n.value=s;e.getResource(kr).emit(t,"change")}n.cursorPos=x.selectionStart??s.length,n.dirty=!0,E()}function C(){const t=w();if(null!==t){const e=o.get(t,$r);e.focused=!1,e.dirty=!0}e.getResource(Xr).blur(),x.blur()}function E(){m=!0,g=0}x.addEventListener("input",b),x.addEventListener("compositionstart",v),x.addEventListener("compositionend",S),x.addEventListener("keydown",T),x.addEventListener("blur",P),this.cleanupListeners_=()=>{x.removeEventListener("input",b),x.removeEventListener("compositionstart",v),x.removeEventListener("compositionend",S),x.removeEventListener("keydown",T),x.removeEventListener("blur",P),x.remove();const e=n.getResourceManager();for(const t of a.values())e.releaseTexture(t);a.clear(),0!==d&&(n._free(d),d=0,h=0)};let A=null;function I(e,t,s,i){(l.width<s||l.height<i)&&(l.width=Do(Math.max(l.width,s)),l.height=Do(Math.max(l.height,i))),u.clearRect(0,0,l.width,l.height);const r=t.backgroundColor;u.fillStyle=`rgba(${Math.round(255*r.r)}, ${Math.round(255*r.g)}, ${Math.round(255*r.b)}, ${r.a})`,u.fillRect(0,0,s,i),u.save(),u.beginPath(),u.rect(t.padding,0,s-2*t.padding,i),u.clip(),u.font=`${t.fontSize}px ${t.fontFamily}`,u.textBaseline="top",u.textAlign="left";const c=0===t.value.length,f=c?t.placeholder:t.password?"●".repeat(t.value.length):t.value,p=c?t.placeholderColor:t.color;u.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const g=Math.ceil(1.2*t.fontSize),y=t.padding;if(t.multiline){const e=Wo(u,f,s-2*y);let t=y;for(const n of e)u.fillText(n,y,t),t+=g}else{const e=(i-t.fontSize)/2;u.fillText(f,y,e)}if(t.focused&&m){const e=t.password?"●".repeat(t.cursorPos):t.value.substring(0,t.cursorPos);let n,o,r;if(t.multiline){const e=Wo(u,t.value,s-2*y);let i=0,a=0,l=0;for(let n=0;n<e.length;n++){const s=e[n].length;if(i+s>=t.cursorPos){a=n,l=t.cursorPos-i;break}i+=s,n<e.length-1&&i<t.value.length&&"\n"===t.value[i]&&i++,a=n+1,l=0}const c=a<e.length?e[a].substring(0,l):"";n=y+u.measureText(c).width,o=y+a*g,r=g}else n=y+u.measureText(e).width,o=(i-t.fontSize)/2,r=t.fontSize;u.fillStyle=`rgba(${Math.round(255*t.color.r)}, ${Math.round(255*t.color.g)}, ${Math.round(255*t.color.b)}, ${t.color.a})`,u.fillRect(n,o,2,r)}u.restore();const _=u.getImageData(0,0,s,i),x=new Uint8Array(_.data.buffer),w=n.getResourceManager();x.length>h&&(0!==d&&n._free(d),d=n._malloc(x.length),h=x.length),n.HEAPU8.set(x,d);const b=a.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(s,i,d,x.length,1,!0);a.set(e,v);const S=o.get(e,Ki);S.texture=v,S.visualType=qi.Image,S.uvOffset={x:0,y:0},S.uvScale={x:1,y:1},S.color={r:1,g:1,b:1,a:1},S.enabled=!0,o.insert(e,Ki,S)}e.addSystemToSchedule(s.Update,i([f(Xr)],e=>{const t=o.getEntitiesWithComponents([$r]);for(const e of t)Go(o,e,Wr,{tabIndex:0,isFocused:!1}),Go(o,e,Eo,{enabled:!0,blockRaycast:!0});const n=w();if(n!==A){if(null!==A&&o.valid(A)&&o.has(A,$r)){const e=o.get(A,$r);e.focused=!1,e.dirty=!0,x.blur()}null!==n&&function(e){const t=o.get(e,$r);t.readOnly||(t.focused=!0,t.dirty=!0,x.value=t.value,x.selectionStart=t.cursorPos,x.selectionEnd=t.cursorPos,x.focus(),E())}(n),A=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(s.PreUpdate,i([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let t=0===y?0:(e-y)/1e3;y=e,t=Math.min(t,.1);const s=w();if(null!==s&&(g+=t,g>=.5)){g-=.5,m=!m;o.get(s,$r).dirty=!0}const i=n.getResourceManager();for(const[e,t]of a)o.valid(e)&&o.has(e,$r)||(i.releaseTexture(t),a.delete(e));const r=o.getEntitiesWithComponents([$r,Co]);for(const e of r){const t=o.get(e,$r);if(!t.dirty)continue;const n=o.get(e,Co),s=Math.ceil(n.size.x),i=Math.ceil(n.size.y);s<=0||i<=0||(o.has(e,Ki)||o.insert(e,Ki,{visualType:qi.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),I(e,t,s,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Yr=new Nr,Vr=sr({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?No(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});function jr(e,t){e.has(t,Ki)||e.insert(t,Ki,{visualType:qi.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Gr{build(e){oe("Image",Mo);const t=e.world,n=new Map;e.addSystemToSchedule(s.PreUpdate,i([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Mo)||n.delete(e);const e=t.getEntitiesWithComponents([Mo]);for(const s of e){const e=t.get(s,Mo),i=t.has(s,Co)?t.get(s,Co):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&t.has(s,Ki)&&!Vr.changed(r,o))continue;jr(t,s);const a=t.get(s,Ki);if(!e.enabled){a.enabled=!1,t.insert(s,Ki,a),n.set(s,Vr.take(o));continue}a.enabled=!0,a.texture=e.texture,a.color={r:e.color.r,g:e.color.g,b:e.color.b,a:e.color.a},a.material=e.material,a.uvOffset={x:0,y:0},a.uvScale={x:1,y:1};if(e.texture!==se&&0!==e.texture?e.imageType===So.Sliced?a.visualType=qi.NineSlice:a.visualType=qi.Image:a.visualType=qi.SolidColor,e.imageType===So.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));i&&No(i,s),i&&Yo(i,s),e.fillMethod===To.Horizontal?(e.fillOrigin===Po.Left||(a.uvOffset={x:1-t,y:0}),a.uvScale={x:t,y:1}):(e.fillOrigin===Po.Bottom||(a.uvOffset={x:0,y:1-t}),a.uvScale={x:1,y:t})}else if(e.imageType===So.Tiled){const t=i?No(i,s):0,n=i?Yo(i,s):0;e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale={x:t/e.tileSize.x,y:n/e.tileSize.y})}t.insert(s,Ki,a),n.set(s,Vr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const qr=new Gr,Kr=a("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null,onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1}},{entityFields:["graphicEntity","group"]}),Jr=a("ToggleGroup",{allowSwitchOff:!1});function Zr(e,t,n){if(!e.has(t,Ki))return;const s=e.get(t,Ki);s.color.r===n.r&&s.color.g===n.g&&s.color.b===n.b&&s.color.a===n.a||(s.color=n,e.insert(t,Ki,s))}function Qr(e,t,n){if(!e.has(t,Ki))return;const s=e.get(t,Ki);s.enabled!==n&&(s.enabled=n,e.insert(t,Ki,s))}class ea{build(e){oe("Toggle",Kr),oe("ToggleGroup",Jr);const t=e.world,n=new Set;e.addSystemToSchedule(s.Update,i([f(kr)],e=>{const s=t.getEntitiesWithComponents([Kr]);if(!be()||ve()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Kr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Kr,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Kr);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Go(t,n,Eo,{enabled:!0}),!t.has(n,Er))continue;const s=t.get(n,Er),i=t.get(n,Kr),r=t.get(n,Eo);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,Jr);if(i.isOn&&r){if(!t.get(s,Jr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Kr,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Kr);i.isOn&&(i.isOn=!1,t.insert(s,Kr,i),e.emit(s,"change"))}}e.emit(n,"change")}let a;if(i.transition)a=zo(i.transition,r.enabled,s.pressed,s.hovered);else{a=Ho(i.isOn?i.onColor:i.offColor,r.enabled,s.pressed,s.hovered)}Zr(t,n,a)}}for(const e of s){const n=t.get(e,Kr);Ko(t,n.graphicEntity,e=>{Qr(t,e,n.isOn)})}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const ta=new ea,na=vo,sa=a("ProgressBar",{value:0,fillEntity:0,direction:vo.LeftToRight},{entityFields:["fillEntity"]});class ia{build(e){oe("ProgressBar",sa);const t=e.world;e.addSystemToSchedule(s.PreUpdate,i([],()=>{const e=t.getEntitiesWithComponents([sa,Co]);for(const n of e){const e=t.get(n,sa),s=Math.max(0,Math.min(1,e.value));Ko(t,e.fillEntity,n=>{Lo(t,n,e.direction,s)})}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const oa=new ia,ra=a("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),la=a("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});function ca(e,t,n,s){if(!e.has(t,ie))return{x:n,y:s};const i=e.get(t,ie).entity;if(!e.valid(i)||!e.has(i,u))return{x:n,y:s};const o=e.get(i,u),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=Mr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/r,y:(n*c+s*d)/a}}class ua{build(e){oe("Draggable",ra),oe("DragState",la);const t=e.world,n=e.getResource(kr);let o=null,r={x:0,y:0},a=null;e.addSystemToSchedule(s.PreUpdate,i([f(it),f(lt)],(e,s)=>{if(be()&&!ve())return;if(!s.valid)return;const i={x:s.worldMouseX,y:s.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ra,Er]);let n=null,s=-1/0,a=-1;for(const i of e){if(!t.get(i,ra).enabled)continue;if(t.get(i,Er).hovered){let e=0;t.has(i,c)&&(e=t.get(i,c).layer);const o=Xo(t,i);(e>s||e===s&&o>=a)&&(s=e,a=o,n=i)}}if(null!==n){o=n,r={x:i.x,y:i.y},t.has(n,la)||t.insert(n,la);const e=t.get(n,la),s=t.get(n,u);e.startWorldPos={x:s.worldPosition.x,y:s.worldPosition.y},e.currentWorldPos={x:s.worldPosition.x,y:s.worldPosition.y},e.pointerStartWorld={x:i.x,y:i.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==o&&!e.isMouseButtonDown(0)){if(t.valid(o)&&t.has(o,la)){t.get(o,la).isDragging=!1}o=null}if(null!==o&&null===a){if(!t.valid(o))return void(o=null);const e=i.x-r.x,l=i.y-r.y,c=Math.sqrt(e*e+l*l),u=t.get(o,ra);if(c*(s.vpW/(s.worldRight-s.worldLeft))>=u.dragThreshold){a=o,o=null;t.get(a,la).isDragging=!0,n.emit(a,"drag_start")}}if(null!==a){if(!t.valid(a)||!t.has(a,la))return void(a=null);const s=t.get(a,la),o=t.get(a,ra),r=i.x-s.pointerStartWorld.x,l=i.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,d=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(o,s,c,d);c=h.x,d=h.y;const f=s.currentWorldPos.x,p=s.currentWorldPos.y;if(s.deltaWorld={x:c-f,y:d-p},s.currentWorldPos={x:c,y:d},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:d-s.startWorldPos.y},t.has(a,Co)){const e=t.get(a,Co),n=ca(t,a,s.deltaWorld.x,s.deltaWorld.y);e.offsetMin.x+=n.x,e.offsetMin.y+=n.y,t.insert(a,Co,e)}else if(t.has(a,u)){const e=ca(t,a,s.deltaWorld.x,s.deltaWorld.y),n=t.get(a,u);n.position.x+=e.x,n.position.y+=e.y,t.insert(a,u,n)}n.emit(a,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(a,"drag_end"),a=null)}},{name:"DragSystem"}))}}const da=new ua,ha=a("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1},{entityFields:["contentEntity"]});function fa(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function pa(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class ma{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){oe("ScrollView",ha);const t=e.world,n=new nr,o={x:0,y:0};e.addSystemToSchedule(s.PostUpdate,i([f(it),f(lt),f(g)],(e,s,i)=>{const r=be()&&!ve(),a=Math.min(i.delta,.05);n.cleanup(t),s.valid&&(o.x=s.worldMouseX,o.y=s.worldMouseY);const l=t.getEntitiesWithComponents([ha,Co]);for(const i of l){Go(t,i,xr,{enabled:!0,mode:_r});const l=t.get(i,ha),d=t.get(i,Co),h=n.ensureInit(i,()=>({isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN})),f=No(d,i),p=Yo(d,i);let m=l.contentWidth,g=l.contentHeight;if((0===m||0===g)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,re)){const e=t.get(l.contentEntity,re).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,u))continue;const e=t.get(r,u);let a=0,l=0,d=.5,h=.5;if(t.has(r,Co)){const e=t.get(r,Co);a=No(e,r)||e.size.x,l=Yo(e,r)||e.size.y,d=e.pivot.x,h=e.pivot.y}else if(t.has(r,c)){const e=t.get(r,c);a=e.size.x,l=e.size.y}const f=e.position.x-a*d,p=e.position.x+a*(1-d),m=e.position.y-l*h,g=e.position.y+l*(1-h);f<n&&(n=f),p>s&&(s=p),m<i&&(i=m),g>o&&(o=g)}0===m&&(m=s-n),0===g&&(g=o-i)}const y=Math.max(0,m-f),_=Math.max(0,g-p);if(!r&&s.valid){Go(t,i,Eo,{enabled:!0,blockRaycast:!0});const n=t.has(i,Er)?t.get(i,Er):null;if(n?.justPressed&&(h.isDragging=!0,h.lastWorldX=o.x,h.lastWorldY=o.y,h.velocityX=0,h.velocityY=0),h.isDragging&&e.isMouseButtonDown(0)){const e=o.x-h.lastWorldX,t=o.y-h.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=fa(l.scrollX,0,y,f);if(l.scrollX-=e*t,0===e)h.velocityX=0;else{const s=a>0?-e*t/a:0;h.velocityX+=(s-h.velocityX)*n}}if(l.verticalEnabled){const e=fa(l.scrollY,0,_,p);if(l.scrollY+=t*e,0===t)h.velocityY=0;else{const s=a>0?t*e/a:0;h.velocityY+=(s-h.velocityY)*n}}h.lastWorldX=o.x,h.lastWorldY=o.y}if(h.isDragging&&e.isMouseButtonReleased(0)){h.isDragging=!1;const e=5*f,t=5*p;h.velocityX=Math.max(-e,Math.min(h.velocityX,e)),h.velocityY=Math.max(-t,Math.min(h.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=fa(l.scrollY,0,_,p);l.scrollY+=t.y*l.wheelSensitivity*e,h.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=fa(l.scrollX,0,y,f);l.scrollX+=t.x*l.wheelSensitivity*e,h.velocityX=0}}}if(!h.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>y,t=l.scrollY<0||l.scrollY>_;if(l.elastic&&e){const e=l.scrollX<0?0:y,t=pa(l.scrollX,e,h.velocityX,.1,a);l.scrollX=t.value,h.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(h.velocityX)<ir&&(l.scrollX=e,h.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(h.velocityX)>ir?(h.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=h.velocityX*a):h.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:_,t=pa(l.scrollY,e,h.velocityY,.1,a);l.scrollY=t.value,h.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(h.velocityY)<ir&&(l.scrollY=e,h.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(h.velocityY)>ir?(h.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=h.velocityY*a):h.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,y)),l.scrollY=Math.max(0,Math.min(l.scrollY,_)),l.scrollX!==e&&(h.velocityX=0),l.scrollY!==t&&(h.velocityY=0)}}if(l.elastic){const e=.5*f,t=.5*p;l.scrollX=Math.max(-e,Math.min(l.scrollX,y+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,_+t))}Ko(t,l.contentEntity,e=>{if(!t.has(e,u))return;const n=t.get(e,u),s=n.position.x,i=n.position.y;(isNaN(h.lastAppliedX)||Math.abs(s-h.lastAppliedX)>.01)&&(h.contentBaseX=s),(isNaN(h.lastAppliedY)||Math.abs(i-h.lastAppliedY)>.01)&&(h.contentBaseY=i),n.position.x=h.contentBaseX-l.scrollX,n.position.y=h.contentBaseY+l.scrollY,h.lastAppliedX=n.position.x,h.lastAppliedY=n.position.y,t.insert(e,u,n)})}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{n.clear()}}}const ga=new ma,ya=vo,_a=a("Slider",{value:0,minValue:0,maxValue:1,direction:vo.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1},{entityFields:["fillEntity","handleEntity"]});function xa(e,t,n,s,i,o){const r=No(s,i)*n.worldScale.x,a=Yo(s,i)*n.worldScale.y,l=Mr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,f=d*u-h*c,p=d*c+h*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case vo.LeftToRight:return r>0?(f-m)/r:0;case vo.RightToLeft:return r>0?1-(f-m)/r:0;case vo.BottomToTop:return a>0?(p-g)/a:0;case vo.TopToBottom:return a>0?1-(p-g)/a:0}}function wa(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case vo.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=.5,e.anchorMax.x=n,e.anchorMax.y=.5;break;case vo.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=.5,e.anchorMax.x=1-n,e.anchorMax.y=.5;break;case vo.BottomToTop:e.anchorMin.x=.5,e.anchorMin.y=n,e.anchorMax.x=.5,e.anchorMax.y=n;break;case vo.TopToBottom:e.anchorMin.x=.5,e.anchorMin.y=1-n,e.anchorMax.x=.5,e.anchorMax.y=1-n}}class ba{build(e){oe("Slider",_a);const t=e.world;e.addSystemToSchedule(s.PreUpdate,i([f(it),f(lt),f(kr)],(e,n,s)=>{if(!n.valid)return;const i=t.getEntitiesWithComponents([_a,Co]);for(const o of i){const i=t.get(o,_a),r=t.get(o,Co);if(!be()||ve()){if(t.has(o,u)){Go(t,o,Eo,{enabled:!0,blockRaycast:!0}),Ko(t,i.handleEntity,e=>{Go(t,e,Eo,{enabled:!0,blockRaycast:!1})});const a=t.get(o,u);let l=!1;if(t.has(o,Er)&&(l=t.get(o,Er).pressed),Ko(t,i.handleEntity,e=>{!l&&t.has(e,Er)&&(l=t.get(e,Er).pressed)}),l&&e.isMouseButtonDown(0)){let e=xa(n.worldMouseX,n.worldMouseY,a,r,o,i.direction);e=Math.max(0,Math.min(1,e));let l=i.minValue+e*(i.maxValue-i.minValue);i.wholeNumbers&&(l=Math.round(l));const c=i.value;i.value=Math.max(i.minValue,Math.min(i.maxValue,l)),t.insert(o,_a,i),i.value!==c&&s.emit(o,"change")}}}const a=i.maxValue-i.minValue,l=a>0?(i.value-i.minValue)/a:0;Ko(t,i.fillEntity,e=>{Lo(t,e,i.direction,l)}),Ko(t,i.handleEntity,e=>{if(!t.has(e,Co))return;const n=t.get(e,Co);wa(n,i.direction,l),t.insert(e,Co,n)})}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const va=new ba;class Sa{build(e){oe("Focusable",Wr);const t=e.world,n=new Dr;e.insertResource(Xr,n),e.addSystemToSchedule(s.Update,i([f(it),f(kr)],(e,s)=>{if(be()&&!ve())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Wr]);for(const e of i){if(!t.has(e,Er))continue;t.get(e,Er).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,Eo)){if(!t.get(n,Eo).enabled)continue}const s=t.get(n,Wr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Wr)){t.get(i,Wr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Wr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Ta=new Sa,Pa=a("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Ma(){return He()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class Ca{build(e){oe("SafeArea",Pa);const t=e.world;let n=Ma(),o=!0,r=0,a=0;if(He()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Ma(),o=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Ma(),o=!0});e.addSystemToSchedule(s.PreUpdate,i([f(lt)],e=>{if(!e.valid||0===e.screenH)return;const s=e.worldTop-e.worldBottom;if(e.screenH===r&&s===a||(r=e.screenH,a=s,o=!0),!o)return;o=!1;const i=Ge(),l=He()?s/e.screenH:i*s/e.screenH,c=t.getEntitiesWithComponents([Pa,Co]);for(const e of c){const s=t.get(e,Pa),i=t.get(e,Co),o=s.applyTop?n.top*l:0,r=s.applyBottom?n.bottom*l:0,a=s.applyLeft?n.left*l:0,c=s.applyRight?n.right*l:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-c&&i.offsetMax.y===-o||(i.offsetMax={x:-c,y:-o},u=!0),u&&t.insert(e,Co,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Ea=new Ca,Aa=a("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Ia=null;function Ra(e,t){if(!Ia)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Ia.get(e);n?n.renderer=t:Ia.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class ka{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null),Ia=null}build(e){oe("ListView",Aa);const t=e.world,n=new Map;Ia=n,e.addSystemToSchedule(s.PostUpdate,i([f(it)],e=>{const s=be()&&!ve();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([Aa,Co]);for(const o of i){Go(t,o,Eo,{enabled:!0,blockRaycast:!0}),Go(t,o,xr,{enabled:!0,mode:_r});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,Aa),a=t.get(o,Co),l=Yo(a,o),c=No(a,o);if(!s){const n=t.has(o,Er)?t.get(o,Er):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const d=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,d));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),f=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=f)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<f;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,P,{value:`ListItem_${e}`}),t.insert(n,Co,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,u)){const s=t.get(n,u);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,u,s)}}i.visibleStart=h,i.visibleEnd=f}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{for(const[,e]of n)for(const n of e.itemEntities.values())t.valid(n)&&t.despawn(n);n.clear()}}}const Fa=new ka,Ua=a("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0},{entityFields:["listEntity","labelEntity"]});class La{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){oe("Dropdown",Ua);const t=e.world,n=new Map,o=new Set;function r(e){Ko(t,e,e=>{if(!t.has(e,u))return;const n=t.get(e,u);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,u,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})})}function a(e){if(t.has(e,Ki)){const n=t.get(e,Ki);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Zo(t,e,{...rr})}else if(t.has(e,c)){const n=t.get(e,c);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Zo(t,e,{...rr})}}function l(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;g(i,!0),m(s);let o=0;if(t.has(e,Co)){const n=t.get(e,Co);o=No(n,e)||n.size.x}else if(t.has(e,c)){o=t.get(e,c).size.x}s.ddWidth=o;const r=30*n.options.length;t.insert(i,Co,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:r},pivot:{x:.5,y:1}}),t.insert(i,Ki,{visualType:qi.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn();t.insert(r,P,{value:`Option_${e}`}),t.insert(r,Co,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:30*-e},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:1}}),t.insert(r,u,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,Ki,{visualType:qi.SolidColor,texture:0,color:{...lr},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),t.insert(r,Eo,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const a=t.spawn();t.insert(a,u,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(a,hr,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:cr.Left,verticalAlign:ur.Middle,wordWrap:!1,overflow:dr.Clip,lineHeight:1.2}),t.insert(a,Co,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:.5}}),t.setParent(a,r),s.textEntities.push(a)}y(s)}function d(e,t,n){t.isOpen=!1,m(n),g(t.listEntity,!1)}function h(e,t,n,s,i){t.selectedIndex=s,d(0,t,n),i.emit(e,"change")}function p(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,hr))return;const s=t.get(n,hr);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,hr,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function m(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function g(e,n){Ko(t,e,e=>{t.has(e,Eo)&&t.insert(e,Eo,{enabled:n,blockRaycast:!0,raycastTarget:!0}),Qo(t,e,n)})}function y(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s))continue;const i=n===e.highlightIndex?{...or}:{...lr};Zo(t,s,i)}}function _(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Er))continue;if(t.get(n,Er).hovered)return!0}return!1}e.addSystemToSchedule(s.Update,i([f(it),f(kr)],(e,s)=>{for(const[e,s]of n)t.valid(e)||(m(s),n.delete(e),o.delete(e));const i=be()&&!ve(),c=t.getEntitiesWithComponents([Ua]);for(const u of c){const c=t.get(u,Ua);let f=n.get(u);if(f||(f={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(u,f)),r(c.listEntity),o.has(u)||(a(u),o.add(u)),c.isOpen||g(c.listEntity,!1),p(c),i)continue;Go(t,u,Eo,{enabled:!0,blockRaycast:!0});const m=t.has(u,Er)?t.get(u,Er):null;if(m?.justPressed&&(c.isOpen?d(u,c,f):l(u,c,f)),c.isOpen){for(let e=0;e<f.optionEntities.length;e++){const n=f.optionEntities[e];if(!t.valid(n)||!t.has(n,Er))continue;if(t.get(n,Er).justPressed){h(u,c,f,e,s);break}}let n=-1;for(let e=0;e<f.optionEntities.length;e++){const s=f.optionEntities[e];if(!t.valid(s)||!t.has(s,Er))continue;if(t.get(s,Er).hovered){n=e;break}}n>=0&&n!==f.highlightIndex&&(f.highlightIndex=n,y(f)),e.isKeyPressed("ArrowDown")?(f.highlightIndex>=c.options.length-1?f.highlightIndex=0:f.highlightIndex++,y(f)):e.isKeyPressed("ArrowUp")?(f.highlightIndex<=0?f.highlightIndex=c.options.length-1:f.highlightIndex--,y(f)):e.isKeyPressed("Enter")&&f.highlightIndex>=0?h(u,c,f,f.highlightIndex,s):e.isKeyPressed("Escape")&&d(u,c,f),e.isMouseButtonPressed(0)&&(m?.hovered||_(f)||d(u,c,f))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]}),this.cleanup_=()=>{for(const[,e]of n)m(e);n.clear(),o.clear()}}}const za=new La,Ba=z("LayoutGroup",{direction:0,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:0,reverseOrder:!1});class Oa{build(e){oe("LayoutGroup",Ba)}}const Ha=new Oa,$a=0,Wa=1,Da=0,Xa=1,Na=0,Ya=0,Va=3,ja=z("FlexContainer",{direction:$a,wrap:Da,justifyContent:Na,alignItems:Va,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0}}),Ga=z("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class qa{build(e){const t=e.world,n=e.wasmModule,o=t.getCppRegistry();e.addSystemToSchedule(s.PostUpdate,i([],()=>{n.uiRenderOrder_update(o)},{name:"UIRenderOrderSystem"}))}}const Ka=new qa,Ja={primary:{r:.25,g:.56,b:.96,a:1},secondary:{r:.4,g:.4,b:.4,a:1},background:{r:.08,g:.08,b:.08,a:1},surface:{r:.14,g:.14,b:.14,a:1},error:{r:.9,g:.2,b:.2,a:1},text:{r:.93,g:.93,b:.93,a:1},textSecondary:{r:.6,g:.6,b:.6,a:1},border:{r:.3,g:.3,b:.3,a:1},fontFamily:"Arial",fontSize:{xs:10,sm:12,md:14,lg:18,xl:24},spacing:{xs:4,sm:8,md:12,lg:16,xl:24},button:{height:36,color:{r:.25,g:.25,b:.25,a:1},textColor:{r:.93,g:.93,b:.93,a:1},transition:{normalColor:{r:.25,g:.25,b:.25,a:1},hoveredColor:{r:.3,g:.3,b:.3,a:1},pressedColor:{r:.18,g:.18,b:.18,a:1},disabledColor:{r:.15,g:.15,b:.15,a:.6}}},slider:{trackHeight:16,trackColor:{r:.15,g:.15,b:.15,a:1},fillColor:{r:.25,g:.56,b:.96,a:1},handleSize:24,handleColor:{r:1,g:1,b:1,a:1}},toggle:{size:{x:24,y:24},onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1},checkColor:{r:1,g:1,b:1,a:1}},input:{height:36,backgroundColor:{r:.15,g:.15,b:.15,a:1},textColor:{r:1,g:1,b:1,a:1},placeholderColor:{r:.6,g:.6,b:.6,a:1},fontSize:16,padding:6},dropdown:{height:32,backgroundColor:{r:.2,g:.2,b:.2,a:1},itemHeight:28},panel:{backgroundColor:{r:.14,g:.14,b:.14,a:1},padding:12},scrollView:{backgroundColor:{r:.1,g:.1,b:.1,a:1}}},Za=e(null,"UITheme");let Qa=null;function el(e){e.hasResource(Za)&&(Qa=e.getResource(Za))}function tl(){return Qa??Ja}function nl(e,t){const n=e.spawn();if(t.name&&e.insert(n,P,{value:t.name}),e.insert(n,u,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},...t.transform}),t.rect&&e.insert(n,Co,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:0,y:0},pivot:{x:.5,y:.5},...t.rect}),t.renderer&&e.insert(n,Ki,{visualType:qi.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0,...t.renderer}),t.interactable&&e.insert(n,Eo,{enabled:!0,blockRaycast:!0,raycastTarget:!0,...t.interactable}),t.text){const s=tl();e.insert(n,hr,{content:"",fontFamily:s.fontFamily,fontSize:s.fontSize.md,color:{r:1,g:1,b:1,a:1},align:cr.Left,verticalAlign:ur.Top,wordWrap:!1,overflow:0,lineHeight:1.2,...t.text})}if(t.image&&e.insert(n,Mo,{...Mo._default,...t.image}),t.flex&&e.insert(n,ja,{direction:$a,wrap:Da,justifyContent:Na,alignItems:Va,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0},...t.flex}),t.flexItem&&e.insert(n,Ga,{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,...t.flexItem}),t.mask&&e.insert(n,xr,{enabled:!0,mode:_r,...t.mask}),t.components)for(const[s,i]of t.components)e.insert(n,s,i);return t.parent&&e.setParent(n,t.parent),n}function sl(e,t={}){const n=tl(),{text:s="Button",fontSize:i=n.fontSize.md,size:o={x:120,y:n.button.height},color:r=n.button.color,textColor:a=n.button.textColor,transition:l=null,parent:c}=t,u=nl(e,{name:"ButtonLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:s,fontSize:i,color:a,align:cr.Center,verticalAlign:ur.Middle}}),d=nl(e,{name:"Button",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:qi.SolidColor,color:r},interactable:{enabled:!0},components:[[Ir,{state:0,transition:l}]]});if(e.setParent(u,d),t.events){if(t.onClick){const e=t.onClick;t.events.on(d,"click",()=>e(d))}if(t.onHover){const e=t.onHover;t.events.on(d,"hover_enter",()=>e(d))}}return d}function il(e,t={}){const n=tl(),{value:s=0,minValue:i=0,maxValue:o=1,direction:r=vo.LeftToRight,size:a={x:200,y:n.slider.trackHeight},trackColor:l=n.slider.trackColor,fillColor:c=n.slider.fillColor,handleSize:u={x:n.slider.handleSize,y:n.slider.handleSize},handleColor:d=n.slider.handleColor,wholeNumbers:h=!1,parent:f}=t,p=nl(e,{name:"SliderFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:qi.SolidColor,color:c}}),m=nl(e,{name:"SliderHandle",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:u},renderer:{visualType:qi.SolidColor,color:d},interactable:{enabled:!0,blockRaycast:!0},components:[[ra,{enabled:!0,dragThreshold:5,lockX:!1,lockY:!0}]]}),g=nl(e,{name:"Slider",parent:f,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:qi.SolidColor,color:l},interactable:{enabled:!0,blockRaycast:!0},components:[[_a,{value:s,minValue:i,maxValue:o,direction:r,wholeNumbers:h,fillEntity:p,handleEntity:m}]]});if(e.setParent(p,g),e.setParent(m,g),t.onChange&&t.events){const n=t.onChange;t.events.on(g,"change",()=>{const t=e.get(g,_a);n(t.value,g)})}return g}function ol(e,t={}){const n=tl(),{isOn:s=!0,size:i=n.toggle.size,onColor:o=n.toggle.onColor,offColor:r=n.toggle.offColor,checkSize:a={x:.58*n.toggle.size.x,y:.58*n.toggle.size.y},checkColor:l=n.toggle.checkColor,group:c=0,transition:u=null,label:d,parent:h}=t,f=nl(e,{name:"ToggleCheck",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:qi.SolidColor,color:l}}),p=nl(e,{name:"Toggle",parent:h,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:qi.SolidColor,color:s?o:r},interactable:{enabled:!0},components:[[Kr,{isOn:s,graphicEntity:f,group:c,transition:u,onColor:o,offColor:r}]]});if(e.setParent(f,p),d&&nl(e,{name:"ToggleLabel",parent:p,rect:{anchorMin:{x:1,y:0},anchorMax:{x:1,y:1},offsetMin:{x:8,y:0},size:{x:100,y:0}},text:{content:d,fontSize:n.fontSize.md,align:cr.Left,verticalAlign:ur.Middle}}),t.onChange&&t.events){const n=t.onChange;t.events.on(p,"change",()=>{const t=e.get(p,Kr);n(t.isOn,p)})}return p}function rl(e,t={}){const n=tl(),{value:s=0,size:i={x:200,y:n.slider.trackHeight},direction:o=vo.LeftToRight,trackColor:r=n.slider.trackColor,fillColor:a=n.primary,parent:l}=t,c=nl(e,{name:"ProgressFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:qi.SolidColor,color:a}}),u=nl(e,{name:"ProgressBar",parent:l,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:qi.SolidColor,color:r},components:[[sa,{value:s,fillEntity:c,direction:o}]]});return e.setParent(c,u),u}function ll(e,t={}){const n=tl(),{size:s={x:300,y:400},contentSize:i={x:300,y:800},horizontal:o=!1,vertical:r=!0,elastic:a=!0,mask:l=!0,parent:c}=t,u=nl(e,{name:"ScrollContent",rect:{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},size:{x:i.x,y:i.y},pivot:{x:.5,y:1}}}),d=nl(e,{name:"ScrollView",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:s},renderer:{visualType:qi.SolidColor,color:n.scrollView.backgroundColor},mask:l?{mode:_r,enabled:!0}:void 0,components:[[ha,{contentEntity:u,horizontalEnabled:o,verticalEnabled:r,contentWidth:i.x,contentHeight:i.y,elastic:a,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,wheelSensitivity:.1}]]});return e.setParent(u,d),d}function cl(e,t={}){const n=tl(),{placeholder:s="",value:i="",size:o={x:200,y:n.input.height},fontSize:r=n.input.fontSize,backgroundColor:a=n.input.backgroundColor,textColor:l=n.input.textColor,maxLength:c=0,multiline:u=!1,password:d=!1,parent:h}=t,f=nl(e,{name:"TextInput",parent:h,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:qi.SolidColor,color:a},interactable:{enabled:!0},components:[[$r,{value:i,placeholder:s,fontSize:r,fontFamily:n.fontFamily,color:l,backgroundColor:a,placeholderColor:n.input.placeholderColor,padding:n.input.padding,maxLength:c,multiline:u,password:d,readOnly:!1,focused:!1,cursorPos:i.length,dirty:!0}],[Wr,{tabIndex:0,isFocused:!1}]]});if(t.events){if(t.onChange){const n=t.onChange;t.events.on(f,"change",()=>{const t=e.get(f,$r);n(t.value,f)})}if(t.onSubmit){const n=t.onSubmit;t.events.on(f,"submit",()=>{const t=e.get(f,$r);n(t.value,f)})}}return f}function ul(e,t){const n=tl(),{options:s,selectedIndex:i=-1,size:o={x:160,y:n.dropdown.height},fontSize:r=n.fontSize.md,parent:a}=t,l=nl(e,{name:"DropdownLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:(i>=0?s[i]:s[0])??"",fontSize:r,align:cr.Left,verticalAlign:ur.Middle}}),c=nl(e,{name:"DropdownList",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},size:{x:o.x,y:Math.min(s.length*n.dropdown.itemHeight,200)},pivot:{x:.5,y:1}},renderer:{visualType:qi.SolidColor,color:n.surface},mask:{mode:_r,enabled:!0}}),u=nl(e,{name:"Dropdown",parent:a,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:qi.SolidColor,color:n.dropdown.backgroundColor},interactable:{enabled:!0},components:[[Ua,{options:s,selectedIndex:i,isOpen:!1,listEntity:c,labelEntity:l}]]});if(e.setParent(l,u),e.setParent(c,u),t.onChange&&t.events){const n=t.onChange;t.events.on(u,"change",()=>{const t=e.get(u,Ua);n(t.selectedIndex,u)})}return u}function dl(e,t){const n=tl();return nl(e,{name:"Label",parent:t.parent,rect:t.size?{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size}:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:t.text,fontSize:t.fontSize??n.fontSize.md,color:t.color??n.text,align:t.align??cr.Left,verticalAlign:t.verticalAlign??ur.Middle}})}function hl(e,t={}){const n=tl();return nl(e,{name:"Panel",parent:t.parent,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size??{x:300,y:200}},renderer:{visualType:qi.SolidColor,color:t.color??n.panel.backgroundColor}})}function fl(e,t={}){return nl(e,{name:"FlexRow",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:$a,wrap:t.wrap?Xa:Da,justifyContent:t.justifyContent??Na,alignItems:t.alignItems??Ya,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}function pl(e,t={}){return nl(e,{name:"FlexColumn",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:Wa,wrap:t.wrap?Xa:Da,justifyContent:t.justifyContent??Na,alignItems:t.alignItems??Ya,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}const ml={button:sl,slider:il,toggle:ol,textInput:cl,dropdown:ul,progressBar:rl,label:dl,panel:hl,flexRow:fl,flexColumn:pl,scrollView:ll};const gl={spawn:nl,destroy:function e(t,n){if(t.valid(n)){if(t.has(n,re)){const s=[...t.get(n,re).entities];for(const n of s)e(t,n)}t.despawn(n)}},build:function e(t,n,s){let i,o;if("element"===n.type)i=nl(t,{...n,parent:s}),o=i;else{if(i=(0,ml[n.type])(t,{...n.options??{},parent:s}),"scrollView"===n.type){o=t.get(i,ha).contentEntity}else o=i}const r=n.children;if(r&&o)for(const n of r)e(t,n,o);return n.ref&&n.ref(i),i},label:dl,panel:hl,button:sl,slider:il,toggle:ol,scrollView:ll,textInput:cl,dropdown:ul,progressBar:rl,flexRow:fl,flexColumn:pl};async function yl(e,t,n){const s=e.getResource(to);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}const _l={nearest:0,linear:1},xl={repeat:0,clamp:1,mirror:2};function wl(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=_l[s.filterMode??"linear"]??1,a=xl[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function bl(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 vl(e,t,n){const s=e.FS;if(!s)return!1;try{return function(e,t){const n=e.FS;if(!n)return;const s=t.substring(0,t.lastIndexOf("/"));if(!s)return;const i=s.split("/").filter(e=>e);let o="";for(const e of i){o+="/"+e;try{n.mkdir(o)}catch{}}}(e,t),s.writeFile(t,n),!0}catch(e){return console.warn(`[Runtime] Failed to write virtual FS: ${t}`,e),!1}}async function Sl(e){const{app:t,module:n,sceneData:s,provider:i,spineManager:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=es(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=wl(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);const d=await async function(e,t,n,s){const i=new Set,o=new Map;for(const r of t.entities)for(const t of r.components){const r=ts(t.type);if(!r||!t.data)continue;const a=t.data[r.skeletonField],l=t.data[r.atlasField];if(!a||!l)continue;const c=`${a}:${l}`;if(i.has(c))continue;i.add(c);const u=n.resolvePath(l);try{const t=await n.readText(l),i=n.resolvePath(a),r="binary"===ys(i)?.contentType?await n.readBinary(a):await n.readText(a),d=s?"string"==typeof r?Fe.detectVersionJson(r):Fe.detectVersion(r):null,h=bl(t),f=u.substring(0,u.lastIndexOf("/")),p=e.getResourceManager(),m=new Map;for(const t of h){const s=f+"/"+t;try{const i=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),o=wl(e,i,!1);p.registerTextureWithPath(o,s),m.set(t,{glId:p.getTextureGLId(o),w:i.width,h:i.height})}catch(e){console.warn(`[Spine] Failed to load texture: ${s}`,e)}}(!d||"4.2"===d)&&(vl(e,u,t),vl(e,i,r)),o.set(c,{version:d,skelData:r,atlasText:t,textures:m})}catch(e){console.warn(`[Runtime] Failed to load spine asset: skel=${a} atlas=${l}`,e)}}return o}(n,s,i,o);if(r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??le,subStepCount:a?.subStepCount??4,contactHertz:a?.contactHertz??120,contactDampingRatio:a?.contactDampingRatio??10,contactSpeed:a?.contactSpeed??10};new ke("",e,()=>Promise.resolve(r)).build(t)}const h=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=es(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=ys(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=wl(e,c,!1),d=e.getResourceManager();s[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch(e){console.warn(`[Runtime] Failed to load bitmap font: ${o}`,e),s[o]=0}}return s}(n,s,i),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=es(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=ge.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=ge.createFromAsset(e,r)}catch(e){console.warn(`[Runtime] Failed to load material: ${o}`,e),n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=es(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=dt(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,wl(e,s))}catch(e){console.warn(`[Runtime] Failed to load anim texture: ${t}`,e),r.set(t,0)}pt(ht(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=es(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=Ot(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=Ht(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=wl(e,t),St(r,t.width,t.height)}catch(e){console.warn(`[Runtime] Failed to load tileset texture: ${s}`,e)}o.push({textureHandle:r,columns:t.columns})}Mt(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=es(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await wt.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await wt.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=es(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,h,f);const p=os(t.world,s),m=t.world.getCppRegistry();if(m&&n.transform_update(m),o&&m&&d.size>0)for(const e of s.entities)for(const t of e.components){const n=ts(t.type);if(!n||!t.data)continue;const s=t.data[n.skeletonField],i=t.data[n.atlasField];if(!s||!i)continue;const r=`${s}:${i}`,a=d.get(r);if(!a||!a.version||"4.2"===a.version)continue;const l=p.get(e.id);if(void 0===l)continue;await o.loadEntity(l,a.skelData,a.atlasText,a.textures,m),o.setEntityProps(l,{skeletonScale:t.data.skeletonScale??1,flipX:t.data.flipX??!1,flipY:t.data.flipY??!1,layer:t.data.layer??0});const c=t.data.skin;c&&o.setSkin(l,c);const u=t.data.animation;u&&o.setAnimation(l,u,!1!==t.data.loop)}if(c&&t.hasResource(to))for(const e of p.values())t.world.insert(e,B,{scene:c,persistent:!1});if(l){const e=t.getResource(ks);e&&e.setAddressableManifest(l)}}function Tl(e,t,n){return{name:e,async setup(){await Sl({...n,sceneData:t,sceneName:e})}}}async function Pl(e){const{app:t,firstScene:n,aspectRatio:s}=e;ro(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,spineManager:e.spineManager,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(to);for(const t of e.scenes)o.register(Tl(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&us(t.world,s)}class Ml{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=ts(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===ys(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=es(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=ys(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Cl="__preview__";class El{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(to);t.register({name:Cl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Cl),this.loadPromise_=t.load(Cl).then(()=>{}).catch(e=>{console.error("[Preview] Failed to load preview scene:",e)}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await We(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Ml(this.baseUrl_);await n.prefetch(t);const s=this.app_.getPlugin(Ue),i=s?.spineManager??null;await Sl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineManager:i,sceneName:Cl})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([A]);for(const s of n){if(e.get(s,A).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=fe/pe;const s=e.getEntitiesWithComponents([ue]);for(const i of s){const s=e.get(i,ue);if(s.designResolution){const e=s.pixelsPerUnit||de;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(to).getScene(Cl),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,u,r);const a={isActive:!0,projectionType:ee.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:he.ColorAndDepth};e.insert(o,A,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(to);await e.switchTo(Cl),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Al={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=Xi.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:Xi.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){Xi.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Xi.releaseRenderTarget(e._handle),Al.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){Xi.begin(t,e._handle)},end(){Xi.end()},getDepthTexture:e=>Xi.getTargetDepthTexture(e._handle)};var Il;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Il||(Il={}));class Rl{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Il[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Il.Debug:console.debug(t,n);break;case Il.Info:console.log(t,n);break;case Il.Warn:console.warn(t,n);break;case Il.Error:console.error(t,n)}}}class kl{constructor(){this.handlers_=[],this.minLevel_=Il.Info,this.addHandler(new Rl)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Il.Debug,e,t,n)}info(e,t,n){this.log(Il.Info,e,t,n)}warn(e,t,n){this.log(Il.Warn,e,t,n)}error(e,t,n){this.log(Il.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Fl=new kl;function Ul(){return Fl}function Ll(e){Fl.setMinLevel(e)}function zl(e,t,n){Fl.debug(e,t,n)}function Bl(e,t,n){Fl.info(e,t,n)}function Ol(e,t,n){Fl.warn(e,t,n)}function Hl(e,t,n){Fl.error(e,t,n)}const $l={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},Wl={Running:0,Paused:1,Completed:2,Cancelled:3},Dl={None:0,Restart:1,PingPong:2};const Xl=1.70158,Nl=2.70158,Yl=2.5949095;const Vl=2*Math.PI/3,jl=2*Math.PI/4.5;const Gl=7.5625,ql=2.75;const Kl=1e-6;function Jl(e,t,n){switch(e){case $l.Linear:return t;case $l.EaseInQuad:return function(e){return e*e}(t);case $l.EaseOutQuad:return function(e){return e*(2-e)}(t);case $l.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case $l.EaseInCubic:return function(e){return e*e*e}(t);case $l.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case $l.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case $l.EaseInBack:return function(e){return Nl*e*e*e-Xl*e*e}(t);case $l.EaseOutBack:return function(e){const t=e-1;return 1+Nl*t*t*t+Xl*t*t}(t);case $l.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Yl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Yl)+2)/2}(t);case $l.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Vl)}(t);case $l.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Vl)+1}(t);case $l.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*jl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*jl)/2+1}(t);case $l.EaseOutBounce:return function(e){return e<1/ql?Gl*e*e:e<2/ql?Gl*(e-=1.5/ql)*e+.75:e<2.5/ql?Gl*(e-=2.25/ql)*e+.9375:Gl*(e-=2.625/ql)*e+.984375}(t);case $l.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<Kl)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<Kl)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case $l.Step:return function(e){return e<1?0:1}(t);default:return t}}const Zl=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??$l.Linear,bezierPoints:null,state:Wl.Running,loop:i?.loop??Dl.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===Wl.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Wl.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=Jl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Dl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Dl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Wl.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Wl.Running&&(t.state=Wl.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Wl.Paused&&(t.state=Wl.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Wl.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Wl.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Ql{constructor(e){this.id=e}get state(){return Zl.getState(this.id)}bezier(e,t,n,s){return Zl.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Ql?Zl.setSequenceNext(this.id,e.id):Zl.setSequenceNextExternal(this.id,e),this}pause(){Zl.pause(this.id)}resume(){Zl.resume(this.id)}cancel(){Zl.cancel(this.id)}}const ec={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class tc{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof Ql?(Zl.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let nc=null,sc=null;function ic(e,t){nc=e,sc=t,Zl.init(e,t)}function oc(){Zl.shutdown(),nc=null,sc=null}function rc(){if(!nc)throw new Error("Tween API not initialized");return nc}function lc(){if(!sc)throw new Error("Tween API not initialized");return sc}const cc={to(e,t,n,s,i,o){const r=rc(),a=lc(),l=o?.easing??$l.Linear,c=o?.delay??0,u=o?.loop??Dl.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,u,d);return new tc(r,a,h)},value(e,t,n,s,i){const o=Zl.create(e,t,n,s,i);return new Ql(o)},cancel(e){rc()._anim_cancelTween(lc(),e.entity)},cancelAll(e){rc()._anim_cancelAllTweens(lc(),e)},update(e){rc()._anim_updateTweens(lc(),e),Zl.update(e)}};class uc{constructor(){this.name="AnimationPlugin"}build(e){ic(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(s.Update,i([f(g)],e=>{be()&&!ve()||cc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(s.Update,i([f(g)],e=>{be()&&!ve()||xt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){oc()}}const dc=new uc;let hc=null,fc=null;function pc(e,t){hc=e,fc=t}function mc(){hc=null,fc=null}const gc={update(e){hc&&fc&&hc.particle_update?.(fc,e)},play(e){hc&&fc&&hc.particle_play?.(fc,e)},stop(e){hc&&fc&&hc.particle_stop?.(fc,e)},reset(e){hc&&fc&&hc.particle_reset?.(fc,e)},getAliveCount:e=>hc?hc.particle_getAliveCount?.(e)??0:0};class yc{constructor(){this.name="ParticlePlugin"}build(e){pc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(s.Update,i([f(g)],e=>{gc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){mc()}}const _c=new yc,xc=1073741824,wc={orthogonal:0,isometric:1,staggered:2};class bc{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.animatedLayers_=new Set,this.sourceEntityKeys_=new Map,this.layerState_=new Map}build(e){It(e.wasmModule);const t=e.world,n=this.initializedLayers_,i=this.animatedLayers_,o=this.sourceEntityKeys_,r=this.layerState_,a={_id:Symbol("TilemapSyncSystem"),_name:"TilemapSyncSystem",_params:[],_fn:()=>{const s=t.getEntitiesWithComponents([Ut,u]),a=new Set(s);for(const e of n)e>=xc||a.has(e)||(kt.destroyLayer(e),n.delete(e),r.delete(e));for(const e of s){const s=t.tryGet(e,Ut);if(!s)continue;const i=s.texture;if(!i)continue;const o=Tt(i);if(!o)continue;if(!n.has(e)){if(kt.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),kt.setOriginEntity(e,e),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];kt.setTiles(e,t)}n.add(e)}const a=s.tileWidth/o.width,l=s.tileHeight/o.height,c=s.tint,u=s.parallaxFactor,d=r.get(e);(!d||d.texture!==i||d.tilesetColumns!==s.tilesetColumns||d.layer!==s.layer||d.parallaxX!==u.x||d.parallaxY!==u.y||d.tintR!==c.r||d.tintG!==c.g||d.tintB!==c.b||d.tintA!==c.a||d.opacity!==s.opacity||d.visible!==s.visible)&&(kt.setRenderProps(e,i,s.tilesetColumns,a,l,s.layer,0,u.x,u.y),kt.setTint(e,c.r,c.g,c.b,c.a,s.opacity),kt.setVisible(e,s.visible),r.set(e,{texture:i,tilesetColumns:s.tilesetColumns,layer:s.layer,tintR:c.r,tintG:c.g,tintB:c.b,tintA:c.a,opacity:s.opacity,parallaxX:u.x,parallaxY:u.y,visible:s.visible}))}const l=t.getEntitiesWithComponents([Ft,u]);for(const e of l){if(t.tryGet(e,Ut))continue;const s=t.tryGet(e,Ft);if(!s?.source)continue;const r=Ct(s.source);if(r&&!o.has(e)){const t=[],s=wc[r.orientation??"orthogonal"]??0;for(let o=0;o<r.layers.length;o++){const a=xc+256*e+o,l=r.layers[o];if(kt.initLayer(a,l.width,l.height,r.tileWidth,r.tileHeight),kt.setOriginEntity(a,e),l.tiles.length>0&&kt.setTiles(a,l.tiles),0!==s&&kt.setGridType(a,s),r.tileAnimations){for(const[e,t]of r.tileAnimations)kt.setTileAnimation(a,e,t);r.tileAnimations.size>0&&i.add(a)}if(r.tileProperties)for(const[e,t]of r.tileProperties)for(const[n,s]of t)kt.setTileProperty(a,e,n,s);const c=r.tilesets[0];if(c){const e=Tt(c.textureHandle);e&&(kt.setRenderProps(a,c.textureHandle,c.columns,r.tileWidth/e.width,r.tileHeight/e.height,o,0,1,1),kt.setTint(a,1,1,1,1,1),kt.setVisible(a,!0))}t.push(a),n.add(a)}o.set(e,t)}}const c=new Set(l);for(const[e,t]of o)if(!c.has(e)){for(const e of t)kt.destroyLayer(e),n.delete(e),i.delete(e),r.delete(e);o.delete(e)}if(i.size>0){const t=1e3*e.getResource(g).delta;for(const e of i)kt.advanceAnimations(e,t)}}};e.addSystemToSchedule(s.PreUpdate,a)}cleanup(){for(const e of this.initializedLayers_)kt.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),this.layerState_.clear(),Pt(),Rt()}}const vc=new bc;function Sc(e,t){return e.toFixed(t)}function Tc(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Pc{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.lastUpdateTime_=0,this.lastStats_=null,this.accumulatedTimings_=new Map,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 220px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;this.lastStats_=e,this.accumulateTimings_(e.systemTimings);const t=performance.now();this.lastUpdateTime_>0&&t-this.lastUpdateTime_<500||(this.lastUpdateTime_=t,this.render_())}show(){this.visible_=!0,this.lastUpdateTime_=0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}accumulateTimings_(e){for(const[t,n]of e){const e=this.accumulatedTimings_.get(t);e?(e.sum+=n,e.count++,n>e.max&&(e.max=n)):this.accumulatedTimings_.set(t,{sum:n,max:n,count:1})}}render_(){const e=this.lastStats_;if(!e)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Sc(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Sc(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),this.accumulatedTimings_.size>0){const e=[];for(const[t,n]of this.accumulatedTimings_){const s=n.sum/n.count;e.push([t,s,n.max])}e.sort((e,t)=>t[2]-e[2]);const n=e.slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t,i]of n){s+=`<div>${Tc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Sc(t,1)} / ${Sc(i,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join(""),this.accumulatedTimings_.clear()}}function Mc(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Cc=e(Mc(),"Stats");class Ec{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const Ac="StatsCollect";class Ic{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Rc{constructor(e){this.name="Stats",this.collector_=new Ic,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Cc,Mc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Pc(e,this.options_.position)}const t=this.collector_,n=this.overlay_,o=i([f(g),me()],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Cc);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Ac),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Xi.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:Ac});e.addSystemToSchedule(s.Last,o)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const kc=new Rc;class Fc{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return Uc(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}function Uc(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}function Lc(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function zc(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await async function(e,t){try{const n=Lc(t),s={instantiateWasm(e,t){const s=new Response(n.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,e).then(e=>t(e.instance,e.module),()=>{WebAssembly.instantiate(n.buffer,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Playable] WASM instantiation fallback failed:",e)})}),{}}};return await e(s)}catch(e){return console.error("[Playable] WASM module init failed:",e),null}}(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}async function Bc(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(ks);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));let a=null;if(e.spineModules&&Object.keys(e.spineModules).length>0){a=function(e,t){const n=new Map;for(const[e,s]of Object.entries(t)){const t=e;n.set(t,async()=>{const e=Lc(s.wasmBase64);return s.factory({instantiateWasm(t,n){const s=new Response(e.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,t).then(e=>n(e.instance,e.module),()=>{WebAssembly.instantiate(e.buffer,t).then(e=>n(e.instance,e.module)).catch(e=>{console.error("[Playable] Spine WASM instantiation fallback failed:",e)})}),{}}})})}return new Fe(e,n)}(n,e.spineModules);const s=t.getPlugin(Ue);s&&s.setSpineManager(a)}const l=e.physicsWasmBase64?await zc(e.physicsWasmBase64):null,c=new Fc(s);wt.setAssetResolver(e=>{const t=s[e];return t?Uc(t).buffer:null}),await Pl({app:t,module:n,provider:c,scenes:i,firstScene:o,spineManager:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Oc=[yr,br,Lr,qr,oa,Hr,da,ga,va,ta,Yr,Ta,Ea,Fa,za,Ha,Ka],Hc=[dc,$n,_c,vc,Ui,Kn];function $c(e,t){const n=new Ue(t?.spineProvider),i=[...Oc,...Hc,n,...t?.plugins??[]];return function(e,t){const n=oo.new(),i=new e.Registry;n.connectCpp(i,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ie(e),Re(e),ei(e),fi(e),Wi(e),Yi(e);const o=new Gi;n.setPipeline(o);let r=je();const a=t?.getViewportSize??(()=>{const e=Ge();return{width:window.innerWidth*e,height:window.innerHeight*e}});function l(t,s,o){o||(o=fo(e,i,t,s));const r=n.getResource(lt);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*s),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*s),r.screenW=t,r.screenH=s,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(lt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=a();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:s}=a();if(0===t||0===s)return;const c=e.registry_getCanvasEntity(i);if(c>=0){const e=i.getCanvas(c).backgroundColor;Xi.setClearColor(e.x,e.y,e.z,e.w)}const u=(je()-r)/1e3;let d;if(Xi.resize(t,s),n.hasResource(to)){const e=n.getResource(to).getActiveScenes();e.length>0&&(d=new Set(e))}o.setActiveScenes(d??null);const h=fo(e,i,t,s,n.world,d);if(l(t,s,h),0===h.length)o.render({registry:{_cpp:i},viewProjection:lo,width:t,height:s,elapsed:u});else{o.beginFrame(),o.beginScreenCapture();for(const e of h){const n=e.viewportRect,r=Math.round(n.x*t),a=Math.round((1-n.y-n.h)*s),l=Math.round(n.w*t),c=Math.round(n.h*s);o.renderCamera({registry:{_cpp:i},viewProjection:e.viewProjection,viewportPixels:{x:r,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}o.endScreenCapture(),Xi.setViewport(0,0,t,s)}}};if(n.addSystemToSchedule(s.First,c),n.addSystemToSchedule(s.Last,u),n.addPlugin(Us),n.addPlugin(Gs),n.addPlugin(rt),n.addPlugin(io),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{...t,plugins:i})}Le=et;export{uc as AnimationPlugin,oo as App,Fs as AssetPlugin,Ls as AssetRefCounter,Rs as AssetServer,ks as Assets,ct as AsyncCache,Fn as AttenuationModel,wt as Audio,qe as AudioBus,On as AudioListener,Ke as AudioMixer,Hn as AudioPlugin,Je as AudioPool,Bn as AudioSource,H as BitmapText,_e as BodyType,we as BoxCollider,Ir as Button,Ar as ButtonState,A as Camera,ue as Canvas,re as Children,xe as CircleCollider,he as ClearFlags,Ja as DARK_THEME,pe as DEFAULT_DESIGN_HEIGHT,fe as DEFAULT_DESIGN_WIDTH,le as DEFAULT_FIXED_TIMESTEP,ce as DEFAULT_GRAVITY,de as DEFAULT_PIXELS_PER_UNIT,qs as DataType,ua as DragPlugin,la as DragState,ra as Draggable,Se as Draw,Ua as Dropdown,La as DropdownPlugin,$l as EasingType,nr as EntityStateMap,D as EventRegistry,vo as FillDirection,To as FillMethod,Po as FillOrigin,Li as FlushReason,Xr as FocusManager,Dr as FocusManagerState,Sa as FocusPlugin,Wr as Focusable,Ec as FrameHistory,ji as GLDebug,si as Geometry,me as GetWorld,E as INVALID_ENTITY,se as INVALID_TEXTURE,Mo as Image,Gr as ImagePlugin,So as ImageType,it as Input,ot as InputPlugin,st as InputState,Eo as Interactable,Oa as LayoutGroupPlugin,Aa as ListView,ka as ListViewPlugin,Il as LogLevel,kl as Logger,Dl as LoopMode,ge as Material,ut as MaterialLoader,P as Name,ie as Parent,gc as Particle,yc as ParticlePlugin,ke as PhysicsPlugin,gi as PostProcess,Fi as PostProcessPlugin,ui as PostProcessStack,F as PostProcessVolume,Ys as PrefabServer,Vs as Prefabs,js as PrefabsPlugin,El as PreviewPlugin,sa as ProgressBar,na as ProgressBarDirection,ia as ProgressBarPlugin,ee as ProjectionType,R as Query,Gi as RenderPipeline,Bi as RenderStage,Al as RenderTexture,zi as RenderType,Xi as Renderer,f as Res,W as ResMut,ye as RigidBody,r as RuntimeConfig,Pa as SafeArea,Ca as SafeAreaPlugin,te as ScaleMode,to as SceneManager,eo as SceneManagerState,B as SceneOwner,s as Schedule,ha as ScrollView,ma as ScrollViewPlugin,_a as Slider,ya as SliderDirection,ba as SliderPlugin,T as SpineAnimation,c as Sprite,_t as SpriteAnimator,Cc as Stats,Ic as StatsCollector,Pc as StatsOverlay,Rc as StatsPlugin,nt as Storage,Oi as SubmitSkipFlags,Q as SystemRunner,hr as Text,cr as TextAlign,$r as TextInput,Nr as TextInputPlugin,dr as TextOverflow,gr as TextPlugin,fr as TextRenderer,ur as TextVerticalAlign,Ft as Tilemap,kt as TilemapAPI,Ut as TilemapLayer,bc as TilemapPlugin,g as Time,qn as TimelinePlugin,Kr as Toggle,ea as TogglePlugin,u as Transform,cc as Tween,tc as TweenHandle,Wl as TweenState,ec as TweenTarget,gl as UI,lt as UICameraInfo,Rr as UIEventQueue,kr as UIEvents,Er as UIInteraction,Or as UIInteractionPlugin,Fr as UILayoutGeneration,Ur as UILayoutPlugin,xr as UIMask,wr as UIMaskPlugin,Co as UIRect,qa as UIRenderOrderPlugin,Ki as UIRenderer,Za as UIThemeRes,qi as UIVisualType,Ml as WebAssetProvider,N as World,d as WorldTransform,dc as animationPlugin,Lo as applyDirectionalFill,$s as applyOverrides,Us as assetPlugin,$n as audioPlugin,Ln as calculateAttenuation,zn as calculatePanning,Mi as cleanupAllPostProcessVolumes,Pi as cleanupPostProcessVolume,yt as clearAnimClips,Ce as clearDrawCallbacks,Pt as clearTextureDimensionsCache,Et as clearTilemapSourceCache,kn as clearTimelineHandles,Os as cloneComponentData,Bs as cloneComponents,Ds as collectNestedPrefabPaths,er as colorScale,tr as colorWithAlpha,ko as computeFillAnchors,Uo as computeFillSize,Fo as computeHandleAnchors,Ao as computeUIRectLayout,Tl as createRuntimeSceneConfig,$c as createWebApp,zl as debug,Mc as defaultFrameStats,a as defineComponent,e as defineResource,i as defineSystem,da as dragPlugin,za as dropdownPlugin,Hl as error,dt as extractAnimClipTexturePaths,ds as findEntityByName,Ws as flattenPrefab,ro as flushPendingSystems,Ta as focusPlugin,xs as getAddressableType,ws as getAddressableTypeByEditorType,vs as getAllAssetExtensions,bi as getAllEffectDefs,gt as getAnimClip,Is as getAssetBuildTransform,Ms as getAssetMimeType,ys as getAssetTypeEntry,b as getComponent,es as getComponentAssetFieldDescriptors,Qn as getComponentAssetFields,C as getComponentEntityFields,ts as getComponentSpineFieldDescriptor,Ts as getCustomExtensions,_s as getEditorType,xi as getEffectDef,wi as getEffectTypes,Ul as getLogger,ze as getPlatform,Oe as getPlatformType,Tt as getTextureDimensions,Ct as getTilemapSource,Rn as getTimelineHandle,Ps as getWeChatPackOptions,qr as imagePlugin,Bl as info,Ie as initDrawAPI,Yi as initGLDebugAPI,ei as initGeometryAPI,Re as initMaterialAPI,pc as initParticleAPI,Bc as initPlayableRuntime,fi as initPostProcessAPI,Wi as initRendererAPI,Pl as initRuntime,It as initTilemapAPI,ic as initTweenAPI,el as initUIBuilder,rt as inputPlugin,Ns as instantiatePrefab,vr as intersectRects,Sr as invertMatrix4,Cs as isCustomExtension,be as isEditor,bs as isKnownAssetExtension,Be as isPlatformInitialized,ve as isPlayMode,He as isWeChat,$e as isWeb,Ha as layoutGroupPlugin,Fa as listViewPlugin,cs as loadComponent,Sl as loadRuntimeScene,os as loadSceneData,rs as loadSceneWithAssets,Xt as loadTiledMap,Ss as looksLikeAssetPath,qo as makeInteractable,ht as parseAnimClipData,$t as parseTiledMap,hn as parseTimelineAsset,Ot as parseTmjJson,_c as particlePlugin,We as platformFetch,Ne as platformFileExists,Ye as platformInstantiateWasm,De as platformReadFile,Xe as platformReadTextFile,Cr as pointInOBB,Pr as pointInWorldRect,Ui as postProcessPlugin,Gs as prefabsPlugin,Xs as preloadNestedPrefabs,oa as progressBarPlugin,pt as registerAnimClip,As as registerAssetBuildTransform,oe as registerComponent,Zn as registerComponentAssetFields,Me as registerDrawCallback,zs as registerEmbeddedAssets,St as registerTextureDimensions,Mt as registerTilemapSource,Xn as registerTimelineAsset,Hs as remapComponentEntityRefs,ns as remapEntityFields,Ht as resolveRelativePath,Ea as safeAreaPlugin,io as sceneManagerPlugin,Tr as screenToWorld,ga as scrollViewPlugin,Zo as setEntityColor,Qo as setEntityEnabled,Ra as setListViewRenderer,Ll as setLogLevel,ne as setWasmErrorHandler,Ae as shutdownDrawAPI,Vi as shutdownGLDebugAPI,ti as shutdownGeometryAPI,Ee as shutdownMaterialAPI,mc as shutdownParticleAPI,pi as shutdownPostProcessAPI,Di as shutdownRendererAPI,Rt as shutdownTilemapAPI,oc as shutdownTweenAPI,va as sliderPlugin,xt as spriteAnimatorSystemUpdate,kc as statsPlugin,jo as syncFillSpriteSize,Ti as syncPostProcessVolume,Yr as textInputPlugin,yr as textPlugin,vc as tilemapPlugin,Kn as timelinePlugin,Es as toBuildPath,ta as togglePlugin,yl as transitionTo,Hr as uiInteractionPlugin,Lr as uiLayoutPlugin,br as uiMaskPlugin,Oc as uiPlugins,Ka as uiRenderOrderPlugin,mt as unregisterAnimClip,Te as unregisterDrawCallback,us as updateCameraAspectRatio,Ol as warn,Ko as withChildEntity,no as wrapSceneSystem};+import{d as e,S as s,a as i,R as r,b as a,c,T as d,W as u,e as f,f as g,g as b,h as T,N as P,i as C,I as E,C as A,j as I,Q as R,P as F,k as z,l as B,B as H,m as W,E as D,n as N,o as G,p as Q,q as ee,r as te,s as ne,t as se,u as ie,v as oe,w as re,D as le,x as ce,y as de,z as ue,A as he,F as fe,G as pe,H as me}from"./shared/system.js";export{J as Added,K as Changed,L as Commands,M as CommandsInstance,O as DEFAULT_FALLBACK_DT,U as DEFAULT_FONT_FAMILY,V as DEFAULT_FONT_SIZE,X as DEFAULT_LINE_HEIGHT,Y as DEFAULT_MAX_DELTA_TIME,Z as DEFAULT_SPINE_SKIN,_ as DEFAULT_SPRITE_SIZE,$ as DEFAULT_TEXT_CANVAS_SIZE,a0 as EmitterShape,a1 as EntityCommands,a2 as EventReader,a3 as EventReaderInstance,a4 as EventWriter,a5 as EventWriterInstance,a6 as INVALID_FONT,a7 as INVALID_MATERIAL,a8 as LocalTransform,a9 as Mut,aa as ParticleEasing,ab as ParticleEmitter,ac as QueryInstance,ad as Removed,ae as RemovedQueryInstance,af as ShapeRenderer,ag as ShapeType,ah as SimulationSpace,ai as Velocity,aj as addStartupSystem,ak as addSystem,al as addSystemToSchedule,am as applyBuildRuntimeConfig,an as applyRuntimeConfig,ao as clearUserComponents,ap as color,aq as defineEvent,ar as defineTag,as as getComponentDefaults,at as getUserComponent,au as isBuiltinComponent,av as quat,aw as registerComponentEntityFields,ax as unregisterComponent,ay as vec2,az as vec3,aA as vec4}from"./shared/system.js";import{M as ge,R as ye,B as _e,C as xe,a as we,i as be,b as ve,D as Se,u as Te,g as Pe,r as Me,c as Ce,s as Ee,d as Ae,e as Ie,f as Re,P as ke}from"./shared/index.js";export{h as BlendMode,j as CapsuleCollider,k as ChainCollider,l as Physics,m as PhysicsEvents,n as PolygonCollider,o as RevoluteJoint,S as SegmentCollider,p as ShaderSources,q as isRuntime,t as isTextureRef,v as loadPhysicsModule,w as registerMaterialCallback,x as setEditorMode,y as setPlayMode}from"./shared/index.js";import{SpineManager as Fe,SpinePlugin as Ue}from"./spine/index.js";let Le=null;function ze(){if(!Le)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return Le}function Be(){return null!==Le}function Oe(){return Le?.name??null}function He(){return"wechat"===Le?.name}function $e(){return"web"===Le?.name}async function We(e,t){return ze().fetch(e,t)}async function De(e){return ze().readFile(e)}async function Xe(e){return ze().readTextFile(e)}async function Ne(e){return ze().fileExists(e)}async function Ye(e,t){return ze().instantiateWasm(e,t)}function Ve(e,t){return ze().createCanvas(e,t)}function je(){return ze().now()}function Ge(){if("wechat"===Le?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class qe{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof qe?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class Ke{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new qe(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new qe(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new qe(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new qe(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new qe(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new qe(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class Je{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class Ze{constructor(e,t,n,s,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=n,this.poolNode_=s,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class Qe{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new Ke(this.context_,e.mixerConfig),this.pool_=new Je(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const n=this.loadingUrls_.get(e);if(n)return n;const s=this.doLoadBuffer_(e);this.loadingUrls_.set(e,s);try{return await s}finally{this.loadingUrls_.delete(e)}}async loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const n=this.urlToId_.get(e);if(void 0!==n&&this.buffers_.has(n)){return{id:n,duration:this.buffers_.get(n).duration}}let s;try{s=await this.context_.decodeAudioData(t)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,s),this.urlToId_.set(e,i),{id:i,duration:s.duration}}async doLoadBuffer_(e){const t=await ze().readFile(e);return this.loadBufferFromData(e,t)}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const n=this.buffers_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=n,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(s.gain),s.source=i,s.gain.gain.value=t.volume??1,s.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;s.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new Ze(l,i,n,s,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const et=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 loadImagePixels(e){const t=this.createImage();await new Promise((n,s)=>{t.crossOrigin="anonymous",t.onload=()=>n(),t.onerror=()=>s(new Error(`Failed to load image: ${e}`)),t.src=e});const n=this.createCanvas(t.width,t.height).getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(s.data.buffer)}}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),i=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},r=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{t.preventDefault();const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{t.preventDefault();const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},d=t=>{t.preventDefault(),e.onPointerUp(0)},u=()=>{e.onPointerUp(0)},h=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",o),n.addEventListener("mousedown",r),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l,{passive:!1}),n.addEventListener("touchmove",c,{passive:!1}),n.addEventListener("touchend",d,{passive:!1}),n.addEventListener("touchcancel",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",d),n.removeEventListener("touchcancel",u),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new Qe}getStorageItem(e){return localStorage.getItem(e)}setStorageItem(e,t){localStorage.setItem(e,t)}removeStorageItem(e){localStorage.removeItem(e)}clearStorage(e){const t=[];for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);null!==s&&s.startsWith(e)&&t.push(s)}for(const e of t)localStorage.removeItem(e)}},tt="esengine:",nt={getString(e,t){const n=ze().getStorageItem(tt+e);return null!==n?n:t},setString(e,t){ze().setStorageItem(tt+e,t)},getNumber(e,t){const n=ze().getStorageItem(tt+e);if(null===n)return t;const s=Number(n);return Number.isNaN(s)?t:s},setNumber(e,t){ze().setStorageItem(tt+e,String(t))},getBoolean(e,t){const n=ze().getStorageItem(tt+e);return null===n?t:"true"===n},setBoolean(e,t){ze().setStorageItem(tt+e,String(t))},getJSON(e,t){const n=ze().getStorageItem(tt+e);if(null===n)return t;try{return JSON.parse(n)}catch(n){return console.warn(`[Storage] Failed to parse JSON for key "${e}"`,n),t}},setJSON(e,t){ze().setStorageItem(tt+e,JSON.stringify(t))},remove(e){ze().removeStorageItem(tt+e)},has:e=>null!==ze().getStorageItem(tt+e),clear(){ze().clearStorage(tt)}};class st{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 it=e(new st,"Input");class ot{constructor(e){this.target_=e??null}build(e){const t=new st;e.insertResource(it,t),ze().bindInputEvents({onKeyDown(e){t.keysDown.has(e)||t.keysPressed.add(e),t.keysDown.add(e)},onKeyUp(e){t.keysDown.delete(e),t.keysReleased.add(e)},onPointerMove(e,n){t.mouseX=e,t.mouseY=n},onPointerDown(e,n,s){t.mouseX=n,t.mouseY=s,t.mouseButtons.add(e),t.mouseButtonsPressed.add(e)},onPointerUp(e){t.mouseButtons.delete(e),t.mouseButtonsReleased.add(e)},onWheel(e,n){t.scrollDeltaX+=e,t.scrollDeltaY+=n}},this.target_??void 0),e.addSystemToSchedule(s.Last,i([],()=>{t.keysPressed.clear(),t.keysReleased.clear(),t.mouseButtonsPressed.clear(),t.mouseButtonsReleased.clear(),t.scrollDeltaX=0,t.scrollDeltaY=0},{name:"InputClearSystem"}))}}const rt=new ot,lt=e({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");class ct{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=r.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const a={promise:null,aborted:!1};a.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{a.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return a.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,a);try{return await a.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+r.assetFailureCooldown}),t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`)),t}}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()}clearAll(){this.cache_.clear(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class dt{constructor(e,t=""){this.cache_=new ct,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(ge.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ge.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await Ne(t))throw new Error(`Material file not found: ${t}`);const n=await Xe(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:ge.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 ut(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function ht(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0,duration:e.duration};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const ft=new Map;function pt(e){ft.set(e.name,e)}function mt(e){ft.delete(e)}function gt(e){return ft.get(e)}function yt(){ft.clear()}const _t=a("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function xt(e,t){const n=e.getEntitiesWithComponents([_t]);for(const s of n){const n=e.get(s,_t);if(!n.enabled||!n.playing||!n.clip)continue;const i=ft.get(n.clip);if(!i||0===i.frames.length)continue;const o=i.frames[n.currentFrame],r=o?.duration??1/(i.fps*n.speed),a=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let l=a;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),l=!0),l&&e.has(s,c)){const t=i.frames[n.currentFrame],o=e.get(s,c);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,c,o)}l&&e.insert(s,_t,n)}}class wt{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static setAssetResolver(e){this.assetResolver_=e}static resolveUrl_(e){return!this.baseUrl||e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}/${e}`}static async preload(e){if(this.bufferCache_.has(e))return;if(this.assetResolver_){const t=this.assetResolver_(e);if(t)return this.preloadFromData(e,t)}const t=await this.backend_.loadBuffer(this.resolveUrl_(e));this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}wt.mixer_=null,wt.bufferCache_=new Map,wt.bgmHandle_=null,wt.bgmVolume_=1,wt.fadeAnimId_=0,wt.disposed_=!1,wt.assetResolver_=null,wt.baseUrl="";const bt=new Map,vt=new Map;function St(e,t,n){bt.set(e,{width:t,height:n})}function Tt(e){return bt.get(e)}function Pt(){bt.clear()}function Mt(e,t){vt.set(e,t)}function Ct(e){return vt.get(e)}function Et(){vt.clear()}let At=null;function It(e){At=e}function Rt(){At=null}const kt={initLayer(e,t,n,s,i){At?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){At?.tilemap_destroyLayer(e)},setTile(e,t,n,s){At?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>At?At.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){At?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!At)return;const n=t.byteLength,s=At._malloc(n);new Uint16Array(At.HEAPU8.buffer,s,t.length).set(t),At.tilemap_setTiles(e,s,t.length),At._free(s)},hasLayer:e=>!!At&&At.tilemap_hasLayer(e),setRenderProps(e,t,n,s,i,o,r,a,l){At?.tilemap_setRenderProps(e,t,n,s,i,o,r,a,l)},setTint(e,t,n,s,i,o){At?.tilemap_setTint(e,t,n,s,i,o)},setVisible(e,t){At?.tilemap_setVisible(e,t)},setOriginEntity(e,t){At?.tilemap_setOriginEntity(e,t)},submitLayer(e,t,n,s,i,o,r,a,l,c,d,u,h,f,p,m,g,y,_,x){At?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,d,u,h,f,p,m,g,y,_,x)},setTileAnimation(e,t,n){if(!At||0===n.length)return;const s=new Uint32Array(2*n.length);for(let e=0;e<n.length;e++)s[2*e]=n[e].tileId,s[2*e+1]=n[e].duration;const i=s.byteLength,o=At._malloc(i);new Uint32Array(At.HEAPU8.buffer,o,s.length).set(s),At.tilemap_setTileAnimation(e,t,o,n.length),At._free(o)},advanceAnimations(e,t){At?.tilemap_advanceAnimations(e,t)},setTileProperty(e,t,n,s){At?.tilemap_setTileProperty(e,t,n,s)},getTileProperty:(e,t,n,s)=>At?At.tilemap_getTileProperty(e,t,n,s):"",flipTile(e,t,n,s,i,o){At?.tilemap_flipTile(e,t,n,s,i,o)},rotateTile(e,t,n,s){At?.tilemap_rotateTile(e,t,n,s)},setGridType(e,t){At?.tilemap_setGridType(e,t)},tileToWorld(e,t,n,s,i){if(!At)return{x:0,y:0};const o=At.tilemap_tileToWorld(e,t,n,s,i),r=new Float32Array(At.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}},worldToTile(e,t,n,s,i){if(!At)return{x:0,y:0};const o=At.tilemap_worldToTile(e,t,n,s,i),r=new Float32Array(At.HEAPU8.buffer,o,2);return{x:r[0],y:r[1]}}},Ft=a("Tilemap",{source:""}),Ut=a("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function Lt(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function zt(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function Bt(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function Ot(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=Bt(r[t],e)}const d="number"==typeof e.opacity?e.opacity:1,u=zt(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:d,tintColor:u,parallaxX:h,parallaxY:f})}const d=[],u=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}d.push({name:e.name??"",objects:n})}const h=new Map,f=new Map;if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.id,s=n+1,i=e.animation;if(i&&i.length>0){const e=i.map(e=>({tileId:(e.tileid??0)+1,duration:e.duration??100}));h.set(s,e)}const o=e.properties;if(o){const e=new Map;for(const s of o){const i=s.name;"collision"===i&&!0===s.value&&u.push(n+t),e.set(i,String(s.value))}e.size>0&&f.set(s,e)}}}return{width:t,height:n,tileWidth:s,tileHeight:i,orientation:e.orientation??"orthogonal",layers:c,tilesets:r,objectGroups:d,collisionTileIds:u,tileAnimations:h,tileProperties:f}}function Ht(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function $t(e,t){const n=At;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),orientation:"orthogonal",layers:[],tilesets:[],objectGroups:[],collisionTileIds:[],tileAnimations:new Map,tileProperties:new Map},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?Lt(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch(e){return console.warn("[Tiled] Failed to parse tilemap",e),n.tiled_freeMap(r),null}}const Wt=Math.PI/180;function Dt(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,h=o+(u-t.row*c)-.5*s,f=e.spawn();e.insert(f,d,{position:{x:r,y:h,z:0}}),e.insert(f,ye,{bodyType:_e.Static}),e.insert(f,we,{halfExtents:{x:.5*n,y:.5*s}}),a.push(f)}return a}function Xt(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,d,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Ut,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,h=-t.rotation*Wt;if(e.insert(r,d,{position:{x:c,y:u,z:0}}),e.insert(r,ye,{bodyType:_e.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,xe,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),d=.5*(s+o);e.insert(r,we,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-d}})}else e.insert(r,we,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,d,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=Dt(e,n,t,a,0,0);i.push(...s)}return i}const Nt=0,Yt=1,Vt=2,jt="property",Gt="spine",qt="spriteAnim",Kt="audio",Jt="activation",Zt="marker",Qt="customEvent",en="animFrames",tn="hermite",nn="linear",sn="step",on="easeIn",rn="easeOut",ln="easeInOut",cn=[["1.0","1.1",e=>{for(const t of e.tracks??[])if(t.type===jt)for(const e of t.channels??[])for(const t of e.keyframes??[])t.interpolation||Math.abs(t.outTangent)>=1e5&&(t.interpolation="step",t.outTangent=0)}]];const dn={once:Nt,loop:Yt,pingPong:Vt};function un(e){const t={name:e.name??"",childPath:e.childPath??""};switch(e.type){case jt:return{...t,type:jt,component:e.component??"",channels:(e.channels??[]).map(e=>({property:e.property,keyframes:e.keyframes??[]}))};case Gt:return{...t,type:Gt,clips:e.clips??[],blendIn:e.blendIn??0};case qt:return{...t,type:qt,clip:e.clip??"",startTime:e.startTime??0};case Kt:return{...t,type:Kt,events:e.events??[]};case Jt:return{...t,type:Jt,ranges:e.ranges??[]};case Zt:return{...t,type:Zt,markers:e.markers??[]};case Qt:return{...t,type:Qt,events:(e.events??[]).map(e=>({time:e.time??0,name:e.name??"",payload:e.payload??{}}))};case en:return{...t,type:en,frames:(e.animFrames??[]).map(e=>({texture:e.texture??"",duration:e.duration}))};default:return console.warn(`[Timeline] Unknown track type: ${e.type}, skipping`),null}}function hn(e){return function(e){let t=e.version??"1.0";for(const[n,s,i]of cn)t===n&&(i(e),t=s);e.version="1.1"}(e),{version:"1.1",type:"timeline",duration:e.duration??0,wrapMode:(t=e.wrapMode,t?dn[t]??Nt:Nt),tracks:(e.tracks??[]).map(un).filter(e=>null!==e)};var t}var fn,pn;!function(e){e[e.PositionX=0]="PositionX",e[e.PositionY=1]="PositionY",e[e.PositionZ=2]="PositionZ",e[e.ScaleX=3]="ScaleX",e[e.ScaleY=4]="ScaleY",e[e.ScaleZ=5]="ScaleZ",e[e.RotationZ=6]="RotationZ",e[e.ColorR=7]="ColorR",e[e.ColorG=8]="ColorG",e[e.ColorB=9]="ColorB",e[e.ColorA=10]="ColorA",e[e.SpriteOpacity=11]="SpriteOpacity",e[e.SpriteSizeX=12]="SpriteSizeX",e[e.SpriteSizeY=13]="SpriteSizeY",e[e.OffsetMinX=14]="OffsetMinX",e[e.OffsetMinY=15]="OffsetMinY",e[e.OffsetMaxX=16]="OffsetMaxX",e[e.OffsetMaxY=17]="OffsetMaxY",e[e.AnchorMinX=18]="AnchorMinX",e[e.AnchorMinY=19]="AnchorMinY",e[e.AnchorMaxX=20]="AnchorMaxX",e[e.AnchorMaxY=21]="AnchorMaxY",e[e.PivotX=22]="PivotX",e[e.PivotY=23]="PivotY",e[e.CameraOrthoSize=24]="CameraOrthoSize",e[e.CustomField=25]="CustomField"}(fn||(fn={})),function(e){e[e.Transform=0]="Transform",e[e.Sprite=1]="Sprite",e[e.UIRect=2]="UIRect",e[e.Camera=3]="Camera",e[e.Custom=4]="Custom"}(pn||(pn={}));const mn={Transform:{"position.x":fn.PositionX,"position.y":fn.PositionY,"position.z":fn.PositionZ,"scale.x":fn.ScaleX,"scale.y":fn.ScaleY,"scale.z":fn.ScaleZ,rotation:fn.RotationZ},Sprite:{"color.r":fn.ColorR,"color.g":fn.ColorG,"color.b":fn.ColorB,"color.a":fn.ColorA,opacity:fn.SpriteOpacity,"size.x":fn.SpriteSizeX,"size.y":fn.SpriteSizeY},UIRect:{"offsetMin.x":fn.OffsetMinX,"offsetMin.y":fn.OffsetMinY,"offsetMax.x":fn.OffsetMaxX,"offsetMax.y":fn.OffsetMaxY,"anchorMin.x":fn.AnchorMinX,"anchorMin.y":fn.AnchorMinY,"anchorMax.x":fn.AnchorMaxX,"anchorMax.y":fn.AnchorMaxY,"pivot.x":fn.PivotX,"pivot.y":fn.PivotY},Camera:{orthoSize:fn.CameraOrthoSize}},gn={Transform:pn.Transform,Sprite:pn.Sprite,UIRect:pn.UIRect,Camera:pn.Camera},yn={[tn]:0,[nn]:1,[sn]:2,[on]:3,[rn]:4,[ln]:5};function _n(e){return e?yn[e]??0:0}function xn(e,t){return mn[e]?.[t]??fn.CustomField}function wn(e,t){const n=(new TextEncoder).encode(t),s=e._malloc(n.length);return new Uint8Array(e.HEAPU8.buffer,s,n.length).set(n),[s,n.length]}function bn(e,t){e._free(t)}function vn(e,t){const n=e._tl_create(t.duration,t.wrapMode);if(!n)return{handle:0,tracks:[],totalPropertyChannels:0};const s=[];let i=0;for(const o of t.tracks)switch(o.type){case jt:Sn(e,n,o),s.push({type:"property",component:o.component,childPath:o.childPath,channelProperties:o.channels.map(e=>e.property)}),i+=o.channels.length;break;case Gt:Tn(e,n,o),s.push({type:"spine",childPath:o.childPath});break;case Kt:Pn(e,n,o),s.push({type:"audio",childPath:o.childPath});break;case Jt:Mn(e,n,o),s.push({type:"activation",childPath:o.childPath});break;case qt:Cn(e,n,o),s.push({type:"spriteAnim",childPath:o.childPath})}return{handle:n,tracks:s,totalPropertyChannels:i}}function Sn(e,t,n){const s=e,i=n.channels.length,o=gn[n.component]??pn.Custom;if(o===pn.Custom)return void function(e,t,n){const s=e,i=n.channels.length,[o,r]=wn(e,n.childPath),[a,l]=wn(e,n.component),c=n.channels.map(e=>(new TextEncoder).encode(e.property));let d=0;for(const e of c)d+=e.length;const u=s._malloc(d);let h=0;for(const e of c)new Uint8Array(s.HEAPU8.buffer,u+h,e.length).set(e),h+=e.length;const f=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,f,i).set(c.map(e=>e.length));let p=0;const m=[];for(const e of n.channels)m.push(e.keyframes.length),p+=e.keyframes.length;const g=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,g,i).set(m);const y=s._malloc(5*p*4),_=new Float32Array(s.HEAPU8.buffer,y,5*p);let x=0;for(const e of n.channels)for(const t of e.keyframes)_[x++]=t.time,_[x++]=t.value,_[x++]=t.inTangent,_[x++]=t.outTangent,_[x++]=_n(t.interpolation);e._tl_addCustomPropertyTrack(t,o,r,a,l,u,f,i,y,g),bn(e,o),bn(e,a),bn(e,u),bn(e,f),bn(e,g),bn(e,y)}(e,t,n);const[r,a]=wn(e,n.childPath),l=s._malloc(i),c=new Uint8Array(s.HEAPU8.buffer,l,i);for(let e=0;e<i;e++)c[e]=xn(n.component,n.channels[e].property);let d=0;const u=[];for(const e of n.channels)u.push(e.keyframes.length),d+=e.keyframes.length;const h=s._malloc(4*i);new Int32Array(s.HEAPU8.buffer,h,i).set(u);const f=s._malloc(5*d*4),p=new Float32Array(s.HEAPU8.buffer,f,5*d);let m=0;for(const e of n.channels)for(const t of e.keyframes)p[m++]=t.time,p[m++]=t.value,p[m++]=t.inTangent,p[m++]=t.outTangent,p[m++]=_n(t.interpolation);e._tl_addPropertyTrack(t,r,a,o,l,i,f,h),bn(e,r),bn(e,l),bn(e,h),bn(e,f)}function Tn(e,t,n){if(n.type!==Gt)return;const s=e,[i,o]=wn(e,n.childPath),r=n.clips.length,a=s._malloc(4*r*4),l=new Float32Array(s.HEAPU8.buffer,a,4*r),c=s._malloc(4*r),d=new Uint32Array(s.HEAPU8.buffer,c,r),u=s._malloc(4*r),h=new Int32Array(s.HEAPU8.buffer,u,r),f=[];for(let t=0;t<r;t++){const s=n.clips[t];l[4*t]=s.start,l[4*t+1]=s.duration,l[4*t+2]=s.speed,l[4*t+3]=s.loop?1:0;const[i,o]=wn(e,s.animation);d[t]=i,h[t]=o,f.push(i)}e._tl_addSpineTrack(t,i,o,a,c,u,r,n.blendIn),bn(e,i),bn(e,a),bn(e,c),bn(e,u);for(const t of f)bn(e,t)}function Pn(e,t,n){if(n.type!==Kt)return;const s=e,[i,o]=wn(e,n.childPath),r=n.events.length,a=s._malloc(2*r*4),l=new Float32Array(s.HEAPU8.buffer,a,2*r),c=s._malloc(4*r),d=new Uint32Array(s.HEAPU8.buffer,c,r),u=s._malloc(4*r),h=new Int32Array(s.HEAPU8.buffer,u,r),f=[];for(let t=0;t<r;t++){const s=n.events[t];l[2*t]=s.time,l[2*t+1]=s.volume;const[i,o]=wn(e,s.clip);d[t]=i,h[t]=o,f.push(i)}e._tl_addAudioTrack(t,i,o,a,c,u,r),bn(e,i),bn(e,a),bn(e,c),bn(e,u);for(const t of f)bn(e,t)}function Mn(e,t,n){if(n.type!==Jt)return;const s=e,[i,o]=wn(e,n.childPath),r=s._malloc(2*n.ranges.length*4),a=new Float32Array(s.HEAPU8.buffer,r,2*n.ranges.length);for(let e=0;e<n.ranges.length;e++)a[2*e]=n.ranges[e].start,a[2*e+1]=n.ranges[e].end;e._tl_addActivationTrack(t,i,o,r,n.ranges.length),bn(e,i),bn(e,r)}function Cn(e,t,n){if(n.type!==qt)return;const[s,i]=wn(e,n.childPath),[o,r]=wn(e,n.clip);e._tl_addSpriteAnimTrack(t,s,i,o,r,n.startTime),bn(e,s),bn(e,o)}const En=new Map;let An=null;function In(e,t){En.set(e,t)}function Rn(e){return En.get(e)}function kn(){if(An)for(const e of En.values())An._tl_destroy(e);En.clear()}var Fn;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Fn||(Fn={}));const Un={model:Fn.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Ln(e,t=Un){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case Fn.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case Fn.Inverse:a=s/Math.max(r,s);break;case Fn.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function zn(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const Bn=a("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Fn.Inverse,rolloff:1,priority:0,enabled:!0}),On=a("AudioListener",{enabled:!0});class Hn{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const t=ze().createAudioBackend(),n=this.config_;t.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const o=t.mixer;wt.init(t,o),o&&(void 0!==n.masterVolume&&(o.master.volume=n.masterVolume),void 0!==n.musicVolume&&(o.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(o.sfx.volume=n.sfxVolume));const r=new Map;this.activeSourceHandles_=r;const a=new Set;this.playedEntities_=a;const l=new Set;let c=!1,d=!1;e.addSystemToSchedule(s.PreUpdate,i([f(g)],n=>{if(!(!be()||ve()))return void(d&&(c=!1,d=!1));d=!0;const s=e.world;let i=0,o=0,h=!1;const f=s.getEntitiesWithComponents([On,u]);for(const e of f){if(s.get(e,On).enabled){const t=s.get(e,u);i=t.position.x,o=t.position.y,h=!0;break}}const p=s.getEntitiesWithComponents([Bn]);l.clear();for(const e of p){const n=s.get(e,Bn);if(!n.enabled||!n.clip)continue;const d=e;if(l.add(d),n.playOnAwake&&!a.has(d)&&!r.has(d)&&t.isReady){const e=wt.getBufferHandle(n.clip);if(e){const s=t.play(e,{bus:n.bus,volume:n.volume,loop:n.loop,playbackRate:n.pitch});r.set(d,s),a.add(d)}else console.warn(`[AudioPlugin] playOnAwake: clip "${n.clip}" not preloaded`)}if(n.spatial&&r.has(d)){const t=r.get(d);if(!t.isPlaying){r.delete(d);continue}h||c||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),c=!0);const a=s.tryGet?.(e,u),l=a?.position.x??0,f=a?.position.y??0,p=l-i,m=f-o,g=Ln(Math.sqrt(p*p+m*m),{model:n.attenuationModel,refDistance:n.minDistance,maxDistance:n.maxDistance,rolloff:n.rolloff}),y=zn(l,0,i,0,n.maxDistance);t.setVolume(n.volume*g),t.setPan(y)}}for(const[e,t]of r)l.has(e)&&t.isPlaying||r.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),wt.dispose()}}const $n=new Hn,Wn=a("TimelinePlayer",{timeline:"",playing:!1,speed:1,wrapMode:"once"}),Dn=new Map;function Xn(e,t){Dn.set(e,t)}const Nn=new Map;function Yn(e,t){return Nn.get(e)?.get(t)??0}const Vn={once:Nt,loop:Yt,pingPong:Vt};function jn(e,t,n){const s=t.split(".");let i=e;for(let e=0;e<s.length-1;e++)if(i=i[s[e]],null==i||"object"!=typeof i)return!1;const o=s[s.length-1];return o in i&&(i[o]=n,!0)}function Gn(e,t,n){if(!n)return t;const s=b("Children"),i=b("Name");if(!s||!i)return null;let o=t;const r=n.split("/");for(const t of r){const n=e.tryGet(o,s);if(!n)return null;const r=n.entities||[];let a=null;for(const n of r){const s=e.tryGet(n,i);if(s&&s.value===t){a=n;break}}if(null===a)return null;o=a}return o}class qn{constructor(){this.name="TimelinePlugin",this.handles_=new Map,this.animFramesStates_=new Map}build(e){const t=e.world;e.addSystemToSchedule(s.Update,i([f(g)],e=>{if(be()&&!ve())return;const n=t.getWasmModule();if(!n)return;An=n;const s=t.getCppRegistry();n.uiRect_clearAnimOverrides(s);const i=t.getEntitiesWithComponents([Wn]);for(const s of i){const i=t.get(s,Wn);if(!i.timeline)continue;let o=this.handles_.get(s);if(!o){const e=Dn.get(i.timeline);if(!e)continue;if(o=vn(n,e),!o.handle)continue;this.resolveTrackTargets(t,n,o,s),this.handles_.set(s,o),In(s,o.handle);const r=e.tracks.filter(e=>e.type===en);r.length>0&&this.animFramesStates_.set(s,{tracks:r,lastFrameIndices:r.map(()=>-1)})}const r=o.handle;if(i.playing&&!n._tl_isPlaying(r)){const e=n._tl_getTime(r);0===e?n._tl_play(r):(n._tl_play(r),n._tl_setTime(r,e))}else!i.playing&&n._tl_isPlaying(r)&&n._tl_pause(r);const a=Vn[i.wrapMode]??Nt;n._tl_setWrapMode(r,a),n._tl_advance(t.getCppRegistry(),r,s,e.delta,i.speed),this.processEvents(t,n),this.processCustomProperties(t,n,o),this.processAnimFrames(t,n,s,o.handle,i.timeline),n._tl_clearResults(),!n._tl_isPlaying(r)&&i.playing&&(i.playing=!1,t.insert(s,Wn,i))}},{name:"TimelineSystem"}))}clearHandles(){this.handles_.clear(),this.animFramesStates_.clear()}cleanup(){this.handles_.clear(),this.animFramesStates_.clear(),Dn.clear()}processAnimFrames(e,t,n,s,i){const o=this.animFramesStates_.get(n);if(!o)return;const r=t._tl_getTime(s),a=b("Sprite");if(!a||!e.has(n,a))return;const l=1/12;for(let t=0;t<o.tracks.length;t++){const s=o.tracks[t].frames;if(0===s.length)continue;let c=0,d=0;for(let e=0;e<s.length;e++){const t=s[e].duration??l;if(r<c+t){d=e;break}c+=t,e===s.length-1&&(d=s.length-1)}if(d!==o.lastFrameIndices[t]){o.lastFrameIndices[t]=d;const r=Yn(i,s[d].texture);if(r){const t=e.get(n,a);t.texture=r,e.set(n,a,t)}}}}resolveTrackTargets(e,t,n,s){let i=0,o=0;for(const r of n.tracks){if(!r.childPath){"property"===r.type?i++:o++;continue}const a=Gn(e,s,r.childPath);if(null!==a){const e="property"!==r.type,s=e?o:i;t._tl_setTrackTarget(n.handle,e?1:0,s,a)}"property"===r.type?i++:o++}}decodeEventString(e,t){const n=e._tl_getEventString(t),s=e._tl_getEventStringLen(t);if(!n||s<=0)return"";const i=new Uint8Array(e.HEAPU8.buffer,n,s);return(new TextDecoder).decode(i)}processEvents(e,t){const n=t._tl_getEventCount();for(let s=0;s<n;s++){const n=t._tl_getEventType(s),i=t._tl_getEventEntity(s);switch(n){case 0:{const n=this.decodeEventString(t,s),o=0!==t._tl_getEventIntParam(s);if(e.has(i,T)){const t=e.get(i,T);t.animation=n,t.playing=!0,t.loop=o,e.set(i,T,t)}break}case 1:if(e.has(i,T)){const t=e.get(i,T);t.playing=!1,e.set(i,T,t)}break;case 2:{const n=this.decodeEventString(t,s);if(e.has(i,_t)){const t=e.get(i,_t);e.insert(i,_t,{...t,clip:n,playing:!0})}break}case 3:{const e=this.decodeEventString(t,s),n=t._tl_getEventFloatParam(s);e&&wt.playSFX(e,{volume:n});break}case 4:{const n=0!==t._tl_getEventIntParam(s);if(e.has(i,T)){const t=e.get(i,T);t.enabled=n,e.set(i,T,t)}if(e.has(i,_t)){const t=e.get(i,_t);e.insert(i,_t,{...t,enabled:n})}const o=b("Sprite");if(o&&e.has(i,o)){const t=e.get(i,o);e.set(i,o,{...t,enabled:n})}break}}}}processCustomProperties(e,t,n){const s=t._tl_getCustomPropertyCount();if(0!==s)for(let i=0;i<s;i++){const s=t._tl_getCustomPropertyEntity(i),o=t._tl_getCustomPropertyTrackIndex(i),r=t._tl_getCustomPropertyChannelIndex(i),a=t._tl_getCustomPropertyValue(i),l=n.tracks.filter(e=>"property"===e.type)[o];if(!l?.component||!l.channelProperties)continue;const c=b(l.component);if(!c||!e.has(s,c))continue;const d=e.get(s,c),u=l.channelProperties[r];u&&jn(d,u,a)&&e.set(s,c,d)}}}const Kn=new qn,Jn=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["UIRenderer",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}],["TimelinePlayer",{fields:[{field:"timeline",type:"timeline"}]}]]);function Zn(e,t){Jn.set(e,t)}function Qn(e){const t=Jn.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function es(e){return Jn.get(e)?.fields??[]}function ts(e){return Jn.get(e)?.spine??null}function ns(e,t){const n=C(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&n!==E){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:E}}}function ss(e){const t=e.components.some(e=>"UIRect"===e.type),n=e.components.findIndex(e=>"Sprite"===e.type),s=e.components.some(e=>"UIRenderer"===e.type);if(!t||-1===n||s)return;const i=e.components[n].data,o=i.texture;e.components.push({type:"UIRenderer",data:{visualType:o?2:1,texture:o??0,color:i.color??{r:1,g:1,b:1,a:1},uvOffset:i.uvOffset??{x:0,y:0},uvScale:i.uvScale??{x:1,y:1},sliceBorder:i.sliceBorder??{x:0,y:0,z:0,w:0},material:i.material??0,enabled:i.enabled??!0}}),e.components.splice(n,1)}function is(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,P,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;ss(s);const t=n.get(s.id);for(const i of s.components)ns(i,n),cs(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function os(e,t){return is(e,t)}async function rs(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of ls.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Jn.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...ls.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),d=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...d]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Jn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=is(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const ls=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),St(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=ut(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);pt(ht(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await wt.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=Ot(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=Ht(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),St(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Mt(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}],["timeline",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=hn(await t.loadJson(e));Xn(e,i);const o=function(e){const t=new Set,n=new Set,s=new Set;for(const i of e.tracks)if(i.type===Kt)for(const e of i.events)t.add(e.clip);else if(i.type===qt)i.clip&&n.add(i.clip);else if(i.type===en)for(const e of i.frames)e.texture&&s.add(e.texture);return{audio:Array.from(t),animClips:Array.from(n),textures:Array.from(s)}}(i);if(o.textures.length>0){const i=new Map,r=o.textures.map(async e=>{try{const o=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o)}catch(t){console.warn(`Failed to load animFrames texture: ${e}`,t),i.set(e,0)}});await Promise.all(r),function(e,t){Nn.set(e,t)}(e,i)}}catch(t){console.warn(`Failed to load timeline: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function cs(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=b(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function ds(e,t){const n=e.getEntitiesWithComponents([A]);for(const s of n){const n=e.get(s,A);n&&(n.aspectRatio=t,e.insert(s,A,n))}}function us(e,t){const n=e.getEntitiesWithComponents([P]);for(const s of n){const n=e.get(s,P);if(n&&n.value===t)return s}return null}const hs=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["estimeline"],contentType:"json",editorType:"timeline",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],fs={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",estimeline:"application/json",bmfont:"application/json",fnt:"text/plain"},ps=new Map,ms=new Set;for(const e of hs)for(const t of e.extensions)ps.set(t,e),ms.add(t);function gs(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function ys(e){return ps.get(gs(e))}function _s(e){return ys(e)?.editorType??"unknown"}function xs(e){return ys(e)?.addressableType??null}function ws(e){for(const t of hs)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function bs(e){return ms.has(e.toLowerCase())}function vs(){return ms}function Ss(e){return"string"==typeof e&&(!!e.includes("/")&&bs(gs(e)))}function Ts(){const e=[];for(const t of hs)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function Ps(){return Ts().map(e=>({type:"suffix",value:e}))}function Ms(e){return fs[e.toLowerCase()]}function Cs(e){const t=ys(e);return t?.wechatPackInclude??!1}function Es(e){const t=ys(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function As(e,t){for(const n of hs)n.editorType===e&&(n.buildTransform=t)}function Is(e){return ys(e)?.buildTransform}class Rs{constructor(e){this.textureCache_=new ct,this.shaderCache_=new ct,this.jsonCache_=new ct,this.textCache_=new ct,this.binaryCache_=new ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ct,this.prefabCache_=new ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=Ve(r.textCanvasSize,r.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new dt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureRefCounts_.get(s);if(void 0===i)continue;const o=this.textureCache_.get(s);if(!o)continue;const r=i-1;r<=0?(t.releaseTexture(o.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),ge.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),d="binary"===ys(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=ys(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of Qn(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=ts(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 rs(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((t,n)=>{const s=ze().createImage();s.crossOrigin="anonymous",s.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(s,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(s)},s.onerror=()=>n(new Error(`Failed to load image: ${e}`)),s.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return ge.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await Ne(t))throw new Error(`Shader file not found: ${e}`);const s=await Xe(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return ge.createShader(i,o)}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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(Es(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await Xe(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await We(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 n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return Xe(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await We(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 n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return De(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await We(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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 ks=e(null,"Assets");class Fs{build(e){const t=e.wasmModule;t?e.insertResource(ks,new Rs(t)):console.warn("AssetPlugin: No WASM module available")}}const Us=new Fs;class Ls{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function zs(e,t){const n=e.getResource(ks);n&&n.registerEmbeddedAssets(t)}function Bs(e){return e.map(e=>({type:e.type,data:JSON.parse(JSON.stringify(e.data))}))}function Os(e){return JSON.parse(JSON.stringify(e))}function Hs(e,t){for(const n of e){const e=C(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function $s(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:Os(n.componentData.data)})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}function Ws(e,t,n){const s=n.depth??0;if(s>10)throw new Error(`Prefab nesting depth exceeded 10. Check for deep or circular nesting in: ${e.name}`);if(e.basePrefab)return function(e,t,n,s){const i=e.basePrefab,o=n.visited??new Set;if(o.has(i))throw new Error(`[Prefab] Circular variant reference detected: "${i}" is already being instantiated in the current prefab chain`);const r=n.loadPrefab(i);if(!r)throw new Error(`Failed to load base prefab for variant: ${i}`);o.add(i);const a=[...e.overrides??[],...t];return Ws(r,a,{...n,visited:o,depth:s+1})}(e,t,n,s);const i=n.visited??new Set,o=new Map;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,n.allocateId());const r=[];for(const a of e.entities){if(a.nestedPrefab){const e=a.nestedPrefab.prefabPath;if(i.has(e))throw new Error(`[Prefab] Circular reference detected: "${e}" is already being instantiated in the current prefab chain`);const t=n.loadPrefab(e);if(!t)throw new Error(`Failed to load nested prefab: ${e}`);i.add(e);const l=Ws(t,a.nestedPrefab.overrides,{...n,visited:i,depth:s+1});o.set(a.prefabEntityId,l.rootId);const c=l.entities.find(e=>e.id===l.rootId);c&&(c.parent=null!==a.parent?o.get(a.parent)??null:null),r.push(...l.entities);continue}const l=o.get(a.prefabEntityId),c=a.prefabEntityId===e.rootEntityId,d={id:l,prefabEntityId:a.prefabEntityId,name:a.name,parent:c?null:null!==a.parent?o.get(a.parent)??null:null,children:a.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:Bs(a.components),visible:a.visible};Hs(d.components,o),$s(d,t),r.push(d)}const a=o.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:r,rootId:a}}function Ds(e,t,n){const s=[],i=n??new Set;if(e.basePrefab&&!i.has(e.basePrefab)){i.add(e.basePrefab),s.push(e.basePrefab);const n=t(e.basePrefab);n&&s.push(...Ds(n,t,i))}for(const n of e.entities){if(!n.nestedPrefab)continue;const e=n.nestedPrefab.prefabPath;if(i.has(e))continue;i.add(e),s.push(e);const o=t(e);o&&s.push(...Ds(o,t,i))}return s}async function Xs(e,t,n,s,i=0){if(i>10)return;const o=s??new Set;if(e.basePrefab&&!o.has(e.basePrefab)&&!n.has(e.basePrefab)){o.add(e.basePrefab);const s=await t(e.basePrefab);n.set(e.basePrefab,s),await Xs(s,t,n,o,i+1)}for(const s of e.entities){if(!s.nestedPrefab)continue;const e=s.nestedPrefab.prefabPath;if(o.has(e)||n.has(e))continue;o.add(e);const r=await t(e);n.set(e,r),await Xs(r,t,n,o,i+1)}}async function Ns(e,t,n){const s=new Map;n?.assetServer&&await Xs(t,e=>n.assetServer.loadPrefab(e,n.assetBaseUrl),s);let i=0;const o={allocateId:()=>i++,loadPrefab:e=>s.get(e)??null,visited:new Set},{entities:r,rootId:a}=Ws(t,n?.overrides??[],o),l={version:t.version,name:t.name,entities:r.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},c=await rs(e,l,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),d=c.get(a);return void 0!==n?.parent&&e.setParent(d,n.parent),{root:d,entities:c}}class Ys{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ns(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vs=e(null,"Prefabs");class js{constructor(){this.name="PrefabsPlugin",this.dependencies=[ks]}build(e){const t=e.getResource(ks);e.insertResource(Vs,new Ys(e.world,t))}}const Gs=new js;var qs;!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"}(qs||(qs={}));let Ks=null,Js=0,Zs=0,Qs=0;function ei(e){Ks=e,Js=Ks._malloc(262144),Zs=Ks._malloc(65536),Qs=Ks._malloc(256)}function ti(){Ks&&(Js&&Ks._free(Js),Zs&&Ks._free(Zs),Qs&&Ks._free(Qs),Js=0,Zs=0,Qs=0),Ks=null}function ni(){if(!Ks)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ks}const si={create(e){const t=ni(),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,Js/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Qs,i).set(o),t.geometry_init(n,Js,s,Qs,i,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,Zs,s).set(e.indices),t.geometry_setIndices16(n,Zs,s)}else{new Uint32Array(t.HEAPU8.buffer,Zs,s).set(e.indices),t.geometry_setIndices32(n,Zs,s)}}return n},updateVertices(e,t,n=0){const s=ni(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,Js/4),s.geometry_updateVertices(e,Js,i,n)},release(e){e>0&&ni().geometry_release(e)},isValid:e=>!(!Ks||e<=0)&&Ks.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return si.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:qs.Float2},{name:"a_texCoord",type:qs.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 i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return si.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:qs.Float2},{name:"a_texCoord",type:qs.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return si.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:qs.Float2},{name:"a_texCoord",type:qs.Float2}],indices:new Uint16Array(r)})}};let ii=1;const oi=new Map,ri=new Map;function li(){return oi}function ci(){return ri}class di{constructor(){this.passes_=[],this.destroyed_=!1,this.id=ii++,oi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}clearPasses(){return this.passes_.length=0,this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of ri)t===this&&ri.delete(e);oi.delete(this.id)}}}const ui="#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";let hi=null;function fi(e){hi=e}function pi(){for(const e of li().values())e.destroy();li().clear(),ci().clear(),hi&&gi.isInitialized()&&gi.shutdown(),hi=null}function mi(){if(!hi)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return hi}const gi={createStack:()=>new di,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");ci().set(e,t)},unbind(e){ci().delete(e)},getStack:e=>ci().get(e)??null,init(e,t){try{return mi().postprocess_init(e,t)}catch(n){return I(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{mi().postprocess_shutdown()}catch(e){I(e,"PostProcess.shutdown")}},resize(e,t){try{mi().postprocess_resize(e,t)}catch(n){I(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!hi)return!1;try{return hi.postprocess_isInitialized()}catch(e){return I(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{mi().postprocess_setBypass(e)}catch(e){I(e,"PostProcess.setBypass")}},begin(){try{mi().postprocess_begin()}catch(e){I(e,"PostProcess.begin")}},end(){try{mi().postprocess_end()}catch(e){I(e,"PostProcess.end")}},setOutputViewport(e,t,n,s){try{mi().postprocess_setOutputViewport(e,t,n,s)}catch(e){I(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=ci().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(gi.isInitialized()||gi.init(1,1),gi.setBypass(!1),function(e){const t=mi();try{t.postprocess_clearPasses()}catch(e){return void I(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){I(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){I(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){I(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):gi.setBypass(!0)},_resetAfterCamera(){try{mi().postprocess_clearPasses(),mi().postprocess_setBypass(!0)}catch(e){I(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of ci().keys())e(t)||ci().delete(t)},screenStack:null,setScreenStack(e){gi.screenStack=e},_beginScreenCapture(){try{mi().postprocess_beginScreenCapture()}catch(e){I(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{mi().postprocess_endScreenCapture()}catch(e){I(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=gi.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=mi();try{t.postprocess_clearScreenPasses()}catch(e){return void I(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){I(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){I(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){I(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{mi().postprocess_executeScreenPasses()}catch(e){I(e,"PostProcess._executeScreenPasses")}},createBlur:()=>ge.createShader(ui,"#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:()=>ge.createShader(ui,"#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 vig = 1.0 - smoothstep(1.0 - u_softness, 1.0, dist);\n fragColor = vec4(color.rgb * mix(1.0, vig, u_intensity), color.a);\n}\n"),createGrayscale:()=>ge.createShader(ui,"#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"),createBloomExtract:()=>ge.createShader(ui,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_threshold;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float brightness = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float knee = u_threshold * 0.5;\n float soft = brightness - u_threshold + knee;\n soft = clamp(soft, 0.0, 2.0 * knee);\n soft = soft * soft / (4.0 * knee + 0.00001);\n float contrib = max(soft, brightness - u_threshold);\n contrib /= max(brightness, 0.00001);\n fragColor = vec4(color.rgb * contrib, 1.0);\n}\n"),createBloomKawase(e){const t=`#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n float d = (${e.toFixed(1)} + 0.5) * max(u_radius, 0.5);\n vec2 ts = 1.0 / u_resolution;\n fragColor = (\n texture(u_texture, v_texCoord + vec2(-d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, -d) * ts) +\n texture(u_texture, v_texCoord + vec2(-d, d) * ts) +\n texture(u_texture, v_texCoord + vec2( d, d) * ts)\n ) * 0.25;\n}\n`;return ge.createShader(ui,t)},createBloomComposite:()=>ge.createShader(ui,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform sampler2D u_sceneTexture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 blur = texture(u_texture, v_texCoord);\n vec4 scene = texture(u_sceneTexture, v_texCoord);\n fragColor = vec4(scene.rgb + blur.rgb * u_intensity, scene.a);\n}\n"),createChromaticAberration:()=>ge.createShader(ui,"#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")},yi=new Map;function _i(e){yi.set(e.type,e)}function xi(e){return yi.get(e)}function wi(){return Array.from(yi.keys())}function bi(){return Array.from(yi.values())}_i({type:"blur",label:"Blur",factory:()=>gi.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),_i({type:"bloom",label:"Bloom",factory:()=>gi.createBloomExtract(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:1,step:.01,defaultValue:.4},{name:"u_intensity",label:"Intensity",min:0,max:5,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:.5,max:5,step:.1,defaultValue:1}],multiPass:[{name:"bloom_extract",factory:()=>gi.createBloomExtract()},{name:"bloom_kawase_0",factory:()=>gi.createBloomKawase(0)},{name:"bloom_kawase_1",factory:()=>gi.createBloomKawase(1)},{name:"bloom_kawase_2",factory:()=>gi.createBloomKawase(2)},{name:"bloom_kawase_3",factory:()=>gi.createBloomKawase(3)},{name:"bloom_kawase_4",factory:()=>gi.createBloomKawase(4)},{name:"bloom_composite",factory:()=>gi.createBloomComposite()}]}),_i({type:"vignette",label:"Vignette",factory:()=>gi.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:.6},{name:"u_softness",label:"Softness",min:0,max:1,step:.01,defaultValue:.5}]}),_i({type:"grayscale",label:"Grayscale",factory:()=>gi.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),_i({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>gi.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const vi=new Map,Si=new Map;function Ti(e,t){let n=vi.get(e),s=Si.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=gi.createStack(),vi.set(e,n)),s||(s=new Map,Si.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=xi(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}gi.bind(e,n)}else if(n&&(gi.unbind(e),n.destroy(),vi.delete(e)),s){for(const e of s.values())ge.releaseShader(e);Si.delete(e)}}function Pi(e){const t=vi.get(e);t&&(gi.unbind(e),t.destroy(),vi.delete(e));const n=Si.get(e);if(n){for(const e of n.values())ge.releaseShader(e);Si.delete(e)}}function Mi(){for(const e of vi.keys())Pi(e)}const Ci=e({enabled:!0},"PostProcessVolumeConfig"),Ei=new Map,Ai=new Map;function Ii(e,t){const n=Ai.get(e);if(void 0!==n)return n;const s=t();return Ai.set(e,s),s}function Ri(e,t){if(0===t.size){const t=Ei.get(e);return void(t&&(gi.unbind(e),t.destroy(),Ei.delete(e)))}let n=Ei.get(e);n||(n=gi.createStack(),Ei.set(e,n)),n.clearPasses();for(const[e,s]of t){if(!s.enabled)continue;const t=xi(e);if(t)if(t.multiPass)for(const e of t.multiPass){const t=Ii(e.name,e.factory);n.addPass(e.name,t);for(const[t,i]of s.uniforms)n.setUniform(e.name,t,i)}else{const i=Ii(e,t.factory);n.addPass(e,i);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?gi.bind(e,n):gi.unbind(e)}const ki=i([R(F,d),R(A)],(e,t)=>{const n=[];for(const[t,s,i]of e)n.push({data:s,tx:{x:i.position.x,y:i.position.y}});const s=[];for(const{data:e}of n)e.isGlobal&&s.push({data:e,factor:1});const i=s.length>0?function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(s):new Map;for(const[e,n]of t)n.isActive&&Ri(e,i)},{name:"PostProcessVolumeSystem"});class Fi{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Ci,{enabled:!0}),e.addSystemToSchedule(s.PostUpdate,ki)}cleanup(){Mi(),function(){for(const[e,t]of Ei)gi.unbind(e),t.destroy();Ei.clear();for(const e of Ai.values())ge.releaseShader(e);Ai.clear()}(),gi.setScreenStack(null)}}const Ui=new Fi;var Li,zi;!function(e){e[e.BatchFull=0]="BatchFull",e[e.TextureSlotsFull=1]="TextureSlotsFull",e[e.ScissorChange=2]="ScissorChange",e[e.StencilChange=3]="StencilChange",e[e.MaterialChange=4]="MaterialChange",e[e.BlendModeChange=5]="BlendModeChange",e[e.StageEnd=6]="StageEnd",e[e.TypeChange=7]="TypeChange",e[e.FrameEnd=8]="FrameEnd"}(Li||(Li={})),function(e){e[e.Sprite=0]="Sprite",e[e.Spine=1]="Spine",e[e.Mesh=2]="Mesh",e[e.ExternalMesh=3]="ExternalMesh",e[e.Text=4]="Text",e[e.Particle=5]="Particle",e[e.Shape=6]="Shape",e[e.UIElement=7]="UIElement"}(zi||(zi={}));var Bi;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bi||(Bi={}));const Oi={None:0,Spine:1,Particles:2};let Hi=null,$i=0;function Wi(e){Hi=e,$i=Hi._malloc(64)}function Di(){Hi&&$i&&(Hi._free($i),$i=0),Hi=null}const Xi={init(e,t){Hi?.renderer_init(e,t)},resize(e,t){Hi?.renderer_resize(e,t)},beginFrame(){Hi?.renderer_beginFrame()},updateTransforms(e){if(Hi)try{Hi.renderer_updateTransforms(e._cpp)}catch(e){I(e,"Renderer.updateTransforms")}},begin(e,t){if(Hi&&$i)try{Hi.HEAPF32.set(e,$i/4),Hi.renderer_begin($i,t??0)}catch(e){I(e,"Renderer.begin")}},flush(){try{Hi?.renderer_flush()}catch(e){I(e,"Renderer.flush")}},end(){try{Hi?.renderer_end()}catch(e){I(e,"Renderer.end")}},submitAll(e,t,n,s,i,o){if(Hi)try{Hi.renderer_submitAll(e._cpp,t,n,s,i,o)}catch(e){I(e,"Renderer.submitAll")}},setStage(e){Hi?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Hi?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Hi?.renderer_releaseTarget(e)},getTargetTexture:e=>Hi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Hi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Hi?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Hi?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Hi?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Hi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Hi?Hi.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Hi?{drawCalls:Hi.renderer_getDrawCalls(),triangles:Hi.renderer_getTriangles(),sprites:Hi.renderer_getSprites(),text:Hi.renderer_getText(),spine:Hi.renderer_getSpine?.()??0,meshes:Hi.renderer_getMeshes(),culled:Hi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0},captureNextFrame(){Hi?.renderer_captureNextFrame()},getCapturedData:()=>Hi?function(e){if(!e.renderer_hasCapturedData())return null;const t=e.renderer_getCapturedFrameSize();if(0===t)return null;const n=e.renderer_getCapturedFrameData(),s=e.renderer_getCapturedEntities(),i=e.renderer_getCapturedEntityCount(),o=e.renderer_getCapturedCameraCount(),r=e.HEAPU8,a=new DataView(r.buffer,n,76*t),l=new Uint32Array(r.buffer,s,i),c=[];for(let e=0;e<t;e++){const t=76*e,n=a.getUint32(t,!0),s=a.getUint32(t+4,!0),o=a.getUint8(t+8),r=a.getUint8(t+9),d=a.getUint8(t+10),u=a.getUint32(t+12,!0),h=a.getUint32(t+16,!0),f=a.getUint32(t+20,!0),p=a.getUint32(t+24,!0),m=a.getUint32(t+28,!0),g=a.getUint32(t+32,!0),y=a.getUint32(t+36,!0),_=a.getInt32(t+40,!0),x=a.getUint8(t+44),w=a.getInt32(t+48,!0),b=a.getInt32(t+52,!0),v=a.getInt32(t+56,!0),S=a.getInt32(t+60,!0),T=0!==a.getUint8(t+64),P=0!==a.getUint8(t+65),M=0!==a.getUint8(t+66),C=a.getInt32(t+68,!0),E=a.getUint8(t+72),A=[];for(let e=0;e<g&&y+e<i;e++)A.push(l[y+e]);c.push({index:n,cameraIndex:s,stage:o,type:r,blendMode:d,textureId:u,materialId:h,shaderId:f,vertexCount:p,triangleCount:m,entityCount:g,entityOffset:y,layer:_,flushReason:x,scissorX:w,scissorY:b,scissorW:v,scissorH:S,scissorEnabled:T,stencilWrite:P,stencilTest:M,stencilRef:C,textureSlotUsage:E,entities:A})}return{drawCalls:c,cameraCount:o}}(Hi):null,hasCapturedData:()=>Hi?.renderer_hasCapturedData()??!1,replayToDrawCall(e){Hi&&function(e,t){e.renderer_replayToDrawCall(t)}(Hi,e)},getSnapshotImageData:()=>Hi?function(e){const t=e.renderer_getSnapshotSize();if(0===t)return null;const n=e.renderer_getSnapshotWidth(),s=e.renderer_getSnapshotHeight();if(0===n||0===s)return null;const i=e.renderer_getSnapshotPtr(),o=e.HEAPU8,r=new Uint8ClampedArray(o.buffer,i,t),a=new Uint8ClampedArray(t),l=4*n;for(let e=0;e<s;e++){const t=e*l,n=(s-1-e)*l;a.set(r.subarray(t,t+l),n)}return new ImageData(a,n,s)}(Hi):null};let Ni=null;function Yi(e){Ni=e}function Vi(){Ni=null}const ji={enable(){Ni?.gl_enableErrorCheck(!0)},disable(){Ni?.gl_enableErrorCheck(!1)},check:e=>Ni?.gl_checkErrors(e)??0,diagnose(){Ni?.renderer_diagnose()}};class Gi{constructor(){this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null,this.preFlushCallbacks_=[]}setActiveScenes(e){this.activeScenes_=e}addPreFlushCallback(e){this.preFlushCallbacks_.push(e)}beginFrame(){Xi.beginFrame()}beginScreenCapture(){gi.screenStack&&gi.screenStack.enabledPassCount>0&&(gi.isInitialized()||gi.init(1,1),gi._applyScreenStack(),gi._beginScreenCapture())}endScreenCapture(){gi.screenStack&&gi.screenStack.enabledPassCount>0&&(gi._endScreenCapture(),gi._executeScreenPasses())}submitScene(e,t,n,s){Xi.updateTransforms(e),Xi.submitAll(e,0,n.x,n.y,n.w,n.h);for(const t of this.preFlushCallbacks_)t(e);Xi.flush(),this.executeDrawCallbacks(t,s)}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Xi.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Xi.beginFrame(),Xi.setViewport(0,0,s,i),Xi.clearBuffers(3),Xi.begin(n),this.submitScene(t,n,{x:0,y:0,w:s,h:i},o),Xi.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==gi.getStack(r);a&&(gi._applyForCamera(r),gi.resize(s.w,s.h),gi.setOutputViewport(s.x,s.y,s.w,s.h),gi.begin()),Xi.setViewport(s.x,s.y,s.w,s.h),Xi.setScissor(s.x,s.y,s.w,s.h,!0),Xi.clearBuffers(i),Xi.setScissor(0,0,0,0,!1),Xi.begin(n),this.submitScene(t,n,s,o),Xi.end(),a&&(gi.end(),gi._resetAfterCamera())}executeDrawCallbacks(e,t){const n=Pe();if(n.size>0){Se.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Se.end();for(const e of s)Te(e)}}}const qi={None:0,SolidColor:1,Image:2,NineSlice:3},Ki=z("UIRenderer",{visualType:qi.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),Ji="__scene_transition_overlay__";class Zi{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Qi{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,B,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Me(e,t,this.instance_.config.name)}bindPostProcess(e,t){gi.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){gi.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,B)){const n=this.app_.world.get(e,B);n.persistent=t,this.app_.world.insert(e,B,n)}}}class eo{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())Te(t);for(const t of e.postProcessBindings.keys())gi.unbind(t)}this.transition_&&(Te(Ji),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise((n,s)=>{const i=t.duration??r.sceneTransitionDuration,o=t.color??{...r.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:i,color:o,targetScene:e,options:t,resolve:n,reject:s},Me(Ji,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;Se.setLayer(9999),Se.setDepth(9999),Se.rect({x:0,y:0},{x:2e4,y:2e4},{r:o.r,g:o.g,b:o.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{reject:t}=this.transition_;this.transition_=null,Te(Ji),t(e)}})().catch(()=>{})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Te(Ji),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Zi(t);this.scenes_.set(e,n);const s=new Qi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ks)?this.app_.getResource(ks):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Zi(t);this.scenes_.set(e,n);const s=new Qi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ks)?this.app_.getResource(ks):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,B)){if(this.app_.world.get(e,B).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Te(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())gi.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(ks)&&(i.assetServer=this.app_.getResource(ks));const o=await rs(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,B,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=no(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(ks)?this.app_.getResource(ks):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)ge.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,c)){const t=n.get(e,c);s.sprite=t.color.a,t.color.a=0,n.insert(e,c,t),i=!0}if(n.has(e,T)){const t=n.get(e,T);s.spine=t.color.a,t.color.a=0,n.insert(e,T,t),i=!0}if(n.has(e,H)){const t=n.get(e,H);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,H,t),i=!0}if(n.has(e,Ki)){const t=n.get(e,Ki);s.uiRenderer=t.color.a,t.color.a=0,n.insert(e,Ki,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,c)){const t=n.get(e,c);t.color.a=s.sprite,n.insert(e,c,t)}if(void 0!==s.spine&&n.has(e,T)){const t=n.get(e,T);t.color.a=s.spine,n.insert(e,T,t)}if(void 0!==s.bitmapText&&n.has(e,H)){const t=n.get(e,H);t.color.a=s.bitmapText,n.insert(e,H,t)}if(void 0!==s.uiRenderer&&n.has(e,Ki)){const t=n.get(e,Ki);t.color.a=s.uiRenderer,n.insert(e,Ki,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const to=e(null,"SceneManager");function no(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(to).getSceneStatus(t)&&n._fn(...s)}}}const so=i([W(to),f(g)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),io={name:"SceneManager",build(e){const t=new eo(e);e.insertResource(to,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(to),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(s.Startup,n),e.addSystemToSchedule(s.Last,so)}};class oo{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new D,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=async()=>{if(!this.running_)return;const e=je(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(s.Last);else{await this.runSchedule(s.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(s.FixedPreUpdate),await this.runSchedule(s.FixedUpdate),await this.runSchedule(s.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(s.PreUpdate),await this.runSchedule(s.Update),await this.runSchedule(s.PostUpdate),await this.runSchedule(s.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new N,this.resources_=new G;for(const e of Object.values(s))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new oo}getPlugin(e){return this.installed_plugins_.find(t=>t instanceof e)}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(s.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(s.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}async waitForPhysics(){this.physicsInitPromise_?await this.physicsInitPromise_:console.warn("[ESEngine] No PhysicsPlugin installed, waitForPhysics() is a no-op")}get isPhysicsReady(){return null!=this.physicsModule_}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return ne(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(to).register(e),this}setInitialScene(e){return this.getResource(to).setInitial(e),this}async tick(e){if(this.runner_||(this.runner_=new Q(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(g)||this.resources_.insert(g,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_()),await this.flushStartupSystems_(),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)await this.runSchedule(s.Last);else{await this.runSchedule(s.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,await this.runSchedule(s.FixedPreUpdate),await this.runSchedule(s.FixedUpdate),await this.runSchedule(s.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),await this.runSchedule(s.PreUpdate),await this.runSchedule(s.Update),await this.runSchedule(s.PostUpdate),await this.runSchedule(s.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}async run(){this.running_||(this.running_=!0,this.runner_=new Q(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(g,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),await this.flushStartupSystems_(),this.lastTime_=je(),this.mainLoop())}quit(){this.running_=!1,Ce();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Vi,Di,pi,ti,Ee,Ae];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){console.warn("[App] Shutdown despawn error:",e)}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}async flushStartupSystems_(){const e=this.systems_.get(s.Startup);0!==e.length&&(this.sortedSystemsCache_.delete(s.Startup),await this.runSchedule(s.Startup),e.length=0,this.sortedSystemsCache_.delete(s.Startup))}async runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const i=this.phaseTimings_?performance.now():0;for(const e of n)try{const t=this.runner_.run(e.system);t instanceof Promise&&await t}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(s[e],performance.now()-i)}updateTime(e){const t=this.resources_.get(g);t.delta=e,t.elapsed+=e,t.frameCount++}}function ro(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const lo=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function co(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case te.FixedWidth:return o;case te.FixedHeight:return r;case te.Expand:return Math.max(o,r);case te.Shrink:return Math.min(o,r);case te.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const uo=[];function ho(e){if(e<uo.length)return uo[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return uo.push(t),t}function fo(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,B);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,d=0,u=0;if(i.projectionType===ee.Orthographic){if(u=i.orthoSize,l){u=co(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}d=u*r,a=mo(-d,d,-u,u,-i.farPlane,i.farPlane)}else a=yo(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=xo(o.position.x,o.position.y,o.position.z),f=ho(c.length);f.entity=e,f.viewProjection.set(bo(a,h)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=u,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const po=new Float32Array(16);function mo(e,t,n,s,i,o){const r=po;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const go=new Float32Array(16);function yo(e,t,n,s){const i=go;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const _o=new Float32Array(16);function xo(e,t,n){const s=_o;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}const wo=new Float32Array(16);function bo(e,t){const n=wo;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const vo={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},So={Simple:0,Sliced:1,Tiled:2,Filled:3},To={Horizontal:0,Vertical:1},Po={Left:0,Right:1,Bottom:2,Top:3},Mo=a("Image",{texture:se,color:{r:1,g:1,b:1,a:1},imageType:So.Simple,fillMethod:To.Horizontal,fillOrigin:Po.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Co=z("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}}),Eo=z("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0});function Ao(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,u=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=d+s.x),e.y===t.y?(p=u+n.y-i.y*r.y,g=p+i.y):(p=u+n.y,g=h+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}let Io=null,Ro=null;function ko(e,t){switch(e){case vo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vo.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vo.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Fo(e,t){switch(e){case vo.RightToLeft:return{anchorMin:{x:1-t,y:.5},anchorMax:{x:1-t,y:.5}};case vo.BottomToTop:return{anchorMin:{x:.5,y:t},anchorMax:{x:.5,y:t}};case vo.TopToBottom:return{anchorMin:{x:.5,y:1-t},anchorMax:{x:.5,y:1-t}};default:return{anchorMin:{x:t,y:.5},anchorMax:{x:t,y:.5}}}}function Uo(e,t,n,s){switch(e){case vo.BottomToTop:case vo.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Lo(e,t,n,s){if(!e.has(t,Co))return;const i=e.get(t,Co),o=ko(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Co,i)}function zo(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}const Bo=1.15,Oo=.75;function Ho(e,t,n,s){return t?n?{r:e.r*Oo,g:e.g*Oo,b:e.b*Oo,a:e.a}:s?{r:Math.min(1,e.r*Bo),g:Math.min(1,e.g*Bo),b:Math.min(1,e.b*Bo),a:e.a}:{...e}:{r:.5*e.r,g:.5*e.g,b:.5*e.b,a:.6*e.a}}function $o(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Wo(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if($o(r.charCodeAt(0))&&s.length>0&&$o(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!$o(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Do(e){let t=1;for(;t<e;)t*=2;return t}function Xo(e,t){let n=0,s=t;for(;e.has(s,ie);){const t=e.get(s,ie).entity;if(!e.valid(t))break;n++,s=t}return n}function No(e,t){if(Io&&Ro){const e=Io.getUIRectComputedWidth(Ro,t);if(e>0)return e}return e.size.x}function Yo(e,t){if(Io&&Ro){const e=Io.getUIRectComputedHeight(Ro,t);if(e>0)return e}return e.size.y}function Vo(e,t,n){Io&&Ro&&Io.setUIRectSize(Ro,e,t,n)}function jo(e,t,n,s,i,o){if(!e.has(t,c))return;const r=e.get(t,c);let a,l;switch(n){case vo.BottomToTop:case vo.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,c,r))}function Go(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function qo(e,t){Go(e,t,Eo,{enabled:!0,blockRaycast:!0,raycastTarget:!0})}function Ko(e,t,n){0!==t&&e.valid(t)&&n(t)}function Jo(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a}function Zo(e,t,n){if(e.has(t,Mo)){const s=e.get(t,Mo);Jo(s.color,n)||(s.color=n,e.insert(t,Mo,s))}else if(e.has(t,c)){const s=e.get(t,c);Jo(s.color,n)||(s.color=n,e.insert(t,c,s))}else if(e.has(t,Ki)){const s=e.get(t,Ki);Jo(s.color,n)||(s.color=n,e.insert(t,Ki,s))}}function Qo(e,t,n){if(e.has(t,Mo)){const s=e.get(t,Mo);s.enabled!==n&&(s.enabled=n,e.insert(t,Mo,s))}else if(e.has(t,c)){const s=e.get(t,c);s.enabled!==n&&(s.enabled=n,e.insert(t,c,s))}else if(e.has(t,Ki)){const s=e.get(t,Ki);s.enabled!==n&&(s.enabled=n,e.insert(t,Ki,s))}}function er(e,t){return{r:Math.min(1,e.r*t),g:Math.min(1,e.g*t),b:Math.min(1,e.b*t),a:e.a}}function tr(e,t){return{r:e.r,g:e.g,b:e.b,a:t}}class nr{constructor(){this.map_=new Map}get(e){return this.map_.get(e)}set(e,t){this.map_.set(e,t)}delete(e){this.map_.delete(e)}has(e){return this.map_.has(e)}cleanup(e){for(const[t]of this.map_)e.valid(t)||this.map_.delete(t)}ensureInit(e,t){let n=this.map_.get(e);return n||(n=t(),this.map_.set(e,n)),n}clear(){this.map_.clear()}[Symbol.iterator](){return this.map_[Symbol.iterator]()}}function sr(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const ir=.1,or={r:.3,g:.5,b:.8,a:1},rr={r:.9,g:.9,b:.9,a:1},lr={r:.95,g:.95,b:.95,a:1},cr={Left:0,Center:1,Right:2},dr={Top:0,Middle:1,Bottom:2},ur={Visible:0,Clip:1,Ellipsis:2},hr=a("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:cr.Left,verticalAlign:dr.Top,wordWrap:!0,overflow:ur.Visible,lineHeight:1.2});class fr{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=Ve(r.textCanvasSize,r.textCanvasSize);const t=this.canvas.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("TextRenderer: failed to create 2D canvas context");this.ctx=t}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Do(this.frameMaxW_)),e.height=Math.max(e.height,Do(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Do(this.frameMaxW_),e.height=Do(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Wo(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=i?Math.ceil(o):u+2*d,p=i?Math.ceil(r):h+2*d;if(i&&e.overflow===ur.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Do(f)),s.height=Math.max(s.height,Do(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===ur.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case dr.Top:w=d;break;case dr.Middle:w=d+(p-2*d-x)/2;break;case dr.Bottom:w=p-x-d;break;default:w=d}w<0&&(w=0)}else w=d;let b=w;for(const t of l){let s;switch(e.align){case cr.Left:s=d;break;case cr.Center:s=f/2;break;case cr.Right:s=f-d;break;default:s=d}n.fillText(t,s,b),b+=c}i&&e.overflow===ur.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),T=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const M=T.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case cr.Left:return"left";case cr.Center:return"center";case cr.Right:return"right"}}}const pr=sr({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?No(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0});function mr(e,t){e.has(t,Ki)||e.insert(t,Ki,{visualType:qi.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class gr{build(e){oe("Text",hr);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new fr(t),o=e.world,r=new Map;e.addSystemToSchedule(s.PreUpdate,i([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>o.valid(e)&&o.has(e,hr));for(const e of r.keys())if(!o.valid(e)||!o.has(e,hr)){if(o.valid(e)&&o.has(e,Ki)){const t=o.get(e,Ki);t.texture=0,t.visualType=qi.None,o.insert(e,Ki,t)}r.delete(e)}const e=o.getEntitiesWithComponents([hr]);for(const t of e){const e=o.get(t,hr),s=o.has(t,Co)?o.get(t,Co):null,i={text:e,uiRect:s,entity:t},a=r.get(t);if(a&&!pr.changed(a,i)){if(o.has(t,Ki)&&0!==o.get(t,Ki).texture)continue}mr(o,t);const l=s?{size:{x:No(s,t),y:Yo(s,t)}}:null,c=n.renderForEntity(t,e,l),d=o.get(t,Ki);d.texture=c.textureHandle,d.visualType=qi.Image,d.color={r:1,g:1,b:1,a:1},d.uvOffset={x:0,y:0},d.uvScale={x:1,y:1},o.insert(t,Ki,d),s&&Vo(t,c.width,c.height),r.set(t,pr.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const yr=new gr,_r=0,xr=z("UIMask",{enabled:!0,mode:_r});class wr{build(e){oe("UIMask",xr)}}const br=new wr;function vr(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=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,i-n),h:Math.max(0,o-s)}}function Sr(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=s*l-i*a,w=s*c-o*a,b=s*d-r*a,v=i*c-o*l,S=i*d-r*l,T=o*d-r*c,P=u*g-h*m,M=u*y-f*m,C=u*_-p*m,E=h*y-f*g,A=h*_-p*g,I=f*_-p*y;let R=x*I-w*A+b*E+v*C-S*M+T*P;return 0===R||(R=1/R,n[0]=(l*I-c*A+d*E)*R,n[1]=(o*A-i*I-r*E)*R,n[2]=(g*T-y*S+_*v)*R,n[3]=(f*S-h*T-p*v)*R,n[4]=(c*C-a*I-d*M)*R,n[5]=(s*I-o*C+r*M)*R,n[6]=(y*b-m*T-_*w)*R,n[7]=(u*T-f*b+p*w)*R,n[8]=(a*A-l*C+d*P)*R,n[9]=(i*C-s*A-r*P)*R,n[10]=(m*S-g*b+_*x)*R,n[11]=(h*b-u*S-p*x)*R,n[12]=(l*M-a*E-c*P)*R,n[13]=(s*E-i*M+o*P)*R,n[14]=(g*w-m*v-y*x)*R,n[15]=(u*v-h*w+f*x)*R),n}function Tr(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],d=n[1]*a+n[5]*l+n[13],u=n[3]*a+n[7]*l+n[15];return{x:c/u,y:d/u}}function Pr(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function Mr(e,t){return 2*Math.atan2(e,t)}function Cr(e,t,n,s,i,o,r,a,l,c){if(0===l&&1===c)return Pr(e,t,n,s,i,o,r,a);const d=Mr(l,c),u=Math.sin(-d),h=Math.cos(-d),f=e-n,p=t-s,m=f*h-p*u+n,g=f*u+p*h+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}const Er=z("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Ar={Normal:0,Hovered:1,Pressed:2,Disabled:3},Ir=a("Button",{state:Ar.Normal,transition:null});class Rr{constructor(){this.events_=[],this.entityTypeHandlers_=new Map,this.globalHandlers_=new Map,this.activeDispatches_=new Set,this.entityValidator_=null}on(e,t,n){if(void 0!==n){const s=e,i=t;let o=this.entityTypeHandlers_.get(s);o||(o=new Map,this.entityTypeHandlers_.set(s,o));let r=o.get(i);r||(r=[],o.set(i,r)),r.push(n);let a=!1;return()=>{if(a)return;a=!0;const e=o.get(i);if(e){const t=e.indexOf(n);-1!==t&&e.splice(t,1)}}}{const n=e,s=t;let i=this.globalHandlers_.get(n);i||(i=[],this.globalHandlers_.set(n,i)),i.push(s);let o=!1;return()=>{if(o)return;o=!0;const e=this.globalHandlers_.get(n);if(e){const t=e.indexOf(s);-1!==t&&e.splice(t,1)}}}}removeAll(e){this.entityTypeHandlers_.delete(e)}setEntityValidator(e){this.entityValidator_=e}emit(e,t,n){const s={entity:e,type:t,target:n??e,currentTarget:e,propagationStopped:!1,stopPropagation(){this.propagationStopped=!0}};this.events_.push(s);const i=`${e}:${t}`;return this.activeDispatches_.has(i)||(this.activeDispatches_.add(i),this.dispatchToHandlers_(s),this.activeDispatches_.delete(i)),s}emitBubbled(e,t,n,s){const i={entity:e,type:t,target:n,currentTarget:e,propagationStopped:!1,stopPropagation(){s.propagationStopped=!0}};this.events_.push(i);const o=`${e}:${t}`;this.activeDispatches_.has(o)||(this.activeDispatches_.add(o),this.dispatchToHandlers_(i),this.activeDispatches_.delete(o))}drain(){if(this.entityValidator_)for(const e of this.entityTypeHandlers_.keys())this.entityValidator_(e)||this.entityTypeHandlers_.delete(e);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)}dispatchToHandlers_(e){const t=this.entityTypeHandlers_.get(e.entity);if(t){const n=t.get(e.type);n&&this.invokeHandlers_([...n],e)}const n=this.globalHandlers_.get(e.type);n&&this.invokeHandlers_([...n],e)}invokeHandlers_(e,t){for(const n of e)try{n(t)}catch(e){console.error(`UIEvent handler error [${t.type}]:`,e)}}}const kr=e(new Rr,"UIEvents"),Fr=e({generation:0},"UILayoutGeneration");class Ur{build(e){oe("UIRect",Co),oe("UIRenderer",Ki);const t=e.world,n=e.wasmModule,o=t.getCppRegistry();!function(e,t){Io=e,Ro=t}(n,o);const r={generation:0};e.insertResource(Fr,r);e.addSystemToSchedule(s.PreUpdate,i([f(lt)],e=>{e.valid&&(n.uiLayout_update(o,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.transform_update(o),r.generation++)},{name:"UILayoutSystem"})),e.addSystemToSchedule(s.PostUpdate,i([f(lt)],e=>{e.valid&&(n.uiLayout_update(o,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),r.generation++)},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(s.PostUpdate,i([],()=>{n.transform_update(o)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Lr=new Ur,zr=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(Sr(t,e),n=!1),e)}}();function Br(e,t,n,s){const i=t.emit(n,s,n);!function(e,t,n){let s=t;for(;e.has(s,ie);){const t=e.get(s,ie).entity;if(!e.valid(t))break;if(n(t))return;s=t}}(e,n,o=>{if(i.propagationStopped)return!0;if(!e.has(o,Eo))return!1;const r=e.get(o,Eo);return r.enabled&&t.emitBubbled(o,s,n,i),r.blockRaycast})}class Or{build(e){oe("Interactable",Eo),oe("Button",Ir);const t=e.world,n=e.wasmModule,o=t.getCppRegistry(),r=new Rr;r.setEntityValidator(e=>t.valid(e)),e.insertResource(kr,r);let a=null,l=null,c=NaN,d=NaN,u=-1;e.addSystemToSchedule(s.PreUpdate,i([f(it),f(lt),f(Fr)],(e,s,i)=>{if(r.drain(),be()&&!ve())return;const h=t.getEntitiesWithComponents([Er]);for(const e of h){const n=t.get(e,Er);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Er,n))}if(!s.valid)return;const f=Ge(),p=e.mouseX*f,m=s.screenH-e.mouseY*f;zr.update(s.viewProjection);const g=Tr(p,m,zr.getInverse(s.viewProjection),s.vpX,s.vpY,s.vpW,s.vpH);s.worldMouseX=g.x,s.worldMouseY=g.y;const y=e.isMouseButtonDown(0),_=e.isMouseButtonPressed(0),x=e.isMouseButtonReleased(0),w=g.x!==c||g.y!==d,b=i.generation!==u,v=w||b||(_||x);c=g.x,d=g.y,u=i.generation;let S=a;if(v){n.uiHitTest_update(o,g.x,g.y,y,_,x);const e=n.uiHitTest_getHitEntity();S=4294967295===e?null:e}if(null===a||t.valid(a)||(a=null),a!==S){if(null!==a&&t.valid(a)&&t.has(a,Er)){const e=t.get(a,Er);e.hovered=!1,t.insert(a,Er,e),r.emit(a,"hover_exit")}if(null!==S){Go(t,S,Er);const e=t.get(S,Er);e.hovered=!0,t.insert(S,Er,e),r.emit(S,"hover_enter")}a=S}if(_&&null!==S){const e=t.get(S,Er);e.pressed=!0,e.justPressed=!0,t.insert(S,Er,e),l=S,Br(t,r,S,"press")}if(x&&null!==l){if(t.valid(l)&&t.has(l,Er)){const e=t.get(l,Er);e.pressed=!1,e.justReleased=!0,t.insert(l,Er,e),Br(t,r,l,"release"),l===a&&Br(t,r,l,"click")}l=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const h=new Set;e.addSystemToSchedule(s.Update,i([],()=>{for(const e of h)t.valid(e)||h.delete(e);const e=t.getEntitiesWithComponents([Ir]);for(const n of e){if(Go(t,n,Eo,{enabled:!0}),!t.has(n,Er))continue;const e=t.get(n,Er),s=t.get(n,Ir),i=t.get(n,Eo),o=!h.has(n),r=s.state;if(i.enabled?e.pressed?s.state=Ar.Pressed:e.hovered?s.state=Ar.Hovered:s.state=Ar.Normal:s.state=Ar.Disabled,o&&h.add(n),(o||r!==s.state)&&s.transition){const o=zo(s.transition,i.enabled,e.pressed,e.hovered);Zo(t,n,o)}else if((o||r!==s.state)&&!s.transition&&t.has(n,Mo)){const s=Ho(t.get(n,Mo).color,i.enabled,e.pressed,e.hovered);Zo(t,n,s)}}},{name:"ButtonSystem"}))}}const Hr=new Or,$r=a("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Wr=a("Focusable",{tabIndex:0,isFocused:!1});class Dr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Xr=e(new Dr,"FocusManager");class Nr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(oe("TextInput",$r),be()&&!ve())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=t,o=e.world,a=new Map,l=Ve(r.textCanvasSize,64),c=l.getContext("2d",{willReadFrequently:!0});if(!c)return void console.warn("TextInputPlugin: failed to create 2D canvas context");const d=c;let u=0,h=0,p=!1,m=!0,g=0,y=0;const _=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!_)return;const x=_;function w(){const t=e.getResource(Xr);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return o.valid(n)&&o.has(n,$r)?n:null}const b=()=>{p||null===w()||M()},v=()=>{p=!0},S=()=>{p=!1,M()},T=t=>{const n=w();if(null===n)return;if("Escape"===t.key)return void C();const s=o.get(n,$r);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(kr).emit(n,"submit"),void C()}let i=s.cursorPos;"ArrowLeft"===t.key?i=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?i=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?i=0:"End"===t.key&&(i=s.value.length),i!==s.cursorPos&&(s.cursorPos=i,x.selectionStart=i,x.selectionEnd=i,s.dirty=!0,E())},P=()=>{const t=w();if(null!==t){const n=o.get(t,$r);n.focused=!1,n.dirty=!0;e.getResource(Xr).blur()}};function M(){const t=w();if(null===t)return;const n=o.get(t,$r);if(n.readOnly)return;let s=x.value;if(n.maxLength>0&&s.length>n.maxLength&&(s=s.substring(0,n.maxLength),x.value=s),s!==n.value){n.value=s;e.getResource(kr).emit(t,"change")}n.cursorPos=x.selectionStart??s.length,n.dirty=!0,E()}function C(){const t=w();if(null!==t){const e=o.get(t,$r);e.focused=!1,e.dirty=!0}e.getResource(Xr).blur(),x.blur()}function E(){m=!0,g=0}x.addEventListener("input",b),x.addEventListener("compositionstart",v),x.addEventListener("compositionend",S),x.addEventListener("keydown",T),x.addEventListener("blur",P),this.cleanupListeners_=()=>{x.removeEventListener("input",b),x.removeEventListener("compositionstart",v),x.removeEventListener("compositionend",S),x.removeEventListener("keydown",T),x.removeEventListener("blur",P),x.remove();const e=n.getResourceManager();for(const t of a.values())e.releaseTexture(t);a.clear(),0!==u&&(n._free(u),u=0,h=0)};let A=null;function I(e,t,s,i){(l.width<s||l.height<i)&&(l.width=Do(Math.max(l.width,s)),l.height=Do(Math.max(l.height,i))),d.clearRect(0,0,l.width,l.height);const r=t.backgroundColor;d.fillStyle=`rgba(${Math.round(255*r.r)}, ${Math.round(255*r.g)}, ${Math.round(255*r.b)}, ${r.a})`,d.fillRect(0,0,s,i),d.save(),d.beginPath(),d.rect(t.padding,0,s-2*t.padding,i),d.clip(),d.font=`${t.fontSize}px ${t.fontFamily}`,d.textBaseline="top",d.textAlign="left";const c=0===t.value.length,f=c?t.placeholder:t.password?"●".repeat(t.value.length):t.value,p=c?t.placeholderColor:t.color;d.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const g=Math.ceil(1.2*t.fontSize),y=t.padding;if(t.multiline){const e=Wo(d,f,s-2*y);let t=y;for(const n of e)d.fillText(n,y,t),t+=g}else{const e=(i-t.fontSize)/2;d.fillText(f,y,e)}if(t.focused&&m){const e=t.password?"●".repeat(t.cursorPos):t.value.substring(0,t.cursorPos);let n,o,r;if(t.multiline){const e=Wo(d,t.value,s-2*y);let i=0,a=0,l=0;for(let n=0;n<e.length;n++){const s=e[n].length;if(i+s>=t.cursorPos){a=n,l=t.cursorPos-i;break}i+=s,n<e.length-1&&i<t.value.length&&"\n"===t.value[i]&&i++,a=n+1,l=0}const c=a<e.length?e[a].substring(0,l):"";n=y+d.measureText(c).width,o=y+a*g,r=g}else n=y+d.measureText(e).width,o=(i-t.fontSize)/2,r=t.fontSize;d.fillStyle=`rgba(${Math.round(255*t.color.r)}, ${Math.round(255*t.color.g)}, ${Math.round(255*t.color.b)}, ${t.color.a})`,d.fillRect(n,o,2,r)}d.restore();const _=d.getImageData(0,0,s,i),x=new Uint8Array(_.data.buffer),w=n.getResourceManager();x.length>h&&(0!==u&&n._free(u),u=n._malloc(x.length),h=x.length),n.HEAPU8.set(x,u);const b=a.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(s,i,u,x.length,1,!0);a.set(e,v);const S=o.get(e,Ki);S.texture=v,S.visualType=qi.Image,S.uvOffset={x:0,y:0},S.uvScale={x:1,y:1},S.color={r:1,g:1,b:1,a:1},S.enabled=!0,o.insert(e,Ki,S)}e.addSystemToSchedule(s.Update,i([f(Xr)],e=>{const t=o.getEntitiesWithComponents([$r]);for(const e of t)Go(o,e,Wr,{tabIndex:0,isFocused:!1}),Go(o,e,Eo,{enabled:!0,blockRaycast:!0});const n=w();if(n!==A){if(null!==A&&o.valid(A)&&o.has(A,$r)){const e=o.get(A,$r);e.focused=!1,e.dirty=!0,x.blur()}null!==n&&function(e){const t=o.get(e,$r);t.readOnly||(t.focused=!0,t.dirty=!0,x.value=t.value,x.selectionStart=t.cursorPos,x.selectionEnd=t.cursorPos,x.focus(),E())}(n),A=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(s.PreUpdate,i([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let t=0===y?0:(e-y)/1e3;y=e,t=Math.min(t,.1);const s=w();if(null!==s&&(g+=t,g>=.5)){g-=.5,m=!m;o.get(s,$r).dirty=!0}const i=n.getResourceManager();for(const[e,t]of a)o.valid(e)&&o.has(e,$r)||(i.releaseTexture(t),a.delete(e));const r=o.getEntitiesWithComponents([$r,Co]);for(const e of r){const t=o.get(e,$r);if(!t.dirty)continue;const n=o.get(e,Co),s=Math.ceil(n.size.x),i=Math.ceil(n.size.y);s<=0||i<=0||(o.has(e,Ki)||o.insert(e,Ki,{visualType:qi.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),I(e,t,s,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Yr=new Nr,Vr=sr({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?No(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});function jr(e,t){e.has(t,Ki)||e.insert(t,Ki,{visualType:qi.None,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0})}class Gr{build(e){oe("Image",Mo);const t=e.world,n=new Map;e.addSystemToSchedule(s.PreUpdate,i([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Mo)||n.delete(e);const e=t.getEntitiesWithComponents([Mo]);for(const s of e){const e=t.get(s,Mo),i=t.has(s,Co)?t.get(s,Co):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&t.has(s,Ki)&&!Vr.changed(r,o))continue;jr(t,s);const a=t.get(s,Ki);if(!e.enabled){a.enabled=!1,t.insert(s,Ki,a),n.set(s,Vr.take(o));continue}a.enabled=!0,a.texture=e.texture,a.color={r:e.color.r,g:e.color.g,b:e.color.b,a:e.color.a},a.material=e.material,a.uvOffset={x:0,y:0},a.uvScale={x:1,y:1};if(e.texture!==se&&0!==e.texture?e.imageType===So.Sliced?a.visualType=qi.NineSlice:a.visualType=qi.Image:a.visualType=qi.SolidColor,e.imageType===So.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));i&&No(i,s),i&&Yo(i,s),e.fillMethod===To.Horizontal?(e.fillOrigin===Po.Left||(a.uvOffset={x:1-t,y:0}),a.uvScale={x:t,y:1}):(e.fillOrigin===Po.Bottom||(a.uvOffset={x:0,y:1-t}),a.uvScale={x:1,y:t})}else if(e.imageType===So.Tiled){const t=i?No(i,s):0,n=i?Yo(i,s):0;e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale={x:t/e.tileSize.x,y:n/e.tileSize.y})}t.insert(s,Ki,a),n.set(s,Vr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const qr=new Gr,Kr=a("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null,onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1}},{entityFields:["graphicEntity","group"]}),Jr=a("ToggleGroup",{allowSwitchOff:!1});function Zr(e,t,n){if(!e.has(t,Ki))return;const s=e.get(t,Ki);s.color.r===n.r&&s.color.g===n.g&&s.color.b===n.b&&s.color.a===n.a||(s.color=n,e.insert(t,Ki,s))}function Qr(e,t,n){if(!e.has(t,Ki))return;const s=e.get(t,Ki);s.enabled!==n&&(s.enabled=n,e.insert(t,Ki,s))}class ea{build(e){oe("Toggle",Kr),oe("ToggleGroup",Jr);const t=e.world,n=new Set;e.addSystemToSchedule(s.Update,i([f(kr)],e=>{const s=t.getEntitiesWithComponents([Kr]);if(!be()||ve()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Kr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Kr,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Kr);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Go(t,n,Eo,{enabled:!0}),!t.has(n,Er))continue;const s=t.get(n,Er),i=t.get(n,Kr),r=t.get(n,Eo);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,Jr);if(i.isOn&&r){if(!t.get(s,Jr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Kr,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Kr);i.isOn&&(i.isOn=!1,t.insert(s,Kr,i),e.emit(s,"change"))}}e.emit(n,"change")}let a;if(i.transition)a=zo(i.transition,r.enabled,s.pressed,s.hovered);else{a=Ho(i.isOn?i.onColor:i.offColor,r.enabled,s.pressed,s.hovered)}Zr(t,n,a)}}for(const e of s){const n=t.get(e,Kr);Ko(t,n.graphicEntity,e=>{Qr(t,e,n.isOn)})}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const ta=new ea,na=vo,sa=a("ProgressBar",{value:0,fillEntity:0,direction:vo.LeftToRight},{entityFields:["fillEntity"]});class ia{build(e){oe("ProgressBar",sa);const t=e.world;e.addSystemToSchedule(s.PreUpdate,i([],()=>{const e=t.getEntitiesWithComponents([sa,Co]);for(const n of e){const e=t.get(n,sa),s=Math.max(0,Math.min(1,e.value));Ko(t,e.fillEntity,n=>{Lo(t,n,e.direction,s)})}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const oa=new ia,ra=a("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),la=a("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});function ca(e,t,n,s){if(!e.has(t,ie))return{x:n,y:s};const i=e.get(t,ie).entity;if(!e.valid(i)||!e.has(i,d))return{x:n,y:s};const o=e.get(i,d),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=Mr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}class da{build(e){oe("Draggable",ra),oe("DragState",la);const t=e.world,n=e.getResource(kr);let o=null,r={x:0,y:0},a=null;e.addSystemToSchedule(s.PreUpdate,i([f(it),f(lt)],(e,s)=>{if(be()&&!ve())return;if(!s.valid)return;const i={x:s.worldMouseX,y:s.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ra,Er]);let n=null,s=-1/0,a=-1;for(const i of e){if(!t.get(i,ra).enabled)continue;if(t.get(i,Er).hovered){let e=0;t.has(i,c)&&(e=t.get(i,c).layer);const o=Xo(t,i);(e>s||e===s&&o>=a)&&(s=e,a=o,n=i)}}if(null!==n){o=n,r={x:i.x,y:i.y},t.has(n,la)||t.insert(n,la);const e=t.get(n,la),s=t.get(n,d);e.startWorldPos={x:s.worldPosition.x,y:s.worldPosition.y},e.currentWorldPos={x:s.worldPosition.x,y:s.worldPosition.y},e.pointerStartWorld={x:i.x,y:i.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==o&&!e.isMouseButtonDown(0)){if(t.valid(o)&&t.has(o,la)){t.get(o,la).isDragging=!1}o=null}if(null!==o&&null===a){if(!t.valid(o))return void(o=null);const e=i.x-r.x,l=i.y-r.y,c=Math.sqrt(e*e+l*l),d=t.get(o,ra);if(c*(s.vpW/(s.worldRight-s.worldLeft))>=d.dragThreshold){a=o,o=null;t.get(a,la).isDragging=!0,n.emit(a,"drag_start")}}if(null!==a){if(!t.valid(a)||!t.has(a,la))return void(a=null);const s=t.get(a,la),o=t.get(a,ra),r=i.x-s.pointerStartWorld.x,l=i.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(o,s,c,u);c=h.x,u=h.y;const f=s.currentWorldPos.x,p=s.currentWorldPos.y;if(s.deltaWorld={x:c-f,y:u-p},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(a,Co)){const e=t.get(a,Co),n=ca(t,a,s.deltaWorld.x,s.deltaWorld.y);e.offsetMin.x+=n.x,e.offsetMin.y+=n.y,t.insert(a,Co,e)}else if(t.has(a,d)){const e=ca(t,a,s.deltaWorld.x,s.deltaWorld.y),n=t.get(a,d);n.position.x+=e.x,n.position.y+=e.y,t.insert(a,d,n)}n.emit(a,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(a,"drag_end"),a=null)}},{name:"DragSystem"}))}}const ua=new da,ha=a("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1},{entityFields:["contentEntity"]});function fa(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function pa(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-o*c)*a}}class ma{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){oe("ScrollView",ha);const t=e.world,n=new nr,o={x:0,y:0};e.addSystemToSchedule(s.PostUpdate,i([f(it),f(lt),f(g)],(e,s,i)=>{const r=be()&&!ve(),a=Math.min(i.delta,.05);n.cleanup(t),s.valid&&(o.x=s.worldMouseX,o.y=s.worldMouseY);const l=t.getEntitiesWithComponents([ha,Co]);for(const i of l){Go(t,i,xr,{enabled:!0,mode:_r});const l=t.get(i,ha),u=t.get(i,Co),h=n.ensureInit(i,()=>({isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN})),f=No(u,i),p=Yo(u,i);let m=l.contentWidth,g=l.contentHeight;if((0===m||0===g)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,re)){const e=t.get(l.contentEntity,re).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,d))continue;const e=t.get(r,d);let a=0,l=0,u=.5,h=.5;if(t.has(r,Co)){const e=t.get(r,Co);a=No(e,r)||e.size.x,l=Yo(e,r)||e.size.y,u=e.pivot.x,h=e.pivot.y}else if(t.has(r,c)){const e=t.get(r,c);a=e.size.x,l=e.size.y}const f=e.position.x-a*u,p=e.position.x+a*(1-u),m=e.position.y-l*h,g=e.position.y+l*(1-h);f<n&&(n=f),p>s&&(s=p),m<i&&(i=m),g>o&&(o=g)}0===m&&(m=s-n),0===g&&(g=o-i)}const y=Math.max(0,m-f),_=Math.max(0,g-p);if(!r&&s.valid){Go(t,i,Eo,{enabled:!0,blockRaycast:!0});const n=t.has(i,Er)?t.get(i,Er):null;if(n?.justPressed&&(h.isDragging=!0,h.lastWorldX=o.x,h.lastWorldY=o.y,h.velocityX=0,h.velocityY=0),h.isDragging&&e.isMouseButtonDown(0)){const e=o.x-h.lastWorldX,t=o.y-h.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=fa(l.scrollX,0,y,f);if(l.scrollX-=e*t,0===e)h.velocityX=0;else{const s=a>0?-e*t/a:0;h.velocityX+=(s-h.velocityX)*n}}if(l.verticalEnabled){const e=fa(l.scrollY,0,_,p);if(l.scrollY+=t*e,0===t)h.velocityY=0;else{const s=a>0?t*e/a:0;h.velocityY+=(s-h.velocityY)*n}}h.lastWorldX=o.x,h.lastWorldY=o.y}if(h.isDragging&&e.isMouseButtonReleased(0)){h.isDragging=!1;const e=5*f,t=5*p;h.velocityX=Math.max(-e,Math.min(h.velocityX,e)),h.velocityY=Math.max(-t,Math.min(h.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=fa(l.scrollY,0,_,p);l.scrollY+=t.y*l.wheelSensitivity*e,h.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=fa(l.scrollX,0,y,f);l.scrollX+=t.x*l.wheelSensitivity*e,h.velocityX=0}}}if(!h.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>y,t=l.scrollY<0||l.scrollY>_;if(l.elastic&&e){const e=l.scrollX<0?0:y,t=pa(l.scrollX,e,h.velocityX,.1,a);l.scrollX=t.value,h.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(h.velocityX)<ir&&(l.scrollX=e,h.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(h.velocityX)>ir?(h.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=h.velocityX*a):h.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:_,t=pa(l.scrollY,e,h.velocityY,.1,a);l.scrollY=t.value,h.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(h.velocityY)<ir&&(l.scrollY=e,h.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(h.velocityY)>ir?(h.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=h.velocityY*a):h.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,y)),l.scrollY=Math.max(0,Math.min(l.scrollY,_)),l.scrollX!==e&&(h.velocityX=0),l.scrollY!==t&&(h.velocityY=0)}}if(l.elastic){const e=.5*f,t=.5*p;l.scrollX=Math.max(-e,Math.min(l.scrollX,y+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,_+t))}Ko(t,l.contentEntity,e=>{if(!t.has(e,d))return;const n=t.get(e,d),s=n.position.x,i=n.position.y;(isNaN(h.lastAppliedX)||Math.abs(s-h.lastAppliedX)>.01)&&(h.contentBaseX=s),(isNaN(h.lastAppliedY)||Math.abs(i-h.lastAppliedY)>.01)&&(h.contentBaseY=i),n.position.x=h.contentBaseX-l.scrollX,n.position.y=h.contentBaseY+l.scrollY,h.lastAppliedX=n.position.x,h.lastAppliedY=n.position.y,t.insert(e,d,n)})}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{n.clear()}}}const ga=new ma,ya=vo,_a=a("Slider",{value:0,minValue:0,maxValue:1,direction:vo.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1},{entityFields:["fillEntity","handleEntity"]});function xa(e,t,n,s,i,o){const r=No(s,i)*n.worldScale.x,a=Yo(s,i)*n.worldScale.y,l=Mr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),u=e-n.worldPosition.x,h=t-n.worldPosition.y,f=u*d-h*c,p=u*c+h*d,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case vo.LeftToRight:return r>0?(f-m)/r:0;case vo.RightToLeft:return r>0?1-(f-m)/r:0;case vo.BottomToTop:return a>0?(p-g)/a:0;case vo.TopToBottom:return a>0?1-(p-g)/a:0}}function wa(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case vo.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=.5,e.anchorMax.x=n,e.anchorMax.y=.5;break;case vo.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=.5,e.anchorMax.x=1-n,e.anchorMax.y=.5;break;case vo.BottomToTop:e.anchorMin.x=.5,e.anchorMin.y=n,e.anchorMax.x=.5,e.anchorMax.y=n;break;case vo.TopToBottom:e.anchorMin.x=.5,e.anchorMin.y=1-n,e.anchorMax.x=.5,e.anchorMax.y=1-n}}class ba{build(e){oe("Slider",_a);const t=e.world;e.addSystemToSchedule(s.PreUpdate,i([f(it),f(lt),f(kr)],(e,n,s)=>{if(!n.valid)return;const i=t.getEntitiesWithComponents([_a,Co]);for(const o of i){const i=t.get(o,_a),r=t.get(o,Co);if(!be()||ve()){if(t.has(o,d)){Go(t,o,Eo,{enabled:!0,blockRaycast:!0}),Ko(t,i.handleEntity,e=>{Go(t,e,Eo,{enabled:!0,blockRaycast:!1})});const a=t.get(o,d);let l=!1;if(t.has(o,Er)&&(l=t.get(o,Er).pressed),Ko(t,i.handleEntity,e=>{!l&&t.has(e,Er)&&(l=t.get(e,Er).pressed)}),l&&e.isMouseButtonDown(0)){let e=xa(n.worldMouseX,n.worldMouseY,a,r,o,i.direction);e=Math.max(0,Math.min(1,e));let l=i.minValue+e*(i.maxValue-i.minValue);i.wholeNumbers&&(l=Math.round(l));const c=i.value;i.value=Math.max(i.minValue,Math.min(i.maxValue,l)),t.insert(o,_a,i),i.value!==c&&s.emit(o,"change")}}}const a=i.maxValue-i.minValue,l=a>0?(i.value-i.minValue)/a:0;Ko(t,i.fillEntity,e=>{Lo(t,e,i.direction,l)}),Ko(t,i.handleEntity,e=>{if(!t.has(e,Co))return;const n=t.get(e,Co);wa(n,i.direction,l),t.insert(e,Co,n)})}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const va=new ba;class Sa{build(e){oe("Focusable",Wr);const t=e.world,n=new Dr;e.insertResource(Xr,n),e.addSystemToSchedule(s.Update,i([f(it),f(kr)],(e,s)=>{if(be()&&!ve())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Wr]);for(const e of i){if(!t.has(e,Er))continue;t.get(e,Er).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,Eo)){if(!t.get(n,Eo).enabled)continue}const s=t.get(n,Wr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Wr)){t.get(i,Wr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Wr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Ta=new Sa,Pa=a("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Ma(){return He()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class Ca{build(e){oe("SafeArea",Pa);const t=e.world;let n=Ma(),o=!0,r=0,a=0;if(He()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Ma(),o=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Ma(),o=!0});e.addSystemToSchedule(s.PreUpdate,i([f(lt)],e=>{if(!e.valid||0===e.screenH)return;const s=e.worldTop-e.worldBottom;if(e.screenH===r&&s===a||(r=e.screenH,a=s,o=!0),!o)return;o=!1;const i=Ge(),l=He()?s/e.screenH:i*s/e.screenH,c=t.getEntitiesWithComponents([Pa,Co]);for(const e of c){const s=t.get(e,Pa),i=t.get(e,Co),o=s.applyTop?n.top*l:0,r=s.applyBottom?n.bottom*l:0,a=s.applyLeft?n.left*l:0,c=s.applyRight?n.right*l:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},d=!0),i.offsetMax.x===-c&&i.offsetMax.y===-o||(i.offsetMax={x:-c,y:-o},d=!0),d&&t.insert(e,Co,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Ea=new Ca,Aa=a("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Ia=null;function Ra(e,t){if(!Ia)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Ia.get(e);n?n.renderer=t:Ia.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class ka{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null),Ia=null}build(e){oe("ListView",Aa);const t=e.world,n=new Map;Ia=n,e.addSystemToSchedule(s.PostUpdate,i([f(it)],e=>{const s=be()&&!ve();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([Aa,Co]);for(const o of i){Go(t,o,Eo,{enabled:!0,blockRaycast:!0}),Go(t,o,xr,{enabled:!0,mode:_r});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,Aa),a=t.get(o,Co),l=Yo(a,o),c=No(a,o);if(!s){const n=t.has(o,Er)?t.get(o,Er):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),f=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=f)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<f;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,P,{value:`ListItem_${e}`}),t.insert(n,Co,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,d)){const s=t.get(n,d);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,d,s)}}i.visibleStart=h,i.visibleEnd=f}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]}),this.cleanup_=()=>{for(const[,e]of n)for(const n of e.itemEntities.values())t.valid(n)&&t.despawn(n);n.clear()}}}const Fa=new ka,Ua=a("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0},{entityFields:["listEntity","labelEntity"]});class La{constructor(){this.cleanup_=null}cleanup(){this.cleanup_&&(this.cleanup_(),this.cleanup_=null)}build(e){oe("Dropdown",Ua);const t=e.world,n=new Map,o=new Set;function r(e){Ko(t,e,e=>{if(!t.has(e,d))return;const n=t.get(e,d);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,d,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})})}function a(e){if(t.has(e,Ki)){const n=t.get(e,Ki);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Zo(t,e,{...rr})}else if(t.has(e,c)){const n=t.get(e,c);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&Zo(t,e,{...rr})}}function l(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;g(i,!0),m(s);let o=0;if(t.has(e,Co)){const n=t.get(e,Co);o=No(n,e)||n.size.x}else if(t.has(e,c)){o=t.get(e,c).size.x}s.ddWidth=o;const r=30*n.options.length;t.insert(i,Co,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:r},pivot:{x:.5,y:1}}),t.insert(i,Ki,{visualType:qi.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn();t.insert(r,P,{value:`Option_${e}`}),t.insert(r,Co,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:30*-e},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:1}}),t.insert(r,d,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,Ki,{visualType:qi.SolidColor,texture:0,color:{...lr},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0}),t.insert(r,Eo,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const a=t.spawn();t.insert(a,d,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(a,hr,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:cr.Left,verticalAlign:dr.Middle,wordWrap:!1,overflow:ur.Clip,lineHeight:1.2}),t.insert(a,Co,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:30},pivot:{x:.5,y:.5}}),t.setParent(a,r),s.textEntities.push(a)}y(s)}function u(e,t,n){t.isOpen=!1,m(n),g(t.listEntity,!1)}function h(e,t,n,s,i){t.selectedIndex=s,u(0,t,n),i.emit(e,"change")}function p(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,hr))return;const s=t.get(n,hr);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,hr,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function m(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function g(e,n){Ko(t,e,e=>{t.has(e,Eo)&&t.insert(e,Eo,{enabled:n,blockRaycast:!0,raycastTarget:!0}),Qo(t,e,n)})}function y(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s))continue;const i=n===e.highlightIndex?{...or}:{...lr};Zo(t,s,i)}}function _(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Er))continue;if(t.get(n,Er).hovered)return!0}return!1}e.addSystemToSchedule(s.Update,i([f(it),f(kr)],(e,s)=>{for(const[e,s]of n)t.valid(e)||(m(s),n.delete(e),o.delete(e));const i=be()&&!ve(),c=t.getEntitiesWithComponents([Ua]);for(const d of c){const c=t.get(d,Ua);let f=n.get(d);if(f||(f={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(d,f)),r(c.listEntity),o.has(d)||(a(d),o.add(d)),c.isOpen||g(c.listEntity,!1),p(c),i)continue;Go(t,d,Eo,{enabled:!0,blockRaycast:!0});const m=t.has(d,Er)?t.get(d,Er):null;if(m?.justPressed&&(c.isOpen?u(d,c,f):l(d,c,f)),c.isOpen){for(let e=0;e<f.optionEntities.length;e++){const n=f.optionEntities[e];if(!t.valid(n)||!t.has(n,Er))continue;if(t.get(n,Er).justPressed){h(d,c,f,e,s);break}}let n=-1;for(let e=0;e<f.optionEntities.length;e++){const s=f.optionEntities[e];if(!t.valid(s)||!t.has(s,Er))continue;if(t.get(s,Er).hovered){n=e;break}}n>=0&&n!==f.highlightIndex&&(f.highlightIndex=n,y(f)),e.isKeyPressed("ArrowDown")?(f.highlightIndex>=c.options.length-1?f.highlightIndex=0:f.highlightIndex++,y(f)):e.isKeyPressed("ArrowUp")?(f.highlightIndex<=0?f.highlightIndex=c.options.length-1:f.highlightIndex--,y(f)):e.isKeyPressed("Enter")&&f.highlightIndex>=0?h(d,c,f,f.highlightIndex,s):e.isKeyPressed("Escape")&&u(d,c,f),e.isMouseButtonPressed(0)&&(m?.hovered||_(f)||u(d,c,f))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]}),this.cleanup_=()=>{for(const[,e]of n)m(e);n.clear(),o.clear()}}}const za=new La,Ba=z("LayoutGroup",{direction:0,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:0,reverseOrder:!1});class Oa{build(e){oe("LayoutGroup",Ba)}}const Ha=new Oa,$a=0,Wa=1,Da=0,Xa=1,Na=0,Ya=0,Va=3,ja=z("FlexContainer",{direction:$a,wrap:Da,justifyContent:Na,alignItems:Va,alignContent:0,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0}}),Ga=z("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,alignSelf:0,margin:{left:0,top:0,right:0,bottom:0},minWidth:-1,minHeight:-1,maxWidth:-1,maxHeight:-1,widthPercent:-1,heightPercent:-1});class qa{build(e){const t=e.world,n=e.wasmModule,o=t.getCppRegistry();e.addSystemToSchedule(s.PostUpdate,i([],()=>{n.uiRenderOrder_update(o)},{name:"UIRenderOrderSystem"}))}}const Ka=new qa,Ja={primary:{r:.25,g:.56,b:.96,a:1},secondary:{r:.4,g:.4,b:.4,a:1},background:{r:.08,g:.08,b:.08,a:1},surface:{r:.14,g:.14,b:.14,a:1},error:{r:.9,g:.2,b:.2,a:1},text:{r:.93,g:.93,b:.93,a:1},textSecondary:{r:.6,g:.6,b:.6,a:1},border:{r:.3,g:.3,b:.3,a:1},fontFamily:"Arial",fontSize:{xs:10,sm:12,md:14,lg:18,xl:24},spacing:{xs:4,sm:8,md:12,lg:16,xl:24},button:{height:36,color:{r:.25,g:.25,b:.25,a:1},textColor:{r:.93,g:.93,b:.93,a:1},transition:{normalColor:{r:.25,g:.25,b:.25,a:1},hoveredColor:{r:.3,g:.3,b:.3,a:1},pressedColor:{r:.18,g:.18,b:.18,a:1},disabledColor:{r:.15,g:.15,b:.15,a:.6}}},slider:{trackHeight:16,trackColor:{r:.15,g:.15,b:.15,a:1},fillColor:{r:.25,g:.56,b:.96,a:1},handleSize:24,handleColor:{r:1,g:1,b:1,a:1}},toggle:{size:{x:24,y:24},onColor:{r:.2,g:.6,b:1,a:1},offColor:{r:.4,g:.4,b:.4,a:1},checkColor:{r:1,g:1,b:1,a:1}},input:{height:36,backgroundColor:{r:.15,g:.15,b:.15,a:1},textColor:{r:1,g:1,b:1,a:1},placeholderColor:{r:.6,g:.6,b:.6,a:1},fontSize:16,padding:6},dropdown:{height:32,backgroundColor:{r:.2,g:.2,b:.2,a:1},itemHeight:28},panel:{backgroundColor:{r:.14,g:.14,b:.14,a:1},padding:12},scrollView:{backgroundColor:{r:.1,g:.1,b:.1,a:1}}},Za=e(null,"UITheme");let Qa=null;function el(e){e.hasResource(Za)&&(Qa=e.getResource(Za))}function tl(){return Qa??Ja}function nl(e,t){const n=e.spawn();if(t.name&&e.insert(n,P,{value:t.name}),e.insert(n,d,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},...t.transform}),t.rect&&e.insert(n,Co,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:0,y:0},pivot:{x:.5,y:.5},...t.rect}),t.renderer&&e.insert(n,Ki,{visualType:qi.SolidColor,texture:0,color:{r:1,g:1,b:1,a:1},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},sliceBorder:{x:0,y:0,z:0,w:0},material:0,enabled:!0,...t.renderer}),t.interactable&&e.insert(n,Eo,{enabled:!0,blockRaycast:!0,raycastTarget:!0,...t.interactable}),t.text){const s=tl();e.insert(n,hr,{content:"",fontFamily:s.fontFamily,fontSize:s.fontSize.md,color:{r:1,g:1,b:1,a:1},align:cr.Left,verticalAlign:dr.Top,wordWrap:!1,overflow:0,lineHeight:1.2,...t.text})}if(t.image&&e.insert(n,Mo,{...Mo._default,...t.image}),t.flex&&e.insert(n,ja,{direction:$a,wrap:Da,justifyContent:Na,alignItems:Va,gap:{x:0,y:0},padding:{left:0,top:0,right:0,bottom:0},...t.flex}),t.flexItem&&e.insert(n,Ga,{flexGrow:0,flexShrink:1,flexBasis:-1,order:0,...t.flexItem}),t.mask&&e.insert(n,xr,{enabled:!0,mode:_r,...t.mask}),t.components)for(const[s,i]of t.components)e.insert(n,s,i);return t.parent&&e.setParent(n,t.parent),n}function sl(e,t={}){const n=tl(),{text:s="Button",fontSize:i=n.fontSize.md,size:o={x:120,y:n.button.height},color:r=n.button.color,textColor:a=n.button.textColor,transition:l=null,parent:c}=t,d=nl(e,{name:"ButtonLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:s,fontSize:i,color:a,align:cr.Center,verticalAlign:dr.Middle}}),u=nl(e,{name:"Button",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:qi.SolidColor,color:r},interactable:{enabled:!0},components:[[Ir,{state:0,transition:l}]]});if(e.setParent(d,u),t.events){if(t.onClick){const e=t.onClick;t.events.on(u,"click",()=>e(u))}if(t.onHover){const e=t.onHover;t.events.on(u,"hover_enter",()=>e(u))}}return u}function il(e,t={}){const n=tl(),{value:s=0,minValue:i=0,maxValue:o=1,direction:r=vo.LeftToRight,size:a={x:200,y:n.slider.trackHeight},trackColor:l=n.slider.trackColor,fillColor:c=n.slider.fillColor,handleSize:d={x:n.slider.handleSize,y:n.slider.handleSize},handleColor:u=n.slider.handleColor,wholeNumbers:h=!1,parent:f}=t,p=nl(e,{name:"SliderFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:qi.SolidColor,color:c}}),m=nl(e,{name:"SliderHandle",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:d},renderer:{visualType:qi.SolidColor,color:u},interactable:{enabled:!0,blockRaycast:!0},components:[[ra,{enabled:!0,dragThreshold:5,lockX:!1,lockY:!0}]]}),g=nl(e,{name:"Slider",parent:f,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:qi.SolidColor,color:l},interactable:{enabled:!0,blockRaycast:!0},components:[[_a,{value:s,minValue:i,maxValue:o,direction:r,wholeNumbers:h,fillEntity:p,handleEntity:m}]]});if(e.setParent(p,g),e.setParent(m,g),t.onChange&&t.events){const n=t.onChange;t.events.on(g,"change",()=>{const t=e.get(g,_a);n(t.value,g)})}return g}function ol(e,t={}){const n=tl(),{isOn:s=!0,size:i=n.toggle.size,onColor:o=n.toggle.onColor,offColor:r=n.toggle.offColor,checkSize:a={x:.58*n.toggle.size.x,y:.58*n.toggle.size.y},checkColor:l=n.toggle.checkColor,group:c=0,transition:d=null,label:u,parent:h}=t,f=nl(e,{name:"ToggleCheck",rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:a},renderer:{visualType:qi.SolidColor,color:l}}),p=nl(e,{name:"Toggle",parent:h,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:qi.SolidColor,color:s?o:r},interactable:{enabled:!0},components:[[Kr,{isOn:s,graphicEntity:f,group:c,transition:d,onColor:o,offColor:r}]]});if(e.setParent(f,p),u&&nl(e,{name:"ToggleLabel",parent:p,rect:{anchorMin:{x:1,y:0},anchorMax:{x:1,y:1},offsetMin:{x:8,y:0},size:{x:100,y:0}},text:{content:u,fontSize:n.fontSize.md,align:cr.Left,verticalAlign:dr.Middle}}),t.onChange&&t.events){const n=t.onChange;t.events.on(p,"change",()=>{const t=e.get(p,Kr);n(t.isOn,p)})}return p}function rl(e,t={}){const n=tl(),{value:s=0,size:i={x:200,y:n.slider.trackHeight},direction:o=vo.LeftToRight,trackColor:r=n.slider.trackColor,fillColor:a=n.primary,parent:l}=t,c=nl(e,{name:"ProgressFill",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},renderer:{visualType:qi.SolidColor,color:a}}),d=nl(e,{name:"ProgressBar",parent:l,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:i},renderer:{visualType:qi.SolidColor,color:r},components:[[sa,{value:s,fillEntity:c,direction:o}]]});return e.setParent(c,d),d}function ll(e,t={}){const n=tl(),{size:s={x:300,y:400},contentSize:i={x:300,y:800},horizontal:o=!1,vertical:r=!0,elastic:a=!0,mask:l=!0,parent:c}=t,d=nl(e,{name:"ScrollContent",rect:{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},size:{x:i.x,y:i.y},pivot:{x:.5,y:1}}}),u=nl(e,{name:"ScrollView",parent:c,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:s},renderer:{visualType:qi.SolidColor,color:n.scrollView.backgroundColor},mask:l?{mode:_r,enabled:!0}:void 0,components:[[ha,{contentEntity:d,horizontalEnabled:o,verticalEnabled:r,contentWidth:i.x,contentHeight:i.y,elastic:a,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,wheelSensitivity:.1}]]});return e.setParent(d,u),u}function cl(e,t={}){const n=tl(),{placeholder:s="",value:i="",size:o={x:200,y:n.input.height},fontSize:r=n.input.fontSize,backgroundColor:a=n.input.backgroundColor,textColor:l=n.input.textColor,maxLength:c=0,multiline:d=!1,password:u=!1,parent:h}=t,f=nl(e,{name:"TextInput",parent:h,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:qi.SolidColor,color:a},interactable:{enabled:!0},components:[[$r,{value:i,placeholder:s,fontSize:r,fontFamily:n.fontFamily,color:l,backgroundColor:a,placeholderColor:n.input.placeholderColor,padding:n.input.padding,maxLength:c,multiline:d,password:u,readOnly:!1,focused:!1,cursorPos:i.length,dirty:!0}],[Wr,{tabIndex:0,isFocused:!1}]]});if(t.events){if(t.onChange){const n=t.onChange;t.events.on(f,"change",()=>{const t=e.get(f,$r);n(t.value,f)})}if(t.onSubmit){const n=t.onSubmit;t.events.on(f,"submit",()=>{const t=e.get(f,$r);n(t.value,f)})}}return f}function dl(e,t){const n=tl(),{options:s,selectedIndex:i=-1,size:o={x:160,y:n.dropdown.height},fontSize:r=n.fontSize.md,parent:a}=t,l=nl(e,{name:"DropdownLabel",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:(i>=0?s[i]:s[0])??"",fontSize:r,align:cr.Left,verticalAlign:dr.Middle}}),c=nl(e,{name:"DropdownList",rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},size:{x:o.x,y:Math.min(s.length*n.dropdown.itemHeight,200)},pivot:{x:.5,y:1}},renderer:{visualType:qi.SolidColor,color:n.surface},mask:{mode:_r,enabled:!0}}),d=nl(e,{name:"Dropdown",parent:a,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:o},renderer:{visualType:qi.SolidColor,color:n.dropdown.backgroundColor},interactable:{enabled:!0},components:[[Ua,{options:s,selectedIndex:i,isOpen:!1,listEntity:c,labelEntity:l}]]});if(e.setParent(l,d),e.setParent(c,d),t.onChange&&t.events){const n=t.onChange;t.events.on(d,"change",()=>{const t=e.get(d,Ua);n(t.selectedIndex,d)})}return d}function ul(e,t){const n=tl();return nl(e,{name:"Label",parent:t.parent,rect:t.size?{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size}:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},text:{content:t.text,fontSize:t.fontSize??n.fontSize.md,color:t.color??n.text,align:t.align??cr.Left,verticalAlign:t.verticalAlign??dr.Middle}})}function hl(e,t={}){const n=tl();return nl(e,{name:"Panel",parent:t.parent,rect:{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},size:t.size??{x:300,y:200}},renderer:{visualType:qi.SolidColor,color:t.color??n.panel.backgroundColor}})}function fl(e,t={}){return nl(e,{name:"FlexRow",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:$a,wrap:t.wrap?Xa:Da,justifyContent:t.justifyContent??Na,alignItems:t.alignItems??Ya,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}function pl(e,t={}){return nl(e,{name:"FlexColumn",parent:t.parent,rect:{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1}},flex:{direction:Wa,wrap:t.wrap?Xa:Da,justifyContent:t.justifyContent??Na,alignItems:t.alignItems??Ya,gap:{x:t.gap??0,y:t.gap??0},padding:t.padding??{left:0,top:0,right:0,bottom:0}}})}const ml={button:sl,slider:il,toggle:ol,textInput:cl,dropdown:dl,progressBar:rl,label:ul,panel:hl,flexRow:fl,flexColumn:pl,scrollView:ll};const gl={spawn:nl,destroy:function e(t,n){if(t.valid(n)){if(t.has(n,re)){const s=[...t.get(n,re).entities];for(const n of s)e(t,n)}t.despawn(n)}},build:function e(t,n,s){let i,o;if("element"===n.type)i=nl(t,{...n,parent:s}),o=i;else{if(i=(0,ml[n.type])(t,{...n.options??{},parent:s}),"scrollView"===n.type){o=t.get(i,ha).contentEntity}else o=i}const r=n.children;if(r&&o)for(const n of r)e(t,n,o);return n.ref&&n.ref(i),i},label:ul,panel:hl,button:sl,slider:il,toggle:ol,scrollView:ll,textInput:cl,dropdown:dl,progressBar:rl,flexRow:fl,flexColumn:pl};async function yl(e,t,n){const s=e.getResource(to);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}const _l={nearest:0,linear:1},xl={repeat:0,clamp:1,mirror:2};function wl(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=_l[s.filterMode??"linear"]??1,a=xl[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function bl(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 vl(e,t,n){const s=e.FS;if(!s)return!1;try{return function(e,t){const n=e.FS;if(!n)return;const s=t.substring(0,t.lastIndexOf("/"));if(!s)return;const i=s.split("/").filter(e=>e);let o="";for(const e of i){o+="/"+e;try{n.mkdir(o)}catch{}}}(e,t),s.writeFile(t,n),!0}catch(e){return console.warn(`[Runtime] Failed to write virtual FS: ${t}`,e),!1}}async function Sl(e){const{app:t,module:n,sceneData:s,provider:i,spineManager:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,d=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=es(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=wl(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,d);const u=await async function(e,t,n,s){const i=new Set,o=new Map;for(const r of t.entities)for(const t of r.components){const r=ts(t.type);if(!r||!t.data)continue;const a=t.data[r.skeletonField],l=t.data[r.atlasField];if(!a||!l)continue;const c=`${a}:${l}`;if(i.has(c))continue;i.add(c);const d=n.resolvePath(l);try{const t=await n.readText(l),i=n.resolvePath(a),r="binary"===ys(i)?.contentType?await n.readBinary(a):await n.readText(a),u=s?"string"==typeof r?Fe.detectVersionJson(r):Fe.detectVersion(r):null,h=bl(t),f=d.substring(0,d.lastIndexOf("/")),p=e.getResourceManager(),m=new Map;for(const t of h){const s=f+"/"+t;try{const i=n.loadPixelsRaw?await n.loadPixelsRaw(s):await n.loadPixels(s),o=wl(e,i,!1);p.registerTextureWithPath(o,s),m.set(t,{glId:p.getTextureGLId(o),w:i.width,h:i.height})}catch(e){console.warn(`[Spine] Failed to load texture: ${s}`,e)}}(!u||"4.2"===u)&&(vl(e,d,t),vl(e,i,r)),o.set(c,{version:u,skelData:r,atlasText:t,textures:m})}catch(e){console.warn(`[Runtime] Failed to load spine asset: skel=${a} atlas=${l}`,e)}}return o}(n,s,i,o);if(r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??le,subStepCount:a?.subStepCount??4,contactHertz:a?.contactHertz??120,contactDampingRatio:a?.contactDampingRatio??10,contactSpeed:a?.contactSpeed??10};new ke("",e,()=>Promise.resolve(r)).build(t)}const h=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=es(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=ys(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),d=wl(e,c,!1),u=e.getResourceManager();s[o]=u.loadBitmapFont(t,d,c.width,c.height)}catch(e){console.warn(`[Runtime] Failed to load bitmap font: ${o}`,e),s[o]=0}}return s}(n,s,i),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=es(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=ge.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=ge.createFromAsset(e,r)}catch(e){console.warn(`[Runtime] Failed to load material: ${o}`,e),n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=es(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=ut(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,wl(e,s))}catch(e){console.warn(`[Runtime] Failed to load anim texture: ${t}`,e),r.set(t,0)}pt(ht(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=es(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=Ot(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=Ht(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=wl(e,t),St(r,t.width,t.height)}catch(e){console.warn(`[Runtime] Failed to load tileset texture: ${s}`,e)}o.push({textureHandle:r,columns:t.columns})}Mt(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=es(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await wt.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await wt.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=es(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,d,h,f);const p=os(t.world,s),m=t.world.getCppRegistry();if(m&&n.transform_update(m),o&&m&&u.size>0)for(const e of s.entities)for(const t of e.components){const n=ts(t.type);if(!n||!t.data)continue;const s=t.data[n.skeletonField],i=t.data[n.atlasField];if(!s||!i)continue;const r=`${s}:${i}`,a=u.get(r);if(!a||!a.version||"4.2"===a.version)continue;const l=p.get(e.id);if(void 0===l)continue;await o.loadEntity(l,a.skelData,a.atlasText,a.textures,m),o.setEntityProps(l,{skeletonScale:t.data.skeletonScale??1,flipX:t.data.flipX??!1,flipY:t.data.flipY??!1,layer:t.data.layer??0});const c=t.data.skin;c&&o.setSkin(l,c);const d=t.data.animation;d&&o.setAnimation(l,d,!1!==t.data.loop)}if(c&&t.hasResource(to))for(const e of p.values())t.world.insert(e,B,{scene:c,persistent:!1});if(l){const e=t.getResource(ks);e&&e.setAddressableManifest(l)}}function Tl(e,t,n){return{name:e,async setup(){await Sl({...n,sceneData:t,sceneName:e})}}}async function Pl(e){const{app:t,firstScene:n,aspectRatio:s}=e;ro(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,spineManager:e.spineManager,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(to);for(const t of e.scenes)o.register(Tl(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&ds(t.world,s)}class Ml{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=ts(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===ys(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=es(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=ys(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Cl="__preview__";class El{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(to);t.register({name:Cl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Cl),this.loadPromise_=t.load(Cl).then(()=>{}).catch(e=>{console.error("[Preview] Failed to load preview scene:",e)}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await We(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Ml(this.baseUrl_);await n.prefetch(t);const s=this.app_.getPlugin(Ue),i=s?.spineManager??null;await Sl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineManager:i,sceneName:Cl})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([A]);for(const s of n){if(e.get(s,A).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=fe/pe;const s=e.getEntitiesWithComponents([de]);for(const i of s){const s=e.get(i,de);if(s.designResolution){const e=s.pixelsPerUnit||ue;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(to).getScene(Cl),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,d,r);const a={isActive:!0,projectionType:ee.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:he.ColorAndDepth};e.insert(o,A,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(to);await e.switchTo(Cl),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Al={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=Xi.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:Xi.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){Xi.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Xi.releaseRenderTarget(e._handle),Al.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){Xi.begin(t,e._handle)},end(){Xi.end()},getDepthTexture:e=>Xi.getTargetDepthTexture(e._handle)};var Il;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Il||(Il={}));class Rl{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Il[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Il.Debug:console.debug(t,n);break;case Il.Info:console.log(t,n);break;case Il.Warn:console.warn(t,n);break;case Il.Error:console.error(t,n)}}}class kl{constructor(){this.handlers_=[],this.minLevel_=Il.Info,this.addHandler(new Rl)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Il.Debug,e,t,n)}info(e,t,n){this.log(Il.Info,e,t,n)}warn(e,t,n){this.log(Il.Warn,e,t,n)}error(e,t,n){this.log(Il.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Fl=new kl;function Ul(){return Fl}function Ll(e){Fl.setMinLevel(e)}function zl(e,t,n){Fl.debug(e,t,n)}function Bl(e,t,n){Fl.info(e,t,n)}function Ol(e,t,n){Fl.warn(e,t,n)}function Hl(e,t,n){Fl.error(e,t,n)}const $l={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},Wl={Running:0,Paused:1,Completed:2,Cancelled:3},Dl={None:0,Restart:1,PingPong:2};const Xl=1.70158,Nl=2.70158,Yl=2.5949095;const Vl=2*Math.PI/3,jl=2*Math.PI/4.5;const Gl=7.5625,ql=2.75;const Kl=1e-6;function Jl(e,t,n){switch(e){case $l.Linear:return t;case $l.EaseInQuad:return function(e){return e*e}(t);case $l.EaseOutQuad:return function(e){return e*(2-e)}(t);case $l.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case $l.EaseInCubic:return function(e){return e*e*e}(t);case $l.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case $l.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case $l.EaseInBack:return function(e){return Nl*e*e*e-Xl*e*e}(t);case $l.EaseOutBack:return function(e){const t=e-1;return 1+Nl*t*t*t+Xl*t*t}(t);case $l.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Yl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Yl)+2)/2}(t);case $l.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Vl)}(t);case $l.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Vl)+1}(t);case $l.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*jl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*jl)/2+1}(t);case $l.EaseOutBounce:return function(e){return e<1/ql?Gl*e*e:e<2/ql?Gl*(e-=1.5/ql)*e+.75:e<2.5/ql?Gl*(e-=2.25/ql)*e+.9375:Gl*(e-=2.625/ql)*e+.984375}(t);case $l.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<Kl)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<Kl)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case $l.Step:return function(e){return e<1?0:1}(t);default:return t}}const Zl=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??$l.Linear,bezierPoints:null,state:Wl.Running,loop:i?.loop??Dl.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===Wl.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Wl.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=Jl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Dl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Dl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Wl.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Wl.Running&&(t.state=Wl.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Wl.Paused&&(t.state=Wl.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Wl.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Wl.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Ql{constructor(e){this.id=e}get state(){return Zl.getState(this.id)}bezier(e,t,n,s){return Zl.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Ql?Zl.setSequenceNext(this.id,e.id):Zl.setSequenceNextExternal(this.id,e),this}pause(){Zl.pause(this.id)}resume(){Zl.resume(this.id)}cancel(){Zl.cancel(this.id)}}const ec={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class tc{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof Ql?(Zl.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let nc=null,sc=null;function ic(e,t){nc=e,sc=t,Zl.init(e,t)}function oc(){Zl.shutdown(),nc=null,sc=null}function rc(){if(!nc)throw new Error("Tween API not initialized");return nc}function lc(){if(!sc)throw new Error("Tween API not initialized");return sc}const cc={to(e,t,n,s,i,o){const r=rc(),a=lc(),l=o?.easing??$l.Linear,c=o?.delay??0,d=o?.loop??Dl.None,u=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,d,u);return new tc(r,a,h)},value(e,t,n,s,i){const o=Zl.create(e,t,n,s,i);return new Ql(o)},cancel(e){rc()._anim_cancelTween(lc(),e.entity)},cancelAll(e){rc()._anim_cancelAllTweens(lc(),e)},update(e){rc()._anim_updateTweens(lc(),e),Zl.update(e)}};class dc{constructor(){this.name="AnimationPlugin"}build(e){ic(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(s.Update,i([f(g)],e=>{be()&&!ve()||cc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(s.Update,i([f(g)],e=>{be()&&!ve()||xt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){oc()}}const uc=new dc;let hc=null,fc=null;function pc(e,t){hc=e,fc=t}function mc(){hc=null,fc=null}const gc={update(e){hc&&fc&&hc.particle_update?.(fc,e)},play(e){hc&&fc&&hc.particle_play?.(fc,e)},stop(e){hc&&fc&&hc.particle_stop?.(fc,e)},reset(e){hc&&fc&&hc.particle_reset?.(fc,e)},getAliveCount:e=>hc?hc.particle_getAliveCount?.(e)??0:0};class yc{constructor(){this.name="ParticlePlugin"}build(e){pc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(s.Update,i([f(g)],e=>{gc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){mc()}}const _c=new yc,xc=1073741824,wc={orthogonal:0,isometric:1,staggered:2};class bc{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.animatedLayers_=new Set,this.sourceEntityKeys_=new Map,this.layerState_=new Map}build(e){It(e.wasmModule);const t=e.world,n=this.initializedLayers_,i=this.animatedLayers_,o=this.sourceEntityKeys_,r=this.layerState_,a={_id:Symbol("TilemapSyncSystem"),_name:"TilemapSyncSystem",_params:[],_fn:()=>{const s=t.getEntitiesWithComponents([Ut,d]),a=new Set(s);for(const e of n)e>=xc||a.has(e)||(kt.destroyLayer(e),n.delete(e),r.delete(e));for(const e of s){const s=t.tryGet(e,Ut);if(!s)continue;const i=s.texture;if(!i)continue;const o=Tt(i);if(!o)continue;if(!n.has(e)){if(kt.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),kt.setOriginEntity(e,e),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];kt.setTiles(e,t)}n.add(e)}const a=s.tileWidth/o.width,l=s.tileHeight/o.height,c=s.tint,d=s.parallaxFactor,u=r.get(e);(!u||u.texture!==i||u.tilesetColumns!==s.tilesetColumns||u.layer!==s.layer||u.parallaxX!==d.x||u.parallaxY!==d.y||u.tintR!==c.r||u.tintG!==c.g||u.tintB!==c.b||u.tintA!==c.a||u.opacity!==s.opacity||u.visible!==s.visible)&&(kt.setRenderProps(e,i,s.tilesetColumns,a,l,s.layer,0,d.x,d.y),kt.setTint(e,c.r,c.g,c.b,c.a,s.opacity),kt.setVisible(e,s.visible),r.set(e,{texture:i,tilesetColumns:s.tilesetColumns,layer:s.layer,tintR:c.r,tintG:c.g,tintB:c.b,tintA:c.a,opacity:s.opacity,parallaxX:d.x,parallaxY:d.y,visible:s.visible}))}const l=t.getEntitiesWithComponents([Ft,d]);for(const e of l){if(t.tryGet(e,Ut))continue;const s=t.tryGet(e,Ft);if(!s?.source)continue;const r=Ct(s.source);if(r&&!o.has(e)){const t=[],s=wc[r.orientation??"orthogonal"]??0;for(let o=0;o<r.layers.length;o++){const a=xc+256*e+o,l=r.layers[o];if(kt.initLayer(a,l.width,l.height,r.tileWidth,r.tileHeight),kt.setOriginEntity(a,e),l.tiles.length>0&&kt.setTiles(a,l.tiles),0!==s&&kt.setGridType(a,s),r.tileAnimations){for(const[e,t]of r.tileAnimations)kt.setTileAnimation(a,e,t);r.tileAnimations.size>0&&i.add(a)}if(r.tileProperties)for(const[e,t]of r.tileProperties)for(const[n,s]of t)kt.setTileProperty(a,e,n,s);const c=r.tilesets[0];if(c){const e=Tt(c.textureHandle);e&&(kt.setRenderProps(a,c.textureHandle,c.columns,r.tileWidth/e.width,r.tileHeight/e.height,o,0,1,1),kt.setTint(a,1,1,1,1,1),kt.setVisible(a,!0))}t.push(a),n.add(a)}o.set(e,t)}}const c=new Set(l);for(const[e,t]of o)if(!c.has(e)){for(const e of t)kt.destroyLayer(e),n.delete(e),i.delete(e),r.delete(e);o.delete(e)}if(i.size>0){const t=1e3*e.getResource(g).delta;for(const e of i)kt.advanceAnimations(e,t)}}};e.addSystemToSchedule(s.PreUpdate,a)}cleanup(){for(const e of this.initializedLayers_)kt.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),this.layerState_.clear(),Pt(),Rt()}}const vc=new bc;function Sc(e,t){return e.toFixed(t)}function Tc(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Pc{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.lastUpdateTime_=0,this.lastStats_=null,this.accumulatedTimings_=new Map,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 220px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;this.lastStats_=e,this.accumulateTimings_(e.systemTimings);const t=performance.now();this.lastUpdateTime_>0&&t-this.lastUpdateTime_<500||(this.lastUpdateTime_=t,this.render_())}show(){this.visible_=!0,this.lastUpdateTime_=0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}accumulateTimings_(e){for(const[t,n]of e){const e=this.accumulatedTimings_.get(t);e?(e.sum+=n,e.count++,n>e.max&&(e.max=n)):this.accumulatedTimings_.set(t,{sum:n,max:n,count:1})}}render_(){const e=this.lastStats_;if(!e)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Sc(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Sc(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),this.accumulatedTimings_.size>0){const e=[];for(const[t,n]of this.accumulatedTimings_){const s=n.sum/n.count;e.push([t,s,n.max])}e.sort((e,t)=>t[2]-e[2]);const n=e.slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t,i]of n){s+=`<div>${Tc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Sc(t,1)} / ${Sc(i,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join(""),this.accumulatedTimings_.clear()}}function Mc(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Cc=e(Mc(),"Stats");class Ec{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const Ac="StatsCollect";class Ic{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Rc{constructor(e){this.name="Stats",this.collector_=new Ic,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Cc,Mc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Pc(e,this.options_.position)}const t=this.collector_,n=this.overlay_,o=i([f(g),me()],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Cc);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Ac),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Xi.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:Ac});e.addSystemToSchedule(s.Last,o)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const kc=new Rc;class Fc{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return Uc(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}function Uc(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}function Lc(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function zc(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await async function(e,t){try{const n=Lc(t),s={instantiateWasm(e,t){const s=new Response(n.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,e).then(e=>t(e.instance,e.module),()=>{WebAssembly.instantiate(n.buffer,e).then(e=>t(e.instance,e.module)).catch(e=>{console.error("[Playable] WASM instantiation fallback failed:",e)})}),{}}};return await e(s)}catch(e){return console.error("[Playable] WASM module init failed:",e),null}}(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}async function Bc(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(ks);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));let a=null;if(e.spineModules&&Object.keys(e.spineModules).length>0){a=function(e,t){const n=new Map;for(const[e,s]of Object.entries(t)){const t=e;n.set(t,async()=>{const e=Lc(s.wasmBase64);return s.factory({instantiateWasm(t,n){const s=new Response(e.buffer,{headers:{"Content-Type":"application/wasm"}});return WebAssembly.instantiateStreaming(s,t).then(e=>n(e.instance,e.module),()=>{WebAssembly.instantiate(e.buffer,t).then(e=>n(e.instance,e.module)).catch(e=>{console.error("[Playable] Spine WASM instantiation fallback failed:",e)})}),{}}})})}return new Fe(e,n)}(n,e.spineModules);const s=t.getPlugin(Ue);s&&s.setSpineManager(a)}const l=e.physicsWasmBase64?await zc(e.physicsWasmBase64):null,c=new Fc(s);wt.setAssetResolver(e=>{const t=s[e];return t?Uc(t).buffer:null}),await Pl({app:t,module:n,provider:c,scenes:i,firstScene:o,spineManager:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Oc=[yr,br,Lr,qr,oa,Hr,ua,ga,va,ta,Yr,Ta,Ea,Fa,za,Ha,Ka],Hc=[uc,$n,_c,vc,Ui,Kn];function $c(e,t){const n=new Ue(t?.spineProvider),i=[...Oc,...Hc,n,...t?.plugins??[]];return function(e,t){const n=oo.new(),i=new e.Registry;n.connectCpp(i,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ie(e),Re(e),ei(e),fi(e),Wi(e),Yi(e);const o=new Gi;n.setPipeline(o);let r=je();const a=t?.getViewportSize??(()=>{const e=Ge();return{width:window.innerWidth*e,height:window.innerHeight*e}});function l(t,s,o){o||(o=fo(e,i,t,s));const r=n.getResource(lt);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*s),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*s),r.screenW=t,r.screenH=s,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(lt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=a();l(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:s}=a();if(0===t||0===s)return;const c=e.registry_getCanvasEntity(i);if(c>=0){const e=i.getCanvas(c).backgroundColor;Xi.setClearColor(e.x,e.y,e.z,e.w)}const d=(je()-r)/1e3;let u;if(Xi.resize(t,s),n.hasResource(to)){const e=n.getResource(to).getActiveScenes();e.length>0&&(u=new Set(e))}o.setActiveScenes(u??null);const h=fo(e,i,t,s,n.world,u);if(l(t,s,h),0===h.length)o.render({registry:{_cpp:i},viewProjection:lo,width:t,height:s,elapsed:d});else{o.beginFrame(),o.beginScreenCapture();for(const e of h){const n=e.viewportRect,r=Math.round(n.x*t),a=Math.round((1-n.y-n.h)*s),l=Math.round(n.w*t),c=Math.round(n.h*s);o.renderCamera({registry:{_cpp:i},viewProjection:e.viewProjection,viewportPixels:{x:r,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:d,cameraEntity:e.entity})}o.endScreenCapture(),Xi.setViewport(0,0,t,s)}}};if(n.addSystemToSchedule(s.First,c),n.addSystemToSchedule(s.Last,d),n.addPlugin(Us),n.addPlugin(Gs),n.addPlugin(rt),n.addPlugin(io),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{...t,plugins:i})}Le=et;export{dc as AnimationPlugin,oo as App,Fs as AssetPlugin,Ls as AssetRefCounter,Rs as AssetServer,ks as Assets,ct as AsyncCache,Fn as AttenuationModel,wt as Audio,qe as AudioBus,On as AudioListener,Ke as AudioMixer,Hn as AudioPlugin,Je as AudioPool,Bn as AudioSource,H as BitmapText,_e as BodyType,we as BoxCollider,Ir as Button,Ar as ButtonState,A as Camera,de as Canvas,re as Children,xe as CircleCollider,he as ClearFlags,Ja as DARK_THEME,pe as DEFAULT_DESIGN_HEIGHT,fe as DEFAULT_DESIGN_WIDTH,le as DEFAULT_FIXED_TIMESTEP,ce as DEFAULT_GRAVITY,ue as DEFAULT_PIXELS_PER_UNIT,qs as DataType,da as DragPlugin,la as DragState,ra as Draggable,Se as Draw,Ua as Dropdown,La as DropdownPlugin,$l as EasingType,nr as EntityStateMap,D as EventRegistry,vo as FillDirection,To as FillMethod,Po as FillOrigin,Li as FlushReason,Xr as FocusManager,Dr as FocusManagerState,Sa as FocusPlugin,Wr as Focusable,Ec as FrameHistory,ji as GLDebug,si as Geometry,me as GetWorld,E as INVALID_ENTITY,se as INVALID_TEXTURE,Mo as Image,Gr as ImagePlugin,So as ImageType,it as Input,ot as InputPlugin,st as InputState,Eo as Interactable,Oa as LayoutGroupPlugin,Aa as ListView,ka as ListViewPlugin,Il as LogLevel,kl as Logger,Dl as LoopMode,ge as Material,dt as MaterialLoader,P as Name,ie as Parent,gc as Particle,yc as ParticlePlugin,ke as PhysicsPlugin,gi as PostProcess,Fi as PostProcessPlugin,di as PostProcessStack,F as PostProcessVolume,Ys as PrefabServer,Vs as Prefabs,js as PrefabsPlugin,El as PreviewPlugin,sa as ProgressBar,na as ProgressBarDirection,ia as ProgressBarPlugin,ee as ProjectionType,R as Query,Gi as RenderPipeline,Bi as RenderStage,Al as RenderTexture,zi as RenderType,Xi as Renderer,f as Res,W as ResMut,ye as RigidBody,r as RuntimeConfig,Pa as SafeArea,Ca as SafeAreaPlugin,te as ScaleMode,to as SceneManager,eo as SceneManagerState,B as SceneOwner,s as Schedule,ha as ScrollView,ma as ScrollViewPlugin,_a as Slider,ya as SliderDirection,ba as SliderPlugin,T as SpineAnimation,c as Sprite,_t as SpriteAnimator,Cc as Stats,Ic as StatsCollector,Pc as StatsOverlay,Rc as StatsPlugin,nt as Storage,Oi as SubmitSkipFlags,Q as SystemRunner,hr as Text,cr as TextAlign,$r as TextInput,Nr as TextInputPlugin,ur as TextOverflow,gr as TextPlugin,fr as TextRenderer,dr as TextVerticalAlign,Ft as Tilemap,kt as TilemapAPI,Ut as TilemapLayer,bc as TilemapPlugin,g as Time,qn as TimelinePlugin,Kr as Toggle,ea as TogglePlugin,d as Transform,cc as Tween,tc as TweenHandle,Wl as TweenState,ec as TweenTarget,gl as UI,lt as UICameraInfo,Rr as UIEventQueue,kr as UIEvents,Er as UIInteraction,Or as UIInteractionPlugin,Fr as UILayoutGeneration,Ur as UILayoutPlugin,xr as UIMask,wr as UIMaskPlugin,Co as UIRect,qa as UIRenderOrderPlugin,Ki as UIRenderer,Za as UIThemeRes,qi as UIVisualType,Ml as WebAssetProvider,N as World,u as WorldTransform,uc as animationPlugin,Lo as applyDirectionalFill,$s as applyOverrides,Us as assetPlugin,$n as audioPlugin,Ln as calculateAttenuation,zn as calculatePanning,Mi as cleanupAllPostProcessVolumes,Pi as cleanupPostProcessVolume,yt as clearAnimClips,Ce as clearDrawCallbacks,Pt as clearTextureDimensionsCache,Et as clearTilemapSourceCache,kn as clearTimelineHandles,Os as cloneComponentData,Bs as cloneComponents,Ds as collectNestedPrefabPaths,er as colorScale,tr as colorWithAlpha,ko as computeFillAnchors,Uo as computeFillSize,Fo as computeHandleAnchors,Ao as computeUIRectLayout,Tl as createRuntimeSceneConfig,$c as createWebApp,zl as debug,Mc as defaultFrameStats,a as defineComponent,e as defineResource,i as defineSystem,ua as dragPlugin,za as dropdownPlugin,Hl as error,ut as extractAnimClipTexturePaths,us as findEntityByName,Ws as flattenPrefab,ro as flushPendingSystems,Ta as focusPlugin,xs as getAddressableType,ws as getAddressableTypeByEditorType,vs as getAllAssetExtensions,bi as getAllEffectDefs,gt as getAnimClip,Is as getAssetBuildTransform,Ms as getAssetMimeType,ys as getAssetTypeEntry,b as getComponent,es as getComponentAssetFieldDescriptors,Qn as getComponentAssetFields,C as getComponentEntityFields,ts as getComponentSpineFieldDescriptor,Ts as getCustomExtensions,_s as getEditorType,xi as getEffectDef,wi as getEffectTypes,Ul as getLogger,ze as getPlatform,Oe as getPlatformType,Tt as getTextureDimensions,Ct as getTilemapSource,Rn as getTimelineHandle,Ps as getWeChatPackOptions,qr as imagePlugin,Bl as info,Ie as initDrawAPI,Yi as initGLDebugAPI,ei as initGeometryAPI,Re as initMaterialAPI,pc as initParticleAPI,Bc as initPlayableRuntime,fi as initPostProcessAPI,Wi as initRendererAPI,Pl as initRuntime,It as initTilemapAPI,ic as initTweenAPI,el as initUIBuilder,rt as inputPlugin,Ns as instantiatePrefab,vr as intersectRects,Sr as invertMatrix4,Cs as isCustomExtension,be as isEditor,bs as isKnownAssetExtension,Be as isPlatformInitialized,ve as isPlayMode,He as isWeChat,$e as isWeb,Ha as layoutGroupPlugin,Fa as listViewPlugin,cs as loadComponent,Sl as loadRuntimeScene,os as loadSceneData,rs as loadSceneWithAssets,Xt as loadTiledMap,Ss as looksLikeAssetPath,qo as makeInteractable,ht as parseAnimClipData,$t as parseTiledMap,hn as parseTimelineAsset,Ot as parseTmjJson,_c as particlePlugin,We as platformFetch,Ne as platformFileExists,Ye as platformInstantiateWasm,De as platformReadFile,Xe as platformReadTextFile,Cr as pointInOBB,Pr as pointInWorldRect,Ui as postProcessPlugin,Gs as prefabsPlugin,Xs as preloadNestedPrefabs,oa as progressBarPlugin,pt as registerAnimClip,As as registerAssetBuildTransform,oe as registerComponent,Zn as registerComponentAssetFields,Me as registerDrawCallback,zs as registerEmbeddedAssets,St as registerTextureDimensions,Mt as registerTilemapSource,Xn as registerTimelineAsset,Hs as remapComponentEntityRefs,ns as remapEntityFields,Ht as resolveRelativePath,Ea as safeAreaPlugin,io as sceneManagerPlugin,Tr as screenToWorld,ga as scrollViewPlugin,Zo as setEntityColor,Qo as setEntityEnabled,Ra as setListViewRenderer,Ll as setLogLevel,ne as setWasmErrorHandler,Ae as shutdownDrawAPI,Vi as shutdownGLDebugAPI,ti as shutdownGeometryAPI,Ee as shutdownMaterialAPI,mc as shutdownParticleAPI,pi as shutdownPostProcessAPI,Di as shutdownRendererAPI,Rt as shutdownTilemapAPI,oc as shutdownTweenAPI,va as sliderPlugin,xt as spriteAnimatorSystemUpdate,kc as statsPlugin,jo as syncFillSpriteSize,Ti as syncPostProcessVolume,Yr as textInputPlugin,yr as textPlugin,vc as tilemapPlugin,Kn as timelinePlugin,Es as toBuildPath,ta as togglePlugin,yl as transitionTo,Hr as uiInteractionPlugin,Lr as uiLayoutPlugin,br as uiMaskPlugin,Oc as uiPlugins,Ka as uiRenderOrderPlugin,mt as unregisterAnimClip,Te as unregisterDrawCallback,ds as updateCameraAspectRatio,Ol as warn,Ko as withChildEntity,no as wrapSceneSystem};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/shared/app.d.ts b/desktop/public/sdk/esm/shared/app.d.tsindex fe979e606..73e3494db 100644--- a/desktop/public/sdk/esm/shared/app.d.ts+++ b/desktop/public/sdk/esm/shared/app.d.ts@@ -332,7 +332,7 @@ declare class World {getCppRegistry(): CppRegistry | null;/** @internal */getWasmModule(): ESEngineModule | null;- spawn(): Entity;+ spawn(name?: string): Entity;despawn(entity: Entity): void;onSpawn(callback: (entity: Entity) => void): () => void;onDespawn(callback: (entity: Entity) => void): () => void;@@ -496,7 +496,7 @@ declare class EntityCommands {private readonly entityRef_;private readonly components_;private isNew_;- constructor(commands: CommandsInstance, entity: Entity | null);+ constructor(commands: CommandsInstance, entity: Entity | null, name?: string);insert<T extends object>(component: AnyComponentDef, data?: Partial<T>): this;remove(component: AnyComponentDef): this;id(): Entity;@@ -508,7 +508,7 @@ declare class CommandsInstance {private pending_;private spawned_;constructor(world: World, resources: ResourceStorage);- spawn(): EntityCommands;+ spawn(name?: string): EntityCommands;entity(entity: Entity): EntityCommands;despawn(entity: Entity): this;insertResource<T>(resource: ResourceDef<T>, value: T): this;diff --git a/desktop/public/sdk/esm/shared/system.js b/desktop/public/sdk/esm/shared/system.jsindex 2b5e51076..c83fdd7c7 100644--- a/desktop/public/sdk/esm/shared/system.js+++ b/desktop/public/sdk/esm/shared/system.js@@ -1,2 +1,2 @@-const t=1920,e=1080,s=100,n=512,i={x:100,y:100},r="Arial",o=24,a=1.2,c=.5,l=1/60,h={x:0,y:-9.81},u=1/60,d="default",f={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};function _(t){t.Text&&(t.Text._default.fontFamily=f.defaultFontFamily),t.TextInput&&(t.TextInput._default.fontFamily=f.defaultFontFamily),t.Canvas&&(t.Canvas._default.scaleMode=f.canvasScaleMode,t.Canvas._default.matchWidthOrHeight=f.canvasMatchWidthOrHeight)}const p={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function m(t,e){if(void 0!==e.maxDeltaTime&&(f.maxDeltaTime=e.maxDeltaTime,t.setMaxDeltaTime(e.maxDeltaTime)),void 0!==e.maxFixedSteps&&(f.maxFixedSteps=e.maxFixedSteps,t.setMaxFixedSteps(e.maxFixedSteps)),void 0!==e.textCanvasSize&&(f.textCanvasSize=e.textCanvasSize),void 0!==e.defaultFontFamily&&(f.defaultFontFamily=e.defaultFontFamily),void 0!==e.sceneTransitionDuration&&(f.sceneTransitionDuration=e.sceneTransitionDuration),e.sceneTransitionColor){const t=e.sceneTransitionColor.replace("#","");f.sceneTransitionColor={r:parseInt(t.substring(0,2),16)/255,g:parseInt(t.substring(2,4),16)/255,b:parseInt(t.substring(4,6),16)/255,a:1}}void 0!==e.canvasScaleMode&&(f.canvasScaleMode=p[e.canvasScaleMode]??1),void 0!==e.canvasMatchWidthOrHeight&&(f.canvasMatchWidthOrHeight=e.canvasMatchWidthOrHeight),void 0!==e.assetLoadTimeout&&(f.assetLoadTimeout=e.assetLoadTimeout),void 0!==e.assetFailureCooldown&&(f.assetFailureCooldown=e.assetFailureCooldown)}const y=0,g=4294967295,w=4294967295,v=0,b=(t=0,e=0)=>({x:t,y:e}),C=(t=0,e=0,s=0)=>({x:t,y:e,z:s}),k=(t=0,e=0,s=0,n=1)=>({x:t,y:e,z:s,w:n}),S=(t=1,e=1,s=1,n=1)=>({r:t,g:e,b:s,a:n}),x=(t=1,e=0,s=0,n=0)=>({w:t,x:e,y:s,z:n}),R=new Map;function T(t,e){R.set(t,e)}function M(t){return R.get(t)}function F(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(F);const e={};for(const s in t)e[s]=F(t[s]);return e}let B=0;function P(t,e){const s=++B,n=function(t){const e=[],s=[],n=[];let i=!1;for(const r in t){const o=t[r];null!==o&&"object"==typeof o?(i=!0,Array.isArray(o)?n.push(r):s.push(r)):e.push(r)}return i?{flatKeys:e,objectKeys:s,arrayKeys:n}:null}(e),i=e;return{_id:Symbol(`Component_${s}_${t}`),_name:t,_default:e,_builtin:!1,create(t){if(n){const e={...i};for(const t of n.objectKeys)e[t]={...i[t]};for(const t of n.arrayKeys)e[t]=i[t].slice();return t&&Object.assign(e,t),e}return t?{...e,...t}:{...e}}}}function E(){const t=globalThis;return t.__esengine_componentRegistry??(t.__esengine_componentRegistry=new Map)}function $(t,e,s){const n=W.get(t)??E().get(t);if(n)return n;const i=P(t,e);return E().set(t,i),W.set(t,i),N(t,e,!1),s?.entityFields&&T(t,s.entityFields),i}function z(t){const e=W.get(t)??E().get(t);if(e)return e;const s=P(t,{});return E().set(t,s),W.set(t,s),N(t,{},!0),s}function A(t){return E().get(t)}function I(){const t=E();for(const e of t.keys())W.delete(e);t.clear()}function D(t){E().delete(t),W.delete(t)}function N(t,e,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(t,e,s)}function q(t){return!0===t._builtin}const W=new Map;function j(t,e){W.set(t,e)}function O(t){return W.get(t)??A(t)}function U(t){if(null===t||"object"!=typeof t)return[];const e=[];for(const s of Object.keys(t)){const n=t[s];if(null!==n&&"object"==typeof n&&!Array.isArray(n)){"r"in n&&"g"in n&&"b"in n&&"a"in n&&e.push(s)}}return e}function V(t,e,s){const n={_id:Symbol(`Builtin_${t}`),_name:t,_cppName:t,_builtin:!0,_default:e,_colorKeys:U(e)};return W.set(t,n),n}const H={Perspective:0,Orthographic:1},L={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},K={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},G={Circle:0,Capsule:1,RoundedRect:2},X=V("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),Y=X,J=X,Q=V("Sprite",{texture:g,color:{r:1,g:1,b:1,a:1},size:{x:i.x,y:i.y},pivot:{x:.5,y:.5},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Z=V("ShapeRenderer",{shapeType:G.Circle,color:{r:1,g:1,b:1,a:1},size:{x:100,y:100},cornerRadius:0,layer:0,enabled:!0}),tt=V("Camera",{projectionType:H.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:L.ColorAndDepth}),et=V("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:K.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),st=V("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),nt=V("Parent",{entity:0}),it=V("Children",{entities:[]}),rt=V("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:w,enabled:!0}),ot=V("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,enabled:!0}),at={Point:0,Circle:1,Rectangle:2,Cone:3},ct={World:0,Local:1},lt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},ht=V("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:at.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:lt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:lt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:g,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:ct.World,enabled:!0}),ut=$("Name",{value:""}),dt=$("SceneOwner",{scene:"",persistent:!1}),ft=$("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function _t(t){const e=O(t);return e?F(e._default):null}let pt=0;function mt(t,e){const s=++pt;return{_id:Symbol(`Resource_${s}_${e??""}`),_name:e??`Resource_${s}`,_default:t}}function yt(t){return{_type:"res",_resource:t}}function gt(t){return{_type:"res_mut",_resource:t}}class wt{constructor(t,e){this.value_=t,this.setter_=e}get(){return this.value_}set(t){this.value_=t,this.setter_(t)}modify(t){t(this.value_),this.setter_(this.value_)}updateValue(t){this.value_=t}}class vt{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(t,e){this.resources_.set(t._id,e)}get(t){return this.resources_.has(t._id)||this.resources_.set(t._id,t._default),this.resources_.get(t._id)}set(t,e){this.resources_.set(t._id,e)}has(t){return this.resources_.has(t._id)}remove(t){this.resources_.delete(t._id),this.resMutPool_.delete(t._id)}getResMut(t){let e=this.resMutPool_.get(t._id);return e?(e.updateValue(this.get(t)),e):(e=new wt(this.get(t),e=>this.set(t,e)),this.resMutPool_.set(t._id,e),e)}}const bt=mt({delta:0,elapsed:0,frameCount:0},"Time");function Ct(t,e,s){const n=[];for(const[t,i]of Object.entries(s)){if(!(t in e)){n.push({field:t,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=kt(e[t]),r=kt(i);"null"!==s&&"undefined"!==s&&(s!==r&&null!=i&&n.push({field:t,expected:s,actual:r,value:i}))}return n}function kt(t){return null===t?"null":void 0===t?"undefined":Array.isArray(t)?"array":typeof t}function St(t,e){const s=[`Invalid component data for "${t}":`];for(const t of e)s.push(` - Field "${t.field}": expected ${t.expected}, got ${t.actual} (${JSON.stringify(t.value)})`);return s.join("\n")}let xt=null;function Rt(t){xt=t}function Tt(t,e){console.error(`[ESEngine] WASM error in ${e}:`,t),xt&&xt(t,e)}function Mt(t,e){if(0===e.length)return t;const s={...t};for(const t of e){const e=s[t];e&&"object"==typeof e&&(s[t]={r:e.x,g:e.y,b:e.z,a:e.w})}return s}function Ft(t,e){if(0===e.length)return t;const s={...t};for(const t of e){const e=s[t];e&&"object"==typeof e&&(s[t]={x:e.r,y:e.g,z:e.b,w:e.a})}return s}const Bt={Transform:{ptrFn:"getTransformPtr",fields:[{name:"position",type:"vec3",offset:0},{name:"rotation",type:"quat",offset:12},{name:"scale",type:"vec3",offset:28},{name:"worldPosition",type:"vec3",offset:40},{name:"worldRotation",type:"quat",offset:52},{name:"worldScale",type:"vec3",offset:68}]},Sprite:{ptrFn:"getSpritePtr",fields:[{name:"texture",type:"u32",offset:0},{name:"color",type:"color",offset:4},{name:"size",type:"vec2",offset:20},{name:"uvOffset",type:"vec2",offset:28},{name:"uvScale",type:"vec2",offset:36},{name:"layer",type:"i32",offset:44},{name:"flipX",type:"bool",offset:48},{name:"flipY",type:"bool",offset:49},{name:"material",type:"u32",offset:52},{name:"enabled",type:"bool",offset:56}]},Velocity:{ptrFn:"getVelocityPtr",fields:[{name:"linear",type:"vec3",offset:0},{name:"angular",type:"vec3",offset:12}]},Camera:{ptrFn:"getCameraPtr",fields:[{name:"projectionType",type:"u8",offset:0},{name:"fov",type:"f32",offset:4},{name:"orthoSize",type:"f32",offset:8},{name:"nearPlane",type:"f32",offset:12},{name:"farPlane",type:"f32",offset:16},{name:"aspectRatio",type:"f32",offset:20},{name:"isActive",type:"bool",offset:24},{name:"priority",type:"i32",offset:28},{name:"viewportX",type:"f32",offset:32},{name:"viewportY",type:"f32",offset:36},{name:"viewportW",type:"f32",offset:40},{name:"viewportH",type:"f32",offset:44},{name:"clearFlags",type:"i32",offset:48}]},UIRect:{ptrFn:"getUIRectPtr",fields:[{name:"anchorMin",type:"vec2",offset:0},{name:"anchorMax",type:"vec2",offset:8},{name:"offsetMin",type:"vec2",offset:16},{name:"offsetMax",type:"vec2",offset:24},{name:"size",type:"vec2",offset:32},{name:"pivot",type:"vec2",offset:40}]},RigidBody:{ptrFn:"getRigidBodyPtr",fields:[{name:"bodyType",type:"u8",offset:0},{name:"gravityScale",type:"f32",offset:4},{name:"linearDamping",type:"f32",offset:8},{name:"angularDamping",type:"f32",offset:12},{name:"fixedRotation",type:"bool",offset:16},{name:"bullet",type:"bool",offset:17},{name:"enabled",type:"bool",offset:18}]},BoxCollider:{ptrFn:"getBoxColliderPtr",fields:[{name:"halfExtents",type:"vec2",offset:0},{name:"offset",type:"vec2",offset:8},{name:"density",type:"f32",offset:16},{name:"friction",type:"f32",offset:20},{name:"restitution",type:"f32",offset:24},{name:"isSensor",type:"bool",offset:28},{name:"enabled",type:"bool",offset:29},{name:"categoryBits",type:"u32",offset:32},{name:"maskBits",type:"u32",offset:36}]},CircleCollider:{ptrFn:"getCircleColliderPtr",fields:[{name:"radius",type:"f32",offset:0},{name:"offset",type:"vec2",offset:4},{name:"density",type:"f32",offset:12},{name:"friction",type:"f32",offset:16},{name:"restitution",type:"f32",offset:20},{name:"isSensor",type:"bool",offset:24},{name:"enabled",type:"bool",offset:25},{name:"categoryBits",type:"u32",offset:28},{name:"maskBits",type:"u32",offset:32}]}};function Pt(t,e,s,n,i,r){const o=n+i.offset,a=o>>2;switch(i.type){case"f32":t[a]=r;break;case"i32":e[a]=0|r;break;case"u32":e[a]=r;break;case"bool":s[o]=r?1:0;break;case"u8":s[o]=r;break;case"vec2":t[a]=r.x,t[a+1]=r.y;break;case"vec3":t[a]=r.x,t[a+1]=r.y,t[a+2]=r.z;break;case"quat":t[a]=r.x,t[a+1]=r.y,t[a+2]=r.z,t[a+3]=r.w;break;case"color":t[a]=r.r,t[a+1]=r.g,t[a+2]=r.b,t[a+3]=r.a}}let Et=1;const $t=new WeakMap;function zt(t){let e=$t.get(t);return void 0===e&&(e=Et++,$t.set(t,e)),e}const At=[];function It(t,e=[],s=[]){At.length=0;for(const e of t)At.push(zt(e));At.sort((t,e)=>t-e);let n=At.join(",");if(e.length>0){At.length=0;for(const t of e)At.push(zt(t));At.sort((t,e)=>t-e),n+="|+"+At.join(",")}if(s.length>0){At.length=0;for(const t of s)At.push(zt(t));At.sort((t,e)=>t-e),n+="|-"+At.join(",")}return n}class Dt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.builtinEntitySets_=new Map,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map,this.trackedComponents_=new Set}connectCpp(t,e){this.cppRegistry_=t,this.module_=e??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}getWasmModule(){return this.module_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let t;if(this.cppRegistry_)try{t=this.cppRegistry_.create()}catch(t){throw Tt(t,"spawn"),t}else t=++this.nextEntityId_;let e=0;if(this.module_&&this.cppRegistry_)try{e=this.module_.registry_getGeneration(this.cppRegistry_,t)}catch{}else e=++this.nextGeneration_;this.entities_.set(t,e),this.worldVersion_++;for(const e of this.spawnCallbacks_)try{e(t)}catch(t){console.warn("[World] Spawn callback error:",t)}return t}despawn(t){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const e of this.despawnCallbacks_)try{e(t)}catch(t){console.warn("[World] Despawn callback error:",t)}if(this.cppRegistry_)try{this.cppRegistry_.destroy(t)}catch(e){Tt(e,`despawn(entity=${t})`)}this.entities_.delete(t),this.worldVersion_++;for(const[,e]of this.builtinEntitySets_)e.delete(t);const e=this.entityComponents_.get(t);if(e){for(const s of e){this.tsStorage_.get(s)?.delete(t),this.componentAddedTicks_.get(s)?.delete(t),this.componentChangedTicks_.get(s)?.delete(t);let e=this.componentRemovedBuffer_.get(s);e||(e=[],this.componentRemovedBuffer_.set(s,e)),e.push({entity:t,tick:this.worldTick_})}this.entityComponents_.delete(t)}}onSpawn(t){return this.spawnCallbacks_.push(t),()=>{const e=this.spawnCallbacks_.indexOf(t);-1!==e&&this.spawnCallbacks_.splice(e,1)}}onDespawn(t){return this.despawnCallbacks_.push(t),()=>{const e=this.despawnCallbacks_.indexOf(t);-1!==e&&this.despawnCallbacks_.splice(e,1)}}valid(t){return this.entities_.has(t)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(t,e){if(this.cppRegistry_)try{this.cppRegistry_.setParent(t,e)}catch(s){Tt(s,`setParent(child=${t}, parent=${e})`)}}removeParent(t){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(t)}catch(e){Tt(e,`removeParent(entity=${t})`)}}insert(t,e,s){return q(e)?this.insertBuiltin(t,e,s):this.insertScript(t,e,s)}set(t,e,s){if(q(e)){if(this.cppRegistry_)try{const n=e._default,i=s;let r=i;for(const t of Object.keys(i))t in n||(r===i&&(r={...i}),delete r[t]);this.getBuiltinMethods(e._cppName).add(t,Ft(r,e._colorKeys))}catch(s){Tt(s,`set(${e._name}, entity=${t})`)}this.recordChangedTick_(e,t)}else this.getStorage(e).set(t,s),this.recordChangedTick_(e,t)}get(t,e){return q(e)?this.getBuiltin(t,e):this.getScript(t,e)}has(t,e){if(e._builtin){if(!this.cppRegistry_)return!1;const s=e._cppName,n=this.builtinEntitySets_.get(s);return n?n.has(t):this.getBuiltinMethods(s).has(t)}return this.hasScript(t,e)}tryGet(t,e){if(q(e)){if(!this.cppRegistry_)return null;const s=this.builtinEntitySets_.get(e._cppName);if(s&&!s.has(t))return null;try{const n=this.getBuiltinMethods(e._cppName);return s||n.has(t)?Mt(n.get(t),e._colorKeys):null}catch(s){return Tt(s,`tryGet(${e._name}, entity=${t})`),null}}const s=this.tsStorage_.get(e._id);if(!s)return null;const n=s.get(t);return void 0!==n?n:null}remove(t,e){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");q(e)?this.removeBuiltin(t,e):this.removeScript(t,e)}getBuiltinMethods(t){let e=this.builtinMethodCache_.get(t);if(e)return e;const s=this.cppRegistry_,n=s[`add${t}`],i=s[`get${t}`],r=s[`has${t}`],o=s[`remove${t}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${t}". Expected: add${t}, get${t}, has${t}, remove${t}`);return e={add:n.bind(s),get:i.bind(s),has:r.bind(s),remove:o.bind(s)},this.builtinMethodCache_.set(t,e),e}insertBuiltin(t,e,s){const n=e._default,i={};if(null!=s&&"object"==typeof s){for(const[t,e]of Object.entries(s))void 0!==e&&t in n&&(i[t]=e);const t=Ct(e._name,n,i);if(t.length>0)throw new Error(St(e._name,t))}const r={...e._default,...i};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(e._cppName);o=!s.has(t),s.add(t,Ft(r,e._colorKeys))}catch(s){Tt(s,`insertBuiltin(${e._name}, entity=${t})`)}let a=this.builtinEntitySets_.get(e._cppName);a||(a=new Set,this.builtinEntitySets_.set(e._cppName,a));const c=a.has(t);return!o&&c||(c||a.add(t),this.worldVersion_++,this.recordAddedTick_(e,t)),this.recordChangedTick_(e,t),r}getBuiltin(t,e){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return Mt(this.getBuiltinMethods(e._cppName).get(t),e._colorKeys)}catch(s){return Tt(s,`getBuiltin(${e._name}, entity=${t})`),{...e._default}}}hasBuiltin(t,e){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(e._cppName).has(t)}catch(s){return Tt(s,`hasBuiltin(${e._name}, entity=${t})`),!1}}removeBuiltin(t,e){if(this.cppRegistry_){try{this.getBuiltinMethods(e._cppName).remove(t)}catch(s){Tt(s,`removeBuiltin(${e._name}, entity=${t})`)}this.recordRemovedTick_(e,t),this.worldVersion_++,this.builtinEntitySets_.get(e._cppName)?.delete(t)}}insertScript(t,e,s){let n;if(null!=s&&"object"==typeof s){const t={};for(const[e,n]of Object.entries(s))void 0!==n&&(t[e]=n);const i=Ct(e._name,e._default,t);if(i.length>0)throw new Error(St(e._name,i));n=t}const i=e.create(n),r=this.getStorage(e),o=!r.has(t);r.set(t,i);let a=this.entityComponents_.get(t);return a||(a=new Set,this.entityComponents_.set(t,a)),a.add(e._id),o&&(this.worldVersion_++,this.recordAddedTick_(e,t)),this.recordChangedTick_(e,t),i}getScript(t,e){const s=this.tsStorage_.get(e._id);if(!s)throw new Error(`Component not found: ${e._name}`);return s.get(t)}hasScript(t,e){const s=this.tsStorage_.get(e._id);return s?.has(t)??!1}removeScript(t,e){const s=this.tsStorage_.get(e._id);s?.delete(t),this.recordRemovedTick_(e,t),this.worldVersion_++;const n=this.entityComponents_.get(t);n&&n.delete(e._id)}getStorage(t){let e=this.tsStorage_.get(t._id);return e||(e=new Map,this.tsStorage_.set(t._id,e)),e}resolveGetter(t){if(q(t)){if(!this.cppRegistry_)return null;if(this.module_){const e=this.resolvePtrGetter_(t._cppName);if(e)return e}const e=this.getBuiltinMethods(t._cppName),s=t._colorKeys;return 0===s.length?t=>e.get(t):t=>Mt(e.get(t),s)}const e=this.tsStorage_.get(t._id);return e?t=>e.get(t):null}resolveHas(t){if(q(t)){if(!this.cppRegistry_)return null;const e=this.getBuiltinMethods(t._cppName);return t=>e.has(t)}const e=this.tsStorage_.get(t._id);return e?t=>e.has(t):null}resolveSetter(t){if(q(t)){if(!this.cppRegistry_)return null;if(this.module_){const e=this.resolvePtrSetter_(t._cppName);if(e)return e}const e=this.getBuiltinMethods(t._cppName),s=t._colorKeys;return 0===s.length?(t,s)=>e.add(t,s):(t,n)=>e.add(t,Ft(n,s))}const e=this.tsStorage_.get(t._id);return e?(t,s)=>e.set(t,s):null}resolvePtrFn_(t){const e=Bt[t];if(!e)return null;const s=this.module_[e.ptrFn];if(!s)return null;const n=this.cppRegistry_;return t=>s(n,t)}resolvePtrSetter_(t){const e=Bt[t];if(!e)return null;const s=this.resolvePtrFn_(t);if(!s)return null;const n=this.module_,i=e.fields;return(t,e)=>{const r=s(t);if(!r)return;const o=e;for(let t=0;t<i.length;t++)Pt(n.HEAPF32,n.HEAPU32,n.HEAPU8,r,i[t],o[i[t].name])}}resolvePtrGetter_(t){const e=Bt[t];if(!e)return null;const s=this.resolvePtrFn_(t);if(!s)return null;const n=this.module_,i=e.fields,r=function(t){const e={};for(const s of t)switch(s.type){case"vec2":e[s.name]={x:0,y:0};break;case"vec3":e[s.name]={x:0,y:0,z:0};break;case"quat":e[s.name]={x:0,y:0,z:0,w:0};break;case"color":e[s.name]={r:0,g:0,b:0,a:0};break;default:e[s.name]=null}return e}(i);return t=>{const e=s(t);return e?(function(t,e,s,n,i,r){for(let o=0;o<i.length;o++){const a=i[o],c=n+a.offset,l=c>>2;switch(a.type){case"f32":r[a.name]=t[l];break;case"i32":r[a.name]=0|e[l];break;case"u32":r[a.name]=e[l];break;case"bool":r[a.name]=0!==s[c];break;case"u8":r[a.name]=s[c];break;case"vec2":{const e=r[a.name];e.x=t[l],e.y=t[l+1];break}case"vec3":{const e=r[a.name];e.x=t[l],e.y=t[l+1],e.z=t[l+2];break}case"quat":{const e=r[a.name];e.x=t[l],e.y=t[l+1],e.z=t[l+2],e.w=t[l+3];break}case"color":{const e=r[a.name];e.r=t[l],e.g=t[l+1],e.b=t[l+2],e.a=t[l+3];break}}}}(n.HEAPF32,n.HEAPU32,n.HEAPU8,e,i,r),r):null}}resetQueryPool(){}getComponentTypes(t){const e=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(t)&&e.add(s)}catch(t){console.warn(`[World] Component check failed for ${s}:`,t)}if(this.cppRegistry_)for(const[s,n]of W)if(q(n)&&!e.has(s))try{this.getBuiltinMethods(n._cppName).has(t)&&e.add(s)}catch(t){console.warn(`[World] Builtin check failed for ${s}:`,t)}const s=this.entityComponents_.get(t);if(s){const t=E();for(const n of s)for(const[s,i]of t)if(i._id===n){e.add(s);break}}return Array.from(e)}resolveStorages_(t,e,s){for(const n of t)if(q(n)){if(!this.cppRegistry_)return!1;s.push(this.getBuiltinMethods(n._cppName))}else{const t=this.tsStorage_.get(n._id);if(!t)return!1;e.push(t)}return!0}getEntitiesWithComponents(t,e=[],s=[],n){if(0===t.length&&0===e.length&&0===s.length)return this.getAllEntities();const i=n??It(t,e,s),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;const o=[],a=[],c=[];if(!this.resolveStorages_(t,a,c))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),o;let l=null,h=null;if(e.length>0&&(l=[],h=[],!this.resolveStorages_(e,l,h)))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),o;let u=null,d=null;s.length>0&&(u=[],d=[],this.resolveStorages_(s,u,d));let f=null,_=1/0;for(let t=0;t<a.length;t++){const e=a[t].size;e<_&&(_=e,f=a[t])}for(const e of t)if(q(e)){const t=this.builtinEntitySets_.get(e._cppName);t&&t.size<_&&(_=t.size,f=t)}const p=f?f.keys():this.entities_.keys(),m=a.length,y=c.length;for(const t of p){let e=!0;for(let s=0;s<m;s++)if(!a[s].has(t)){e=!1;break}if(e)for(let s=0;s<y;s++)if(!c[s].has(t)){e=!1;break}if(e&&l){for(let s=0;s<l.length;s++)if(!l[s].has(t)){e=!1;break}if(e)for(let s=0;s<h.length;s++)if(!h[s].has(t)){e=!1;break}}if(e&&u){for(let s=0;s<u.length;s++)if(u[s].has(t)){e=!1;break}if(e)for(let s=0;s<d.length;s++)if(d[s].has(t)){e=!1;break}}e&&o.push(t)}return this.queryCache_.set(i,{version:this.worldVersion_,result:o}),o}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}enableChangeTracking(t){this.trackedComponents_.add(t._id)}isAddedSince(t,e,s){const n=this.componentAddedTicks_.get(e._id);if(!n)return!1;const i=n.get(t);return void 0!==i&&i>s}isChangedSince(t,e,s){const n=this.componentChangedTicks_.get(e._id);if(!n)return!1;const i=n.get(t);return void 0!==i&&i>s}getRemovedEntitiesSince(t,e){const s=this.componentRemovedBuffer_.get(t._id);if(!s)return[];const n=[];for(const t of s)t.tick>e&&n.push(t.entity);return n}cleanRemovedBuffer(t){for(const[e,s]of this.componentRemovedBuffer_){let n=0;for(let e=0;e<s.length;e++)s[e].tick>=t&&(s[n++]=s[e]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(e)}}recordAddedTick_(t,e){if(!this.trackedComponents_.has(t._id))return;let s=this.componentAddedTicks_.get(t._id);s||(s=new Map,this.componentAddedTicks_.set(t._id,s)),s.set(e,this.worldTick_)}markChanged(t,e){this.recordChangedTick_(e,t)}recordChangedTick_(t,e){if(!this.trackedComponents_.has(t._id))return;let s=this.componentChangedTicks_.get(t._id);s||(s=new Map,this.componentChangedTicks_.set(t._id,s)),s.set(e,this.worldTick_)}recordRemovedTick_(t,e){if(!this.trackedComponents_.has(t._id))return;let s=this.componentRemovedBuffer_.get(t._id);s||(s=[],this.componentRemovedBuffer_.set(t._id,s)),s.push({entity:e,tick:this.worldTick_}),this.componentAddedTicks_.get(t._id)?.delete(e),this.componentChangedTicks_.get(t._id)?.delete(e)}}function Nt(t){return{_type:"mut",_component:t}}function qt(t){return"object"==typeof t&&null!==t&&"_type"in t&&"mut"===t._type}function Wt(t){return{_filterType:"added",_component:t}}function jt(t){return{_filterType:"changed",_component:t}}function Ot(t){return"object"==typeof t&&null!==t&&"_filterType"in t&&"added"===t._filterType}function Ut(t){return"object"==typeof t&&null!==t&&"_filterType"in t&&"changed"===t._filterType}function Vt(t){return qt(t)||Ot(t)||Ut(t)?t._component:t}function Ht(t,e=[],s=[]){const n=[],i=[],r=[];return t.forEach((t,e)=>{qt(t)&&n.push(e),Ot(t)?i.push({index:e,component:t._component}):Ut(t)&&r.push({index:e,component:t._component})}),{_type:"query",_components:t,_mutIndices:n,_with:e,_without:s,_addedFilters:i,_changedFilters:r,with:(...n)=>Ht(t,[...e,...n],s),without:(...n)=>Ht(t,e,[...s,...n])}}function Lt(...t){return Ht(t)}class Kt{constructor(t,e,s=-1){this.world_=t,this.descriptor_=e,this.lastRunTick_=s,this.actualComponents_=e._components.map(Vt),this.allRequired_=this.actualComponents_.concat(e._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=e._mutIndices.map(t=>({component:this.actualComponents_[t],data:null})),this.cacheKey_=It(this.allRequired_,e._with,e._without),this.getters_=this.actualComponents_.map(e=>t.resolveGetter(e)),this.mutSetters_=e._mutIndices.map(e=>t.resolveSetter(this.actualComponents_[e])),this.mutIsBuiltin_=e._mutIndices.map(t=>q(this.actualComponents_[t]));for(const s of e._addedFilters)t.enableChangeTracking(s.component);for(const s of e._changedFilters)t.enableChangeTracking(s.component)}resetTick(t){this.lastRunTick_=t}passesChangeFilters_(t){const{_addedFilters:e,_changedFilters:s}=this.descriptor_;if(0===e.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of e)if(!this.world_.isAddedSince(t,s.component,n))return!1;for(const e of s)if(!this.world_.isChangedSince(t,e.component,n))return!1;return!0}[Symbol.iterator](){const{_mutIndices:t}=this.descriptor_,e=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=e.length,i=t.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,c=a.length,l=this.mutSetters_,h=this.world_,u=this.getters_,d=this;let f=0,_=null,p=!1,m=!1;const y=this.mutIsBuiltin_,g=()=>{for(let t=0;t<c;t++){const e=a[t];if(y[t]){const s=l[t];s?s(_,e.data):h.set(_,e.component,e.data)}else h.markChanged(_,e.component)}},w=()=>{m||(m=!0,h.endIteration(),null!==_&&i&&g())},v={value:o,done:!1},b={value:void 0,done:!0};return{next(){for(p||(p=!0,h.beginIteration());f<s.length;){const l=s[f++];if(!r||d.passesChangeFilters_(l)){null!==_&&i&&g(),o[0]=l;for(let t=0;t<n;t++){const s=u[t];o[t+1]=s?s(l):h.get(l,e[t])}if(i){for(let e=0;e<c;e++)a[e].data=o[t[e]+1];_=l}return v}}return w(),b},return:()=>(w(),b)}}forEach(t){const{_mutIndices:e}=this.descriptor_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=this.actualComponents_.length,i=e.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,c=a.length,l=this.mutSetters_,h=this.world_,u=this.getters_,d=this.actualComponents_;h.beginIteration();let f=null;for(let _=0;_<s.length;_++){const p=s[_];if(!r||this.passesChangeFilters_(p)){if(null!==f&&i)for(let t=0;t<c;t++){const e=a[t];if(this.mutIsBuiltin_[t]){const s=l[t];s?s(f,e.data):h.set(f,e.component,e.data)}else h.markChanged(f,e.component)}o[0]=p;for(let t=0;t<n;t++){const e=u[t];o[t+1]=e?e(p):h.get(p,d[t])}if(i){for(let t=0;t<c;t++)a[t].data=o[e[t]+1];f=p}switch(n){case 1:t(p,o[1]);break;case 2:t(p,o[1],o[2]);break;case 3:t(p,o[1],o[2],o[3]);break;default:t.apply(null,o)}}}if(null!==f&&i)for(let t=0;t<c;t++){const e=a[t];if(this.mutIsBuiltin_[t]){const s=l[t];s?s(f,e.data):h.set(f,e.component,e.data)}else h.markChanged(f,e.component)}h.endIteration()}single(){for(const t of this)return t;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const t=[];for(const e of this)t.push([...e]);return t}}function Gt(t){return{_type:"removed",_component:t}}class Xt{constructor(t,e,s){this.world_=t,this.component_=e,this.lastRunTick_=s,t.enableChangeTracking(e)}resetTick(t){this.lastRunTick_=t}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function Yt(){return{_type:"commands"}}class Jt{constructor(t,e){this.components_=[],this.commands_=t,null===e?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:e},this.isNew_=!1)}insert(t,e){let s;return s=q(t)?{...t._default,...e}:t.create(e),this.isNew_?this.components_.push({component:t,data:s}):this.commands_.queueInsert(this.entityRef_.entity,t,s),this}remove(t){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,t),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 Qt{constructor(t,e){this.pending_=[],this.spawned_=[],this.world_=t,this.resources_=e}spawn(){const t=new Jt(this,null);return this.spawned_.push(t),t}entity(t){return new Jt(this,t)}despawn(t){return this.pending_.push({type:"despawn",entity:t}),this}insertResource(t,e){return this.pending_.push({type:"insert_resource",resource:t,value:e}),this}queueInsert(t,e,s){this.pending_.push({type:"insert",entity:t,component:e,data:s})}queueRemove(t,e){this.pending_.push({type:"remove",entity:t,component:e})}spawnImmediate(t,e){const s=this.world_.spawn();e.entity=s;for(const e of t)this.world_.insert(s,e.component,e.data)}flush(){for(const t of this.spawned_)t.finalize();this.spawned_.length=0;for(const t of this.pending_)this.executeCommand(t);this.pending_.length=0}executeCommand(t){switch(t.type){case"despawn":if(!this.world_.valid(t.entity)){console.warn(`[Commands] despawn skipped: entity ${t.entity} is already invalid`);break}this.world_.despawn(t.entity);break;case"insert":if(!this.world_.valid(t.entity)){console.warn(`[Commands] insert skipped: entity ${t.entity} is invalid`);break}this.world_.insert(t.entity,t.component,t.data);break;case"remove":if(!this.world_.valid(t.entity)){console.warn(`[Commands] remove skipped: entity ${t.entity} is invalid`);break}this.world_.remove(t.entity,t.component);break;case"insert_resource":this.resources_.insert(t.resource,t.value)}}}function Zt(t){return{_id:Symbol(`Event_${t}`),_name:t}}class te{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(t){this.writeBuffer_.push(t)}getReadBuffer(){return this.readBuffer_}swap(){const t=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=t,this.writeBuffer_.length=0}}class ee{constructor(){this.buses_=new Map}register(t){this.buses_.has(t._id)||this.buses_.set(t._id,new te)}getBus(t){let e=this.buses_.get(t._id);return e||(e=new te,this.buses_.set(t._id,e)),e}swapAll(){for(const t of this.buses_.values())t.swap()}}function se(t){return{_type:"event_writer",_event:t}}function ne(t){return{_type:"event_reader",_event:t}}class ie{constructor(t){this.bus_=t}send(t){this.bus_.send(t)}}class re{constructor(t){this.bus_=t}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var oe;function ae(){return{_type:"get_world"}}!function(t){t[t.Startup=0]="Startup",t[t.First=1]="First",t[t.PreUpdate=2]="PreUpdate",t[t.Update=3]="Update",t[t.PostUpdate=4]="PostUpdate",t[t.Last=5]="Last",t[t.FixedPreUpdate=10]="FixedPreUpdate",t[t.FixedUpdate=11]="FixedUpdate",t[t.FixedPostUpdate=12]="FixedPostUpdate"}(oe||(oe={}));let ce=0;function le(t,e,s){const n=++ce;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:t,_fn:e,_name:s?.name??`System_${n}`}}function he(){const t=globalThis;return t.__esengine_pendingSystems??(t.__esengine_pendingSystems=[])}function ue(t){he().push({schedule:oe.Update,system:t})}function de(t){he().push({schedule:oe.Startup,system:t})}function fe(t,e){he().push({schedule:t,system:e})}class _e{constructor(t,e,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.queryCache_=new Map,this.removedCache_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=t,this.resources_=e,this.eventRegistry_=s??null}setTimingEnabled(t){this.timings_=t?new Map:null}getTimings(){return this.timings_}run(t){let e=this.argsCache_.get(t._id);e||(e=new Array(t._params.length),this.argsCache_.set(t._id,e)),this.currentLastRunTick_=this.systemTicks_.get(t._id)??-1;let s=this.queryCache_.get(t._id),n=this.removedCache_.get(t._id);const i=!s;i&&(s=[],n=[],this.queryCache_.set(t._id,s),this.removedCache_.set(t._id,n));let r=0,o=0;for(let a=0;a<t._params.length;a++){const c=t._params[a];if("query"===c._type){if(i){const t=new Kt(this.world_,c,this.currentLastRunTick_);s.push(t),e[a]=t}else{const t=s[r];t.resetTick(this.currentLastRunTick_),e[a]=t}r++}else if("removed"===c._type){if(i){const t=c,s=new Xt(this.world_,t._component,this.currentLastRunTick_);n.push(s),e[a]=s}else{const t=n[o];t.resetTick(this.currentLastRunTick_),e[a]=t}o++}else e[a]=this.resolveParam(c)}const a=this.timings_?performance.now():0;let c;try{c=t._fn(...e)}catch(s){throw this.flushSystem_(t,e,a),s}if(c instanceof Promise)return c.then(()=>{this.flushSystem_(t,e,a)},s=>{throw this.flushSystem_(t,e,a),s});this.flushSystem_(t,e,a)}flushSystem_(t,e,s){for(let t=0;t<e.length;t++)e[t]instanceof Qt&&e[t].flush();this.timings_&&this.timings_.set(t._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(t._id,this.world_.getWorldTick())}resolveParam(t){switch(t._type){case"res":return this.resources_.get(t._resource);case"res_mut":return this.resources_.getResMut(t._resource);case"commands":return new Qt(this.world_,this.resources_);case"event_writer":{const e=t,s=this.eventRegistry_?this.eventRegistry_.getBus(e._event):(()=>{throw new Error("EventRegistry not available")})();return new ie(s)}case"event_reader":{const e=t,s=this.eventRegistry_?this.eventRegistry_.getBus(e._event):(()=>{throw new Error("EventRegistry not available")})();return new re(s)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}export{n as $,L as A,rt as B,tt as C,u as D,ee as E,t as F,e as G,ae as H,y as I,Wt as J,jt as K,Yt as L,Qt as M,ut as N,l as O,ft as P,Lt as Q,f as R,oe as S,X as T,r as U,o as V,J as W,a as X,c as Y,d as Z,i as _,le as a,at as a0,Jt as a1,ne as a2,re as a3,se as a4,ie as a5,w as a6,v as a7,Y as a8,Nt as a9,k as aA,lt as aa,ht as ab,Kt as ac,Gt as ad,Xt as ae,Z as af,G as ag,ct as ah,st as ai,de as aj,ue as ak,fe as al,m as am,_ as an,I as ao,S as ap,Zt as aq,z as ar,_t as as,A as at,q as au,x as av,T as aw,D as ax,b as ay,C as az,$ as b,Q as c,mt as d,yt as e,bt as f,O as g,ot as h,M as i,Tt as j,V as k,dt as l,gt as m,Dt as n,vt as o,_e as p,H as q,K as r,Rt as s,g as t,nt as u,j as v,it as w,h as x,et as y,s as z};+const t=1920,e=1080,s=100,n=512,i={x:100,y:100},r="Arial",o=24,a=1.2,c=.5,l=1/60,h={x:0,y:-9.81},u=1/60,d="default",f={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};function _(t){t.Text&&(t.Text._default.fontFamily=f.defaultFontFamily),t.TextInput&&(t.TextInput._default.fontFamily=f.defaultFontFamily),t.Canvas&&(t.Canvas._default.scaleMode=f.canvasScaleMode,t.Canvas._default.matchWidthOrHeight=f.canvasMatchWidthOrHeight)}const p={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function m(t,e){if(void 0!==e.maxDeltaTime&&(f.maxDeltaTime=e.maxDeltaTime,t.setMaxDeltaTime(e.maxDeltaTime)),void 0!==e.maxFixedSteps&&(f.maxFixedSteps=e.maxFixedSteps,t.setMaxFixedSteps(e.maxFixedSteps)),void 0!==e.textCanvasSize&&(f.textCanvasSize=e.textCanvasSize),void 0!==e.defaultFontFamily&&(f.defaultFontFamily=e.defaultFontFamily),void 0!==e.sceneTransitionDuration&&(f.sceneTransitionDuration=e.sceneTransitionDuration),e.sceneTransitionColor){const t=e.sceneTransitionColor.replace("#","");f.sceneTransitionColor={r:parseInt(t.substring(0,2),16)/255,g:parseInt(t.substring(2,4),16)/255,b:parseInt(t.substring(4,6),16)/255,a:1}}void 0!==e.canvasScaleMode&&(f.canvasScaleMode=p[e.canvasScaleMode]??1),void 0!==e.canvasMatchWidthOrHeight&&(f.canvasMatchWidthOrHeight=e.canvasMatchWidthOrHeight),void 0!==e.assetLoadTimeout&&(f.assetLoadTimeout=e.assetLoadTimeout),void 0!==e.assetFailureCooldown&&(f.assetFailureCooldown=e.assetFailureCooldown)}const y=0,g=4294967295,w=4294967295,v=0,b=(t=0,e=0)=>({x:t,y:e}),C=(t=0,e=0,s=0)=>({x:t,y:e,z:s}),k=(t=0,e=0,s=0,n=1)=>({x:t,y:e,z:s,w:n}),S=(t=1,e=1,s=1,n=1)=>({r:t,g:e,b:s,a:n}),x=(t=1,e=0,s=0,n=0)=>({w:t,x:e,y:s,z:n}),R=new Map;function T(t,e){R.set(t,e)}function M(t){return R.get(t)}function F(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(F);const e={};for(const s in t)e[s]=F(t[s]);return e}let B=0;function P(t,e){const s=++B,n=function(t){const e=[],s=[],n=[];let i=!1;for(const r in t){const o=t[r];null!==o&&"object"==typeof o?(i=!0,Array.isArray(o)?n.push(r):s.push(r)):e.push(r)}return i?{flatKeys:e,objectKeys:s,arrayKeys:n}:null}(e),i=e;return{_id:Symbol(`Component_${s}_${t}`),_name:t,_default:e,_builtin:!1,create(t){if(n){const e={...i};for(const t of n.objectKeys)e[t]={...i[t]};for(const t of n.arrayKeys)e[t]=i[t].slice();return t&&Object.assign(e,t),e}return t?{...e,...t}:{...e}}}}function E(){const t=globalThis;return t.__esengine_componentRegistry??(t.__esengine_componentRegistry=new Map)}function $(t,e,s){const n=W.get(t)??E().get(t);if(n)return n;const i=P(t,e);return E().set(t,i),W.set(t,i),N(t,e,!1),s?.entityFields&&T(t,s.entityFields),i}function z(t){const e=W.get(t)??E().get(t);if(e)return e;const s=P(t,{});return E().set(t,s),W.set(t,s),N(t,{},!0),s}function A(t){return E().get(t)}function I(){const t=E();for(const e of t.keys())W.delete(e);t.clear()}function D(t){E().delete(t),W.delete(t)}function N(t,e,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(t,e,s)}function q(t){return!0===t._builtin}const W=new Map;function j(t,e){W.set(t,e)}function O(t){return W.get(t)??A(t)}function U(t){if(null===t||"object"!=typeof t)return[];const e=[];for(const s of Object.keys(t)){const n=t[s];if(null!==n&&"object"==typeof n&&!Array.isArray(n)){"r"in n&&"g"in n&&"b"in n&&"a"in n&&e.push(s)}}return e}function V(t,e,s){const n={_id:Symbol(`Builtin_${t}`),_name:t,_cppName:t,_builtin:!0,_default:e,_colorKeys:U(e)};return W.set(t,n),n}const H={Perspective:0,Orthographic:1},L={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},K={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},G={Circle:0,Capsule:1,RoundedRect:2},X=V("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),Y=X,J=X,Q=V("Sprite",{texture:g,color:{r:1,g:1,b:1,a:1},size:{x:i.x,y:i.y},pivot:{x:.5,y:.5},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Z=V("ShapeRenderer",{shapeType:G.Circle,color:{r:1,g:1,b:1,a:1},size:{x:100,y:100},cornerRadius:0,layer:0,enabled:!0}),tt=V("Camera",{projectionType:H.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:L.ColorAndDepth}),et=V("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:K.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),st=V("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),nt=V("Parent",{entity:0}),it=V("Children",{entities:[]}),rt=V("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:w,enabled:!0}),ot=V("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,enabled:!0}),at={Point:0,Circle:1,Rectangle:2,Cone:3},ct={World:0,Local:1},lt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},ht=V("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:at.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:lt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:lt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:g,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:ct.World,enabled:!0}),ut=$("Name",{value:""}),dt=$("SceneOwner",{scene:"",persistent:!1}),ft=$("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function _t(t){const e=O(t);return e?F(e._default):null}let pt=0;function mt(t,e){const s=++pt;return{_id:Symbol(`Resource_${s}_${e??""}`),_name:e??`Resource_${s}`,_default:t}}function yt(t){return{_type:"res",_resource:t}}function gt(t){return{_type:"res_mut",_resource:t}}class wt{constructor(t,e){this.value_=t,this.setter_=e}get(){return this.value_}set(t){this.value_=t,this.setter_(t)}modify(t){t(this.value_),this.setter_(this.value_)}updateValue(t){this.value_=t}}class vt{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(t,e){this.resources_.set(t._id,e)}get(t){return this.resources_.has(t._id)||this.resources_.set(t._id,t._default),this.resources_.get(t._id)}set(t,e){this.resources_.set(t._id,e)}has(t){return this.resources_.has(t._id)}remove(t){this.resources_.delete(t._id),this.resMutPool_.delete(t._id)}getResMut(t){let e=this.resMutPool_.get(t._id);return e?(e.updateValue(this.get(t)),e):(e=new wt(this.get(t),e=>this.set(t,e)),this.resMutPool_.set(t._id,e),e)}}const bt=mt({delta:0,elapsed:0,frameCount:0},"Time");function Ct(t,e,s){const n=[];for(const[t,i]of Object.entries(s)){if(!(t in e)){n.push({field:t,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=kt(e[t]),r=kt(i);"null"!==s&&"undefined"!==s&&(s!==r&&null!=i&&n.push({field:t,expected:s,actual:r,value:i}))}return n}function kt(t){return null===t?"null":void 0===t?"undefined":Array.isArray(t)?"array":typeof t}function St(t,e){const s=[`Invalid component data for "${t}":`];for(const t of e)s.push(` - Field "${t.field}": expected ${t.expected}, got ${t.actual} (${JSON.stringify(t.value)})`);return s.join("\n")}let xt=null;function Rt(t){xt=t}function Tt(t,e){console.error(`[ESEngine] WASM error in ${e}:`,t),xt&&xt(t,e)}function Mt(t,e){if(0===e.length)return t;const s={...t};for(const t of e){const e=s[t];e&&"object"==typeof e&&(s[t]={r:e.x,g:e.y,b:e.z,a:e.w})}return s}function Ft(t,e){if(0===e.length)return t;const s={...t};for(const t of e){const e=s[t];e&&"object"==typeof e&&(s[t]={x:e.r,y:e.g,z:e.b,w:e.a})}return s}const Bt={Transform:{ptrFn:"getTransformPtr",fields:[{name:"position",type:"vec3",offset:0},{name:"rotation",type:"quat",offset:12},{name:"scale",type:"vec3",offset:28},{name:"worldPosition",type:"vec3",offset:40},{name:"worldRotation",type:"quat",offset:52},{name:"worldScale",type:"vec3",offset:68}]},Sprite:{ptrFn:"getSpritePtr",fields:[{name:"texture",type:"u32",offset:0},{name:"color",type:"color",offset:4},{name:"size",type:"vec2",offset:20},{name:"uvOffset",type:"vec2",offset:28},{name:"uvScale",type:"vec2",offset:36},{name:"layer",type:"i32",offset:44},{name:"flipX",type:"bool",offset:48},{name:"flipY",type:"bool",offset:49},{name:"material",type:"u32",offset:52},{name:"enabled",type:"bool",offset:56}]},Velocity:{ptrFn:"getVelocityPtr",fields:[{name:"linear",type:"vec3",offset:0},{name:"angular",type:"vec3",offset:12}]},Camera:{ptrFn:"getCameraPtr",fields:[{name:"projectionType",type:"u8",offset:0},{name:"fov",type:"f32",offset:4},{name:"orthoSize",type:"f32",offset:8},{name:"nearPlane",type:"f32",offset:12},{name:"farPlane",type:"f32",offset:16},{name:"aspectRatio",type:"f32",offset:20},{name:"isActive",type:"bool",offset:24},{name:"priority",type:"i32",offset:28},{name:"viewportX",type:"f32",offset:32},{name:"viewportY",type:"f32",offset:36},{name:"viewportW",type:"f32",offset:40},{name:"viewportH",type:"f32",offset:44},{name:"clearFlags",type:"i32",offset:48}]},UIRect:{ptrFn:"getUIRectPtr",fields:[{name:"anchorMin",type:"vec2",offset:0},{name:"anchorMax",type:"vec2",offset:8},{name:"offsetMin",type:"vec2",offset:16},{name:"offsetMax",type:"vec2",offset:24},{name:"size",type:"vec2",offset:32},{name:"pivot",type:"vec2",offset:40}]},RigidBody:{ptrFn:"getRigidBodyPtr",fields:[{name:"bodyType",type:"u8",offset:0},{name:"gravityScale",type:"f32",offset:4},{name:"linearDamping",type:"f32",offset:8},{name:"angularDamping",type:"f32",offset:12},{name:"fixedRotation",type:"bool",offset:16},{name:"bullet",type:"bool",offset:17},{name:"enabled",type:"bool",offset:18}]},BoxCollider:{ptrFn:"getBoxColliderPtr",fields:[{name:"halfExtents",type:"vec2",offset:0},{name:"offset",type:"vec2",offset:8},{name:"density",type:"f32",offset:16},{name:"friction",type:"f32",offset:20},{name:"restitution",type:"f32",offset:24},{name:"isSensor",type:"bool",offset:28},{name:"enabled",type:"bool",offset:29},{name:"categoryBits",type:"u32",offset:32},{name:"maskBits",type:"u32",offset:36}]},CircleCollider:{ptrFn:"getCircleColliderPtr",fields:[{name:"radius",type:"f32",offset:0},{name:"offset",type:"vec2",offset:4},{name:"density",type:"f32",offset:12},{name:"friction",type:"f32",offset:16},{name:"restitution",type:"f32",offset:20},{name:"isSensor",type:"bool",offset:24},{name:"enabled",type:"bool",offset:25},{name:"categoryBits",type:"u32",offset:28},{name:"maskBits",type:"u32",offset:32}]}};function Pt(t,e,s,n,i,r){const o=n+i.offset,a=o>>2;switch(i.type){case"f32":t[a]=r;break;case"i32":e[a]=0|r;break;case"u32":e[a]=r;break;case"bool":s[o]=r?1:0;break;case"u8":s[o]=r;break;case"vec2":t[a]=r.x,t[a+1]=r.y;break;case"vec3":t[a]=r.x,t[a+1]=r.y,t[a+2]=r.z;break;case"quat":t[a]=r.x,t[a+1]=r.y,t[a+2]=r.z,t[a+3]=r.w;break;case"color":t[a]=r.r,t[a+1]=r.g,t[a+2]=r.b,t[a+3]=r.a}}let Et=1;const $t=new WeakMap;function zt(t){let e=$t.get(t);return void 0===e&&(e=Et++,$t.set(t,e)),e}const At=[];function It(t,e=[],s=[]){At.length=0;for(const e of t)At.push(zt(e));At.sort((t,e)=>t-e);let n=At.join(",");if(e.length>0){At.length=0;for(const t of e)At.push(zt(t));At.sort((t,e)=>t-e),n+="|+"+At.join(",")}if(s.length>0){At.length=0;for(const t of s)At.push(zt(t));At.sort((t,e)=>t-e),n+="|-"+At.join(",")}return n}class Dt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.builtinEntitySets_=new Map,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map,this.trackedComponents_=new Set}connectCpp(t,e){this.cppRegistry_=t,this.module_=e??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}getWasmModule(){return this.module_}spawn(t){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(t){throw Tt(t,"spawn"),t}else e=++this.nextEntityId_;let s=0;if(this.module_&&this.cppRegistry_)try{s=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else s=++this.nextGeneration_;this.entities_.set(e,s),this.worldVersion_++,void 0!==t&&this.insert(e,ut,{value:t});for(const t of this.spawnCallbacks_)try{t(e)}catch(t){console.warn("[World] Spawn callback error:",t)}return e}despawn(t){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const e of this.despawnCallbacks_)try{e(t)}catch(t){console.warn("[World] Despawn callback error:",t)}if(this.cppRegistry_)try{this.cppRegistry_.destroy(t)}catch(e){Tt(e,`despawn(entity=${t})`)}this.entities_.delete(t),this.worldVersion_++;for(const[,e]of this.builtinEntitySets_)e.delete(t);const e=this.entityComponents_.get(t);if(e){for(const s of e){this.tsStorage_.get(s)?.delete(t),this.componentAddedTicks_.get(s)?.delete(t),this.componentChangedTicks_.get(s)?.delete(t);let e=this.componentRemovedBuffer_.get(s);e||(e=[],this.componentRemovedBuffer_.set(s,e)),e.push({entity:t,tick:this.worldTick_})}this.entityComponents_.delete(t)}}onSpawn(t){return this.spawnCallbacks_.push(t),()=>{const e=this.spawnCallbacks_.indexOf(t);-1!==e&&this.spawnCallbacks_.splice(e,1)}}onDespawn(t){return this.despawnCallbacks_.push(t),()=>{const e=this.despawnCallbacks_.indexOf(t);-1!==e&&this.despawnCallbacks_.splice(e,1)}}valid(t){return this.entities_.has(t)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(t,e){if(this.cppRegistry_)try{this.cppRegistry_.setParent(t,e)}catch(s){Tt(s,`setParent(child=${t}, parent=${e})`)}}removeParent(t){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(t)}catch(e){Tt(e,`removeParent(entity=${t})`)}}insert(t,e,s){return q(e)?this.insertBuiltin(t,e,s):this.insertScript(t,e,s)}set(t,e,s){if(q(e)){if(this.cppRegistry_)try{const n=e._default,i=s;let r=i;for(const t of Object.keys(i))t in n||(r===i&&(r={...i}),delete r[t]);this.getBuiltinMethods(e._cppName).add(t,Ft(r,e._colorKeys))}catch(s){Tt(s,`set(${e._name}, entity=${t})`)}this.recordChangedTick_(e,t)}else this.getStorage(e).set(t,s),this.recordChangedTick_(e,t)}get(t,e){return q(e)?this.getBuiltin(t,e):this.getScript(t,e)}has(t,e){if(e._builtin){if(!this.cppRegistry_)return!1;const s=e._cppName,n=this.builtinEntitySets_.get(s);return n?n.has(t):this.getBuiltinMethods(s).has(t)}return this.hasScript(t,e)}tryGet(t,e){if(q(e)){if(!this.cppRegistry_)return null;const s=this.builtinEntitySets_.get(e._cppName);if(s&&!s.has(t))return null;try{const n=this.getBuiltinMethods(e._cppName);return s||n.has(t)?Mt(n.get(t),e._colorKeys):null}catch(s){return Tt(s,`tryGet(${e._name}, entity=${t})`),null}}const s=this.tsStorage_.get(e._id);if(!s)return null;const n=s.get(t);return void 0!==n?n:null}remove(t,e){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");q(e)?this.removeBuiltin(t,e):this.removeScript(t,e)}getBuiltinMethods(t){let e=this.builtinMethodCache_.get(t);if(e)return e;const s=this.cppRegistry_,n=s[`add${t}`],i=s[`get${t}`],r=s[`has${t}`],o=s[`remove${t}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${t}". Expected: add${t}, get${t}, has${t}, remove${t}`);return e={add:n.bind(s),get:i.bind(s),has:r.bind(s),remove:o.bind(s)},this.builtinMethodCache_.set(t,e),e}insertBuiltin(t,e,s){const n=e._default,i={};if(null!=s&&"object"==typeof s){for(const[t,e]of Object.entries(s))void 0!==e&&t in n&&(i[t]=e);const t=Ct(e._name,n,i);if(t.length>0)throw new Error(St(e._name,t))}const r={...e._default,...i};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(e._cppName);o=!s.has(t),s.add(t,Ft(r,e._colorKeys))}catch(s){Tt(s,`insertBuiltin(${e._name}, entity=${t})`)}let a=this.builtinEntitySets_.get(e._cppName);a||(a=new Set,this.builtinEntitySets_.set(e._cppName,a));const c=a.has(t);return!o&&c||(c||a.add(t),this.worldVersion_++,this.recordAddedTick_(e,t)),this.recordChangedTick_(e,t),r}getBuiltin(t,e){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return Mt(this.getBuiltinMethods(e._cppName).get(t),e._colorKeys)}catch(s){return Tt(s,`getBuiltin(${e._name}, entity=${t})`),{...e._default}}}hasBuiltin(t,e){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(e._cppName).has(t)}catch(s){return Tt(s,`hasBuiltin(${e._name}, entity=${t})`),!1}}removeBuiltin(t,e){if(this.cppRegistry_){try{this.getBuiltinMethods(e._cppName).remove(t)}catch(s){Tt(s,`removeBuiltin(${e._name}, entity=${t})`)}this.recordRemovedTick_(e,t),this.worldVersion_++,this.builtinEntitySets_.get(e._cppName)?.delete(t)}}insertScript(t,e,s){let n;if(null!=s&&"object"==typeof s){const t={};for(const[e,n]of Object.entries(s))void 0!==n&&(t[e]=n);const i=Ct(e._name,e._default,t);if(i.length>0)throw new Error(St(e._name,i));n=t}const i=e.create(n),r=this.getStorage(e),o=!r.has(t);r.set(t,i);let a=this.entityComponents_.get(t);return a||(a=new Set,this.entityComponents_.set(t,a)),a.add(e._id),o&&(this.worldVersion_++,this.recordAddedTick_(e,t)),this.recordChangedTick_(e,t),i}getScript(t,e){const s=this.tsStorage_.get(e._id);if(!s)throw new Error(`Component not found: ${e._name}`);return s.get(t)}hasScript(t,e){const s=this.tsStorage_.get(e._id);return s?.has(t)??!1}removeScript(t,e){const s=this.tsStorage_.get(e._id);s?.delete(t),this.recordRemovedTick_(e,t),this.worldVersion_++;const n=this.entityComponents_.get(t);n&&n.delete(e._id)}getStorage(t){let e=this.tsStorage_.get(t._id);return e||(e=new Map,this.tsStorage_.set(t._id,e)),e}resolveGetter(t){if(q(t)){if(!this.cppRegistry_)return null;if(this.module_){const e=this.resolvePtrGetter_(t._cppName);if(e)return e}const e=this.getBuiltinMethods(t._cppName),s=t._colorKeys;return 0===s.length?t=>e.get(t):t=>Mt(e.get(t),s)}const e=this.tsStorage_.get(t._id);return e?t=>e.get(t):null}resolveHas(t){if(q(t)){if(!this.cppRegistry_)return null;const e=this.getBuiltinMethods(t._cppName);return t=>e.has(t)}const e=this.tsStorage_.get(t._id);return e?t=>e.has(t):null}resolveSetter(t){if(q(t)){if(!this.cppRegistry_)return null;if(this.module_){const e=this.resolvePtrSetter_(t._cppName);if(e)return e}const e=this.getBuiltinMethods(t._cppName),s=t._colorKeys;return 0===s.length?(t,s)=>e.add(t,s):(t,n)=>e.add(t,Ft(n,s))}const e=this.tsStorage_.get(t._id);return e?(t,s)=>e.set(t,s):null}resolvePtrFn_(t){const e=Bt[t];if(!e)return null;const s=this.module_[e.ptrFn];if(!s)return null;const n=this.cppRegistry_;return t=>s(n,t)}resolvePtrSetter_(t){const e=Bt[t];if(!e)return null;const s=this.resolvePtrFn_(t);if(!s)return null;const n=this.module_,i=e.fields;return(t,e)=>{const r=s(t);if(!r)return;const o=e;for(let t=0;t<i.length;t++)Pt(n.HEAPF32,n.HEAPU32,n.HEAPU8,r,i[t],o[i[t].name])}}resolvePtrGetter_(t){const e=Bt[t];if(!e)return null;const s=this.resolvePtrFn_(t);if(!s)return null;const n=this.module_,i=e.fields,r=function(t){const e={};for(const s of t)switch(s.type){case"vec2":e[s.name]={x:0,y:0};break;case"vec3":e[s.name]={x:0,y:0,z:0};break;case"quat":e[s.name]={x:0,y:0,z:0,w:0};break;case"color":e[s.name]={r:0,g:0,b:0,a:0};break;default:e[s.name]=null}return e}(i);return t=>{const e=s(t);return e?(function(t,e,s,n,i,r){for(let o=0;o<i.length;o++){const a=i[o],c=n+a.offset,l=c>>2;switch(a.type){case"f32":r[a.name]=t[l];break;case"i32":r[a.name]=0|e[l];break;case"u32":r[a.name]=e[l];break;case"bool":r[a.name]=0!==s[c];break;case"u8":r[a.name]=s[c];break;case"vec2":{const e=r[a.name];e.x=t[l],e.y=t[l+1];break}case"vec3":{const e=r[a.name];e.x=t[l],e.y=t[l+1],e.z=t[l+2];break}case"quat":{const e=r[a.name];e.x=t[l],e.y=t[l+1],e.z=t[l+2],e.w=t[l+3];break}case"color":{const e=r[a.name];e.r=t[l],e.g=t[l+1],e.b=t[l+2],e.a=t[l+3];break}}}}(n.HEAPF32,n.HEAPU32,n.HEAPU8,e,i,r),r):null}}resetQueryPool(){}getComponentTypes(t){const e=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(t)&&e.add(s)}catch(t){console.warn(`[World] Component check failed for ${s}:`,t)}if(this.cppRegistry_)for(const[s,n]of W)if(q(n)&&!e.has(s))try{this.getBuiltinMethods(n._cppName).has(t)&&e.add(s)}catch(t){console.warn(`[World] Builtin check failed for ${s}:`,t)}const s=this.entityComponents_.get(t);if(s){const t=E();for(const n of s)for(const[s,i]of t)if(i._id===n){e.add(s);break}}return Array.from(e)}resolveStorages_(t,e,s){for(const n of t)if(q(n)){if(!this.cppRegistry_)return!1;s.push(this.getBuiltinMethods(n._cppName))}else{const t=this.tsStorage_.get(n._id);if(!t)return!1;e.push(t)}return!0}getEntitiesWithComponents(t,e=[],s=[],n){if(0===t.length&&0===e.length&&0===s.length)return this.getAllEntities();const i=n??It(t,e,s),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;const o=[],a=[],c=[];if(!this.resolveStorages_(t,a,c))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),o;let l=null,h=null;if(e.length>0&&(l=[],h=[],!this.resolveStorages_(e,l,h)))return this.queryCache_.set(i,{version:this.worldVersion_,result:[]}),o;let u=null,d=null;s.length>0&&(u=[],d=[],this.resolveStorages_(s,u,d));let f=null,_=1/0;for(let t=0;t<a.length;t++){const e=a[t].size;e<_&&(_=e,f=a[t])}for(const e of t)if(q(e)){const t=this.builtinEntitySets_.get(e._cppName);t&&t.size<_&&(_=t.size,f=t)}const p=f?f.keys():this.entities_.keys(),m=a.length,y=c.length;for(const t of p){let e=!0;for(let s=0;s<m;s++)if(!a[s].has(t)){e=!1;break}if(e)for(let s=0;s<y;s++)if(!c[s].has(t)){e=!1;break}if(e&&l){for(let s=0;s<l.length;s++)if(!l[s].has(t)){e=!1;break}if(e)for(let s=0;s<h.length;s++)if(!h[s].has(t)){e=!1;break}}if(e&&u){for(let s=0;s<u.length;s++)if(u[s].has(t)){e=!1;break}if(e)for(let s=0;s<d.length;s++)if(d[s].has(t)){e=!1;break}}e&&o.push(t)}return this.queryCache_.set(i,{version:this.worldVersion_,result:o}),o}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}enableChangeTracking(t){this.trackedComponents_.add(t._id)}isAddedSince(t,e,s){const n=this.componentAddedTicks_.get(e._id);if(!n)return!1;const i=n.get(t);return void 0!==i&&i>s}isChangedSince(t,e,s){const n=this.componentChangedTicks_.get(e._id);if(!n)return!1;const i=n.get(t);return void 0!==i&&i>s}getRemovedEntitiesSince(t,e){const s=this.componentRemovedBuffer_.get(t._id);if(!s)return[];const n=[];for(const t of s)t.tick>e&&n.push(t.entity);return n}cleanRemovedBuffer(t){for(const[e,s]of this.componentRemovedBuffer_){let n=0;for(let e=0;e<s.length;e++)s[e].tick>=t&&(s[n++]=s[e]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(e)}}recordAddedTick_(t,e){if(!this.trackedComponents_.has(t._id))return;let s=this.componentAddedTicks_.get(t._id);s||(s=new Map,this.componentAddedTicks_.set(t._id,s)),s.set(e,this.worldTick_)}markChanged(t,e){this.recordChangedTick_(e,t)}recordChangedTick_(t,e){if(!this.trackedComponents_.has(t._id))return;let s=this.componentChangedTicks_.get(t._id);s||(s=new Map,this.componentChangedTicks_.set(t._id,s)),s.set(e,this.worldTick_)}recordRemovedTick_(t,e){if(!this.trackedComponents_.has(t._id))return;let s=this.componentRemovedBuffer_.get(t._id);s||(s=[],this.componentRemovedBuffer_.set(t._id,s)),s.push({entity:e,tick:this.worldTick_}),this.componentAddedTicks_.get(t._id)?.delete(e),this.componentChangedTicks_.get(t._id)?.delete(e)}}function Nt(t){return{_type:"mut",_component:t}}function qt(t){return"object"==typeof t&&null!==t&&"_type"in t&&"mut"===t._type}function Wt(t){return{_filterType:"added",_component:t}}function jt(t){return{_filterType:"changed",_component:t}}function Ot(t){return"object"==typeof t&&null!==t&&"_filterType"in t&&"added"===t._filterType}function Ut(t){return"object"==typeof t&&null!==t&&"_filterType"in t&&"changed"===t._filterType}function Vt(t){return qt(t)||Ot(t)||Ut(t)?t._component:t}function Ht(t,e=[],s=[]){const n=[],i=[],r=[];return t.forEach((t,e)=>{qt(t)&&n.push(e),Ot(t)?i.push({index:e,component:t._component}):Ut(t)&&r.push({index:e,component:t._component})}),{_type:"query",_components:t,_mutIndices:n,_with:e,_without:s,_addedFilters:i,_changedFilters:r,with:(...n)=>Ht(t,[...e,...n],s),without:(...n)=>Ht(t,e,[...s,...n])}}function Lt(...t){return Ht(t)}class Kt{constructor(t,e,s=-1){this.world_=t,this.descriptor_=e,this.lastRunTick_=s,this.actualComponents_=e._components.map(Vt),this.allRequired_=this.actualComponents_.concat(e._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=e._mutIndices.map(t=>({component:this.actualComponents_[t],data:null})),this.cacheKey_=It(this.allRequired_,e._with,e._without),this.getters_=this.actualComponents_.map(e=>t.resolveGetter(e)),this.mutSetters_=e._mutIndices.map(e=>t.resolveSetter(this.actualComponents_[e])),this.mutIsBuiltin_=e._mutIndices.map(t=>q(this.actualComponents_[t]));for(const s of e._addedFilters)t.enableChangeTracking(s.component);for(const s of e._changedFilters)t.enableChangeTracking(s.component)}resetTick(t){this.lastRunTick_=t}passesChangeFilters_(t){const{_addedFilters:e,_changedFilters:s}=this.descriptor_;if(0===e.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of e)if(!this.world_.isAddedSince(t,s.component,n))return!1;for(const e of s)if(!this.world_.isChangedSince(t,e.component,n))return!1;return!0}[Symbol.iterator](){const{_mutIndices:t}=this.descriptor_,e=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=e.length,i=t.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,c=a.length,l=this.mutSetters_,h=this.world_,u=this.getters_,d=this;let f=0,_=null,p=!1,m=!1;const y=this.mutIsBuiltin_,g=()=>{for(let t=0;t<c;t++){const e=a[t];if(y[t]){const s=l[t];s?s(_,e.data):h.set(_,e.component,e.data)}else h.markChanged(_,e.component)}},w=()=>{m||(m=!0,h.endIteration(),null!==_&&i&&g())},v={value:o,done:!1},b={value:void 0,done:!0};return{next(){for(p||(p=!0,h.beginIteration());f<s.length;){const l=s[f++];if(!r||d.passesChangeFilters_(l)){null!==_&&i&&g(),o[0]=l;for(let t=0;t<n;t++){const s=u[t];o[t+1]=s?s(l):h.get(l,e[t])}if(i){for(let e=0;e<c;e++)a[e].data=o[t[e]+1];_=l}return v}}return w(),b},return:()=>(w(),b)}}forEach(t){const{_mutIndices:e}=this.descriptor_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=this.actualComponents_.length,i=e.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,c=a.length,l=this.mutSetters_,h=this.world_,u=this.getters_,d=this.actualComponents_;h.beginIteration();let f=null;for(let _=0;_<s.length;_++){const p=s[_];if(!r||this.passesChangeFilters_(p)){if(null!==f&&i)for(let t=0;t<c;t++){const e=a[t];if(this.mutIsBuiltin_[t]){const s=l[t];s?s(f,e.data):h.set(f,e.component,e.data)}else h.markChanged(f,e.component)}o[0]=p;for(let t=0;t<n;t++){const e=u[t];o[t+1]=e?e(p):h.get(p,d[t])}if(i){for(let t=0;t<c;t++)a[t].data=o[e[t]+1];f=p}switch(n){case 1:t(p,o[1]);break;case 2:t(p,o[1],o[2]);break;case 3:t(p,o[1],o[2],o[3]);break;default:t.apply(null,o)}}}if(null!==f&&i)for(let t=0;t<c;t++){const e=a[t];if(this.mutIsBuiltin_[t]){const s=l[t];s?s(f,e.data):h.set(f,e.component,e.data)}else h.markChanged(f,e.component)}h.endIteration()}single(){for(const t of this)return t;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const t=[];for(const e of this)t.push([...e]);return t}}function Gt(t){return{_type:"removed",_component:t}}class Xt{constructor(t,e,s){this.world_=t,this.component_=e,this.lastRunTick_=s,t.enableChangeTracking(e)}resetTick(t){this.lastRunTick_=t}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function Yt(){return{_type:"commands"}}class Jt{constructor(t,e,s){this.components_=[],this.commands_=t,null===e?(this.entityRef_={entity:0},this.isNew_=!0,void 0!==s&&this.insert(ut,{value:s})):(this.entityRef_={entity:e},this.isNew_=!1)}insert(t,e){let s;return s=q(t)?{...t._default,...e}:t.create(e),this.isNew_?this.components_.push({component:t,data:s}):this.commands_.queueInsert(this.entityRef_.entity,t,s),this}remove(t){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,t),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 Qt{constructor(t,e){this.pending_=[],this.spawned_=[],this.world_=t,this.resources_=e}spawn(t){const e=new Jt(this,null,t);return this.spawned_.push(e),e}entity(t){return new Jt(this,t)}despawn(t){return this.pending_.push({type:"despawn",entity:t}),this}insertResource(t,e){return this.pending_.push({type:"insert_resource",resource:t,value:e}),this}queueInsert(t,e,s){this.pending_.push({type:"insert",entity:t,component:e,data:s})}queueRemove(t,e){this.pending_.push({type:"remove",entity:t,component:e})}spawnImmediate(t,e){const s=this.world_.spawn();e.entity=s;for(const e of t)this.world_.insert(s,e.component,e.data)}flush(){for(const t of this.spawned_)t.finalize();this.spawned_.length=0;for(const t of this.pending_)this.executeCommand(t);this.pending_.length=0}executeCommand(t){switch(t.type){case"despawn":if(!this.world_.valid(t.entity)){console.warn(`[Commands] despawn skipped: entity ${t.entity} is already invalid`);break}this.world_.despawn(t.entity);break;case"insert":if(!this.world_.valid(t.entity)){console.warn(`[Commands] insert skipped: entity ${t.entity} is invalid`);break}this.world_.insert(t.entity,t.component,t.data);break;case"remove":if(!this.world_.valid(t.entity)){console.warn(`[Commands] remove skipped: entity ${t.entity} is invalid`);break}this.world_.remove(t.entity,t.component);break;case"insert_resource":this.resources_.insert(t.resource,t.value)}}}function Zt(t){return{_id:Symbol(`Event_${t}`),_name:t}}class te{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(t){this.writeBuffer_.push(t)}getReadBuffer(){return this.readBuffer_}swap(){const t=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=t,this.writeBuffer_.length=0}}class ee{constructor(){this.buses_=new Map}register(t){this.buses_.has(t._id)||this.buses_.set(t._id,new te)}getBus(t){let e=this.buses_.get(t._id);return e||(e=new te,this.buses_.set(t._id,e)),e}swapAll(){for(const t of this.buses_.values())t.swap()}}function se(t){return{_type:"event_writer",_event:t}}function ne(t){return{_type:"event_reader",_event:t}}class ie{constructor(t){this.bus_=t}send(t){this.bus_.send(t)}}class re{constructor(t){this.bus_=t}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var oe;function ae(){return{_type:"get_world"}}!function(t){t[t.Startup=0]="Startup",t[t.First=1]="First",t[t.PreUpdate=2]="PreUpdate",t[t.Update=3]="Update",t[t.PostUpdate=4]="PostUpdate",t[t.Last=5]="Last",t[t.FixedPreUpdate=10]="FixedPreUpdate",t[t.FixedUpdate=11]="FixedUpdate",t[t.FixedPostUpdate=12]="FixedPostUpdate"}(oe||(oe={}));let ce=0;function le(t,e,s){const n=++ce;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:t,_fn:e,_name:s?.name??`System_${n}`}}function he(){const t=globalThis;return t.__esengine_pendingSystems??(t.__esengine_pendingSystems=[])}function ue(t){he().push({schedule:oe.Update,system:t})}function de(t){he().push({schedule:oe.Startup,system:t})}function fe(t,e){he().push({schedule:t,system:e})}class _e{constructor(t,e,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.queryCache_=new Map,this.removedCache_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=t,this.resources_=e,this.eventRegistry_=s??null}setTimingEnabled(t){this.timings_=t?new Map:null}getTimings(){return this.timings_}run(t){let e=this.argsCache_.get(t._id);e||(e=new Array(t._params.length),this.argsCache_.set(t._id,e)),this.currentLastRunTick_=this.systemTicks_.get(t._id)??-1;let s=this.queryCache_.get(t._id),n=this.removedCache_.get(t._id);const i=!s;i&&(s=[],n=[],this.queryCache_.set(t._id,s),this.removedCache_.set(t._id,n));let r=0,o=0;for(let a=0;a<t._params.length;a++){const c=t._params[a];if("query"===c._type){if(i){const t=new Kt(this.world_,c,this.currentLastRunTick_);s.push(t),e[a]=t}else{const t=s[r];t.resetTick(this.currentLastRunTick_),e[a]=t}r++}else if("removed"===c._type){if(i){const t=c,s=new Xt(this.world_,t._component,this.currentLastRunTick_);n.push(s),e[a]=s}else{const t=n[o];t.resetTick(this.currentLastRunTick_),e[a]=t}o++}else e[a]=this.resolveParam(c)}const a=this.timings_?performance.now():0;let c;try{c=t._fn(...e)}catch(s){throw this.flushSystem_(t,e,a),s}if(c instanceof Promise)return c.then(()=>{this.flushSystem_(t,e,a)},s=>{throw this.flushSystem_(t,e,a),s});this.flushSystem_(t,e,a)}flushSystem_(t,e,s){for(let t=0;t<e.length;t++)e[t]instanceof Qt&&e[t].flush();this.timings_&&this.timings_.set(t._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(t._id,this.world_.getWorldTick())}resolveParam(t){switch(t._type){case"res":return this.resources_.get(t._resource);case"res_mut":return this.resources_.getResMut(t._resource);case"commands":return new Qt(this.world_,this.resources_);case"event_writer":{const e=t,s=this.eventRegistry_?this.eventRegistry_.getBus(e._event):(()=>{throw new Error("EventRegistry not available")})();return new ie(s)}case"event_reader":{const e=t,s=this.eventRegistry_?this.eventRegistry_.getBus(e._event):(()=>{throw new Error("EventRegistry not available")})();return new re(s)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}export{n as $,L as A,rt as B,tt as C,u as D,ee as E,t as F,e as G,ae as H,y as I,Wt as J,jt as K,Yt as L,Qt as M,ut as N,l as O,ft as P,Lt as Q,f as R,oe as S,X as T,r as U,o as V,J as W,a as X,c as Y,d as Z,i as _,le as a,at as a0,Jt as a1,ne as a2,re as a3,se as a4,ie as a5,w as a6,v as a7,Y as a8,Nt as a9,k as aA,lt as aa,ht as ab,Kt as ac,Gt as ad,Xt as ae,Z as af,G as ag,ct as ah,st as ai,de as aj,ue as ak,fe as al,m as am,_ as an,I as ao,S as ap,Zt as aq,z as ar,_t as as,A as at,q as au,x as av,T as aw,D as ax,b as ay,C as az,$ as b,Q as c,mt as d,yt as e,bt as f,O as g,ot as h,M as i,Tt as j,V as k,dt as l,gt as m,Dt as n,vt as o,_e as p,H as q,K as r,Rt as s,g as t,nt as u,j as v,it as w,h as x,et as y,s as z};//# sourceMappingURL=system.js.mapdiff --git a/desktop/public/sdk/esm/shared/system.js.map b/desktop/public/sdk/esm/shared/system.js.mapindex 886f7d0ac..e0ba9a538 100644--- a/desktop/public/sdk/esm/shared/system.js.map+++ b/desktop/public/sdk/esm/shared/system.js.map@@ -1 +1 @@-{"version":3,"file":"system.js","sources":["../../src/defaults.ts","../../src/types.ts","../../src/componentEntityFields.ts","../../src/component.ts","../../src/resource.ts","../../src/validation.ts","../../src/wasmError.ts","../../src/world.ts","../../src/query.ts","../../src/commands.ts","../../src/event.ts","../../src/system.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null],"names":["DEFAULT_DESIGN_WIDTH","DEFAULT_DESIGN_HEIGHT","DEFAULT_PIXELS_PER_UNIT","DEFAULT_TEXT_CANVAS_SIZE","DEFAULT_SPRITE_SIZE","x","y","DEFAULT_FONT_FAMILY","DEFAULT_FONT_SIZE","DEFAULT_LINE_HEIGHT","DEFAULT_MAX_DELTA_TIME","DEFAULT_FALLBACK_DT","DEFAULT_GRAVITY","DEFAULT_FIXED_TIMESTEP","DEFAULT_SPINE_SKIN","RuntimeConfig","sceneTransitionDuration","sceneTransitionColor","r","g","b","a","defaultFontFamily","canvasScaleMode","canvasMatchWidthOrHeight","maxDeltaTime","maxFixedSteps","textCanvasSize","assetLoadTimeout","assetFailureCooldown","applyRuntimeConfig","components","Text","_default","fontFamily","TextInput","Canvas","scaleMode","matchWidthOrHeight","CANVAS_SCALE_MODE_MAP","FixedWidth","FixedHeight","Expand","Shrink","Match","applyBuildRuntimeConfig","app","config","undefined","setMaxDeltaTime","setMaxFixedSteps","hex","replace","parseInt","substring","INVALID_ENTITY","INVALID_TEXTURE","INVALID_FONT","INVALID_MATERIAL","vec2","vec3","z","vec4","w","color","quat","COMPONENT_ENTITY_FIELDS","Map","registerComponentEntityFields","componentType","fields","set","getComponentEntityFields","get","deepClone","value","Array","isArray","map","result","key","componentCounter","createComponentDef","name","defaults","id","keyInfo","obj","flatKeys","objectKeys","arrayKeys","hasNested","val","push","classifyKeys","defaultsRec","_id","Symbol","_name","_builtin","create","data","k","slice","Object","assign","getComponentRegistry","globalThis","__esengine_componentRegistry","defineComponent","metadata","existing","componentRegistry","def","registerToEditor","entityFields","defineTag","getUserComponent","clearUserComponents","userRegistry","keys","delete","clear","unregisterComponent","isTag","__esengine_registerComponent","isBuiltinComponent","comp","registerComponent","getComponent","detectColorKeys","defineBuiltin","_cppName","_colorKeys","ProjectionType","Perspective","Orthographic","ClearFlags","None","ColorOnly","DepthOnly","ColorAndDepth","ScaleMode","ShapeType","Circle","Capsule","RoundedRect","Transform","position","rotation","scale","worldPosition","worldRotation","worldScale","LocalTransform","WorldTransform","Sprite","texture","size","pivot","uvOffset","uvScale","layer","flipX","flipY","material","enabled","ShapeRenderer","shapeType","cornerRadius","Camera","projectionType","fov","orthoSize","nearPlane","farPlane","aspectRatio","isActive","priority","showFrustum","viewportX","viewportY","viewportW","viewportH","clearFlags","designResolution","pixelsPerUnit","backgroundColor","Velocity","linear","angular","Parent","entity","Children","entities","BitmapText","text","fontSize","align","spacing","font","SpineAnimation","skeletonPath","atlasPath","skin","animation","timeScale","loop","playing","skeletonScale","EmitterShape","Point","Rectangle","Cone","SimulationSpace","World","Local","ParticleEasing","Linear","EaseIn","EaseOut","EaseInOut","ParticleEmitter","rate","burstCount","burstInterval","duration","looping","playOnStart","maxParticles","lifetimeMin","lifetimeMax","shape","shapeRadius","shapeSize","shapeAngle","speedMin","speedMax","angleSpreadMin","angleSpreadMax","startSizeMin","startSizeMax","endSizeMin","endSizeMax","sizeEasing","startColor","endColor","colorEasing","rotationMin","rotationMax","angularVelocityMin","angularVelocityMax","gravity","damping","spriteColumns","spriteRows","spriteFPS","spriteLoop","blendMode","simulationSpace","Name","SceneOwner","scene","persistent","PostProcessVolume","effects","isGlobal","weight","blendDistance","getComponentDefaults","typeName","resourceCounter","defineResource","defaultValue","Res","resource","_type","_resource","ResMut","ResMutInstance","constructor","setter","this","value_","setter_","modify","fn","updateValue","ResourceStorage","resources_","resMutPool_","insert","has","remove","getResMut","instance","v","Time","delta","elapsed","frameCount","validateComponentData","componentName","errors","field","entries","expected","actual","expectedType","getType","actualType","formatValidationErrors","lines","err","JSON","stringify","join","errorHandler","setWasmErrorHandler","handler","handleWasmError","error","context","console","convertFromWasm","colorKeys","length","convertForWasm","PTR_LAYOUTS","ptrFn","type","offset","UIRect","RigidBody","BoxCollider","CircleCollider","writePtrField","f32","u32","u8","ptr","byteOff","idx","nextCompNumId_","compNumIds_","WeakMap","getCompNumId","_keyIds","computeQueryCacheKey","withFilters","withoutFilters","c","sort","cppRegistry_","module_","entities_","tsStorage_","entityComponents_","builtinEntitySets_","worldVersion_","queryCache_","builtinMethodCache_","iterationDepth_","nextEntityId_","nextGeneration_","spawnCallbacks_","despawnCallbacks_","worldTick_","componentAddedTicks_","componentChangedTicks_","componentRemovedBuffer_","trackedComponents_","Set","connectCpp","cppRegistry","module","disconnectCpp","hasCpp","getCppRegistry","getWasmModule","spawn","isIterating","Error","e","generation","registry_getGeneration","cb","warn","despawn","destroy","ids","buffer","tick","onSpawn","callback","indexOf","splice","onDespawn","valid","entityCount","getWorldVersion","beginIteration","endIteration","resetIterationDepth","getAllEntities","from","setParent","child","parent","removeParent","component","insertBuiltin","insertScript","raw","wasmData","getBuiltinMethods","add","recordChangedTick_","getStorage","getBuiltin","getScript","cppName","bset","hasScript","tryGet","methods","storage","removeBuiltin","removeScript","reg","addFn","getFn","hasFn","removeFn","bind","filtered","merged","isNew","tracked","recordAddedTick_","hasBuiltin","recordRemovedTick_","clean","resolveGetter","ptrGetter","resolvePtrGetter_","resolveHas","resolveSetter","ptrSetter","resolvePtrSetter_","d","resolvePtrFn_","layout","getPtrFn","mod","i","HEAPF32","HEAPU32","HEAPU8","cached","f","createPreallocatedResult","target","fillPtrFields","resetQueryPool","getComponentTypes","types","registry","resolveStorages_","comps","scriptOut","builtinOut","getEntitiesWithComponents","precomputedKey","cacheKey","version","reqScript","reqBuiltin","withScript","withBuiltin","woScript","woBuiltin","smallestSet","smallestSize","Infinity","candidates","rsLen","rbLen","match","advanceTick","getWorldTick","enableChangeTracking","isAddedSince","sinceTick","isChangedSince","getRemovedEntitiesSince","entry","cleanRemovedBuffer","beforeTick","writeIdx","markChanged","Mut","_component","isMutWrapper","Added","_filterType","Changed","isAddedWrapper","isChangedWrapper","unwrapComponent","createQueryDescriptor","mutIndices","addedFilters","changedFilters","forEach","index","_components","_mutIndices","_with","_without","_addedFilters","_changedFilters","with","extraWith","without","extraWithout","Query","QueryInstance","world","descriptor","lastRunTick","world_","descriptor_","lastRunTick_","actualComponents_","allRequired_","concat","result_","mutData_","cacheKey_","getters_","mutSetters_","mutIsBuiltin_","resetTick","passesChangeFilters_","iterator","actualComponents","compCount","hasMut","hasChangeFilters","mutData","mutCount","mutSetters","getters","self","prevEntity","started","done","mutIsBuiltin","writeMut","mut","finalize","iterResult","doneResult","next","getter","return","apply","single","isEmpty","count","toArray","arr","row","Removed","RemovedQueryInstance","component_","Commands","EntityCommands","commands","components_","commands_","entityRef_","isNew_","queueInsert","queueRemove","spawnImmediate","CommandsInstance","resources","pending_","spawned_","ec","insertResource","entityRef","flush","cmd","executeCommand","defineEvent","EventBus","readBuffer_","writeBuffer_","send","event","getReadBuffer","swap","tmp","EventRegistry","buses_","register","getBus","bus","swapAll","values","EventWriter","_event","EventReader","EventWriterInstance","bus_","EventReaderInstance","Schedule","GetWorld","systemCounter","defineSystem","params","options","_params","_fn","getPendingSystems","__esengine_pendingSystems","addSystem","system","schedule","Update","addStartupSystem","Startup","addSystemToSchedule","SystemRunner","eventRegistry","argsCache_","systemTicks_","removedCache_","currentLastRunTick_","timings_","eventRegistry_","setTimingEnabled","getTimings","run","args","queries","removeds","firstRun","qi","ri","param","inst","desc","resolveParam","t0","performance","now","flushSystem_","Promise","then"],"mappings":"AAAO,MAAMA,EAAuB,KACvBC,EAAwB,KACxBC,EAA0B,IAC1BC,EAA2B,IAC3BC,EAAsB,CAAEC,EAAG,IAAKC,EAAG,KACnCC,EAAsB,QACtBC,EAAoB,GACpBC,EAAsB,IACtBC,EAAyB,GACzBC,EAAsB,EAAI,GAC1BC,EAAkB,CAAEP,EAAG,EAAGC,GAAG,MAC7BO,EAAyB,EAAI,GAC7BC,EAAqB,UAErBC,EAAgB,CACzBC,wBAAyB,GACzBC,qBAAsB,CAAEC,EAAG,EAAGC,EAAG,EAAGC,EAAG,EAAGC,EAAG,GAC7CC,kBAAmB,QACnBC,gBAAiB,EACjBC,yBAA0B,GAC1BC,aAAc,IACdC,cAAe,EACfC,eAAgB,IAChBC,iBAAkB,IAClBC,qBAAsB,KAGpB,SAAUC,EAAmBC,GAK3BA,EAAWC,OAAMD,EAAWC,KAAKC,SAASC,WAAanB,EAAc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AOK,KAAKO,WAAWK,UAAUuW,EAAMxX,WAE3C,IAAK,WACD,OAAO,IAAIsT,GAAiBjT,KAAKyP,OAAQzP,KAAKO,YAElD,IAAK,eAAgB,CACjB,MAAM8W,EAAOF,EACP3C,EAAMxU,KAAKyW,eACXzW,KAAKyW,eAAelC,OAAO8C,EAAKzC,QAChC,MAAS,MAAM,IAAIxO,MAAM,8BAAiC,EAA1D,GACN,OAAO,IAAI0O,GAAoBN,EACnC,CAEA,IAAK,eAAgB,CACjB,MAAM6C,EAAOF,EACP3C,EAAMxU,KAAKyW,eACXzW,KAAKyW,eAAelC,OAAO8C,EAAKzC,QAChC,MAAS,MAAM,IAAIxO,MAAM,8BAAiC,EAA1D,GACN,OAAO,IAAI4O,GAAoBR,EACnC,CAEA,IAAK,YACD,OAAOxU,KAAKyP,OAEhB,QACI,MAAM,IAAIrJ,MAAM,iCAE5B"}\ No newline at end of file+{"version":3,"file":"system.js","sources":["../../src/defaults.ts","../../src/types.ts","../../src/componentEntityFields.ts","../../src/component.ts","../../src/resource.ts","../../src/validation.ts","../../src/wasmError.ts","../../src/world.ts","../../src/query.ts","../../src/commands.ts","../../src/event.ts","../../src/system.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null],"names":["DEFAULT_DESIGN_WIDTH","DEFAULT_DESIGN_HEIGHT","DEFAULT_PIXELS_PER_UNIT","DEFAULT_TEXT_CANVAS_SIZE","DEFAULT_SPRITE_SIZE","x","y","DEFAULT_FONT_FAMILY","DEFAULT_FONT_SIZE","DEFAULT_LINE_HEIGHT","DEFAULT_MAX_DELTA_TIME","DEFAULT_FALLBACK_DT","DEFAULT_GRAVITY","DEFAULT_FIXED_TIMESTEP","DEFAULT_SPINE_SKIN","RuntimeConfig","sceneTransitionDuration","sceneTransitionColor","r","g","b","a","defaultFontFamily","canvasScaleMode","canvasMatchWidthOrHeight","maxDeltaTime","maxFixedSteps","textCanvasSize","assetLoadTimeout","assetFailureCooldown","applyRuntimeConfig","components","Text","_default","fontFamily","TextInput","Canvas","scaleMode","matchWidthOrHeight","CANVAS_SCALE_MODE_MAP","FixedWidth","FixedHeight","Expand","Shrink","Match","applyBuildRuntimeConfig","app","config","undefined","setMaxDeltaTime","setMaxFixedSteps","hex","replace","parseInt","substring","INVALID_ENTITY","INVALID_TEXTURE","INVALID_FONT","INVALID_MATERIAL","vec2","vec3","z","vec4","w","color","quat","COMPONENT_ENTITY_FIELDS","Map","registerComponentEntityFields","componentType","fields","set","getComponentEntityFields","get","deepClone","value","Array","isArray","map","result","key","componentCounter","createComponentDef","name","defaults","id","keyInfo","obj","flatKeys","objectKeys","arrayKeys","hasNested","val","push","classifyKeys","defaultsRec","_id","Symbol","_name","_builtin","create","data","k","slice","Object","assign","getComponentRegistry","globalThis","__esengine_componentRegistry","defineComponent","metadata","existing","componentRegistry","def","registerToEditor","entityFields","defineTag","getUserComponent","clearUserComponents","userRegistry","keys","delete","clear","unregisterComponent","isTag","__esengine_registerComponent","isBuiltinComponent","comp","registerComponent","getComponent","detectColorKeys","defineBuiltin","_cppName","_colorKeys","ProjectionType","Perspective","Orthographic","ClearFlags","None","ColorOnly","DepthOnly","ColorAndDepth","ScaleMode","ShapeType","Circle","Capsule","RoundedRect","Transform","position","rotation","scale","worldPosition","worldRotation","worldScale","LocalTransform","WorldTransform","Sprite","texture","size","pivot","uvOffset","uvScale","layer","flipX","flipY","material","enabled","ShapeRenderer","shapeType","cornerRadius","Camera","projectionType","fov","orthoSize","nearPlane","farPlane","aspectRatio","isActive","priority","showFrustum","viewportX","viewportY","viewportW","viewportH","clearFlags","designResolution","pixelsPerUnit","backgroundColor","Velocity","linear","angular","Parent","entity","Children","entities","BitmapText","text","fontSize","align","spacing","font","SpineAnimation","skeletonPath","atlasPath","skin","animation","timeScale","loop","playing","skeletonScale","EmitterShape","Point","Rectangle","Cone","SimulationSpace","World","Local","ParticleEasing","Linear","EaseIn","EaseOut","EaseInOut","ParticleEmitter","rate","burstCount","burstInterval","duration","looping","playOnStart","maxParticles","lifetimeMin","lifetimeMax","shape","shapeRadius","shapeSize","shapeAngle","speedMin","speedMax","angleSpreadMin","angleSpreadMax","startSizeMin","startSizeMax","endSizeMin","endSizeMax","sizeEasing","startColor","endColor","colorEasing","rotationMin","rotationMax","angularVelocityMin","angularVelocityMax","gravity","damping","spriteColumns","spriteRows","spriteFPS","spriteLoop","blendMode","simulationSpace","Name","SceneOwner","scene","persistent","PostProcessVolume","effects","isGlobal","weight","blendDistance","getComponentDefaults","typeName","resourceCounter","defineResource","defaultValue","Res","resource","_type","_resource","ResMut","ResMutInstance","constructor","setter","this","value_","setter_","modify","fn","updateValue","ResourceStorage","resources_","resMutPool_","insert","has","remove","getResMut","instance","v","Time","delta","elapsed","frameCount","validateComponentData","componentName","errors","field","entries","expected","actual","expectedType","getType","actualType","formatValidationErrors","lines","err","JSON","stringify","join","errorHandler","setWasmErrorHandler","handler","handleWasmError","error","context","console","convertFromWasm","colorKeys","length","convertForWasm","PTR_LAYOUTS","ptrFn","type","offset","UIRect","RigidBody","BoxCollider","CircleCollider","writePtrField","f32","u32","u8","ptr","byteOff","idx","nextCompNumId_","compNumIds_","WeakMap","getCompNumId","_keyIds","computeQueryCacheKey","withFilters","withoutFilters","c","sort","cppRegistry_","module_","entities_","tsStorage_","entityComponents_","builtinEntitySets_","worldVersion_","queryCache_","builtinMethodCache_","iterationDepth_","nextEntityId_","nextGeneration_","spawnCallbacks_","despawnCallbacks_","worldTick_","componentAddedTicks_","componentChangedTicks_","componentRemovedBuffer_","trackedComponents_","Set","connectCpp","cppRegistry","module","disconnectCpp","hasCpp","getCppRegistry","getWasmModule","spawn","isIterating","Error","e","generation","registry_getGeneration","cb","warn","despawn","destroy","ids","buffer","tick","onSpawn","callback","indexOf","splice","onDespawn","valid","entityCount","getWorldVersion","beginIteration","endIteration","resetIterationDepth","getAllEntities","from","setParent","child","parent","removeParent","component","insertBuiltin","insertScript","raw","wasmData","getBuiltinMethods","add","recordChangedTick_","getStorage","getBuiltin","getScript","cppName","bset","hasScript","tryGet","methods","storage","removeBuiltin","removeScript","reg","addFn","getFn","hasFn","removeFn","bind","filtered","merged","isNew","tracked","recordAddedTick_","hasBuiltin","recordRemovedTick_","clean","resolveGetter","ptrGetter","resolvePtrGetter_","resolveHas","resolveSetter","ptrSetter","resolvePtrSetter_","d","resolvePtrFn_","layout","getPtrFn","mod","i","HEAPF32","HEAPU32","HEAPU8","cached","f","createPreallocatedResult","target","fillPtrFields","resetQueryPool","getComponentTypes","types","registry","resolveStorages_","comps","scriptOut","builtinOut","getEntitiesWithComponents","precomputedKey","cacheKey","version","reqScript","reqBuiltin","withScript","withBuiltin","woScript","woBuiltin","smallestSet","smallestSize","Infinity","candidates","rsLen","rbLen","match","advanceTick","getWorldTick","enableChangeTracking","isAddedSince","sinceTick","isChangedSince","getRemovedEntitiesSince","entry","cleanRemovedBuffer","beforeTick","writeIdx","markChanged","Mut","_component","isMutWrapper","Added","_filterType","Changed","isAddedWrapper","isChangedWrapper","unwrapComponent","createQueryDescriptor","mutIndices","addedFilters","changedFilters","forEach","index","_components","_mutIndices","_with","_without","_addedFilters","_changedFilters","with","extraWith","without","extraWithout","Query","QueryInstance","world","descriptor","lastRunTick","world_","descriptor_","lastRunTick_","actualComponents_","allRequired_","concat","result_","mutData_","cacheKey_","getters_","mutSetters_","mutIsBuiltin_","resetTick","passesChangeFilters_","iterator","actualComponents","compCount","hasMut","hasChangeFilters","mutData","mutCount","mutSetters","getters","self","prevEntity","started","done","mutIsBuiltin","writeMut","mut","finalize","iterResult","doneResult","next","getter","return","apply","single","isEmpty","count","toArray","arr","row","Removed","RemovedQueryInstance","component_","Commands","EntityCommands","commands","components_","commands_","entityRef_","isNew_","queueInsert","queueRemove","spawnImmediate","CommandsInstance","resources","pending_","spawned_","ec","insertResource","entityRef","flush","cmd","executeCommand","defineEvent","EventBus","readBuffer_","writeBuffer_","send","event","getReadBuffer","swap","tmp","EventRegistry","buses_","register","getBus","bus","swapAll","values","EventWriter","_event","EventReader","EventWriterInstance","bus_","EventReaderInstance","Schedule","GetWorld","systemCounter","defineSystem","params","options","_params","_fn","getPendingSystems","__esengine_pendingSystems","addSystem","system","schedule","Update","addStartupSystem","Startup","addSystemToSchedule","SystemRunner","eventRegistry","argsCache_","systemTicks_","removedCache_","currentLastRunTick_","timings_","eventRegistry_","setTimingEnabled","getTimings","run","args","queries","removeds","firstRun","qi","ri","param","inst","desc","resolveParam","t0","performance","now","flushSystem_","Promise","then"],"mappings":"AAAO,MAAMA,EAAuB,KACvBC,EAAwB,KACxBC,EAA0B,IAC1BC,EAA2B,IAC3BC,EAAsB,CAAEC,EAAG,IAAKC,EAAG,KACnCC,EAAsB,QACtBC,EAAoB,GACpBC,EAAsB,IACtBC,EAAyB,GACzBC,EAAsB,EAAI,GAC1BC,EAAkB,CAAEP,EAAG,EAAGC,GAAG,MAC7BO,EAAyB,EAAI,GAC7BC,EAAqB,UAErBC,EAAgB,CACzBC,wBAAyB,GACzBC,qBAAsB,CAAEC,EAAG,EAAGC,EAAG,EAAGC,EAAG,EAAGC,EAAG,GAC7CC,kBAAmB,QACnBC,gBAAiB,EACjBC,yBAA0B,GAC1BC,aAAc,IACdC,cAAe,EACfC,eAAgB,IAChBC,iBAAkB,IAClBC,qBAAsB,KAGpB,SAAUC,EAAmBC,GAK3BA,EAAWC,OAAMD,EAAWC,KAAKC,SAASC,WAAanB,EAAcO,mBACrES,EAAWI,YAAWJ,EAAWI,UAAUF,SAASC,WAAanB,EAAcO,mBAC/ES,EAAWK,SACXL,EAAWK,OAAOH,SAASI,UAAYtB,EAAcQ,gBACrDQ,EAAWK,OAAOH,SAASK,mBAAqBvB,EAAcS,yBAEtE,CAmBA,MAAMe,EAAgD,CAClDC,WAAY,EAAGC,YAAa,EAAGC,OAAQ,EAAGC,OAAQ,EAAGC,MAAO,GAG1D,SAAUC,EAAwBC,EAA8EC,GAkBlH,QAjB4BC,IAAxBD,EAAOtB,eACPV,EAAcU,aAAesB,EAAOtB,aACpCqB,EAAIG,g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C,MAAS,MAAM,IAAIxO,MAAM,8BAAiC,EAA1D,GACN,OAAO,IAAI0O,GAAoBN,EACnC,CAEA,IAAK,eAAgB,CACjB,MAAM6C,EAAOF,EACP3C,EAAMxU,KAAKyW,eACXzW,KAAKyW,eAAelC,OAAO8C,EAAKzC,QAChC,MAAS,MAAM,IAAIxO,MAAM,8BAAiC,EAA1D,GACN,OAAO,IAAI4O,GAAoBR,EACnC,CAEA,IAAK,YACD,OAAOxU,KAAKyP,OAEhB,QACI,MAAM,IAAIrJ,MAAM,iCAE5B"}\ No newline at end of filediff --git a/desktop/public/sdk/esm/shared/wasm.d.ts b/desktop/public/sdk/esm/shared/wasm.d.tsindex da5b75e77..0b5e494e5 100644--- a/desktop/public/sdk/esm/shared/wasm.d.ts+++ b/desktop/public/sdk/esm/shared/wasm.d.ts@@ -78,6 +78,14 @@ interface FlexItem {flexShrink: number;flexBasis: number;order: number;+ alignSelf: number;+ margin: Padding;+ minWidth: number;+ minHeight: number;+ maxWidth: number;+ maxHeight: number;+ widthPercent: number;+ heightPercent: number;}interface BoxCollider {halfExtents: Vec2;@@ -257,6 +265,7 @@ interface FlexContainer {wrap: number;justifyContent: number;alignItems: number;+ alignContent: number;gap: Vec2;padding: Padding;}diff --git a/desktop/public/wasm/esengine.js b/desktop/public/wasm/esengine.jsindex a37f20ed2..88d15a6ca 100644--- a/desktop/public/wasm/esengine.js+++ b/desktop/public/wasm/esengine.js@@ -1,2 +1,2 @@-async function ESEngineModule(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("node:module");var require=createRequire(import.meta.url)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["fb"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("esengine.wasm")}return new URL("esengine.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var structRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_object=structType=>{var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};for(var[i,field]of fieldRecords.entries()){const getterReturnType=fieldTypes[i];const getter=field.getter;const getterContext=field.getterContext;const setterArgumentType=fieldTypes[i+fieldRecords.length];const setter=field.setter;const setterContext=field.setterContext;fields[field.fieldName]={read:ptr=>getterReturnType.fromWireType(getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType.toWireType(destructors,o));runDestructors(destructors)},optional:getterReturnType.optional}}return[{name:reg.name,fromWireType:ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},toWireType:(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)&&!fields[fieldName].optional){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction:rawDestructor}]})};var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var attachFinalizer=handle=>{if(!globalThis.FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var init_ClassHandle=()=>{let proto=ClassHandle.prototype;Object.assign(proto,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}});const symbolDispose=Symbol.dispose;if(symbolDispose){proto[symbolDispose]=proto["delete"]}};function ClassHandle(){}var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var registeredPointers={};var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupported sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this.toWireType=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this.toWireType=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this.toWireType=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=AsciiToString(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError(`Use 'new' to construct ${name}`)}if(undefined===registeredClass.constructor_body){throw new BindingError(`${name} has no accessible constructor`)}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync){var needsDestructorStack=usesDestructorStack(argTypes);var argCount=argTypes.length-2;var argsList=[];var argsListWired=["fn"];if(isClassMethodFunc){argsListWired.push("thisWired")}for(var i=0;i<argCount;++i){argsList.push(`arg${i}`);argsListWired.push(`arg${i}Wired`)}argsList=argsList.join(",");argsListWired=argsListWired.join(",");var invokerFnBody=`return function (${argsList}) {\n`;if(needsDestructorStack){invokerFnBody+="var destructors = [];\n"}var dtorStack=needsDestructorStack?"destructors":"null";var args1=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];if(isClassMethodFunc){invokerFnBody+=`var thisWired = toClassParamWire(${dtorStack}, this);\n`}for(var i=0;i<argCount;++i){var argName=`toArg${i}Wire`;invokerFnBody+=`var arg${i}Wired = ${argName}(${dtorStack}, arg${i});\n`;args1.push(argName)}invokerFnBody+=(returns||isAsync?"var rv = ":"")+`invoker(${argsListWired});\n`;if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;++i){var paramName=i===1?"thisWired":"arg"+(i-2)+"Wired";if(argTypes[i].destructorFunction!==null){invokerFnBody+=`${paramName}_dtor(${paramName});\n`;args1.push(`${paramName}_dtor`)}}}if(returns){invokerFnBody+="var ret = fromRetWire(rv);\n"+"return ret;\n"}else{}invokerFnBody+="}\n";return new Function(args1,invokerFnBody)}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=!argTypes[0].isVoid;var retType=argTypes[0];var instType=argTypes[1];var closureArgs=[humanName,throwBindingError,cppInvokerFunc,cppTargetFunc,runDestructors,retType.fromWireType.bind(retType),instType?.toWireType.bind(instType)];for(var i=2;i<argCount;++i){var argType=argTypes[i];closureArgs.push(argType.toWireType.bind(argType))}if(!needsDestructorStack){for(var i=isClassMethodFunc?1:2;i<argTypes.length;++i){if(argTypes[i].destructorFunction!==null){closureArgs.push(argTypes[i].destructorFunction)}}}let invokerFactory=createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync);var invokerFn=invokerFactory(...closureArgs);return createNamedFunction(humanName,invokerFn)}var __embind_register_class_constructor=(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync,isNonnullReturn)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=AsciiToString(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker,isAsync);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var enumReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?function(pointer){return this.fromWireType(HEAP8[pointer])}:function(pointer){return this.fromWireType(HEAPU8[pointer])};case 2:return signed?function(pointer){return this.fromWireType(HEAP16[pointer>>1])}:function(pointer){return this.fromWireType(HEAPU16[pointer>>1])};case 4:return signed?function(pointer){return this.fromWireType(HEAP32[pointer>>2])}:function(pointer){return this.fromWireType(HEAPU32[pointer>>2])};default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};function getEnumValueType(rawValueType){return rawValueType===0?"object":rawValueType===1?"number":"string"}var __embind_register_enum=(rawType,name,size,isSigned,rawValueType)=>{name=AsciiToString(name);const valueType=getEnumValueType(rawValueType);switch(valueType){case"object":{function ctor(){}ctor.values={};registerType(rawType,{name,constructor:ctor,valueType,fromWireType:function(c){return this.constructor.values[c]},toWireType:(destructors,c)=>c.value,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor);break}case"number":{var keysMap={};registerType(rawType,{name,keysMap,valueType,fromWireType:c=>c,toWireType:(destructors,c)=>c,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}case"string":{var valuesMap={};var reverseMap={};var keysMap={};registerType(rawType,{name,valuesMap,reverseMap,keysMap,valueType,fromWireType:function(c){return this.reverseMap[c]},toWireType:function(destructors,c){return this.valuesMap[c]},readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}}};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var __embind_register_enum_value=(rawEnumType,name,enumValue)=>{var enumType=requireRegisteredType(rawEnumType,"enum");name=AsciiToString(name);switch(enumType.valueType){case"object":{var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(`${enumType.name}_${name}`,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value;break}case"number":{enumType.keysMap[name]=enumValue;break}case"string":{enumType.valuesMap[name]=enumValue;enumType.reverseMap[enumValue]=name;enumType.keysMap[name]=name;break}}};var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var installIndexedIterator=(proto,sizeMethodName,getMethodName)=>{const makeIterator=(size,getValue)=>{let index=0;return{next(){if(index>=size){return{done:true}}const current=index;index++;const value=getValue(current);return{value,done:false}},[Symbol.iterator](){return this}}};if(!proto[Symbol.iterator]){proto[Symbol.iterator]=function(){const size=this[sizeMethodName]();return makeIterator(size,i=>this[getMethodName](i))}}};var __embind_register_iterable=(rawClassType,rawElementType,sizeMethodName,getMethodName)=>{sizeMethodName=AsciiToString(sizeMethodName);getMethodName=AsciiToString(getMethodName);whenDependentTypesAreResolved([],[rawClassType,rawElementType],types=>{const classType=types[0];installIndexedIterator(classType.registeredClass.instancePrototype,sizeMethodName,getMethodName);return[]})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var EmValOptionalType=Object.assign({optional:true},EmValType);var __embind_register_optional=(rawOptionalType,rawType)=>{registerType(rawOptionalType,EmValOptionalType)};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_value_object=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{structRegistrations[rawType]={name:AsciiToString(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}};var __embind_register_value_object_field=(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{structRegistrations[structType].fields.push({fieldName:AsciiToString(fieldName),getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext,setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`)}return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=(argCount,argTypesPtr,kind)=>{var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var captures={toValue:Emval.toValue};var args=argFromPtr.map((argFromPtr,i)=>{var captureName=`argFromPtr${i}`;captures[captureName]=argFromPtr;return`${captureName}(args${i?"+"+i*GenericWireTypeSize:""})`});var functionBody;switch(kind){case 0:functionBody="toValue(handle)";break;case 2:functionBody="new (toValue(handle))";break;case 3:functionBody="";break;case 1:captures["getStringOrSymbol"]=getStringOrSymbol;functionBody="toValue(handle)[getStringOrSymbol(methodName)]";break}functionBody+=`(${args})`;if(!retType.isVoid){captures["toReturnWire"]=toReturnWire;captures["emval_returnValue"]=emval_returnValue;functionBody=`return emval_returnValue(toReturnWire, destructorsRef, ${functionBody})`}functionBody=`return function (handle, methodName, destructorsRef, args) {\n${functionBody}\n}`;var invokerFunction=new Function(Object.keys(captures),functionBody)(...Object.values(captures));var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_invoke=(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args);var __emval_new_array=()=>Emval.toHandle([]);var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var __emval_new_object=()=>Emval.toHandle({});var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var GLctx;var webgl_enable_ANGLE_instanced_arrays=ctx=>{var ext=ctx.getExtension("ANGLE_instanced_arrays");if(ext){ctx["vertexAttribDivisor"]=(index,divisor)=>ext["vertexAttribDivisorANGLE"](index,divisor);ctx["drawArraysInstanced"]=(mode,first,count,primcount)=>ext["drawArraysInstancedANGLE"](mode,first,count,primcount);ctx["drawElementsInstanced"]=(mode,count,type,indices,primcount)=>ext["drawElementsInstancedANGLE"](mode,count,type,indices,primcount);return 1}};var webgl_enable_OES_vertex_array_object=ctx=>{var ext=ctx.getExtension("OES_vertex_array_object");if(ext){ctx["createVertexArray"]=()=>ext["createVertexArrayOES"]();ctx["deleteVertexArray"]=vao=>ext["deleteVertexArrayOES"](vao);ctx["bindVertexArray"]=vao=>ext["bindVertexArrayOES"](vao);ctx["isVertexArray"]=vao=>ext["isVertexArrayOES"](vao);return 1}};var webgl_enable_WEBGL_draw_buffers=ctx=>{var ext=ctx.getExtension("WEBGL_draw_buffers");if(ext){ctx["drawBuffers"]=(n,bufs)=>ext["drawBuffersWEBGL"](n,bufs);return 1}};var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.dibvbi=ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.mdibvbi=ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));var webgl_enable_EXT_polygon_offset_clamp=ctx=>!!(ctx.extPolygonOffsetClamp=ctx.getExtension("EXT_polygon_offset_clamp"));var webgl_enable_EXT_clip_control=ctx=>!!(ctx.extClipControl=ctx.getExtension("EXT_clip_control"));var webgl_enable_WEBGL_polygon_mode=ctx=>!!(ctx.webglPolygonMode=ctx.getExtension("WEBGL_polygon_mode"));var webgl_enable_WEBGL_multi_draw=ctx=>!!(ctx.multiDrawWebgl=ctx.getExtension("WEBGL_multi_draw"));var getEmscriptenSupportedExtensions=ctx=>{var supportedExtensions=["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_disjoint_timer_query","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_depth_texture","WEBGL_draw_buffers","EXT_color_buffer_float","EXT_conservative_depth","EXT_disjoint_timer_query_webgl2","EXT_texture_norm16","NV_shader_noperspective_interpolation","WEBGL_clip_cull_distance","EXT_clip_control","EXT_color_buffer_half_float","EXT_depth_clamp","EXT_float_blend","EXT_polygon_offset_clamp","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","KHR_parallel_shader_compile","OES_texture_float_linear","WEBGL_blend_func_extended","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_multi_draw","WEBGL_polygon_mode"];return(ctx.getSupportedExtensions()||[]).filter(ext=>supportedExtensions.includes(ext))};var registerPreMainLoop=f=>{typeof MainLoop!="undefined"&&MainLoop.preMainLoop.push(f)};var GL={counter:1,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:[],offscreenCanvases:{},queries:[],samplers:[],transformFeedbacks:[],syncs:[],byteSizeByTypeRoot:5120,byteSizeByType:[1,1,2,2,4,4,4,2,3,4,8],stringCache:{},stringiCache:{},unpackAlignment:4,unpackRowLength:0,recordError:errorCode=>{if(!GL.lastError){GL.lastError=errorCode}},getNewId:table=>{var ret=GL.counter++;for(var i=table.length;i<ret;i++){table[i]=null}while(table[ret]){ret=GL.counter++}return ret},genObject:(n,buffers,createFunction,objectTable)=>{for(var i=0;i<n;i++){var buffer=GLctx[createFunction]();var id=buffer&&GL.getNewId(objectTable);if(buffer){buffer.name=id;objectTable[id]=buffer}else{GL.recordError(1282)}HEAP32[buffers+i*4>>2]=id}},MAX_TEMP_BUFFER_SIZE:2097152,numTempVertexBuffersPerSize:64,log2ceilLookup:i=>32-Math.clz32(i===0?0:i-1),generateTempBuffers:(quads,context)=>{var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);context.tempVertexBufferCounters1=[];context.tempVertexBufferCounters2=[];context.tempVertexBufferCounters1.length=context.tempVertexBufferCounters2.length=largestIndex+1;context.tempVertexBuffers1=[];context.tempVertexBuffers2=[];context.tempVertexBuffers1.length=context.tempVertexBuffers2.length=largestIndex+1;context.tempIndexBuffers=[];context.tempIndexBuffers.length=largestIndex+1;for(var i=0;i<=largestIndex;++i){context.tempIndexBuffers[i]=null;context.tempVertexBufferCounters1[i]=context.tempVertexBufferCounters2[i]=0;var ringbufferLength=GL.numTempVertexBuffersPerSize;context.tempVertexBuffers1[i]=[];context.tempVertexBuffers2[i]=[];var ringbuffer1=context.tempVertexBuffers1[i];var ringbuffer2=context.tempVertexBuffers2[i];ringbuffer1.length=ringbuffer2.length=ringbufferLength;for(var j=0;j<ringbufferLength;++j){ringbuffer1[j]=ringbuffer2[j]=null}}if(quads){context.tempQuadIndexBuffer=GLctx.createBuffer();context.GLctx.bindBuffer(34963,context.tempQuadIndexBuffer);var numIndexes=GL.MAX_TEMP_BUFFER_SIZE>>1;var quadIndexes=new Uint16Array(numIndexes);var i=0,v=0;while(1){quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+1;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v+3;if(i>=numIndexes)break;v+=4}context.GLctx.bufferData(34963,quadIndexes,35044);context.GLctx.bindBuffer(34963,null)}},getTempVertexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ringbuffer=GL.currentContext.tempVertexBuffers1[idx];var nextFreeBufferIndex=GL.currentContext.tempVertexBufferCounters1[idx];GL.currentContext.tempVertexBufferCounters1[idx]=GL.currentContext.tempVertexBufferCounters1[idx]+1&GL.numTempVertexBuffersPerSize-1;var vbo=ringbuffer[nextFreeBufferIndex];if(vbo){return vbo}var prevVBO=GLctx.getParameter(34964);ringbuffer[nextFreeBufferIndex]=GLctx.createBuffer();GLctx.bindBuffer(34962,ringbuffer[nextFreeBufferIndex]);GLctx.bufferData(34962,1<<idx,35048);GLctx.bindBuffer(34962,prevVBO);return ringbuffer[nextFreeBufferIndex]},getTempIndexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ibo=GL.currentContext.tempIndexBuffers[idx];if(ibo){return ibo}var prevIBO=GLctx.getParameter(34965);GL.currentContext.tempIndexBuffers[idx]=GLctx.createBuffer();GLctx.bindBuffer(34963,GL.currentContext.tempIndexBuffers[idx]);GLctx.bufferData(34963,1<<idx,35048);GLctx.bindBuffer(34963,prevIBO);return GL.currentContext.tempIndexBuffers[idx]},newRenderingFrameStarted:()=>{if(!GL.currentContext){return}var vb=GL.currentContext.tempVertexBuffers1;GL.currentContext.tempVertexBuffers1=GL.currentContext.tempVertexBuffers2;GL.currentContext.tempVertexBuffers2=vb;vb=GL.currentContext.tempVertexBufferCounters1;GL.currentContext.tempVertexBufferCounters1=GL.currentContext.tempVertexBufferCounters2;GL.currentContext.tempVertexBufferCounters2=vb;var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);for(var i=0;i<=largestIndex;++i){GL.currentContext.tempVertexBufferCounters1[i]=0}},getSource:(shader,count,string,length)=>{var source="";for(var i=0;i<count;++i){var len=length?HEAPU32[length+i*4>>2]:undefined;source+=UTF8ToString(HEAPU32[string+i*4>>2],len)}return source},calcBufLength:(size,type,stride,count)=>{if(stride>0){return count*stride}var typeSize=GL.byteSizeByType[type-GL.byteSizeByTypeRoot];return size*typeSize*count},usedTempBuffers:[],preDrawHandleClientVertexAttribBindings:count=>{GL.resetBufferBinding=false;for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(!cb.clientside||!cb.enabled)continue;GL.resetBufferBinding=true;var size=GL.calcBufLength(cb.size,cb.type,cb.stride,count);var buf=GL.getTempVertexBuffer(size);GLctx.bindBuffer(34962,buf);GLctx.bufferSubData(34962,0,HEAPU8.subarray(cb.ptr,cb.ptr+size));cb.vertexAttribPointerAdaptor.call(GLctx,i,cb.size,cb.type,cb.normalized,cb.stride,0)}},postDrawHandleClientVertexAttribBindings:()=>{if(GL.resetBufferBinding){GLctx.bindBuffer(34962,GL.buffers[GLctx.currentArrayBufferBinding])}},createContext:(canvas,webGLContextAttributes)=>{if(!canvas.getContextSafariWebGL2Fixed){canvas.getContextSafariWebGL2Fixed=canvas.getContext;function fixedGetContext(ver,attrs){var gl=canvas.getContextSafariWebGL2Fixed(ver,attrs);return ver=="webgl"==gl instanceof WebGLRenderingContext?gl:null}canvas.getContext=fixedGetContext}var ctx=webGLContextAttributes.majorVersion>1?canvas.getContext("webgl2",webGLContextAttributes):canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:(ctx,webGLContextAttributes)=>{var handle=GL.getNewId(GL.contexts);var context={handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault=="undefined"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}context.maxVertexAttribs=context.GLctx.getParameter(34921);context.clientBuffers=[];for(var i=0;i<context.maxVertexAttribs;i++){context.clientBuffers[i]={enabled:false,clientside:false,size:0,type:0,normalized:0,stride:0,ptr:0,vertexAttribPointerAdaptor:null}}GL.generateTempBuffers(false,context);return handle},makeContextCurrent:contextHandle=>{GL.currentContext=GL.contexts[contextHandle];Module["ctx"]=GLctx=GL.currentContext?.GLctx;return!(contextHandle&&!GLctx)},getContext:contextHandle=>GL.contexts[contextHandle],deleteContext:contextHandle=>{if(GL.currentContext===GL.contexts[contextHandle]){GL.currentContext=null}if(typeof JSEvents=="object"){JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas)}if(GL.contexts[contextHandle]?.GLctx.canvas){GL.contexts[contextHandle].GLctx.canvas.GLctxObject=undefined}GL.contexts[contextHandle]=null},initExtensions:context=>{context||=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx=context.GLctx;webgl_enable_WEBGL_multi_draw(GLctx);webgl_enable_EXT_polygon_offset_clamp(GLctx);webgl_enable_EXT_clip_control(GLctx);webgl_enable_WEBGL_polygon_mode(GLctx);webgl_enable_ANGLE_instanced_arrays(GLctx);webgl_enable_OES_vertex_array_object(GLctx);webgl_enable_WEBGL_draw_buffers(GLctx);webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);if(context.version>=2){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query_webgl2")}if(context.version<2||!GLctx.disjointTimerQueryExt){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query")}for(var ext of getEmscriptenSupportedExtensions(GLctx)){if(!ext.includes("lose_context")&&!ext.includes("debug")){GLctx.getExtension(ext)}}}};var webglPowerPreferences=["default","low-power","high-performance"];var maybeCStringToJsString=cString=>cString>2?UTF8ToString(cString):cString;var specialHTMLTargets=[0,globalThis.document??0,globalThis.window??0];var findEventTarget=target=>{target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||globalThis.document?.querySelector(target);return domElement};var findCanvasEventTarget=findEventTarget;var _emscripten_webgl_do_create_context=(target,attributes)=>{var attr32=attributes>>2;var powerPreference=HEAP32[attr32+(8>>2)];var contextAttributes={alpha:!!HEAP8[attributes+0],depth:!!HEAP8[attributes+1],stencil:!!HEAP8[attributes+2],antialias:!!HEAP8[attributes+3],premultipliedAlpha:!!HEAP8[attributes+4],preserveDrawingBuffer:!!HEAP8[attributes+5],powerPreference:webglPowerPreferences[powerPreference],failIfMajorPerformanceCaveat:!!HEAP8[attributes+12],majorVersion:HEAP32[attr32+(16>>2)],minorVersion:HEAP32[attr32+(20>>2)],enableExtensionsByDefault:HEAP8[attributes+24],explicitSwapControl:HEAP8[attributes+25],proxyContextToMainThread:HEAP32[attr32+(28>>2)],renderViaOffscreenBackBuffer:HEAP8[attributes+32]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle};var _emscripten_webgl_create_context=_emscripten_webgl_do_create_context;var _emscripten_webgl_destroy_context=contextHandle=>{if(GL.currentContext==contextHandle)GL.currentContext=0;GL.deleteContext(contextHandle)};var _emscripten_webgl_make_context_current=contextHandle=>{var success=GL.makeContextCurrent(contextHandle);return success?0:-5};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _emscripten_glActiveTexture=x0=>GLctx.activeTexture(x0);var _glActiveTexture=_emscripten_glActiveTexture;var _emscripten_glAttachShader=(program,shader)=>{GLctx.attachShader(GL.programs[program],GL.shaders[shader])};var _glAttachShader=_emscripten_glAttachShader;var _emscripten_glBindAttribLocation=(program,index,name)=>{GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))};var _glBindAttribLocation=_emscripten_glBindAttribLocation;var _emscripten_glBindBuffer=(target,buffer)=>{if(buffer&&!GL.buffers[buffer]){var b=GLctx.createBuffer();b.name=buffer;GL.buffers[buffer]=b}if(target==34962){GLctx.currentArrayBufferBinding=buffer}else if(target==34963){GLctx.currentElementArrayBufferBinding=buffer}if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])};var _glBindBuffer=_emscripten_glBindBuffer;var _emscripten_glBindFramebuffer=(target,framebuffer)=>{GLctx.bindFramebuffer(target,GL.framebuffers[framebuffer])};var _glBindFramebuffer=_emscripten_glBindFramebuffer;var _emscripten_glBindTexture=(target,texture)=>{GLctx.bindTexture(target,GL.textures[texture])};var _glBindTexture=_emscripten_glBindTexture;var _emscripten_glBindVertexArray=vao=>{GLctx.bindVertexArray(GL.vaos[vao]);var ibo=GLctx.getParameter(34965);GLctx.currentElementArrayBufferBinding=ibo?ibo.name|0:0};var _glBindVertexArray=_emscripten_glBindVertexArray;var _emscripten_glBlendFunc=(x0,x1)=>GLctx.blendFunc(x0,x1);var _glBlendFunc=_emscripten_glBlendFunc;var _emscripten_glBlendFuncSeparate=(x0,x1,x2,x3)=>GLctx.blendFuncSeparate(x0,x1,x2,x3);var _glBlendFuncSeparate=_emscripten_glBlendFuncSeparate;var _emscripten_glBufferData=(target,size,data,usage)=>{if(GL.currentContext.version>=2){if(data&&size){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}return}GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)};var _glBufferData=_emscripten_glBufferData;var _emscripten_glBufferSubData=(target,offset,size,data)=>{if(GL.currentContext.version>=2){size&&GLctx.bufferSubData(target,offset,HEAPU8,data,size);return}GLctx.bufferSubData(target,offset,HEAPU8.subarray(data,data+size))};var _glBufferSubData=_emscripten_glBufferSubData;var _emscripten_glCheckFramebufferStatus=x0=>GLctx.checkFramebufferStatus(x0);var _glCheckFramebufferStatus=_emscripten_glCheckFramebufferStatus;var _emscripten_glClear=x0=>GLctx.clear(x0);var _glClear=_emscripten_glClear;var _emscripten_glClearColor=(x0,x1,x2,x3)=>GLctx.clearColor(x0,x1,x2,x3);var _glClearColor=_emscripten_glClearColor;var _emscripten_glClearStencil=x0=>GLctx.clearStencil(x0);var _glClearStencil=_emscripten_glClearStencil;var _emscripten_glColorMask=(red,green,blue,alpha)=>{GLctx.colorMask(!!red,!!green,!!blue,!!alpha)};var _glColorMask=_emscripten_glColorMask;var _emscripten_glCompileShader=shader=>{GLctx.compileShader(GL.shaders[shader])};var _glCompileShader=_emscripten_glCompileShader;var _emscripten_glCreateProgram=()=>{var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id};var _glCreateProgram=_emscripten_glCreateProgram;var _emscripten_glCreateShader=shaderType=>{var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);return id};var _glCreateShader=_emscripten_glCreateShader;var _emscripten_glDeleteBuffers=(n,buffers)=>{for(var i=0;i<n;i++){var id=HEAP32[buffers+i*4>>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentArrayBufferBinding)GLctx.currentArrayBufferBinding=0;if(id==GLctx.currentElementArrayBufferBinding)GLctx.currentElementArrayBufferBinding=0;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}};var _glDeleteBuffers=_emscripten_glDeleteBuffers;var _emscripten_glDeleteFramebuffers=(n,framebuffers)=>{for(var i=0;i<n;++i){var id=HEAP32[framebuffers+i*4>>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}};var _glDeleteFramebuffers=_emscripten_glDeleteFramebuffers;var _emscripten_glDeleteProgram=id=>{if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null};var _glDeleteProgram=_emscripten_glDeleteProgram;var _emscripten_glDeleteShader=id=>{if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null};var _glDeleteShader=_emscripten_glDeleteShader;var _emscripten_glDeleteTextures=(n,textures)=>{for(var i=0;i<n;i++){var id=HEAP32[textures+i*4>>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}};var _glDeleteTextures=_emscripten_glDeleteTextures;var _emscripten_glDeleteVertexArrays=(n,vaos)=>{for(var i=0;i<n;i++){var id=HEAP32[vaos+i*4>>2];GLctx.deleteVertexArray(GL.vaos[id]);GL.vaos[id]=null}};var _glDeleteVertexArrays=_emscripten_glDeleteVertexArrays;var _emscripten_glDepthMask=flag=>{GLctx.depthMask(!!flag)};var _glDepthMask=_emscripten_glDepthMask;var _emscripten_glDisable=x0=>GLctx.disable(x0);var _glDisable=_emscripten_glDisable;var _emscripten_glDrawArrays=(mode,first,count)=>{GL.preDrawHandleClientVertexAttribBindings(first+count);GLctx.drawArrays(mode,first,count);GL.postDrawHandleClientVertexAttribBindings()};var _glDrawArrays=_emscripten_glDrawArrays;var _emscripten_glDrawElements=(mode,count,type,indices)=>{var buf;var vertexes=0;if(!GLctx.currentElementArrayBufferBinding){var size=GL.calcBufLength(1,type,0,count);buf=GL.getTempIndexBuffer(size);GLctx.bindBuffer(34963,buf);GLctx.bufferSubData(34963,0,HEAPU8.subarray(indices,indices+size));if(count>0){for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(cb.clientside&&cb.enabled){let arrayClass;switch(type){case 5121:arrayClass=Uint8Array;break;case 5123:arrayClass=Uint16Array;break;case 5125:arrayClass=Uint32Array;break;default:GL.recordError(1282);return}vertexes=new arrayClass(HEAPU8.buffer,indices,count).reduce((max,current)=>Math.max(max,current))+1;break}}}indices=0}GL.preDrawHandleClientVertexAttribBindings(vertexes);GLctx.drawElements(mode,count,type,indices);GL.postDrawHandleClientVertexAttribBindings(count);if(!GLctx.currentElementArrayBufferBinding){GLctx.bindBuffer(34963,null)}};var _glDrawElements=_emscripten_glDrawElements;var _emscripten_glEnable=x0=>GLctx.enable(x0);var _glEnable=_emscripten_glEnable;var _emscripten_glEnableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=true;GLctx.enableVertexAttribArray(index)};var _glEnableVertexAttribArray=_emscripten_glEnableVertexAttribArray;var _emscripten_glFramebufferTexture2D=(target,attachment,textarget,texture,level)=>{GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)};var _glFramebufferTexture2D=_emscripten_glFramebufferTexture2D;var _emscripten_glGenBuffers=(n,buffers)=>{GL.genObject(n,buffers,"createBuffer",GL.buffers)};var _glGenBuffers=_emscripten_glGenBuffers;var _emscripten_glGenFramebuffers=(n,ids)=>{GL.genObject(n,ids,"createFramebuffer",GL.framebuffers)};var _glGenFramebuffers=_emscripten_glGenFramebuffers;var _emscripten_glGenTextures=(n,textures)=>{GL.genObject(n,textures,"createTexture",GL.textures)};var _glGenTextures=_emscripten_glGenTextures;var _emscripten_glGenVertexArrays=(n,arrays)=>{GL.genObject(n,arrays,"createVertexArray",GL.vaos)};var _glGenVertexArrays=_emscripten_glGenVertexArrays;var _emscripten_glGenerateMipmap=x0=>GLctx.generateMipmap(x0);var _glGenerateMipmap=_emscripten_glGenerateMipmap;var _emscripten_glGetError=()=>{var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error};var _glGetError=_emscripten_glGetError;var writeI53ToI64=(ptr,num)=>{HEAPU32[ptr>>2]=num;var lower=HEAPU32[ptr>>2];HEAPU32[ptr+4>>2]=(num-lower)/4294967296};var webglGetExtensions=()=>{var exts=getEmscriptenSupportedExtensions(GLctx);exts=exts.concat(exts.map(e=>"GL_"+e));return exts};var emscriptenWebGLGet=(name_,p,type)=>{if(!p){GL.recordError(1281);return}var ret=undefined;switch(name_){case 36346:ret=1;break;case 36344:if(type!=0&&type!=1){GL.recordError(1280)}return;case 34814:case 36345:ret=0;break;case 34466:var formats=GLctx.getParameter(34467);ret=formats?formats.length:0;break;case 33309:if(GL.currentContext.version<2){GL.recordError(1282);return}ret=webglGetExtensions().length;break;case 33307:case 33308:if(GL.currentContext.version<2){GL.recordError(1280);return}ret=name_==33307?3:0;break}if(ret===undefined){var result=GLctx.getParameter(name_);switch(typeof result){case"number":ret=result;break;case"boolean":ret=result?1:0;break;case"string":GL.recordError(1280);return;case"object":if(result===null){switch(name_){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:{ret=0;break}default:{GL.recordError(1280);return}}}else if(result instanceof Float32Array||result instanceof Uint32Array||result instanceof Int32Array||result instanceof Array){for(var i=0;i<result.length;++i){switch(type){case 0:HEAP32[p+i*4>>2]=result[i];break;case 2:HEAPF32[p+i*4>>2]=result[i];break;case 4:HEAP8[p+i]=result[i]?1:0;break}}return}else{try{ret=result.name|0}catch(e){GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);return}}break;default:GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof result}!`);return}}switch(type){case 1:writeI53ToI64(p,ret);break;case 0:HEAP32[p>>2]=ret;break;case 2:HEAPF32[p>>2]=ret;break;case 4:HEAP8[p]=ret?1:0;break}};var _emscripten_glGetIntegerv=(name_,p)=>emscriptenWebGLGet(name_,p,0);var _glGetIntegerv=_emscripten_glGetIntegerv;var _emscripten_glGetProgramInfoLog=(program,maxLength,length,infoLog)=>{var log=GLctx.getProgramInfoLog(GL.programs[program]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetProgramInfoLog=_emscripten_glGetProgramInfoLog;var _emscripten_glGetProgramiv=(program,pname,p)=>{if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(var i=0;i<numActiveUniforms;++i){program.maxUniformLength=Math.max(program.maxUniformLength,GLctx.getActiveUniform(program,i).name.length+1)}}HEAP32[p>>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){var numActiveAttributes=GLctx.getProgramParameter(program,35721);for(var i=0;i<numActiveAttributes;++i){program.maxAttributeLength=Math.max(program.maxAttributeLength,GLctx.getActiveAttrib(program,i).name.length+1)}}HEAP32[p>>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){var numActiveUniformBlocks=GLctx.getProgramParameter(program,35382);for(var i=0;i<numActiveUniformBlocks;++i){program.maxUniformBlockNameLength=Math.max(program.maxUniformBlockNameLength,GLctx.getActiveUniformBlockName(program,i).length+1)}}HEAP32[p>>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}};var _glGetProgramiv=_emscripten_glGetProgramiv;var _emscripten_glGetShaderInfoLog=(shader,maxLength,length,infoLog)=>{var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetShaderInfoLog=_emscripten_glGetShaderInfoLog;var _emscripten_glGetShaderiv=(shader,pname,p)=>{if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}};var _glGetShaderiv=_emscripten_glGetShaderiv;var stringToNewUTF8=str=>{var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8(str,ret,size);return ret};var _emscripten_glGetString=name_=>{var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:ret=stringToNewUTF8(webglGetExtensions().join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s?stringToNewUTF8(s):0;break;case 7938:var webGLVersion=GLctx.getParameter(7938);var glVersion=`OpenGL ES 2.0 (${webGLVersion})`;if(GL.currentContext.version>=2)glVersion=`OpenGL ES 3.0 (${webGLVersion})`;ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion=`OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret};var _glGetString=_emscripten_glGetString;var jstoi_q=str=>parseInt(str);var webglGetLeftBracePos=name=>name.slice(-1)=="]"&&name.lastIndexOf("[");var webglPrepareUniformLocationsBeforeFirstUse=program=>{var uniformLocsById=program.uniformLocsById,uniformSizeAndIdsByName=program.uniformSizeAndIdsByName,i,j;if(!uniformLocsById){program.uniformLocsById=uniformLocsById={};program.uniformArrayNamesById={};var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(i=0;i<numActiveUniforms;++i){var u=GLctx.getActiveUniform(program,i);var nm=u.name;var sz=u.size;var lb=webglGetLeftBracePos(nm);var arrayName=lb>0?nm.slice(0,lb):nm;var id=program.uniformIdCounter;program.uniformIdCounter+=sz;uniformSizeAndIdsByName[arrayName]=[sz,id];for(j=0;j<sz;++j){uniformLocsById[id]=j;program.uniformArrayNamesById[id++]=arrayName}}}};var _emscripten_glGetUniformLocation=(program,name)=>{name=UTF8ToString(name);if(program=GL.programs[program]){webglPrepareUniformLocationsBeforeFirstUse(program);var uniformLocsById=program.uniformLocsById;var arrayIndex=0;var uniformBaseName=name;var leftBrace=webglGetLeftBracePos(name);if(leftBrace>0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=program.uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex<sizeAndId[0]){arrayIndex+=sizeAndId[1];if(uniformLocsById[arrayIndex]=uniformLocsById[arrayIndex]||GLctx.getUniformLocation(program,name)){return arrayIndex}}}else{GL.recordError(1281)}return-1};var _glGetUniformLocation=_emscripten_glGetUniformLocation;var _emscripten_glLinkProgram=program=>{program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={}};var _glLinkProgram=_emscripten_glLinkProgram;var _emscripten_glPixelStorei=(pname,param)=>{if(pname==3317){GL.unpackAlignment=param}else if(pname==3314){GL.unpackRowLength=param}GLctx.pixelStorei(pname,param)};var _glPixelStorei=_emscripten_glPixelStorei;var computeUnpackAlignedImageSize=(width,height,sizePerPixel)=>{function roundedToNextMultipleOf(x,y){return x+y-1&-y}var plainRowSize=(GL.unpackRowLength||width)*sizePerPixel;var alignedRowSize=roundedToNextMultipleOf(plainRowSize,GL.unpackAlignment);return height*alignedRowSize};var colorChannelsInGlTextureFormat=format=>{var colorChannels={5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4};return colorChannels[format-6402]||1};var heapObjectForWebGLType=type=>{type-=5120;if(type==0)return HEAP8;if(type==1)return HEAPU8;if(type==2)return HEAP16;if(type==4)return HEAP32;if(type==6)return HEAPF32;if(type==5||type==28922||type==28520||type==30779||type==30782)return HEAPU32;return HEAPU16};var toTypedArrayIndex=(pointer,heap)=>pointer>>>31-Math.clz32(heap.BYTES_PER_ELEMENT);var emscriptenWebGLGetTexPixelData=(type,format,width,height,pixels,internalFormat)=>{var heap=heapObjectForWebGLType(type);var sizePerPixel=colorChannelsInGlTextureFormat(format)*heap.BYTES_PER_ELEMENT;var bytes=computeUnpackAlignedImageSize(width,height,sizePerPixel);return heap.subarray(toTypedArrayIndex(pixels,heap),toTypedArrayIndex(pixels+bytes,heap))};var _emscripten_glReadPixels=(x,y,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelPackBufferBinding){GLctx.readPixels(x,y,width,height,format,type,pixels);return}var heap=heapObjectForWebGLType(type);var target=toTypedArrayIndex(pixels,heap);GLctx.readPixels(x,y,width,height,format,type,heap,target);return}var pixelData=emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,format);if(!pixelData){GL.recordError(1280);return}GLctx.readPixels(x,y,width,height,format,type,pixelData)};var _glReadPixels=_emscripten_glReadPixels;var _emscripten_glScissor=(x0,x1,x2,x3)=>GLctx.scissor(x0,x1,x2,x3);var _glScissor=_emscripten_glScissor;var _emscripten_glShaderSource=(shader,count,string,length)=>{var source=GL.getSource(shader,count,string,length);GLctx.shaderSource(GL.shaders[shader],source)};var _glShaderSource=_emscripten_glShaderSource;var _emscripten_glStencilFunc=(x0,x1,x2)=>GLctx.stencilFunc(x0,x1,x2);var _glStencilFunc=_emscripten_glStencilFunc;var _emscripten_glStencilMask=x0=>GLctx.stencilMask(x0);var _glStencilMask=_emscripten_glStencilMask;var _emscripten_glStencilOp=(x0,x1,x2)=>GLctx.stencilOp(x0,x1,x2);var _glStencilOp=_emscripten_glStencilOp;var _emscripten_glTexImage2D=(target,level,internalFormat,width,height,border,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);var index=toTypedArrayIndex(pixels,heap);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,index);return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null;GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixelData)};var _glTexImage2D=_emscripten_glTexImage2D;var _emscripten_glTexParameteri=(x0,x1,x2)=>GLctx.texParameteri(x0,x1,x2);var _glTexParameteri=_emscripten_glTexParameteri;var _emscripten_glTexSubImage2D=(target,level,xoffset,yoffset,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,toTypedArrayIndex(pixels,heap));return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0):null;GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)};var _glTexSubImage2D=_emscripten_glTexSubImage2D;var webglGetUniformLocation=location=>{var p=GLctx.currentProgram;if(p){var webglLoc=p.uniformLocsById[location];if(typeof webglLoc=="number"){p.uniformLocsById[location]=webglLoc=GLctx.getUniformLocation(p,p.uniformArrayNamesById[location]+(webglLoc>0?`[${webglLoc}]`:""))}return webglLoc}else{GL.recordError(1282)}};var _emscripten_glUniform1f=(location,v0)=>{GLctx.uniform1f(webglGetUniformLocation(location),v0)};var _glUniform1f=_emscripten_glUniform1f;var _emscripten_glUniform1i=(location,v0)=>{GLctx.uniform1i(webglGetUniformLocation(location),v0)};var _glUniform1i=_emscripten_glUniform1i;var _emscripten_glUniform2f=(location,v0,v1)=>{GLctx.uniform2f(webglGetUniformLocation(location),v0,v1)};var _glUniform2f=_emscripten_glUniform2f;var _emscripten_glUniform3f=(location,v0,v1,v2)=>{GLctx.uniform3f(webglGetUniformLocation(location),v0,v1,v2)};var _glUniform3f=_emscripten_glUniform3f;var _emscripten_glUniform4f=(location,v0,v1,v2,v3)=>{GLctx.uniform4f(webglGetUniformLocation(location),v0,v1,v2,v3)};var _glUniform4f=_emscripten_glUniform4f;var miniTempWebGLFloatBuffers=[];var _emscripten_glUniformMatrix4fv=(location,count,transpose,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count];var heap=HEAPF32;value=value>>2;count*=16;for(var i=0;i<count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)};var _glUniformMatrix4fv=_emscripten_glUniformMatrix4fv;var _emscripten_glUseProgram=program=>{program=GL.programs[program];GLctx.useProgram(program);GLctx.currentProgram=program};var _glUseProgram=_emscripten_glUseProgram;var _emscripten_glVertexAttribPointer=(index,size,type,normalized,stride,ptr)=>{var cb=GL.currentContext.clientBuffers[index];if(!GLctx.currentArrayBufferBinding){cb.size=size;cb.type=type;cb.normalized=normalized;cb.stride=stride;cb.ptr=ptr;cb.clientside=true;cb.vertexAttribPointerAdaptor=function(index,size,type,normalized,stride,ptr){this.vertexAttribPointer(index,size,type,normalized,stride,ptr)};return}cb.clientside=false;GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)};var _glVertexAttribPointer=_emscripten_glVertexAttribPointer;var _emscripten_glViewport=(x0,x1,x2,x3)=>GLctx.viewport(x0,x1,x2,x3);var _glViewport=_emscripten_glViewport;var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var updateTableMap=(offset,count)=>{if(functionsInTableMap){for(var i=offset;i<offset+count;i++){var item=getWasmTableEntry(i);if(item){functionsInTableMap.set(item,i)}}}};var functionsInTableMap;var getFunctionAddress=func=>{if(!functionsInTableMap){functionsInTableMap=new WeakMap;updateTableMap(0,wasmTable.length)}return functionsInTableMap.get(func)||0};var freeTableIndexes=[];var getEmptyTableSlot=()=>{if(freeTableIndexes.length){return freeTableIndexes.pop()}return wasmTable["grow"](1)};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var uleb128EncodeWithLen=arr=>{const n=arr.length;return[n%128|128,n>>7,...arr]};var wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111};var generateTypePack=types=>uleb128EncodeWithLen(Array.from(types,type=>{var code=wasmTypeCodes[type];return code}));var convertJsFunctionToWasm=(func,sig)=>{var bytes=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(sig.slice(1)),...generateTypePack(sig[0]==="v"?"":sig[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};var addFunction=(func,sig)=>{var rtn=getFunctionAddress(func);if(rtn){return rtn}var ret=getEmptyTableSlot();try{setWasmTableEntry(ret,func)}catch(err){if(!(err instanceof TypeError)){throw err}var wrapped=convertJsFunctionToWasm(func,sig);setWasmTableEntry(ret,wrapped)}functionsInTableMap.set(func,ret);return ret};var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();init_ClassHandle();init_RegisteredPointer();registerPreMainLoop(()=>GL.newRenderingFrameStarted());var miniTempWebGLFloatBuffersStorage=new Float32Array(288);for(var i=0;i<=288;++i){miniTempWebGLFloatBuffers[i]=miniTempWebGLFloatBuffersStorage.subarray(0,i)}{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["addFunction"]=addFunction;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;Module["GL"]=GL;var ___getTypeName,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["gb"];_malloc=Module["_malloc"]=wasmExports["hb"];_free=Module["_free"]=wasmExports["ib"];__emscripten_timeout=wasmExports["kb"];__emscripten_stack_restore=wasmExports["lb"];__emscripten_stack_alloc=wasmExports["mb"];_emscripten_stack_get_current=wasmExports["nb"];memory=wasmMemory=wasmExports["eb"];__indirect_function_table=wasmTable=wasmExports["jb"]}var wasmImports={ea:___syscall_fcntl64,Ba:___syscall_ioctl,Ca:___syscall_openat,Da:__abort_js,f:__embind_finalize_value_object,ya:__embind_register_bigint,cb:__embind_register_bool,ca:__embind_register_class,ua:__embind_register_class_constructor,c:__embind_register_class_function,Ra:__embind_register_emval,v:__embind_register_enum,e:__embind_register_enum_value,xa:__embind_register_float,a:__embind_register_function,G:__embind_register_integer,Oa:__embind_register_iterable,o:__embind_register_memory_view,Pa:__embind_register_optional,Ua:__embind_register_std_string,da:__embind_register_std_wstring,g:__embind_register_value_object,b:__embind_register_value_object_field,Fa:__embind_register_void,Ta:__emscripten_runtime_keepalive_clear,E:__emval_create_invoker,x:__emval_decref,D:__emval_invoke,W:__emval_new_array,R:__emval_new_cstring,ba:__emval_new_object,C:__emval_run_destructors,N:__emval_set_property,Va:__setitimer_js,Wa:__tzset_js,Za:_clock_time_get,_a:_emscripten_resize_heap,db:_emscripten_webgl_create_context,Qa:_emscripten_webgl_destroy_context,Aa:_emscripten_webgl_make_context_current,Xa:_environ_get,Ya:_environ_sizes_get,za:_fd_close,bb:_fd_read,$a:_fd_seek,ab:_fd_write,q:_glActiveTexture,oa:_glAttachShader,Ma:_glBindAttribLocation,i:_glBindBuffer,m:_glBindFramebuffer,n:_glBindTexture,p:_glBindVertexArray,$:_glBlendFunc,l:_glBlendFuncSeparate,w:_glBufferData,H:_glBufferSubData,Ea:_glCheckFramebufferStatus,B:_glClear,Y:_glClearColor,va:_glClearStencil,Z:_glColorMask,qa:_glCompileShader,Na:_glCreateProgram,sa:_glCreateShader,A:_glDeleteBuffers,j:_glDeleteFramebuffers,ta:_glDeleteProgram,I:_glDeleteShader,d:_glDeleteTextures,J:_glDeleteVertexArrays,_:_glDepthMask,h:_glDisable,P:_glDrawArrays,Q:_glDrawElements,k:_glEnable,u:_glEnableVertexAttribArray,ha:_glFramebufferTexture2D,z:_glGenBuffers,Ga:_glGenFramebuffers,V:_glGenTextures,K:_glGenVertexArrays,Ia:_glGenerateMipmap,M:_glGetError,aa:_glGetIntegerv,Ka:_glGetProgramInfoLog,na:_glGetProgramiv,pa:_glGetShaderInfoLog,T:_glGetShaderiv,X:_glGetString,r:_glGetUniformLocation,La:_glLinkProgram,ja:_glPixelStorei,Ha:_glReadPixels,wa:_glScissor,ra:_glShaderSource,ga:_glStencilFunc,O:_glStencilMask,fa:_glStencilOp,U:_glTexImage2D,s:_glTexParameteri,ia:_glTexSubImage2D,ma:_glUniform1f,L:_glUniform1i,la:_glUniform2f,Ja:_glUniform3f,ka:_glUniform4f,S:_glUniformMatrix4fv,F:_glUseProgram,t:_glVertexAttribPointer,y:_glViewport,Sa:_proc_exit};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}+async function ESEngineModule(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("node:module");var require=createRequire(import.meta.url)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["fb"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("esengine.wasm")}return new URL("esengine.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var structRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_object=structType=>{var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};for(var[i,field]of fieldRecords.entries()){const getterReturnType=fieldTypes[i];const getter=field.getter;const getterContext=field.getterContext;const setterArgumentType=fieldTypes[i+fieldRecords.length];const setter=field.setter;const setterContext=field.setterContext;fields[field.fieldName]={read:ptr=>getterReturnType.fromWireType(getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType.toWireType(destructors,o));runDestructors(destructors)},optional:getterReturnType.optional}}return[{name:reg.name,fromWireType:ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},toWireType:(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)&&!fields[fieldName].optional){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction:rawDestructor}]})};var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var attachFinalizer=handle=>{if(!globalThis.FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var init_ClassHandle=()=>{let proto=ClassHandle.prototype;Object.assign(proto,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}});const symbolDispose=Symbol.dispose;if(symbolDispose){proto[symbolDispose]=proto["delete"]}};function ClassHandle(){}var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var registeredPointers={};var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupported sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this.toWireType=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this.toWireType=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this.toWireType=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=AsciiToString(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError(`Use 'new' to construct ${name}`)}if(undefined===registeredClass.constructor_body){throw new BindingError(`${name} has no accessible constructor`)}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync){var needsDestructorStack=usesDestructorStack(argTypes);var argCount=argTypes.length-2;var argsList=[];var argsListWired=["fn"];if(isClassMethodFunc){argsListWired.push("thisWired")}for(var i=0;i<argCount;++i){argsList.push(`arg${i}`);argsListWired.push(`arg${i}Wired`)}argsList=argsList.join(",");argsListWired=argsListWired.join(",");var invokerFnBody=`return function (${argsList}) {\n`;if(needsDestructorStack){invokerFnBody+="var destructors = [];\n"}var dtorStack=needsDestructorStack?"destructors":"null";var args1=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];if(isClassMethodFunc){invokerFnBody+=`var thisWired = toClassParamWire(${dtorStack}, this);\n`}for(var i=0;i<argCount;++i){var argName=`toArg${i}Wire`;invokerFnBody+=`var arg${i}Wired = ${argName}(${dtorStack}, arg${i});\n`;args1.push(argName)}invokerFnBody+=(returns||isAsync?"var rv = ":"")+`invoker(${argsListWired});\n`;if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;++i){var paramName=i===1?"thisWired":"arg"+(i-2)+"Wired";if(argTypes[i].destructorFunction!==null){invokerFnBody+=`${paramName}_dtor(${paramName});\n`;args1.push(`${paramName}_dtor`)}}}if(returns){invokerFnBody+="var ret = fromRetWire(rv);\n"+"return ret;\n"}else{}invokerFnBody+="}\n";return new Function(args1,invokerFnBody)}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=!argTypes[0].isVoid;var retType=argTypes[0];var instType=argTypes[1];var closureArgs=[humanName,throwBindingError,cppInvokerFunc,cppTargetFunc,runDestructors,retType.fromWireType.bind(retType),instType?.toWireType.bind(instType)];for(var i=2;i<argCount;++i){var argType=argTypes[i];closureArgs.push(argType.toWireType.bind(argType))}if(!needsDestructorStack){for(var i=isClassMethodFunc?1:2;i<argTypes.length;++i){if(argTypes[i].destructorFunction!==null){closureArgs.push(argTypes[i].destructorFunction)}}}let invokerFactory=createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync);var invokerFn=invokerFactory(...closureArgs);return createNamedFunction(humanName,invokerFn)}var __embind_register_class_constructor=(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync,isNonnullReturn)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=AsciiToString(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker,isAsync);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var enumReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?function(pointer){return this.fromWireType(HEAP8[pointer])}:function(pointer){return this.fromWireType(HEAPU8[pointer])};case 2:return signed?function(pointer){return this.fromWireType(HEAP16[pointer>>1])}:function(pointer){return this.fromWireType(HEAPU16[pointer>>1])};case 4:return signed?function(pointer){return this.fromWireType(HEAP32[pointer>>2])}:function(pointer){return this.fromWireType(HEAPU32[pointer>>2])};default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};function getEnumValueType(rawValueType){return rawValueType===0?"object":rawValueType===1?"number":"string"}var __embind_register_enum=(rawType,name,size,isSigned,rawValueType)=>{name=AsciiToString(name);const valueType=getEnumValueType(rawValueType);switch(valueType){case"object":{function ctor(){}ctor.values={};registerType(rawType,{name,constructor:ctor,valueType,fromWireType:function(c){return this.constructor.values[c]},toWireType:(destructors,c)=>c.value,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor);break}case"number":{var keysMap={};registerType(rawType,{name,keysMap,valueType,fromWireType:c=>c,toWireType:(destructors,c)=>c,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}case"string":{var valuesMap={};var reverseMap={};var keysMap={};registerType(rawType,{name,valuesMap,reverseMap,keysMap,valueType,fromWireType:function(c){return this.reverseMap[c]},toWireType:function(destructors,c){return this.valuesMap[c]},readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}}};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var __embind_register_enum_value=(rawEnumType,name,enumValue)=>{var enumType=requireRegisteredType(rawEnumType,"enum");name=AsciiToString(name);switch(enumType.valueType){case"object":{var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(`${enumType.name}_${name}`,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value;break}case"number":{enumType.keysMap[name]=enumValue;break}case"string":{enumType.valuesMap[name]=enumValue;enumType.reverseMap[enumValue]=name;enumType.keysMap[name]=name;break}}};var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var installIndexedIterator=(proto,sizeMethodName,getMethodName)=>{const makeIterator=(size,getValue)=>{let index=0;return{next(){if(index>=size){return{done:true}}const current=index;index++;const value=getValue(current);return{value,done:false}},[Symbol.iterator](){return this}}};if(!proto[Symbol.iterator]){proto[Symbol.iterator]=function(){const size=this[sizeMethodName]();return makeIterator(size,i=>this[getMethodName](i))}}};var __embind_register_iterable=(rawClassType,rawElementType,sizeMethodName,getMethodName)=>{sizeMethodName=AsciiToString(sizeMethodName);getMethodName=AsciiToString(getMethodName);whenDependentTypesAreResolved([],[rawClassType,rawElementType],types=>{const classType=types[0];installIndexedIterator(classType.registeredClass.instancePrototype,sizeMethodName,getMethodName);return[]})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var EmValOptionalType=Object.assign({optional:true},EmValType);var __embind_register_optional=(rawOptionalType,rawType)=>{registerType(rawOptionalType,EmValOptionalType)};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_value_object=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{structRegistrations[rawType]={name:AsciiToString(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}};var __embind_register_value_object_field=(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{structRegistrations[structType].fields.push({fieldName:AsciiToString(fieldName),getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext,setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`)}return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=(argCount,argTypesPtr,kind)=>{var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var captures={toValue:Emval.toValue};var args=argFromPtr.map((argFromPtr,i)=>{var captureName=`argFromPtr${i}`;captures[captureName]=argFromPtr;return`${captureName}(args${i?"+"+i*GenericWireTypeSize:""})`});var functionBody;switch(kind){case 0:functionBody="toValue(handle)";break;case 2:functionBody="new (toValue(handle))";break;case 3:functionBody="";break;case 1:captures["getStringOrSymbol"]=getStringOrSymbol;functionBody="toValue(handle)[getStringOrSymbol(methodName)]";break}functionBody+=`(${args})`;if(!retType.isVoid){captures["toReturnWire"]=toReturnWire;captures["emval_returnValue"]=emval_returnValue;functionBody=`return emval_returnValue(toReturnWire, destructorsRef, ${functionBody})`}functionBody=`return function (handle, methodName, destructorsRef, args) {\n${functionBody}\n}`;var invokerFunction=new Function(Object.keys(captures),functionBody)(...Object.values(captures));var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_invoke=(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args);var __emval_new_array=()=>Emval.toHandle([]);var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var __emval_new_object=()=>Emval.toHandle({});var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var GLctx;var webgl_enable_ANGLE_instanced_arrays=ctx=>{var ext=ctx.getExtension("ANGLE_instanced_arrays");if(ext){ctx["vertexAttribDivisor"]=(index,divisor)=>ext["vertexAttribDivisorANGLE"](index,divisor);ctx["drawArraysInstanced"]=(mode,first,count,primcount)=>ext["drawArraysInstancedANGLE"](mode,first,count,primcount);ctx["drawElementsInstanced"]=(mode,count,type,indices,primcount)=>ext["drawElementsInstancedANGLE"](mode,count,type,indices,primcount);return 1}};var webgl_enable_OES_vertex_array_object=ctx=>{var ext=ctx.getExtension("OES_vertex_array_object");if(ext){ctx["createVertexArray"]=()=>ext["createVertexArrayOES"]();ctx["deleteVertexArray"]=vao=>ext["deleteVertexArrayOES"](vao);ctx["bindVertexArray"]=vao=>ext["bindVertexArrayOES"](vao);ctx["isVertexArray"]=vao=>ext["isVertexArrayOES"](vao);return 1}};var webgl_enable_WEBGL_draw_buffers=ctx=>{var ext=ctx.getExtension("WEBGL_draw_buffers");if(ext){ctx["drawBuffers"]=(n,bufs)=>ext["drawBuffersWEBGL"](n,bufs);return 1}};var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.dibvbi=ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.mdibvbi=ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));var webgl_enable_EXT_polygon_offset_clamp=ctx=>!!(ctx.extPolygonOffsetClamp=ctx.getExtension("EXT_polygon_offset_clamp"));var webgl_enable_EXT_clip_control=ctx=>!!(ctx.extClipControl=ctx.getExtension("EXT_clip_control"));var webgl_enable_WEBGL_polygon_mode=ctx=>!!(ctx.webglPolygonMode=ctx.getExtension("WEBGL_polygon_mode"));var webgl_enable_WEBGL_multi_draw=ctx=>!!(ctx.multiDrawWebgl=ctx.getExtension("WEBGL_multi_draw"));var getEmscriptenSupportedExtensions=ctx=>{var supportedExtensions=["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_disjoint_timer_query","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_depth_texture","WEBGL_draw_buffers","EXT_color_buffer_float","EXT_conservative_depth","EXT_disjoint_timer_query_webgl2","EXT_texture_norm16","NV_shader_noperspective_interpolation","WEBGL_clip_cull_distance","EXT_clip_control","EXT_color_buffer_half_float","EXT_depth_clamp","EXT_float_blend","EXT_polygon_offset_clamp","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","KHR_parallel_shader_compile","OES_texture_float_linear","WEBGL_blend_func_extended","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_multi_draw","WEBGL_polygon_mode"];return(ctx.getSupportedExtensions()||[]).filter(ext=>supportedExtensions.includes(ext))};var registerPreMainLoop=f=>{typeof MainLoop!="undefined"&&MainLoop.preMainLoop.push(f)};var GL={counter:1,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:[],offscreenCanvases:{},queries:[],samplers:[],transformFeedbacks:[],syncs:[],byteSizeByTypeRoot:5120,byteSizeByType:[1,1,2,2,4,4,4,2,3,4,8],stringCache:{},stringiCache:{},unpackAlignment:4,unpackRowLength:0,recordError:errorCode=>{if(!GL.lastError){GL.lastError=errorCode}},getNewId:table=>{var ret=GL.counter++;for(var i=table.length;i<ret;i++){table[i]=null}while(table[ret]){ret=GL.counter++}return ret},genObject:(n,buffers,createFunction,objectTable)=>{for(var i=0;i<n;i++){var buffer=GLctx[createFunction]();var id=buffer&&GL.getNewId(objectTable);if(buffer){buffer.name=id;objectTable[id]=buffer}else{GL.recordError(1282)}HEAP32[buffers+i*4>>2]=id}},MAX_TEMP_BUFFER_SIZE:2097152,numTempVertexBuffersPerSize:64,log2ceilLookup:i=>32-Math.clz32(i===0?0:i-1),generateTempBuffers:(quads,context)=>{var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);context.tempVertexBufferCounters1=[];context.tempVertexBufferCounters2=[];context.tempVertexBufferCounters1.length=context.tempVertexBufferCounters2.length=largestIndex+1;context.tempVertexBuffers1=[];context.tempVertexBuffers2=[];context.tempVertexBuffers1.length=context.tempVertexBuffers2.length=largestIndex+1;context.tempIndexBuffers=[];context.tempIndexBuffers.length=largestIndex+1;for(var i=0;i<=largestIndex;++i){context.tempIndexBuffers[i]=null;context.tempVertexBufferCounters1[i]=context.tempVertexBufferCounters2[i]=0;var ringbufferLength=GL.numTempVertexBuffersPerSize;context.tempVertexBuffers1[i]=[];context.tempVertexBuffers2[i]=[];var ringbuffer1=context.tempVertexBuffers1[i];var ringbuffer2=context.tempVertexBuffers2[i];ringbuffer1.length=ringbuffer2.length=ringbufferLength;for(var j=0;j<ringbufferLength;++j){ringbuffer1[j]=ringbuffer2[j]=null}}if(quads){context.tempQuadIndexBuffer=GLctx.createBuffer();context.GLctx.bindBuffer(34963,context.tempQuadIndexBuffer);var numIndexes=GL.MAX_TEMP_BUFFER_SIZE>>1;var quadIndexes=new Uint16Array(numIndexes);var i=0,v=0;while(1){quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+1;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v+3;if(i>=numIndexes)break;v+=4}context.GLctx.bufferData(34963,quadIndexes,35044);context.GLctx.bindBuffer(34963,null)}},getTempVertexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ringbuffer=GL.currentContext.tempVertexBuffers1[idx];var nextFreeBufferIndex=GL.currentContext.tempVertexBufferCounters1[idx];GL.currentContext.tempVertexBufferCounters1[idx]=GL.currentContext.tempVertexBufferCounters1[idx]+1&GL.numTempVertexBuffersPerSize-1;var vbo=ringbuffer[nextFreeBufferIndex];if(vbo){return vbo}var prevVBO=GLctx.getParameter(34964);ringbuffer[nextFreeBufferIndex]=GLctx.createBuffer();GLctx.bindBuffer(34962,ringbuffer[nextFreeBufferIndex]);GLctx.bufferData(34962,1<<idx,35048);GLctx.bindBuffer(34962,prevVBO);return ringbuffer[nextFreeBufferIndex]},getTempIndexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ibo=GL.currentContext.tempIndexBuffers[idx];if(ibo){return ibo}var prevIBO=GLctx.getParameter(34965);GL.currentContext.tempIndexBuffers[idx]=GLctx.createBuffer();GLctx.bindBuffer(34963,GL.currentContext.tempIndexBuffers[idx]);GLctx.bufferData(34963,1<<idx,35048);GLctx.bindBuffer(34963,prevIBO);return GL.currentContext.tempIndexBuffers[idx]},newRenderingFrameStarted:()=>{if(!GL.currentContext){return}var vb=GL.currentContext.tempVertexBuffers1;GL.currentContext.tempVertexBuffers1=GL.currentContext.tempVertexBuffers2;GL.currentContext.tempVertexBuffers2=vb;vb=GL.currentContext.tempVertexBufferCounters1;GL.currentContext.tempVertexBufferCounters1=GL.currentContext.tempVertexBufferCounters2;GL.currentContext.tempVertexBufferCounters2=vb;var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);for(var i=0;i<=largestIndex;++i){GL.currentContext.tempVertexBufferCounters1[i]=0}},getSource:(shader,count,string,length)=>{var source="";for(var i=0;i<count;++i){var len=length?HEAPU32[length+i*4>>2]:undefined;source+=UTF8ToString(HEAPU32[string+i*4>>2],len)}return source},calcBufLength:(size,type,stride,count)=>{if(stride>0){return count*stride}var typeSize=GL.byteSizeByType[type-GL.byteSizeByTypeRoot];return size*typeSize*count},usedTempBuffers:[],preDrawHandleClientVertexAttribBindings:count=>{GL.resetBufferBinding=false;for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(!cb.clientside||!cb.enabled)continue;GL.resetBufferBinding=true;var size=GL.calcBufLength(cb.size,cb.type,cb.stride,count);var buf=GL.getTempVertexBuffer(size);GLctx.bindBuffer(34962,buf);GLctx.bufferSubData(34962,0,HEAPU8.subarray(cb.ptr,cb.ptr+size));cb.vertexAttribPointerAdaptor.call(GLctx,i,cb.size,cb.type,cb.normalized,cb.stride,0)}},postDrawHandleClientVertexAttribBindings:()=>{if(GL.resetBufferBinding){GLctx.bindBuffer(34962,GL.buffers[GLctx.currentArrayBufferBinding])}},createContext:(canvas,webGLContextAttributes)=>{if(!canvas.getContextSafariWebGL2Fixed){canvas.getContextSafariWebGL2Fixed=canvas.getContext;function fixedGetContext(ver,attrs){var gl=canvas.getContextSafariWebGL2Fixed(ver,attrs);return ver=="webgl"==gl instanceof WebGLRenderingContext?gl:null}canvas.getContext=fixedGetContext}var ctx=webGLContextAttributes.majorVersion>1?canvas.getContext("webgl2",webGLContextAttributes):canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:(ctx,webGLContextAttributes)=>{var handle=GL.getNewId(GL.contexts);var context={handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault=="undefined"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}context.maxVertexAttribs=context.GLctx.getParameter(34921);context.clientBuffers=[];for(var i=0;i<context.maxVertexAttribs;i++){context.clientBuffers[i]={enabled:false,clientside:false,size:0,type:0,normalized:0,stride:0,ptr:0,vertexAttribPointerAdaptor:null}}GL.generateTempBuffers(false,context);return handle},makeContextCurrent:contextHandle=>{GL.currentContext=GL.contexts[contextHandle];Module["ctx"]=GLctx=GL.currentContext?.GLctx;return!(contextHandle&&!GLctx)},getContext:contextHandle=>GL.contexts[contextHandle],deleteContext:contextHandle=>{if(GL.currentContext===GL.contexts[contextHandle]){GL.currentContext=null}if(typeof JSEvents=="object"){JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas)}if(GL.contexts[contextHandle]?.GLctx.canvas){GL.contexts[contextHandle].GLctx.canvas.GLctxObject=undefined}GL.contexts[contextHandle]=null},initExtensions:context=>{context||=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx=context.GLctx;webgl_enable_WEBGL_multi_draw(GLctx);webgl_enable_EXT_polygon_offset_clamp(GLctx);webgl_enable_EXT_clip_control(GLctx);webgl_enable_WEBGL_polygon_mode(GLctx);webgl_enable_ANGLE_instanced_arrays(GLctx);webgl_enable_OES_vertex_array_object(GLctx);webgl_enable_WEBGL_draw_buffers(GLctx);webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);if(context.version>=2){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query_webgl2")}if(context.version<2||!GLctx.disjointTimerQueryExt){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query")}for(var ext of getEmscriptenSupportedExtensions(GLctx)){if(!ext.includes("lose_context")&&!ext.includes("debug")){GLctx.getExtension(ext)}}}};var webglPowerPreferences=["default","low-power","high-performance"];var maybeCStringToJsString=cString=>cString>2?UTF8ToString(cString):cString;var specialHTMLTargets=[0,globalThis.document??0,globalThis.window??0];var findEventTarget=target=>{target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||globalThis.document?.querySelector(target);return domElement};var findCanvasEventTarget=findEventTarget;var _emscripten_webgl_do_create_context=(target,attributes)=>{var attr32=attributes>>2;var powerPreference=HEAP32[attr32+(8>>2)];var contextAttributes={alpha:!!HEAP8[attributes+0],depth:!!HEAP8[attributes+1],stencil:!!HEAP8[attributes+2],antialias:!!HEAP8[attributes+3],premultipliedAlpha:!!HEAP8[attributes+4],preserveDrawingBuffer:!!HEAP8[attributes+5],powerPreference:webglPowerPreferences[powerPreference],failIfMajorPerformanceCaveat:!!HEAP8[attributes+12],majorVersion:HEAP32[attr32+(16>>2)],minorVersion:HEAP32[attr32+(20>>2)],enableExtensionsByDefault:HEAP8[attributes+24],explicitSwapControl:HEAP8[attributes+25],proxyContextToMainThread:HEAP32[attr32+(28>>2)],renderViaOffscreenBackBuffer:HEAP8[attributes+32]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle};var _emscripten_webgl_create_context=_emscripten_webgl_do_create_context;var _emscripten_webgl_destroy_context=contextHandle=>{if(GL.currentContext==contextHandle)GL.currentContext=0;GL.deleteContext(contextHandle)};var _emscripten_webgl_make_context_current=contextHandle=>{var success=GL.makeContextCurrent(contextHandle);return success?0:-5};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _emscripten_glActiveTexture=x0=>GLctx.activeTexture(x0);var _glActiveTexture=_emscripten_glActiveTexture;var _emscripten_glAttachShader=(program,shader)=>{GLctx.attachShader(GL.programs[program],GL.shaders[shader])};var _glAttachShader=_emscripten_glAttachShader;var _emscripten_glBindAttribLocation=(program,index,name)=>{GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))};var _glBindAttribLocation=_emscripten_glBindAttribLocation;var _emscripten_glBindBuffer=(target,buffer)=>{if(buffer&&!GL.buffers[buffer]){var b=GLctx.createBuffer();b.name=buffer;GL.buffers[buffer]=b}if(target==34962){GLctx.currentArrayBufferBinding=buffer}else if(target==34963){GLctx.currentElementArrayBufferBinding=buffer}if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])};var _glBindBuffer=_emscripten_glBindBuffer;var _emscripten_glBindFramebuffer=(target,framebuffer)=>{GLctx.bindFramebuffer(target,GL.framebuffers[framebuffer])};var _glBindFramebuffer=_emscripten_glBindFramebuffer;var _emscripten_glBindTexture=(target,texture)=>{GLctx.bindTexture(target,GL.textures[texture])};var _glBindTexture=_emscripten_glBindTexture;var _emscripten_glBindVertexArray=vao=>{GLctx.bindVertexArray(GL.vaos[vao]);var ibo=GLctx.getParameter(34965);GLctx.currentElementArrayBufferBinding=ibo?ibo.name|0:0};var _glBindVertexArray=_emscripten_glBindVertexArray;var _emscripten_glBlendFunc=(x0,x1)=>GLctx.blendFunc(x0,x1);var _glBlendFunc=_emscripten_glBlendFunc;var _emscripten_glBlendFuncSeparate=(x0,x1,x2,x3)=>GLctx.blendFuncSeparate(x0,x1,x2,x3);var _glBlendFuncSeparate=_emscripten_glBlendFuncSeparate;var _emscripten_glBufferData=(target,size,data,usage)=>{if(GL.currentContext.version>=2){if(data&&size){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}return}GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)};var _glBufferData=_emscripten_glBufferData;var _emscripten_glBufferSubData=(target,offset,size,data)=>{if(GL.currentContext.version>=2){size&&GLctx.bufferSubData(target,offset,HEAPU8,data,size);return}GLctx.bufferSubData(target,offset,HEAPU8.subarray(data,data+size))};var _glBufferSubData=_emscripten_glBufferSubData;var _emscripten_glCheckFramebufferStatus=x0=>GLctx.checkFramebufferStatus(x0);var _glCheckFramebufferStatus=_emscripten_glCheckFramebufferStatus;var _emscripten_glClear=x0=>GLctx.clear(x0);var _glClear=_emscripten_glClear;var _emscripten_glClearColor=(x0,x1,x2,x3)=>GLctx.clearColor(x0,x1,x2,x3);var _glClearColor=_emscripten_glClearColor;var _emscripten_glClearStencil=x0=>GLctx.clearStencil(x0);var _glClearStencil=_emscripten_glClearStencil;var _emscripten_glColorMask=(red,green,blue,alpha)=>{GLctx.colorMask(!!red,!!green,!!blue,!!alpha)};var _glColorMask=_emscripten_glColorMask;var _emscripten_glCompileShader=shader=>{GLctx.compileShader(GL.shaders[shader])};var _glCompileShader=_emscripten_glCompileShader;var _emscripten_glCreateProgram=()=>{var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id};var _glCreateProgram=_emscripten_glCreateProgram;var _emscripten_glCreateShader=shaderType=>{var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);return id};var _glCreateShader=_emscripten_glCreateShader;var _emscripten_glDeleteBuffers=(n,buffers)=>{for(var i=0;i<n;i++){var id=HEAP32[buffers+i*4>>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentArrayBufferBinding)GLctx.currentArrayBufferBinding=0;if(id==GLctx.currentElementArrayBufferBinding)GLctx.currentElementArrayBufferBinding=0;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}};var _glDeleteBuffers=_emscripten_glDeleteBuffers;var _emscripten_glDeleteFramebuffers=(n,framebuffers)=>{for(var i=0;i<n;++i){var id=HEAP32[framebuffers+i*4>>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}};var _glDeleteFramebuffers=_emscripten_glDeleteFramebuffers;var _emscripten_glDeleteProgram=id=>{if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null};var _glDeleteProgram=_emscripten_glDeleteProgram;var _emscripten_glDeleteShader=id=>{if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null};var _glDeleteShader=_emscripten_glDeleteShader;var _emscripten_glDeleteTextures=(n,textures)=>{for(var i=0;i<n;i++){var id=HEAP32[textures+i*4>>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}};var _glDeleteTextures=_emscripten_glDeleteTextures;var _emscripten_glDeleteVertexArrays=(n,vaos)=>{for(var i=0;i<n;i++){var id=HEAP32[vaos+i*4>>2];GLctx.deleteVertexArray(GL.vaos[id]);GL.vaos[id]=null}};var _glDeleteVertexArrays=_emscripten_glDeleteVertexArrays;var _emscripten_glDepthMask=flag=>{GLctx.depthMask(!!flag)};var _glDepthMask=_emscripten_glDepthMask;var _emscripten_glDisable=x0=>GLctx.disable(x0);var _glDisable=_emscripten_glDisable;var _emscripten_glDrawArrays=(mode,first,count)=>{GL.preDrawHandleClientVertexAttribBindings(first+count);GLctx.drawArrays(mode,first,count);GL.postDrawHandleClientVertexAttribBindings()};var _glDrawArrays=_emscripten_glDrawArrays;var _emscripten_glDrawElements=(mode,count,type,indices)=>{var buf;var vertexes=0;if(!GLctx.currentElementArrayBufferBinding){var size=GL.calcBufLength(1,type,0,count);buf=GL.getTempIndexBuffer(size);GLctx.bindBuffer(34963,buf);GLctx.bufferSubData(34963,0,HEAPU8.subarray(indices,indices+size));if(count>0){for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(cb.clientside&&cb.enabled){let arrayClass;switch(type){case 5121:arrayClass=Uint8Array;break;case 5123:arrayClass=Uint16Array;break;case 5125:arrayClass=Uint32Array;break;default:GL.recordError(1282);return}vertexes=new arrayClass(HEAPU8.buffer,indices,count).reduce((max,current)=>Math.max(max,current))+1;break}}}indices=0}GL.preDrawHandleClientVertexAttribBindings(vertexes);GLctx.drawElements(mode,count,type,indices);GL.postDrawHandleClientVertexAttribBindings(count);if(!GLctx.currentElementArrayBufferBinding){GLctx.bindBuffer(34963,null)}};var _glDrawElements=_emscripten_glDrawElements;var _emscripten_glEnable=x0=>GLctx.enable(x0);var _glEnable=_emscripten_glEnable;var _emscripten_glEnableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=true;GLctx.enableVertexAttribArray(index)};var _glEnableVertexAttribArray=_emscripten_glEnableVertexAttribArray;var _emscripten_glFramebufferTexture2D=(target,attachment,textarget,texture,level)=>{GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)};var _glFramebufferTexture2D=_emscripten_glFramebufferTexture2D;var _emscripten_glGenBuffers=(n,buffers)=>{GL.genObject(n,buffers,"createBuffer",GL.buffers)};var _glGenBuffers=_emscripten_glGenBuffers;var _emscripten_glGenFramebuffers=(n,ids)=>{GL.genObject(n,ids,"createFramebuffer",GL.framebuffers)};var _glGenFramebuffers=_emscripten_glGenFramebuffers;var _emscripten_glGenTextures=(n,textures)=>{GL.genObject(n,textures,"createTexture",GL.textures)};var _glGenTextures=_emscripten_glGenTextures;var _emscripten_glGenVertexArrays=(n,arrays)=>{GL.genObject(n,arrays,"createVertexArray",GL.vaos)};var _glGenVertexArrays=_emscripten_glGenVertexArrays;var _emscripten_glGenerateMipmap=x0=>GLctx.generateMipmap(x0);var _glGenerateMipmap=_emscripten_glGenerateMipmap;var _emscripten_glGetError=()=>{var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error};var _glGetError=_emscripten_glGetError;var writeI53ToI64=(ptr,num)=>{HEAPU32[ptr>>2]=num;var lower=HEAPU32[ptr>>2];HEAPU32[ptr+4>>2]=(num-lower)/4294967296};var webglGetExtensions=()=>{var exts=getEmscriptenSupportedExtensions(GLctx);exts=exts.concat(exts.map(e=>"GL_"+e));return exts};var emscriptenWebGLGet=(name_,p,type)=>{if(!p){GL.recordError(1281);return}var ret=undefined;switch(name_){case 36346:ret=1;break;case 36344:if(type!=0&&type!=1){GL.recordError(1280)}return;case 34814:case 36345:ret=0;break;case 34466:var formats=GLctx.getParameter(34467);ret=formats?formats.length:0;break;case 33309:if(GL.currentContext.version<2){GL.recordError(1282);return}ret=webglGetExtensions().length;break;case 33307:case 33308:if(GL.currentContext.version<2){GL.recordError(1280);return}ret=name_==33307?3:0;break}if(ret===undefined){var result=GLctx.getParameter(name_);switch(typeof result){case"number":ret=result;break;case"boolean":ret=result?1:0;break;case"string":GL.recordError(1280);return;case"object":if(result===null){switch(name_){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:{ret=0;break}default:{GL.recordError(1280);return}}}else if(result instanceof Float32Array||result instanceof Uint32Array||result instanceof Int32Array||result instanceof Array){for(var i=0;i<result.length;++i){switch(type){case 0:HEAP32[p+i*4>>2]=result[i];break;case 2:HEAPF32[p+i*4>>2]=result[i];break;case 4:HEAP8[p+i]=result[i]?1:0;break}}return}else{try{ret=result.name|0}catch(e){GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);return}}break;default:GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof result}!`);return}}switch(type){case 1:writeI53ToI64(p,ret);break;case 0:HEAP32[p>>2]=ret;break;case 2:HEAPF32[p>>2]=ret;break;case 4:HEAP8[p]=ret?1:0;break}};var _emscripten_glGetIntegerv=(name_,p)=>emscriptenWebGLGet(name_,p,0);var _glGetIntegerv=_emscripten_glGetIntegerv;var _emscripten_glGetProgramInfoLog=(program,maxLength,length,infoLog)=>{var log=GLctx.getProgramInfoLog(GL.programs[program]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetProgramInfoLog=_emscripten_glGetProgramInfoLog;var _emscripten_glGetProgramiv=(program,pname,p)=>{if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(var i=0;i<numActiveUniforms;++i){program.maxUniformLength=Math.max(program.maxUniformLength,GLctx.getActiveUniform(program,i).name.length+1)}}HEAP32[p>>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){var numActiveAttributes=GLctx.getProgramParameter(program,35721);for(var i=0;i<numActiveAttributes;++i){program.maxAttributeLength=Math.max(program.maxAttributeLength,GLctx.getActiveAttrib(program,i).name.length+1)}}HEAP32[p>>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){var numActiveUniformBlocks=GLctx.getProgramParameter(program,35382);for(var i=0;i<numActiveUniformBlocks;++i){program.maxUniformBlockNameLength=Math.max(program.maxUniformBlockNameLength,GLctx.getActiveUniformBlockName(program,i).length+1)}}HEAP32[p>>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}};var _glGetProgramiv=_emscripten_glGetProgramiv;var _emscripten_glGetShaderInfoLog=(shader,maxLength,length,infoLog)=>{var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetShaderInfoLog=_emscripten_glGetShaderInfoLog;var _emscripten_glGetShaderiv=(shader,pname,p)=>{if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}};var _glGetShaderiv=_emscripten_glGetShaderiv;var stringToNewUTF8=str=>{var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8(str,ret,size);return ret};var _emscripten_glGetString=name_=>{var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:ret=stringToNewUTF8(webglGetExtensions().join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s?stringToNewUTF8(s):0;break;case 7938:var webGLVersion=GLctx.getParameter(7938);var glVersion=`OpenGL ES 2.0 (${webGLVersion})`;if(GL.currentContext.version>=2)glVersion=`OpenGL ES 3.0 (${webGLVersion})`;ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion=`OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret};var _glGetString=_emscripten_glGetString;var jstoi_q=str=>parseInt(str);var webglGetLeftBracePos=name=>name.slice(-1)=="]"&&name.lastIndexOf("[");var webglPrepareUniformLocationsBeforeFirstUse=program=>{var uniformLocsById=program.uniformLocsById,uniformSizeAndIdsByName=program.uniformSizeAndIdsByName,i,j;if(!uniformLocsById){program.uniformLocsById=uniformLocsById={};program.uniformArrayNamesById={};var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(i=0;i<numActiveUniforms;++i){var u=GLctx.getActiveUniform(program,i);var nm=u.name;var sz=u.size;var lb=webglGetLeftBracePos(nm);var arrayName=lb>0?nm.slice(0,lb):nm;var id=program.uniformIdCounter;program.uniformIdCounter+=sz;uniformSizeAndIdsByName[arrayName]=[sz,id];for(j=0;j<sz;++j){uniformLocsById[id]=j;program.uniformArrayNamesById[id++]=arrayName}}}};var _emscripten_glGetUniformLocation=(program,name)=>{name=UTF8ToString(name);if(program=GL.programs[program]){webglPrepareUniformLocationsBeforeFirstUse(program);var uniformLocsById=program.uniformLocsById;var arrayIndex=0;var uniformBaseName=name;var leftBrace=webglGetLeftBracePos(name);if(leftBrace>0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=program.uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex<sizeAndId[0]){arrayIndex+=sizeAndId[1];if(uniformLocsById[arrayIndex]=uniformLocsById[arrayIndex]||GLctx.getUniformLocation(program,name)){return arrayIndex}}}else{GL.recordError(1281)}return-1};var _glGetUniformLocation=_emscripten_glGetUniformLocation;var _emscripten_glLinkProgram=program=>{program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={}};var _glLinkProgram=_emscripten_glLinkProgram;var _emscripten_glPixelStorei=(pname,param)=>{if(pname==3317){GL.unpackAlignment=param}else if(pname==3314){GL.unpackRowLength=param}GLctx.pixelStorei(pname,param)};var _glPixelStorei=_emscripten_glPixelStorei;var computeUnpackAlignedImageSize=(width,height,sizePerPixel)=>{function roundedToNextMultipleOf(x,y){return x+y-1&-y}var plainRowSize=(GL.unpackRowLength||width)*sizePerPixel;var alignedRowSize=roundedToNextMultipleOf(plainRowSize,GL.unpackAlignment);return height*alignedRowSize};var colorChannelsInGlTextureFormat=format=>{var colorChannels={5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4};return colorChannels[format-6402]||1};var heapObjectForWebGLType=type=>{type-=5120;if(type==0)return HEAP8;if(type==1)return HEAPU8;if(type==2)return HEAP16;if(type==4)return HEAP32;if(type==6)return HEAPF32;if(type==5||type==28922||type==28520||type==30779||type==30782)return HEAPU32;return HEAPU16};var toTypedArrayIndex=(pointer,heap)=>pointer>>>31-Math.clz32(heap.BYTES_PER_ELEMENT);var emscriptenWebGLGetTexPixelData=(type,format,width,height,pixels,internalFormat)=>{var heap=heapObjectForWebGLType(type);var sizePerPixel=colorChannelsInGlTextureFormat(format)*heap.BYTES_PER_ELEMENT;var bytes=computeUnpackAlignedImageSize(width,height,sizePerPixel);return heap.subarray(toTypedArrayIndex(pixels,heap),toTypedArrayIndex(pixels+bytes,heap))};var _emscripten_glReadPixels=(x,y,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelPackBufferBinding){GLctx.readPixels(x,y,width,height,format,type,pixels);return}var heap=heapObjectForWebGLType(type);var target=toTypedArrayIndex(pixels,heap);GLctx.readPixels(x,y,width,height,format,type,heap,target);return}var pixelData=emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,format);if(!pixelData){GL.recordError(1280);return}GLctx.readPixels(x,y,width,height,format,type,pixelData)};var _glReadPixels=_emscripten_glReadPixels;var _emscripten_glScissor=(x0,x1,x2,x3)=>GLctx.scissor(x0,x1,x2,x3);var _glScissor=_emscripten_glScissor;var _emscripten_glShaderSource=(shader,count,string,length)=>{var source=GL.getSource(shader,count,string,length);GLctx.shaderSource(GL.shaders[shader],source)};var _glShaderSource=_emscripten_glShaderSource;var _emscripten_glStencilFunc=(x0,x1,x2)=>GLctx.stencilFunc(x0,x1,x2);var _glStencilFunc=_emscripten_glStencilFunc;var _emscripten_glStencilMask=x0=>GLctx.stencilMask(x0);var _glStencilMask=_emscripten_glStencilMask;var _emscripten_glStencilOp=(x0,x1,x2)=>GLctx.stencilOp(x0,x1,x2);var _glStencilOp=_emscripten_glStencilOp;var _emscripten_glTexImage2D=(target,level,internalFormat,width,height,border,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);var index=toTypedArrayIndex(pixels,heap);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,index);return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null;GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixelData)};var _glTexImage2D=_emscripten_glTexImage2D;var _emscripten_glTexParameteri=(x0,x1,x2)=>GLctx.texParameteri(x0,x1,x2);var _glTexParameteri=_emscripten_glTexParameteri;var _emscripten_glTexSubImage2D=(target,level,xoffset,yoffset,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,toTypedArrayIndex(pixels,heap));return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0):null;GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)};var _glTexSubImage2D=_emscripten_glTexSubImage2D;var webglGetUniformLocation=location=>{var p=GLctx.currentProgram;if(p){var webglLoc=p.uniformLocsById[location];if(typeof webglLoc=="number"){p.uniformLocsById[location]=webglLoc=GLctx.getUniformLocation(p,p.uniformArrayNamesById[location]+(webglLoc>0?`[${webglLoc}]`:""))}return webglLoc}else{GL.recordError(1282)}};var _emscripten_glUniform1f=(location,v0)=>{GLctx.uniform1f(webglGetUniformLocation(location),v0)};var _glUniform1f=_emscripten_glUniform1f;var _emscripten_glUniform1i=(location,v0)=>{GLctx.uniform1i(webglGetUniformLocation(location),v0)};var _glUniform1i=_emscripten_glUniform1i;var _emscripten_glUniform2f=(location,v0,v1)=>{GLctx.uniform2f(webglGetUniformLocation(location),v0,v1)};var _glUniform2f=_emscripten_glUniform2f;var _emscripten_glUniform3f=(location,v0,v1,v2)=>{GLctx.uniform3f(webglGetUniformLocation(location),v0,v1,v2)};var _glUniform3f=_emscripten_glUniform3f;var _emscripten_glUniform4f=(location,v0,v1,v2,v3)=>{GLctx.uniform4f(webglGetUniformLocation(location),v0,v1,v2,v3)};var _glUniform4f=_emscripten_glUniform4f;var miniTempWebGLFloatBuffers=[];var _emscripten_glUniformMatrix4fv=(location,count,transpose,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count];var heap=HEAPF32;value=value>>2;count*=16;for(var i=0;i<count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)};var _glUniformMatrix4fv=_emscripten_glUniformMatrix4fv;var _emscripten_glUseProgram=program=>{program=GL.programs[program];GLctx.useProgram(program);GLctx.currentProgram=program};var _glUseProgram=_emscripten_glUseProgram;var _emscripten_glVertexAttribPointer=(index,size,type,normalized,stride,ptr)=>{var cb=GL.currentContext.clientBuffers[index];if(!GLctx.currentArrayBufferBinding){cb.size=size;cb.type=type;cb.normalized=normalized;cb.stride=stride;cb.ptr=ptr;cb.clientside=true;cb.vertexAttribPointerAdaptor=function(index,size,type,normalized,stride,ptr){this.vertexAttribPointer(index,size,type,normalized,stride,ptr)};return}cb.clientside=false;GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)};var _glVertexAttribPointer=_emscripten_glVertexAttribPointer;var _emscripten_glViewport=(x0,x1,x2,x3)=>GLctx.viewport(x0,x1,x2,x3);var _glViewport=_emscripten_glViewport;var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var updateTableMap=(offset,count)=>{if(functionsInTableMap){for(var i=offset;i<offset+count;i++){var item=getWasmTableEntry(i);if(item){functionsInTableMap.set(item,i)}}}};var functionsInTableMap;var getFunctionAddress=func=>{if(!functionsInTableMap){functionsInTableMap=new WeakMap;updateTableMap(0,wasmTable.length)}return functionsInTableMap.get(func)||0};var freeTableIndexes=[];var getEmptyTableSlot=()=>{if(freeTableIndexes.length){return freeTableIndexes.pop()}return wasmTable["grow"](1)};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var uleb128EncodeWithLen=arr=>{const n=arr.length;return[n%128|128,n>>7,...arr]};var wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111};var generateTypePack=types=>uleb128EncodeWithLen(Array.from(types,type=>{var code=wasmTypeCodes[type];return code}));var convertJsFunctionToWasm=(func,sig)=>{var bytes=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(sig.slice(1)),...generateTypePack(sig[0]==="v"?"":sig[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};var addFunction=(func,sig)=>{var rtn=getFunctionAddress(func);if(rtn){return rtn}var ret=getEmptyTableSlot();try{setWasmTableEntry(ret,func)}catch(err){if(!(err instanceof TypeError)){throw err}var wrapped=convertJsFunctionToWasm(func,sig);setWasmTableEntry(ret,wrapped)}functionsInTableMap.set(func,ret);return ret};var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();init_ClassHandle();init_RegisteredPointer();registerPreMainLoop(()=>GL.newRenderingFrameStarted());var miniTempWebGLFloatBuffersStorage=new Float32Array(288);for(var i=0;i<=288;++i){miniTempWebGLFloatBuffers[i]=miniTempWebGLFloatBuffersStorage.subarray(0,i)}{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["addFunction"]=addFunction;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;Module["GL"]=GL;var ___getTypeName,_YGNodeNew,_YGNodeStyleSetFlexDirection,_YGNodeStyleSetFlexWrap,_YGNodeStyleSetJustifyContent,_YGNodeStyleSetAlignItems,_YGNodeStyleSetWidth,_YGNodeStyleSetHeight,_YGNodeStyleSetPadding,_YGNodeStyleSetAlignContent,_YGNodeStyleSetGap,_YGNodeStyleSetFlexGrow,_YGNodeStyleSetFlexShrink,_YGNodeStyleSetFlexBasis,_YGNodeStyleSetFlexBasisAuto,_YGNodeStyleSetAlignSelf,_YGNodeStyleSetMargin,_YGNodeStyleSetMinWidth,_YGNodeStyleSetMinHeight,_YGNodeStyleSetMaxWidth,_YGNodeStyleSetMaxHeight,_YGNodeStyleSetWidthPercent,_YGNodeStyleSetHeightPercent,_YGNodeInsertChild,_YGNodeCalculateLayout,_YGNodeLayoutGetLeft,_YGNodeLayoutGetTop,_YGNodeLayoutGetWidth,_YGNodeLayoutGetHeight,_YGNodeFreeRecursive,_malloc,_free,_YGConfigNew,_YGConfigFree,_YGConfigGetDefault,_YGConfigSetUseWebDefaults,_YGConfigGetUseWebDefaults,_YGConfigSetPointScaleFactor,_YGConfigGetPointScaleFactor,_YGConfigSetErrata,_YGConfigGetErrata,_YGConfigSetLogger,_YGConfigSetContext,_YGConfigGetContext,_YGConfigSetExperimentalFeatureEnabled,_YGConfigIsExperimentalFeatureEnabled,_YGConfigSetCloneNodeFunc,_YGNodeNewWithConfig,_YGNodeClone,_YGNodeFree,_YGNodeGetConfig,_YGNodeRemoveChild,_YGNodeFinalize,_YGNodeReset,_YGNodeGetHasNewLayout,_YGNodeSetHasNewLayout,_YGNodeIsDirty,_YGNodeMarkDirty,_YGNodeSetDirtiedFunc,_YGNodeGetDirtiedFunc,_YGNodeSwapChild,_YGNodeRemoveAllChildren,_YGNodeSetChildren,_YGNodeGetChild,_YGNodeGetChildCount,_YGNodeGetOwner,_YGNodeGetParent,_YGNodeSetConfig,_YGNodeSetContext,_YGNodeGetContext,_YGNodeSetMeasureFunc,_YGNodeHasMeasureFunc,_YGNodeSetBaselineFunc,_YGNodeHasBaselineFunc,_YGNodeSetIsReferenceBaseline,_YGNodeIsReferenceBaseline,_YGNodeSetNodeType,_YGNodeGetNodeType,_YGNodeSetAlwaysFormsContainingBlock,_YGNodeGetAlwaysFormsContainingBlock,_YGNodeCanUseCachedMeasurement,_YGNodeLayoutGetRight,_YGNodeLayoutGetBottom,_YGNodeLayoutGetDirection,_YGNodeLayoutGetHadOverflow,_YGNodeLayoutGetMargin,_YGNodeLayoutGetBorder,_YGNodeLayoutGetPadding,_YGNodeLayoutGetRawHeight,_YGNodeLayoutGetRawWidth,_YGNodeCopyStyle,_YGNodeStyleSetDirection,_YGNodeStyleGetDirection,_YGNodeStyleGetFlexDirection,_YGNodeStyleGetJustifyContent,_YGNodeStyleSetJustifyItems,_YGNodeStyleGetJustifyItems,_YGNodeStyleSetJustifySelf,_YGNodeStyleGetJustifySelf,_YGNodeStyleGetAlignContent,_YGNodeStyleGetAlignItems,_YGNodeStyleGetAlignSelf,_YGNodeStyleSetPositionType,_YGNodeStyleGetPositionType,_YGNodeStyleGetFlexWrap,_YGNodeStyleSetOverflow,_YGNodeStyleGetOverflow,_YGNodeStyleSetDisplay,_YGNodeStyleGetDisplay,_YGNodeStyleSetFlex,_YGNodeStyleGetFlex,_YGNodeStyleGetFlexGrow,_YGNodeStyleGetFlexShrink,_YGNodeStyleSetFlexBasisPercent,_YGNodeStyleSetFlexBasisMaxContent,_YGNodeStyleSetFlexBasisFitContent,_YGNodeStyleSetFlexBasisStretch,_YGNodeStyleGetFlexBasis,_YGNodeStyleSetPosition,_YGNodeStyleSetPositionPercent,_YGNodeStyleSetPositionAuto,_YGNodeStyleGetPosition,_YGNodeStyleSetMarginPercent,_YGNodeStyleSetMarginAuto,_YGNodeStyleGetMargin,_YGNodeStyleSetPaddingPercent,_YGNodeStyleGetPadding,_YGNodeStyleSetBorder,_YGNodeStyleGetBorder,_YGNodeStyleSetGapPercent,_YGNodeStyleGetGap,_YGNodeStyleSetAspectRatio,_YGNodeStyleGetAspectRatio,_YGNodeStyleSetBoxSizing,_YGNodeStyleGetBoxSizing,_YGNodeStyleSetWidthAuto,_YGNodeStyleSetWidthMaxContent,_YGNodeStyleSetWidthFitContent,_YGNodeStyleSetWidthStretch,_YGNodeStyleGetWidth,_YGNodeStyleSetHeightAuto,_YGNodeStyleSetHeightMaxContent,_YGNodeStyleSetHeightFitContent,_YGNodeStyleSetHeightStretch,_YGNodeStyleGetHeight,_YGNodeStyleSetMinWidthPercent,_YGNodeStyleSetMinWidthMaxContent,_YGNodeStyleSetMinWidthFitContent,_YGNodeStyleSetMinWidthStretch,_YGNodeStyleGetMinWidth,_YGNodeStyleSetMinHeightPercent,_YGNodeStyleSetMinHeightMaxContent,_YGNodeStyleSetMinHeightFitContent,_YGNodeStyleSetMinHeightStretch,_YGNodeStyleGetMinHeight,_YGNodeStyleSetMaxWidthPercent,_YGNodeStyleSetMaxWidthMaxContent,_YGNodeStyleSetMaxWidthFitContent,_YGNodeStyleSetMaxWidthStretch,_YGNodeStyleGetMaxWidth,_YGNodeStyleSetMaxHeightPercent,_YGNodeStyleSetMaxHeightMaxContent,_YGNodeStyleSetMaxHeightFitContent,_YGNodeStyleSetMaxHeightStretch,_YGNodeStyleGetMaxHeight,_YGNodeStyleSetGridColumnStart,_YGNodeStyleSetGridColumnStartAuto,_YGNodeStyleSetGridColumnStartSpan,_YGNodeStyleGetGridColumnStart,_YGNodeStyleSetGridColumnEnd,_YGNodeStyleSetGridColumnEndAuto,_YGNodeStyleSetGridColumnEndSpan,_YGNodeStyleGetGridColumnEnd,_YGNodeStyleSetGridRowStart,_YGNodeStyleSetGridRowStartAuto,_YGNodeStyleSetGridRowStartSpan,_YGNodeStyleGetGridRowStart,_YGNodeStyleSetGridRowEnd,_YGNodeStyleSetGridRowEndAuto,_YGNodeStyleSetGridRowEndSpan,_YGNodeStyleGetGridRowEnd,_YGNodeStyleSetGridTemplateColumnsCount,_YGNodeStyleSetGridTemplateColumn,_YGNodeStyleSetGridTemplateColumnMinMax,_YGNodeStyleSetGridTemplateRowsCount,_YGNodeStyleSetGridTemplateRow,_YGNodeStyleSetGridTemplateRowMinMax,_YGNodeStyleSetGridAutoColumnsCount,_YGNodeStyleSetGridAutoColumn,_YGNodeStyleSetGridAutoColumnMinMax,_YGNodeStyleSetGridAutoRowsCount,_YGNodeStyleSetGridAutoRow,_YGNodeStyleSetGridAutoRowMinMax,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["gb"];_YGNodeNew=Module["_YGNodeNew"]=wasmExports["hb"];_YGNodeStyleSetFlexDirection=Module["_YGNodeStyleSetFlexDirection"]=wasmExports["ib"];_YGNodeStyleSetFlexWrap=Module["_YGNodeStyleSetFlexWrap"]=wasmExports["jb"];_YGNodeStyleSetJustifyContent=Module["_YGNodeStyleSetJustifyContent"]=wasmExports["kb"];_YGNodeStyleSetAlignItems=Module["_YGNodeStyleSetAlignItems"]=wasmExports["lb"];_YGNodeStyleSetWidth=Module["_YGNodeStyleSetWidth"]=wasmExports["mb"];_YGNodeStyleSetHeight=Module["_YGNodeStyleSetHeight"]=wasmExports["nb"];_YGNodeStyleSetPadding=Module["_YGNodeStyleSetPadding"]=wasmExports["ob"];_YGNodeStyleSetAlignContent=Module["_YGNodeStyleSetAlignContent"]=wasmExports["pb"];_YGNodeStyleSetGap=Module["_YGNodeStyleSetGap"]=wasmExports["qb"];_YGNodeStyleSetFlexGrow=Module["_YGNodeStyleSetFlexGrow"]=wasmExports["rb"];_YGNodeStyleSetFlexShrink=Module["_YGNodeStyleSetFlexShrink"]=wasmExports["sb"];_YGNodeStyleSetFlexBasis=Module["_YGNodeStyleSetFlexBasis"]=wasmExports["tb"];_YGNodeStyleSetFlexBasisAuto=Module["_YGNodeStyleSetFlexBasisAuto"]=wasmExports["ub"];_YGNodeStyleSetAlignSelf=Module["_YGNodeStyleSetAlignSelf"]=wasmExports["vb"];_YGNodeStyleSetMargin=Module["_YGNodeStyleSetMargin"]=wasmExports["wb"];_YGNodeStyleSetMinWidth=Module["_YGNodeStyleSetMinWidth"]=wasmExports["xb"];_YGNodeStyleSetMinHeight=Module["_YGNodeStyleSetMinHeight"]=wasmExports["yb"];_YGNodeStyleSetMaxWidth=Module["_YGNodeStyleSetMaxWidth"]=wasmExports["zb"];_YGNodeStyleSetMaxHeight=Module["_YGNodeStyleSetMaxHeight"]=wasmExports["Ab"];_YGNodeStyleSetWidthPercent=Module["_YGNodeStyleSetWidthPercent"]=wasmExports["Bb"];_YGNodeStyleSetHeightPercent=Module["_YGNodeStyleSetHeightPercent"]=wasmExports["Cb"];_YGNodeInsertChild=Module["_YGNodeInsertChild"]=wasmExports["Db"];_YGNodeCalculateLayout=Module["_YGNodeCalculateLayout"]=wasmExports["Eb"];_YGNodeLayoutGetLeft=Module["_YGNodeLayoutGetLeft"]=wasmExports["Fb"];_YGNodeLayoutGetTop=Module["_YGNodeLayoutGetTop"]=wasmExports["Gb"];_YGNodeLayoutGetWidth=Module["_YGNodeLayoutGetWidth"]=wasmExports["Hb"];_YGNodeLayoutGetHeight=Module["_YGNodeLayoutGetHeight"]=wasmExports["Ib"];_YGNodeFreeRecursive=Module["_YGNodeFreeRecursive"]=wasmExports["Jb"];_malloc=Module["_malloc"]=wasmExports["Kb"];_free=Module["_free"]=wasmExports["Lb"];_YGConfigNew=Module["_YGConfigNew"]=wasmExports["Mb"];_YGConfigFree=Module["_YGConfigFree"]=wasmExports["Nb"];_YGConfigGetDefault=Module["_YGConfigGetDefault"]=wasmExports["Ob"];_YGConfigSetUseWebDefaults=Module["_YGConfigSetUseWebDefaults"]=wasmExports["Pb"];_YGConfigGetUseWebDefaults=Module["_YGConfigGetUseWebDefaults"]=wasmExports["Qb"];_YGConfigSetPointScaleFactor=Module["_YGConfigSetPointScaleFactor"]=wasmExports["Rb"];_YGConfigGetPointScaleFactor=Module["_YGConfigGetPointScaleFactor"]=wasmExports["Sb"];_YGConfigSetErrata=Module["_YGConfigSetErrata"]=wasmExports["Tb"];_YGConfigGetErrata=Module["_YGConfigGetErrata"]=wasmExports["Ub"];_YGConfigSetLogger=Module["_YGConfigSetLogger"]=wasmExports["Vb"];_YGConfigSetContext=Module["_YGConfigSetContext"]=wasmExports["Wb"];_YGConfigGetContext=Module["_YGConfigGetContext"]=wasmExports["Xb"];_YGConfigSetExperimentalFeatureEnabled=Module["_YGConfigSetExperimentalFeatureEnabled"]=wasmExports["Yb"];_YGConfigIsExperimentalFeatureEnabled=Module["_YGConfigIsExperimentalFeatureEnabled"]=wasmExports["Zb"];_YGConfigSetCloneNodeFunc=Module["_YGConfigSetCloneNodeFunc"]=wasmExports["_b"];_YGNodeNewWithConfig=Module["_YGNodeNewWithConfig"]=wasmExports["$b"];_YGNodeClone=Module["_YGNodeClone"]=wasmExports["ac"];_YGNodeFree=Module["_YGNodeFree"]=wasmExports["bc"];_YGNodeGetConfig=Module["_YGNodeGetConfig"]=wasmExports["cc"];_YGNodeRemoveChild=Module["_YGNodeRemoveChild"]=wasmExports["dc"];_YGNodeFinalize=Module["_YGNodeFinalize"]=wasmExports["ec"];_YGNodeReset=Module["_YGNodeReset"]=wasmExports["fc"];_YGNodeGetHasNewLayout=Module["_YGNodeGetHasNewLayout"]=wasmExports["gc"];_YGNodeSetHasNewLayout=Module["_YGNodeSetHasNewLayout"]=wasmExports["hc"];_YGNodeIsDirty=Module["_YGNodeIsDirty"]=wasmExports["ic"];_YGNodeMarkDirty=Module["_YGNodeMarkDirty"]=wasmExports["jc"];_YGNodeSetDirtiedFunc=Module["_YGNodeSetDirtiedFunc"]=wasmExports["kc"];_YGNodeGetDirtiedFunc=Module["_YGNodeGetDirtiedFunc"]=wasmExports["lc"];_YGNodeSwapChild=Module["_YGNodeSwapChild"]=wasmExports["mc"];_YGNodeRemoveAllChildren=Module["_YGNodeRemoveAllChildren"]=wasmExports["nc"];_YGNodeSetChildren=Module["_YGNodeSetChildren"]=wasmExports["oc"];_YGNodeGetChild=Module["_YGNodeGetChild"]=wasmExports["pc"];_YGNodeGetChildCount=Module["_YGNodeGetChildCount"]=wasmExports["qc"];_YGNodeGetOwner=Module["_YGNodeGetOwner"]=wasmExports["rc"];_YGNodeGetParent=Module["_YGNodeGetParent"]=wasmExports["sc"];_YGNodeSetConfig=Module["_YGNodeSetConfig"]=wasmExports["tc"];_YGNodeSetContext=Module["_YGNodeSetContext"]=wasmExports["uc"];_YGNodeGetContext=Module["_YGNodeGetContext"]=wasmExports["vc"];_YGNodeSetMeasureFunc=Module["_YGNodeSetMeasureFunc"]=wasmExports["wc"];_YGNodeHasMeasureFunc=Module["_YGNodeHasMeasureFunc"]=wasmExports["xc"];_YGNodeSetBaselineFunc=Module["_YGNodeSetBaselineFunc"]=wasmExports["yc"];_YGNodeHasBaselineFunc=Module["_YGNodeHasBaselineFunc"]=wasmExports["zc"];_YGNodeSetIsReferenceBaseline=Module["_YGNodeSetIsReferenceBaseline"]=wasmExports["Ac"];_YGNodeIsReferenceBaseline=Module["_YGNodeIsReferenceBaseline"]=wasmExports["Bc"];_YGNodeSetNodeType=Module["_YGNodeSetNodeType"]=wasmExports["Cc"];_YGNodeGetNodeType=Module["_YGNodeGetNodeType"]=wasmExports["Dc"];_YGNodeSetAlwaysFormsContainingBlock=Module["_YGNodeSetAlwaysFormsContainingBlock"]=wasmExports["Ec"];_YGNodeGetAlwaysFormsContainingBlock=Module["_YGNodeGetAlwaysFormsContainingBlock"]=wasmExports["Fc"];_YGNodeCanUseCachedMeasurement=Module["_YGNodeCanUseCachedMeasurement"]=wasmExports["Gc"];_YGNodeLayoutGetRight=Module["_YGNodeLayoutGetRight"]=wasmExports["Hc"];_YGNodeLayoutGetBottom=Module["_YGNodeLayoutGetBottom"]=wasmExports["Ic"];_YGNodeLayoutGetDirection=Module["_YGNodeLayoutGetDirection"]=wasmExports["Jc"];_YGNodeLayoutGetHadOverflow=Module["_YGNodeLayoutGetHadOverflow"]=wasmExports["Kc"];_YGNodeLayoutGetMargin=Module["_YGNodeLayoutGetMargin"]=wasmExports["Lc"];_YGNodeLayoutGetBorder=Module["_YGNodeLayoutGetBorder"]=wasmExports["Mc"];_YGNodeLayoutGetPadding=Module["_YGNodeLayoutGetPadding"]=wasmExports["Nc"];_YGNodeLayoutGetRawHeight=Module["_YGNodeLayoutGetRawHeight"]=wasmExports["Oc"];_YGNodeLayoutGetRawWidth=Module["_YGNodeLayoutGetRawWidth"]=wasmExports["Pc"];_YGNodeCopyStyle=Module["_YGNodeCopyStyle"]=wasmExports["Qc"];_YGNodeStyleSetDirection=Module["_YGNodeStyleSetDirection"]=wasmExports["Rc"];_YGNodeStyleGetDirection=Module["_YGNodeStyleGetDirection"]=wasmExports["Sc"];_YGNodeStyleGetFlexDirection=Module["_YGNodeStyleGetFlexDirection"]=wasmExports["Tc"];_YGNodeStyleGetJustifyContent=Module["_YGNodeStyleGetJustifyContent"]=wasmExports["Uc"];_YGNodeStyleSetJustifyItems=Module["_YGNodeStyleSetJustifyItems"]=wasmExports["Vc"];_YGNodeStyleGetJustifyItems=Module["_YGNodeStyleGetJustifyItems"]=wasmExports["Wc"];_YGNodeStyleSetJustifySelf=Module["_YGNodeStyleSetJustifySelf"]=wasmExports["Xc"];_YGNodeStyleGetJustifySelf=Module["_YGNodeStyleGetJustifySelf"]=wasmExports["Yc"];_YGNodeStyleGetAlignContent=Module["_YGNodeStyleGetAlignContent"]=wasmExports["Zc"];_YGNodeStyleGetAlignItems=Module["_YGNodeStyleGetAlignItems"]=wasmExports["_c"];_YGNodeStyleGetAlignSelf=Module["_YGNodeStyleGetAlignSelf"]=wasmExports["$c"];_YGNodeStyleSetPositionType=Module["_YGNodeStyleSetPositionType"]=wasmExports["ad"];_YGNodeStyleGetPositionType=Module["_YGNodeStyleGetPositionType"]=wasmExports["bd"];_YGNodeStyleGetFlexWrap=Module["_YGNodeStyleGetFlexWrap"]=wasmExports["cd"];_YGNodeStyleSetOverflow=Module["_YGNodeStyleSetOverflow"]=wasmExports["dd"];_YGNodeStyleGetOverflow=Module["_YGNodeStyleGetOverflow"]=wasmExports["ed"];_YGNodeStyleSetDisplay=Module["_YGNodeStyleSetDisplay"]=wasmExports["fd"];_YGNodeStyleGetDisplay=Module["_YGNodeStyleGetDisplay"]=wasmExports["gd"];_YGNodeStyleSetFlex=Module["_YGNodeStyleSetFlex"]=wasmExports["hd"];_YGNodeStyleGetFlex=Module["_YGNodeStyleGetFlex"]=wasmExports["id"];_YGNodeStyleGetFlexGrow=Module["_YGNodeStyleGetFlexGrow"]=wasmExports["jd"];_YGNodeStyleGetFlexShrink=Module["_YGNodeStyleGetFlexShrink"]=wasmExports["kd"];_YGNodeStyleSetFlexBasisPercent=Module["_YGNodeStyleSetFlexBasisPercent"]=wasmExports["ld"];_YGNodeStyleSetFlexBasisMaxContent=Module["_YGNodeStyleSetFlexBasisMaxContent"]=wasmExports["md"];_YGNodeStyleSetFlexBasisFitContent=Module["_YGNodeStyleSetFlexBasisFitContent"]=wasmExports["nd"];_YGNodeStyleSetFlexBasisStretch=Module["_YGNodeStyleSetFlexBasisStretch"]=wasmExports["od"];_YGNodeStyleGetFlexBasis=Module["_YGNodeStyleGetFlexBasis"]=wasmExports["pd"];_YGNodeStyleSetPosition=Module["_YGNodeStyleSetPosition"]=wasmExports["qd"];_YGNodeStyleSetPositionPercent=Module["_YGNodeStyleSetPositionPercent"]=wasmExports["rd"];_YGNodeStyleSetPositionAuto=Module["_YGNodeStyleSetPositionAuto"]=wasmExports["sd"];_YGNodeStyleGetPosition=Module["_YGNodeStyleGetPosition"]=wasmExports["td"];_YGNodeStyleSetMarginPercent=Module["_YGNodeStyleSetMarginPercent"]=wasmExports["ud"];_YGNodeStyleSetMarginAuto=Module["_YGNodeStyleSetMarginAuto"]=wasmExports["vd"];_YGNodeStyleGetMargin=Module["_YGNodeStyleGetMargin"]=wasmExports["wd"];_YGNodeStyleSetPaddingPercent=Module["_YGNodeStyleSetPaddingPercent"]=wasmExports["xd"];_YGNodeStyleGetPadding=Module["_YGNodeStyleGetPadding"]=wasmExports["yd"];_YGNodeStyleSetBorder=Module["_YGNodeStyleSetBorder"]=wasmExports["zd"];_YGNodeStyleGetBorder=Module["_YGNodeStyleGetBorder"]=wasmExports["Ad"];_YGNodeStyleSetGapPercent=Module["_YGNodeStyleSetGapPercent"]=wasmExports["Bd"];_YGNodeStyleGetGap=Module["_YGNodeStyleGetGap"]=wasmExports["Cd"];_YGNodeStyleSetAspectRatio=Module["_YGNodeStyleSetAspectRatio"]=wasmExports["Dd"];_YGNodeStyleGetAspectRatio=Module["_YGNodeStyleGetAspectRatio"]=wasmExports["Ed"];_YGNodeStyleSetBoxSizing=Module["_YGNodeStyleSetBoxSizing"]=wasmExports["Fd"];_YGNodeStyleGetBoxSizing=Module["_YGNodeStyleGetBoxSizing"]=wasmExports["Gd"];_YGNodeStyleSetWidthAuto=Module["_YGNodeStyleSetWidthAuto"]=wasmExports["Hd"];_YGNodeStyleSetWidthMaxContent=Module["_YGNodeStyleSetWidthMaxContent"]=wasmExports["Id"];_YGNodeStyleSetWidthFitContent=Module["_YGNodeStyleSetWidthFitContent"]=wasmExports["Jd"];_YGNodeStyleSetWidthStretch=Module["_YGNodeStyleSetWidthStretch"]=wasmExports["Kd"];_YGNodeStyleGetWidth=Module["_YGNodeStyleGetWidth"]=wasmExports["Ld"];_YGNodeStyleSetHeightAuto=Module["_YGNodeStyleSetHeightAuto"]=wasmExports["Md"];_YGNodeStyleSetHeightMaxContent=Module["_YGNodeStyleSetHeightMaxContent"]=wasmExports["Nd"];_YGNodeStyleSetHeightFitContent=Module["_YGNodeStyleSetHeightFitContent"]=wasmExports["Od"];_YGNodeStyleSetHeightStretch=Module["_YGNodeStyleSetHeightStretch"]=wasmExports["Pd"];_YGNodeStyleGetHeight=Module["_YGNodeStyleGetHeight"]=wasmExports["Qd"];_YGNodeStyleSetMinWidthPercent=Module["_YGNodeStyleSetMinWidthPercent"]=wasmExports["Rd"];_YGNodeStyleSetMinWidthMaxContent=Module["_YGNodeStyleSetMinWidthMaxContent"]=wasmExports["Sd"];_YGNodeStyleSetMinWidthFitContent=Module["_YGNodeStyleSetMinWidthFitContent"]=wasmExports["Td"];_YGNodeStyleSetMinWidthStretch=Module["_YGNodeStyleSetMinWidthStretch"]=wasmExports["Ud"];_YGNodeStyleGetMinWidth=Module["_YGNodeStyleGetMinWidth"]=wasmExports["Vd"];_YGNodeStyleSetMinHeightPercent=Module["_YGNodeStyleSetMinHeightPercent"]=wasmExports["Wd"];_YGNodeStyleSetMinHeightMaxContent=Module["_YGNodeStyleSetMinHeightMaxContent"]=wasmExports["Xd"];_YGNodeStyleSetMinHeightFitContent=Module["_YGNodeStyleSetMinHeightFitContent"]=wasmExports["Yd"];_YGNodeStyleSetMinHeightStretch=Module["_YGNodeStyleSetMinHeightStretch"]=wasmExports["Zd"];_YGNodeStyleGetMinHeight=Module["_YGNodeStyleGetMinHeight"]=wasmExports["_d"];_YGNodeStyleSetMaxWidthPercent=Module["_YGNodeStyleSetMaxWidthPercent"]=wasmExports["$d"];_YGNodeStyleSetMaxWidthMaxContent=Module["_YGNodeStyleSetMaxWidthMaxContent"]=wasmExports["ae"];_YGNodeStyleSetMaxWidthFitContent=Module["_YGNodeStyleSetMaxWidthFitContent"]=wasmExports["be"];_YGNodeStyleSetMaxWidthStretch=Module["_YGNodeStyleSetMaxWidthStretch"]=wasmExports["ce"];_YGNodeStyleGetMaxWidth=Module["_YGNodeStyleGetMaxWidth"]=wasmExports["de"];_YGNodeStyleSetMaxHeightPercent=Module["_YGNodeStyleSetMaxHeightPercent"]=wasmExports["ee"];_YGNodeStyleSetMaxHeightMaxContent=Module["_YGNodeStyleSetMaxHeightMaxContent"]=wasmExports["fe"];_YGNodeStyleSetMaxHeightFitContent=Module["_YGNodeStyleSetMaxHeightFitContent"]=wasmExports["ge"];_YGNodeStyleSetMaxHeightStretch=Module["_YGNodeStyleSetMaxHeightStretch"]=wasmExports["he"];_YGNodeStyleGetMaxHeight=Module["_YGNodeStyleGetMaxHeight"]=wasmExports["ie"];_YGNodeStyleSetGridColumnStart=Module["_YGNodeStyleSetGridColumnStart"]=wasmExports["je"];_YGNodeStyleSetGridColumnStartAuto=Module["_YGNodeStyleSetGridColumnStartAuto"]=wasmExports["ke"];_YGNodeStyleSetGridColumnStartSpan=Module["_YGNodeStyleSetGridColumnStartSpan"]=wasmExports["le"];_YGNodeStyleGetGridColumnStart=Module["_YGNodeStyleGetGridColumnStart"]=wasmExports["me"];_YGNodeStyleSetGridColumnEnd=Module["_YGNodeStyleSetGridColumnEnd"]=wasmExports["ne"];_YGNodeStyleSetGridColumnEndAuto=Module["_YGNodeStyleSetGridColumnEndAuto"]=wasmExports["oe"];_YGNodeStyleSetGridColumnEndSpan=Module["_YGNodeStyleSetGridColumnEndSpan"]=wasmExports["pe"];_YGNodeStyleGetGridColumnEnd=Module["_YGNodeStyleGetGridColumnEnd"]=wasmExports["qe"];_YGNodeStyleSetGridRowStart=Module["_YGNodeStyleSetGridRowStart"]=wasmExports["re"];_YGNodeStyleSetGridRowStartAuto=Module["_YGNodeStyleSetGridRowStartAuto"]=wasmExports["se"];_YGNodeStyleSetGridRowStartSpan=Module["_YGNodeStyleSetGridRowStartSpan"]=wasmExports["te"];_YGNodeStyleGetGridRowStart=Module["_YGNodeStyleGetGridRowStart"]=wasmExports["ue"];_YGNodeStyleSetGridRowEnd=Module["_YGNodeStyleSetGridRowEnd"]=wasmExports["ve"];_YGNodeStyleSetGridRowEndAuto=Module["_YGNodeStyleSetGridRowEndAuto"]=wasmExports["we"];_YGNodeStyleSetGridRowEndSpan=Module["_YGNodeStyleSetGridRowEndSpan"]=wasmExports["xe"];_YGNodeStyleGetGridRowEnd=Module["_YGNodeStyleGetGridRowEnd"]=wasmExports["ye"];_YGNodeStyleSetGridTemplateColumnsCount=Module["_YGNodeStyleSetGridTemplateColumnsCount"]=wasmExports["ze"];_YGNodeStyleSetGridTemplateColumn=Module["_YGNodeStyleSetGridTemplateColumn"]=wasmExports["Ae"];_YGNodeStyleSetGridTemplateColumnMinMax=Module["_YGNodeStyleSetGridTemplateColumnMinMax"]=wasmExports["Be"];_YGNodeStyleSetGridTemplateRowsCount=Module["_YGNodeStyleSetGridTemplateRowsCount"]=wasmExports["Ce"];_YGNodeStyleSetGridTemplateRow=Module["_YGNodeStyleSetGridTemplateRow"]=wasmExports["De"];_YGNodeStyleSetGridTemplateRowMinMax=Module["_YGNodeStyleSetGridTemplateRowMinMax"]=wasmExports["Ee"];_YGNodeStyleSetGridAutoColumnsCount=Module["_YGNodeStyleSetGridAutoColumnsCount"]=wasmExports["Fe"];_YGNodeStyleSetGridAutoColumn=Module["_YGNodeStyleSetGridAutoColumn"]=wasmExports["Ge"];_YGNodeStyleSetGridAutoColumnMinMax=Module["_YGNodeStyleSetGridAutoColumnMinMax"]=wasmExports["He"];_YGNodeStyleSetGridAutoRowsCount=Module["_YGNodeStyleSetGridAutoRowsCount"]=wasmExports["Ie"];_YGNodeStyleSetGridAutoRow=Module["_YGNodeStyleSetGridAutoRow"]=wasmExports["Je"];_YGNodeStyleSetGridAutoRowMinMax=Module["_YGNodeStyleSetGridAutoRowMinMax"]=wasmExports["Ke"];__emscripten_timeout=wasmExports["Me"];__emscripten_stack_restore=wasmExports["Ne"];__emscripten_stack_alloc=wasmExports["Oe"];_emscripten_stack_get_current=wasmExports["Pe"];memory=wasmMemory=wasmExports["eb"];__indirect_function_table=wasmTable=wasmExports["Le"]}var wasmImports={ea:___syscall_fcntl64,Ba:___syscall_ioctl,Ca:___syscall_openat,Da:__abort_js,f:__embind_finalize_value_object,ya:__embind_register_bigint,cb:__embind_register_bool,ca:__embind_register_class,ua:__embind_register_class_constructor,c:__embind_register_class_function,Ra:__embind_register_emval,t:__embind_register_enum,d:__embind_register_enum_value,xa:__embind_register_float,a:__embind_register_function,G:__embind_register_integer,Oa:__embind_register_iterable,o:__embind_register_memory_view,Pa:__embind_register_optional,Ua:__embind_register_std_string,da:__embind_register_std_wstring,g:__embind_register_value_object,b:__embind_register_value_object_field,Fa:__embind_register_void,Ta:__emscripten_runtime_keepalive_clear,E:__emval_create_invoker,x:__emval_decref,D:__emval_invoke,W:__emval_new_array,R:__emval_new_cstring,ba:__emval_new_object,C:__emval_run_destructors,N:__emval_set_property,Va:__setitimer_js,Wa:__tzset_js,Za:_clock_time_get,_a:_emscripten_resize_heap,db:_emscripten_webgl_create_context,Qa:_emscripten_webgl_destroy_context,Aa:_emscripten_webgl_make_context_current,Xa:_environ_get,Ya:_environ_sizes_get,za:_fd_close,bb:_fd_read,$a:_fd_seek,ab:_fd_write,q:_glActiveTexture,oa:_glAttachShader,Ma:_glBindAttribLocation,i:_glBindBuffer,m:_glBindFramebuffer,n:_glBindTexture,p:_glBindVertexArray,$:_glBlendFunc,l:_glBlendFuncSeparate,w:_glBufferData,H:_glBufferSubData,Ea:_glCheckFramebufferStatus,B:_glClear,Y:_glClearColor,va:_glClearStencil,Z:_glColorMask,qa:_glCompileShader,Na:_glCreateProgram,sa:_glCreateShader,A:_glDeleteBuffers,j:_glDeleteFramebuffers,ta:_glDeleteProgram,I:_glDeleteShader,e:_glDeleteTextures,J:_glDeleteVertexArrays,_:_glDepthMask,h:_glDisable,P:_glDrawArrays,Q:_glDrawElements,k:_glEnable,v:_glEnableVertexAttribArray,ha:_glFramebufferTexture2D,z:_glGenBuffers,Ga:_glGenFramebuffers,V:_glGenTextures,K:_glGenVertexArrays,Ia:_glGenerateMipmap,M:_glGetError,aa:_glGetIntegerv,Ka:_glGetProgramInfoLog,na:_glGetProgramiv,pa:_glGetShaderInfoLog,T:_glGetShaderiv,X:_glGetString,r:_glGetUniformLocation,La:_glLinkProgram,ja:_glPixelStorei,Ha:_glReadPixels,wa:_glScissor,ra:_glShaderSource,ga:_glStencilFunc,O:_glStencilMask,fa:_glStencilOp,U:_glTexImage2D,s:_glTexParameteri,ia:_glTexSubImage2D,ma:_glUniform1f,L:_glUniform1i,la:_glUniform2f,Ja:_glUniform3f,ka:_glUniform4f,S:_glUniformMatrix4fv,F:_glUseProgram,u:_glVertexAttribPointer,y:_glViewport,Sa:_proc_exit};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})};return moduleRtn}export default ESEngineModule;diff --git a/editor/src/plugins/ui.ts b/editor/src/plugins/ui.tsindex 02fa1cef5..96f08aa55 100644--- a/editor/src/plugins/ui.ts+++ b/editor/src/plugins/ui.ts@@ -210,12 +210,13 @@ const FlexContainerSchema: ComponentSchema = {category: 'ui',requires: ['UIRect'],conflicts: ['LayoutGroup'],- description: 'CSS-like flexbox layout for child elements',+ description: 'Flexbox layout powered by Yoga engine',properties: [{ name: 'direction', type: 'enum', options: [{ label: 'Row', value: 0 }, { label: 'Column', value: 1 }, { label: 'RowReverse', value: 2 }, { label: 'ColumnReverse', value: 3 }] },{ name: 'wrap', type: 'enum', options: [{ label: 'NoWrap', value: 0 }, { label: 'Wrap', value: 1 }] },{ name: 'justifyContent', type: 'enum', options: [{ label: 'Start', value: 0 }, { label: 'Center', value: 1 }, { label: 'End', value: 2 }, { label: 'SpaceBetween', value: 3 }, { label: 'SpaceAround', value: 4 }, { label: 'SpaceEvenly', value: 5 }] },{ name: 'alignItems', type: 'enum', options: [{ label: 'Start', value: 0 }, { label: 'Center', value: 1 }, { label: 'End', value: 2 }, { label: 'Stretch', value: 3 }] },+ { name: 'alignContent', type: 'enum', options: [{ label: 'Start', value: 0 }, { label: 'Center', value: 1 }, { label: 'End', value: 2 }, { label: 'Stretch', value: 3 }, { label: 'SpaceBetween', value: 4 }, { label: 'SpaceAround', value: 5 }] },{ name: 'gap', type: 'vec2' },{ name: 'padding', type: 'padding' },],@@ -229,6 +230,14 @@ const FlexItemSchema: ComponentSchema = {{ name: 'flexShrink', type: 'number', min: 0, step: 0.1 },{ name: 'flexBasis', type: 'number', step: 1 },{ name: 'order', type: 'number', step: 1 },+ { name: 'alignSelf', type: 'enum', options: [{ label: 'Auto', value: 0 }, { label: 'Start', value: 1 }, { label: 'Center', value: 2 }, { label: 'End', value: 3 }, { label: 'Stretch', value: 4 }] },+ { name: 'margin', type: 'padding' },+ { name: 'minWidth', type: 'number', step: 1 },+ { name: 'minHeight', type: 'number', step: 1 },+ { name: 'maxWidth', type: 'number', step: 1 },+ { name: 'maxHeight', type: 'number', step: 1 },+ { name: 'widthPercent', type: 'number', step: 1, advanced: true },+ { name: 'heightPercent', type: 'number', step: 1, advanced: true },],};diff --git a/sdk/src/commands.ts b/sdk/src/commands.tsindex 8f58c4cf5..0fdaf9df2 100644--- a/sdk/src/commands.ts+++ b/sdk/src/commands.ts@@ -4,7 +4,7 @@*/import { Entity } from './types';-import { AnyComponentDef, ComponentDef, isBuiltinComponent } from './component';+import { AnyComponentDef, ComponentDef, isBuiltinComponent, Name } from './component';import type { World } from './world';import { ResourceDef, ResourceStorage } from './resource';@@ -69,12 +69,15 @@ export class EntityCommands {private readonly components_: SpawnComponentEntry[] = [];private isNew_: boolean;- constructor(commands: CommandsInstance, entity: Entity | null) {+ constructor(commands: CommandsInstance, entity: Entity | null, name?: string) {this.commands_ = commands;if (entity === null) {this.entityRef_ = { entity: 0 as Entity };this.isNew_ = true;+ if (name !== undefined) {+ this.insert(Name, { value: name });+ }} else {this.entityRef_ = { entity };this.isNew_ = false;@@ -136,8 +139,8 @@ export class CommandsInstance {this.resources_ = resources;}- spawn(): EntityCommands {- const ec = new EntityCommands(this, null);+ spawn(name?: string): EntityCommands {+ const ec = new EntityCommands(this, null, name);this.spawned_.push(ec);return ec;}diff --git a/sdk/src/ui/FlexContainer.ts b/sdk/src/ui/FlexContainer.tsindex acbcdc7dd..72b8c556c 100644--- a/sdk/src/ui/FlexContainer.ts+++ b/sdk/src/ui/FlexContainer.ts@@ -14,11 +14,15 @@ export type JustifyContent = (typeof JustifyContent)[keyof typeof JustifyContentexport const AlignItems = { Start: 0, Center: 1, End: 2, Stretch: 3 } as const;export type AlignItems = (typeof AlignItems)[keyof typeof AlignItems];+export const AlignContent = { Start: 0, Center: 1, End: 2, Stretch: 3, SpaceBetween: 4, SpaceAround: 5 } as const;+export type AlignContent = (typeof AlignContent)[keyof typeof AlignContent];+export interface FlexContainerData {direction: FlexDirection;wrap: FlexWrap;justifyContent: JustifyContent;alignItems: AlignItems;+ alignContent: AlignContent;gap: Vec2;padding: Padding;}@@ -28,6 +32,7 @@ export const FlexContainer = defineBuiltin<FlexContainerData>('FlexContainer', {wrap: FlexWrap.NoWrap,justifyContent: JustifyContent.Start,alignItems: AlignItems.Stretch,+ alignContent: AlignContent.Start,gap: { x: 0, y: 0 },padding: { left: 0, top: 0, right: 0, bottom: 0 },});diff --git a/sdk/src/ui/FlexItem.ts b/sdk/src/ui/FlexItem.tsindex 72669aab4..0eb4c50a3 100644--- a/sdk/src/ui/FlexItem.ts+++ b/sdk/src/ui/FlexItem.ts@@ -1,10 +1,22 @@import { defineBuiltin } from '../component';+import type { Padding } from '../wasm.generated';++export const AlignSelf = { Auto: 0, Start: 1, Center: 2, End: 3, Stretch: 4 } as const;+export type AlignSelf = (typeof AlignSelf)[keyof typeof AlignSelf];export interface FlexItemData {flexGrow: number;flexShrink: number;flexBasis: number;order: number;+ alignSelf: AlignSelf;+ margin: Padding;+ minWidth: number;+ minHeight: number;+ maxWidth: number;+ maxHeight: number;+ widthPercent: number;+ heightPercent: number;}export const FlexItem = defineBuiltin<FlexItemData>('FlexItem', {@@ -12,4 +24,12 @@ export const FlexItem = defineBuiltin<FlexItemData>('FlexItem', {flexShrink: 1,flexBasis: -1,order: 0,+ alignSelf: AlignSelf.Auto,+ margin: { left: 0, top: 0, right: 0, bottom: 0 },+ minWidth: -1,+ minHeight: -1,+ maxWidth: -1,+ maxHeight: -1,+ widthPercent: -1,+ heightPercent: -1,});diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.tsindex 376723e23..26ae8e0c6 100644--- a/sdk/src/wasm.generated.ts+++ b/sdk/src/wasm.generated.ts@@ -22,6 +22,14 @@ export interface VectorEntity {// Enums+export enum AlignSelf {+ Auto = 0,+ Start = 1,+ Center = 2,+ End = 3,+ Stretch = 4,+}+export enum EmitterShape {Point = 0,Circle = 1,@@ -86,6 +94,15 @@ export enum AlignItems {Stretch = 3,}+export enum AlignContent {+ Start = 0,+ Center = 1,+ End = 2,+ Stretch = 3,+ SpaceBetween = 4,+ SpaceAround = 5,+}+export enum LayoutDirection {Horizontal = 0,Vertical = 1,@@ -126,6 +143,14 @@ export interface FlexItem {flexShrink: number;flexBasis: number;order: number;+ alignSelf: number;+ margin: Padding;+ minWidth: number;+ minHeight: number;+ maxWidth: number;+ maxHeight: number;+ widthPercent: number;+ heightPercent: number;}export interface BoxCollider {@@ -321,6 +346,7 @@ export interface FlexContainer {wrap: number;justifyContent: number;alignItems: number;+ alignContent: number;gap: Vec2;padding: Padding;}diff --git a/sdk/src/world.ts b/sdk/src/world.tsindex 9044b6eec..06e60edb3 100644--- a/sdk/src/world.ts+++ b/sdk/src/world.ts@@ -4,7 +4,7 @@*/import { Entity } from './types';-import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents, getComponentRegistry } from './component';+import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents, getComponentRegistry, Name } from './component';import type { CppRegistry, ESEngineModule } from './wasm';import { validateComponentData, formatValidationErrors } from './validation';import { handleWasmError } from './wasmError';@@ -355,7 +355,7 @@ export class World {// Entity Management// =========================================================================- spawn(): Entity {+ spawn(name?: string): Entity {if (this.isIterating()) {throw new Error('Cannot spawn entity during query iteration. ' +@@ -387,6 +387,10 @@ export class World {this.entities_.set(entity, generation);this.worldVersion_++;+ if (name !== undefined) {+ this.insert(entity, Name, { value: name });+ }+for (const cb of this.spawnCallbacks_) {try { cb(entity); } catch (e) { console.warn('[World] Spawn callback error:', e); }}diff --git a/sdk/tests/commands.test.ts b/sdk/tests/commands.test.tsindex 6e079081a..41e57af02 100644--- a/sdk/tests/commands.test.ts+++ b/sdk/tests/commands.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { CommandsInstance, EntityCommands, Commands } from '../src/commands';-import { defineComponent, defineBuiltin } from '../src/component';+import { defineComponent, defineBuiltin, Name } from '../src/component';import { defineResource, ResourceStorage } from '../src/resource';import type { World } from '../src/world';import type { Entity } from '../src/types';@@ -102,6 +102,46 @@ describe('CommandsInstance', () => {});});+ describe('spawn with name', () => {+ it('should insert Name component when name is provided', () => {+ commands.spawn('Player');+ commands.flush();++ expect(world.spawn).toHaveBeenCalledOnce();+ expect(world.insert).toHaveBeenCalledWith(+ 1,+ Name,+ expect.objectContaining({ value: 'Player' }),+ );+ });++ it('should not insert Name component when name is omitted', () => {+ commands.spawn();+ commands.flush();++ expect(world.spawn).toHaveBeenCalledOnce();+ expect(world.insert).not.toHaveBeenCalled();+ });++ it('should insert Name alongside other components', () => {+ commands.spawn('Enemy')+ .insert(Position, { x: 5, y: 10 });+ commands.flush();++ expect(world.insert).toHaveBeenCalledTimes(2);+ expect(world.insert).toHaveBeenCalledWith(+ 1,+ Name,+ expect.objectContaining({ value: 'Enemy' }),+ );+ expect(world.insert).toHaveBeenCalledWith(+ 1,+ Position,+ expect.objectContaining({ x: 5, y: 10 }),+ );+ });+ });+describe('spawn with builtin component', () => {it('should merge data with builtin defaults', () => {commands.spawn().insert(Health, { value: 50 });diff --git a/sdk/tests/world.test.ts b/sdk/tests/world.test.tsindex 942cb687b..77b9ac550 100644--- a/sdk/tests/world.test.ts+++ b/sdk/tests/world.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, beforeEach, vi } from 'vitest';import { World, computeQueryCacheKey } from '../src/world';-import { defineComponent, defineTag, defineBuiltin } from '../src/component';+import { defineComponent, defineTag, defineBuiltin, Name } from '../src/component';import { createMockModule } from './mocks/wasm';describe('World', () => {@@ -23,6 +23,18 @@ describe('World', () => {expect(entity).toBeGreaterThan(0);});+ it('should spawn entity with name', () => {+ const entity = world.spawn('Player');+ expect(entity).toBeGreaterThan(0);+ const name = world.get(entity, Name);+ expect(name.value).toBe('Player');+ });++ it('should spawn entity without name when omitted', () => {+ const entity = world.spawn();+ expect(world.has(entity, Name)).toBe(false);+ });+it('should spawn multiple entities', () => {const e1 = world.spawn();const e2 = world.spawn();diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex ef3cb1530..68bd26c50 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -81,6 +81,13 @@ EMSCRIPTEN_BINDINGS(esengine_math) {// =============================================================================EMSCRIPTEN_BINDINGS(esengine_enums) {+ enum_<esengine::ecs::AlignSelf>("AlignSelf")+ .value("Auto", esengine::ecs::AlignSelf::Auto)+ .value("Start", esengine::ecs::AlignSelf::Start)+ .value("Center", esengine::ecs::AlignSelf::Center)+ .value("End", esengine::ecs::AlignSelf::End)+ .value("Stretch", esengine::ecs::AlignSelf::Stretch);+enum_<esengine::ecs::EmitterShape>("EmitterShape").value("Point", esengine::ecs::EmitterShape::Point).value("Circle", esengine::ecs::EmitterShape::Circle)@@ -135,6 +142,14 @@ EMSCRIPTEN_BINDINGS(esengine_enums) {.value("End", esengine::ecs::AlignItems::End).value("Stretch", esengine::ecs::AlignItems::Stretch);+ enum_<esengine::ecs::AlignContent>("AlignContent")+ .value("Start", esengine::ecs::AlignContent::Start)+ .value("Center", esengine::ecs::AlignContent::Center)+ .value("End", esengine::ecs::AlignContent::End)+ .value("Stretch", esengine::ecs::AlignContent::Stretch)+ .value("SpaceBetween", esengine::ecs::AlignContent::SpaceBetween)+ .value("SpaceAround", esengine::ecs::AlignContent::SpaceAround);+enum_<esengine::ecs::LayoutDirection>("LayoutDirection").value("Horizontal", esengine::ecs::LayoutDirection::Horizontal).value("Vertical", esengine::ecs::LayoutDirection::Vertical);@@ -161,6 +176,55 @@ EMSCRIPTEN_BINDINGS(esengine_enums) {// Components// =============================================================================+struct FlexItemJS {+ f32 flexGrow;+ f32 flexShrink;+ f32 flexBasis;+ i32 order;+ i32 alignSelf;+ Padding margin;+ f32 minWidth;+ f32 minHeight;+ f32 maxWidth;+ f32 maxHeight;+ f32 widthPercent;+ f32 heightPercent;+};++esengine::ecs::FlexItem flexitemFromJS(const FlexItemJS& js) {+ esengine::ecs::FlexItem c;+ c.flexGrow = js.flexGrow;+ c.flexShrink = js.flexShrink;+ c.flexBasis = js.flexBasis;+ c.order = js.order;+ c.alignSelf = static_cast<AlignSelf>(js.alignSelf);+ c.margin = js.margin;+ c.minWidth = js.minWidth;+ c.minHeight = js.minHeight;+ c.maxWidth = js.maxWidth;+ c.maxHeight = js.maxHeight;+ c.widthPercent = js.widthPercent;+ c.heightPercent = js.heightPercent;+ return c;+}++FlexItemJS flexitemToJS(const esengine::ecs::FlexItem& c) {+ FlexItemJS js;+ js.flexGrow = c.flexGrow;+ js.flexShrink = c.flexShrink;+ js.flexBasis = c.flexBasis;+ js.order = c.order;+ js.alignSelf = static_cast<i32>(c.alignSelf);+ js.margin = c.margin;+ js.minWidth = c.minWidth;+ js.minHeight = c.minHeight;+ js.maxWidth = c.maxWidth;+ js.maxHeight = c.maxHeight;+ js.widthPercent = c.widthPercent;+ js.heightPercent = c.heightPercent;+ return js;+}+struct ParticleEmitterJS {f32 rate;i32 burstCount;@@ -475,6 +539,7 @@ struct FlexContainerJS {i32 wrap;i32 justifyContent;i32 alignItems;+ i32 alignContent;glm::vec2 gap;Padding padding;};@@ -485,6 +550,7 @@ esengine::ecs::FlexContainer flexcontainerFromJS(const FlexContainerJS& js) {c.wrap = static_cast<FlexWrap>(js.wrap);c.justifyContent = static_cast<JustifyContent>(js.justifyContent);c.alignItems = static_cast<AlignItems>(js.alignItems);+ c.alignContent = static_cast<AlignContent>(js.alignContent);c.gap = js.gap;c.padding = js.padding;return c;@@ -496,6 +562,7 @@ FlexContainerJS flexcontainerToJS(const esengine::ecs::FlexContainer& c) {js.wrap = static_cast<i32>(c.wrap);js.justifyContent = static_cast<i32>(c.justifyContent);js.alignItems = static_cast<i32>(c.alignItems);+ js.alignContent = static_cast<i32>(c.alignContent);js.gap = c.gap;js.padding = c.padding;return js;@@ -620,11 +687,19 @@ EMSCRIPTEN_BINDINGS(esengine_components) {.field("size", &esengine::ecs::UIRect::size).field("pivot", &esengine::ecs::UIRect::pivot);- value_object<esengine::ecs::FlexItem>("FlexItem")- .field("flexGrow", &esengine::ecs::FlexItem::flexGrow)- .field("flexShrink", &esengine::ecs::FlexItem::flexShrink)- .field("flexBasis", &esengine::ecs::FlexItem::flexBasis)- .field("order", &esengine::ecs::FlexItem::order);+ value_object<FlexItemJS>("FlexItem")+ .field("flexGrow", &FlexItemJS::flexGrow)+ .field("flexShrink", &FlexItemJS::flexShrink)+ .field("flexBasis", &FlexItemJS::flexBasis)+ .field("order", &FlexItemJS::order)+ .field("alignSelf", &FlexItemJS::alignSelf)+ .field("margin", &FlexItemJS::margin)+ .field("minWidth", &FlexItemJS::minWidth)+ .field("minHeight", &FlexItemJS::minHeight)+ .field("maxWidth", &FlexItemJS::maxWidth)+ .field("maxHeight", &FlexItemJS::maxHeight)+ .field("widthPercent", &FlexItemJS::widthPercent)+ .field("heightPercent", &FlexItemJS::heightPercent);value_object<esengine::ecs::BoxCollider>("BoxCollider").field("halfExtents", &esengine::ecs::BoxCollider::halfExtents)@@ -804,6 +879,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {.field("wrap", &FlexContainerJS::wrap).field("justifyContent", &FlexContainerJS::justifyContent).field("alignItems", &FlexContainerJS::alignItems)+ .field("alignContent", &FlexContainerJS::alignContent).field("gap", &FlexContainerJS::gap).field("padding", &FlexContainerJS::padding);@@ -897,16 +973,15 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {.function("hasFlexItem", optional_override([](Registry& r, u32 e) {return r.has<esengine::ecs::FlexItem>(static_cast<Entity>(e));}))- .function("getFlexItem", optional_override([](Registry& r, u32 e) -> esengine::ecs::FlexItem& {+ .function("getFlexItem", optional_override([](Registry& r, u32 e) {auto entity = static_cast<Entity>(e);- static esengine::ecs::FlexItem s_dummy{};- if (!r.valid(entity) || !r.has<esengine::ecs::FlexItem>(entity)) return s_dummy;- return r.get<esengine::ecs::FlexItem>(entity);- }), allow_raw_pointers())- .function("addFlexItem", optional_override([](Registry& r, u32 e, const esengine::ecs::FlexItem& c) {+ if (!r.valid(entity) || !r.has<esengine::ecs::FlexItem>(entity)) return FlexItemJS{};+ return flexitemToJS(r.get<esengine::ecs::FlexItem>(entity));+ }))+ .function("addFlexItem", optional_override([](Registry& r, u32 e, const FlexItemJS& js) {auto entity = static_cast<Entity>(e);if (!r.valid(entity)) return;- r.emplaceOrReplace<esengine::ecs::FlexItem>(entity, c);+ r.emplaceOrReplace<esengine::ecs::FlexItem>(entity, flexitemFromJS(js));})).function("removeFlexItem", optional_override([](Registry& r, u32 e) {auto entity = static_cast<Entity>(e);diff --git a/src/esengine/ecs/UILayoutSystem.hpp b/src/esengine/ecs/UILayoutSystem.hppindex d3a4aee58..3cc527e1e 100644--- a/src/esengine/ecs/UILayoutSystem.hpp+++ b/src/esengine/ecs/UILayoutSystem.hpp@@ -10,6 +10,7 @@#include "components/FlexItem.hpp"#include "components/LayoutGroup.hpp"+#include <yoga/Yoga.h>#include <algorithm>#include <cmath>#include <vector>@@ -141,15 +142,72 @@ inline void layoutNodeAnchor(writePosition(registry, node, result.origin_x, result.origin_y, cameraRect);}-struct UnifiedFlexItem {+inline YGFlexDirection toYGFlexDirection(FlexDirection dir) {+ switch (dir) {+ case FlexDirection::Row: return YGFlexDirectionRow;+ case FlexDirection::Column: return YGFlexDirectionColumn;+ case FlexDirection::RowReverse: return YGFlexDirectionRowReverse;+ case FlexDirection::ColumnReverse: return YGFlexDirectionColumnReverse;+ }+ return YGFlexDirectionRow;+}++inline YGWrap toYGWrap(FlexWrap wrap) {+ switch (wrap) {+ case FlexWrap::NoWrap: return YGWrapNoWrap;+ case FlexWrap::Wrap: return YGWrapWrap;+ }+ return YGWrapNoWrap;+}++inline YGJustify toYGJustify(JustifyContent jc) {+ switch (jc) {+ case JustifyContent::Start: return YGJustifyFlexStart;+ case JustifyContent::Center: return YGJustifyCenter;+ case JustifyContent::End: return YGJustifyFlexEnd;+ case JustifyContent::SpaceBetween: return YGJustifySpaceBetween;+ case JustifyContent::SpaceAround: return YGJustifySpaceAround;+ case JustifyContent::SpaceEvenly: return YGJustifySpaceEvenly;+ }+ return YGJustifyFlexStart;+}++inline YGAlign toYGAlign(AlignItems ai) {+ switch (ai) {+ case AlignItems::Start: return YGAlignFlexStart;+ case AlignItems::Center: return YGAlignCenter;+ case AlignItems::End: return YGAlignFlexEnd;+ case AlignItems::Stretch: return YGAlignStretch;+ }+ return YGAlignStretch;+}++inline YGAlign toYGAlignContent(AlignContent ac) {+ switch (ac) {+ case AlignContent::Start: return YGAlignFlexStart;+ case AlignContent::Center: return YGAlignCenter;+ case AlignContent::End: return YGAlignFlexEnd;+ case AlignContent::Stretch: return YGAlignStretch;+ case AlignContent::SpaceBetween: return YGAlignSpaceBetween;+ case AlignContent::SpaceAround: return YGAlignSpaceAround;+ }+ return YGAlignFlexStart;+}++inline YGAlign toYGAlignSelf(AlignSelf as) {+ switch (as) {+ case AlignSelf::Auto: return YGAlignAuto;+ case AlignSelf::Start: return YGAlignFlexStart;+ case AlignSelf::Center: return YGAlignCenter;+ case AlignSelf::End: return YGAlignFlexEnd;+ case AlignSelf::Stretch: return YGAlignStretch;+ }+ return YGAlignAuto;+}++struct FlexChildInfo {i32 tree_index;Entity entity;- f32 grow;- f32 shrink;- f32 basis;- i32 order;- f32 main_size;- f32 cross_size;};inline void resolveFlexChildren(@@ -167,182 +225,99 @@ inline void resolveFlexChildren(f32 pivotX = parentRect.pivot.x;f32 pivotY = parentRect.pivot.y;- f32 padLeft = flex.padding.left;- f32 padTop = flex.padding.top;- f32 padRight = flex.padding.right;- f32 padBottom = flex.padding.bottom;-- bool isRow = (flex.direction == FlexDirection::Row || flex.direction == FlexDirection::RowReverse);- bool isReverse = (flex.direction == FlexDirection::RowReverse || flex.direction == FlexDirection::ColumnReverse);-- f32 contentW = parentW - padLeft - padRight;- f32 contentH = parentH - padTop - padBottom;- f32 mainSpace = isRow ? contentW : contentH;- f32 crossSpace = isRow ? contentH : contentW;- f32 mainGap = isRow ? flex.gap.x : flex.gap.y;-- std::vector<UnifiedFlexItem> items;+ std::vector<FlexChildInfo> children;for (i32 j = containerIndex + 1; j < static_cast<i32>(tree.nodes_.size()); j++) {if (tree.nodes_[j].parent != containerEntity) continue;if (tree.nodes_[j].depth != tree.nodes_[containerIndex].depth + 1) continue;-Entity childEntity = tree.nodes_[j].entity;- auto* childRect = registry.tryGet<UIRect>(childEntity);- if (!childRect) continue;-- UnifiedFlexItem item;- item.tree_index = j;- item.entity = childEntity;-- auto* fi = registry.tryGet<FlexItem>(childEntity);- if (fi) {- item.grow = fi->flexGrow;- item.shrink = fi->flexShrink;- item.basis = fi->flexBasis;- item.order = fi->order;- } else {- item.grow = 0.0f;- item.shrink = 1.0f;- item.basis = -1.0f;- item.order = 0;- }-- f32 cw = childRect->computed_size_.x > 0.0f ? childRect->computed_size_.x : childRect->size.x;- f32 ch = childRect->computed_size_.y > 0.0f ? childRect->computed_size_.y : childRect->size.y;-- if (item.basis >= 0.0f) {- item.main_size = item.basis;- } else {- item.main_size = isRow ? cw : ch;- }- item.cross_size = isRow ? ch : cw;- items.push_back(item);+ if (!registry.has<UIRect>(childEntity)) continue;+ children.push_back({j, childEntity});}- if (items.empty()) return;-- std::stable_sort(items.begin(), items.end(), [](const UnifiedFlexItem& a, const UnifiedFlexItem& b) {- return a.order < b.order;- });+ if (children.empty()) return;- if (isReverse) {- std::reverse(items.begin(), items.end());- }+ YGNodeRef root = YGNodeNew();+ YGNodeStyleSetFlexDirection(root, toYGFlexDirection(flex.direction));+ YGNodeStyleSetFlexWrap(root, toYGWrap(flex.wrap));+ YGNodeStyleSetJustifyContent(root, toYGJustify(flex.justifyContent));+ YGNodeStyleSetAlignItems(root, toYGAlign(flex.alignItems));+ YGNodeStyleSetWidth(root, parentW);+ YGNodeStyleSetHeight(root, parentH);+ YGNodeStyleSetPadding(root, YGEdgeLeft, flex.padding.left);+ YGNodeStyleSetPadding(root, YGEdgeTop, flex.padding.top);+ YGNodeStyleSetPadding(root, YGEdgeRight, flex.padding.right);+ YGNodeStyleSetPadding(root, YGEdgeBottom, flex.padding.bottom);+ YGNodeStyleSetAlignContent(root, toYGAlignContent(flex.alignContent));+ YGNodeStyleSetGap(root, YGGutterColumn, flex.gap.x);+ YGNodeStyleSetGap(root, YGGutterRow, flex.gap.y);++ std::vector<YGNodeRef> childNodes;+ childNodes.reserve(children.size());- f32 totalMainSize = 0.0f;- for (auto& item : items) {- totalMainSize += item.main_size;- }- totalMainSize += mainGap * static_cast<f32>(items.size() - 1);+ for (usize i = 0; i < children.size(); i++) {+ auto& childRect = registry.get<UIRect>(children[i].entity);+ f32 cw = childRect.computed_size_.x > 0.0f ? childRect.computed_size_.x : childRect.size.x;+ f32 ch = childRect.computed_size_.y > 0.0f ? childRect.computed_size_.y : childRect.size.y;- f32 freeSpace = mainSpace - totalMainSize;+ YGNodeRef child = YGNodeNew();- if (freeSpace > 0.0f) {- f32 totalGrow = 0.0f;- for (auto& item : items) {- totalGrow += item.grow;- }- if (totalGrow > 0.0f) {- for (auto& item : items) {- item.main_size += freeSpace * (item.grow / totalGrow);+ auto* fi = registry.tryGet<FlexItem>(children[i].entity);+ if (fi) {+ YGNodeStyleSetFlexGrow(child, fi->flexGrow);+ YGNodeStyleSetFlexShrink(child, fi->flexShrink);+ if (fi->flexBasis >= 0.0f) {+ YGNodeStyleSetFlexBasis(child, fi->flexBasis);+ } else {+ YGNodeStyleSetFlexBasisAuto(child);}- freeSpace = 0.0f;- }- } else if (freeSpace < 0.0f) {- f32 totalShrinkBasis = 0.0f;- for (auto& item : items) {- totalShrinkBasis += item.shrink * item.main_size;- }- if (totalShrinkBasis > 0.0f) {- for (auto& item : items) {- item.main_size += freeSpace * (item.shrink * item.main_size / totalShrinkBasis);- item.main_size = std::max(0.0f, item.main_size);+ YGNodeStyleSetAlignSelf(child, toYGAlignSelf(fi->alignSelf));+ YGNodeStyleSetMargin(child, YGEdgeLeft, fi->margin.left);+ YGNodeStyleSetMargin(child, YGEdgeTop, fi->margin.top);+ YGNodeStyleSetMargin(child, YGEdgeRight, fi->margin.right);+ YGNodeStyleSetMargin(child, YGEdgeBottom, fi->margin.bottom);+ if (fi->minWidth >= 0.0f) YGNodeStyleSetMinWidth(child, fi->minWidth);+ if (fi->minHeight >= 0.0f) YGNodeStyleSetMinHeight(child, fi->minHeight);+ if (fi->maxWidth >= 0.0f) YGNodeStyleSetMaxWidth(child, fi->maxWidth);+ if (fi->maxHeight >= 0.0f) YGNodeStyleSetMaxHeight(child, fi->maxHeight);+ if (fi->widthPercent >= 0.0f) {+ YGNodeStyleSetWidthPercent(child, fi->widthPercent);+ } else {+ YGNodeStyleSetWidth(child, cw);+ }+ if (fi->heightPercent >= 0.0f) {+ YGNodeStyleSetHeightPercent(child, fi->heightPercent);+ } else {+ YGNodeStyleSetHeight(child, ch);}- freeSpace = 0.0f;+ } else {+ YGNodeStyleSetFlexGrow(child, 0.0f);+ YGNodeStyleSetFlexShrink(child, 1.0f);+ YGNodeStyleSetFlexBasisAuto(child);+ YGNodeStyleSetWidth(child, cw);+ YGNodeStyleSetHeight(child, ch);}- }- f32 cursor = 0.0f;- f32 gap = mainGap;- usize n = items.size();-- switch (flex.justifyContent) {- case JustifyContent::Start:- cursor = 0.0f;- break;- case JustifyContent::Center:- cursor = freeSpace * 0.5f;- break;- case JustifyContent::End:- cursor = freeSpace;- break;- case JustifyContent::SpaceBetween:- cursor = 0.0f;- if (n > 1) gap = mainGap + freeSpace / static_cast<f32>(n - 1);- break;- case JustifyContent::SpaceAround:- if (n > 0) {- f32 spacePerItem = freeSpace / static_cast<f32>(n);- cursor = spacePerItem * 0.5f;- gap = mainGap + spacePerItem;- }- break;- case JustifyContent::SpaceEvenly:- if (n > 0) {- f32 spaceUnit = freeSpace / static_cast<f32>(n + 1);- cursor = spaceUnit;- gap = mainGap + spaceUnit;- }- break;+ YGNodeInsertChild(root, child, i);+ childNodes.push_back(child);}- for (usize i = 0; i < n; i++) {- auto& item = items[i];- auto& childRect = registry.get<UIRect>(item.entity);-- f32 mainPos = cursor;- cursor += item.main_size;- if (i < n - 1) cursor += gap;-- f32 crossPos = 0.0f;- f32 finalCrossSize = item.cross_size;-- switch (flex.alignItems) {- case AlignItems::Start:- crossPos = 0.0f;- break;- case AlignItems::Center:- crossPos = (crossSpace - finalCrossSize) * 0.5f;- break;- case AlignItems::End:- crossPos = crossSpace - finalCrossSize;- break;- case AlignItems::Stretch:- crossPos = 0.0f;- finalCrossSize = crossSpace;- break;- }+ YGNodeCalculateLayout(root, parentW, parentH, YGDirectionLTR);- f32 finalW, finalH;- f32 localX, localY;+ for (usize i = 0; i < children.size(); i++) {+ auto& info = children[i];+ auto& childRect = registry.get<UIRect>(info.entity);- if (isRow) {- finalW = item.main_size;- finalH = finalCrossSize;- f32 cpx = childRect.pivot.x;- f32 cpy = childRect.pivot.y;- localX = -pivotX * parentW + padLeft + mainPos + cpx * finalW;- localY = (1.0f - pivotY) * parentH - padTop - crossPos - (1.0f - cpy) * finalH;- } else {- finalW = finalCrossSize;- finalH = item.main_size;- f32 cpx = childRect.pivot.x;- f32 cpy = childRect.pivot.y;- localX = -pivotX * parentW + padLeft + crossPos + cpx * finalW;- localY = (1.0f - pivotY) * parentH - padTop - mainPos - (1.0f - cpy) * finalH;- }+ f32 yogaLeft = YGNodeLayoutGetLeft(childNodes[i]);+ f32 yogaTop = YGNodeLayoutGetTop(childNodes[i]);+ f32 finalW = YGNodeLayoutGetWidth(childNodes[i]);+ f32 finalH = YGNodeLayoutGetHeight(childNodes[i]);++ f32 cpx = childRect.pivot.x;+ f32 cpy = childRect.pivot.y;+ f32 localX = -pivotX * parentW + yogaLeft + cpx * finalW;+ f32 localY = (1.0f - pivotY) * parentH - yogaTop - (1.0f - cpy) * finalH;- auto* transform = registry.tryGet<Transform>(item.entity);+ auto* transform = registry.tryGet<Transform>(info.entity);if (transform) {if (childRect.anim_override_) {if (!(childRect.anim_override_ & UIRect::ANIM_POS_X)) {@@ -360,7 +335,7 @@ inline void resolveFlexChildren(childRect.computed_size_.x = finalW;childRect.computed_size_.y = finalH;- auto* sprite = registry.tryGet<Sprite>(item.entity);+ auto* sprite = registry.tryGet<Sprite>(info.entity);if (sprite) {if (sprite->size.x != finalW || sprite->size.y != finalH) {sprite->size.x = finalW;@@ -368,8 +343,14 @@ inline void resolveFlexChildren(}}- tree.nodes_[item.tree_index].flags &= ~LAYOUT_DIRTY;+ if (registry.has<FlexContainer>(info.entity) || registry.has<LayoutGroup>(info.entity)) {+ tree.nodes_[info.tree_index].flags |= LAYOUT_DIRTY;+ } else {+ tree.nodes_[info.tree_index].flags &= ~LAYOUT_DIRTY;+ }}++ YGNodeFreeRecursive(root);}inline void resolveLayoutGroupChildren(diff --git a/src/esengine/ecs/components/FlexContainer.hpp b/src/esengine/ecs/components/FlexContainer.hppindex 8ca131cab..8777ff7a4 100644--- a/src/esengine/ecs/components/FlexContainer.hpp+++ b/src/esengine/ecs/components/FlexContainer.hpp@@ -39,6 +39,16 @@ enum class AlignItems : u8 {Stretch};+ES_ENUM()+enum class AlignContent : u8 {+ Start,+ Center,+ End,+ Stretch,+ SpaceBetween,+ SpaceAround+};+ES_COMPONENT()struct FlexContainer {ES_PROPERTY()@@ -50,6 +60,8 @@ struct FlexContainer {ES_PROPERTY()AlignItems alignItems{AlignItems::Stretch};ES_PROPERTY()+ AlignContent alignContent{AlignContent::Start};+ ES_PROPERTY()glm::vec2 gap{0.0f, 0.0f};ES_PROPERTY()Padding padding{};diff --git a/src/esengine/ecs/components/FlexItem.hpp b/src/esengine/ecs/components/FlexItem.hppindex f7a1f0fe0..a96c2cb22 100644--- a/src/esengine/ecs/components/FlexItem.hpp+++ b/src/esengine/ecs/components/FlexItem.hpp@@ -1,10 +1,20 @@#pragma once#include "../../core/Types.hpp"+#include "../../core/UITypes.hpp"#include "../../core/Reflection.hpp"namespace esengine::ecs {+ES_ENUM()+enum class AlignSelf : u8 {+ Auto,+ Start,+ Center,+ End,+ Stretch+};+ES_COMPONENT()struct FlexItem {ES_PROPERTY()@@ -15,6 +25,22 @@ struct FlexItem {f32 flexBasis{-1.0f};ES_PROPERTY()i32 order{0};+ ES_PROPERTY()+ AlignSelf alignSelf{AlignSelf::Auto};+ ES_PROPERTY()+ Padding margin{};+ ES_PROPERTY()+ f32 minWidth{-1.0f};+ ES_PROPERTY()+ f32 minHeight{-1.0f};+ ES_PROPERTY()+ f32 maxWidth{-1.0f};+ ES_PROPERTY()+ f32 maxHeight{-1.0f};+ ES_PROPERTY()+ f32 widthPercent{-1.0f};+ ES_PROPERTY()+ f32 heightPercent{-1.0f};};} // namespace esengine::ecsdiff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txtindex c098843ed..d2b70f351 100644--- a/third_party/CMakeLists.txt+++ b/third_party/CMakeLists.txt@@ -60,6 +60,27 @@ endif()# Native Platform Dependencies# =============================================================================+# =============================================================================+# Yoga - Flexbox Layout Engine (Meta)+# =============================================================================++file(GLOB_RECURSE YOGA_SOURCES+ "${CMAKE_CURRENT_SOURCE_DIR}/yoga/*.cpp"+)+add_library(yogacore STATIC ${YOGA_SOURCES})+target_include_directories(yogacore PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})+target_compile_features(yogacore PUBLIC cxx_std_20)+if(NOT MSVC)+ target_compile_options(yogacore PRIVATE -Wno-unused-parameter)+endif()+if(ES_BUILD_WEB OR ES_BUILD_WXGAME)+ target_compile_options(yogacore PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS})+endif()++# =============================================================================+# Native Platform Dependencies+# =============================================================================+if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)diff --git a/third_party/yoga/CMakeLists.txt b/third_party/yoga/CMakeLists.txtnew file mode 100644index 000000000..b6eca1ac7--- /dev/null+++ b/third_party/yoga/CMakeLists.txt@@ -0,0 +1,41 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+#+# This source code is licensed under the MIT license found in the+# LICENSE file in the root directory of this source tree.+++cmake_minimum_required(VERSION 3.13...3.26)+project(yogacore)+set(CMAKE_VERBOSE_MAKEFILE on)++if(TARGET yogacore)+ return()+endif()++include(CheckIPOSupported)++set(YOGA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/..)+include(${YOGA_ROOT}/cmake/project-defaults.cmake)+++file(GLOB SOURCES CONFIGURE_DEPENDS+ ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/**/*.cpp)++add_library(yogacore STATIC ${SOURCES})++# Yoga conditionally uses <android/log> when building for Android+if (ANDROID)+ target_link_libraries(yogacore log)+endif()++check_ipo_supported(RESULT result)+if(result)+ set_target_properties(yogacore PROPERTIES+ CMAKE_INTERPROCEDURAL_OPTIMIZATION true)+endif()++target_include_directories(yogacore+ PUBLIC+ $<BUILD_INTERFACE:${YOGA_ROOT}>+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/include/yoga>)diff --git a/third_party/yoga/LICENSE b/third_party/yoga/LICENSEnew file mode 100644index 000000000..b96dcb048--- /dev/null+++ b/third_party/yoga/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) Facebook, Inc. and its affiliates.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/third_party/yoga/YGConfig.cpp b/third_party/yoga/YGConfig.cppnew file mode 100644index 000000000..b3a82e1ad--- /dev/null+++ b/third_party/yoga/YGConfig.cpp@@ -0,0 +1,92 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/Yoga.h>+#include <yoga/debug/AssertFatal.h>+#include <yoga/debug/Log.h>++using namespace facebook;+using namespace facebook::yoga;++YGConfigRef YGConfigNew(void) {+ return new yoga::Config(getDefaultLogger());+}++void YGConfigFree(const YGConfigRef config) {+ delete resolveRef(config);+}++YGConfigConstRef YGConfigGetDefault() {+ return &yoga::Config::getDefault();+}++void YGConfigSetUseWebDefaults(const YGConfigRef config, const bool enabled) {+ resolveRef(config)->setUseWebDefaults(enabled);+}++bool YGConfigGetUseWebDefaults(const YGConfigConstRef config) {+ return resolveRef(config)->useWebDefaults();+}++void YGConfigSetPointScaleFactor(+ const YGConfigRef config,+ const float pixelsInPoint) {+ yoga::assertFatalWithConfig(+ resolveRef(config),+ pixelsInPoint >= 0.0f,+ "Scale factor should not be less than zero");++ resolveRef(config)->setPointScaleFactor(pixelsInPoint);+}++float YGConfigGetPointScaleFactor(const YGConfigConstRef config) {+ return resolveRef(config)->getPointScaleFactor();+}++void YGConfigSetErrata(YGConfigRef config, YGErrata errata) {+ resolveRef(config)->setErrata(scopedEnum(errata));+}++YGErrata YGConfigGetErrata(YGConfigConstRef config) {+ return unscopedEnum(resolveRef(config)->getErrata());+}++void YGConfigSetLogger(const YGConfigRef config, YGLogger logger) {+ if (logger != nullptr) {+ resolveRef(config)->setLogger(logger);+ } else {+ resolveRef(config)->setLogger(getDefaultLogger());+ }+}++void YGConfigSetContext(const YGConfigRef config, void* context) {+ resolveRef(config)->setContext(context);+}++void* YGConfigGetContext(const YGConfigConstRef config) {+ return resolveRef(config)->getContext();+}++void YGConfigSetExperimentalFeatureEnabled(+ const YGConfigRef config,+ const YGExperimentalFeature feature,+ const bool enabled) {+ resolveRef(config)->setExperimentalFeatureEnabled(+ scopedEnum(feature), enabled);+}++bool YGConfigIsExperimentalFeatureEnabled(+ const YGConfigConstRef config,+ const YGExperimentalFeature feature) {+ return resolveRef(config)->isExperimentalFeatureEnabled(scopedEnum(feature));+}++void YGConfigSetCloneNodeFunc(+ const YGConfigRef config,+ const YGCloneNodeFunc callback) {+ resolveRef(config)->setCloneNodeCallback(callback);+}diff --git a/third_party/yoga/YGConfig.h b/third_party/yoga/YGConfig.hnew file mode 100644index 000000000..12f6e204a--- /dev/null+++ b/third_party/yoga/YGConfig.h@@ -0,0 +1,158 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <stdarg.h>+#include <stdbool.h>+#include <stddef.h>++#include <yoga/YGEnums.h>+#include <yoga/YGMacros.h>++YG_EXTERN_C_BEGIN++typedef struct YGNode* YGNodeRef;+typedef const struct YGNode* YGNodeConstRef;++/**+ * Handle to a mutable Yoga configuration.+ */+typedef struct YGConfig* YGConfigRef;++/**+ * Handle to an immutable Yoga configuration.+ */+typedef const struct YGConfig* YGConfigConstRef;++/**+ * Allocates a set of configuration options. The configuration may be applied to+ * multiple nodes (i.e. a single global config), or can be applied more+ * granularly per-node.+ */+YG_EXPORT YGConfigRef YGConfigNew(void);++/**+ * Frees the associated Yoga configuration.+ */+YG_EXPORT void YGConfigFree(YGConfigRef config);++/**+ * Returns the default config values set by Yoga.+ */+YG_EXPORT YGConfigConstRef YGConfigGetDefault(void);++/**+ * Yoga by default creates new nodes with style defaults different from flexbox+ * on web (e.g. `YGFlexDirectionColumn` and `YGPositionRelative`).+ * `UseWebDefaults` instructs Yoga to instead use a default style consistent+ * with the web.+ */+YG_EXPORT void YGConfigSetUseWebDefaults(YGConfigRef config, bool enabled);++/**+ * Whether the configuration is set to use web defaults.+ */+YG_EXPORT bool YGConfigGetUseWebDefaults(YGConfigConstRef config);++/**+ * Yoga will by default round final layout positions and dimensions to the+ * nearst point. `pointScaleFactor` controls the density of the grid used for+ * layout rounding (e.g. to round to the closest display pixel).+ *+ * May be set to 0.0f to avoid rounding the layout results.+ */+YG_EXPORT void YGConfigSetPointScaleFactor(+ YGConfigRef config,+ float pixelsInPoint);++/**+ * Get the currently set point scale factor.+ */+YG_EXPORT float YGConfigGetPointScaleFactor(YGConfigConstRef config);++/**+ * Configures how Yoga balances W3C conformance vs compatibility with layouts+ * created against earlier versions of Yoga.+ *+ * By default Yoga will prioritize W3C conformance. `Errata` may be set to ask+ * Yoga to produce specific incorrect behaviors. E.g. `YGConfigSetErrata(config,+ * YGErrataStretchFlexBasis)`.+ *+ * YGErrata is a bitmask, and multiple errata may be set at once. Predefined+ * constants exist for convenience:+ * 1. YGErrataNone: No errata+ * 2. YGErrataClassic: Match layout behaviors of Yoga 1.x+ * 3. YGErrataAll: Match layout behaviors of Yoga 1.x, including+ * `UseLegacyStretchBehaviour`+ */+YG_EXPORT void YGConfigSetErrata(YGConfigRef config, YGErrata errata);++/**+ * Get the currently set errata.+ */+YG_EXPORT YGErrata YGConfigGetErrata(YGConfigConstRef config);++/**+ * Function pointer type for YGConfigSetLogger.+ */+typedef int (*YGLogger)(+ YGConfigConstRef config,+ YGNodeConstRef node,+ YGLogLevel level,+ const char* format,+ va_list args);++/**+ * Set a custom log function for to use when logging diagnostics or fatal.+ * errors.+ */+YG_EXPORT void YGConfigSetLogger(YGConfigRef config, YGLogger logger);++/**+ * Sets an arbitrary context pointer on the config which may be read from during+ * callbacks.+ */+YG_EXPORT void YGConfigSetContext(YGConfigRef config, void* context);++/**+ * Gets the currently set context.+ */+YG_EXPORT void* YGConfigGetContext(YGConfigConstRef config);++/**+ * Function pointer type for YGConfigSetCloneNodeFunc.+ */+typedef YGNodeRef (*YGCloneNodeFunc)(+ YGNodeConstRef oldNode,+ YGNodeConstRef owner,+ size_t childIndex);++/**+ * Enable an experimental/unsupported feature in Yoga.+ */+YG_EXPORT void YGConfigSetExperimentalFeatureEnabled(+ YGConfigRef config,+ YGExperimentalFeature feature,+ bool enabled);++/**+ * Whether an experimental feature is set.+ */+YG_EXPORT bool YGConfigIsExperimentalFeatureEnabled(+ YGConfigConstRef config,+ YGExperimentalFeature feature);++/**+ * Sets a callback, called during layout, to create a new mutable Yoga node if+ * Yoga must write to it and its owner is not its parent observed during layout.+ */+YG_EXPORT void YGConfigSetCloneNodeFunc(+ YGConfigRef config,+ YGCloneNodeFunc callback);++YG_EXTERN_C_ENDdiff --git a/third_party/yoga/YGEnums.cpp b/third_party/yoga/YGEnums.cppnew file mode 100644index 000000000..9fc4a83a8--- /dev/null+++ b/third_party/yoga/YGEnums.cpp@@ -0,0 +1,298 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#include <yoga/YGEnums.h>++const char* YGAlignToString(const YGAlign value) {+ switch (value) {+ case YGAlignAuto:+ return "auto";+ case YGAlignFlexStart:+ return "flex-start";+ case YGAlignCenter:+ return "center";+ case YGAlignFlexEnd:+ return "flex-end";+ case YGAlignStretch:+ return "stretch";+ case YGAlignBaseline:+ return "baseline";+ case YGAlignSpaceBetween:+ return "space-between";+ case YGAlignSpaceAround:+ return "space-around";+ case YGAlignSpaceEvenly:+ return "space-evenly";+ case YGAlignStart:+ return "start";+ case YGAlignEnd:+ return "end";+ }+ return "unknown";+}++const char* YGBoxSizingToString(const YGBoxSizing value) {+ switch (value) {+ case YGBoxSizingBorderBox:+ return "border-box";+ case YGBoxSizingContentBox:+ return "content-box";+ }+ return "unknown";+}++const char* YGDimensionToString(const YGDimension value) {+ switch (value) {+ case YGDimensionWidth:+ return "width";+ case YGDimensionHeight:+ return "height";+ }+ return "unknown";+}++const char* YGDirectionToString(const YGDirection value) {+ switch (value) {+ case YGDirectionInherit:+ return "inherit";+ case YGDirectionLTR:+ return "ltr";+ case YGDirectionRTL:+ return "rtl";+ }+ return "unknown";+}++const char* YGDisplayToString(const YGDisplay value) {+ switch (value) {+ case YGDisplayFlex:+ return "flex";+ case YGDisplayNone:+ return "none";+ case YGDisplayContents:+ return "contents";+ case YGDisplayGrid:+ return "grid";+ }+ return "unknown";+}++const char* YGEdgeToString(const YGEdge value) {+ switch (value) {+ case YGEdgeLeft:+ return "left";+ case YGEdgeTop:+ return "top";+ case YGEdgeRight:+ return "right";+ case YGEdgeBottom:+ return "bottom";+ case YGEdgeStart:+ return "start";+ case YGEdgeEnd:+ return "end";+ case YGEdgeHorizontal:+ return "horizontal";+ case YGEdgeVertical:+ return "vertical";+ case YGEdgeAll:+ return "all";+ }+ return "unknown";+}++const char* YGErrataToString(const YGErrata value) {+ switch (value) {+ case YGErrataNone:+ return "none";+ case YGErrataStretchFlexBasis:+ return "stretch-flex-basis";+ case YGErrataAbsolutePositionWithoutInsetsExcludesPadding:+ return "absolute-position-without-insets-excludes-padding";+ case YGErrataAbsolutePercentAgainstInnerSize:+ return "absolute-percent-against-inner-size";+ case YGErrataAll:+ return "all";+ case YGErrataClassic:+ return "classic";+ }+ return "unknown";+}++const char* YGExperimentalFeatureToString(const YGExperimentalFeature value) {+ switch (value) {+ case YGExperimentalFeatureWebFlexBasis:+ return "web-flex-basis";+ }+ return "unknown";+}++const char* YGFlexDirectionToString(const YGFlexDirection value) {+ switch (value) {+ case YGFlexDirectionColumn:+ return "column";+ case YGFlexDirectionColumnReverse:+ return "column-reverse";+ case YGFlexDirectionRow:+ return "row";+ case YGFlexDirectionRowReverse:+ return "row-reverse";+ }+ return "unknown";+}++const char* YGGridTrackTypeToString(const YGGridTrackType value) {+ switch (value) {+ case YGGridTrackTypeAuto:+ return "auto";+ case YGGridTrackTypePoints:+ return "points";+ case YGGridTrackTypePercent:+ return "percent";+ case YGGridTrackTypeFr:+ return "fr";+ case YGGridTrackTypeMinmax:+ return "minmax";+ }+ return "unknown";+}++const char* YGGutterToString(const YGGutter value) {+ switch (value) {+ case YGGutterColumn:+ return "column";+ case YGGutterRow:+ return "row";+ case YGGutterAll:+ return "all";+ }+ return "unknown";+}++const char* YGJustifyToString(const YGJustify value) {+ switch (value) {+ case YGJustifyAuto:+ return "auto";+ case YGJustifyFlexStart:+ return "flex-start";+ case YGJustifyCenter:+ return "center";+ case YGJustifyFlexEnd:+ return "flex-end";+ case YGJustifySpaceBetween:+ return "space-between";+ case YGJustifySpaceAround:+ return "space-around";+ case YGJustifySpaceEvenly:+ return "space-evenly";+ case YGJustifyStretch:+ return "stretch";+ case YGJustifyStart:+ return "start";+ case YGJustifyEnd:+ return "end";+ }+ return "unknown";+}++const char* YGLogLevelToString(const YGLogLevel value) {+ switch (value) {+ case YGLogLevelError:+ return "error";+ case YGLogLevelWarn:+ return "warn";+ case YGLogLevelInfo:+ return "info";+ case YGLogLevelDebug:+ return "debug";+ case YGLogLevelVerbose:+ return "verbose";+ case YGLogLevelFatal:+ return "fatal";+ }+ return "unknown";+}++const char* YGMeasureModeToString(const YGMeasureMode value) {+ switch (value) {+ case YGMeasureModeUndefined:+ return "undefined";+ case YGMeasureModeExactly:+ return "exactly";+ case YGMeasureModeAtMost:+ return "at-most";+ }+ return "unknown";+}++const char* YGNodeTypeToString(const YGNodeType value) {+ switch (value) {+ case YGNodeTypeDefault:+ return "default";+ case YGNodeTypeText:+ return "text";+ }+ return "unknown";+}++const char* YGOverflowToString(const YGOverflow value) {+ switch (value) {+ case YGOverflowVisible:+ return "visible";+ case YGOverflowHidden:+ return "hidden";+ case YGOverflowScroll:+ return "scroll";+ }+ return "unknown";+}++const char* YGPositionTypeToString(const YGPositionType value) {+ switch (value) {+ case YGPositionTypeStatic:+ return "static";+ case YGPositionTypeRelative:+ return "relative";+ case YGPositionTypeAbsolute:+ return "absolute";+ }+ return "unknown";+}++const char* YGUnitToString(const YGUnit value) {+ switch (value) {+ case YGUnitUndefined:+ return "undefined";+ case YGUnitPoint:+ return "point";+ case YGUnitPercent:+ return "percent";+ case YGUnitAuto:+ return "auto";+ case YGUnitMaxContent:+ return "max-content";+ case YGUnitFitContent:+ return "fit-content";+ case YGUnitStretch:+ return "stretch";+ }+ return "unknown";+}++const char* YGWrapToString(const YGWrap value) {+ switch (value) {+ case YGWrapNoWrap:+ return "no-wrap";+ case YGWrapWrap:+ return "wrap";+ case YGWrapWrapReverse:+ return "wrap-reverse";+ }+ return "unknown";+}diff --git a/third_party/yoga/YGEnums.h b/third_party/yoga/YGEnums.hnew file mode 100644index 000000000..1b69f0931--- /dev/null+++ b/third_party/yoga/YGEnums.h@@ -0,0 +1,160 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once+#include <yoga/YGMacros.h>++YG_EXTERN_C_BEGIN++YG_ENUM_DECL(+ YGAlign,+ YGAlignAuto,+ YGAlignFlexStart,+ YGAlignCenter,+ YGAlignFlexEnd,+ YGAlignStretch,+ YGAlignBaseline,+ YGAlignSpaceBetween,+ YGAlignSpaceAround,+ YGAlignSpaceEvenly,+ YGAlignStart,+ YGAlignEnd)++YG_ENUM_DECL(+ YGBoxSizing,+ YGBoxSizingBorderBox,+ YGBoxSizingContentBox)++YG_ENUM_DECL(+ YGDimension,+ YGDimensionWidth,+ YGDimensionHeight)++YG_ENUM_DECL(+ YGDirection,+ YGDirectionInherit,+ YGDirectionLTR,+ YGDirectionRTL)++YG_ENUM_DECL(+ YGDisplay,+ YGDisplayFlex,+ YGDisplayNone,+ YGDisplayContents,+ YGDisplayGrid)++YG_ENUM_DECL(+ YGEdge,+ YGEdgeLeft,+ YGEdgeTop,+ YGEdgeRight,+ YGEdgeBottom,+ YGEdgeStart,+ YGEdgeEnd,+ YGEdgeHorizontal,+ YGEdgeVertical,+ YGEdgeAll)++YG_ENUM_DECL(+ YGErrata,+ YGErrataNone = 0,+ YGErrataStretchFlexBasis = 1,+ YGErrataAbsolutePositionWithoutInsetsExcludesPadding = 2,+ YGErrataAbsolutePercentAgainstInnerSize = 4,+ YGErrataAll = 2147483647,+ YGErrataClassic = 2147483646)+YG_DEFINE_ENUM_FLAG_OPERATORS(YGErrata)++YG_ENUM_DECL(+ YGExperimentalFeature,+ YGExperimentalFeatureWebFlexBasis)++YG_ENUM_DECL(+ YGFlexDirection,+ YGFlexDirectionColumn,+ YGFlexDirectionColumnReverse,+ YGFlexDirectionRow,+ YGFlexDirectionRowReverse)++YG_ENUM_DECL(+ YGGridTrackType,+ YGGridTrackTypeAuto,+ YGGridTrackTypePoints,+ YGGridTrackTypePercent,+ YGGridTrackTypeFr,+ YGGridTrackTypeMinmax)++YG_ENUM_DECL(+ YGGutter,+ YGGutterColumn,+ YGGutterRow,+ YGGutterAll)++YG_ENUM_DECL(+ YGJustify,+ YGJustifyAuto,+ YGJustifyFlexStart,+ YGJustifyCenter,+ YGJustifyFlexEnd,+ YGJustifySpaceBetween,+ YGJustifySpaceAround,+ YGJustifySpaceEvenly,+ YGJustifyStretch,+ YGJustifyStart,+ YGJustifyEnd)++YG_ENUM_DECL(+ YGLogLevel,+ YGLogLevelError,+ YGLogLevelWarn,+ YGLogLevelInfo,+ YGLogLevelDebug,+ YGLogLevelVerbose,+ YGLogLevelFatal)++YG_ENUM_DECL(+ YGMeasureMode,+ YGMeasureModeUndefined,+ YGMeasureModeExactly,+ YGMeasureModeAtMost)++YG_ENUM_DECL(+ YGNodeType,+ YGNodeTypeDefault,+ YGNodeTypeText)++YG_ENUM_DECL(+ YGOverflow,+ YGOverflowVisible,+ YGOverflowHidden,+ YGOverflowScroll)++YG_ENUM_DECL(+ YGPositionType,+ YGPositionTypeStatic,+ YGPositionTypeRelative,+ YGPositionTypeAbsolute)++YG_ENUM_DECL(+ YGUnit,+ YGUnitUndefined,+ YGUnitPoint,+ YGUnitPercent,+ YGUnitAuto,+ YGUnitMaxContent,+ YGUnitFitContent,+ YGUnitStretch)++YG_ENUM_DECL(+ YGWrap,+ YGWrapNoWrap,+ YGWrapWrap,+ YGWrapWrapReverse)++YG_EXTERN_C_ENDdiff --git a/third_party/yoga/YGMacros.h b/third_party/yoga/YGMacros.hnew file mode 100644index 000000000..ab9b2627a--- /dev/null+++ b/third_party/yoga/YGMacros.h@@ -0,0 +1,101 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#ifdef __cplusplus+#include <type_traits>+#endif++#ifdef __cplusplus+#define YG_EXTERN_C_BEGIN extern "C" {+#define YG_EXTERN_C_END }+#else+#define YG_EXTERN_C_BEGIN+#define YG_EXTERN_C_END+#endif++#if defined(__cplusplus)+#define YG_DEPRECATED(message) [[deprecated(message)]]+#elif defined(_MSC_VER)+#define YG_DEPRECATED(message) __declspec(deprecated(message))+#else+#define YG_DEPRECATED(message) __attribute__((deprecated(message)))+#endif++#ifdef _WINDLL+#define YG_EXPORT __declspec(dllexport)+#elif defined(__EMSCRIPTEN__)+#define YG_EXPORT __attribute__((visibility("default"), used))+#elif !defined(_MSC_VER)+#define YG_EXPORT __attribute__((visibility("default")))+#else+#define YG_EXPORT+#endif++#ifdef __OBJC__+#if __has_include(<Foundation/Foundation.h>)+#import <Foundation/Foundation.h>+#endif+#endif++#ifdef NS_ENUM+// Cannot use NSInteger as NSInteger has a different size than int (which is the+// default type of a enum). Therefor when linking the Yoga C library into obj-c+// the header is a mismatch for the Yoga ABI.+#define YG_ENUM_BEGIN(name) NS_ENUM(int, name)+#define YG_ENUM_END(name)+#else+#define YG_ENUM_BEGIN(name) enum name+#define YG_ENUM_END(name) name+#endif++#ifdef __cplusplus+#define YG_DEFINE_ENUM_FLAG_OPERATORS(name) \+ extern "C++" { \+ constexpr name operator~(name a) { \+ return static_cast<name>( \+ ~static_cast<std::underlying_type<name>::type>(a)); \+ } \+ constexpr name operator|(name a, name b) { \+ return static_cast<name>( \+ static_cast<std::underlying_type<name>::type>(a) | \+ static_cast<std::underlying_type<name>::type>(b)); \+ } \+ constexpr name operator&(name a, name b) { \+ return static_cast<name>( \+ static_cast<std::underlying_type<name>::type>(a) & \+ static_cast<std::underlying_type<name>::type>(b)); \+ } \+ constexpr name operator^(name a, name b) { \+ return static_cast<name>( \+ static_cast<std::underlying_type<name>::type>(a) ^ \+ static_cast<std::underlying_type<name>::type>(b)); \+ } \+ inline name& operator|=(name& a, name b) { \+ return reinterpret_cast<name&>( \+ reinterpret_cast<std::underlying_type<name>::type&>(a) |= \+ static_cast<std::underlying_type<name>::type>(b)); \+ } \+ inline name& operator&=(name& a, name b) { \+ return reinterpret_cast<name&>( \+ reinterpret_cast<std::underlying_type<name>::type&>(a) &= \+ static_cast<std::underlying_type<name>::type>(b)); \+ } \+ inline name& operator^=(name& a, name b) { \+ return reinterpret_cast<name&>( \+ reinterpret_cast<std::underlying_type<name>::type&>(a) ^= \+ static_cast<std::underlying_type<name>::type>(b)); \+ } \+ }+#else+#define YG_DEFINE_ENUM_FLAG_OPERATORS(name)+#endif++#define YG_ENUM_DECL(NAME, ...) \+ typedef YG_ENUM_BEGIN(NAME){__VA_ARGS__} YG_ENUM_END(NAME); \+ YG_EXPORT const char* NAME##ToString(NAME);diff --git a/third_party/yoga/YGNode.cpp b/third_party/yoga/YGNode.cppnew file mode 100644index 000000000..f55cab6be--- /dev/null+++ b/third_party/yoga/YGNode.cpp@@ -0,0 +1,380 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/Yoga.h>++#include <yoga/algorithm/Cache.h>+#include <yoga/algorithm/CalculateLayout.h>+#include <yoga/debug/AssertFatal.h>+#include <yoga/debug/Log.h>+#include <yoga/event/event.h>+#include <yoga/node/Node.h>++using namespace facebook;+using namespace facebook::yoga;++YGNodeRef YGNodeNew(void) {+ return YGNodeNewWithConfig(YGConfigGetDefault());+}++YGNodeRef YGNodeNewWithConfig(const YGConfigConstRef config) {+ auto* node = new yoga::Node{resolveRef(config)};+ yoga::assertFatal(+ config != nullptr, "Tried to construct YGNode with null config");+ Event::publish<Event::NodeAllocation>(node, {config});++ return node;+}++YGNodeRef YGNodeClone(YGNodeConstRef oldNodeRef) {+ auto oldNode = resolveRef(oldNodeRef);+ const auto node = new yoga::Node(*oldNode);+ Event::publish<Event::NodeAllocation>(node, {node->getConfig()});+ node->setOwner(nullptr);+ return node;+}++void YGNodeFree(const YGNodeRef nodeRef) {+ const auto node = resolveRef(nodeRef);++ if (auto owner = node->getOwner()) {+ owner->removeChild(node);+ node->setOwner(nullptr);+ }++ const size_t childCount = node->getChildCount();+ for (size_t i = 0; i < childCount; i++) {+ auto child = node->getChild(i);+ child->setOwner(nullptr);+ }++ node->clearChildren();++ Event::publish<Event::NodeDeallocation>(node, {YGNodeGetConfig(node)});+ delete resolveRef(node);+}++void YGNodeFreeRecursive(YGNodeRef rootRef) {+ const auto root = resolveRef(rootRef);++ size_t skipped = 0;+ while (root->getChildCount() > skipped) {+ const auto child = root->getChild(skipped);+ if (child->getOwner() != root) {+ // Don't free shared nodes that we don't own.+ skipped += 1;+ } else {+ YGNodeRemoveChild(root, child);+ YGNodeFreeRecursive(child);+ }+ }+ YGNodeFree(root);+}++void YGNodeFinalize(const YGNodeRef node) {+ Event::publish<Event::NodeDeallocation>(node, {YGNodeGetConfig(node)});+ delete resolveRef(node);+}++void YGNodeReset(YGNodeRef node) {+ resolveRef(node)->reset();+}++void YGNodeCalculateLayout(+ const YGNodeRef node,+ const float ownerWidth,+ const float ownerHeight,+ const YGDirection ownerDirection) {+ yoga::calculateLayout(+ resolveRef(node), ownerWidth, ownerHeight, scopedEnum(ownerDirection));+}++bool YGNodeGetHasNewLayout(YGNodeConstRef node) {+ return resolveRef(node)->getHasNewLayout();+}++void YGNodeSetHasNewLayout(YGNodeRef node, bool hasNewLayout) {+ resolveRef(node)->setHasNewLayout(hasNewLayout);+}++bool YGNodeIsDirty(YGNodeConstRef node) {+ return resolveRef(node)->isDirty();+}++void YGNodeMarkDirty(const YGNodeRef nodeRef) {+ const auto node = resolveRef(nodeRef);++ yoga::assertFatalWithNode(+ node,+ node->hasMeasureFunc(),+ "Only leaf nodes with custom measure functions "+ "should manually mark themselves as dirty");++ node->markDirtyAndPropagate();+}++void YGNodeSetDirtiedFunc(YGNodeRef node, YGDirtiedFunc dirtiedFunc) {+ resolveRef(node)->setDirtiedFunc(dirtiedFunc);+}++YGDirtiedFunc YGNodeGetDirtiedFunc(YGNodeConstRef node) {+ return resolveRef(node)->getDirtiedFunc();+}++void YGNodeInsertChild(+ const YGNodeRef ownerRef,+ const YGNodeRef childRef,+ const size_t index) {+ auto owner = resolveRef(ownerRef);+ auto child = resolveRef(childRef);++ yoga::assertFatalWithNode(+ owner,+ child->getOwner() == nullptr,+ "Child already has a owner, it must be removed first.");++ yoga::assertFatalWithNode(+ owner,+ !owner->hasMeasureFunc(),+ "Cannot add child: Nodes with measure functions cannot have children.");++ owner->insertChild(child, index);+ child->setOwner(owner);+ owner->markDirtyAndPropagate();+}++void YGNodeSwapChild(+ const YGNodeRef ownerRef,+ const YGNodeRef childRef,+ const size_t index) {+ auto owner = resolveRef(ownerRef);+ auto child = resolveRef(childRef);++ owner->replaceChild(child, index);+ child->setOwner(owner);+}++void YGNodeRemoveChild(+ const YGNodeRef ownerRef,+ const YGNodeRef excludedChildRef) {+ auto owner = resolveRef(ownerRef);+ auto excludedChild = resolveRef(excludedChildRef);++ if (owner->getChildCount() == 0) {+ // This is an empty set. Nothing to remove.+ return;+ }++ // Children may be shared between parents, which is indicated by not having an+ // owner. We only want to reset the child completely if it is owned+ // exclusively by one node.+ auto childOwner = excludedChild->getOwner();+ if (owner->removeChild(excludedChild)) {+ if (owner == childOwner) {+ excludedChild->setLayout({}); // layout is no longer valid+ excludedChild->setOwner(nullptr);+ // Mark dirty to invalidate cache, but suppress the dirtied callback+ // since the node is being detached from the tree and should not+ // propagate dirty signals through external callback mechanisms.+ auto dirtiedFunc = excludedChild->getDirtiedFunc();+ excludedChild->setDirtiedFunc(nullptr);+ excludedChild->setDirty(true);+ excludedChild->setDirtiedFunc(dirtiedFunc);+ }+ owner->markDirtyAndPropagate();+ }+}++void YGNodeRemoveAllChildren(const YGNodeRef ownerRef) {+ auto owner = resolveRef(ownerRef);++ const size_t childCount = owner->getChildCount();+ if (childCount == 0) {+ // This is an empty set already. Nothing to do.+ return;+ }+ auto* firstChild = owner->getChild(0);+ if (firstChild->getOwner() == owner) {+ // If the first child has this node as its owner, we assume that this child+ // set is unique.+ for (size_t i = 0; i < childCount; i++) {+ yoga::Node* oldChild = owner->getChild(i);+ oldChild->setLayout({}); // layout is no longer valid+ oldChild->setOwner(nullptr);+ // Mark dirty to invalidate cache, but suppress the dirtied callback+ // since the node is being detached from the tree and should not+ // propagate dirty signals through external callback mechanisms.+ auto dirtiedFunc = oldChild->getDirtiedFunc();+ oldChild->setDirtiedFunc(nullptr);+ oldChild->setDirty(true);+ oldChild->setDirtiedFunc(dirtiedFunc);+ }+ owner->clearChildren();+ owner->markDirtyAndPropagate();+ return;+ }+ // Otherwise, we are not the owner of the child set. We don't have to do+ // anything to clear it.+ owner->setChildren({});+ owner->markDirtyAndPropagate();+}++void YGNodeSetChildren(+ const YGNodeRef ownerRef,+ const YGNodeRef* childrenRefs,+ const size_t count) {+ auto owner = resolveRef(ownerRef);+ auto children = reinterpret_cast<yoga::Node* const*>(childrenRefs);++ if (owner == nullptr) {+ return;+ }++ const std::vector<yoga::Node*> childrenVector = {children, children + count};+ if (childrenVector.empty()) {+ if (owner->getChildCount() > 0) {+ for (auto* child : owner->getChildren()) {+ child->setLayout({});+ child->setOwner(nullptr);+ }+ owner->setChildren({});+ owner->markDirtyAndPropagate();+ }+ } else {+ if (owner->getChildCount() > 0) {+ for (auto* oldChild : owner->getChildren()) {+ // Our new children may have nodes in common with the old children. We+ // don't reset these common nodes.+ if (std::find(childrenVector.begin(), childrenVector.end(), oldChild) ==+ childrenVector.end()) {+ oldChild->setLayout({});+ oldChild->setOwner(nullptr);+ }+ }+ }+ owner->setChildren(childrenVector);+ for (yoga::Node* child : childrenVector) {+ child->setOwner(owner);+ }+ owner->markDirtyAndPropagate();+ }+}++YGNodeRef YGNodeGetChild(const YGNodeRef nodeRef, const size_t index) {+ const auto node = resolveRef(nodeRef);++ if (index < node->getChildren().size()) {+ return node->getChild(index);+ }+ return nullptr;+}++size_t YGNodeGetChildCount(const YGNodeConstRef node) {+ return resolveRef(node)->getChildren().size();+}++YGNodeRef YGNodeGetOwner(const YGNodeRef node) {+ return resolveRef(node)->getOwner();+}++YGNodeRef YGNodeGetParent(const YGNodeRef node) {+ return resolveRef(node)->getOwner();+}++void YGNodeSetConfig(YGNodeRef node, YGConfigRef config) {+ resolveRef(node)->setConfig(resolveRef(config));+}++YGConfigConstRef YGNodeGetConfig(YGNodeRef node) {+ return resolveRef(node)->getConfig();+}++void YGNodeSetContext(YGNodeRef node, void* context) {+ return resolveRef(node)->setContext(context);+}++void* YGNodeGetContext(YGNodeConstRef node) {+ return resolveRef(node)->getContext();+}++void YGNodeSetMeasureFunc(YGNodeRef node, YGMeasureFunc measureFunc) {+ resolveRef(node)->setMeasureFunc(measureFunc);+}++bool YGNodeHasMeasureFunc(YGNodeConstRef node) {+ return resolveRef(node)->hasMeasureFunc();+}++void YGNodeSetBaselineFunc(YGNodeRef node, YGBaselineFunc baselineFunc) {+ resolveRef(node)->setBaselineFunc(baselineFunc);+}++bool YGNodeHasBaselineFunc(YGNodeConstRef node) {+ return resolveRef(node)->hasBaselineFunc();+}++void YGNodeSetIsReferenceBaseline(YGNodeRef nodeRef, bool isReferenceBaseline) {+ const auto node = resolveRef(nodeRef);+ if (node->isReferenceBaseline() != isReferenceBaseline) {+ node->setIsReferenceBaseline(isReferenceBaseline);+ node->markDirtyAndPropagate();+ }+}++bool YGNodeIsReferenceBaseline(YGNodeConstRef node) {+ return resolveRef(node)->isReferenceBaseline();+}++void YGNodeSetNodeType(YGNodeRef node, YGNodeType nodeType) {+ return resolveRef(node)->setNodeType(scopedEnum(nodeType));+}++YGNodeType YGNodeGetNodeType(YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->getNodeType());+}++void YGNodeSetAlwaysFormsContainingBlock(+ YGNodeRef node,+ bool alwaysFormsContainingBlock) {+ resolveRef(node)->setAlwaysFormsContainingBlock(alwaysFormsContainingBlock);+}++bool YGNodeGetAlwaysFormsContainingBlock(YGNodeConstRef node) {+ return resolveRef(node)->alwaysFormsContainingBlock();+}++// TODO: This leaks internal details to the public API. Remove after removing+// ComponentKit usage of it.+bool YGNodeCanUseCachedMeasurement(+ YGMeasureMode widthMode,+ float availableWidth,+ YGMeasureMode heightMode,+ float availableHeight,+ YGMeasureMode lastWidthMode,+ float lastAvailableWidth,+ YGMeasureMode lastHeightMode,+ float lastAvailableHeight,+ float lastComputedWidth,+ float lastComputedHeight,+ float marginRow,+ float marginColumn,+ YGConfigRef config) {+ return yoga::canUseCachedMeasurement(+ sizingMode(scopedEnum(widthMode)),+ availableWidth,+ sizingMode(scopedEnum(heightMode)),+ availableHeight,+ sizingMode(scopedEnum(lastWidthMode)),+ lastAvailableWidth,+ sizingMode(scopedEnum(lastHeightMode)),+ lastAvailableHeight,+ lastComputedWidth,+ lastComputedHeight,+ marginRow,+ marginColumn,+ resolveRef(config));+}diff --git a/third_party/yoga/YGNode.h b/third_party/yoga/YGNode.hnew file mode 100644index 000000000..de797b82c--- /dev/null+++ b/third_party/yoga/YGNode.h@@ -0,0 +1,304 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <stdbool.h>+#include <stddef.h>++#include <yoga/YGConfig.h>+#include <yoga/YGEnums.h>+#include <yoga/YGMacros.h>++YG_EXTERN_C_BEGIN++/**+ * Handle to a mutable Yoga Node.+ */+typedef struct YGNode* YGNodeRef;++/**+ * Handle to an immutable Yoga Node.+ */+typedef const struct YGNode* YGNodeConstRef;++/**+ * Heap allocates and returns a new Yoga node using Yoga settings.+ */+YG_EXPORT YGNodeRef YGNodeNew(void);++/**+ * Heap allocates and returns a new Yoga node, with customized settings.+ */+YG_EXPORT YGNodeRef YGNodeNewWithConfig(YGConfigConstRef config);++/**+ * Returns a mutable copy of an existing node, with the same context and+ * children, but no owner set. Does not call the function set by+ * YGConfigSetCloneNodeFunc().+ */+YG_EXPORT YGNodeRef YGNodeClone(YGNodeConstRef node);++/**+ * Frees the Yoga node, disconnecting it from its owner and children.+ */+YG_EXPORT void YGNodeFree(YGNodeRef node);++/**+ * Frees the subtree of Yoga nodes rooted at the given node.+ */+YG_EXPORT void YGNodeFreeRecursive(YGNodeRef node);++/**+ * Frees the Yoga node without disconnecting it from its owner or children.+ * Allows garbage collecting Yoga nodes in parallel when the entire tree is+ * unreachable.+ */+YG_EXPORT void YGNodeFinalize(YGNodeRef node);++/**+ * Resets the node to its default state.+ */+YG_EXPORT void YGNodeReset(YGNodeRef node);++/**+ * Calculates the layout of the tree rooted at the given node.+ *+ * Layout results may be read after calling YGNodeCalculateLayout() using+ * functions like YGNodeLayoutGetLeft(), YGNodeLayoutGetTop(), etc.+ *+ * YGNodeGetHasNewLayout() may be read to know if the layout of the node or its+ * subtrees may have changed since the last time YGNodeCalculate() was called.+ */+YG_EXPORT void YGNodeCalculateLayout(+ YGNodeRef node,+ float availableWidth,+ float availableHeight,+ YGDirection ownerDirection);++/**+ * Whether the given node may have new layout results. Must be reset by calling+ * YGNodeSetHasNewLayout().+ */+YG_EXPORT bool YGNodeGetHasNewLayout(YGNodeConstRef node);++/**+ * Sets whether a nodes layout is considered new.+ */+YG_EXPORT void YGNodeSetHasNewLayout(YGNodeRef node, bool hasNewLayout);++/**+ * Whether the node's layout results are dirty due to it or its children+ * changing.+ */+YG_EXPORT bool YGNodeIsDirty(YGNodeConstRef node);++/**+ * Marks a node with custom measure function as dirty.+ */+YG_EXPORT void YGNodeMarkDirty(YGNodeRef node);++typedef void (*YGDirtiedFunc)(YGNodeConstRef node);++/**+ * Called when a change is made to the Yoga tree which dirties this node.+ */+YG_EXPORT void YGNodeSetDirtiedFunc(YGNodeRef node, YGDirtiedFunc dirtiedFunc);++/**+ * Returns a dirtied func if set.+ */+YG_EXPORT YGDirtiedFunc YGNodeGetDirtiedFunc(YGNodeConstRef node);++/**+ * Inserts a child node at the given index.+ */+YG_EXPORT void YGNodeInsertChild(YGNodeRef node, YGNodeRef child, size_t index);++/**+ * Replaces the child node at a given index with a new one.+ */+YG_EXPORT void YGNodeSwapChild(YGNodeRef node, YGNodeRef child, size_t index);++/**+ * Removes the given child node.+ */+YG_EXPORT void YGNodeRemoveChild(YGNodeRef node, YGNodeRef child);++/**+ * Removes all children nodes.+ */+YG_EXPORT void YGNodeRemoveAllChildren(YGNodeRef node);++/**+ * Sets children according to the given list of nodes.+ */+YG_EXPORT void+YGNodeSetChildren(YGNodeRef owner, const YGNodeRef* children, size_t count);++/**+ * Get the child node at a given index.+ */+YG_EXPORT YGNodeRef YGNodeGetChild(YGNodeRef node, size_t index);++/**+ * The number of child nodes.+ */+YG_EXPORT size_t YGNodeGetChildCount(YGNodeConstRef node);++/**+ * Get the parent/owner currently set for a node.+ */+YG_EXPORT YGNodeRef YGNodeGetOwner(YGNodeRef node);++/**+ * Get the parent/owner currently set for a node.+ */+YG_EXPORT YGNodeRef YGNodeGetParent(YGNodeRef node);++/**+ * Set a new config for the node after creation.+ */+YG_EXPORT void YGNodeSetConfig(YGNodeRef node, YGConfigRef config);++/**+ * Get the config currently set on the node.+ */+YG_EXPORT YGConfigConstRef YGNodeGetConfig(YGNodeRef node);++/**+ * Sets extra data on the Yoga node which may be read from during callbacks.+ */+YG_EXPORT void YGNodeSetContext(YGNodeRef node, void* context);++/**+ * Returns the context or NULL if no context has been set.+ */+YG_EXPORT void* YGNodeGetContext(YGNodeConstRef node);++typedef struct YGSize {+ float width;+ float height;+} YGSize;++/**+ * Returns the computed dimensions of the node, following the constraints of+ * `widthMode` and `heightMode`:+ *+ * YGMeasureModeUndefined: The parent has not imposed any constraint on the+ * child. It can be whatever size it wants.+ *+ * YGMeasureModeAtMost: The child can be as large as it wants up to the+ * specified size.+ *+ * YGMeasureModeExactly: The parent has determined an exact size for the+ * child. The child is going to be given those bounds regardless of how big it+ * wants to be.+ *+ * @returns the size of the leaf node, measured under the given constraints.+ */+typedef YGSize (*YGMeasureFunc)(+ YGNodeConstRef node,+ float width,+ YGMeasureMode widthMode,+ float height,+ YGMeasureMode heightMode);++/**+ * Allows providing custom measurements for a Yoga leaf node (usually for+ * measuring text). YGNodeMarkDirty() must be set if content effecting the+ * measurements of the node changes.+ */+YG_EXPORT void YGNodeSetMeasureFunc(YGNodeRef node, YGMeasureFunc measureFunc);++/**+ * Whether a measure function is set.+ */+YG_EXPORT bool YGNodeHasMeasureFunc(YGNodeConstRef node);++/**+ * @returns a defined offset to baseline (ascent).+ */+typedef float (*YGBaselineFunc)(YGNodeConstRef node, float width, float height);++/**+ * Set a custom function for determining the text baseline for use in baseline+ * alignment.+ */+YG_EXPORT void YGNodeSetBaselineFunc(+ YGNodeRef node,+ YGBaselineFunc baselineFunc);++/**+ * Whether a baseline function is set.+ */+YG_EXPORT bool YGNodeHasBaselineFunc(YGNodeConstRef node);++/**+ * Sets this node should be considered the reference baseline among siblings.+ */+YG_EXPORT void YGNodeSetIsReferenceBaseline(+ YGNodeRef node,+ bool isReferenceBaseline);++/**+ * Whether this node is set as the reference baseline.+ */+YG_EXPORT bool YGNodeIsReferenceBaseline(YGNodeConstRef node);++/**+ * Sets whether a leaf node's layout results may be truncated during layout+ * rounding.+ */+YG_EXPORT void YGNodeSetNodeType(YGNodeRef node, YGNodeType nodeType);++/**+ * Wwhether a leaf node's layout results may be truncated during layout+ * rounding.+ */+YG_EXPORT YGNodeType YGNodeGetNodeType(YGNodeConstRef node);++/**+ * Make it so that this node will always form a containing block for any+ * descendant nodes. This is useful for when a node has a property outside of+ * of Yoga that will form a containing block. For example, transforms or some of+ * the others listed in+ * https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block+ */+YG_EXPORT void YGNodeSetAlwaysFormsContainingBlock(+ YGNodeRef node,+ bool alwaysFormsContainingBlock);++/**+ * Whether the node will always form a containing block for any descendant. This+ * can happen in situation where the client implements something like a+ * transform that can affect containing blocks but is not handled by Yoga+ * directly.+ */+YG_EXPORT bool YGNodeGetAlwaysFormsContainingBlock(YGNodeConstRef node);++/**+ * @deprecated+ */+YG_DEPRECATED(+ "YGNodeCanUseCachedMeasurement may be removed in a future version of Yoga")+YG_EXPORT bool YGNodeCanUseCachedMeasurement(+ YGMeasureMode widthMode,+ float availableWidth,+ YGMeasureMode heightMode,+ float availableHeight,+ YGMeasureMode lastWidthMode,+ float lastAvailableWidth,+ YGMeasureMode lastHeightMode,+ float lastAvailableHeight,+ float lastComputedWidth,+ float lastComputedHeight,+ float marginRow,+ float marginColumn,+ YGConfigRef config);++YG_EXTERN_C_ENDdiff --git a/third_party/yoga/YGNodeLayout.cpp b/third_party/yoga/YGNodeLayout.cppnew file mode 100644index 000000000..50c8766eb--- /dev/null+++ b/third_party/yoga/YGNodeLayout.cpp@@ -0,0 +1,100 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/Yoga.h>+#include <yoga/debug/AssertFatal.h>+#include <yoga/enums/Edge.h>+#include <yoga/node/Node.h>++using namespace facebook;+using namespace facebook::yoga;++namespace {++template <auto LayoutMember>+float getResolvedLayoutProperty(const YGNodeConstRef nodeRef, const Edge edge) {+ const auto node = resolveRef(nodeRef);+ yoga::assertFatalWithNode(+ node,+ edge <= Edge::End,+ "Cannot get layout properties of multi-edge shorthands");++ if (edge == Edge::Start) {+ if (node->getLayout().direction() == Direction::RTL) {+ return (node->getLayout().*LayoutMember)(PhysicalEdge::Right);+ } else {+ return (node->getLayout().*LayoutMember)(PhysicalEdge::Left);+ }+ }++ if (edge == Edge::End) {+ if (node->getLayout().direction() == Direction::RTL) {+ return (node->getLayout().*LayoutMember)(PhysicalEdge::Left);+ } else {+ return (node->getLayout().*LayoutMember)(PhysicalEdge::Right);+ }+ }++ return (node->getLayout().*LayoutMember)(static_cast<PhysicalEdge>(edge));+}++} // namespace++float YGNodeLayoutGetLeft(const YGNodeConstRef node) {+ return resolveRef(node)->getLayout().position(PhysicalEdge::Left);+}++float YGNodeLayoutGetTop(const YGNodeConstRef node) {+ return resolveRef(node)->getLayout().position(PhysicalEdge::Top);+}++float YGNodeLayoutGetRight(const YGNodeConstRef node) {+ return resolveRef(node)->getLayout().position(PhysicalEdge::Right);+}++float YGNodeLayoutGetBottom(const YGNodeConstRef node) {+ return resolveRef(node)->getLayout().position(PhysicalEdge::Bottom);+}++float YGNodeLayoutGetWidth(const YGNodeConstRef node) {+ return resolveRef(node)->getLayout().dimension(Dimension::Width);+}++float YGNodeLayoutGetHeight(const YGNodeConstRef node) {+ return resolveRef(node)->getLayout().dimension(Dimension::Height);+}++YGDirection YGNodeLayoutGetDirection(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->getLayout().direction());+}++bool YGNodeLayoutGetHadOverflow(const YGNodeConstRef node) {+ return resolveRef(node)->getLayout().hadOverflow();+}++float YGNodeLayoutGetMargin(YGNodeConstRef node, YGEdge edge) {+ return getResolvedLayoutProperty<&LayoutResults::margin>(+ node, scopedEnum(edge));+}++float YGNodeLayoutGetBorder(YGNodeConstRef node, YGEdge edge) {+ return getResolvedLayoutProperty<&LayoutResults::border>(+ node, scopedEnum(edge));+}++float YGNodeLayoutGetPadding(YGNodeConstRef node, YGEdge edge) {+ return getResolvedLayoutProperty<&LayoutResults::padding>(+ node, scopedEnum(edge));+}++float YGNodeLayoutGetRawHeight(YGNodeConstRef node) {+ return resolveRef(node)->getLayout().rawDimension(Dimension::Height);+}++float YGNodeLayoutGetRawWidth(YGNodeConstRef node) {+ return resolveRef(node)->getLayout().rawDimension(Dimension::Width);+}diff --git a/third_party/yoga/YGNodeLayout.h b/third_party/yoga/YGNodeLayout.hnew file mode 100644index 000000000..4f25af213--- /dev/null+++ b/third_party/yoga/YGNodeLayout.h@@ -0,0 +1,45 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <stdbool.h>++#include <yoga/YGConfig.h>+#include <yoga/YGEnums.h>+#include <yoga/YGMacros.h>++YG_EXTERN_C_BEGIN++YG_EXPORT float YGNodeLayoutGetLeft(YGNodeConstRef node);+YG_EXPORT float YGNodeLayoutGetTop(YGNodeConstRef node);+YG_EXPORT float YGNodeLayoutGetRight(YGNodeConstRef node);+YG_EXPORT float YGNodeLayoutGetBottom(YGNodeConstRef node);+YG_EXPORT float YGNodeLayoutGetWidth(YGNodeConstRef node);+YG_EXPORT float YGNodeLayoutGetHeight(YGNodeConstRef node);+YG_EXPORT YGDirection YGNodeLayoutGetDirection(YGNodeConstRef node);+YG_EXPORT bool YGNodeLayoutGetHadOverflow(YGNodeConstRef node);++// Get the computed values for these nodes after performing layout. If they were+// set using point values then the returned value will be the same as+// YGNodeStyleGetXXX. However if they were set using a percentage value then the+// returned value is the computed value used during layout.+YG_EXPORT float YGNodeLayoutGetMargin(YGNodeConstRef node, YGEdge edge);+YG_EXPORT float YGNodeLayoutGetBorder(YGNodeConstRef node, YGEdge edge);+YG_EXPORT float YGNodeLayoutGetPadding(YGNodeConstRef node, YGEdge edge);++/**+ * Return the measured height of the node, before layout rounding+ */+YG_EXPORT float YGNodeLayoutGetRawHeight(YGNodeConstRef node);++/**+ * Return the measured width of the node, before layout rounding+ */+YG_EXPORT float YGNodeLayoutGetRawWidth(YGNodeConstRef node);++YG_EXTERN_C_ENDdiff --git a/third_party/yoga/YGNodeStyle.cpp b/third_party/yoga/YGNodeStyle.cppnew file mode 100644index 000000000..e43a38e64--- /dev/null+++ b/third_party/yoga/YGNodeStyle.cpp@@ -0,0 +1,774 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/Yoga.h>+#include <yoga/debug/AssertFatal.h>+#include <yoga/node/Node.h>+#include <yoga/style/GridTrack.h>++using namespace facebook;+using namespace facebook::yoga;++namespace {++template <auto GetterT, auto SetterT, typename ValueT>+void updateStyle(YGNodeRef node, ValueT value) {+ auto& style = resolveRef(node)->style();+ if ((style.*GetterT)() != value) {+ (style.*SetterT)(value);+ resolveRef(node)->markDirtyAndPropagate();+ }+}++template <auto GetterT, auto SetterT, typename IdxT, typename ValueT>+void updateStyle(YGNodeRef node, IdxT idx, ValueT value) {+ auto& style = resolveRef(node)->style();+ if ((style.*GetterT)(idx) != value) {+ (style.*SetterT)(idx, value);+ resolveRef(node)->markDirtyAndPropagate();+ }+}++} // namespace++void YGNodeCopyStyle(YGNodeRef dstNode, YGNodeConstRef srcNode) {+ auto dst = resolveRef(dstNode);+ auto src = resolveRef(srcNode);++ if (dst->style() != src->style()) {+ dst->setStyle(src->style());+ dst->markDirtyAndPropagate();+ }+}++void YGNodeStyleSetDirection(const YGNodeRef node, const YGDirection value) {+ updateStyle<&Style::direction, &Style::setDirection>(node, scopedEnum(value));+}++YGDirection YGNodeStyleGetDirection(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().direction());+}++void YGNodeStyleSetFlexDirection(+ const YGNodeRef node,+ const YGFlexDirection flexDirection) {+ updateStyle<&Style::flexDirection, &Style::setFlexDirection>(+ node, scopedEnum(flexDirection));+}++YGFlexDirection YGNodeStyleGetFlexDirection(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().flexDirection());+}++void YGNodeStyleSetJustifyContent(+ const YGNodeRef node,+ const YGJustify justifyContent) {+ updateStyle<&Style::justifyContent, &Style::setJustifyContent>(+ node, scopedEnum(justifyContent));+}++YGJustify YGNodeStyleGetJustifyContent(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().justifyContent());+}++void YGNodeStyleSetJustifyItems(YGNodeRef node, const YGJustify justifyItems) {+ updateStyle<&Style::justifyItems, &Style::setJustifyItems>(+ node, scopedEnum(justifyItems));+}++YGJustify YGNodeStyleGetJustifyItems(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().justifyItems());+}++void YGNodeStyleSetJustifySelf(YGNodeRef node, const YGJustify justifySelf) {+ updateStyle<&Style::justifySelf, &Style::setJustifySelf>(+ node, scopedEnum(justifySelf));+}++YGJustify YGNodeStyleGetJustifySelf(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().justifySelf());+}++void YGNodeStyleSetAlignContent(+ const YGNodeRef node,+ const YGAlign alignContent) {+ updateStyle<&Style::alignContent, &Style::setAlignContent>(+ node, scopedEnum(alignContent));+}++YGAlign YGNodeStyleGetAlignContent(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().alignContent());+}++void YGNodeStyleSetAlignItems(const YGNodeRef node, const YGAlign alignItems) {+ updateStyle<&Style::alignItems, &Style::setAlignItems>(+ node, scopedEnum(alignItems));+}++YGAlign YGNodeStyleGetAlignItems(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().alignItems());+}++void YGNodeStyleSetAlignSelf(const YGNodeRef node, const YGAlign alignSelf) {+ updateStyle<&Style::alignSelf, &Style::setAlignSelf>(+ node, scopedEnum(alignSelf));+}++YGAlign YGNodeStyleGetAlignSelf(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().alignSelf());+}++void YGNodeStyleSetPositionType(+ const YGNodeRef node,+ const YGPositionType positionType) {+ updateStyle<&Style::positionType, &Style::setPositionType>(+ node, scopedEnum(positionType));+}++YGPositionType YGNodeStyleGetPositionType(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().positionType());+}++void YGNodeStyleSetFlexWrap(const YGNodeRef node, const YGWrap flexWrap) {+ updateStyle<&Style::flexWrap, &Style::setFlexWrap>(+ node, scopedEnum(flexWrap));+}++YGWrap YGNodeStyleGetFlexWrap(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().flexWrap());+}++void YGNodeStyleSetOverflow(const YGNodeRef node, const YGOverflow overflow) {+ updateStyle<&Style::overflow, &Style::setOverflow>(+ node, scopedEnum(overflow));+}++YGOverflow YGNodeStyleGetOverflow(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().overflow());+}++void YGNodeStyleSetDisplay(const YGNodeRef node, const YGDisplay display) {+ updateStyle<&Style::display, &Style::setDisplay>(node, scopedEnum(display));+}++YGDisplay YGNodeStyleGetDisplay(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().display());+}++void YGNodeStyleSetFlex(const YGNodeRef node, const float flex) {+ updateStyle<&Style::flex, &Style::setFlex>(node, FloatOptional{flex});+}++float YGNodeStyleGetFlex(const YGNodeConstRef nodeRef) {+ const auto node = resolveRef(nodeRef);+ return node->style().flex().isUndefined() ? YGUndefined+ : node->style().flex().unwrap();+}++void YGNodeStyleSetFlexGrow(const YGNodeRef node, const float flexGrow) {+ updateStyle<&Style::flexGrow, &Style::setFlexGrow>(+ node, FloatOptional{flexGrow});+}++float YGNodeStyleGetFlexGrow(const YGNodeConstRef nodeRef) {+ const auto node = resolveRef(nodeRef);+ return node->style().flexGrow().isUndefined()+ ? Style::DefaultFlexGrow+ : node->style().flexGrow().unwrap();+}++void YGNodeStyleSetFlexShrink(const YGNodeRef node, const float flexShrink) {+ updateStyle<&Style::flexShrink, &Style::setFlexShrink>(+ node, FloatOptional{flexShrink});+}++float YGNodeStyleGetFlexShrink(const YGNodeConstRef nodeRef) {+ const auto node = resolveRef(nodeRef);+ return node->style().flexShrink().isUndefined()+ ? (node->getConfig()->useWebDefaults() ? Style::WebDefaultFlexShrink+ : Style::DefaultFlexShrink)+ : node->style().flexShrink().unwrap();+}++void YGNodeStyleSetFlexBasis(const YGNodeRef node, const float flexBasis) {+ updateStyle<&Style::flexBasis, &Style::setFlexBasis>(+ node, StyleSizeLength::points(flexBasis));+}++void YGNodeStyleSetFlexBasisPercent(+ const YGNodeRef node,+ const float flexBasisPercent) {+ updateStyle<&Style::flexBasis, &Style::setFlexBasis>(+ node, StyleSizeLength::percent(flexBasisPercent));+}++void YGNodeStyleSetFlexBasisAuto(const YGNodeRef node) {+ updateStyle<&Style::flexBasis, &Style::setFlexBasis>(+ node, StyleSizeLength::ofAuto());+}++void YGNodeStyleSetFlexBasisMaxContent(const YGNodeRef node) {+ updateStyle<&Style::flexBasis, &Style::setFlexBasis>(+ node, StyleSizeLength::ofMaxContent());+}++void YGNodeStyleSetFlexBasisFitContent(const YGNodeRef node) {+ updateStyle<&Style::flexBasis, &Style::setFlexBasis>(+ node, StyleSizeLength::ofFitContent());+}++void YGNodeStyleSetFlexBasisStretch(const YGNodeRef node) {+ updateStyle<&Style::flexBasis, &Style::setFlexBasis>(+ node, StyleSizeLength::ofStretch());+}++YGValue YGNodeStyleGetFlexBasis(const YGNodeConstRef node) {+ return (YGValue)resolveRef(node)->style().flexBasis();+}++void YGNodeStyleSetPosition(YGNodeRef node, YGEdge edge, float points) {+ updateStyle<&Style::position, &Style::setPosition>(+ node, scopedEnum(edge), StyleLength::points(points));+}++void YGNodeStyleSetPositionPercent(YGNodeRef node, YGEdge edge, float percent) {+ updateStyle<&Style::position, &Style::setPosition>(+ node, scopedEnum(edge), StyleLength::percent(percent));+}++void YGNodeStyleSetPositionAuto(YGNodeRef node, YGEdge edge) {+ updateStyle<&Style::position, &Style::setPosition>(+ node, scopedEnum(edge), StyleLength::ofAuto());+}++YGValue YGNodeStyleGetPosition(YGNodeConstRef node, YGEdge edge) {+ return (YGValue)resolveRef(node)->style().position(scopedEnum(edge));+}++void YGNodeStyleSetMargin(YGNodeRef node, YGEdge edge, float points) {+ updateStyle<&Style::margin, &Style::setMargin>(+ node, scopedEnum(edge), StyleLength::points(points));+}++void YGNodeStyleSetMarginPercent(YGNodeRef node, YGEdge edge, float percent) {+ updateStyle<&Style::margin, &Style::setMargin>(+ node, scopedEnum(edge), StyleLength::percent(percent));+}++void YGNodeStyleSetMarginAuto(YGNodeRef node, YGEdge edge) {+ updateStyle<&Style::margin, &Style::setMargin>(+ node, scopedEnum(edge), StyleLength::ofAuto());+}++YGValue YGNodeStyleGetMargin(YGNodeConstRef node, YGEdge edge) {+ return (YGValue)resolveRef(node)->style().margin(scopedEnum(edge));+}++void YGNodeStyleSetPadding(YGNodeRef node, YGEdge edge, float points) {+ updateStyle<&Style::padding, &Style::setPadding>(+ node, scopedEnum(edge), StyleLength::points(points));+}++void YGNodeStyleSetPaddingPercent(YGNodeRef node, YGEdge edge, float percent) {+ updateStyle<&Style::padding, &Style::setPadding>(+ node, scopedEnum(edge), StyleLength::percent(percent));+}++YGValue YGNodeStyleGetPadding(YGNodeConstRef node, YGEdge edge) {+ return (YGValue)resolveRef(node)->style().padding(scopedEnum(edge));+}++void YGNodeStyleSetBorder(+ const YGNodeRef node,+ const YGEdge edge,+ const float border) {+ updateStyle<&Style::border, &Style::setBorder>(+ node, scopedEnum(edge), StyleLength::points(border));+}++float YGNodeStyleGetBorder(const YGNodeConstRef node, const YGEdge edge) {+ auto border = resolveRef(node)->style().border(scopedEnum(edge));+ if (border.isUndefined() || border.isAuto()) {+ return YGUndefined;+ }++ return static_cast<YGValue>(border).value;+}++void YGNodeStyleSetGap(+ const YGNodeRef node,+ const YGGutter gutter,+ const float gapLength) {+ updateStyle<&Style::gap, &Style::setGap>(+ node, scopedEnum(gutter), StyleLength::points(gapLength));+}++void YGNodeStyleSetGapPercent(YGNodeRef node, YGGutter gutter, float percent) {+ updateStyle<&Style::gap, &Style::setGap>(+ node, scopedEnum(gutter), StyleLength::percent(percent));+}++YGValue YGNodeStyleGetGap(const YGNodeConstRef node, const YGGutter gutter) {+ return (YGValue)resolveRef(node)->style().gap(scopedEnum(gutter));+}++void YGNodeStyleSetAspectRatio(const YGNodeRef node, const float aspectRatio) {+ updateStyle<&Style::aspectRatio, &Style::setAspectRatio>(+ node, FloatOptional{aspectRatio});+}++float YGNodeStyleGetAspectRatio(const YGNodeConstRef node) {+ const FloatOptional op = resolveRef(node)->style().aspectRatio();+ return op.isUndefined() ? YGUndefined : op.unwrap();+}++void YGNodeStyleSetBoxSizing(YGNodeRef node, YGBoxSizing boxSizing) {+ updateStyle<&Style::boxSizing, &Style::setBoxSizing>(+ node, scopedEnum(boxSizing));+}++YGBoxSizing YGNodeStyleGetBoxSizing(const YGNodeConstRef node) {+ return unscopedEnum(resolveRef(node)->style().boxSizing());+}++void YGNodeStyleSetWidth(YGNodeRef node, float points) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Width, StyleSizeLength::points(points));+}++void YGNodeStyleSetWidthPercent(YGNodeRef node, float percent) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Width, StyleSizeLength::percent(percent));+}++void YGNodeStyleSetWidthAuto(YGNodeRef node) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Width, StyleSizeLength::ofAuto());+}++void YGNodeStyleSetWidthMaxContent(YGNodeRef node) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Width, StyleSizeLength::ofMaxContent());+}++void YGNodeStyleSetWidthFitContent(YGNodeRef node) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Width, StyleSizeLength::ofFitContent());+}++void YGNodeStyleSetWidthStretch(YGNodeRef node) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Width, StyleSizeLength::ofStretch());+}++YGValue YGNodeStyleGetWidth(YGNodeConstRef node) {+ return (YGValue)resolveRef(node)->style().dimension(Dimension::Width);+}++void YGNodeStyleSetHeight(YGNodeRef node, float points) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Height, StyleSizeLength::points(points));+}++void YGNodeStyleSetHeightPercent(YGNodeRef node, float percent) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Height, StyleSizeLength::percent(percent));+}++void YGNodeStyleSetHeightAuto(YGNodeRef node) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Height, StyleSizeLength::ofAuto());+}++void YGNodeStyleSetHeightMaxContent(YGNodeRef node) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Height, StyleSizeLength::ofMaxContent());+}++void YGNodeStyleSetHeightFitContent(YGNodeRef node) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Height, StyleSizeLength::ofFitContent());+}++void YGNodeStyleSetHeightStretch(YGNodeRef node) {+ updateStyle<&Style::dimension, &Style::setDimension>(+ node, Dimension::Height, StyleSizeLength::ofStretch());+}++YGValue YGNodeStyleGetHeight(YGNodeConstRef node) {+ return (YGValue)resolveRef(node)->style().dimension(Dimension::Height);+}++void YGNodeStyleSetMinWidth(const YGNodeRef node, const float minWidth) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Width, StyleSizeLength::points(minWidth));+}++void YGNodeStyleSetMinWidthPercent(const YGNodeRef node, const float minWidth) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Width, StyleSizeLength::percent(minWidth));+}++void YGNodeStyleSetMinWidthMaxContent(const YGNodeRef node) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Width, StyleSizeLength::ofMaxContent());+}++void YGNodeStyleSetMinWidthFitContent(const YGNodeRef node) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Width, StyleSizeLength::ofFitContent());+}++void YGNodeStyleSetMinWidthStretch(const YGNodeRef node) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Width, StyleSizeLength::ofStretch());+}++YGValue YGNodeStyleGetMinWidth(const YGNodeConstRef node) {+ return (YGValue)resolveRef(node)->style().minDimension(Dimension::Width);+}++void YGNodeStyleSetMinHeight(const YGNodeRef node, const float minHeight) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Height, StyleSizeLength::points(minHeight));+}++void YGNodeStyleSetMinHeightPercent(+ const YGNodeRef node,+ const float minHeight) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Height, StyleSizeLength::percent(minHeight));+}++void YGNodeStyleSetMinHeightMaxContent(const YGNodeRef node) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Height, StyleSizeLength::ofMaxContent());+}++void YGNodeStyleSetMinHeightFitContent(const YGNodeRef node) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Height, StyleSizeLength::ofFitContent());+}++void YGNodeStyleSetMinHeightStretch(const YGNodeRef node) {+ updateStyle<&Style::minDimension, &Style::setMinDimension>(+ node, Dimension::Height, StyleSizeLength::ofStretch());+}++YGValue YGNodeStyleGetMinHeight(const YGNodeConstRef node) {+ return (YGValue)resolveRef(node)->style().minDimension(Dimension::Height);+}++void YGNodeStyleSetMaxWidth(const YGNodeRef node, const float maxWidth) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Width, StyleSizeLength::points(maxWidth));+}++void YGNodeStyleSetMaxWidthPercent(const YGNodeRef node, const float maxWidth) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Width, StyleSizeLength::percent(maxWidth));+}++void YGNodeStyleSetMaxWidthMaxContent(const YGNodeRef node) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Width, StyleSizeLength::ofMaxContent());+}++void YGNodeStyleSetMaxWidthFitContent(const YGNodeRef node) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Width, StyleSizeLength::ofFitContent());+}++void YGNodeStyleSetMaxWidthStretch(const YGNodeRef node) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Width, StyleSizeLength::ofStretch());+}++YGValue YGNodeStyleGetMaxWidth(const YGNodeConstRef node) {+ return (YGValue)resolveRef(node)->style().maxDimension(Dimension::Width);+}++void YGNodeStyleSetMaxHeight(const YGNodeRef node, const float maxHeight) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Height, StyleSizeLength::points(maxHeight));+}++void YGNodeStyleSetMaxHeightPercent(+ const YGNodeRef node,+ const float maxHeight) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Height, StyleSizeLength::percent(maxHeight));+}++void YGNodeStyleSetMaxHeightMaxContent(const YGNodeRef node) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Height, StyleSizeLength::ofMaxContent());+}++void YGNodeStyleSetMaxHeightFitContent(const YGNodeRef node) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Height, StyleSizeLength::ofFitContent());+}++void YGNodeStyleSetMaxHeightStretch(const YGNodeRef node) {+ updateStyle<&Style::maxDimension, &Style::setMaxDimension>(+ node, Dimension::Height, StyleSizeLength::ofStretch());+}++YGValue YGNodeStyleGetMaxHeight(const YGNodeConstRef node) {+ return (YGValue)resolveRef(node)->style().maxDimension(Dimension::Height);+}++// Grid Item Placement Properties++void YGNodeStyleSetGridColumnStart(YGNodeRef node, int32_t gridColumnStart) {+ updateStyle<&Style::gridColumnStart, &Style::setGridColumnStart>(+ node, GridLine::fromInteger(gridColumnStart));+}++void YGNodeStyleSetGridColumnStartAuto(YGNodeRef node) {+ updateStyle<&Style::gridColumnStart, &Style::setGridColumnStart>(+ node, GridLine::auto_());+}++void YGNodeStyleSetGridColumnStartSpan(YGNodeRef node, int32_t span) {+ updateStyle<&Style::gridColumnStart, &Style::setGridColumnStart>(+ node, GridLine::span(span));+}++int32_t YGNodeStyleGetGridColumnStart(YGNodeConstRef node) {+ const auto& gridLine = resolveRef(node)->style().gridColumnStart();+ return gridLine.isInteger() ? gridLine.integer : 0;+}++void YGNodeStyleSetGridColumnEnd(YGNodeRef node, int32_t gridColumnEnd) {+ updateStyle<&Style::gridColumnEnd, &Style::setGridColumnEnd>(+ node, GridLine::fromInteger(gridColumnEnd));+}++void YGNodeStyleSetGridColumnEndAuto(YGNodeRef node) {+ updateStyle<&Style::gridColumnEnd, &Style::setGridColumnEnd>(+ node, GridLine::auto_());+}++void YGNodeStyleSetGridColumnEndSpan(YGNodeRef node, int32_t span) {+ updateStyle<&Style::gridColumnEnd, &Style::setGridColumnEnd>(+ node, GridLine::span(span));+}++int32_t YGNodeStyleGetGridColumnEnd(YGNodeConstRef node) {+ const auto& gridLine = resolveRef(node)->style().gridColumnEnd();+ return gridLine.isInteger() ? gridLine.integer : 0;+}++void YGNodeStyleSetGridRowStart(YGNodeRef node, int32_t gridRowStart) {+ updateStyle<&Style::gridRowStart, &Style::setGridRowStart>(+ node, GridLine::fromInteger(gridRowStart));+}++void YGNodeStyleSetGridRowStartAuto(YGNodeRef node) {+ updateStyle<&Style::gridRowStart, &Style::setGridRowStart>(+ node, GridLine::auto_());+}++void YGNodeStyleSetGridRowStartSpan(YGNodeRef node, int32_t span) {+ updateStyle<&Style::gridRowStart, &Style::setGridRowStart>(+ node, GridLine::span(span));+}++int32_t YGNodeStyleGetGridRowStart(YGNodeConstRef node) {+ const auto& gridLine = resolveRef(node)->style().gridRowStart();+ return gridLine.isInteger() ? gridLine.integer : 0;+}++void YGNodeStyleSetGridRowEnd(YGNodeRef node, int32_t gridRowEnd) {+ updateStyle<&Style::gridRowEnd, &Style::setGridRowEnd>(+ node, GridLine::fromInteger(gridRowEnd));+}++void YGNodeStyleSetGridRowEndAuto(YGNodeRef node) {+ updateStyle<&Style::gridRowEnd, &Style::setGridRowEnd>(+ node, GridLine::auto_());+}++void YGNodeStyleSetGridRowEndSpan(YGNodeRef node, int32_t span) {+ updateStyle<&Style::gridRowEnd, &Style::setGridRowEnd>(+ node, GridLine::span(span));+}++int32_t YGNodeStyleGetGridRowEnd(YGNodeConstRef node) {+ const auto& gridLine = resolveRef(node)->style().gridRowEnd();+ return gridLine.isInteger() ? gridLine.integer : 0;+}++// Grid Container Properties++namespace {++GridTrackSize gridTrackSizeFromTypeAndValue(YGGridTrackType type, float value) {+ switch (type) {+ case YGGridTrackTypePoints:+ return GridTrackSize::length(value);+ case YGGridTrackTypePercent:+ return GridTrackSize::percent(value);+ case YGGridTrackTypeFr:+ return GridTrackSize::fr(value);+ case YGGridTrackTypeAuto:+ return GridTrackSize::auto_();+ case YGGridTrackTypeMinmax:+ return GridTrackSize::auto_();+ }+ fatalWithMessage("Unknown YGGridTrackType");+}++StyleSizeLength styleSizeLengthFromTypeAndValue(+ YGGridTrackType type,+ float value) {+ switch (type) {+ case YGGridTrackTypePoints:+ return StyleSizeLength::points(value);+ case YGGridTrackTypePercent:+ return StyleSizeLength::percent(value);+ case YGGridTrackTypeFr:+ return StyleSizeLength::stretch(value);+ case YGGridTrackTypeAuto:+ return StyleSizeLength::ofAuto();+ case YGGridTrackTypeMinmax:+ return StyleSizeLength::ofAuto();+ }+ fatalWithMessage("Unknown YGGridTrackType");+}++} // namespace++// GridTemplateColumns++void YGNodeStyleSetGridTemplateColumnsCount(YGNodeRef node, size_t count) {+ resolveRef(node)->style().resizeGridTemplateColumns(count);+ resolveRef(node)->markDirtyAndPropagate();+}++void YGNodeStyleSetGridTemplateColumn(+ YGNodeRef node,+ size_t index,+ YGGridTrackType type,+ float value) {+ resolveRef(node)->style().setGridTemplateColumnAt(+ index, gridTrackSizeFromTypeAndValue(type, value));+ resolveRef(node)->markDirtyAndPropagate();+}++void YGNodeStyleSetGridTemplateColumnMinMax(+ YGNodeRef node,+ size_t index,+ YGGridTrackType minType,+ float minValue,+ YGGridTrackType maxType,+ float maxValue) {+ resolveRef(node)->style().setGridTemplateColumnAt(+ index,+ GridTrackSize::minmax(+ styleSizeLengthFromTypeAndValue(minType, minValue),+ styleSizeLengthFromTypeAndValue(maxType, maxValue)));+ resolveRef(node)->markDirtyAndPropagate();+}++// GridTemplateRows++void YGNodeStyleSetGridTemplateRowsCount(YGNodeRef node, size_t count) {+ resolveRef(node)->style().resizeGridTemplateRows(count);+ resolveRef(node)->markDirtyAndPropagate();+}++void YGNodeStyleSetGridTemplateRow(+ YGNodeRef node,+ size_t index,+ YGGridTrackType type,+ float value) {+ resolveRef(node)->style().setGridTemplateRowAt(+ index, gridTrackSizeFromTypeAndValue(type, value));+ resolveRef(node)->markDirtyAndPropagate();+}++void YGNodeStyleSetGridTemplateRowMinMax(+ YGNodeRef node,+ size_t index,+ YGGridTrackType minType,+ float minValue,+ YGGridTrackType maxType,+ float maxValue) {+ resolveRef(node)->style().setGridTemplateRowAt(+ index,+ GridTrackSize::minmax(+ styleSizeLengthFromTypeAndValue(minType, minValue),+ styleSizeLengthFromTypeAndValue(maxType, maxValue)));+ resolveRef(node)->markDirtyAndPropagate();+}++// GridAutoColumns++void YGNodeStyleSetGridAutoColumnsCount(YGNodeRef node, size_t count) {+ resolveRef(node)->style().resizeGridAutoColumns(count);+ resolveRef(node)->markDirtyAndPropagate();+}++void YGNodeStyleSetGridAutoColumn(+ YGNodeRef node,+ size_t index,+ YGGridTrackType type,+ float value) {+ resolveRef(node)->style().setGridAutoColumnAt(+ index, gridTrackSizeFromTypeAndValue(type, value));+ resolveRef(node)->markDirtyAndPropagate();+}++void YGNodeStyleSetGridAutoColumnMinMax(+ YGNodeRef node,+ size_t index,+ YGGridTrackType minType,+ float minValue,+ YGGridTrackType maxType,+ float maxValue) {+ resolveRef(node)->style().setGridAutoColumnAt(+ index,+ GridTrackSize::minmax(+ styleSizeLengthFromTypeAndValue(minType, minValue),+ styleSizeLengthFromTypeAndValue(maxType, maxValue)));+ resolveRef(node)->markDirtyAndPropagate();+}++// GridAutoRows++void YGNodeStyleSetGridAutoRowsCount(YGNodeRef node, size_t count) {+ resolveRef(node)->style().resizeGridAutoRows(count);+ resolveRef(node)->markDirtyAndPropagate();+}++void YGNodeStyleSetGridAutoRow(+ YGNodeRef node,+ size_t index,+ YGGridTrackType type,+ float value) {+ resolveRef(node)->style().setGridAutoRowAt(+ index, gridTrackSizeFromTypeAndValue(type, value));+ resolveRef(node)->markDirtyAndPropagate();+}++void YGNodeStyleSetGridAutoRowMinMax(+ YGNodeRef node,+ size_t index,+ YGGridTrackType minType,+ float minValue,+ YGGridTrackType maxType,+ float maxValue) {+ resolveRef(node)->style().setGridAutoRowAt(+ index,+ GridTrackSize::minmax(+ styleSizeLengthFromTypeAndValue(minType, minValue),+ styleSizeLengthFromTypeAndValue(maxType, maxValue)));+ resolveRef(node)->markDirtyAndPropagate();+}diff --git a/third_party/yoga/YGNodeStyle.h b/third_party/yoga/YGNodeStyle.hnew file mode 100644index 000000000..a1c7e0956--- /dev/null+++ b/third_party/yoga/YGNodeStyle.h@@ -0,0 +1,243 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <stddef.h>+#include <yoga/YGEnums.h>+#include <yoga/YGNode.h>+#include <yoga/YGValue.h>++YG_EXTERN_C_BEGIN++YG_EXPORT void YGNodeCopyStyle(YGNodeRef dstNode, YGNodeConstRef srcNode);++YG_EXPORT void YGNodeStyleSetDirection(YGNodeRef node, YGDirection direction);+YG_EXPORT YGDirection YGNodeStyleGetDirection(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetFlexDirection(+ YGNodeRef node,+ YGFlexDirection flexDirection);+YG_EXPORT YGFlexDirection YGNodeStyleGetFlexDirection(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetJustifyContent(+ YGNodeRef node,+ YGJustify justifyContent);+YG_EXPORT YGJustify YGNodeStyleGetJustifyContent(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetJustifyItems(+ YGNodeRef node,+ YGJustify justifyItems);+YG_EXPORT YGJustify YGNodeStyleGetJustifyItems(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetJustifySelf(YGNodeRef node, YGJustify justifySelf);+YG_EXPORT YGJustify YGNodeStyleGetJustifySelf(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetAlignContent(YGNodeRef node, YGAlign alignContent);+YG_EXPORT YGAlign YGNodeStyleGetAlignContent(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetAlignItems(YGNodeRef node, YGAlign alignItems);+YG_EXPORT YGAlign YGNodeStyleGetAlignItems(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetAlignSelf(YGNodeRef node, YGAlign alignSelf);+YG_EXPORT YGAlign YGNodeStyleGetAlignSelf(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetPositionType(+ YGNodeRef node,+ YGPositionType positionType);+YG_EXPORT YGPositionType YGNodeStyleGetPositionType(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetFlexWrap(YGNodeRef node, YGWrap flexWrap);+YG_EXPORT YGWrap YGNodeStyleGetFlexWrap(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetOverflow(YGNodeRef node, YGOverflow overflow);+YG_EXPORT YGOverflow YGNodeStyleGetOverflow(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetDisplay(YGNodeRef node, YGDisplay display);+YG_EXPORT YGDisplay YGNodeStyleGetDisplay(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetFlex(YGNodeRef node, float flex);+YG_EXPORT float YGNodeStyleGetFlex(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetFlexGrow(YGNodeRef node, float flexGrow);+YG_EXPORT float YGNodeStyleGetFlexGrow(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetFlexShrink(YGNodeRef node, float flexShrink);+YG_EXPORT float YGNodeStyleGetFlexShrink(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetFlexBasis(YGNodeRef node, float flexBasis);+YG_EXPORT void YGNodeStyleSetFlexBasisPercent(YGNodeRef node, float flexBasis);+YG_EXPORT void YGNodeStyleSetFlexBasisAuto(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetFlexBasisMaxContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetFlexBasisFitContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetFlexBasisStretch(YGNodeRef node);+YG_EXPORT YGValue YGNodeStyleGetFlexBasis(YGNodeConstRef node);++YG_EXPORT void+YGNodeStyleSetPosition(YGNodeRef node, YGEdge edge, float position);+YG_EXPORT void+YGNodeStyleSetPositionPercent(YGNodeRef node, YGEdge edge, float position);+YG_EXPORT YGValue YGNodeStyleGetPosition(YGNodeConstRef node, YGEdge edge);+YG_EXPORT void YGNodeStyleSetPositionAuto(YGNodeRef node, YGEdge edge);++YG_EXPORT+void YGNodeStyleSetMargin(YGNodeRef node, YGEdge edge, float margin);+YG_EXPORT void+YGNodeStyleSetMarginPercent(YGNodeRef node, YGEdge edge, float margin);+YG_EXPORT void YGNodeStyleSetMarginAuto(YGNodeRef node, YGEdge edge);+YG_EXPORT YGValue YGNodeStyleGetMargin(YGNodeConstRef node, YGEdge edge);++YG_EXPORT void+YGNodeStyleSetPadding(YGNodeRef node, YGEdge edge, float padding);+YG_EXPORT void+YGNodeStyleSetPaddingPercent(YGNodeRef node, YGEdge edge, float padding);+YG_EXPORT YGValue YGNodeStyleGetPadding(YGNodeConstRef node, YGEdge edge);++YG_EXPORT void YGNodeStyleSetBorder(YGNodeRef node, YGEdge edge, float border);+YG_EXPORT float YGNodeStyleGetBorder(YGNodeConstRef node, YGEdge edge);++YG_EXPORT void+YGNodeStyleSetGap(YGNodeRef node, YGGutter gutter, float gapLength);+YG_EXPORT void+YGNodeStyleSetGapPercent(YGNodeRef node, YGGutter gutter, float gapLength);+YG_EXPORT YGValue YGNodeStyleGetGap(YGNodeConstRef node, YGGutter gutter);++YG_EXPORT void YGNodeStyleSetBoxSizing(YGNodeRef node, YGBoxSizing boxSizing);+YG_EXPORT YGBoxSizing YGNodeStyleGetBoxSizing(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetWidth(YGNodeRef node, float width);+YG_EXPORT void YGNodeStyleSetWidthPercent(YGNodeRef node, float width);+YG_EXPORT void YGNodeStyleSetWidthAuto(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetWidthMaxContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetWidthFitContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetWidthStretch(YGNodeRef node);+YG_EXPORT YGValue YGNodeStyleGetWidth(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetHeight(YGNodeRef node, float height);+YG_EXPORT void YGNodeStyleSetHeightPercent(YGNodeRef node, float height);+YG_EXPORT void YGNodeStyleSetHeightAuto(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetHeightMaxContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetHeightFitContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetHeightStretch(YGNodeRef node);+YG_EXPORT YGValue YGNodeStyleGetHeight(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetMinWidth(YGNodeRef node, float minWidth);+YG_EXPORT void YGNodeStyleSetMinWidthPercent(YGNodeRef node, float minWidth);+YG_EXPORT void YGNodeStyleSetMinWidthMaxContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetMinWidthFitContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetMinWidthStretch(YGNodeRef node);+YG_EXPORT YGValue YGNodeStyleGetMinWidth(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetMinHeight(YGNodeRef node, float minHeight);+YG_EXPORT void YGNodeStyleSetMinHeightPercent(YGNodeRef node, float minHeight);+YG_EXPORT void YGNodeStyleSetMinHeightMaxContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetMinHeightFitContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetMinHeightStretch(YGNodeRef node);+YG_EXPORT YGValue YGNodeStyleGetMinHeight(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetMaxWidth(YGNodeRef node, float maxWidth);+YG_EXPORT void YGNodeStyleSetMaxWidthPercent(YGNodeRef node, float maxWidth);+YG_EXPORT void YGNodeStyleSetMaxWidthMaxContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetMaxWidthFitContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetMaxWidthStretch(YGNodeRef node);+YG_EXPORT YGValue YGNodeStyleGetMaxWidth(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetMaxHeight(YGNodeRef node, float maxHeight);+YG_EXPORT void YGNodeStyleSetMaxHeightPercent(YGNodeRef node, float maxHeight);+YG_EXPORT void YGNodeStyleSetMaxHeightMaxContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetMaxHeightFitContent(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetMaxHeightStretch(YGNodeRef node);+YG_EXPORT YGValue YGNodeStyleGetMaxHeight(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetAspectRatio(YGNodeRef node, float aspectRatio);+YG_EXPORT float YGNodeStyleGetAspectRatio(YGNodeConstRef node);++// Grid Item Properties+YG_EXPORT void YGNodeStyleSetGridColumnStart(+ YGNodeRef node,+ int gridColumnStart);+YG_EXPORT void YGNodeStyleSetGridColumnStartAuto(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetGridColumnStartSpan(YGNodeRef node, int span);+YG_EXPORT int YGNodeStyleGetGridColumnStart(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetGridColumnEnd(YGNodeRef node, int gridColumnEnd);+YG_EXPORT void YGNodeStyleSetGridColumnEndAuto(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetGridColumnEndSpan(YGNodeRef node, int span);+YG_EXPORT int YGNodeStyleGetGridColumnEnd(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetGridRowStart(YGNodeRef node, int gridRowStart);+YG_EXPORT void YGNodeStyleSetGridRowStartAuto(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetGridRowStartSpan(YGNodeRef node, int span);+YG_EXPORT int YGNodeStyleGetGridRowStart(YGNodeConstRef node);++YG_EXPORT void YGNodeStyleSetGridRowEnd(YGNodeRef node, int gridRowEnd);+YG_EXPORT void YGNodeStyleSetGridRowEndAuto(YGNodeRef node);+YG_EXPORT void YGNodeStyleSetGridRowEndSpan(YGNodeRef node, int span);+YG_EXPORT int YGNodeStyleGetGridRowEnd(YGNodeConstRef node);++// Grid Container Properties+YG_EXPORT void YGNodeStyleSetGridTemplateColumnsCount(+ YGNodeRef node,+ size_t count);+YG_EXPORT void YGNodeStyleSetGridTemplateColumn(+ YGNodeRef node,+ size_t index,+ YGGridTrackType type,+ float value);+YG_EXPORT void YGNodeStyleSetGridTemplateColumnMinMax(+ YGNodeRef node,+ size_t index,+ YGGridTrackType minType,+ float minValue,+ YGGridTrackType maxType,+ float maxValue);++YG_EXPORT void YGNodeStyleSetGridTemplateRowsCount(+ YGNodeRef node,+ size_t count);+YG_EXPORT void YGNodeStyleSetGridTemplateRow(+ YGNodeRef node,+ size_t index,+ YGGridTrackType type,+ float value);+YG_EXPORT void YGNodeStyleSetGridTemplateRowMinMax(+ YGNodeRef node,+ size_t index,+ YGGridTrackType minType,+ float minValue,+ YGGridTrackType maxType,+ float maxValue);++YG_EXPORT void YGNodeStyleSetGridAutoColumnsCount(YGNodeRef node, size_t count);+YG_EXPORT void YGNodeStyleSetGridAutoColumn(+ YGNodeRef node,+ size_t index,+ YGGridTrackType type,+ float value);+YG_EXPORT void YGNodeStyleSetGridAutoColumnMinMax(+ YGNodeRef node,+ size_t index,+ YGGridTrackType minType,+ float minValue,+ YGGridTrackType maxType,+ float maxValue);++YG_EXPORT void YGNodeStyleSetGridAutoRowsCount(YGNodeRef node, size_t count);+YG_EXPORT void YGNodeStyleSetGridAutoRow(+ YGNodeRef node,+ size_t index,+ YGGridTrackType type,+ float value);+YG_EXPORT void YGNodeStyleSetGridAutoRowMinMax(+ YGNodeRef node,+ size_t index,+ YGGridTrackType minType,+ float minValue,+ YGGridTrackType maxType,+ float maxValue);++YG_EXTERN_C_ENDdiff --git a/third_party/yoga/YGPixelGrid.cpp b/third_party/yoga/YGPixelGrid.cppnew file mode 100644index 000000000..a855a292c--- /dev/null+++ b/third_party/yoga/YGPixelGrid.cpp@@ -0,0 +1,22 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/Yoga.h>++#include <yoga/algorithm/PixelGrid.h>++using namespace facebook;+using namespace facebook::yoga;++float YGRoundValueToPixelGrid(+ const double value,+ const double pointScaleFactor,+ const bool forceCeil,+ const bool forceFloor) {+ return yoga::roundValueToPixelGrid(+ value, pointScaleFactor, forceCeil, forceFloor);+}diff --git a/third_party/yoga/YGPixelGrid.h b/third_party/yoga/YGPixelGrid.hnew file mode 100644index 000000000..e2a6aeb69--- /dev/null+++ b/third_party/yoga/YGPixelGrid.h@@ -0,0 +1,29 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <stdbool.h>++#include <yoga/YGConfig.h>+#include <yoga/YGEnums.h>+#include <yoga/YGMacros.h>++YG_EXTERN_C_BEGIN++/**+ * Rounds a point value to the nearest whole pixel, given a pointScaleFactor+ * describing pixel density.+ * @returns the rounded value in points+ */+YG_EXPORT float YGRoundValueToPixelGrid(+ double value,+ double pointScaleFactor,+ bool forceCeil,+ bool forceFloor);++YG_EXTERN_C_ENDdiff --git a/third_party/yoga/YGValue.cpp b/third_party/yoga/YGValue.cppnew file mode 100644index 000000000..7a469b9cc--- /dev/null+++ b/third_party/yoga/YGValue.cpp@@ -0,0 +1,20 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/YGValue.h>+#include <yoga/numeric/Comparison.h>++using namespace facebook;+using namespace facebook::yoga;++const YGValue YGValueZero = {0, YGUnitPoint};+const YGValue YGValueUndefined = {YGUndefined, YGUnitUndefined};+const YGValue YGValueAuto = {YGUndefined, YGUnitAuto};++bool YGFloatIsUndefined(const float value) {+ return yoga::isUndefined(value);+}diff --git a/third_party/yoga/YGValue.h b/third_party/yoga/YGValue.hnew file mode 100644index 000000000..138135229--- /dev/null+++ b/third_party/yoga/YGValue.h@@ -0,0 +1,83 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <stdbool.h>++#include <yoga/YGEnums.h>+#include <yoga/YGMacros.h>++/**+ * Float value to represent "undefined" in style values.+ */+#ifdef __cplusplus+#include <limits>+constexpr float YGUndefined = std::numeric_limits<float>::quiet_NaN();+#else+#include <math.h>+#define YGUndefined NAN+#endif++YG_EXTERN_C_BEGIN++/**+ * Structure used to represent a dimension in a style.+ */+typedef struct YGValue {+ float value;+ YGUnit unit;+} YGValue;++/**+ * Constant for a dimension of "auto".+ */+YG_EXPORT extern const YGValue YGValueAuto;++/**+ * Constant for a dimension which is not defined.+ */+YG_EXPORT extern const YGValue YGValueUndefined;++/**+ * Constant for a dimension that is zero-length.+ */+YG_EXPORT extern const YGValue YGValueZero;++/**+ * Whether a dimension represented as a float is defined.+ */+YG_EXPORT bool YGFloatIsUndefined(float value);++YG_EXTERN_C_END++// Equality operators for comparison of YGValue in C+++#ifdef __cplusplus+inline bool operator==(const YGValue& lhs, const YGValue& rhs) {+ if (lhs.unit != rhs.unit) {+ return false;+ }++ switch (lhs.unit) {+ case YGUnitUndefined:+ case YGUnitAuto:+ case YGUnitFitContent:+ case YGUnitMaxContent:+ case YGUnitStretch:+ return true;+ case YGUnitPoint:+ case YGUnitPercent:+ return lhs.value == rhs.value;+ default:+ return false;+ }+}++inline YGValue operator-(const YGValue& value) {+ return {-value.value, value.unit};+}+#endifdiff --git a/third_party/yoga/Yoga.h b/third_party/yoga/Yoga.hnew file mode 100644index 000000000..97f05ed3e--- /dev/null+++ b/third_party/yoga/Yoga.h@@ -0,0 +1,21 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++/**+ * `#include <yoga/Yoga.h>` includes all of Yoga's public headers.+ */++#include <yoga/YGConfig.h> // IWYU pragma: export+#include <yoga/YGEnums.h> // IWYU pragma: export+#include <yoga/YGMacros.h> // IWYU pragma: export+#include <yoga/YGNode.h> // IWYU pragma: export+#include <yoga/YGNodeLayout.h> // IWYU pragma: export+#include <yoga/YGNodeStyle.h> // IWYU pragma: export+#include <yoga/YGPixelGrid.h> // IWYU pragma: export+#include <yoga/YGValue.h> // IWYU pragma: exportdiff --git a/third_party/yoga/algorithm/AbsoluteLayout.cpp b/third_party/yoga/algorithm/AbsoluteLayout.cppnew file mode 100644index 000000000..181dfcb1b--- /dev/null+++ b/third_party/yoga/algorithm/AbsoluteLayout.cpp@@ -0,0 +1,593 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/algorithm/AbsoluteLayout.h>+#include <yoga/algorithm/Align.h>+#include <yoga/algorithm/BoundAxis.h>+#include <yoga/algorithm/CalculateLayout.h>+#include <yoga/algorithm/TrailingPosition.h>++namespace facebook::yoga {++static inline void setFlexStartLayoutPosition(+ const yoga::Node* const parent,+ yoga::Node* child,+ const Direction direction,+ const FlexDirection axis,+ const float containingBlockWidth) {+ float position = child->style().computeFlexStartMargin(+ axis, direction, containingBlockWidth) ++ parent->getLayout().border(flexStartEdge(axis));++ // https://www.w3.org/TR/css-grid-1/#abspos+ // absolute positioned grid items are positioned relative to the padding edge+ // of the grid container+ if (!child->hasErrata(Errata::AbsolutePositionWithoutInsetsExcludesPadding) &&+ parent->style().display() != Display::Grid) {+ position += parent->getLayout().padding(flexStartEdge(axis));+ }++ child->setLayoutPosition(position, flexStartEdge(axis));+}++static inline void setFlexEndLayoutPosition(+ const yoga::Node* const parent,+ yoga::Node* child,+ const Direction direction,+ const FlexDirection axis,+ const float containingBlockWidth) {+ float flexEndPosition = parent->getLayout().border(flexEndEdge(axis)) ++ child->style().computeFlexEndMargin(+ axis, direction, containingBlockWidth);++ // https://www.w3.org/TR/css-grid-1/#abspos+ // absolute positioned grid items are positioned relative to the padding edge+ // of the grid container+ if (!child->hasErrata(Errata::AbsolutePositionWithoutInsetsExcludesPadding) &&+ parent->style().display() != Display::Grid) {+ flexEndPosition += parent->getLayout().padding(flexEndEdge(axis));+ }++ child->setLayoutPosition(+ getPositionOfOppositeEdge(flexEndPosition, axis, parent, child),+ flexStartEdge(axis));+}++static inline void setCenterLayoutPosition(+ const yoga::Node* const parent,+ yoga::Node* child,+ const Direction direction,+ const FlexDirection axis,+ const float containingBlockWidth) {+ float parentContentBoxSize =+ parent->getLayout().measuredDimension(dimension(axis)) -+ parent->getLayout().border(flexStartEdge(axis)) -+ parent->getLayout().border(flexEndEdge(axis));++ // https://www.w3.org/TR/css-grid-1/#abspos+ // absolute positioned grid items are positioned relative to the padding edge+ // of the grid container+ if (!child->hasErrata(Errata::AbsolutePositionWithoutInsetsExcludesPadding) &&+ parent->style().display() != Display::Grid) {+ parentContentBoxSize -= parent->getLayout().padding(flexStartEdge(axis));+ parentContentBoxSize -= parent->getLayout().padding(flexEndEdge(axis));+ }++ const float childOuterSize =+ child->getLayout().measuredDimension(dimension(axis)) ++ child->style().computeMarginForAxis(axis, containingBlockWidth);++ float position = (parentContentBoxSize - childOuterSize) / 2.0f ++ parent->getLayout().border(flexStartEdge(axis)) ++ child->style().computeFlexStartMargin(+ axis, direction, containingBlockWidth);++ // https://www.w3.org/TR/css-grid-1/#abspos+ // absolute positioned grid items are positioned relative to the padding edge+ // of the grid container+ if (!child->hasErrata(Errata::AbsolutePositionWithoutInsetsExcludesPadding) &&+ parent->style().display() != Display::Grid) {+ position += parent->getLayout().padding(flexStartEdge(axis));+ }++ child->setLayoutPosition(position, flexStartEdge(axis));+}++static void justifyAbsoluteChild(+ const yoga::Node* const parent,+ yoga::Node* child,+ const Direction direction,+ const FlexDirection mainAxis,+ const float containingBlockWidth) {+ const Justify justify = parent->style().display() == Display::Grid+ ? resolveChildJustification(parent, child)+ : parent->style().justifyContent();+ switch (justify) {+ case Justify::Start:+ case Justify::Auto:+ case Justify::Stretch:+ case Justify::FlexStart:+ case Justify::SpaceBetween:+ setFlexStartLayoutPosition(+ parent, child, direction, mainAxis, containingBlockWidth);+ break;+ case Justify::End:+ case Justify::FlexEnd:+ setFlexEndLayoutPosition(+ parent, child, direction, mainAxis, containingBlockWidth);+ break;+ case Justify::Center:+ case Justify::SpaceAround:+ case Justify::SpaceEvenly:+ setCenterLayoutPosition(+ parent, child, direction, mainAxis, containingBlockWidth);+ break;+ }+}++static void alignAbsoluteChild(+ const yoga::Node* const parent,+ yoga::Node* child,+ const Direction direction,+ const FlexDirection crossAxis,+ const float containingBlockWidth) {+ Align itemAlign = resolveChildAlignment(parent, child);+ const Wrap parentWrap = parent->style().flexWrap();+ if (parentWrap == Wrap::WrapReverse) {+ if (itemAlign == Align::FlexEnd) {+ itemAlign = Align::FlexStart;+ } else if (itemAlign != Align::Center) {+ itemAlign = Align::FlexEnd;+ }+ }++ switch (itemAlign) {+ case Align::Start:+ case Align::Auto:+ case Align::FlexStart:+ case Align::Baseline:+ case Align::SpaceAround:+ case Align::SpaceBetween:+ case Align::Stretch:+ case Align::SpaceEvenly:+ setFlexStartLayoutPosition(+ parent, child, direction, crossAxis, containingBlockWidth);+ break;+ case Align::End:+ case Align::FlexEnd:+ setFlexEndLayoutPosition(+ parent, child, direction, crossAxis, containingBlockWidth);+ break;+ case Align::Center:+ setCenterLayoutPosition(+ parent, child, direction, crossAxis, containingBlockWidth);+ break;+ }+}++/*+ * Absolutely positioned nodes do not participate in flex layout and thus their+ * positions can be determined independently from the rest of their siblings.+ * For each axis there are essentially two cases:+ *+ * 1) The node has insets defined. In this case we can just use these to+ * determine the position of the node.+ * 2) The node does not have insets defined. In this case we look at the style+ * of the parent to position the node. Things like justify content and+ * align content will move absolute children around. If none of these+ * special properties are defined, the child is positioned at the start+ * (defined by flex direction) of the leading flex line.+ *+ * This function does that positioning for the given axis. The spec has more+ * information on this topic: https://www.w3.org/TR/css-flexbox-1/#abspos-items+ */+static void positionAbsoluteChild(+ const yoga::Node* const containingNode,+ const yoga::Node* const parent,+ yoga::Node* child,+ const Direction direction,+ const FlexDirection axis,+ const bool isMainAxis,+ const float containingBlockWidth,+ const float containingBlockHeight) {+ const bool isAxisRow = isRow(axis);+ const float containingBlockSize =+ isAxisRow ? containingBlockWidth : containingBlockHeight;++ // The inline-start position takes priority over the end position in the case+ // that they are both set and the node has a fixed width. Thus we only have 2+ // cases here: if inline-start is defined and if inline-end is defined.+ //+ // Despite checking inline-start to honor prioritization of insets, we write+ // to the flex-start edge because this algorithm works by positioning on the+ // flex-start edge and then filling in the flex-end direction at the end if+ // necessary.+ if (child->style().isInlineStartPositionDefined(axis, direction) &&+ !child->style().isInlineStartPositionAuto(axis, direction)) {+ const float positionRelativeToInlineStart =+ child->style().computeInlineStartPosition(+ axis, direction, containingBlockSize) ++ containingNode->style().computeInlineStartBorder(axis, direction) ++ child->style().computeInlineStartMargin(+ axis, direction, containingBlockSize);+ const float positionRelativeToFlexStart =+ inlineStartEdge(axis, direction) != flexStartEdge(axis)+ ? getPositionOfOppositeEdge(+ positionRelativeToInlineStart, axis, containingNode, child)+ : positionRelativeToInlineStart;++ child->setLayoutPosition(positionRelativeToFlexStart, flexStartEdge(axis));+ } else if (+ child->style().isInlineEndPositionDefined(axis, direction) &&+ !child->style().isInlineEndPositionAuto(axis, direction)) {+ const float positionRelativeToInlineStart =+ containingNode->getLayout().measuredDimension(dimension(axis)) -+ child->getLayout().measuredDimension(dimension(axis)) -+ containingNode->style().computeInlineEndBorder(axis, direction) -+ child->style().computeInlineEndMargin(+ axis, direction, containingBlockSize) -+ child->style().computeInlineEndPosition(+ axis, direction, containingBlockSize);+ const float positionRelativeToFlexStart =+ inlineStartEdge(axis, direction) != flexStartEdge(axis)+ ? getPositionOfOppositeEdge(+ positionRelativeToInlineStart, axis, containingNode, child)+ : positionRelativeToInlineStart;++ child->setLayoutPosition(positionRelativeToFlexStart, flexStartEdge(axis));+ } else {+ isMainAxis ? justifyAbsoluteChild(+ parent, child, direction, axis, containingBlockWidth)+ : alignAbsoluteChild(+ parent, child, direction, axis, containingBlockWidth);+ }+}++void layoutAbsoluteChild(+ const yoga::Node* const containingNode,+ const yoga::Node* const node,+ yoga::Node* const child,+ const float containingBlockWidth,+ const float containingBlockHeight,+ const SizingMode widthMode,+ const Direction direction,+ LayoutData& layoutMarkerData,+ const uint32_t depth,+ const uint32_t generationCount) {+ // For grid containers, use inline (Row) and block (Column) axes for+ // positioning, since grid alignment properties (justify-self, align-self)+ // operate on inline/block axes, not main/cross axes based on flex-direction.+ const FlexDirection mainAxis = node->style().display() == Display::Grid+ ? resolveDirection(FlexDirection::Row, direction)+ : resolveDirection(node->style().flexDirection(), direction);+ const FlexDirection crossAxis = node->style().display() == Display::Grid+ ? FlexDirection::Column+ : resolveCrossDirection(mainAxis, direction);+ const bool isMainAxisRow = isRow(mainAxis);++ float childWidth = YGUndefined;+ float childHeight = YGUndefined;+ SizingMode childWidthSizingMode = SizingMode::MaxContent;+ SizingMode childHeightSizingMode = SizingMode::MaxContent;++ auto marginRow = child->style().computeMarginForAxis(+ FlexDirection::Row, containingBlockWidth);+ auto marginColumn = child->style().computeMarginForAxis(+ FlexDirection::Column, containingBlockWidth);++ if (child->hasDefiniteLength(Dimension::Width, containingBlockWidth)) {+ childWidth = child+ ->getResolvedDimension(+ direction,+ Dimension::Width,+ containingBlockWidth,+ containingBlockWidth)+ .unwrap() ++ marginRow;+ } else {+ // If the child doesn't have a specified width, compute the width based on+ // the left/right offsets if they're defined.+ if (child->style().isFlexStartPositionDefined(+ FlexDirection::Row, direction) &&+ child->style().isFlexEndPositionDefined(+ FlexDirection::Row, direction) &&+ !child->style().isFlexStartPositionAuto(+ FlexDirection::Row, direction) &&+ !child->style().isFlexEndPositionAuto(FlexDirection::Row, direction)) {+ childWidth =+ containingNode->getLayout().measuredDimension(Dimension::Width) -+ (containingNode->style().computeFlexStartBorder(+ FlexDirection::Row, direction) ++ containingNode->style().computeFlexEndBorder(+ FlexDirection::Row, direction)) -+ (child->style().computeFlexStartPosition(+ FlexDirection::Row, direction, containingBlockWidth) ++ child->style().computeFlexEndPosition(+ FlexDirection::Row, direction, containingBlockWidth));+ childWidth = boundAxis(+ child,+ FlexDirection::Row,+ direction,+ childWidth,+ containingBlockWidth,+ containingBlockWidth);+ }+ }++ if (child->hasDefiniteLength(Dimension::Height, containingBlockHeight)) {+ childHeight = child+ ->getResolvedDimension(+ direction,+ Dimension::Height,+ containingBlockHeight,+ containingBlockWidth)+ .unwrap() ++ marginColumn;+ } else {+ // If the child doesn't have a specified height, compute the height based+ // on the top/bottom offsets if they're defined.+ if (child->style().isFlexStartPositionDefined(+ FlexDirection::Column, direction) &&+ child->style().isFlexEndPositionDefined(+ FlexDirection::Column, direction) &&+ !child->style().isFlexStartPositionAuto(+ FlexDirection::Column, direction) &&+ !child->style().isFlexEndPositionAuto(+ FlexDirection::Column, direction)) {+ childHeight =+ containingNode->getLayout().measuredDimension(Dimension::Height) -+ (containingNode->style().computeFlexStartBorder(+ FlexDirection::Column, direction) ++ containingNode->style().computeFlexEndBorder(+ FlexDirection::Column, direction)) -+ (child->style().computeFlexStartPosition(+ FlexDirection::Column, direction, containingBlockHeight) ++ child->style().computeFlexEndPosition(+ FlexDirection::Column, direction, containingBlockHeight));+ childHeight = boundAxis(+ child,+ FlexDirection::Column,+ direction,+ childHeight,+ containingBlockHeight,+ containingBlockWidth);+ }+ }++ // Exactly one dimension needs to be defined for us to be able to do aspect+ // ratio calculation. One dimension being the anchor and the other being+ // flexible.+ const auto& childStyle = child->style();+ if (yoga::isUndefined(childWidth) ^ yoga::isUndefined(childHeight)) {+ if (childStyle.aspectRatio().isDefined()) {+ if (yoga::isUndefined(childWidth)) {+ childWidth = marginRow ++ (childHeight - marginColumn) * childStyle.aspectRatio().unwrap();+ } else if (yoga::isUndefined(childHeight)) {+ childHeight = marginColumn ++ (childWidth - marginRow) / childStyle.aspectRatio().unwrap();+ }+ }+ }++ // If we're still missing one or the other dimension, measure the content.+ if (yoga::isUndefined(childWidth) || yoga::isUndefined(childHeight)) {+ childWidthSizingMode = yoga::isUndefined(childWidth)+ ? SizingMode::MaxContent+ : SizingMode::StretchFit;+ childHeightSizingMode = yoga::isUndefined(childHeight)+ ? SizingMode::MaxContent+ : SizingMode::StretchFit;++ // If the size of the owner is defined then try to constrain the absolute+ // child to that size as well. This allows text within the absolute child+ // to wrap to the size of its owner. This is the same behavior as many+ // browsers implement.+ if (!isMainAxisRow && yoga::isUndefined(childWidth) &&+ widthMode != SizingMode::MaxContent &&+ yoga::isDefined(containingBlockWidth) && containingBlockWidth > 0) {+ childWidth = containingBlockWidth;+ childWidthSizingMode = SizingMode::FitContent;+ }++ calculateLayoutInternal(+ child,+ childWidth,+ childHeight,+ direction,+ childWidthSizingMode,+ childHeightSizingMode,+ containingBlockWidth,+ containingBlockHeight,+ false,+ LayoutPassReason::kAbsMeasureChild,+ layoutMarkerData,+ depth,+ generationCount);+ childWidth = child->getLayout().measuredDimension(Dimension::Width) ++ child->style().computeMarginForAxis(+ FlexDirection::Row, containingBlockWidth);+ childHeight = child->getLayout().measuredDimension(Dimension::Height) ++ child->style().computeMarginForAxis(+ FlexDirection::Column, containingBlockWidth);+ }++ calculateLayoutInternal(+ child,+ childWidth,+ childHeight,+ direction,+ SizingMode::StretchFit,+ SizingMode::StretchFit,+ containingBlockWidth,+ containingBlockHeight,+ true,+ LayoutPassReason::kAbsLayout,+ layoutMarkerData,+ depth,+ generationCount);++ positionAbsoluteChild(+ containingNode,+ node,+ child,+ direction,+ mainAxis,+ true /*isMainAxis*/,+ containingBlockWidth,+ containingBlockHeight);+ positionAbsoluteChild(+ containingNode,+ node,+ child,+ direction,+ crossAxis,+ false /*isMainAxis*/,+ containingBlockWidth,+ containingBlockHeight);+}++bool layoutAbsoluteDescendants(+ yoga::Node* containingNode,+ yoga::Node* currentNode,+ SizingMode widthSizingMode,+ Direction currentNodeDirection,+ LayoutData& layoutMarkerData,+ uint32_t currentDepth,+ uint32_t generationCount,+ float currentNodeLeftOffsetFromContainingBlock,+ float currentNodeTopOffsetFromContainingBlock,+ float containingNodeAvailableInnerWidth,+ float containingNodeAvailableInnerHeight) {+ bool hasNewLayout = false;+ for (auto child : currentNode->getLayoutChildren()) {+ if (child->style().display() == Display::None) {+ continue;+ } else if (child->style().positionType() == PositionType::Absolute) {+ const bool absoluteErrata =+ currentNode->hasErrata(Errata::AbsolutePercentAgainstInnerSize);+ const float containingBlockWidth = absoluteErrata+ ? containingNodeAvailableInnerWidth+ : containingNode->getLayout().measuredDimension(Dimension::Width) -+ containingNode->style().computeBorderForAxis(FlexDirection::Row);+ const float containingBlockHeight = absoluteErrata+ ? containingNodeAvailableInnerHeight+ : containingNode->getLayout().measuredDimension(Dimension::Height) -+ containingNode->style().computeBorderForAxis(+ FlexDirection::Column);++ layoutAbsoluteChild(+ containingNode,+ currentNode,+ child,+ containingBlockWidth,+ containingBlockHeight,+ widthSizingMode,+ currentNodeDirection,+ layoutMarkerData,+ currentDepth,+ generationCount);++ hasNewLayout = hasNewLayout || child->getHasNewLayout();++ /*+ * At this point the child has its position set but only on its the+ * parent's flexStart edge. Additionally, this position should be+ * interpreted relative to the containing block of the child if it had+ * insets defined. So we need to adjust the position by subtracting the+ * the parents offset from the containing block. However, getting that+ * offset is complicated since the two nodes can have different main/cross+ * axes.+ */+ const FlexDirection parentMainAxis = resolveDirection(+ currentNode->style().flexDirection(), currentNodeDirection);+ const FlexDirection parentCrossAxis =+ resolveCrossDirection(parentMainAxis, currentNodeDirection);++ if (needsTrailingPosition(parentMainAxis)) {+ const bool mainInsetsDefined = isRow(parentMainAxis)+ ? child->style().horizontalInsetsDefined()+ : child->style().verticalInsetsDefined();+ setChildTrailingPosition(+ mainInsetsDefined ? containingNode : currentNode,+ child,+ parentMainAxis);+ }+ if (needsTrailingPosition(parentCrossAxis)) {+ const bool crossInsetsDefined = isRow(parentCrossAxis)+ ? child->style().horizontalInsetsDefined()+ : child->style().verticalInsetsDefined();+ setChildTrailingPosition(+ crossInsetsDefined ? containingNode : currentNode,+ child,+ parentCrossAxis);+ }++ /*+ * At this point we know the left and top physical edges of the child are+ * set with positions that are relative to the containing block if insets+ * are defined+ */+ const float childLeftPosition =+ child->getLayout().position(PhysicalEdge::Left);+ const float childTopPosition =+ child->getLayout().position(PhysicalEdge::Top);++ const float childLeftOffsetFromParent =+ child->style().horizontalInsetsDefined()+ ? (childLeftPosition - currentNodeLeftOffsetFromContainingBlock)+ : childLeftPosition;+ const float childTopOffsetFromParent =+ child->style().verticalInsetsDefined()+ ? (childTopPosition - currentNodeTopOffsetFromContainingBlock)+ : childTopPosition;++ child->setLayoutPosition(childLeftOffsetFromParent, PhysicalEdge::Left);+ child->setLayoutPosition(childTopOffsetFromParent, PhysicalEdge::Top);+ } else if (+ child->style().positionType() == PositionType::Static &&+ !child->alwaysFormsContainingBlock()) {+ // We may write new layout results for absolute descendants of "child"+ // which are positioned relative to the current containing block instead+ // of their parent. "child" may not be dirty, or have new constraints, so+ // absolute positioning may be the first time during this layout pass that+ // we need to mutate these descendents. Make sure the path of+ // nodes to them is mutable before positioning.+ child->cloneChildrenIfNeeded();+ const Direction childDirection =+ child->resolveDirection(currentNodeDirection);+ // By now all descendants of the containing block that are not absolute+ // will have their positions set for left and top.+ const float childLeftOffsetFromContainingBlock =+ currentNodeLeftOffsetFromContainingBlock ++ child->getLayout().position(PhysicalEdge::Left);+ const float childTopOffsetFromContainingBlock =+ currentNodeTopOffsetFromContainingBlock ++ child->getLayout().position(PhysicalEdge::Top);++ hasNewLayout = layoutAbsoluteDescendants(+ containingNode,+ child,+ widthSizingMode,+ childDirection,+ layoutMarkerData,+ currentDepth + 1,+ generationCount,+ childLeftOffsetFromContainingBlock,+ childTopOffsetFromContainingBlock,+ containingNodeAvailableInnerWidth,+ containingNodeAvailableInnerHeight) ||+ hasNewLayout;++ if (hasNewLayout) {+ child->setHasNewLayout(hasNewLayout);+ }+ }+ }+ return hasNewLayout;+}+} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/AbsoluteLayout.h b/third_party/yoga/algorithm/AbsoluteLayout.hnew file mode 100644index 000000000..584a586a0--- /dev/null+++ b/third_party/yoga/algorithm/AbsoluteLayout.h@@ -0,0 +1,41 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/event/event.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++void layoutAbsoluteChild(+ const yoga::Node* containingNode,+ const yoga::Node* node,+ yoga::Node* child,+ float containingBlockWidth,+ float containingBlockHeight,+ SizingMode widthMode,+ Direction direction,+ LayoutData& layoutMarkerData,+ uint32_t depth,+ uint32_t generationCount);++// Returns if some absolute descendant has new layout+bool layoutAbsoluteDescendants(+ yoga::Node* containingNode,+ yoga::Node* currentNode,+ SizingMode widthSizingMode,+ Direction currentNodeDirection,+ LayoutData& layoutMarkerData,+ uint32_t currentDepth,+ uint32_t generationCount,+ float currentNodeMainOffsetFromContainingBlock,+ float currentNodeCrossOffsetFromContainingBlock,+ float containingNodeAvailableInnerWidth,+ float containingNodeAvailableInnerHeight);++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/Align.h b/third_party/yoga/algorithm/Align.hnew file mode 100644index 000000000..b12ae7fd5--- /dev/null+++ b/third_party/yoga/algorithm/Align.h@@ -0,0 +1,83 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/Yoga.h>++#include <yoga/algorithm/FlexDirection.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++inline Align resolveChildAlignment(+ const yoga::Node* node,+ const yoga::Node* child) {+ const Align align = child->style().alignSelf() == Align::Auto+ ? node->style().alignItems()+ : child->style().alignSelf();++ if (node->style().display() == Display::Flex && align == Align::Baseline &&+ isColumn(node->style().flexDirection())) {+ return Align::FlexStart;+ }++ return align;+}++inline Justify resolveChildJustification(+ const yoga::Node* node,+ const yoga::Node* child) {+ return child->style().justifySelf() == Justify::Auto+ ? node->style().justifyItems()+ : child->style().justifySelf();+}++/**+ * Fallback alignment to use on overflow+ * https://www.w3.org/TR/css-align-3/#distribution-values+ */+constexpr Align fallbackAlignment(Align align) {+ switch (align) {+ // Fallback to flex-start+ case Align::SpaceBetween:+ case Align::Stretch:+ return Align::FlexStart;++ // Fallback to safe center. TODO (T208209388): This should be aligned to+ // Start instead of FlexStart (for row-reverse containers)+ case Align::SpaceAround:+ case Align::SpaceEvenly:+ return Align::FlexStart;+ default:+ return align;+ }+}++/**+ * Fallback alignment to use on overflow+ * https://www.w3.org/TR/css-align-3/#distribution-values+ */+constexpr Justify fallbackAlignment(Justify align) {+ switch (align) {+ // Fallback to flex-start+ case Justify::SpaceBetween:+ // TODO: Support `justify-content: stretch`+ // case Justify::Stretch:+ return Justify::FlexStart;++ // Fallback to safe center. TODO (T208209388): This should be aligned to+ // Start instead of FlexStart (for row-reverse containers)+ case Justify::SpaceAround:+ case Justify::SpaceEvenly:+ return Justify::FlexStart;+ default:+ return align;+ }+}++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/Baseline.cpp b/third_party/yoga/algorithm/Baseline.cppnew file mode 100644index 000000000..b3002012b--- /dev/null+++ b/third_party/yoga/algorithm/Baseline.cpp@@ -0,0 +1,78 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/Yoga.h>++#include <yoga/algorithm/Align.h>+#include <yoga/algorithm/Baseline.h>+#include <yoga/debug/AssertFatal.h>+#include <yoga/event/event.h>++namespace facebook::yoga {++float calculateBaseline(const yoga::Node* node) {+ if (node->hasBaselineFunc()) {+ Event::publish<Event::NodeBaselineStart>(node);++ const float baseline = node->baseline(+ node->getLayout().measuredDimension(Dimension::Width),+ node->getLayout().measuredDimension(Dimension::Height));++ Event::publish<Event::NodeBaselineEnd>(node);++ yoga::assertFatalWithNode(+ node,+ !std::isnan(baseline),+ "Expect custom baseline function to not return NaN");+ return baseline;+ }++ yoga::Node* baselineChild = nullptr;+ for (auto child : node->getLayoutChildren()) {+ if (child->getLineIndex() > 0) {+ break;+ }+ if (child->style().positionType() == PositionType::Absolute) {+ continue;+ }+ if (resolveChildAlignment(node, child) == Align::Baseline ||+ child->isReferenceBaseline()) {+ baselineChild = child;+ break;+ }++ if (baselineChild == nullptr) {+ baselineChild = child;+ }+ }++ if (baselineChild == nullptr) {+ return node->getLayout().measuredDimension(Dimension::Height);+ }++ const float baseline = calculateBaseline(baselineChild);+ return baseline + baselineChild->getLayout().position(PhysicalEdge::Top);+}++bool isBaselineLayout(const yoga::Node* node) {+ if (isColumn(node->style().flexDirection())) {+ return false;+ }+ if (node->style().alignItems() == Align::Baseline) {+ return true;+ }+ for (auto child : node->getLayoutChildren()) {+ if (child->style().positionType() != PositionType::Absolute &&+ child->style().alignSelf() == Align::Baseline) {+ return true;+ }+ }++ return false;+}++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/Baseline.h b/third_party/yoga/algorithm/Baseline.hnew file mode 100644index 000000000..c95ffd0f0--- /dev/null+++ b/third_party/yoga/algorithm/Baseline.h@@ -0,0 +1,21 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/Yoga.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++// Calculate baseline represented as an offset from the top edge of the node.+float calculateBaseline(const yoga::Node* node);++// Whether any of the children of this node participate in baseline alignment+bool isBaselineLayout(const yoga::Node* node);++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/BoundAxis.h b/third_party/yoga/algorithm/BoundAxis.hnew file mode 100644index 000000000..d9ebc68c5--- /dev/null+++ b/third_party/yoga/algorithm/BoundAxis.h@@ -0,0 +1,79 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/algorithm/FlexDirection.h>+#include <yoga/enums/Dimension.h>+#include <yoga/enums/FlexDirection.h>+#include <yoga/node/Node.h>+#include <yoga/numeric/Comparison.h>+#include <yoga/numeric/FloatOptional.h>++namespace facebook::yoga {++inline float paddingAndBorderForAxis(+ const yoga::Node* const node,+ const FlexDirection axis,+ const Direction direction,+ const float widthSize) {+ return node->style().computeInlineStartPaddingAndBorder(+ axis, direction, widthSize) ++ node->style().computeInlineEndPaddingAndBorder(+ axis, direction, widthSize);+}++inline FloatOptional boundAxisWithinMinAndMax(+ const yoga::Node* const node,+ const Direction direction,+ const FlexDirection axis,+ const FloatOptional value,+ const float axisSize,+ const float widthSize) {+ FloatOptional min;+ FloatOptional max;++ if (isColumn(axis)) {+ min = node->style().resolvedMinDimension(+ direction, Dimension::Height, axisSize, widthSize);+ max = node->style().resolvedMaxDimension(+ direction, Dimension::Height, axisSize, widthSize);+ } else if (isRow(axis)) {+ min = node->style().resolvedMinDimension(+ direction, Dimension::Width, axisSize, widthSize);+ max = node->style().resolvedMaxDimension(+ direction, Dimension::Width, axisSize, widthSize);+ }++ if (max >= FloatOptional{0} && value > max) {+ return max;+ }++ if (min >= FloatOptional{0} && value < min) {+ return min;+ }++ return value;+}++// Like boundAxisWithinMinAndMax but also ensures that the value doesn't+// go below the padding and border amount.+inline float boundAxis(+ const yoga::Node* const node,+ const FlexDirection axis,+ const Direction direction,+ const float value,+ const float axisSize,+ const float widthSize) {+ return yoga::maxOrDefined(+ boundAxisWithinMinAndMax(+ node, direction, axis, FloatOptional{value}, axisSize, widthSize)+ .unwrap(),+ paddingAndBorderForAxis(node, axis, direction, widthSize));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/Cache.cpp b/third_party/yoga/algorithm/Cache.cppnew file mode 100644index 000000000..9154fc6ce--- /dev/null+++ b/third_party/yoga/algorithm/Cache.cpp@@ -0,0 +1,121 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/algorithm/Cache.h>+#include <yoga/algorithm/PixelGrid.h>+#include <yoga/numeric/Comparison.h>++namespace facebook::yoga {++static inline bool sizeIsExactAndMatchesOldMeasuredSize(+ SizingMode sizeMode,+ float size,+ float lastComputedSize) {+ return sizeMode == SizingMode::StretchFit &&+ yoga::inexactEquals(size, lastComputedSize);+}++static inline bool oldSizeIsMaxContentAndStillFits(+ SizingMode sizeMode,+ float size,+ SizingMode lastSizeMode,+ float lastComputedSize) {+ return sizeMode == SizingMode::FitContent &&+ lastSizeMode == SizingMode::MaxContent &&+ (size >= lastComputedSize || yoga::inexactEquals(size, lastComputedSize));+}++static inline bool newSizeIsStricterAndStillValid(+ SizingMode sizeMode,+ float size,+ SizingMode lastSizeMode,+ float lastSize,+ float lastComputedSize) {+ return lastSizeMode == SizingMode::FitContent &&+ sizeMode == SizingMode::FitContent && yoga::isDefined(lastSize) &&+ yoga::isDefined(size) && yoga::isDefined(lastComputedSize) &&+ lastSize > size &&+ (lastComputedSize <= size || yoga::inexactEquals(size, lastComputedSize));+}++bool canUseCachedMeasurement(+ const SizingMode widthMode,+ const float availableWidth,+ const SizingMode heightMode,+ const float availableHeight,+ const SizingMode lastWidthMode,+ const float lastAvailableWidth,+ const SizingMode lastHeightMode,+ const float lastAvailableHeight,+ const float lastComputedWidth,+ const float lastComputedHeight,+ const float marginRow,+ const float marginColumn,+ const yoga::Config* const config) {+ if ((yoga::isDefined(lastComputedHeight) && lastComputedHeight < 0) ||+ ((yoga::isDefined(lastComputedWidth)) && lastComputedWidth < 0)) {+ return false;+ }++ const float pointScaleFactor = config->getPointScaleFactor();++ bool useRoundedComparison = config != nullptr && pointScaleFactor != 0;+ const float effectiveWidth = useRoundedComparison+ ? roundValueToPixelGrid(availableWidth, pointScaleFactor, false, false)+ : availableWidth;+ const float effectiveHeight = useRoundedComparison+ ? roundValueToPixelGrid(availableHeight, pointScaleFactor, false, false)+ : availableHeight;+ const float effectiveLastWidth = useRoundedComparison+ ? roundValueToPixelGrid(+ lastAvailableWidth, pointScaleFactor, false, false)+ : lastAvailableWidth;+ const float effectiveLastHeight = useRoundedComparison+ ? roundValueToPixelGrid(+ lastAvailableHeight, pointScaleFactor, false, false)+ : lastAvailableHeight;++ const bool hasSameWidthSpec = lastWidthMode == widthMode &&+ yoga::inexactEquals(effectiveLastWidth, effectiveWidth);+ const bool hasSameHeightSpec = lastHeightMode == heightMode &&+ yoga::inexactEquals(effectiveLastHeight, effectiveHeight);++ const bool widthIsCompatible =+ hasSameWidthSpec ||+ sizeIsExactAndMatchesOldMeasuredSize(+ widthMode, availableWidth - marginRow, lastComputedWidth) ||+ oldSizeIsMaxContentAndStillFits(+ widthMode,+ availableWidth - marginRow,+ lastWidthMode,+ lastComputedWidth) ||+ newSizeIsStricterAndStillValid(+ widthMode,+ availableWidth - marginRow,+ lastWidthMode,+ lastAvailableWidth,+ lastComputedWidth);++ const bool heightIsCompatible = hasSameHeightSpec ||+ sizeIsExactAndMatchesOldMeasuredSize(+ heightMode,+ availableHeight - marginColumn,+ lastComputedHeight) ||+ oldSizeIsMaxContentAndStillFits(heightMode,+ availableHeight - marginColumn,+ lastHeightMode,+ lastComputedHeight) ||+ newSizeIsStricterAndStillValid(heightMode,+ availableHeight - marginColumn,+ lastHeightMode,+ lastAvailableHeight,+ lastComputedHeight);++ return widthIsCompatible && heightIsCompatible;+}++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/Cache.h b/third_party/yoga/algorithm/Cache.hnew file mode 100644index 000000000..f8857eaf3--- /dev/null+++ b/third_party/yoga/algorithm/Cache.h@@ -0,0 +1,30 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/algorithm/SizingMode.h>+#include <yoga/config/Config.h>++namespace facebook::yoga {++bool canUseCachedMeasurement(+ SizingMode widthMode,+ float availableWidth,+ SizingMode heightMode,+ float availableHeight,+ SizingMode lastWidthMode,+ float lastAvailableWidth,+ SizingMode lastHeightMode,+ float lastAvailableHeight,+ float lastComputedWidth,+ float lastComputedHeight,+ float marginRow,+ float marginColumn,+ const yoga::Config* config);++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/CalculateLayout.cpp b/third_party/yoga/algorithm/CalculateLayout.cppnew file mode 100644index 000000000..0a7224cc0--- /dev/null+++ b/third_party/yoga/algorithm/CalculateLayout.cpp@@ -0,0 +1,2452 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <algorithm>+#include <atomic>+#include <cfloat>+#include <cmath>+#include <cstring>++#include <yoga/Yoga.h>++#include <yoga/algorithm/AbsoluteLayout.h>+#include <yoga/algorithm/Align.h>+#include <yoga/algorithm/Baseline.h>+#include <yoga/algorithm/BoundAxis.h>+#include <yoga/algorithm/Cache.h>+#include <yoga/algorithm/CalculateLayout.h>+#include <yoga/algorithm/FlexDirection.h>+#include <yoga/algorithm/FlexLine.h>+#include <yoga/algorithm/PixelGrid.h>+#include <yoga/algorithm/SizingMode.h>+#include <yoga/algorithm/TrailingPosition.h>+#include <yoga/debug/AssertFatal.h>+#include <yoga/debug/Log.h>+#include <yoga/event/event.h>+#include <yoga/node/Node.h>+#include <yoga/numeric/Comparison.h>+#include <yoga/numeric/FloatOptional.h>++namespace facebook::yoga {++std::atomic<uint32_t> gCurrentGenerationCount(0);++void constrainMaxSizeForMode(+ const yoga::Node* node,+ Direction direction,+ FlexDirection axis,+ float ownerAxisSize,+ float ownerWidth,+ /*in_out*/ SizingMode* mode,+ /*in_out*/ float* size) {+ const FloatOptional maxSize =+ node->style().resolvedMaxDimension(+ direction, dimension(axis), ownerAxisSize, ownerWidth) ++ FloatOptional(node->style().computeMarginForAxis(axis, ownerWidth));+ switch (*mode) {+ case SizingMode::StretchFit:+ case SizingMode::FitContent:+ *size = (maxSize.isUndefined() || *size < maxSize.unwrap())+ ? *size+ : maxSize.unwrap();+ break;+ case SizingMode::MaxContent:+ if (maxSize.isDefined()) {+ *mode = SizingMode::FitContent;+ *size = maxSize.unwrap();+ }+ break;+ }+}++static void computeFlexBasisForChild(+ const yoga::Node* const node,+ yoga::Node* const child,+ const float width,+ const SizingMode widthMode,+ const float height,+ const float ownerWidth,+ const float ownerHeight,+ const SizingMode heightMode,+ const Direction direction,+ LayoutData& layoutMarkerData,+ const uint32_t depth,+ const uint32_t generationCount) {+ const FlexDirection mainAxis =+ resolveDirection(node->style().flexDirection(), direction);+ const bool isMainAxisRow = isRow(mainAxis);+ const float mainAxisSize = isMainAxisRow ? width : height;+ const float mainAxisOwnerSize = isMainAxisRow ? ownerWidth : ownerHeight;++ float childWidth = YGUndefined;+ float childHeight = YGUndefined;+ SizingMode childWidthSizingMode;+ SizingMode childHeightSizingMode;++ const FloatOptional resolvedFlexBasis = child->resolveFlexBasis(+ direction, mainAxis, mainAxisOwnerSize, ownerWidth);+ const bool isRowStyleDimDefined =+ child->hasDefiniteLength(Dimension::Width, ownerWidth);+ const bool isColumnStyleDimDefined =+ child->hasDefiniteLength(Dimension::Height, ownerHeight);++ if (resolvedFlexBasis.isDefined() && yoga::isDefined(mainAxisSize)) {+ if (child->getLayout().computedFlexBasis.isUndefined() ||+ (child->getConfig()->isExperimentalFeatureEnabled(+ ExperimentalFeature::WebFlexBasis) &&+ child->getLayout().computedFlexBasisGeneration != generationCount)) {+ const FloatOptional paddingAndBorder = FloatOptional(+ paddingAndBorderForAxis(child, mainAxis, direction, ownerWidth));+ child->setLayoutComputedFlexBasis(+ yoga::maxOrDefined(resolvedFlexBasis, paddingAndBorder));+ }+ } else if (isMainAxisRow && isRowStyleDimDefined) {+ // The width is definite, so use that as the flex basis.+ const FloatOptional paddingAndBorder =+ FloatOptional(paddingAndBorderForAxis(+ child, FlexDirection::Row, direction, ownerWidth));++ child->setLayoutComputedFlexBasis(+ yoga::maxOrDefined(+ child->getResolvedDimension(+ direction, Dimension::Width, ownerWidth, ownerWidth),+ paddingAndBorder));+ } else if (!isMainAxisRow && isColumnStyleDimDefined) {+ // The height is definite, so use that as the flex basis.+ const FloatOptional paddingAndBorder =+ FloatOptional(paddingAndBorderForAxis(+ child, FlexDirection::Column, direction, ownerWidth));+ child->setLayoutComputedFlexBasis(+ yoga::maxOrDefined(+ child->getResolvedDimension(+ direction, Dimension::Height, ownerHeight, ownerWidth),+ paddingAndBorder));+ } else {+ // Compute the flex basis and hypothetical main size (i.e. the clamped flex+ // basis).+ childWidthSizingMode = SizingMode::MaxContent;+ childHeightSizingMode = SizingMode::MaxContent;++ auto marginRow =+ child->style().computeMarginForAxis(FlexDirection::Row, ownerWidth);+ auto marginColumn =+ child->style().computeMarginForAxis(FlexDirection::Column, ownerWidth);++ if (isRowStyleDimDefined) {+ childWidth = child+ ->getResolvedDimension(+ direction, Dimension::Width, ownerWidth, ownerWidth)+ .unwrap() ++ marginRow;+ childWidthSizingMode = SizingMode::StretchFit;+ }+ if (isColumnStyleDimDefined) {+ childHeight =+ child+ ->getResolvedDimension(+ direction, Dimension::Height, ownerHeight, ownerWidth)+ .unwrap() ++ marginColumn;+ childHeightSizingMode = SizingMode::StretchFit;+ }++ // The W3C spec doesn't say anything about the 'overflow' property, but all+ // major browsers appear to implement the following logic.+ if ((!isMainAxisRow && node->style().overflow() == Overflow::Scroll) ||+ node->style().overflow() != Overflow::Scroll) {+ if (yoga::isUndefined(childWidth) && yoga::isDefined(width)) {+ childWidth = width;+ childWidthSizingMode = SizingMode::FitContent;+ }+ }++ if ((isMainAxisRow && node->style().overflow() == Overflow::Scroll) ||+ node->style().overflow() != Overflow::Scroll) {+ if (yoga::isUndefined(childHeight) && yoga::isDefined(height)) {+ childHeight = height;+ childHeightSizingMode = SizingMode::FitContent;+ }+ }++ const auto& childStyle = child->style();+ if (childStyle.aspectRatio().isDefined()) {+ if (!isMainAxisRow && childWidthSizingMode == SizingMode::StretchFit) {+ childHeight = marginColumn ++ (childWidth - marginRow) / childStyle.aspectRatio().unwrap();+ childHeightSizingMode = SizingMode::StretchFit;+ } else if (+ isMainAxisRow && childHeightSizingMode == SizingMode::StretchFit) {+ childWidth = marginRow ++ (childHeight - marginColumn) * childStyle.aspectRatio().unwrap();+ childWidthSizingMode = SizingMode::StretchFit;+ }+ }++ // If child has no defined size in the cross axis and is set to stretch, set+ // the cross axis to be measured exactly with the available inner width++ const bool hasExactWidth =+ yoga::isDefined(width) && widthMode == SizingMode::StretchFit;+ const bool childWidthStretch =+ resolveChildAlignment(node, child) == Align::Stretch &&+ childWidthSizingMode != SizingMode::StretchFit;+ if (!isMainAxisRow && !isRowStyleDimDefined && hasExactWidth &&+ childWidthStretch) {+ childWidth = width;+ childWidthSizingMode = SizingMode::StretchFit;+ if (childStyle.aspectRatio().isDefined()) {+ childHeight =+ (childWidth - marginRow) / childStyle.aspectRatio().unwrap();+ childHeightSizingMode = SizingMode::StretchFit;+ }+ }++ const bool hasExactHeight =+ yoga::isDefined(height) && heightMode == SizingMode::StretchFit;+ const bool childHeightStretch =+ resolveChildAlignment(node, child) == Align::Stretch &&+ childHeightSizingMode != SizingMode::StretchFit;+ if (isMainAxisRow && !isColumnStyleDimDefined && hasExactHeight &&+ childHeightStretch) {+ childHeight = height;+ childHeightSizingMode = SizingMode::StretchFit;++ if (childStyle.aspectRatio().isDefined()) {+ childWidth =+ (childHeight - marginColumn) * childStyle.aspectRatio().unwrap();+ childWidthSizingMode = SizingMode::StretchFit;+ }+ }++ constrainMaxSizeForMode(+ child,+ direction,+ FlexDirection::Row,+ ownerWidth,+ ownerWidth,+ &childWidthSizingMode,+ &childWidth);+ constrainMaxSizeForMode(+ child,+ direction,+ FlexDirection::Column,+ ownerHeight,+ ownerWidth,+ &childHeightSizingMode,+ &childHeight);++ // Measure the child+ calculateLayoutInternal(+ child,+ childWidth,+ childHeight,+ direction,+ childWidthSizingMode,+ childHeightSizingMode,+ ownerWidth,+ ownerHeight,+ false,+ LayoutPassReason::kMeasureChild,+ layoutMarkerData,+ depth,+ generationCount);++ child->setLayoutComputedFlexBasis(FloatOptional(+ yoga::maxOrDefined(+ child->getLayout().measuredDimension(dimension(mainAxis)),+ paddingAndBorderForAxis(child, mainAxis, direction, ownerWidth))));+ }+ child->setLayoutComputedFlexBasisGeneration(generationCount);+}++static void measureNodeWithMeasureFunc(+ yoga::Node* const node,+ const Direction direction,+ float availableWidth,+ float availableHeight,+ const SizingMode widthSizingMode,+ const SizingMode heightSizingMode,+ const float ownerWidth,+ const float ownerHeight,+ LayoutData& layoutMarkerData,+ const LayoutPassReason reason) {+ yoga::assertFatalWithNode(+ node,+ node->hasMeasureFunc(),+ "Expected node to have custom measure function");++ if (widthSizingMode == SizingMode::MaxContent) {+ availableWidth = YGUndefined;+ }+ if (heightSizingMode == SizingMode::MaxContent) {+ availableHeight = YGUndefined;+ }++ const auto& layout = node->getLayout();+ const float paddingAndBorderAxisRow = layout.padding(PhysicalEdge::Left) ++ layout.padding(PhysicalEdge::Right) + layout.border(PhysicalEdge::Left) ++ layout.border(PhysicalEdge::Right);+ const float paddingAndBorderAxisColumn = layout.padding(PhysicalEdge::Top) ++ layout.padding(PhysicalEdge::Bottom) + layout.border(PhysicalEdge::Top) ++ layout.border(PhysicalEdge::Bottom);++ // We want to make sure we don't call measure with negative size+ const float innerWidth = yoga::isUndefined(availableWidth)+ ? availableWidth+ : yoga::maxOrDefined(0.0f, availableWidth - paddingAndBorderAxisRow);+ const float innerHeight = yoga::isUndefined(availableHeight)+ ? availableHeight+ : yoga::maxOrDefined(0.0f, availableHeight - paddingAndBorderAxisColumn);++ if (widthSizingMode == SizingMode::StretchFit &&+ heightSizingMode == SizingMode::StretchFit) {+ // Don't bother sizing the text if both dimensions are already defined.+ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ FlexDirection::Row,+ direction,+ availableWidth,+ ownerWidth,+ ownerWidth),+ Dimension::Width);+ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ FlexDirection::Column,+ direction,+ availableHeight,+ ownerHeight,+ ownerWidth),+ Dimension::Height);+ } else {+ Event::publish<Event::MeasureCallbackStart>(node);++ // Measure the text under the current constraints.+ const YGSize measuredSize = node->measure(+ innerWidth,+ measureMode(widthSizingMode),+ innerHeight,+ measureMode(heightSizingMode));++ layoutMarkerData.measureCallbacks += 1;+ layoutMarkerData.measureCallbackReasonsCount[static_cast<size_t>(reason)] +=+ 1;++ Event::publish<Event::MeasureCallbackEnd>(+ node,+ {.width = innerWidth,+ .widthMeasureMode = unscopedEnum(measureMode(widthSizingMode)),+ .height = innerHeight,+ .heightMeasureMode = unscopedEnum(measureMode(heightSizingMode)),+ .measuredWidth = measuredSize.width,+ .measuredHeight = measuredSize.height,+ .reason = reason});++ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ FlexDirection::Row,+ direction,+ (widthSizingMode == SizingMode::MaxContent ||+ widthSizingMode == SizingMode::FitContent)+ ? measuredSize.width + paddingAndBorderAxisRow+ : availableWidth,+ ownerWidth,+ ownerWidth),+ Dimension::Width);++ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ FlexDirection::Column,+ direction,+ (heightSizingMode == SizingMode::MaxContent ||+ heightSizingMode == SizingMode::FitContent)+ ? measuredSize.height + paddingAndBorderAxisColumn+ : availableHeight,+ ownerHeight,+ ownerWidth),+ Dimension::Height);+ }+}++// For nodes with no children, use the available values if they were provided,+// or the minimum size as indicated by the padding and border sizes.+static void measureNodeWithoutChildren(+ yoga::Node* const node,+ const Direction direction,+ const float availableWidth,+ const float availableHeight,+ const SizingMode widthSizingMode,+ const SizingMode heightSizingMode,+ const float ownerWidth,+ const float ownerHeight) {+ const auto& layout = node->getLayout();++ float width = availableWidth;+ if (widthSizingMode == SizingMode::MaxContent ||+ widthSizingMode == SizingMode::FitContent) {+ width = layout.padding(PhysicalEdge::Left) ++ layout.padding(PhysicalEdge::Right) ++ layout.border(PhysicalEdge::Left) + layout.border(PhysicalEdge::Right);+ }+ node->setLayoutMeasuredDimension(+ boundAxis(+ node, FlexDirection::Row, direction, width, ownerWidth, ownerWidth),+ Dimension::Width);++ float height = availableHeight;+ if (heightSizingMode == SizingMode::MaxContent ||+ heightSizingMode == SizingMode::FitContent) {+ height = layout.padding(PhysicalEdge::Top) ++ layout.padding(PhysicalEdge::Bottom) ++ layout.border(PhysicalEdge::Top) + layout.border(PhysicalEdge::Bottom);+ }+ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ FlexDirection::Column,+ direction,+ height,+ ownerHeight,+ ownerWidth),+ Dimension::Height);+}++inline bool isFixedSize(float dim, SizingMode sizingMode) {+ return sizingMode == SizingMode::StretchFit ||+ (yoga::isDefined(dim) && sizingMode == SizingMode::FitContent &&+ dim <= 0.0);+}++static bool measureNodeWithFixedSize(+ yoga::Node* const node,+ const Direction direction,+ const float availableWidth,+ const float availableHeight,+ const SizingMode widthSizingMode,+ const SizingMode heightSizingMode,+ const float ownerWidth,+ const float ownerHeight) {+ if (isFixedSize(availableWidth, widthSizingMode) &&+ isFixedSize(availableHeight, heightSizingMode)) {+ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ FlexDirection::Row,+ direction,+ yoga::isUndefined(availableWidth) ||+ (widthSizingMode == SizingMode::FitContent &&+ availableWidth < 0.0f)+ ? 0.0f+ : availableWidth,+ ownerWidth,+ ownerWidth),+ Dimension::Width);++ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ FlexDirection::Column,+ direction,+ yoga::isUndefined(availableHeight) ||+ (heightSizingMode == SizingMode::FitContent &&+ availableHeight < 0.0f)+ ? 0.0f+ : availableHeight,+ ownerHeight,+ ownerWidth),+ Dimension::Height);+ return true;+ }++ return false;+}++void zeroOutLayoutRecursively(yoga::Node* const node) {+ node->getLayout() = {};+ node->setLayoutDimension(0, Dimension::Width);+ node->setLayoutDimension(0, Dimension::Height);+ node->setHasNewLayout(true);++ node->cloneChildrenIfNeeded();+ for (const auto child : node->getChildren()) {+ zeroOutLayoutRecursively(child);+ }+}++void cleanupContentsNodesRecursively(yoga::Node* const node) {+ if (node->hasContentsChildren()) [[unlikely]] {+ node->cloneContentsChildrenIfNeeded();+ for (auto child : node->getChildren()) {+ if (child->style().display() == Display::Contents) {+ child->getLayout() = {};+ child->setLayoutDimension(0, Dimension::Width);+ child->setLayoutDimension(0, Dimension::Height);+ child->setHasNewLayout(true);+ child->setDirty(false);+ child->cloneChildrenIfNeeded();++ cleanupContentsNodesRecursively(child);+ }+ }+ }+}++float calculateAvailableInnerDimension(+ const yoga::Node* const node,+ const Direction direction,+ const Dimension dimension,+ const float availableDim,+ const float paddingAndBorder,+ const float ownerDim,+ const float ownerWidth) {+ float availableInnerDim = availableDim - paddingAndBorder;+ // Max dimension overrides predefined dimension value; Min dimension in turn+ // overrides both of the above+ if (yoga::isDefined(availableInnerDim)) {+ // We want to make sure our available height does not violate min and max+ // constraints+ const FloatOptional minDimensionOptional =+ node->style().resolvedMinDimension(+ direction, dimension, ownerDim, ownerWidth);+ const float minInnerDim = minDimensionOptional.isUndefined()+ ? 0.0f+ : minDimensionOptional.unwrap() - paddingAndBorder;++ const FloatOptional maxDimensionOptional =+ node->style().resolvedMaxDimension(+ direction, dimension, ownerDim, ownerWidth);++ const float maxInnerDim = maxDimensionOptional.isUndefined()+ ? FLT_MAX+ : maxDimensionOptional.unwrap() - paddingAndBorder;+ availableInnerDim = yoga::maxOrDefined(+ yoga::minOrDefined(availableInnerDim, maxInnerDim), minInnerDim);+ }++ return availableInnerDim;+}++static float computeFlexBasisForChildren(+ yoga::Node* const node,+ const float availableInnerWidth,+ const float availableInnerHeight,+ SizingMode widthSizingMode,+ SizingMode heightSizingMode,+ Direction direction,+ FlexDirection mainAxis,+ bool performLayout,+ LayoutData& layoutMarkerData,+ const uint32_t depth,+ const uint32_t generationCount) {+ float totalOuterFlexBasis = 0.0f;+ YGNodeRef singleFlexChild = nullptr;+ auto children = node->getLayoutChildren();+ SizingMode sizingModeMainDim =+ isRow(mainAxis) ? widthSizingMode : heightSizingMode;+ // If there is only one child with flexGrow + flexShrink it means we can set+ // the computedFlexBasis to 0 instead of measuring and shrinking / flexing the+ // child to exactly match the remaining space+ if (sizingModeMainDim == SizingMode::StretchFit) {+ for (auto child : children) {+ if (child->isNodeFlexible()) {+ if (singleFlexChild != nullptr ||+ yoga::inexactEquals(child->resolveFlexGrow(), 0.0f) ||+ yoga::inexactEquals(child->resolveFlexShrink(), 0.0f)) {+ // There is already a flexible child, or this flexible child doesn't+ // have flexGrow and flexShrink, abort+ singleFlexChild = nullptr;+ break;+ } else {+ singleFlexChild = child;+ }+ }+ }+ }++ for (auto child : children) {+ child->processDimensions();+ if (child->style().display() == Display::None) {+ zeroOutLayoutRecursively(child);+ child->setHasNewLayout(true);+ child->setDirty(false);+ continue;+ }+ if (performLayout) {+ // Set the initial position (relative to the owner).+ const Direction childDirection = child->resolveDirection(direction);+ child->setPosition(+ childDirection, availableInnerWidth, availableInnerHeight);+ }++ if (child->style().positionType() == PositionType::Absolute) {+ continue;+ }+ if (child == singleFlexChild) {+ child->setLayoutComputedFlexBasisGeneration(generationCount);+ child->setLayoutComputedFlexBasis(FloatOptional(0));+ } else {+ computeFlexBasisForChild(+ node,+ child,+ availableInnerWidth,+ widthSizingMode,+ availableInnerHeight,+ availableInnerWidth,+ availableInnerHeight,+ heightSizingMode,+ direction,+ layoutMarkerData,+ depth,+ generationCount);+ }++ totalOuterFlexBasis +=+ (child->getLayout().computedFlexBasis.unwrap() ++ child->style().computeMarginForAxis(mainAxis, availableInnerWidth));+ }++ return totalOuterFlexBasis;+}++// It distributes the free space to the flexible items and ensures that the size+// of the flex items abide the min and max constraints. At the end of this+// function the child nodes would have proper size. Prior using this function+// please ensure that distributeFreeSpaceFirstPass is called.+static float distributeFreeSpaceSecondPass(+ FlexLine& flexLine,+ yoga::Node* const node,+ const FlexDirection mainAxis,+ const FlexDirection crossAxis,+ const Direction direction,+ const float ownerWidth,+ const float mainAxisOwnerSize,+ const float availableInnerMainDim,+ const float availableInnerCrossDim,+ const float availableInnerWidth,+ const float availableInnerHeight,+ const bool mainAxisOverflows,+ const SizingMode sizingModeCrossDim,+ const bool performLayout,+ LayoutData& layoutMarkerData,+ const uint32_t depth,+ const uint32_t generationCount) {+ float childFlexBasis = 0;+ float flexShrinkScaledFactor = 0;+ float flexGrowFactor = 0;+ float deltaFreeSpace = 0;+ const bool isMainAxisRow = isRow(mainAxis);+ const bool isNodeFlexWrap = node->style().flexWrap() != Wrap::NoWrap;++ for (auto currentLineChild : flexLine.itemsInFlow) {+ childFlexBasis = boundAxisWithinMinAndMax(+ currentLineChild,+ direction,+ mainAxis,+ currentLineChild->getLayout().computedFlexBasis,+ mainAxisOwnerSize,+ ownerWidth)+ .unwrap();+ float updatedMainSize = childFlexBasis;++ if (yoga::isDefined(flexLine.layout.remainingFreeSpace) &&+ flexLine.layout.remainingFreeSpace < 0) {+ flexShrinkScaledFactor =+ -currentLineChild->resolveFlexShrink() * childFlexBasis;+ // Is this child able to shrink?+ if (flexShrinkScaledFactor != 0) {+ float childSize = YGUndefined;++ if (yoga::isDefined(flexLine.layout.totalFlexShrinkScaledFactors) &&+ flexLine.layout.totalFlexShrinkScaledFactors == 0) {+ childSize = childFlexBasis + flexShrinkScaledFactor;+ } else {+ childSize = childFlexBasis ++ (flexLine.layout.remainingFreeSpace /+ flexLine.layout.totalFlexShrinkScaledFactors) *+ flexShrinkScaledFactor;+ }++ updatedMainSize = boundAxis(+ currentLineChild,+ mainAxis,+ direction,+ childSize,+ availableInnerMainDim,+ availableInnerWidth);+ }+ } else if (+ yoga::isDefined(flexLine.layout.remainingFreeSpace) &&+ flexLine.layout.remainingFreeSpace > 0) {+ flexGrowFactor = currentLineChild->resolveFlexGrow();++ // Is this child able to grow?+ if (!std::isnan(flexGrowFactor) && flexGrowFactor != 0) {+ updatedMainSize = boundAxis(+ currentLineChild,+ mainAxis,+ direction,+ childFlexBasis ++ flexLine.layout.remainingFreeSpace /+ flexLine.layout.totalFlexGrowFactors * flexGrowFactor,+ availableInnerMainDim,+ availableInnerWidth);+ }+ }++ deltaFreeSpace += updatedMainSize - childFlexBasis;++ const float marginMain = currentLineChild->style().computeMarginForAxis(+ mainAxis, availableInnerWidth);+ const float marginCross = currentLineChild->style().computeMarginForAxis(+ crossAxis, availableInnerWidth);++ float childCrossSize = YGUndefined;+ float childMainSize = updatedMainSize + marginMain;+ SizingMode childCrossSizingMode;+ SizingMode childMainSizingMode = SizingMode::StretchFit;++ const auto& childStyle = currentLineChild->style();+ if (childStyle.aspectRatio().isDefined()) {+ childCrossSize = isMainAxisRow+ ? (childMainSize - marginMain) / childStyle.aspectRatio().unwrap()+ : (childMainSize - marginMain) * childStyle.aspectRatio().unwrap();+ childCrossSizingMode = SizingMode::StretchFit;++ childCrossSize += marginCross;+ } else if (+ !std::isnan(availableInnerCrossDim) &&+ !currentLineChild->hasDefiniteLength(+ dimension(crossAxis), availableInnerCrossDim) &&+ sizingModeCrossDim == SizingMode::StretchFit &&+ !(isNodeFlexWrap && mainAxisOverflows) &&+ resolveChildAlignment(node, currentLineChild) == Align::Stretch &&+ !currentLineChild->style().flexStartMarginIsAuto(+ crossAxis, direction) &&+ !currentLineChild->style().flexEndMarginIsAuto(crossAxis, direction)) {+ childCrossSize = availableInnerCrossDim;+ childCrossSizingMode = SizingMode::StretchFit;+ } else if (!currentLineChild->hasDefiniteLength(+ dimension(crossAxis), availableInnerCrossDim)) {+ childCrossSize = availableInnerCrossDim;+ childCrossSizingMode = yoga::isUndefined(childCrossSize)+ ? SizingMode::MaxContent+ : SizingMode::FitContent;+ } else {+ childCrossSize = currentLineChild+ ->getResolvedDimension(+ direction,+ dimension(crossAxis),+ availableInnerCrossDim,+ availableInnerWidth)+ .unwrap() ++ marginCross;+ const bool isLoosePercentageMeasurement =+ currentLineChild->getProcessedDimension(dimension(crossAxis))+ .isPercent() &&+ sizingModeCrossDim != SizingMode::StretchFit;+ childCrossSizingMode =+ yoga::isUndefined(childCrossSize) || isLoosePercentageMeasurement+ ? SizingMode::MaxContent+ : SizingMode::StretchFit;+ }++ constrainMaxSizeForMode(+ currentLineChild,+ direction,+ mainAxis,+ availableInnerMainDim,+ availableInnerWidth,+ &childMainSizingMode,+ &childMainSize);+ constrainMaxSizeForMode(+ currentLineChild,+ direction,+ crossAxis,+ availableInnerCrossDim,+ availableInnerWidth,+ &childCrossSizingMode,+ &childCrossSize);++ const bool requiresStretchLayout =+ !currentLineChild->hasDefiniteLength(+ dimension(crossAxis), availableInnerCrossDim) &&+ resolveChildAlignment(node, currentLineChild) == Align::Stretch &&+ !currentLineChild->style().flexStartMarginIsAuto(+ crossAxis, direction) &&+ !currentLineChild->style().flexEndMarginIsAuto(crossAxis, direction);++ const float childWidth = isMainAxisRow ? childMainSize : childCrossSize;+ const float childHeight = !isMainAxisRow ? childMainSize : childCrossSize;++ const SizingMode childWidthSizingMode =+ isMainAxisRow ? childMainSizingMode : childCrossSizingMode;+ const SizingMode childHeightSizingMode =+ !isMainAxisRow ? childMainSizingMode : childCrossSizingMode;++ const bool isLayoutPass = performLayout && !requiresStretchLayout;+ // Recursively call the layout algorithm for this child with the updated+ // main size.+ calculateLayoutInternal(+ currentLineChild,+ childWidth,+ childHeight,+ node->getLayout().direction(),+ childWidthSizingMode,+ childHeightSizingMode,+ availableInnerWidth,+ availableInnerHeight,+ isLayoutPass,+ isLayoutPass ? LayoutPassReason::kFlexLayout+ : LayoutPassReason::kFlexMeasure,+ layoutMarkerData,+ depth,+ generationCount);+ node->setLayoutHadOverflow(+ node->getLayout().hadOverflow() ||+ currentLineChild->getLayout().hadOverflow());+ }+ return deltaFreeSpace;+}++// It distributes the free space to the flexible items.For those flexible items+// whose min and max constraints are triggered, those flex item's clamped size+// is removed from the remaingfreespace.+static void distributeFreeSpaceFirstPass(+ FlexLine& flexLine,+ const Direction direction,+ const FlexDirection mainAxis,+ const float ownerWidth,+ const float mainAxisOwnerSize,+ const float availableInnerMainDim,+ const float availableInnerWidth) {+ float flexShrinkScaledFactor = 0;+ float flexGrowFactor = 0;+ float baseMainSize = 0;+ float boundMainSize = 0;+ float deltaFreeSpace = 0;++ for (auto currentLineChild : flexLine.itemsInFlow) {+ float childFlexBasis = boundAxisWithinMinAndMax(+ currentLineChild,+ direction,+ mainAxis,+ currentLineChild->getLayout().computedFlexBasis,+ mainAxisOwnerSize,+ ownerWidth)+ .unwrap();++ if (flexLine.layout.remainingFreeSpace < 0) {+ flexShrinkScaledFactor =+ -currentLineChild->resolveFlexShrink() * childFlexBasis;++ // Is this child able to shrink?+ if (yoga::isDefined(flexShrinkScaledFactor) &&+ flexShrinkScaledFactor != 0) {+ baseMainSize = childFlexBasis ++ flexLine.layout.remainingFreeSpace /+ flexLine.layout.totalFlexShrinkScaledFactors *+ flexShrinkScaledFactor;+ boundMainSize = boundAxis(+ currentLineChild,+ mainAxis,+ direction,+ baseMainSize,+ availableInnerMainDim,+ availableInnerWidth);+ if (yoga::isDefined(baseMainSize) && yoga::isDefined(boundMainSize) &&+ baseMainSize != boundMainSize) {+ // By excluding this item's size and flex factor from remaining, this+ // item's min/max constraints should also trigger in the second pass+ // resulting in the item's size calculation being identical in the+ // first and second passes.+ deltaFreeSpace += boundMainSize - childFlexBasis;+ flexLine.layout.totalFlexShrinkScaledFactors -=+ (-currentLineChild->resolveFlexShrink() *+ currentLineChild->getLayout().computedFlexBasis.unwrap());+ }+ }+ } else if (+ yoga::isDefined(flexLine.layout.remainingFreeSpace) &&+ flexLine.layout.remainingFreeSpace > 0) {+ flexGrowFactor = currentLineChild->resolveFlexGrow();++ // Is this child able to grow?+ if (yoga::isDefined(flexGrowFactor) && flexGrowFactor != 0) {+ baseMainSize = childFlexBasis ++ flexLine.layout.remainingFreeSpace /+ flexLine.layout.totalFlexGrowFactors * flexGrowFactor;+ boundMainSize = boundAxis(+ currentLineChild,+ mainAxis,+ direction,+ baseMainSize,+ availableInnerMainDim,+ availableInnerWidth);++ if (yoga::isDefined(baseMainSize) && yoga::isDefined(boundMainSize) &&+ baseMainSize != boundMainSize) {+ // By excluding this item's size and flex factor from remaining, this+ // item's min/max constraints should also trigger in the second pass+ // resulting in the item's size calculation being identical in the+ // first and second passes.+ deltaFreeSpace += boundMainSize - childFlexBasis;+ flexLine.layout.totalFlexGrowFactors -= flexGrowFactor;+ }+ }+ }+ }+ flexLine.layout.remainingFreeSpace -= deltaFreeSpace;+}++// Do two passes over the flex items to figure out how to distribute the+// remaining space.+//+// The first pass finds the items whose min/max constraints trigger, freezes+// them at those sizes, and excludes those sizes from the remaining space.+//+// The second pass sets the size of each flexible item. It distributes the+// remaining space amongst the items whose min/max constraints didn't trigger in+// the first pass. For the other items, it sets their sizes by forcing their+// min/max constraints to trigger again.+//+// This two pass approach for resolving min/max constraints deviates from the+// spec. The spec+// (https://www.w3.org/TR/CSS-flexbox-1/#resolve-flexible-lengths) describes a+// process that needs to be repeated a variable number of times. The algorithm+// implemented here won't handle all cases but it was simpler to implement and+// it mitigates performance concerns because we know exactly how many passes+// it'll do.+//+// At the end of this function the child nodes would have the proper size+// assigned to them.+//+static void resolveFlexibleLength(+ yoga::Node* const node,+ FlexLine& flexLine,+ const FlexDirection mainAxis,+ const FlexDirection crossAxis,+ const Direction direction,+ const float ownerWidth,+ const float mainAxisOwnerSize,+ const float availableInnerMainDim,+ const float availableInnerCrossDim,+ const float availableInnerWidth,+ const float availableInnerHeight,+ const bool mainAxisOverflows,+ const SizingMode sizingModeCrossDim,+ const bool performLayout,+ LayoutData& layoutMarkerData,+ const uint32_t depth,+ const uint32_t generationCount) {+ const float originalFreeSpace = flexLine.layout.remainingFreeSpace;+ // First pass: detect the flex items whose min/max constraints trigger+ distributeFreeSpaceFirstPass(+ flexLine,+ direction,+ mainAxis,+ ownerWidth,+ mainAxisOwnerSize,+ availableInnerMainDim,+ availableInnerWidth);++ // Second pass: resolve the sizes of the flexible items+ const float distributedFreeSpace = distributeFreeSpaceSecondPass(+ flexLine,+ node,+ mainAxis,+ crossAxis,+ direction,+ ownerWidth,+ mainAxisOwnerSize,+ availableInnerMainDim,+ availableInnerCrossDim,+ availableInnerWidth,+ availableInnerHeight,+ mainAxisOverflows,+ sizingModeCrossDim,+ performLayout,+ layoutMarkerData,+ depth,+ generationCount);++ flexLine.layout.remainingFreeSpace = originalFreeSpace - distributedFreeSpace;+}++static void justifyMainAxis(+ yoga::Node* const node,+ FlexLine& flexLine,+ const FlexDirection mainAxis,+ const FlexDirection crossAxis,+ const Direction direction,+ const SizingMode sizingModeMainDim,+ const SizingMode sizingModeCrossDim,+ const float mainAxisOwnerSize,+ const float ownerWidth,+ const float availableInnerMainDim,+ const float availableInnerCrossDim,+ const float availableInnerWidth,+ const bool performLayout) {+ const auto& style = node->style();++ const float leadingPaddingAndBorderMain =+ node->style().computeFlexStartPaddingAndBorder(+ mainAxis, direction, ownerWidth);+ const float trailingPaddingAndBorderMain =+ node->style().computeFlexEndPaddingAndBorder(+ mainAxis, direction, ownerWidth);++ const float gap =+ node->style().computeGapForAxis(mainAxis, availableInnerMainDim);+ // If we are using "at most" rules in the main axis, make sure that+ // remainingFreeSpace is 0 when min main dimension is not given+ if (sizingModeMainDim == SizingMode::FitContent &&+ flexLine.layout.remainingFreeSpace > 0) {+ if (style.minDimension(dimension(mainAxis)).isDefined() &&+ style+ .resolvedMinDimension(+ direction, dimension(mainAxis), mainAxisOwnerSize, ownerWidth)+ .isDefined()) {+ // This condition makes sure that if the size of main dimension(after+ // considering child nodes main dim, leading and trailing padding etc)+ // falls below min dimension, then the remainingFreeSpace is reassigned+ // considering the min dimension++ // `minAvailableMainDim` denotes minimum available space in which child+ // can be laid out, it will exclude space consumed by padding and border.+ const float minAvailableMainDim =+ style+ .resolvedMinDimension(+ direction, dimension(mainAxis), mainAxisOwnerSize, ownerWidth)+ .unwrap() -+ leadingPaddingAndBorderMain - trailingPaddingAndBorderMain;+ const float occupiedSpaceByChildNodes =+ availableInnerMainDim - flexLine.layout.remainingFreeSpace;+ flexLine.layout.remainingFreeSpace = yoga::maxOrDefined(+ 0.0f, minAvailableMainDim - occupiedSpaceByChildNodes);+ } else {+ flexLine.layout.remainingFreeSpace = 0;+ }+ }++ // In order to position the elements in the main axis, we have two controls.+ // The space between the beginning and the first element and the space between+ // each two elements.+ float leadingMainDim = 0;+ float betweenMainDim = gap;+ const Justify justifyContent = flexLine.layout.remainingFreeSpace >= 0+ ? node->style().justifyContent()+ : fallbackAlignment(node->style().justifyContent());++ if (flexLine.numberOfAutoMargins == 0) {+ switch (justifyContent) {+ case Justify::Start:+ case Justify::End:+ case Justify::Auto:+ // No-Op+ break;+ case Justify::Stretch:+ // No-Op+ break;+ case Justify::Center:+ leadingMainDim = flexLine.layout.remainingFreeSpace / 2;+ break;+ case Justify::FlexEnd:+ leadingMainDim = flexLine.layout.remainingFreeSpace;+ break;+ case Justify::SpaceBetween:+ if (flexLine.itemsInFlow.size() > 1) {+ betweenMainDim += flexLine.layout.remainingFreeSpace /+ static_cast<float>(flexLine.itemsInFlow.size() - 1);+ }+ break;+ case Justify::SpaceEvenly:+ // Space is distributed evenly across all elements+ leadingMainDim = flexLine.layout.remainingFreeSpace /+ static_cast<float>(flexLine.itemsInFlow.size() + 1);+ betweenMainDim += leadingMainDim;+ break;+ case Justify::SpaceAround:+ // Space on the edges is half of the space between elements+ leadingMainDim = 0.5f * flexLine.layout.remainingFreeSpace /+ static_cast<float>(flexLine.itemsInFlow.size());+ betweenMainDim += leadingMainDim * 2;+ break;+ case Justify::FlexStart:+ break;+ }+ }++ flexLine.layout.mainDim = leadingPaddingAndBorderMain + leadingMainDim;+ flexLine.layout.crossDim = 0;++ float maxAscentForCurrentLine = 0;+ float maxDescentForCurrentLine = 0;+ bool isNodeBaselineLayout = isBaselineLayout(node);+ for (auto child : flexLine.itemsInFlow) {+ const LayoutResults& childLayout = child->getLayout();+ if (child->style().flexStartMarginIsAuto(mainAxis, direction) &&+ flexLine.layout.remainingFreeSpace > 0.0f) {+ flexLine.layout.mainDim += flexLine.layout.remainingFreeSpace /+ static_cast<float>(flexLine.numberOfAutoMargins);+ }++ if (performLayout) {+ child->setLayoutPosition(+ childLayout.position(flexStartEdge(mainAxis)) ++ flexLine.layout.mainDim,+ flexStartEdge(mainAxis));+ }++ if (child != flexLine.itemsInFlow.back()) {+ flexLine.layout.mainDim += betweenMainDim;+ }++ if (child->style().flexEndMarginIsAuto(mainAxis, direction) &&+ flexLine.layout.remainingFreeSpace > 0.0f) {+ flexLine.layout.mainDim += flexLine.layout.remainingFreeSpace /+ static_cast<float>(flexLine.numberOfAutoMargins);+ }+ bool canSkipFlex =+ !performLayout && sizingModeCrossDim == SizingMode::StretchFit;+ if (canSkipFlex) {+ // If we skipped the flex step, then we can't rely on the measuredDims+ // because they weren't computed. This means we can't call+ // dimensionWithMargin.+ flexLine.layout.mainDim +=+ child->style().computeMarginForAxis(mainAxis, availableInnerWidth) ++ childLayout.computedFlexBasis.unwrap();+ flexLine.layout.crossDim = availableInnerCrossDim;+ } else {+ // The main dimension is the sum of all the elements dimension plus+ // the spacing.+ flexLine.layout.mainDim +=+ child->dimensionWithMargin(mainAxis, availableInnerWidth);++ if (isNodeBaselineLayout) {+ // If the child is baseline aligned then the cross dimension is+ // calculated by adding maxAscent and maxDescent from the baseline.+ const float ascent = calculateBaseline(child) ++ child->style().computeFlexStartMargin(+ FlexDirection::Column, direction, availableInnerWidth);+ const float descent =+ child->getLayout().measuredDimension(Dimension::Height) ++ child->style().computeMarginForAxis(+ FlexDirection::Column, availableInnerWidth) -+ ascent;++ maxAscentForCurrentLine =+ yoga::maxOrDefined(maxAscentForCurrentLine, ascent);+ maxDescentForCurrentLine =+ yoga::maxOrDefined(maxDescentForCurrentLine, descent);+ } else {+ // The cross dimension is the max of the elements dimension since+ // there can only be one element in that cross dimension in the case+ // when the items are not baseline aligned+ flexLine.layout.crossDim = yoga::maxOrDefined(+ flexLine.layout.crossDim,+ child->dimensionWithMargin(crossAxis, availableInnerWidth));+ }+ }+ }+ flexLine.layout.mainDim += trailingPaddingAndBorderMain;++ if (isNodeBaselineLayout) {+ flexLine.layout.crossDim =+ maxAscentForCurrentLine + maxDescentForCurrentLine;+ }+}++//+// This is the main routine that implements a subset of the flexbox layout+// algorithm described in the W3C CSS documentation:+// https://www.w3.org/TR/CSS3-flexbox/.+//+// Limitations of this algorithm, compared to the full standard:+// * Display property is always assumed to be 'flex' except for Text nodes,+// which are assumed to be 'inline-flex'.+// * The 'zIndex' property (or any form of z ordering) is not supported. Nodes+// are stacked in document order.+// * The 'order' property is not supported. The order of flex items is always+// defined by document order.+// * The 'visibility' property is always assumed to be 'visible'. Values of+// 'collapse' and 'hidden' are not supported.+// * There is no support for forced breaks.+// * It does not support vertical inline directions (top-to-bottom or+// bottom-to-top text).+//+// Deviations from standard:+// * Section 4.5 of the spec indicates that all flex items have a default+// minimum main size. For text blocks, for example, this is the width of the+// widest word. Calculating the minimum width is expensive, so we forego it+// and assume a default minimum main size of 0.+// * Min/Max sizes in the main axis are not honored when resolving flexible+// lengths.+// * The spec indicates that the default value for 'flexDirection' is 'row',+// but the algorithm below assumes a default of 'column'.+//+// Input parameters:+// - node: current node to be sized and laid out+// - availableWidth & availableHeight: available size to be used for sizing+// the node or YGUndefined if the size is not available; interpretation+// depends on layout flags+// - ownerDirection: the inline (text) direction within the owner+// (left-to-right or right-to-left)+// - widthSizingMode: indicates the sizing rules for the width (see below+// for explanation)+// - heightSizingMode: indicates the sizing rules for the height (see below+// for explanation)+// - performLayout: specifies whether the caller is interested in just the+// dimensions of the node or it requires the entire node and its subtree to+// be laid out (with final positions)+//+// Details:+// This routine is called recursively to lay out subtrees of flexbox+// elements. It uses the information in node.style, which is treated as a+// read-only input. It is responsible for setting the layout.direction and+// layout.measuredDimensions fields for the input node as well as the+// layout.position and layout.lineIndex fields for its child nodes. The+// layout.measuredDimensions field includes any border or padding for the+// node but does not include margins.+//+// When calling calculateLayoutImpl and calculateLayoutInternal, if the+// caller passes an available size of undefined then it must also pass a+// measure mode of SizingMode::MaxContent in that dimension.+//+static void calculateLayoutImpl(+ yoga::Node* const node,+ const float availableWidth,+ const float availableHeight,+ const Direction ownerDirection,+ const SizingMode widthSizingMode,+ const SizingMode heightSizingMode,+ const float ownerWidth,+ const float ownerHeight,+ const bool performLayout,+ const LayoutPassReason reason,+ LayoutData& layoutMarkerData,+ const uint32_t depth,+ const uint32_t generationCount) {+ yoga::assertFatalWithNode(+ node,+ yoga::isUndefined(availableWidth)+ ? widthSizingMode == SizingMode::MaxContent+ : true,+ "availableWidth is indefinite so widthSizingMode must be "+ "SizingMode::MaxContent");+ yoga::assertFatalWithNode(+ node,+ yoga::isUndefined(availableHeight)+ ? heightSizingMode == SizingMode::MaxContent+ : true,+ "availableHeight is indefinite so heightSizingMode must be "+ "SizingMode::MaxContent");++ (performLayout ? layoutMarkerData.layouts : layoutMarkerData.measures) += 1;++ // Set the resolved resolution in the node's layout.+ const Direction direction = node->resolveDirection(ownerDirection);+ node->setLayoutDirection(direction);++ const FlexDirection flexRowDirection =+ resolveDirection(FlexDirection::Row, direction);+ const FlexDirection flexColumnDirection =+ resolveDirection(FlexDirection::Column, direction);++ const auto startEdge =+ direction == Direction::LTR ? PhysicalEdge::Left : PhysicalEdge::Right;+ const auto endEdge =+ direction == Direction::LTR ? PhysicalEdge::Right : PhysicalEdge::Left;++ const float marginRowLeading = node->style().computeInlineStartMargin(+ flexRowDirection, direction, ownerWidth);+ node->setLayoutMargin(marginRowLeading, startEdge);+ const float marginRowTrailing = node->style().computeInlineEndMargin(+ flexRowDirection, direction, ownerWidth);+ node->setLayoutMargin(marginRowTrailing, endEdge);+ const float marginColumnLeading = node->style().computeInlineStartMargin(+ flexColumnDirection, direction, ownerWidth);+ node->setLayoutMargin(marginColumnLeading, PhysicalEdge::Top);+ const float marginColumnTrailing = node->style().computeInlineEndMargin(+ flexColumnDirection, direction, ownerWidth);+ node->setLayoutMargin(marginColumnTrailing, PhysicalEdge::Bottom);++ const float marginAxisRow = marginRowLeading + marginRowTrailing;+ const float marginAxisColumn = marginColumnLeading + marginColumnTrailing;++ node->setLayoutBorder(+ node->style().computeInlineStartBorder(flexRowDirection, direction),+ startEdge);+ node->setLayoutBorder(+ node->style().computeInlineEndBorder(flexRowDirection, direction),+ endEdge);+ node->setLayoutBorder(+ node->style().computeInlineStartBorder(flexColumnDirection, direction),+ PhysicalEdge::Top);+ node->setLayoutBorder(+ node->style().computeInlineEndBorder(flexColumnDirection, direction),+ PhysicalEdge::Bottom);++ node->setLayoutPadding(+ node->style().computeInlineStartPadding(+ flexRowDirection, direction, ownerWidth),+ startEdge);+ node->setLayoutPadding(+ node->style().computeInlineEndPadding(+ flexRowDirection, direction, ownerWidth),+ endEdge);+ node->setLayoutPadding(+ node->style().computeInlineStartPadding(+ flexColumnDirection, direction, ownerWidth),+ PhysicalEdge::Top);+ node->setLayoutPadding(+ node->style().computeInlineEndPadding(+ flexColumnDirection, direction, ownerWidth),+ PhysicalEdge::Bottom);++ if (node->hasMeasureFunc()) {+ measureNodeWithMeasureFunc(+ node,+ direction,+ availableWidth - marginAxisRow,+ availableHeight - marginAxisColumn,+ widthSizingMode,+ heightSizingMode,+ ownerWidth,+ ownerHeight,+ layoutMarkerData,+ reason);++ // Clean and update all display: contents nodes with a direct path to the+ // current node as they will not be traversed+ cleanupContentsNodesRecursively(node);+ return;+ }++ const auto childCount = node->getLayoutChildCount();+ if (childCount == 0) {+ measureNodeWithoutChildren(+ node,+ direction,+ availableWidth - marginAxisRow,+ availableHeight - marginAxisColumn,+ widthSizingMode,+ heightSizingMode,+ ownerWidth,+ ownerHeight);++ // Clean and update all display: contents nodes with a direct path to the+ // current node as they will not be traversed+ cleanupContentsNodesRecursively(node);+ return;+ }++ // If we're not being asked to perform a full layout we can skip the algorithm+ // if we already know the size+ if (!performLayout &&+ measureNodeWithFixedSize(+ node,+ direction,+ availableWidth - marginAxisRow,+ availableHeight - marginAxisColumn,+ widthSizingMode,+ heightSizingMode,+ ownerWidth,+ ownerHeight)) {+ // Clean and update all display: contents nodes with a direct path to the+ // current node as they will not be traversed+ cleanupContentsNodesRecursively(node);+ return;+ }++ // At this point we know we're going to perform work. Ensure that each child+ // has a mutable copy.+ node->cloneChildrenIfNeeded();+ // Reset layout flags, as they could have changed.+ node->setLayoutHadOverflow(false);++ // Clean and update all display: contents nodes with a direct path to the+ // current node as they will not be traversed+ cleanupContentsNodesRecursively(node);++ // STEP 1: CALCULATE VALUES FOR REMAINDER OF ALGORITHM+ const FlexDirection mainAxis =+ resolveDirection(node->style().flexDirection(), direction);+ const FlexDirection crossAxis = resolveCrossDirection(mainAxis, direction);+ const bool isMainAxisRow = isRow(mainAxis);+ const bool isNodeFlexWrap = node->style().flexWrap() != Wrap::NoWrap;++ const float mainAxisOwnerSize = isMainAxisRow ? ownerWidth : ownerHeight;+ const float crossAxisOwnerSize = isMainAxisRow ? ownerHeight : ownerWidth;++ const float paddingAndBorderAxisMain =+ paddingAndBorderForAxis(node, mainAxis, direction, ownerWidth);+ const float paddingAndBorderAxisCross =+ paddingAndBorderForAxis(node, crossAxis, direction, ownerWidth);+ const float leadingPaddingAndBorderCross =+ node->style().computeFlexStartPaddingAndBorder(+ crossAxis, direction, ownerWidth);++ SizingMode sizingModeMainDim =+ isMainAxisRow ? widthSizingMode : heightSizingMode;+ SizingMode sizingModeCrossDim =+ isMainAxisRow ? heightSizingMode : widthSizingMode;++ const float paddingAndBorderAxisRow =+ isMainAxisRow ? paddingAndBorderAxisMain : paddingAndBorderAxisCross;+ const float paddingAndBorderAxisColumn =+ isMainAxisRow ? paddingAndBorderAxisCross : paddingAndBorderAxisMain;++ // STEP 2: DETERMINE AVAILABLE SIZE IN MAIN AND CROSS DIRECTIONS++ float availableInnerWidth = calculateAvailableInnerDimension(+ node,+ direction,+ Dimension::Width,+ availableWidth - marginAxisRow,+ paddingAndBorderAxisRow,+ ownerWidth,+ ownerWidth);+ float availableInnerHeight = calculateAvailableInnerDimension(+ node,+ direction,+ Dimension::Height,+ availableHeight - marginAxisColumn,+ paddingAndBorderAxisColumn,+ ownerHeight,+ ownerWidth);++ float availableInnerMainDim =+ isMainAxisRow ? availableInnerWidth : availableInnerHeight;+ const float availableInnerCrossDim =+ isMainAxisRow ? availableInnerHeight : availableInnerWidth;++ // STEP 3: DETERMINE FLEX BASIS FOR EACH ITEM++ // Computed basis + margins + gap+ float totalMainDim = 0;+ totalMainDim += computeFlexBasisForChildren(+ node,+ availableInnerWidth,+ availableInnerHeight,+ widthSizingMode,+ heightSizingMode,+ direction,+ mainAxis,+ performLayout,+ layoutMarkerData,+ depth,+ generationCount);++ if (childCount > 1) {+ totalMainDim +=+ node->style().computeGapForAxis(mainAxis, availableInnerMainDim) *+ static_cast<float>(childCount - 1);+ }++ const bool mainAxisOverflows =+ (sizingModeMainDim != SizingMode::MaxContent) &&+ totalMainDim > availableInnerMainDim;++ if (isNodeFlexWrap && mainAxisOverflows &&+ sizingModeMainDim == SizingMode::FitContent) {+ sizingModeMainDim = SizingMode::StretchFit;+ }+ // STEP 4: COLLECT FLEX ITEMS INTO FLEX LINES++ // Iterator representing the beginning of the current line+ Node::LayoutableChildren::Iterator startOfLineIterator =+ node->getLayoutChildren().begin();++ // Number of lines.+ size_t lineCount = 0;++ // Accumulated cross dimensions of all lines so far.+ float totalLineCrossDim = 0;++ const float crossAxisGap =+ node->style().computeGapForAxis(crossAxis, availableInnerCrossDim);++ // Max main dimension of all the lines.+ float maxLineMainDim = 0;+ for (; startOfLineIterator != node->getLayoutChildren().end(); lineCount++) {+ auto flexLine = calculateFlexLine(+ node,+ ownerDirection,+ ownerWidth,+ mainAxisOwnerSize,+ availableInnerWidth,+ availableInnerMainDim,+ startOfLineIterator,+ lineCount);++ // If we don't need to measure the cross axis, we can skip the entire flex+ // step.+ const bool canSkipFlex =+ !performLayout && sizingModeCrossDim == SizingMode::StretchFit;++ // STEP 5: RESOLVING FLEXIBLE LENGTHS ON MAIN AXIS+ // Calculate the remaining available space that needs to be allocated. If+ // the main dimension size isn't known, it is computed based on the line+ // length, so there's no more space left to distribute.++ bool sizeBasedOnContent = false;+ // If we don't measure with exact main dimension we want to ensure we don't+ // violate min and max+ if (sizingModeMainDim != SizingMode::StretchFit) {+ const auto& style = node->style();+ const float minInnerWidth =+ style+ .resolvedMinDimension(+ direction, Dimension::Width, ownerWidth, ownerWidth)+ .unwrap() -+ paddingAndBorderAxisRow;+ const float maxInnerWidth =+ style+ .resolvedMaxDimension(+ direction, Dimension::Width, ownerWidth, ownerWidth)+ .unwrap() -+ paddingAndBorderAxisRow;+ const float minInnerHeight =+ style+ .resolvedMinDimension(+ direction, Dimension::Height, ownerHeight, ownerWidth)+ .unwrap() -+ paddingAndBorderAxisColumn;+ const float maxInnerHeight =+ style+ .resolvedMaxDimension(+ direction, Dimension::Height, ownerHeight, ownerWidth)+ .unwrap() -+ paddingAndBorderAxisColumn;++ const float minInnerMainDim =+ isMainAxisRow ? minInnerWidth : minInnerHeight;+ const float maxInnerMainDim =+ isMainAxisRow ? maxInnerWidth : maxInnerHeight;++ if (yoga::isDefined(minInnerMainDim) &&+ flexLine.sizeConsumed < minInnerMainDim) {+ availableInnerMainDim = minInnerMainDim;+ } else if (+ yoga::isDefined(maxInnerMainDim) &&+ flexLine.sizeConsumed > maxInnerMainDim) {+ availableInnerMainDim = maxInnerMainDim;+ } else {+ bool useLegacyStretchBehaviour =+ node->hasErrata(Errata::StretchFlexBasis);++ if (!useLegacyStretchBehaviour &&+ ((yoga::isDefined(flexLine.layout.totalFlexGrowFactors) &&+ flexLine.layout.totalFlexGrowFactors == 0) ||+ (yoga::isDefined(node->resolveFlexGrow()) &&+ node->resolveFlexGrow() == 0))) {+ // If we don't have any children to flex or we can't flex the node+ // itself, space we've used is all space we need. Root node also+ // should be shrunk to minimum+ availableInnerMainDim = flexLine.sizeConsumed;+ }++ sizeBasedOnContent = !useLegacyStretchBehaviour;+ }+ }++ if (!sizeBasedOnContent && yoga::isDefined(availableInnerMainDim)) {+ flexLine.layout.remainingFreeSpace =+ availableInnerMainDim - flexLine.sizeConsumed;+ } else if (flexLine.sizeConsumed < 0) {+ // availableInnerMainDim is indefinite which means the node is being sized+ // based on its content. sizeConsumed is negative which means+ // the node will allocate 0 points for its content. Consequently,+ // remainingFreeSpace is 0 - sizeConsumed.+ flexLine.layout.remainingFreeSpace = -flexLine.sizeConsumed;+ }++ if (!canSkipFlex) {+ resolveFlexibleLength(+ node,+ flexLine,+ mainAxis,+ crossAxis,+ direction,+ ownerWidth,+ mainAxisOwnerSize,+ availableInnerMainDim,+ availableInnerCrossDim,+ availableInnerWidth,+ availableInnerHeight,+ mainAxisOverflows,+ sizingModeCrossDim,+ performLayout,+ layoutMarkerData,+ depth,+ generationCount);+ }++ node->setLayoutHadOverflow(+ node->getLayout().hadOverflow() ||+ (flexLine.layout.remainingFreeSpace < 0));++ // STEP 6: MAIN-AXIS JUSTIFICATION & CROSS-AXIS SIZE DETERMINATION++ // At this point, all the children have their dimensions set in the main+ // axis. Their dimensions are also set in the cross axis with the exception+ // of items that are aligned "stretch". We need to compute these stretch+ // values and set the final positions.++ justifyMainAxis(+ node,+ flexLine,+ mainAxis,+ crossAxis,+ direction,+ sizingModeMainDim,+ sizingModeCrossDim,+ mainAxisOwnerSize,+ ownerWidth,+ availableInnerMainDim,+ availableInnerCrossDim,+ availableInnerWidth,+ performLayout);++ float containerCrossAxis = availableInnerCrossDim;+ if (sizingModeCrossDim == SizingMode::MaxContent ||+ sizingModeCrossDim == SizingMode::FitContent) {+ // Compute the cross axis from the max cross dimension of the children.+ containerCrossAxis =+ boundAxis(+ node,+ crossAxis,+ direction,+ flexLine.layout.crossDim + paddingAndBorderAxisCross,+ crossAxisOwnerSize,+ ownerWidth) -+ paddingAndBorderAxisCross;+ }++ // If there's no flex wrap, the cross dimension is defined by the container.+ if (!isNodeFlexWrap && sizingModeCrossDim == SizingMode::StretchFit) {+ flexLine.layout.crossDim = availableInnerCrossDim;+ }++ // As-per https://www.w3.org/TR/css-flexbox-1/#cross-sizing, the+ // cross-size of the line within a single-line container should be bound to+ // min/max constraints before alignment within the line. In a multi-line+ // container, affecting alignment between the lines.+ if (!isNodeFlexWrap) {+ flexLine.layout.crossDim =+ boundAxis(+ node,+ crossAxis,+ direction,+ flexLine.layout.crossDim + paddingAndBorderAxisCross,+ crossAxisOwnerSize,+ ownerWidth) -+ paddingAndBorderAxisCross;+ }++ // STEP 7: CROSS-AXIS ALIGNMENT+ // We can skip child alignment if we're just measuring the container.+ if (performLayout) {+ for (auto child : flexLine.itemsInFlow) {+ float leadingCrossDim = leadingPaddingAndBorderCross;++ // For a relative children, we're either using alignItems (owner) or+ // alignSelf (child) in order to determine the position in the cross+ // axis+ const Align alignItem = resolveChildAlignment(node, child);++ // If the child uses align stretch, we need to lay it out one more+ // time, this time forcing the cross-axis size to be the computed+ // cross size for the current line.+ if (alignItem == Align::Stretch &&+ !child->style().flexStartMarginIsAuto(crossAxis, direction) &&+ !child->style().flexEndMarginIsAuto(crossAxis, direction)) {+ // If the child defines a definite size for its cross axis, there's+ // no need to stretch.+ if (!child->hasDefiniteLength(+ dimension(crossAxis), availableInnerCrossDim)) {+ float childMainSize =+ child->getLayout().measuredDimension(dimension(mainAxis));+ const auto& childStyle = child->style();+ float childCrossSize = childStyle.aspectRatio().isDefined()+ ? child->style().computeMarginForAxis(+ crossAxis, availableInnerWidth) ++ (isMainAxisRow+ ? childMainSize / childStyle.aspectRatio().unwrap()+ : childMainSize * childStyle.aspectRatio().unwrap())+ : flexLine.layout.crossDim;++ childMainSize += child->style().computeMarginForAxis(+ mainAxis, availableInnerWidth);++ SizingMode childMainSizingMode = SizingMode::StretchFit;+ SizingMode childCrossSizingMode = SizingMode::StretchFit;+ constrainMaxSizeForMode(+ child,+ direction,+ mainAxis,+ availableInnerMainDim,+ availableInnerWidth,+ &childMainSizingMode,+ &childMainSize);+ constrainMaxSizeForMode(+ child,+ direction,+ crossAxis,+ availableInnerCrossDim,+ availableInnerWidth,+ &childCrossSizingMode,+ &childCrossSize);++ const float childWidth =+ isMainAxisRow ? childMainSize : childCrossSize;+ const float childHeight =+ !isMainAxisRow ? childMainSize : childCrossSize;++ auto alignContent = node->style().alignContent();+ auto crossAxisDoesNotGrow =+ alignContent != Align::Stretch && isNodeFlexWrap;+ const SizingMode childWidthSizingMode =+ yoga::isUndefined(childWidth) ||+ (!isMainAxisRow && crossAxisDoesNotGrow)+ ? SizingMode::MaxContent+ : SizingMode::StretchFit;+ const SizingMode childHeightSizingMode =+ yoga::isUndefined(childHeight) ||+ (isMainAxisRow && crossAxisDoesNotGrow)+ ? SizingMode::MaxContent+ : SizingMode::StretchFit;++ calculateLayoutInternal(+ child,+ childWidth,+ childHeight,+ direction,+ childWidthSizingMode,+ childHeightSizingMode,+ availableInnerWidth,+ availableInnerHeight,+ true,+ LayoutPassReason::kStretch,+ layoutMarkerData,+ depth,+ generationCount);+ }+ } else {+ const float remainingCrossDim = containerCrossAxis -+ child->dimensionWithMargin(crossAxis, availableInnerWidth);++ if (child->style().flexStartMarginIsAuto(crossAxis, direction) &&+ child->style().flexEndMarginIsAuto(crossAxis, direction)) {+ leadingCrossDim += yoga::maxOrDefined(0.0f, remainingCrossDim / 2);+ } else if (child->style().flexEndMarginIsAuto(crossAxis, direction)) {+ // No-Op+ } else if (child->style().flexStartMarginIsAuto(+ crossAxis, direction)) {+ leadingCrossDim += yoga::maxOrDefined(0.0f, remainingCrossDim);+ } else if (alignItem == Align::FlexStart) {+ // No-Op+ } else if (alignItem == Align::Center) {+ leadingCrossDim += remainingCrossDim / 2;+ } else {+ leadingCrossDim += remainingCrossDim;+ }+ }+ // And we apply the position+ child->setLayoutPosition(+ child->getLayout().position(flexStartEdge(crossAxis)) ++ totalLineCrossDim + leadingCrossDim,+ flexStartEdge(crossAxis));+ }+ }++ const float appliedCrossGap = lineCount != 0 ? crossAxisGap : 0.0f;+ totalLineCrossDim += flexLine.layout.crossDim + appliedCrossGap;+ maxLineMainDim =+ yoga::maxOrDefined(maxLineMainDim, flexLine.layout.mainDim);+ }++ // STEP 8: MULTI-LINE CONTENT ALIGNMENT+ // currentLead stores the size of the cross dim+ if (performLayout && (isNodeFlexWrap || isBaselineLayout(node))) {+ float leadPerLine = 0;+ float currentLead = leadingPaddingAndBorderCross;+ float extraSpacePerLine = 0;++ const float unclampedCrossDim = sizingModeCrossDim == SizingMode::StretchFit+ ? availableInnerCrossDim + paddingAndBorderAxisCross+ : node->hasDefiniteLength(dimension(crossAxis), crossAxisOwnerSize)+ ? node->getResolvedDimension(+ direction,+ dimension(crossAxis),+ crossAxisOwnerSize,+ ownerWidth)+ .unwrap()+ : totalLineCrossDim + paddingAndBorderAxisCross;++ const float innerCrossDim = boundAxis(+ node,+ crossAxis,+ direction,+ unclampedCrossDim,+ crossAxisOwnerSize,+ ownerWidth) -+ paddingAndBorderAxisCross;++ const float remainingAlignContentDim = innerCrossDim - totalLineCrossDim;++ const auto alignContent = remainingAlignContentDim >= 0+ ? node->style().alignContent()+ : fallbackAlignment(node->style().alignContent());++ switch (alignContent) {+ case Align::Start:+ case Align::End:+ // No-Op+ break;+ case Align::FlexEnd:+ currentLead += remainingAlignContentDim;+ break;+ case Align::Center:+ currentLead += remainingAlignContentDim / 2;+ break;+ case Align::Stretch:+ extraSpacePerLine =+ remainingAlignContentDim / static_cast<float>(lineCount);+ break;+ case Align::SpaceAround:+ currentLead +=+ remainingAlignContentDim / (2 * static_cast<float>(lineCount));+ leadPerLine = remainingAlignContentDim / static_cast<float>(lineCount);+ break;+ case Align::SpaceEvenly:+ currentLead +=+ remainingAlignContentDim / static_cast<float>(lineCount + 1);+ leadPerLine =+ remainingAlignContentDim / static_cast<float>(lineCount + 1);+ break;+ case Align::SpaceBetween:+ if (lineCount > 1) {+ leadPerLine =+ remainingAlignContentDim / static_cast<float>(lineCount - 1);+ }+ break;+ case Align::Auto:+ case Align::FlexStart:+ case Align::Baseline:+ break;+ }+ Node::LayoutableChildren::Iterator endIterator =+ node->getLayoutChildren().begin();+ for (size_t i = 0; i < lineCount; i++) {+ const Node::LayoutableChildren::Iterator startIterator = endIterator;+ auto iterator = startIterator;++ // compute the line's height and find the endIndex+ float lineHeight = 0;+ float maxAscentForCurrentLine = 0;+ float maxDescentForCurrentLine = 0;+ for (; iterator != node->getLayoutChildren().end(); iterator++) {+ const auto child = *iterator;+ if (child->style().display() == Display::None) {+ continue;+ }+ if (child->style().positionType() != PositionType::Absolute) {+ if (child->getLineIndex() != i) {+ break;+ }+ if (child->isLayoutDimensionDefined(crossAxis)) {+ lineHeight = yoga::maxOrDefined(+ lineHeight,+ child->getLayout().measuredDimension(dimension(crossAxis)) ++ child->style().computeMarginForAxis(+ crossAxis, availableInnerWidth));+ }+ if (resolveChildAlignment(node, child) == Align::Baseline) {+ const float ascent = calculateBaseline(child) ++ child->style().computeFlexStartMargin(+ FlexDirection::Column, direction, availableInnerWidth);+ const float descent =+ child->getLayout().measuredDimension(Dimension::Height) ++ child->style().computeMarginForAxis(+ FlexDirection::Column, availableInnerWidth) -+ ascent;+ maxAscentForCurrentLine =+ yoga::maxOrDefined(maxAscentForCurrentLine, ascent);+ maxDescentForCurrentLine =+ yoga::maxOrDefined(maxDescentForCurrentLine, descent);+ lineHeight = yoga::maxOrDefined(+ lineHeight, maxAscentForCurrentLine + maxDescentForCurrentLine);+ }+ }+ }+ endIterator = iterator;+ currentLead += i != 0 ? crossAxisGap : 0;+ lineHeight += extraSpacePerLine;++ for (iterator = startIterator; iterator != endIterator; iterator++) {+ const auto child = *iterator;+ if (child->style().display() == Display::None) {+ continue;+ }+ if (child->style().positionType() != PositionType::Absolute) {+ switch (resolveChildAlignment(node, child)) {+ case Align::Start:+ case Align::End:+ // Not yet implemented+ break;+ case Align::FlexStart: {+ child->setLayoutPosition(+ currentLead ++ child->style().computeFlexStartPosition(+ crossAxis, direction, availableInnerWidth),+ flexStartEdge(crossAxis));+ break;+ }+ case Align::FlexEnd: {+ child->setLayoutPosition(+ currentLead + lineHeight -+ child->style().computeFlexEndMargin(+ crossAxis, direction, availableInnerWidth) -+ child->getLayout().measuredDimension(+ dimension(crossAxis)),+ flexStartEdge(crossAxis));+ break;+ }+ case Align::Center: {+ float childHeight =+ child->getLayout().measuredDimension(dimension(crossAxis));++ child->setLayoutPosition(+ currentLead + (lineHeight - childHeight) / 2,+ flexStartEdge(crossAxis));+ break;+ }+ case Align::Stretch: {+ child->setLayoutPosition(+ currentLead ++ child->style().computeFlexStartMargin(+ crossAxis, direction, availableInnerWidth),+ flexStartEdge(crossAxis));++ // Remeasure child with the line height as it as been only+ // measured with the owners height yet.+ if (!child->hasDefiniteLength(+ dimension(crossAxis), availableInnerCrossDim)) {+ const float childWidth = isMainAxisRow+ ? (child->getLayout().measuredDimension(Dimension::Width) ++ child->style().computeMarginForAxis(+ mainAxis, availableInnerWidth))+ : leadPerLine + lineHeight;++ const float childHeight = !isMainAxisRow+ ? (child->getLayout().measuredDimension(Dimension::Height) ++ child->style().computeMarginForAxis(+ crossAxis, availableInnerWidth))+ : leadPerLine + lineHeight;++ if (!(yoga::inexactEquals(+ childWidth,+ child->getLayout().measuredDimension(+ Dimension::Width)) &&+ yoga::inexactEquals(+ childHeight,+ child->getLayout().measuredDimension(+ Dimension::Height)))) {+ calculateLayoutInternal(+ child,+ childWidth,+ childHeight,+ direction,+ SizingMode::StretchFit,+ SizingMode::StretchFit,+ availableInnerWidth,+ availableInnerHeight,+ true,+ LayoutPassReason::kMultilineStretch,+ layoutMarkerData,+ depth,+ generationCount);+ }+ }+ break;+ }+ case Align::Baseline: {+ child->setLayoutPosition(+ currentLead + maxAscentForCurrentLine -+ calculateBaseline(child) ++ child->style().computeFlexStartPosition(+ FlexDirection::Column,+ direction,+ availableInnerCrossDim),+ PhysicalEdge::Top);++ break;+ }+ case Align::Auto:+ case Align::SpaceBetween:+ case Align::SpaceAround:+ case Align::SpaceEvenly:+ break;+ }+ }+ }++ currentLead = currentLead + leadPerLine + lineHeight;+ }+ }++ // STEP 9: COMPUTING FINAL DIMENSIONS++ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ FlexDirection::Row,+ direction,+ availableWidth - marginAxisRow,+ ownerWidth,+ ownerWidth),+ Dimension::Width);++ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ FlexDirection::Column,+ direction,+ availableHeight - marginAxisColumn,+ ownerHeight,+ ownerWidth),+ Dimension::Height);++ // If the user didn't specify a width or height for the node, set the+ // dimensions based on the children.+ if (sizingModeMainDim == SizingMode::MaxContent ||+ (node->style().overflow() != Overflow::Scroll &&+ sizingModeMainDim == SizingMode::FitContent)) {+ // Clamp the size to the min/max size, if specified, and make sure it+ // doesn't go below the padding and border amount.+ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ mainAxis,+ direction,+ maxLineMainDim,+ mainAxisOwnerSize,+ ownerWidth),+ dimension(mainAxis));++ } else if (+ sizingModeMainDim == SizingMode::FitContent &&+ node->style().overflow() == Overflow::Scroll) {+ node->setLayoutMeasuredDimension(+ yoga::maxOrDefined(+ yoga::minOrDefined(+ availableInnerMainDim + paddingAndBorderAxisMain,+ boundAxisWithinMinAndMax(+ node,+ direction,+ mainAxis,+ FloatOptional{maxLineMainDim},+ mainAxisOwnerSize,+ ownerWidth)+ .unwrap()),+ paddingAndBorderAxisMain),+ dimension(mainAxis));+ }++ if (sizingModeCrossDim == SizingMode::MaxContent ||+ (node->style().overflow() != Overflow::Scroll &&+ sizingModeCrossDim == SizingMode::FitContent)) {+ // Clamp the size to the min/max size, if specified, and make sure it+ // doesn't go below the padding and border amount.+ node->setLayoutMeasuredDimension(+ boundAxis(+ node,+ crossAxis,+ direction,+ totalLineCrossDim + paddingAndBorderAxisCross,+ crossAxisOwnerSize,+ ownerWidth),+ dimension(crossAxis));++ } else if (+ sizingModeCrossDim == SizingMode::FitContent &&+ node->style().overflow() == Overflow::Scroll) {+ node->setLayoutMeasuredDimension(+ yoga::maxOrDefined(+ yoga::minOrDefined(+ availableInnerCrossDim + paddingAndBorderAxisCross,+ boundAxisWithinMinAndMax(+ node,+ direction,+ crossAxis,+ FloatOptional{+ totalLineCrossDim + paddingAndBorderAxisCross},+ crossAxisOwnerSize,+ ownerWidth)+ .unwrap()),+ paddingAndBorderAxisCross),+ dimension(crossAxis));+ }++ // As we only wrapped in normal direction yet, we need to reverse the+ // positions on wrap-reverse.+ if (performLayout && node->style().flexWrap() == Wrap::WrapReverse) {+ for (auto child : node->getLayoutChildren()) {+ if (child->style().positionType() != PositionType::Absolute) {+ child->setLayoutPosition(+ node->getLayout().measuredDimension(dimension(crossAxis)) -+ child->getLayout().position(flexStartEdge(crossAxis)) -+ child->getLayout().measuredDimension(dimension(crossAxis)),+ flexStartEdge(crossAxis));+ }+ }+ }++ if (performLayout) {+ // STEP 10: SETTING TRAILING POSITIONS FOR CHILDREN+ const bool needsMainTrailingPos = needsTrailingPosition(mainAxis);+ const bool needsCrossTrailingPos = needsTrailingPosition(crossAxis);++ if (needsMainTrailingPos || needsCrossTrailingPos) {+ for (auto child : node->getLayoutChildren()) {+ // Absolute children will be handled by their containing block since we+ // cannot guarantee that their positions are set when their parents are+ // done with layout.+ if (child->style().display() == Display::None ||+ child->style().positionType() == PositionType::Absolute) {+ continue;+ }+ if (needsMainTrailingPos) {+ setChildTrailingPosition(node, child, mainAxis);+ }++ if (needsCrossTrailingPos) {+ setChildTrailingPosition(node, child, crossAxis);+ }+ }+ }++ // STEP 11: SIZING AND POSITIONING ABSOLUTE CHILDREN+ // Let the containing block layout its absolute descendants.+ if (node->style().positionType() != PositionType::Static ||+ node->alwaysFormsContainingBlock() || depth == 1) {+ layoutAbsoluteDescendants(+ node,+ node,+ isMainAxisRow ? sizingModeMainDim : sizingModeCrossDim,+ direction,+ layoutMarkerData,+ depth,+ generationCount,+ 0.0f,+ 0.0f,+ availableInnerWidth,+ availableInnerHeight);+ }+ }+}++//+// This is a wrapper around the calculateLayoutImpl function. It determines+// whether the layout request is redundant and can be skipped.+//+// Parameters:+// Input parameters are the same as calculateLayoutImpl (see above)+// Return parameter is true if layout was performed, false if skipped+//+bool calculateLayoutInternal(+ yoga::Node* const node,+ const float availableWidth,+ const float availableHeight,+ const Direction ownerDirection,+ const SizingMode widthSizingMode,+ const SizingMode heightSizingMode,+ const float ownerWidth,+ const float ownerHeight,+ const bool performLayout,+ const LayoutPassReason reason,+ LayoutData& layoutMarkerData,+ uint32_t depth,+ const uint32_t generationCount) {+ LayoutResults* layout = &node->getLayout();++ depth++;++ const bool needToVisitNode =+ (node->isDirty() && layout->generationCount != generationCount) ||+ layout->configVersion != node->getConfig()->getVersion() ||+ layout->lastOwnerDirection != ownerDirection;++ if (needToVisitNode) {+ // Invalidate the cached results.+ layout->nextCachedMeasurementsIndex = 0;+ layout->cachedLayout.availableWidth = -1;+ layout->cachedLayout.availableHeight = -1;+ layout->cachedLayout.widthSizingMode = SizingMode::MaxContent;+ layout->cachedLayout.heightSizingMode = SizingMode::MaxContent;+ layout->cachedLayout.computedWidth = -1;+ layout->cachedLayout.computedHeight = -1;+ }++ CachedMeasurement* cachedResults = nullptr;++ // Determine whether the results are already cached. We maintain a separate+ // cache for layouts and measurements. A layout operation modifies the+ // positions and dimensions for nodes in the subtree. The algorithm assumes+ // that each node gets laid out a maximum of one time per tree layout, but+ // multiple measurements may be required to resolve all of the flex+ // dimensions. We handle nodes with measure functions specially here because+ // they are the most expensive to measure, so it's worth avoiding redundant+ // measurements if at all possible.+ if (node->hasMeasureFunc()) {+ const float marginAxisRow =+ node->style().computeMarginForAxis(FlexDirection::Row, ownerWidth);+ const float marginAxisColumn =+ node->style().computeMarginForAxis(FlexDirection::Column, ownerWidth);++ // First, try to use the layout cache.+ if (canUseCachedMeasurement(+ widthSizingMode,+ availableWidth,+ heightSizingMode,+ availableHeight,+ layout->cachedLayout.widthSizingMode,+ layout->cachedLayout.availableWidth,+ layout->cachedLayout.heightSizingMode,+ layout->cachedLayout.availableHeight,+ layout->cachedLayout.computedWidth,+ layout->cachedLayout.computedHeight,+ marginAxisRow,+ marginAxisColumn,+ node->getConfig())) {+ cachedResults = &layout->cachedLayout;+ } else {+ // Try to use the measurement cache.+ for (size_t i = 0; i < layout->nextCachedMeasurementsIndex; i++) {+ if (canUseCachedMeasurement(+ widthSizingMode,+ availableWidth,+ heightSizingMode,+ availableHeight,+ layout->cachedMeasurements[i].widthSizingMode,+ layout->cachedMeasurements[i].availableWidth,+ layout->cachedMeasurements[i].heightSizingMode,+ layout->cachedMeasurements[i].availableHeight,+ layout->cachedMeasurements[i].computedWidth,+ layout->cachedMeasurements[i].computedHeight,+ marginAxisRow,+ marginAxisColumn,+ node->getConfig())) {+ cachedResults = &layout->cachedMeasurements[i];+ break;+ }+ }+ }+ } else if (performLayout) {+ if (yoga::inexactEquals(+ layout->cachedLayout.availableWidth, availableWidth) &&+ yoga::inexactEquals(+ layout->cachedLayout.availableHeight, availableHeight) &&+ layout->cachedLayout.widthSizingMode == widthSizingMode &&+ layout->cachedLayout.heightSizingMode == heightSizingMode) {+ cachedResults = &layout->cachedLayout;+ }+ } else {+ for (uint32_t i = 0; i < layout->nextCachedMeasurementsIndex; i++) {+ if (yoga::inexactEquals(+ layout->cachedMeasurements[i].availableWidth, availableWidth) &&+ yoga::inexactEquals(+ layout->cachedMeasurements[i].availableHeight, availableHeight) &&+ layout->cachedMeasurements[i].widthSizingMode == widthSizingMode &&+ layout->cachedMeasurements[i].heightSizingMode == heightSizingMode) {+ cachedResults = &layout->cachedMeasurements[i];+ break;+ }+ }+ }++ if (!needToVisitNode && cachedResults != nullptr) {+ layout->setMeasuredDimension(+ Dimension::Width, cachedResults->computedWidth);+ layout->setMeasuredDimension(+ Dimension::Height, cachedResults->computedHeight);++ (performLayout ? layoutMarkerData.cachedLayouts+ : layoutMarkerData.cachedMeasures) += 1;+ } else {+ calculateLayoutImpl(+ node,+ availableWidth,+ availableHeight,+ ownerDirection,+ widthSizingMode,+ heightSizingMode,+ ownerWidth,+ ownerHeight,+ performLayout,+ reason,+ layoutMarkerData,+ depth,+ generationCount);++ layout->lastOwnerDirection = ownerDirection;+ layout->configVersion = node->getConfig()->getVersion();++ if (cachedResults == nullptr) {+ layoutMarkerData.maxMeasureCache = std::max(+ layoutMarkerData.maxMeasureCache,+ layout->nextCachedMeasurementsIndex + 1u);++ if (layout->nextCachedMeasurementsIndex ==+ LayoutResults::MaxCachedMeasurements) {+ layout->nextCachedMeasurementsIndex = 0;+ }++ CachedMeasurement* newCacheEntry = nullptr;+ if (performLayout) {+ // Use the single layout cache entry.+ newCacheEntry = &layout->cachedLayout;+ } else {+ // Allocate a new measurement cache entry.+ newCacheEntry =+ &layout->cachedMeasurements[layout->nextCachedMeasurementsIndex];+ layout->nextCachedMeasurementsIndex++;+ }++ newCacheEntry->availableWidth = availableWidth;+ newCacheEntry->availableHeight = availableHeight;+ newCacheEntry->widthSizingMode = widthSizingMode;+ newCacheEntry->heightSizingMode = heightSizingMode;+ newCacheEntry->computedWidth =+ layout->measuredDimension(Dimension::Width);+ newCacheEntry->computedHeight =+ layout->measuredDimension(Dimension::Height);+ }+ }++ if (performLayout) {+ node->setLayoutDimension(+ node->getLayout().measuredDimension(Dimension::Width),+ Dimension::Width);+ node->setLayoutDimension(+ node->getLayout().measuredDimension(Dimension::Height),+ Dimension::Height);++ node->setHasNewLayout(true);+ node->setDirty(false);+ }++ layout->generationCount = generationCount;++ LayoutType layoutType;+ if (performLayout) {+ layoutType = !needToVisitNode && cachedResults == &layout->cachedLayout+ ? LayoutType::kCachedLayout+ : LayoutType::kLayout;+ } else {+ layoutType = cachedResults != nullptr ? LayoutType::kCachedMeasure+ : LayoutType::kMeasure;+ }+ Event::publish<Event::NodeLayout>(node, {layoutType});++ return (needToVisitNode || cachedResults == nullptr);+}++void calculateLayout(+ yoga::Node* const node,+ const float ownerWidth,+ const float ownerHeight,+ const Direction ownerDirection) {+ Event::publish<Event::LayoutPassStart>(node);+ LayoutData markerData = {};++ // Increment the generation count. This will force the recursive routine to+ // visit all dirty nodes at least once. Subsequent visits will be skipped if+ // the input parameters don't change.+ gCurrentGenerationCount.fetch_add(1, std::memory_order_relaxed);+ node->processDimensions();+ const Direction direction = node->resolveDirection(ownerDirection);+ float width = YGUndefined;+ SizingMode widthSizingMode = SizingMode::MaxContent;+ const auto& style = node->style();+ if (node->hasDefiniteLength(Dimension::Width, ownerWidth)) {+ width =+ (node->getResolvedDimension(+ direction,+ dimension(FlexDirection::Row),+ ownerWidth,+ ownerWidth)+ .unwrap() ++ node->style().computeMarginForAxis(FlexDirection::Row, ownerWidth));+ widthSizingMode = SizingMode::StretchFit;+ } else if (style+ .resolvedMaxDimension(+ direction, Dimension::Width, ownerWidth, ownerWidth)+ .isDefined()) {+ width = style+ .resolvedMaxDimension(+ direction, Dimension::Width, ownerWidth, ownerWidth)+ .unwrap();+ widthSizingMode = SizingMode::FitContent;+ } else {+ width = ownerWidth;+ widthSizingMode = yoga::isUndefined(width) ? SizingMode::MaxContent+ : SizingMode::StretchFit;+ }++ float height = YGUndefined;+ SizingMode heightSizingMode = SizingMode::MaxContent;+ if (node->hasDefiniteLength(Dimension::Height, ownerHeight)) {+ height =+ (node->getResolvedDimension(+ direction,+ dimension(FlexDirection::Column),+ ownerHeight,+ ownerWidth)+ .unwrap() ++ node->style().computeMarginForAxis(FlexDirection::Column, ownerWidth));+ heightSizingMode = SizingMode::StretchFit;+ } else if (style+ .resolvedMaxDimension(+ direction, Dimension::Height, ownerHeight, ownerWidth)+ .isDefined()) {+ height = style+ .resolvedMaxDimension(+ direction, Dimension::Height, ownerHeight, ownerWidth)+ .unwrap();+ heightSizingMode = SizingMode::FitContent;+ } else {+ height = ownerHeight;+ heightSizingMode = yoga::isUndefined(height) ? SizingMode::MaxContent+ : SizingMode::StretchFit;+ }+ if (calculateLayoutInternal(+ node,+ width,+ height,+ ownerDirection,+ widthSizingMode,+ heightSizingMode,+ ownerWidth,+ ownerHeight,+ true,+ LayoutPassReason::kInitial,+ markerData,+ 0, // tree root+ gCurrentGenerationCount.load(std::memory_order_relaxed))) {+ node->setPosition(node->getLayout().direction(), ownerWidth, ownerHeight);+ roundLayoutResultsToPixelGrid(node, 0.0f, 0.0f);+ }++ Event::publish<Event::LayoutPassEnd>(node, {&markerData});+}++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/CalculateLayout.h b/third_party/yoga/algorithm/CalculateLayout.hnew file mode 100644index 000000000..2314bce0e--- /dev/null+++ b/third_party/yoga/algorithm/CalculateLayout.h@@ -0,0 +1,60 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/Yoga.h>+#include <yoga/algorithm/FlexDirection.h>+#include <yoga/event/event.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++void calculateLayout(+ yoga::Node* node,+ float ownerWidth,+ float ownerHeight,+ Direction ownerDirection);++bool calculateLayoutInternal(+ yoga::Node* node,+ float availableWidth,+ float availableHeight,+ Direction ownerDirection,+ SizingMode widthSizingMode,+ SizingMode heightSizingMode,+ float ownerWidth,+ float ownerHeight,+ bool performLayout,+ LayoutPassReason reason,+ LayoutData& layoutMarkerData,+ uint32_t depth,+ uint32_t generationCount);++void constrainMaxSizeForMode(+ const yoga::Node* node,+ Direction direction,+ FlexDirection axis,+ float ownerAxisSize,+ float ownerWidth,+ /*in_out*/ SizingMode* mode,+ /*in_out*/ float* size);++float calculateAvailableInnerDimension(+ const yoga::Node* const node,+ const Direction direction,+ const Dimension dimension,+ const float availableDim,+ float paddingAndBorder,+ const float ownerDim,+ const float ownerWidth);++void zeroOutLayoutRecursively(yoga::Node* const node);++void cleanupContentsNodesRecursively(yoga::Node* const node);++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/FlexDirection.h b/third_party/yoga/algorithm/FlexDirection.hnew file mode 100644index 000000000..e76d0d7fc--- /dev/null+++ b/third_party/yoga/algorithm/FlexDirection.h@@ -0,0 +1,120 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/Yoga.h>++#include <yoga/debug/AssertFatal.h>+#include <yoga/enums/Dimension.h>+#include <yoga/enums/Direction.h>+#include <yoga/enums/Edge.h>+#include <yoga/enums/FlexDirection.h>+#include <yoga/enums/PhysicalEdge.h>++namespace facebook::yoga {++inline bool isRow(const FlexDirection flexDirection) {+ return flexDirection == FlexDirection::Row ||+ flexDirection == FlexDirection::RowReverse;+}++inline bool isColumn(const FlexDirection flexDirection) {+ return flexDirection == FlexDirection::Column ||+ flexDirection == FlexDirection::ColumnReverse;+}++inline FlexDirection resolveDirection(+ const FlexDirection flexDirection,+ const Direction direction) {+ if (direction == Direction::RTL) {+ if (flexDirection == FlexDirection::Row) {+ return FlexDirection::RowReverse;+ } else if (flexDirection == FlexDirection::RowReverse) {+ return FlexDirection::Row;+ }+ }++ return flexDirection;+}++inline FlexDirection resolveCrossDirection(+ const FlexDirection flexDirection,+ const Direction direction) {+ return isColumn(flexDirection)+ ? resolveDirection(FlexDirection::Row, direction)+ : FlexDirection::Column;+}++inline PhysicalEdge flexStartEdge(FlexDirection flexDirection) {+ switch (flexDirection) {+ case FlexDirection::Column:+ return PhysicalEdge::Top;+ case FlexDirection::ColumnReverse:+ return PhysicalEdge::Bottom;+ case FlexDirection::Row:+ return PhysicalEdge::Left;+ case FlexDirection::RowReverse:+ return PhysicalEdge::Right;+ default:+ fatalWithMessage("Invalid FlexDirection");+ }+}++inline PhysicalEdge flexEndEdge(FlexDirection flexDirection) {+ switch (flexDirection) {+ case FlexDirection::Column:+ return PhysicalEdge::Bottom;+ case FlexDirection::ColumnReverse:+ return PhysicalEdge::Top;+ case FlexDirection::Row:+ return PhysicalEdge::Right;+ case FlexDirection::RowReverse:+ return PhysicalEdge::Left;+ default:+ fatalWithMessage("Invalid FlexDirection");+ }+}++inline PhysicalEdge inlineStartEdge(+ FlexDirection flexDirection,+ Direction direction) {+ if (isRow(flexDirection)) {+ return direction == Direction::RTL ? PhysicalEdge::Right+ : PhysicalEdge::Left;+ }++ return PhysicalEdge::Top;+}++inline PhysicalEdge inlineEndEdge(+ FlexDirection flexDirection,+ Direction direction) {+ if (isRow(flexDirection)) {+ return direction == Direction::RTL ? PhysicalEdge::Left+ : PhysicalEdge::Right;+ }++ return PhysicalEdge::Bottom;+}++inline Dimension dimension(FlexDirection flexDirection) {+ switch (flexDirection) {+ case FlexDirection::Column:+ return Dimension::Height;+ case FlexDirection::ColumnReverse:+ return Dimension::Height;+ case FlexDirection::Row:+ return Dimension::Width;+ case FlexDirection::RowReverse:+ return Dimension::Width;+ default:+ fatalWithMessage("Invalid FlexDirection");+ }+}++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/FlexLine.cpp b/third_party/yoga/algorithm/FlexLine.cppnew file mode 100644index 000000000..dc0a300ad--- /dev/null+++ b/third_party/yoga/algorithm/FlexLine.cpp@@ -0,0 +1,124 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/Yoga.h>++#include <yoga/algorithm/BoundAxis.h>+#include <yoga/algorithm/FlexDirection.h>+#include <yoga/algorithm/FlexLine.h>++namespace facebook::yoga {++FlexLine calculateFlexLine(+ yoga::Node* const node,+ const Direction ownerDirection,+ const float ownerWidth,+ const float mainAxisOwnerSize,+ const float availableInnerWidth,+ const float availableInnerMainDim,+ Node::LayoutableChildren::Iterator& iterator,+ const size_t lineCount) {+ std::vector<yoga::Node*> itemsInFlow;+ itemsInFlow.reserve(node->getChildCount());++ float sizeConsumed = 0.0f;+ float totalFlexGrowFactors = 0.0f;+ float totalFlexShrinkScaledFactors = 0.0f;+ size_t numberOfAutoMargins = 0;+ yoga::Node* firstElementInLine = nullptr;++ float sizeConsumedIncludingMinConstraint = 0;+ const Direction direction = node->resolveDirection(ownerDirection);+ const FlexDirection mainAxis =+ resolveDirection(node->style().flexDirection(), direction);+ const bool isNodeFlexWrap = node->style().flexWrap() != Wrap::NoWrap;+ const float gap =+ node->style().computeGapForAxis(mainAxis, availableInnerMainDim);++ const auto childrenEnd = node->getLayoutChildren().end();+ // Add items to the current line until it's full or we run out of items.+ for (; iterator != childrenEnd; iterator++) {+ auto child = *iterator;+ if (child->style().display() == Display::None ||+ child->style().positionType() == PositionType::Absolute) {+ continue;+ }++ if (firstElementInLine == nullptr) {+ firstElementInLine = child;+ }++ if (child->style().flexStartMarginIsAuto(mainAxis, ownerDirection)) {+ numberOfAutoMargins++;+ }+ if (child->style().flexEndMarginIsAuto(mainAxis, ownerDirection)) {+ numberOfAutoMargins++;+ }++ child->setLineIndex(lineCount);+ const float childMarginMainAxis =+ child->style().computeMarginForAxis(mainAxis, availableInnerWidth);+ const float childLeadingGapMainAxis =+ child == firstElementInLine ? 0.0f : gap;+ const float flexBasisWithMinAndMaxConstraints =+ boundAxisWithinMinAndMax(+ child,+ direction,+ mainAxis,+ child->getLayout().computedFlexBasis,+ mainAxisOwnerSize,+ ownerWidth)+ .unwrap();++ // If this is a multi-line flow and this item pushes us over the available+ // size, we've hit the end of the current line. Break out of the loop and+ // lay out the current line.+ if (sizeConsumedIncludingMinConstraint + flexBasisWithMinAndMaxConstraints ++ childMarginMainAxis + childLeadingGapMainAxis >+ availableInnerMainDim &&+ isNodeFlexWrap && !itemsInFlow.empty()) {+ break;+ }++ sizeConsumedIncludingMinConstraint += flexBasisWithMinAndMaxConstraints ++ childMarginMainAxis + childLeadingGapMainAxis;+ sizeConsumed += flexBasisWithMinAndMaxConstraints + childMarginMainAxis ++ childLeadingGapMainAxis;++ if (child->isNodeFlexible()) {+ totalFlexGrowFactors += child->resolveFlexGrow();++ // Unlike the grow factor, the shrink factor is scaled relative to the+ // child dimension.+ totalFlexShrinkScaledFactors += -child->resolveFlexShrink() *+ child->getLayout().computedFlexBasis.unwrap();+ }++ itemsInFlow.push_back(child);+ }++ // The total flex factor needs to be floored to 1.+ if (totalFlexGrowFactors > 0 && totalFlexGrowFactors < 1) {+ totalFlexGrowFactors = 1;+ }++ // The total flex shrink factor needs to be floored to 1.+ if (totalFlexShrinkScaledFactors > 0 && totalFlexShrinkScaledFactors < 1) {+ totalFlexShrinkScaledFactors = 1;+ }++ return FlexLine{+ .itemsInFlow = std::move(itemsInFlow),+ .sizeConsumed = sizeConsumed,+ .numberOfAutoMargins = numberOfAutoMargins,+ .layout = FlexLineRunningLayout{+ totalFlexGrowFactors,+ totalFlexShrinkScaledFactors,+ }};+}++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/FlexLine.h b/third_party/yoga/algorithm/FlexLine.hnew file mode 100644index 000000000..3f2ef2f17--- /dev/null+++ b/third_party/yoga/algorithm/FlexLine.h@@ -0,0 +1,75 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <vector>++#include <yoga/Yoga.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++struct FlexLineRunningLayout {+ // Total flex grow factors of flex items which are to be laid in the current+ // line. This is decremented as free space is distributed.+ float totalFlexGrowFactors{0.0f};++ // Total flex shrink factors of flex items which are to be laid in the current+ // line. This is decremented as free space is distributed.+ float totalFlexShrinkScaledFactors{0.0f};++ // The amount of available space within inner dimensions of the line which may+ // still be distributed.+ float remainingFreeSpace{0.0f};++ // The size of the mainDim for the row after considering size, padding, margin+ // and border of flex items. This is used to calculate maxLineDim after going+ // through all the rows to decide on the main axis size of owner.+ float mainDim{0.0f};++ // The size of the crossDim for the row after considering size, padding,+ // margin and border of flex items. Used for calculating containers crossSize.+ float crossDim{0.0f};+};++struct FlexLine {+ // List of children which are part of the line flow. This means they are not+ // positioned absolutely, or with `display: "none"`, and do not overflow the+ // available dimensions.+ const std::vector<yoga::Node*> itemsInFlow{};++ // Accumulation of the dimensions and margin of all the children on the+ // current line. This will be used in order to either set the dimensions of+ // the node if none already exist or to compute the remaining space left for+ // the flexible children.+ const float sizeConsumed{0.0f};++ // Number of edges along the line flow with an auto margin.+ const size_t numberOfAutoMargins{0};++ // Layout information about the line computed in steps after line-breaking+ FlexLineRunningLayout layout{};+};++// Calculates where a line starting at a given index should break, returning+// information about the collective children on the liune.+//+// This function assumes that all the children of node have their+// computedFlexBasis properly computed(To do this use+// computeFlexBasisForChildren function).+FlexLine calculateFlexLine(+ yoga::Node* node,+ Direction ownerDirection,+ float ownerWidth,+ float mainAxisOwnerSize,+ float availableInnerWidth,+ float availableInnerMainDim,+ Node::LayoutableChildren::Iterator& iterator,+ size_t lineCount);++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/PixelGrid.cpp b/third_party/yoga/algorithm/PixelGrid.cppnew file mode 100644index 000000000..61de2be2e--- /dev/null+++ b/third_party/yoga/algorithm/PixelGrid.cpp@@ -0,0 +1,135 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/Yoga.h>++#include <yoga/algorithm/PixelGrid.h>+#include <yoga/numeric/Comparison.h>++namespace facebook::yoga {++float roundValueToPixelGrid(+ const double value,+ const double pointScaleFactor,+ const bool forceCeil,+ const bool forceFloor) {+ double scaledValue = value * pointScaleFactor;+ // We want to calculate `fractial` such that `floor(scaledValue) = scaledValue+ // - fractial`.+ double fractial = fmod(scaledValue, 1.0);+ if (fractial < 0) {+ // This branch is for handling negative numbers for `value`.+ //+ // Regarding `floor` and `ceil`. Note that for a number x, `floor(x) <= x <=+ // ceil(x)` even for negative numbers. Here are a couple of examples:+ // - x = 2.2: floor( 2.2) = 2, ceil( 2.2) = 3+ // - x = -2.2: floor(-2.2) = -3, ceil(-2.2) = -2+ //+ // Regarding `fmodf`. For fractional negative numbers, `fmodf` returns a+ // negative number. For example, `fmodf(-2.2) = -0.2`. However, we want+ // `fractial` to be the number such that subtracting it from `value` will+ // give us `floor(value)`. In the case of negative numbers, adding 1 to+ // `fmodf(value)` gives us this. Let's continue the example from above:+ // - fractial = fmodf(-2.2) = -0.2+ // - Add 1 to the fraction: fractial2 = fractial + 1 = -0.2 + 1 = 0.8+ // - Finding the `floor`: -2.2 - fractial2 = -2.2 - 0.8 = -3+ ++fractial;+ }+ if (yoga::inexactEquals(fractial, 0)) {+ // First we check if the value is already rounded+ scaledValue = scaledValue - fractial;+ } else if (yoga::inexactEquals(fractial, 1.0)) {+ scaledValue = scaledValue - fractial + 1.0;+ } else if (forceCeil) {+ // Next we check if we need to use forced rounding+ scaledValue = scaledValue - fractial + 1.0;+ } else if (forceFloor) {+ scaledValue = scaledValue - fractial;+ } else {+ // Finally we just round the value+ scaledValue = scaledValue - fractial ++ (!std::isnan(fractial) &&+ (fractial > 0.5 || yoga::inexactEquals(fractial, 0.5))+ ? 1.0+ : 0.0);+ }+ return (std::isnan(scaledValue) || std::isnan(pointScaleFactor))+ ? YGUndefined+ : (float)(scaledValue / pointScaleFactor);+}++void roundLayoutResultsToPixelGrid(+ yoga::Node* const node,+ const double absoluteLeft,+ const double absoluteTop) {+ const auto pointScaleFactor =+ static_cast<double>(node->getConfig()->getPointScaleFactor());++ const double nodeLeft = node->getLayout().position(PhysicalEdge::Left);+ const double nodeTop = node->getLayout().position(PhysicalEdge::Top);++ const double nodeWidth = node->getLayout().dimension(Dimension::Width);+ const double nodeHeight = node->getLayout().dimension(Dimension::Height);++ const double absoluteNodeLeft = absoluteLeft + nodeLeft;+ const double absoluteNodeTop = absoluteTop + nodeTop;++ const double absoluteNodeRight = absoluteNodeLeft + nodeWidth;+ const double absoluteNodeBottom = absoluteNodeTop + nodeHeight;++ if (pointScaleFactor != 0.0) {+ // If a node has a custom measure function we never want to round down its+ // size as this could lead to unwanted text truncation.+ const bool textRounding = node->getNodeType() == NodeType::Text;++ node->setLayoutPosition(+ roundValueToPixelGrid(nodeLeft, pointScaleFactor, false, textRounding),+ PhysicalEdge::Left);++ node->setLayoutPosition(+ roundValueToPixelGrid(nodeTop, pointScaleFactor, false, textRounding),+ PhysicalEdge::Top);++ // We multiply dimension by scale factor and if the result is close to the+ // whole number, we don't have any fraction To verify if the result is close+ // to whole number we want to check both floor and ceil numbers++ const double scaledNodeWith = nodeWidth * pointScaleFactor;+ const bool hasFractionalWidth =+ !yoga::inexactEquals(round(scaledNodeWith), scaledNodeWith);++ const double scaledNodeHeight = nodeHeight * pointScaleFactor;+ const bool hasFractionalHeight =+ !yoga::inexactEquals(round(scaledNodeHeight), scaledNodeHeight);++ node->getLayout().setDimension(+ Dimension::Width,+ roundValueToPixelGrid(+ absoluteNodeRight,+ pointScaleFactor,+ (textRounding && hasFractionalWidth),+ (textRounding && !hasFractionalWidth)) -+ roundValueToPixelGrid(+ absoluteNodeLeft, pointScaleFactor, false, textRounding));++ node->getLayout().setDimension(+ Dimension::Height,+ roundValueToPixelGrid(+ absoluteNodeBottom,+ pointScaleFactor,+ (textRounding && hasFractionalHeight),+ (textRounding && !hasFractionalHeight)) -+ roundValueToPixelGrid(+ absoluteNodeTop, pointScaleFactor, false, textRounding));+ }++ for (yoga::Node* child : node->getChildren()) {+ roundLayoutResultsToPixelGrid(child, absoluteNodeLeft, absoluteNodeTop);+ }+}++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/PixelGrid.h b/third_party/yoga/algorithm/PixelGrid.hnew file mode 100644index 000000000..f3bf79f98--- /dev/null+++ b/third_party/yoga/algorithm/PixelGrid.h@@ -0,0 +1,29 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/Yoga.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++// Round a point value to the nearest physical pixel based on DPI+// (pointScaleFactor)+float roundValueToPixelGrid(+ double value,+ double pointScaleFactor,+ bool forceCeil,+ bool forceFloor);++// Round the layout results of a node and its subtree to the pixel grid.+void roundLayoutResultsToPixelGrid(+ yoga::Node* node,+ double absoluteLeft,+ double absoluteTop);++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/SizingMode.h b/third_party/yoga/algorithm/SizingMode.hnew file mode 100644index 000000000..2b3087440--- /dev/null+++ b/third_party/yoga/algorithm/SizingMode.h@@ -0,0 +1,73 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/debug/AssertFatal.h>+#include <yoga/enums/MeasureMode.h>++namespace facebook::yoga {++/**+ * Corresponds to a CSS auto box sizes. Missing "min-content", as Yoga does not+ * current support automatic minimum sizes.+ * https://www.w3.org/TR/css-sizing-3/#auto-box-sizes+ * https://www.w3.org/TR/css-flexbox-1/#min-size-auto+ */+enum class SizingMode {+ /**+ * The size a box would take if its outer size filled the available space in+ * the given axis; in other words, the stretch fit into the available space,+ * if that is definite. Undefined if the available space is indefinite.+ */+ StretchFit,++ /**+ * A box’s “ideal” size in a given axis when given infinite available space.+ * Usually this is the smallest size the box could take in that axis while+ * still fitting around its contents, i.e. minimizing unfilled space while+ * avoiding overflow.+ */+ MaxContent,++ /**+ * If the available space in a given axis is definite, equal to+ * clamp(min-content size, stretch-fit size, max-content size) (i.e.+ * max(min-content size, min(max-content size, stretch-fit size))). When+ * sizing under a min-content constraint, equal to the min-content size.+ * Otherwise, equal to the max-content size in that axis.+ */+ FitContent,+};++inline MeasureMode measureMode(SizingMode mode) {+ switch (mode) {+ case SizingMode::StretchFit:+ return MeasureMode::Exactly;+ case SizingMode::MaxContent:+ return MeasureMode::Undefined;+ case SizingMode::FitContent:+ return MeasureMode::AtMost;+ default:+ fatalWithMessage("Invalid SizingMode");+ }+}++inline SizingMode sizingMode(MeasureMode mode) {+ switch (mode) {+ case MeasureMode::Exactly:+ return SizingMode::StretchFit;+ case MeasureMode::Undefined:+ return SizingMode::MaxContent;+ case MeasureMode::AtMost:+ return SizingMode::FitContent;+ default:+ fatalWithMessage("Invalid MeasureMode");+ }+}++} // namespace facebook::yogadiff --git a/third_party/yoga/algorithm/TrailingPosition.h b/third_party/yoga/algorithm/TrailingPosition.hnew file mode 100644index 000000000..84d00edbe--- /dev/null+++ b/third_party/yoga/algorithm/TrailingPosition.h@@ -0,0 +1,44 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/Yoga.h>+#include <yoga/algorithm/FlexDirection.h>+#include <yoga/event/event.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++// Given an offset to an edge, returns the offset to the opposite edge on the+// same axis. This assumes that the width/height of both nodes is determined at+// this point.+inline float getPositionOfOppositeEdge(+ float position,+ FlexDirection axis,+ const yoga::Node* const containingNode,+ const yoga::Node* const node) {+ return containingNode->getLayout().measuredDimension(dimension(axis)) -+ node->getLayout().measuredDimension(dimension(axis)) - position;+}++inline void setChildTrailingPosition(+ const yoga::Node* const node,+ yoga::Node* const child,+ const FlexDirection axis) {+ child->setLayoutPosition(+ getPositionOfOppositeEdge(+ child->getLayout().position(flexStartEdge(axis)), axis, node, child),+ flexEndEdge(axis));+}++inline bool needsTrailingPosition(const FlexDirection axis) {+ return axis == FlexDirection::RowReverse ||+ axis == FlexDirection::ColumnReverse;+}++} // namespace facebook::yogadiff --git a/third_party/yoga/config/Config.cpp b/third_party/yoga/config/Config.cppnew file mode 100644index 000000000..0f5fb019c--- /dev/null+++ b/third_party/yoga/config/Config.cpp@@ -0,0 +1,135 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/config/Config.h>+#include <yoga/debug/Log.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++bool configUpdateInvalidatesLayout(+ const Config& oldConfig,+ const Config& newConfig) {+ return oldConfig.getErrata() != newConfig.getErrata() ||+ oldConfig.getEnabledExperiments() != newConfig.getEnabledExperiments() ||+ oldConfig.getPointScaleFactor() != newConfig.getPointScaleFactor() ||+ oldConfig.useWebDefaults() != newConfig.useWebDefaults();+}++void Config::setUseWebDefaults(bool useWebDefaults) {+ useWebDefaults_ = useWebDefaults;+}++bool Config::useWebDefaults() const {+ return useWebDefaults_;+}++void Config::setExperimentalFeatureEnabled(+ ExperimentalFeature feature,+ bool enabled) {+ if (isExperimentalFeatureEnabled(feature) != enabled) {+ experimentalFeatures_.set(static_cast<size_t>(feature), enabled);+ version_++;+ }+}++bool Config::isExperimentalFeatureEnabled(ExperimentalFeature feature) const {+ return experimentalFeatures_.test(static_cast<size_t>(feature));+}++ExperimentalFeatureSet Config::getEnabledExperiments() const {+ return experimentalFeatures_;+}++void Config::setErrata(Errata errata) {+ if (errata_ != errata) {+ errata_ = errata;+ version_++;+ }+}++void Config::addErrata(Errata errata) {+ if (!hasErrata(errata)) {+ errata_ |= errata;+ version_++;+ }+}++void Config::removeErrata(Errata errata) {+ if (hasErrata(errata)) {+ errata_ &= (~errata);+ version_++;+ }+}++Errata Config::getErrata() const {+ return errata_;+}++bool Config::hasErrata(Errata errata) const {+ return (errata_ & errata) != Errata::None;+}++void Config::setPointScaleFactor(float pointScaleFactor) {+ if (pointScaleFactor_ != pointScaleFactor) {+ pointScaleFactor_ = pointScaleFactor;+ version_++;+ }+}++float Config::getPointScaleFactor() const {+ return pointScaleFactor_;+}++void Config::setContext(void* context) {+ context_ = context;+}++void* Config::getContext() const {+ return context_;+}++uint32_t Config::getVersion() const noexcept {+ return version_;+}++void Config::setLogger(YGLogger logger) {+ logger_ = logger;+}++void Config::log(+ const yoga::Node* node,+ LogLevel logLevel,+ const char* format,+ va_list args) const {+ logger_(this, node, unscopedEnum(logLevel), format, args);+}++void Config::setCloneNodeCallback(YGCloneNodeFunc cloneNode) {+ cloneNodeCallback_ = cloneNode;+}++YGNodeRef Config::cloneNode(+ YGNodeConstRef node,+ YGNodeConstRef owner,+ size_t childIndex) const {+ YGNodeRef clone = nullptr;+ if (cloneNodeCallback_ != nullptr) {+ clone = cloneNodeCallback_(node, owner, childIndex);+ }+ if (clone == nullptr) {+ clone = YGNodeClone(node);+ }+ return clone;+}++/*static*/ const Config& Config::getDefault() {+ static Config config{getDefaultLogger()};+ return config;+}++} // namespace facebook::yogadiff --git a/third_party/yoga/config/Config.h b/third_party/yoga/config/Config.hnew file mode 100644index 000000000..7bcffd148--- /dev/null+++ b/third_party/yoga/config/Config.h@@ -0,0 +1,92 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <bitset>++#include <yoga/Yoga.h>+#include <yoga/enums/Errata.h>+#include <yoga/enums/ExperimentalFeature.h>+#include <yoga/enums/LogLevel.h>++// Tag struct used to form the opaque YGConfigRef for the public C API+struct YGConfig {};++namespace facebook::yoga {++class Config;+class Node;++using ExperimentalFeatureSet = std::bitset<ordinalCount<ExperimentalFeature>()>;++// Whether moving a node from an old to new config should dirty previously+// calculated layout results.+bool configUpdateInvalidatesLayout(+ const Config& oldConfig,+ const Config& newConfig);++class YG_EXPORT Config : public ::YGConfig {+ public:+ explicit Config(YGLogger logger) : logger_{logger} {}++ void setUseWebDefaults(bool useWebDefaults);+ bool useWebDefaults() const;++ void setExperimentalFeatureEnabled(ExperimentalFeature feature, bool enabled);+ bool isExperimentalFeatureEnabled(ExperimentalFeature feature) const;+ ExperimentalFeatureSet getEnabledExperiments() const;++ void setErrata(Errata errata);+ void addErrata(Errata errata);+ void removeErrata(Errata errata);+ Errata getErrata() const;+ bool hasErrata(Errata errata) const;++ void setPointScaleFactor(float pointScaleFactor);+ float getPointScaleFactor() const;++ void setContext(void* context);+ void* getContext() const;++ uint32_t getVersion() const noexcept;++ void setLogger(YGLogger logger);+ void log(+ const yoga::Node* node,+ LogLevel logLevel,+ const char* format,+ va_list args) const;++ void setCloneNodeCallback(YGCloneNodeFunc cloneNode);+ YGNodeRef+ cloneNode(YGNodeConstRef node, YGNodeConstRef owner, size_t childIndex) const;++ static const Config& getDefault();++ private:+ YGCloneNodeFunc cloneNodeCallback_{nullptr};+ YGLogger logger_{};++ bool useWebDefaults_ : 1 = false;++ uint32_t version_ = 0;+ ExperimentalFeatureSet experimentalFeatures_{};+ Errata errata_ = Errata::None;+ float pointScaleFactor_ = 1.0f;+ void* context_ = nullptr;+};++inline Config* resolveRef(const YGConfigRef ref) {+ return static_cast<Config*>(ref);+}++inline const Config* resolveRef(const YGConfigConstRef ref) {+ return static_cast<const Config*>(ref);+}++} // namespace facebook::yogadiff --git a/third_party/yoga/debug/AssertFatal.cpp b/third_party/yoga/debug/AssertFatal.cppnew file mode 100644index 000000000..e36af650f--- /dev/null+++ b/third_party/yoga/debug/AssertFatal.cpp@@ -0,0 +1,54 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <exception>+#include <stdexcept>++#include <yoga/config/Config.h>+#include <yoga/debug/AssertFatal.h>+#include <yoga/debug/Log.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++[[noreturn]] void fatalWithMessage(const char* message) {+#if defined(__cpp_exceptions)+ throw std::logic_error(message);+#else+ static_cast<void>(message); // Unused+ std::terminate();+#endif+}++void assertFatal(const bool condition, const char* message) {+ if (!condition) {+ yoga::log(LogLevel::Fatal, "%s\n", message);+ fatalWithMessage(message);+ }+}++void assertFatalWithNode(+ const yoga::Node* const node,+ const bool condition,+ const char* message) {+ if (!condition) {+ yoga::log(node, LogLevel::Fatal, "%s\n", message);+ fatalWithMessage(message);+ }+}++void assertFatalWithConfig(+ const yoga::Config* const config,+ const bool condition,+ const char* message) {+ if (!condition) {+ yoga::log(config, LogLevel::Fatal, "%s\n", message);+ fatalWithMessage(message);+ }+}++} // namespace facebook::yogadiff --git a/third_party/yoga/debug/AssertFatal.h b/third_party/yoga/debug/AssertFatal.hnew file mode 100644index 000000000..bbd8ad19e--- /dev/null+++ b/third_party/yoga/debug/AssertFatal.h@@ -0,0 +1,29 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/Yoga.h>++namespace facebook::yoga {++class Node;+class Config;++[[noreturn]] void fatalWithMessage(const char* message);++void assertFatal(bool condition, const char* message);+void assertFatalWithNode(+ const yoga::Node* node,+ bool condition,+ const char* message);+void assertFatalWithConfig(+ const yoga::Config* config,+ bool condition,+ const char* message);++} // namespace facebook::yogadiff --git a/third_party/yoga/debug/Log.cpp b/third_party/yoga/debug/Log.cppnew file mode 100644index 000000000..9b525d8a8--- /dev/null+++ b/third_party/yoga/debug/Log.cpp@@ -0,0 +1,107 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <yoga/debug/Log.h>++#ifdef ANDROID+#include <android/log.h>+#endif++namespace facebook::yoga {++namespace {++void vlog(+ const yoga::Config* config,+ const yoga::Node* node,+ LogLevel level,+ const char* format,+ va_list args) {+ if (config == nullptr) {+ getDefaultLogger()(nullptr, node, unscopedEnum(level), format, args);+ } else {+ config->log(node, level, format, args);+ }+}+} // namespace++void log(LogLevel level, const char* format, ...) noexcept {+ va_list args;+ va_start(args, format);+ vlog(nullptr, nullptr, level, format, args);+ va_end(args);+}++void log(+ const yoga::Node* node,+ LogLevel level,+ const char* format,+ ...) noexcept {+ va_list args;+ va_start(args, format);+ vlog(+ node == nullptr ? nullptr : node->getConfig(), node, level, format, args);+ va_end(args);+}++void log(+ const yoga::Config* config,+ LogLevel level,+ const char* format,+ ...) noexcept {+ va_list args;+ va_start(args, format);+ vlog(config, nullptr, level, format, args);+ va_end(args);+}++YGLogger getDefaultLogger() {+ return [](const YGConfigConstRef /*config*/,+ const YGNodeConstRef /*node*/,+ YGLogLevel level,+ const char* format,+ va_list args) -> int {+#ifdef ANDROID+ int androidLevel = YGLogLevelDebug;+ switch (level) {+ case YGLogLevelFatal:+ androidLevel = ANDROID_LOG_FATAL;+ break;+ case YGLogLevelError:+ androidLevel = ANDROID_LOG_ERROR;+ break;+ case YGLogLevelWarn:+ androidLevel = ANDROID_LOG_WARN;+ break;+ case YGLogLevelInfo:+ androidLevel = ANDROID_LOG_INFO;+ break;+ case YGLogLevelDebug:+ androidLevel = ANDROID_LOG_DEBUG;+ break;+ case YGLogLevelVerbose:+ androidLevel = ANDROID_LOG_VERBOSE;+ break;+ }+ return __android_log_vprint(androidLevel, "yoga", format, args);+#else+ switch (level) {+ case YGLogLevelError:+ case YGLogLevelFatal:+ return vfprintf(stderr, format, args);+ case YGLogLevelWarn:+ case YGLogLevelInfo:+ case YGLogLevelDebug:+ case YGLogLevelVerbose:+ default:+ return vprintf(format, args);+ }+#endif+ };+}++} // namespace facebook::yogadiff --git a/third_party/yoga/debug/Log.h b/third_party/yoga/debug/Log.hnew file mode 100644index 000000000..0a932d80e--- /dev/null+++ b/third_party/yoga/debug/Log.h@@ -0,0 +1,34 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/Yoga.h>++#include <yoga/config/Config.h>+#include <yoga/enums/LogLevel.h>+#include <yoga/node/Node.h>++namespace facebook::yoga {++void log(LogLevel level, const char* format, ...) noexcept;++void log(+ const yoga::Node* node,+ LogLevel level,+ const char* format,+ ...) noexcept;++void log(+ const yoga::Config* config,+ LogLevel level,+ const char* format,+ ...) noexcept;++YGLogger getDefaultLogger();++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Align.h b/third_party/yoga/enums/Align.hnew file mode 100644index 000000000..e1b8b29bd--- /dev/null+++ b/third_party/yoga/enums/Align.h@@ -0,0 +1,49 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Align : uint8_t {+ Auto = YGAlignAuto,+ FlexStart = YGAlignFlexStart,+ Center = YGAlignCenter,+ FlexEnd = YGAlignFlexEnd,+ Stretch = YGAlignStretch,+ Baseline = YGAlignBaseline,+ SpaceBetween = YGAlignSpaceBetween,+ SpaceAround = YGAlignSpaceAround,+ SpaceEvenly = YGAlignSpaceEvenly,+ Start = YGAlignStart,+ End = YGAlignEnd,+};++template <>+constexpr int32_t ordinalCount<Align>() {+ return 11;+}++constexpr Align scopedEnum(YGAlign unscoped) {+ return static_cast<Align>(unscoped);+}++constexpr YGAlign unscopedEnum(Align scoped) {+ return static_cast<YGAlign>(scoped);+}++inline const char* toString(Align e) {+ return YGAlignToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/BoxSizing.h b/third_party/yoga/enums/BoxSizing.hnew file mode 100644index 000000000..eb18b99a0--- /dev/null+++ b/third_party/yoga/enums/BoxSizing.h@@ -0,0 +1,40 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class BoxSizing : uint8_t {+ BorderBox = YGBoxSizingBorderBox,+ ContentBox = YGBoxSizingContentBox,+};++template <>+constexpr int32_t ordinalCount<BoxSizing>() {+ return 2;+}++constexpr BoxSizing scopedEnum(YGBoxSizing unscoped) {+ return static_cast<BoxSizing>(unscoped);+}++constexpr YGBoxSizing unscopedEnum(BoxSizing scoped) {+ return static_cast<YGBoxSizing>(scoped);+}++inline const char* toString(BoxSizing e) {+ return YGBoxSizingToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Dimension.h b/third_party/yoga/enums/Dimension.hnew file mode 100644index 000000000..965901525--- /dev/null+++ b/third_party/yoga/enums/Dimension.h@@ -0,0 +1,40 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Dimension : uint8_t {+ Width = YGDimensionWidth,+ Height = YGDimensionHeight,+};++template <>+constexpr int32_t ordinalCount<Dimension>() {+ return 2;+}++constexpr Dimension scopedEnum(YGDimension unscoped) {+ return static_cast<Dimension>(unscoped);+}++constexpr YGDimension unscopedEnum(Dimension scoped) {+ return static_cast<YGDimension>(scoped);+}++inline const char* toString(Dimension e) {+ return YGDimensionToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Direction.h b/third_party/yoga/enums/Direction.hnew file mode 100644index 000000000..5bbabaecd--- /dev/null+++ b/third_party/yoga/enums/Direction.h@@ -0,0 +1,41 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Direction : uint8_t {+ Inherit = YGDirectionInherit,+ LTR = YGDirectionLTR,+ RTL = YGDirectionRTL,+};++template <>+constexpr int32_t ordinalCount<Direction>() {+ return 3;+}++constexpr Direction scopedEnum(YGDirection unscoped) {+ return static_cast<Direction>(unscoped);+}++constexpr YGDirection unscopedEnum(Direction scoped) {+ return static_cast<YGDirection>(scoped);+}++inline const char* toString(Direction e) {+ return YGDirectionToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Display.h b/third_party/yoga/enums/Display.hnew file mode 100644index 000000000..9edbee80b--- /dev/null+++ b/third_party/yoga/enums/Display.h@@ -0,0 +1,42 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Display : uint8_t {+ Flex = YGDisplayFlex,+ None = YGDisplayNone,+ Contents = YGDisplayContents,+ Grid = YGDisplayGrid,+};++template <>+constexpr int32_t ordinalCount<Display>() {+ return 4;+}++constexpr Display scopedEnum(YGDisplay unscoped) {+ return static_cast<Display>(unscoped);+}++constexpr YGDisplay unscopedEnum(Display scoped) {+ return static_cast<YGDisplay>(scoped);+}++inline const char* toString(Display e) {+ return YGDisplayToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Edge.h b/third_party/yoga/enums/Edge.hnew file mode 100644index 000000000..3ab6a33fa--- /dev/null+++ b/third_party/yoga/enums/Edge.h@@ -0,0 +1,47 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Edge : uint8_t {+ Left = YGEdgeLeft,+ Top = YGEdgeTop,+ Right = YGEdgeRight,+ Bottom = YGEdgeBottom,+ Start = YGEdgeStart,+ End = YGEdgeEnd,+ Horizontal = YGEdgeHorizontal,+ Vertical = YGEdgeVertical,+ All = YGEdgeAll,+};++template <>+constexpr int32_t ordinalCount<Edge>() {+ return 9;+}++constexpr Edge scopedEnum(YGEdge unscoped) {+ return static_cast<Edge>(unscoped);+}++constexpr YGEdge unscopedEnum(Edge scoped) {+ return static_cast<YGEdge>(scoped);+}++inline const char* toString(Edge e) {+ return YGEdgeToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Errata.h b/third_party/yoga/enums/Errata.hnew file mode 100644index 000000000..2f47a9417--- /dev/null+++ b/third_party/yoga/enums/Errata.h@@ -0,0 +1,41 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Errata : uint32_t {+ None = YGErrataNone,+ StretchFlexBasis = YGErrataStretchFlexBasis,+ AbsolutePositionWithoutInsetsExcludesPadding = YGErrataAbsolutePositionWithoutInsetsExcludesPadding,+ AbsolutePercentAgainstInnerSize = YGErrataAbsolutePercentAgainstInnerSize,+ All = YGErrataAll,+ Classic = YGErrataClassic,+};++YG_DEFINE_ENUM_FLAG_OPERATORS(Errata)++constexpr Errata scopedEnum(YGErrata unscoped) {+ return static_cast<Errata>(unscoped);+}++constexpr YGErrata unscopedEnum(Errata scoped) {+ return static_cast<YGErrata>(scoped);+}++inline const char* toString(Errata e) {+ return YGErrataToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/ExperimentalFeature.h b/third_party/yoga/enums/ExperimentalFeature.hnew file mode 100644index 000000000..bbbf9cda4--- /dev/null+++ b/third_party/yoga/enums/ExperimentalFeature.h@@ -0,0 +1,39 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class ExperimentalFeature : uint8_t {+ WebFlexBasis = YGExperimentalFeatureWebFlexBasis,+};++template <>+constexpr int32_t ordinalCount<ExperimentalFeature>() {+ return 1;+}++constexpr ExperimentalFeature scopedEnum(YGExperimentalFeature unscoped) {+ return static_cast<ExperimentalFeature>(unscoped);+}++constexpr YGExperimentalFeature unscopedEnum(ExperimentalFeature scoped) {+ return static_cast<YGExperimentalFeature>(scoped);+}++inline const char* toString(ExperimentalFeature e) {+ return YGExperimentalFeatureToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/FlexDirection.h b/third_party/yoga/enums/FlexDirection.hnew file mode 100644index 000000000..d2d3f6105--- /dev/null+++ b/third_party/yoga/enums/FlexDirection.h@@ -0,0 +1,42 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class FlexDirection : uint8_t {+ Column = YGFlexDirectionColumn,+ ColumnReverse = YGFlexDirectionColumnReverse,+ Row = YGFlexDirectionRow,+ RowReverse = YGFlexDirectionRowReverse,+};++template <>+constexpr int32_t ordinalCount<FlexDirection>() {+ return 4;+}++constexpr FlexDirection scopedEnum(YGFlexDirection unscoped) {+ return static_cast<FlexDirection>(unscoped);+}++constexpr YGFlexDirection unscopedEnum(FlexDirection scoped) {+ return static_cast<YGFlexDirection>(scoped);+}++inline const char* toString(FlexDirection e) {+ return YGFlexDirectionToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/GridTrackType.h b/third_party/yoga/enums/GridTrackType.hnew file mode 100644index 000000000..eb6e8332b--- /dev/null+++ b/third_party/yoga/enums/GridTrackType.h@@ -0,0 +1,43 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class GridTrackType : uint8_t {+ Auto = YGGridTrackTypeAuto,+ Points = YGGridTrackTypePoints,+ Percent = YGGridTrackTypePercent,+ Fr = YGGridTrackTypeFr,+ Minmax = YGGridTrackTypeMinmax,+};++template <>+constexpr int32_t ordinalCount<GridTrackType>() {+ return 5;+}++constexpr GridTrackType scopedEnum(YGGridTrackType unscoped) {+ return static_cast<GridTrackType>(unscoped);+}++constexpr YGGridTrackType unscopedEnum(GridTrackType scoped) {+ return static_cast<YGGridTrackType>(scoped);+}++inline const char* toString(GridTrackType e) {+ return YGGridTrackTypeToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Gutter.h b/third_party/yoga/enums/Gutter.hnew file mode 100644index 000000000..f16bbbcdf--- /dev/null+++ b/third_party/yoga/enums/Gutter.h@@ -0,0 +1,41 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Gutter : uint8_t {+ Column = YGGutterColumn,+ Row = YGGutterRow,+ All = YGGutterAll,+};++template <>+constexpr int32_t ordinalCount<Gutter>() {+ return 3;+}++constexpr Gutter scopedEnum(YGGutter unscoped) {+ return static_cast<Gutter>(unscoped);+}++constexpr YGGutter unscopedEnum(Gutter scoped) {+ return static_cast<YGGutter>(scoped);+}++inline const char* toString(Gutter e) {+ return YGGutterToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Justify.h b/third_party/yoga/enums/Justify.hnew file mode 100644index 000000000..db4afece9--- /dev/null+++ b/third_party/yoga/enums/Justify.h@@ -0,0 +1,48 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Justify : uint8_t {+ Auto = YGJustifyAuto,+ FlexStart = YGJustifyFlexStart,+ Center = YGJustifyCenter,+ FlexEnd = YGJustifyFlexEnd,+ SpaceBetween = YGJustifySpaceBetween,+ SpaceAround = YGJustifySpaceAround,+ SpaceEvenly = YGJustifySpaceEvenly,+ Stretch = YGJustifyStretch,+ Start = YGJustifyStart,+ End = YGJustifyEnd,+};++template <>+constexpr int32_t ordinalCount<Justify>() {+ return 10;+}++constexpr Justify scopedEnum(YGJustify unscoped) {+ return static_cast<Justify>(unscoped);+}++constexpr YGJustify unscopedEnum(Justify scoped) {+ return static_cast<YGJustify>(scoped);+}++inline const char* toString(Justify e) {+ return YGJustifyToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/LogLevel.h b/third_party/yoga/enums/LogLevel.hnew file mode 100644index 000000000..d4b2c3601--- /dev/null+++ b/third_party/yoga/enums/LogLevel.h@@ -0,0 +1,44 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class LogLevel : uint8_t {+ Error = YGLogLevelError,+ Warn = YGLogLevelWarn,+ Info = YGLogLevelInfo,+ Debug = YGLogLevelDebug,+ Verbose = YGLogLevelVerbose,+ Fatal = YGLogLevelFatal,+};++template <>+constexpr int32_t ordinalCount<LogLevel>() {+ return 6;+}++constexpr LogLevel scopedEnum(YGLogLevel unscoped) {+ return static_cast<LogLevel>(unscoped);+}++constexpr YGLogLevel unscopedEnum(LogLevel scoped) {+ return static_cast<YGLogLevel>(scoped);+}++inline const char* toString(LogLevel e) {+ return YGLogLevelToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/MeasureMode.h b/third_party/yoga/enums/MeasureMode.hnew file mode 100644index 000000000..39e2102ff--- /dev/null+++ b/third_party/yoga/enums/MeasureMode.h@@ -0,0 +1,41 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class MeasureMode : uint8_t {+ Undefined = YGMeasureModeUndefined,+ Exactly = YGMeasureModeExactly,+ AtMost = YGMeasureModeAtMost,+};++template <>+constexpr int32_t ordinalCount<MeasureMode>() {+ return 3;+}++constexpr MeasureMode scopedEnum(YGMeasureMode unscoped) {+ return static_cast<MeasureMode>(unscoped);+}++constexpr YGMeasureMode unscopedEnum(MeasureMode scoped) {+ return static_cast<YGMeasureMode>(scoped);+}++inline const char* toString(MeasureMode e) {+ return YGMeasureModeToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/NodeType.h b/third_party/yoga/enums/NodeType.hnew file mode 100644index 000000000..dc881be83--- /dev/null+++ b/third_party/yoga/enums/NodeType.h@@ -0,0 +1,40 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class NodeType : uint8_t {+ Default = YGNodeTypeDefault,+ Text = YGNodeTypeText,+};++template <>+constexpr int32_t ordinalCount<NodeType>() {+ return 2;+}++constexpr NodeType scopedEnum(YGNodeType unscoped) {+ return static_cast<NodeType>(unscoped);+}++constexpr YGNodeType unscopedEnum(NodeType scoped) {+ return static_cast<YGNodeType>(scoped);+}++inline const char* toString(NodeType e) {+ return YGNodeTypeToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Overflow.h b/third_party/yoga/enums/Overflow.hnew file mode 100644index 000000000..20901b02c--- /dev/null+++ b/third_party/yoga/enums/Overflow.h@@ -0,0 +1,41 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Overflow : uint8_t {+ Visible = YGOverflowVisible,+ Hidden = YGOverflowHidden,+ Scroll = YGOverflowScroll,+};++template <>+constexpr int32_t ordinalCount<Overflow>() {+ return 3;+}++constexpr Overflow scopedEnum(YGOverflow unscoped) {+ return static_cast<Overflow>(unscoped);+}++constexpr YGOverflow unscopedEnum(Overflow scoped) {+ return static_cast<YGOverflow>(scoped);+}++inline const char* toString(Overflow e) {+ return YGOverflowToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/PhysicalEdge.h b/third_party/yoga/enums/PhysicalEdge.hnew file mode 100644index 000000000..21e37d2c2--- /dev/null+++ b/third_party/yoga/enums/PhysicalEdge.h@@ -0,0 +1,21 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/enums/Edge.h>++namespace facebook::yoga {++enum class PhysicalEdge : uint32_t {+ Left = yoga::to_underlying(Edge::Left),+ Top = yoga::to_underlying(Edge::Top),+ Right = yoga::to_underlying(Edge::Right),+ Bottom = yoga::to_underlying(Edge::Bottom),+};++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/PositionType.h b/third_party/yoga/enums/PositionType.hnew file mode 100644index 000000000..8a552aacb--- /dev/null+++ b/third_party/yoga/enums/PositionType.h@@ -0,0 +1,41 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class PositionType : uint8_t {+ Static = YGPositionTypeStatic,+ Relative = YGPositionTypeRelative,+ Absolute = YGPositionTypeAbsolute,+};++template <>+constexpr int32_t ordinalCount<PositionType>() {+ return 3;+}++constexpr PositionType scopedEnum(YGPositionType unscoped) {+ return static_cast<PositionType>(unscoped);+}++constexpr YGPositionType unscopedEnum(PositionType scoped) {+ return static_cast<YGPositionType>(scoped);+}++inline const char* toString(PositionType e) {+ return YGPositionTypeToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Unit.h b/third_party/yoga/enums/Unit.hnew file mode 100644index 000000000..685b1caec--- /dev/null+++ b/third_party/yoga/enums/Unit.h@@ -0,0 +1,45 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Unit : uint8_t {+ Undefined = YGUnitUndefined,+ Point = YGUnitPoint,+ Percent = YGUnitPercent,+ Auto = YGUnitAuto,+ MaxContent = YGUnitMaxContent,+ FitContent = YGUnitFitContent,+ Stretch = YGUnitStretch,+};++template <>+constexpr int32_t ordinalCount<Unit>() {+ return 7;+}++constexpr Unit scopedEnum(YGUnit unscoped) {+ return static_cast<Unit>(unscoped);+}++constexpr YGUnit unscopedEnum(Unit scoped) {+ return static_cast<YGUnit>(scoped);+}++inline const char* toString(Unit e) {+ return YGUnitToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/Wrap.h b/third_party/yoga/enums/Wrap.hnew file mode 100644index 000000000..96552b7b2--- /dev/null+++ b/third_party/yoga/enums/Wrap.h@@ -0,0 +1,41 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++// @generated by enums.py+// clang-format off+#pragma once++#include <cstdint>+#include <yoga/YGEnums.h>+#include <yoga/enums/YogaEnums.h>++namespace facebook::yoga {++enum class Wrap : uint8_t {+ NoWrap = YGWrapNoWrap,+ Wrap = YGWrapWrap,+ WrapReverse = YGWrapWrapReverse,+};++template <>+constexpr int32_t ordinalCount<Wrap>() {+ return 3;+}++constexpr Wrap scopedEnum(YGWrap unscoped) {+ return static_cast<Wrap>(unscoped);+}++constexpr YGWrap unscopedEnum(Wrap scoped) {+ return static_cast<YGWrap>(scoped);+}++inline const char* toString(Wrap e) {+ return YGWrapToString(unscopedEnum(e));+}++} // namespace facebook::yogadiff --git a/third_party/yoga/enums/YogaEnums.h b/third_party/yoga/enums/YogaEnums.hnew file mode 100644index 000000000..521d9f7a3--- /dev/null+++ b/third_party/yoga/enums/YogaEnums.h@@ -0,0 +1,84 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <bit>+#include <iterator>+#include <type_traits>++namespace facebook::yoga {++/**+ * Concept for any enum/enum class+ */+template <typename EnumT>+concept Enumeration = std::is_enum_v<EnumT>;++/**+ * Count of ordinals in a Yoga enum which is sequential+ */+template <Enumeration EnumT>+constexpr int32_t ordinalCount();++/**+ * Concept for a yoga enum which is sequential+ */+template <typename EnumT>+concept HasOrdinality = (ordinalCount<EnumT>() > 0);++/**+ * Count of bits needed to represent every ordinal+ */+template <HasOrdinality EnumT>+constexpr int32_t bitCount() {+ return std::bit_width(+ static_cast<std::underlying_type_t<EnumT>>(ordinalCount<EnumT>() - 1));+}++/**+ * Polyfill of C++ 23 to_underlying()+ * https://en.cppreference.com/w/cpp/utility/to_underlying+ */+constexpr auto to_underlying(Enumeration auto e) noexcept {+ return static_cast<std::underlying_type_t<decltype(e)>>(e);+}++/**+ * Convenience function to iterate through every value in a Yoga enum as part of+ * a range-based for loop.+ */+template <HasOrdinality EnumT>+auto ordinals() {+ struct Iterator {+ EnumT e{};++ EnumT operator*() const {+ return e;+ }++ Iterator& operator++() {+ e = static_cast<EnumT>(to_underlying(e) + 1);+ return *this;+ }++ bool operator==(const Iterator& other) const = default;+ };++ struct Range {+ Iterator begin() const {+ return Iterator{};+ }+ Iterator end() const {+ return Iterator{static_cast<EnumT>(ordinalCount<EnumT>())};+ }+ };++ return Range{};+}++} // namespace facebook::yogadiff --git a/third_party/yoga/event/event.cpp b/third_party/yoga/event/event.cppnew file mode 100644index 000000000..ac6735d6d--- /dev/null+++ b/third_party/yoga/event/event.cpp@@ -0,0 +1,89 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include "event.h"+#include <atomic>+#include <memory>++namespace facebook::yoga {++const char* LayoutPassReasonToString(const LayoutPassReason value) {+ switch (value) {+ case LayoutPassReason::kInitial:+ return "initial";+ case LayoutPassReason::kAbsLayout:+ return "abs_layout";+ case LayoutPassReason::kStretch:+ return "stretch";+ case LayoutPassReason::kMultilineStretch:+ return "multiline_stretch";+ case LayoutPassReason::kFlexLayout:+ return "flex_layout";+ case LayoutPassReason::kMeasureChild:+ return "measure";+ case LayoutPassReason::kAbsMeasureChild:+ return "abs_measure";+ case LayoutPassReason::kFlexMeasure:+ return "flex_measure";+ case LayoutPassReason::kGridLayout:+ return "grid_layout";+ default:+ return "unknown";+ }+}++namespace {++struct Node {+ std::function<Event::Subscriber> subscriber = nullptr;+ Node* next = nullptr;++ explicit Node(std::function<Event::Subscriber>&& subscriber)+ : subscriber{std::move(subscriber)} {}+};++std::atomic<Node*> subscribers{nullptr};++Node* push(Node* newHead) {+ Node* oldHead = nullptr;+ do {+ oldHead = subscribers.load(std::memory_order_relaxed);+ if (newHead != nullptr) {+ newHead->next = oldHead;+ }+ } while (!subscribers.compare_exchange_weak(+ oldHead, newHead, std::memory_order_release, std::memory_order_relaxed));+ return oldHead;+}++} // namespace++void Event::reset() {+ auto head = push(nullptr);+ while (head != nullptr) {+ auto current = head;+ head = head->next;+ delete current;+ }+}++void Event::subscribe(std::function<Subscriber>&& subscriber) {+ push(new Node{std::move(subscriber)});+}++void Event::publish(+ YGNodeConstRef node,+ Type eventType,+ const Data& eventData) {+ for (auto subscriber = subscribers.load(std::memory_order_relaxed);+ subscriber != nullptr;+ subscriber = subscriber->next) {+ subscriber->subscriber(node, eventType, eventData);+ }+}++} // namespace facebook::yogadiff --git a/third_party/yoga/event/event.h b/third_party/yoga/event/event.hnew file mode 100644index 000000000..0d032240d--- /dev/null+++ b/third_party/yoga/event/event.h@@ -0,0 +1,131 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/Yoga.h>++#include <array>+#include <cstdint>+#include <functional>+#include <vector>++namespace facebook::yoga {++enum struct LayoutType : int {+ kLayout = 0,+ kMeasure = 1,+ kCachedLayout = 2,+ kCachedMeasure = 3+};++enum struct LayoutPassReason : int {+ kInitial = 0,+ kAbsLayout = 1,+ kStretch = 2,+ kMultilineStretch = 3,+ kFlexLayout = 4,+ kMeasureChild = 5,+ kAbsMeasureChild = 6,+ kFlexMeasure = 7,+ kGridLayout = 8,+ COUNT+};++struct LayoutData {+ int layouts = 0;+ int measures = 0;+ uint32_t maxMeasureCache = 0;+ int cachedLayouts = 0;+ int cachedMeasures = 0;+ int measureCallbacks = 0;+ std::array<int, static_cast<uint8_t>(LayoutPassReason::COUNT)>+ measureCallbackReasonsCount;+};++const char* LayoutPassReasonToString(LayoutPassReason value);++struct YG_EXPORT Event {+ enum Type {+ NodeAllocation,+ NodeDeallocation,+ NodeLayout,+ LayoutPassStart,+ LayoutPassEnd,+ MeasureCallbackStart,+ MeasureCallbackEnd,+ NodeBaselineStart,+ NodeBaselineEnd,+ };+ class Data;+ using Subscriber = void(YGNodeConstRef, Type, Data);+ using Subscribers = std::vector<std::function<Subscriber>>;++ template <Type E>+ struct TypedData {};++ class Data {+ const void* data_;++ public:+ template <Type E>+ explicit Data(const TypedData<E>& data) : data_{&data} {}++ template <Type E>+ const TypedData<E>& get() const {+ return *static_cast<const TypedData<E>*>(data_);+ }+ };++ static void reset();++ static void subscribe(std::function<Subscriber>&& subscriber);++ template <Type E>+ static void publish(YGNodeConstRef node, const TypedData<E>& eventData = {}) {+ publish(node, E, Data{eventData});+ }++ private:+ static void publish(+ YGNodeConstRef /*node*/,+ Type /*eventType*/,+ const Data& /*eventData*/);+};++template <>+struct Event::TypedData<Event::NodeAllocation> {+ YGConfigConstRef config;+};++template <>+struct Event::TypedData<Event::NodeDeallocation> {+ YGConfigConstRef config;+};++template <>+struct Event::TypedData<Event::LayoutPassEnd> {+ LayoutData* layoutData;+};++template <>+struct Event::TypedData<Event::MeasureCallbackEnd> {+ float width;+ YGMeasureMode widthMeasureMode;+ float height;+ YGMeasureMode heightMeasureMode;+ float measuredWidth;+ float measuredHeight;+ const LayoutPassReason reason;+};++template <>+struct Event::TypedData<Event::NodeLayout> {+ LayoutType layoutType;+};++} // namespace facebook::yogadiff --git a/third_party/yoga/module.modulemap b/third_party/yoga/module.modulemapnew file mode 100644index 000000000..6a0f46030--- /dev/null+++ b/third_party/yoga/module.modulemap@@ -0,0 +1,21 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++module yoga [system] {+ module core {+ header "YGConfig.h"+ header "YGEnums.h"+ header "YGMacros.h"+ header "YGNode.h"+ header "YGNodeLayout.h"+ header "YGNodeStyle.h"+ header "YGPixelGrid.h"+ header "YGValue.h"+ header "Yoga.h"+ export *+ }+}diff --git a/third_party/yoga/node/CachedMeasurement.h b/third_party/yoga/node/CachedMeasurement.hnew file mode 100644index 000000000..9c76280ac--- /dev/null+++ b/third_party/yoga/node/CachedMeasurement.h@@ -0,0 +1,53 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <cmath>++#include <yoga/Yoga.h>++#include <yoga/algorithm/SizingMode.h>+#include <yoga/numeric/Comparison.h>++namespace facebook::yoga {++struct CachedMeasurement {+ float availableWidth{-1};+ float availableHeight{-1};+ SizingMode widthSizingMode{SizingMode::MaxContent};+ SizingMode heightSizingMode{SizingMode::MaxContent};++ float computedWidth{-1};+ float computedHeight{-1};++ bool operator==(CachedMeasurement measurement) const {+ bool isEqual = widthSizingMode == measurement.widthSizingMode &&+ heightSizingMode == measurement.heightSizingMode;++ if (!yoga::isUndefined(availableWidth) ||+ !yoga::isUndefined(measurement.availableWidth)) {+ isEqual = isEqual && availableWidth == measurement.availableWidth;+ }+ if (!yoga::isUndefined(availableHeight) ||+ !yoga::isUndefined(measurement.availableHeight)) {+ isEqual = isEqual && availableHeight == measurement.availableHeight;+ }+ if (!yoga::isUndefined(computedWidth) ||+ !yoga::isUndefined(measurement.computedWidth)) {+ isEqual = isEqual && computedWidth == measurement.computedWidth;+ }+ if (!yoga::isUndefined(computedHeight) ||+ !yoga::isUndefined(measurement.computedHeight)) {+ isEqual = isEqual && computedHeight == measurement.computedHeight;+ }++ return isEqual;+ }+};++} // namespace facebook::yogadiff --git a/third_party/yoga/node/LayoutResults.cpp b/third_party/yoga/node/LayoutResults.cppnew file mode 100644index 000000000..acc37a1b4--- /dev/null+++ b/third_party/yoga/node/LayoutResults.cpp@@ -0,0 +1,48 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <cmath>++#include <yoga/node/LayoutResults.h>+#include <yoga/numeric/Comparison.h>++namespace facebook::yoga {++bool LayoutResults::operator==(LayoutResults layout) const {+ bool isEqual = yoga::inexactEquals(position_, layout.position_) &&+ yoga::inexactEquals(dimensions_, layout.dimensions_) &&+ yoga::inexactEquals(margin_, layout.margin_) &&+ yoga::inexactEquals(border_, layout.border_) &&+ yoga::inexactEquals(padding_, layout.padding_) &&+ direction() == layout.direction() &&+ hadOverflow() == layout.hadOverflow() &&+ lastOwnerDirection == layout.lastOwnerDirection &&+ configVersion == layout.configVersion &&+ nextCachedMeasurementsIndex == layout.nextCachedMeasurementsIndex &&+ cachedLayout == layout.cachedLayout &&+ computedFlexBasis == layout.computedFlexBasis;++ for (uint32_t i = 0; i < LayoutResults::MaxCachedMeasurements && isEqual;+ ++i) {+ isEqual = isEqual && cachedMeasurements[i] == layout.cachedMeasurements[i];+ }++ if (!yoga::isUndefined(measuredDimensions_[0]) ||+ !yoga::isUndefined(layout.measuredDimensions_[0])) {+ isEqual =+ isEqual && (measuredDimensions_[0] == layout.measuredDimensions_[0]);+ }+ if (!yoga::isUndefined(measuredDimensions_[1]) ||+ !yoga::isUndefined(layout.measuredDimensions_[1])) {+ isEqual =+ isEqual && (measuredDimensions_[1] == layout.measuredDimensions_[1]);+ }++ return isEqual;+}++} // namespace facebook::yogadiff --git a/third_party/yoga/node/LayoutResults.h b/third_party/yoga/node/LayoutResults.hnew file mode 100644index 000000000..833dc927b--- /dev/null+++ b/third_party/yoga/node/LayoutResults.h@@ -0,0 +1,128 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <array>++#include <yoga/debug/AssertFatal.h>+#include <yoga/enums/Dimension.h>+#include <yoga/enums/Direction.h>+#include <yoga/enums/Edge.h>+#include <yoga/enums/PhysicalEdge.h>+#include <yoga/node/CachedMeasurement.h>+#include <yoga/numeric/FloatOptional.h>++namespace facebook::yoga {++struct LayoutResults {+ // This value was chosen based on empirical data:+ // 98% of analyzed layouts require less than 8 entries.+ static constexpr int32_t MaxCachedMeasurements = 8;++ uint32_t computedFlexBasisGeneration = 0;+ FloatOptional computedFlexBasis = {};++ // Instead of recomputing the entire layout every single time, we cache some+ // information to break early when nothing changed+ uint32_t generationCount = 0;+ uint32_t configVersion = 0;+ Direction lastOwnerDirection = Direction::Inherit;++ uint32_t nextCachedMeasurementsIndex = 0;+ std::array<CachedMeasurement, MaxCachedMeasurements> cachedMeasurements = {};++ CachedMeasurement cachedLayout{};++ Direction direction() const {+ return direction_;+ }++ void setDirection(Direction direction) {+ direction_ = direction;+ }++ bool hadOverflow() const {+ return hadOverflow_;+ }++ void setHadOverflow(bool hadOverflow) {+ hadOverflow_ = hadOverflow;+ }++ float dimension(Dimension axis) const {+ return dimensions_[yoga::to_underlying(axis)];+ }++ void setDimension(Dimension axis, float dimension) {+ dimensions_[yoga::to_underlying(axis)] = dimension;+ }++ float measuredDimension(Dimension axis) const {+ return measuredDimensions_[yoga::to_underlying(axis)];+ }++ float rawDimension(Dimension axis) const {+ return rawDimensions_[yoga::to_underlying(axis)];+ }++ void setMeasuredDimension(Dimension axis, float dimension) {+ measuredDimensions_[yoga::to_underlying(axis)] = dimension;+ }++ void setRawDimension(Dimension axis, float dimension) {+ rawDimensions_[yoga::to_underlying(axis)] = dimension;+ }++ float position(PhysicalEdge physicalEdge) const {+ return position_[yoga::to_underlying(physicalEdge)];+ }++ void setPosition(PhysicalEdge physicalEdge, float dimension) {+ position_[yoga::to_underlying(physicalEdge)] = dimension;+ }++ float margin(PhysicalEdge physicalEdge) const {+ return margin_[yoga::to_underlying(physicalEdge)];+ }++ void setMargin(PhysicalEdge physicalEdge, float dimension) {+ margin_[yoga::to_underlying(physicalEdge)] = dimension;+ }++ float border(PhysicalEdge physicalEdge) const {+ return border_[yoga::to_underlying(physicalEdge)];+ }++ void setBorder(PhysicalEdge physicalEdge, float dimension) {+ border_[yoga::to_underlying(physicalEdge)] = dimension;+ }++ float padding(PhysicalEdge physicalEdge) const {+ return padding_[yoga::to_underlying(physicalEdge)];+ }++ void setPadding(PhysicalEdge physicalEdge, float dimension) {+ padding_[yoga::to_underlying(physicalEdge)] = dimension;+ }++ bool operator==(LayoutResults layout) const;++ private:+ Direction direction_ : bitCount<Direction>() = Direction::Inherit;+ bool hadOverflow_ : 1 = false;++ std::array<float, 2> dimensions_ = {{YGUndefined, YGUndefined}};+ std::array<float, 2> measuredDimensions_ = {{YGUndefined, YGUndefined}};+ std::array<float, 2> rawDimensions_ = {{YGUndefined, YGUndefined}};+ std::array<float, 4> position_ = {};+ std::array<float, 4> margin_ = {};+ std::array<float, 4> border_ = {};+ std::array<float, 4> padding_ = {};+};++} // namespace facebook::yogadiff --git a/third_party/yoga/node/LayoutableChildren.h b/third_party/yoga/node/LayoutableChildren.hnew file mode 100644index 000000000..b158a6a63--- /dev/null+++ b/third_party/yoga/node/LayoutableChildren.h@@ -0,0 +1,148 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <cstdint>+#include <forward_list>+#include <utility>++#include <yoga/enums/Display.h>++namespace facebook::yoga {++class Node;++template <typename T>+class LayoutableChildren {+ public:+ struct Iterator {+ using iterator_category = std::input_iterator_tag;+ using difference_type = std::ptrdiff_t;+ using value_type = T*;+ using pointer = T*;+ using reference = T*;++ Iterator() = default;++ Iterator(const T* node, size_t childIndex)+ : node_(node), childIndex_(childIndex) {}++ T* operator*() const {+ return node_->getChild(childIndex_);+ }++ Iterator& operator++() {+ next();+ return *this;+ }++ Iterator operator++(int) {+ Iterator tmp = *this;+ ++(*this);+ return tmp;+ }++ friend bool operator==(const Iterator& a, const Iterator& b) {+ return a.node_ == b.node_ && a.childIndex_ == b.childIndex_;+ }++ friend bool operator!=(const Iterator& a, const Iterator& b) {+ return a.node_ != b.node_ || a.childIndex_ != b.childIndex_;+ }++ private:+ void next() {+ if (childIndex_ + 1 >= node_->getChildCount()) {+ // if the current node has no more children, try to backtrack and+ // visit its successor+ if (backtrack_.empty()) [[likely]] {+ // if there are no nodes to backtrack to, the last node has been+ // visited+ *this = Iterator{};+ } else {+ // pop and restore the latest backtrack entry+ const auto& back = backtrack_.front();+ node_ = back.first;+ childIndex_ = back.second;+ backtrack_.pop_front();++ // go to the next node+ next();+ }+ } else {+ // current node has more children to visit, go to next+ ++childIndex_;+ // skip all display: contents nodes, possibly going deeper into the+ // tree+ if (node_->getChild(childIndex_)->style().display() ==+ Display::Contents) [[unlikely]] {+ skipContentsNodes();+ }+ }+ }++ void skipContentsNodes() {+ // get the node that would be returned from the iterator+ auto currentNode = node_->getChild(childIndex_);+ while (currentNode->style().display() == Display::Contents &&+ currentNode->getChildCount() > 0) {+ // if it has display: contents set, it shouldn't be returned but its+ // children should in its place push the current node and child index+ // so that the current state can be restored when backtracking+ backtrack_.push_front({node_, childIndex_});+ // traverse the child+ node_ = currentNode;+ childIndex_ = 0;++ // repeat until a node without display: contents is found in the+ // subtree or a leaf is reached+ currentNode = currentNode->getChild(childIndex_);+ }++ // if no node without display: contents was found, try to backtrack+ if (currentNode->style().display() == Display::Contents) {+ next();+ }+ }++ const T* node_{nullptr};+ size_t childIndex_{0};+ std::forward_list<std::pair<const T*, size_t>> backtrack_;++ friend LayoutableChildren;+ };++ explicit LayoutableChildren(const T* node) : node_(node) {+ static_assert(std::input_iterator<LayoutableChildren<T>::Iterator>);+ static_assert(+ std::is_base_of<Node, T>::value,+ "Type parameter of LayoutableChildren must derive from yoga::Node");+ }++ Iterator begin() const {+ if (node_->getChildCount() > 0) {+ auto result = Iterator(node_, 0);+ if (node_->getChild(0)->style().display() == Display::Contents)+ [[unlikely]] {+ result.skipContentsNodes();+ }+ return result;+ } else {+ return Iterator{};+ }+ }++ Iterator end() const {+ return Iterator{};+ }++ private:+ const T* node_;+};++} // namespace facebook::yogadiff --git a/third_party/yoga/node/Node.cpp b/third_party/yoga/node/Node.cppnew file mode 100644index 000000000..d42bd5f9e--- /dev/null+++ b/third_party/yoga/node/Node.cpp@@ -0,0 +1,472 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#include <algorithm>+#include <cstddef>+#include <iostream>++#include <yoga/algorithm/FlexDirection.h>+#include <yoga/debug/AssertFatal.h>+#include <yoga/debug/Log.h>+#include <yoga/node/Node.h>+#include <yoga/numeric/Comparison.h>++namespace facebook::yoga {++Node::Node() : Node{&Config::getDefault()} {}++Node::Node(const yoga::Config* config) : config_{config} {+ yoga::assertFatal(+ config != nullptr, "Attempting to construct Node with null config");++ if (config->useWebDefaults()) {+ useWebDefaults();+ }+}++Node::Node(Node&& node) noexcept+ : hasNewLayout_(node.hasNewLayout_),+ isReferenceBaseline_(node.isReferenceBaseline_),+ isDirty_(node.isDirty_),+ alwaysFormsContainingBlock_(node.alwaysFormsContainingBlock_),+ nodeType_(node.nodeType_),+ context_(node.context_),+ measureFunc_(node.measureFunc_),+ baselineFunc_(node.baselineFunc_),+ dirtiedFunc_(node.dirtiedFunc_),+ style_(std::move(node.style_)),+ layout_(node.layout_),+ lineIndex_(node.lineIndex_),+ contentsChildrenCount_(node.contentsChildrenCount_),+ owner_(node.owner_),+ children_(std::move(node.children_)),+ config_(node.config_),+ processedDimensions_(node.processedDimensions_) {+ for (auto c : children_) {+ c->setOwner(this);+ }+}++YGSize Node::measure(+ float availableWidth,+ MeasureMode widthMode,+ float availableHeight,+ MeasureMode heightMode) {+ const auto size = measureFunc_(+ this,+ availableWidth,+ unscopedEnum(widthMode),+ availableHeight,+ unscopedEnum(heightMode));++ if (yoga::isUndefined(size.height) || size.height < 0 ||+ yoga::isUndefined(size.width) || size.width < 0) {+ yoga::log(+ this,+ LogLevel::Warn,+ "Measure function returned an invalid dimension to Yoga: [width=%f, height=%f]",+ size.width,+ size.height);+ return {+ .width = maxOrDefined(0.0f, size.width),+ .height = maxOrDefined(0.0f, size.height)};+ }++ return size;+}++float Node::baseline(float width, float height) const {+ return baselineFunc_(this, width, height);+}++float Node::dimensionWithMargin(+ const FlexDirection axis,+ const float widthSize) {+ return getLayout().measuredDimension(dimension(axis)) ++ style_.computeMarginForAxis(axis, widthSize);+}++bool Node::isLayoutDimensionDefined(const FlexDirection axis) {+ const float value = getLayout().measuredDimension(dimension(axis));+ return yoga::isDefined(value) && value >= 0.0f;+}++// Setters++void Node::setMeasureFunc(YGMeasureFunc measureFunc) {+ if (measureFunc == nullptr) {+ // TODO: t18095186 Move nodeType to opt-in function and mark appropriate+ // places in Litho+ setNodeType(NodeType::Default);+ } else {+ yoga::assertFatalWithNode(+ this,+ children_.empty(),+ "Cannot set measure function: Nodes with measure functions cannot have "+ "children.");+ // TODO: t18095186 Move nodeType to opt-in function and mark appropriate+ // places in Litho+ setNodeType(NodeType::Text);+ }++ measureFunc_ = measureFunc;+}++void Node::replaceChild(Node* child, size_t index) {+ auto previousChild = children_[index];+ if (previousChild->style().display() == Display::Contents &&+ child->style().display() != Display::Contents) {+ contentsChildrenCount_--;+ } else if (+ previousChild->style().display() != Display::Contents &&+ child->style().display() == Display::Contents) {+ contentsChildrenCount_++;+ }++ children_[index] = child;+}++void Node::replaceChild(Node* oldChild, Node* newChild) {+ if (oldChild->style().display() == Display::Contents &&+ newChild->style().display() != Display::Contents) {+ contentsChildrenCount_--;+ } else if (+ oldChild->style().display() != Display::Contents &&+ newChild->style().display() == Display::Contents) {+ contentsChildrenCount_++;+ }++ std::replace(children_.begin(), children_.end(), oldChild, newChild);+}++void Node::insertChild(Node* child, size_t index) {+ if (child->style().display() == Display::Contents) {+ contentsChildrenCount_++;+ }++ children_.insert(children_.begin() + static_cast<ptrdiff_t>(index), child);+}++void Node::setConfig(yoga::Config* config) {+ yoga::assertFatal(+ config != nullptr, "Attempting to set a null config on a Node");+ yoga::assertFatalWithConfig(+ config,+ config->useWebDefaults() == config_->useWebDefaults(),+ "UseWebDefaults may not be changed after constructing a Node");++ if (yoga::configUpdateInvalidatesLayout(*config_, *config)) {+ markDirtyAndPropagate();+ layout_.configVersion = 0;+ } else {+ // If the config is functionally the same, then align the configVersion so+ // that we can reuse the layout cache+ layout_.configVersion = config->getVersion();+ }++ config_ = config;+}++void Node::setDirty(bool isDirty) {+ if (static_cast<int>(isDirty) == isDirty_) {+ return;+ }+ isDirty_ = isDirty;+ if (isDirty && (dirtiedFunc_ != nullptr)) {+ dirtiedFunc_(this);+ }+}++void Node::setChildren(const std::vector<Node*>& children) {+ children_ = children;++ contentsChildrenCount_ = 0;+ for (const auto& child : children) {+ if (child->style().display() == Display::Contents) {+ contentsChildrenCount_++;+ }+ }+}++bool Node::removeChild(Node* child) {+ auto p = std::find(children_.begin(), children_.end(), child);+ if (p != children_.end()) {+ if (child->style().display() == Display::Contents) {+ contentsChildrenCount_--;+ }++ children_.erase(p);+ return true;+ }+ return false;+}++void Node::removeChild(size_t index) {+ if (children_[index]->style().display() == Display::Contents) {+ contentsChildrenCount_--;+ }++ children_.erase(children_.begin() + static_cast<ptrdiff_t>(index));+}++void Node::setLayoutDirection(Direction direction) {+ layout_.setDirection(direction);+}++void Node::setLayoutMargin(float margin, PhysicalEdge edge) {+ layout_.setMargin(edge, margin);+}++void Node::setLayoutBorder(float border, PhysicalEdge edge) {+ layout_.setBorder(edge, border);+}++void Node::setLayoutPadding(float padding, PhysicalEdge edge) {+ layout_.setPadding(edge, padding);+}++void Node::setLayoutLastOwnerDirection(Direction direction) {+ layout_.lastOwnerDirection = direction;+}++void Node::setLayoutComputedFlexBasis(const FloatOptional computedFlexBasis) {+ layout_.computedFlexBasis = computedFlexBasis;+}++void Node::setLayoutPosition(float position, PhysicalEdge edge) {+ layout_.setPosition(edge, position);+}++void Node::setLayoutComputedFlexBasisGeneration(+ uint32_t computedFlexBasisGeneration) {+ layout_.computedFlexBasisGeneration = computedFlexBasisGeneration;+}++void Node::setLayoutMeasuredDimension(+ float measuredDimension,+ Dimension dimension) {+ layout_.setMeasuredDimension(dimension, measuredDimension);+}++void Node::setLayoutHadOverflow(bool hadOverflow) {+ layout_.setHadOverflow(hadOverflow);+}++void Node::setLayoutDimension(float lengthValue, Dimension dimension) {+ layout_.setDimension(dimension, lengthValue);+ layout_.setRawDimension(dimension, lengthValue);+}++// If both left and right are defined, then use left. Otherwise return +left or+// -right depending on which is defined. Ignore statically positioned nodes as+// insets do not apply to them.+float Node::relativePosition(+ FlexDirection axis,+ Direction direction,+ float axisSize) const {+ if (style_.positionType() == PositionType::Static) {+ return 0;+ }+ if (style_.isInlineStartPositionDefined(axis, direction) &&+ !style_.isInlineStartPositionAuto(axis, direction)) {+ return style_.computeInlineStartPosition(axis, direction, axisSize);+ }++ return -1 * style_.computeInlineEndPosition(axis, direction, axisSize);+}++void Node::setPosition(+ const Direction direction,+ const float ownerWidth,+ const float ownerHeight) {+ /* Root nodes should be always layouted as LTR, so we don't return negative+ * values. */+ const Direction directionRespectingRoot =+ owner_ != nullptr ? direction : Direction::LTR;+ const FlexDirection mainAxis =+ yoga::resolveDirection(style_.flexDirection(), directionRespectingRoot);+ const FlexDirection crossAxis =+ yoga::resolveCrossDirection(mainAxis, directionRespectingRoot);++ // In the case of position static these are just 0. See:+ // https://www.w3.org/TR/css-position-3/#valdef-position-static+ const float relativePositionMain = relativePosition(+ mainAxis,+ directionRespectingRoot,+ isRow(mainAxis) ? ownerWidth : ownerHeight);+ const float relativePositionCross = relativePosition(+ crossAxis,+ directionRespectingRoot,+ isRow(mainAxis) ? ownerHeight : ownerWidth);++ const auto mainAxisLeadingEdge = inlineStartEdge(mainAxis, direction);+ const auto mainAxisTrailingEdge = inlineEndEdge(mainAxis, direction);+ const auto crossAxisLeadingEdge = inlineStartEdge(crossAxis, direction);+ const auto crossAxisTrailingEdge = inlineEndEdge(crossAxis, direction);++ setLayoutPosition(+ (style_.computeInlineStartMargin(mainAxis, direction, ownerWidth) ++ relativePositionMain),+ mainAxisLeadingEdge);+ setLayoutPosition(+ (style_.computeInlineEndMargin(mainAxis, direction, ownerWidth) ++ relativePositionMain),+ mainAxisTrailingEdge);+ setLayoutPosition(+ (style_.computeInlineStartMargin(crossAxis, direction, ownerWidth) ++ relativePositionCross),+ crossAxisLeadingEdge);+ setLayoutPosition(+ (style_.computeInlineEndMargin(crossAxis, direction, ownerWidth) ++ relativePositionCross),+ crossAxisTrailingEdge);+}++Style::SizeLength Node::processFlexBasis() const {+ Style::SizeLength flexBasis = style_.flexBasis();+ if (!flexBasis.isAuto() && !flexBasis.isUndefined()) {+ return flexBasis;+ }+ if (style_.flex().isDefined() && style_.flex().unwrap() > 0.0f) {+ return config_->useWebDefaults() ? StyleSizeLength::ofAuto()+ : StyleSizeLength::points(0);+ }+ return StyleSizeLength::ofAuto();+}++FloatOptional Node::resolveFlexBasis(+ Direction direction,+ FlexDirection flexDirection,+ float referenceLength,+ float ownerWidth) const {+ FloatOptional value = processFlexBasis().resolve(referenceLength);+ if (style_.boxSizing() == BoxSizing::BorderBox) {+ return value;+ }++ Dimension dim = dimension(flexDirection);+ FloatOptional dimensionPaddingAndBorder = FloatOptional{+ style_.computePaddingAndBorderForDimension(direction, dim, ownerWidth)};++ return value ++ (dimensionPaddingAndBorder.isDefined() ? dimensionPaddingAndBorder+ : FloatOptional{0.0});+}++void Node::processDimensions() {+ for (auto dim : {Dimension::Width, Dimension::Height}) {+ if (style_.maxDimension(dim).isDefined() &&+ yoga::inexactEquals(+ style_.maxDimension(dim), style_.minDimension(dim))) {+ processedDimensions_[yoga::to_underlying(dim)] = style_.maxDimension(dim);+ } else {+ processedDimensions_[yoga::to_underlying(dim)] = style_.dimension(dim);+ }+ }+}++Direction Node::resolveDirection(const Direction ownerDirection) {+ if (style_.direction() == Direction::Inherit) {+ return ownerDirection != Direction::Inherit ? ownerDirection+ : Direction::LTR;+ } else {+ return style_.direction();+ }+}++void Node::clearChildren() {+ children_.clear();+ children_.shrink_to_fit();+}++// Other Methods++void Node::cloneChildrenIfNeeded() {+ size_t i = 0;+ for (Node*& child : children_) {+ if (child->getOwner() != this) {+ child = resolveRef(config_->cloneNode(child, this, i));+ child->setOwner(this);++ if (child->hasContentsChildren()) [[unlikely]] {+ child->cloneContentsChildrenIfNeeded();+ }+ }+ i += 1;+ }+}++void Node::cloneContentsChildrenIfNeeded() {+ size_t i = 0;+ for (Node*& child : children_) {+ if (child->style().display() == Display::Contents &&+ child->getOwner() != this) {+ child = resolveRef(config_->cloneNode(child, this, i));+ child->setOwner(this);+ child->cloneChildrenIfNeeded();+ }+ i += 1;+ }+}++void Node::markDirtyAndPropagate() {+ if (!isDirty_) {+ setDirty(true);+ setLayoutComputedFlexBasis(FloatOptional());+ if (owner_ != nullptr) {+ owner_->markDirtyAndPropagate();+ }+ }+}++float Node::resolveFlexGrow() const {+ // Root nodes flexGrow should always be 0+ if (owner_ == nullptr) {+ return 0.0;+ }+ if (style_.flexGrow().isDefined()) {+ return style_.flexGrow().unwrap();+ }+ if (style_.flex().isDefined() && style_.flex().unwrap() > 0.0f) {+ return style_.flex().unwrap();+ }+ return Style::DefaultFlexGrow;+}++float Node::resolveFlexShrink() const {+ if (owner_ == nullptr) {+ return 0.0;+ }+ if (style_.flexShrink().isDefined()) {+ return style_.flexShrink().unwrap();+ }+ if (!config_->useWebDefaults() && style_.flex().isDefined() &&+ style_.flex().unwrap() < 0.0f) {+ return -style_.flex().unwrap();+ }+ return config_->useWebDefaults() ? Style::WebDefaultFlexShrink+ : Style::DefaultFlexShrink;+}++bool Node::isNodeFlexible() {+ return (+ (style_.positionType() != PositionType::Absolute) &&+ (resolveFlexGrow() != 0 || resolveFlexShrink() != 0));+}++void Node::reset() {+ yoga::assertFatalWithNode(+ this,+ children_.empty(),+ "Cannot reset a node which still has children attached");+ yoga::assertFatalWithNode(+ this, owner_ == nullptr, "Cannot reset a node still attached to a owner");++ *this = Node{getConfig()};+}++} // namespace facebook::yogadiff --git a/third_party/yoga/node/Node.h b/third_party/yoga/node/Node.hnew file mode 100644index 000000000..d22c4c1ef--- /dev/null+++ b/third_party/yoga/node/Node.h@@ -0,0 +1,339 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <cstdint>+#include <cstdio>+#include <vector>++#include <yoga/Yoga.h>+#include <yoga/node/LayoutableChildren.h>++#include <yoga/config/Config.h>+#include <yoga/enums/Dimension.h>+#include <yoga/enums/Direction.h>+#include <yoga/enums/Edge.h>+#include <yoga/enums/Errata.h>+#include <yoga/enums/MeasureMode.h>+#include <yoga/enums/NodeType.h>+#include <yoga/enums/PhysicalEdge.h>+#include <yoga/node/LayoutResults.h>+#include <yoga/style/Style.h>++// Tag struct used to form the opaque YGNodeRef for the public C API+struct YGNode {};++namespace facebook::yoga {++class YG_EXPORT Node : public ::YGNode {+ public:+ using LayoutableChildren = yoga::LayoutableChildren<Node>;+ Node();+ explicit Node(const Config* config);++ Node(Node&& node) noexcept;++ // Does not expose true value semantics, as children are not cloned eagerly.+ // Should we remove this?+ Node(const Node& node) = default;++ // assignment means potential leaks of existing children, or alternatively+ // freeing unowned memory, double free, or freeing stack memory.+ Node& operator=(const Node&) = delete;++ // Getters+ void* getContext() const {+ return context_;+ }++ bool alwaysFormsContainingBlock() const {+ return alwaysFormsContainingBlock_;+ }++ bool getHasNewLayout() const {+ return hasNewLayout_;+ }++ NodeType getNodeType() const {+ return nodeType_;+ }++ bool hasMeasureFunc() const noexcept {+ return measureFunc_ != nullptr;+ }++ YGSize measure(+ float availableWidth,+ MeasureMode widthMode,+ float availableHeight,+ MeasureMode heightMode);++ bool hasBaselineFunc() const noexcept {+ return baselineFunc_ != nullptr;+ }++ float baseline(float width, float height) const;++ float dimensionWithMargin(FlexDirection axis, float widthSize);++ bool isLayoutDimensionDefined(FlexDirection axis);++ /**+ * Whether the node has a "definite length" along the given axis.+ * https://www.w3.org/TR/css-sizing-3/#definite+ */+ inline bool hasDefiniteLength(Dimension dimension, float ownerSize) {+ auto usedValue = getProcessedDimension(dimension).resolve(ownerSize);+ return usedValue.isDefined() && usedValue.unwrap() >= 0.0f;+ }++ bool hasErrata(Errata errata) const {+ return config_->hasErrata(errata);+ }++ bool hasContentsChildren() const {+ return contentsChildrenCount_ != 0;+ }++ YGDirtiedFunc getDirtiedFunc() const {+ return dirtiedFunc_;+ }++ // For Performance reasons passing as reference.+ Style& style() {+ return style_;+ }++ const Style& style() const {+ return style_;+ }++ // For Performance reasons passing as reference.+ LayoutResults& getLayout() {+ return layout_;+ }++ const LayoutResults& getLayout() const {+ return layout_;+ }++ size_t getLineIndex() const {+ return lineIndex_;+ }++ bool isReferenceBaseline() const {+ return isReferenceBaseline_;+ }++ // returns the Node that owns this Node. An owner is used to identify+ // the YogaTree that a Node belongs to. This method will return the parent+ // of the Node when a Node only belongs to one YogaTree or nullptr when+ // the Node is shared between two or more YogaTrees.+ Node* getOwner() const {+ return owner_;+ }++ const std::vector<Node*>& getChildren() const {+ return children_;+ }++ Node* getChild(size_t index) const {+ return children_.at(index);+ }++ size_t getChildCount() const {+ return children_.size();+ }++ LayoutableChildren getLayoutChildren() const {+ return LayoutableChildren(this);+ }++ size_t getLayoutChildCount() const {+ if (contentsChildrenCount_ == 0) {+ return children_.size();+ } else {+ size_t count = 0;+ for (auto iter = getLayoutChildren().begin();+ iter != getLayoutChildren().end();+ iter++) {+ count++;+ }+ return count;+ }+ }++ const Config* getConfig() const {+ return config_;+ }++ bool isDirty() const {+ return isDirty_;+ }++ Style::SizeLength getProcessedDimension(Dimension dimension) const {+ return processedDimensions_[static_cast<size_t>(dimension)];+ }++ FloatOptional getResolvedDimension(+ Direction direction,+ Dimension dimension,+ float referenceLength,+ float ownerWidth) const {+ FloatOptional value =+ getProcessedDimension(dimension).resolve(referenceLength);+ if (style_.boxSizing() == BoxSizing::BorderBox) {+ return value;+ }++ FloatOptional dimensionPaddingAndBorder =+ FloatOptional{style_.computePaddingAndBorderForDimension(+ direction, dimension, ownerWidth)};++ return value ++ (dimensionPaddingAndBorder.isDefined() ? dimensionPaddingAndBorder+ : FloatOptional{0.0});+ }++ // Setters++ void setContext(void* context) {+ context_ = context;+ }++ void setAlwaysFormsContainingBlock(bool alwaysFormsContainingBlock) {+ alwaysFormsContainingBlock_ = alwaysFormsContainingBlock;+ }++ void setHasNewLayout(bool hasNewLayout) {+ hasNewLayout_ = hasNewLayout;+ }++ void setNodeType(NodeType nodeType) {+ nodeType_ = nodeType;+ }++ void setMeasureFunc(YGMeasureFunc measureFunc);++ void setBaselineFunc(YGBaselineFunc baseLineFunc) {+ baselineFunc_ = baseLineFunc;+ }++ void setDirtiedFunc(YGDirtiedFunc dirtiedFunc) {+ dirtiedFunc_ = dirtiedFunc;+ }++ void setStyle(const Style& style) {+ style_ = style;+ }++ void setLayout(const LayoutResults& layout) {+ layout_ = layout;+ }++ void setLineIndex(size_t lineIndex) {+ lineIndex_ = lineIndex;+ }++ void setIsReferenceBaseline(bool isReferenceBaseline) {+ isReferenceBaseline_ = isReferenceBaseline;+ }++ void setOwner(Node* owner) {+ owner_ = owner;+ }++ // TODO: rvalue override for setChildren++ void setConfig(Config* config);++ void setDirty(bool isDirty);+ void setChildren(const std::vector<Node*>& children);+ void setLayoutLastOwnerDirection(Direction direction);+ void setLayoutComputedFlexBasis(FloatOptional computedFlexBasis);+ void setLayoutComputedFlexBasisGeneration(+ uint32_t computedFlexBasisGeneration);+ void setLayoutMeasuredDimension(float measuredDimension, Dimension dimension);+ void setLayoutHadOverflow(bool hadOverflow);+ void setLayoutDimension(float lengthValue, Dimension dimension);+ void setLayoutDirection(Direction direction);+ void setLayoutMargin(float margin, PhysicalEdge edge);+ void setLayoutBorder(float border, PhysicalEdge edge);+ void setLayoutPadding(float padding, PhysicalEdge edge);+ void setLayoutPosition(float position, PhysicalEdge edge);+ void setPosition(Direction direction, float ownerWidth, float ownerHeight);++ // Other methods+ Style::SizeLength processFlexBasis() const;+ FloatOptional resolveFlexBasis(+ Direction direction,+ FlexDirection flexDirection,+ float referenceLength,+ float ownerWidth) const;+ void processDimensions();+ Direction resolveDirection(Direction ownerDirection);+ void clearChildren();+ /// Replaces the occurrences of oldChild with newChild+ void replaceChild(Node* oldChild, Node* newChild);+ void replaceChild(Node* child, size_t index);+ void insertChild(Node* child, size_t index);+ /// Removes the first occurrence of child+ bool removeChild(Node* child);+ void removeChild(size_t index);++ void cloneChildrenIfNeeded();+ void cloneContentsChildrenIfNeeded();+ void markDirtyAndPropagate();+ float resolveFlexGrow() const;+ float resolveFlexShrink() const;+ bool isNodeFlexible();+ void reset();++ float relativePosition(+ FlexDirection axis,+ Direction direction,+ float axisSize) const;++ private:+ // Used to allow resetting the node+ Node& operator=(Node&&) noexcept = default;++ void useWebDefaults() {+ style_.setFlexDirection(FlexDirection::Row);+ style_.setAlignContent(Align::Stretch);+ }++ bool hasNewLayout_ : 1 = true;+ bool isReferenceBaseline_ : 1 = false;+ bool isDirty_ : 1 = true;+ bool alwaysFormsContainingBlock_ : 1 = false;+ NodeType nodeType_ : bitCount<NodeType>() = NodeType::Default;+ void* context_ = nullptr;+ YGMeasureFunc measureFunc_ = nullptr;+ YGBaselineFunc baselineFunc_ = nullptr;+ YGDirtiedFunc dirtiedFunc_ = nullptr;+ Style style_;+ LayoutResults layout_;+ size_t lineIndex_ = 0;+ size_t contentsChildrenCount_ = 0;+ Node* owner_ = nullptr;+ std::vector<Node*> children_;+ const Config* config_;+ std::array<Style::SizeLength, 2> processedDimensions_{+ {StyleSizeLength::undefined(), StyleSizeLength::undefined()}};+};++inline Node* resolveRef(const YGNodeRef ref) {+ return static_cast<Node*>(ref);+}++inline const Node* resolveRef(const YGNodeConstRef ref) {+ return static_cast<const Node*>(ref);+}++} // namespace facebook::yogadiff --git a/third_party/yoga/numeric/Comparison.h b/third_party/yoga/numeric/Comparison.hnew file mode 100644index 000000000..0e23a837b--- /dev/null+++ b/third_party/yoga/numeric/Comparison.h@@ -0,0 +1,81 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <algorithm>+#include <array>+#include <cmath>+#include <concepts>++#include <yoga/Yoga.h>++namespace facebook::yoga {++constexpr bool isUndefined(std::floating_point auto value) {+ return value != value;+}++constexpr bool isDefined(std::floating_point auto value) {+ return !isUndefined(value);+}++/**+ * Constexpr version of `std::isinf` before C++ 23+ */+constexpr bool isinf(auto value) {+ return value == +std::numeric_limits<decltype(value)>::infinity() ||+ value == -std::numeric_limits<decltype(value)>::infinity();+}++constexpr auto maxOrDefined(+ std::floating_point auto a,+ std::floating_point auto b) {+ if (yoga::isDefined(a) && yoga::isDefined(b)) {+ return std::max(a, b);+ }+ return yoga::isUndefined(a) ? b : a;+}++constexpr auto minOrDefined(+ std::floating_point auto a,+ std::floating_point auto b) {+ if (yoga::isDefined(a) && yoga::isDefined(b)) {+ return std::min(a, b);+ }++ return yoga::isUndefined(a) ? b : a;+}++// Custom equality functions using a hardcoded epsilon of 0.0001f, or returning+// true if both floats are NaN.+inline bool inexactEquals(float a, float b) {+ if (yoga::isDefined(a) && yoga::isDefined(b)) {+ return std::abs(a - b) < 0.0001f;+ }+ return yoga::isUndefined(a) && yoga::isUndefined(b);+}++inline bool inexactEquals(double a, double b) {+ if (yoga::isDefined(a) && yoga::isDefined(b)) {+ return std::abs(a - b) < 0.0001;+ }+ return yoga::isUndefined(a) && yoga::isUndefined(b);+}++template <std::size_t Size, typename ElementT>+bool inexactEquals(+ const std::array<ElementT, Size>& val1,+ const std::array<ElementT, Size>& val2) {+ bool areEqual = true;+ for (std::size_t i = 0; i < Size && areEqual; ++i) {+ areEqual = inexactEquals(val1[i], val2[i]);+ }+ return areEqual;+}++} // namespace facebook::yogadiff --git a/third_party/yoga/numeric/FloatOptional.h b/third_party/yoga/numeric/FloatOptional.hnew file mode 100644index 000000000..c255277ae--- /dev/null+++ b/third_party/yoga/numeric/FloatOptional.h@@ -0,0 +1,84 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/numeric/Comparison.h>+#include <limits>++namespace facebook::yoga {++struct FloatOptional {+ private:+ float value_ = std::numeric_limits<float>::quiet_NaN();++ public:+ explicit constexpr FloatOptional(float value) : value_(value) {}+ constexpr FloatOptional() = default;++ // returns the wrapped value, or a value x with YGIsUndefined(x) == true+ constexpr float unwrap() const {+ return value_;+ }++ constexpr float unwrapOrDefault(float defaultValue) const {+ return isUndefined() ? defaultValue : value_;+ }++ constexpr bool isUndefined() const {+ return yoga::isUndefined(value_);+ }++ constexpr bool isDefined() const {+ return yoga::isDefined(value_);+ }+};++// operators take FloatOptional by value, as it is a 32bit value++constexpr bool operator==(FloatOptional lhs, FloatOptional rhs) {+ return lhs.unwrap() == rhs.unwrap() ||+ (lhs.isUndefined() && rhs.isUndefined());+}++constexpr bool operator==(FloatOptional lhs, float rhs) {+ return lhs == FloatOptional{rhs};+}++constexpr bool operator==(float lhs, FloatOptional rhs) {+ return rhs == lhs;+}++constexpr FloatOptional operator+(FloatOptional lhs, FloatOptional rhs) {+ return FloatOptional{lhs.unwrap() + rhs.unwrap()};+}++constexpr bool operator>(FloatOptional lhs, FloatOptional rhs) {+ return lhs.unwrap() > rhs.unwrap();+}++constexpr bool operator<(FloatOptional lhs, FloatOptional rhs) {+ return lhs.unwrap() < rhs.unwrap();+}++constexpr bool operator>=(FloatOptional lhs, FloatOptional rhs) {+ return lhs > rhs || lhs == rhs;+}++constexpr bool operator<=(FloatOptional lhs, FloatOptional rhs) {+ return lhs < rhs || lhs == rhs;+}++constexpr FloatOptional maxOrDefined(FloatOptional lhs, FloatOptional rhs) {+ return FloatOptional{yoga::maxOrDefined(lhs.unwrap(), rhs.unwrap())};+}++inline bool inexactEquals(FloatOptional lhs, FloatOptional rhs) {+ return yoga::inexactEquals(lhs.unwrap(), rhs.unwrap());+}++} // namespace facebook::yogadiff --git a/third_party/yoga/style/GridLine.h b/third_party/yoga/style/GridLine.hnew file mode 100644index 000000000..0a06c0dfa--- /dev/null+++ b/third_party/yoga/style/GridLine.h@@ -0,0 +1,53 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <cstdint>++namespace facebook::yoga {++// https://www.w3.org/TR/css-grid-1/#typedef-grid-row-start-grid-line+enum class GridLineType : uint8_t {+ Auto,+ Integer,+ Span,+};++struct GridLine {+ GridLineType type{};+ // Line position (1, 2, -1, -2, etc)+ int32_t integer{};++ constexpr static GridLine auto_() {+ return GridLine{.type = GridLineType::Auto, .integer = 0};+ }++ constexpr static GridLine fromInteger(int32_t value) {+ return GridLine{.type = GridLineType::Integer, .integer = value};+ }++ constexpr static GridLine span(int32_t value) {+ return GridLine{.type = GridLineType::Span, .integer = value};+ }++ constexpr bool isAuto() const {+ return type == GridLineType::Auto;+ }++ constexpr bool isInteger() const {+ return type == GridLineType::Integer;+ }++ constexpr bool isSpan() const {+ return type == GridLineType::Span;+ }++ bool operator==(const GridLine& other) const = default;+};++} // namespace facebook::yogadiff --git a/third_party/yoga/style/GridTrack.h b/third_party/yoga/style/GridTrack.hnew file mode 100644index 000000000..2a2bafb50--- /dev/null+++ b/third_party/yoga/style/GridTrack.h@@ -0,0 +1,63 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/style/StyleSizeLength.h>+#include <vector>++namespace facebook::yoga {+// https://www.w3.org/TR/css-grid-1/#typedef-track-size+struct GridTrackSize {+ StyleSizeLength minSizingFunction;+ StyleSizeLength maxSizingFunction;++ // These are used in the grid layout algorithm when distributing spaces among+ // tracks+ // TODO: maybe move them to TrackSizing since these are track states+ float baseSize = 0.0f;+ float growthLimit = 0.0f;+ bool infinitelyGrowable = false;++ // Static factory methods for common cases+ constexpr static GridTrackSize auto_() {+ return GridTrackSize{+ .minSizingFunction = StyleSizeLength::ofAuto(),+ .maxSizingFunction = StyleSizeLength::ofAuto()};+ }++ constexpr static GridTrackSize length(float points) {+ auto len = StyleSizeLength::points(points);+ return GridTrackSize{.minSizingFunction = len, .maxSizingFunction = len};+ }++ constexpr static GridTrackSize fr(float fraction) {+ // Flex sizing function is always a max sizing function+ return GridTrackSize{+ .minSizingFunction = StyleSizeLength::ofAuto(),+ .maxSizingFunction = StyleSizeLength::stretch(fraction)};+ }++ constexpr static GridTrackSize percent(float percentage) {+ return GridTrackSize{+ .minSizingFunction = StyleSizeLength::percent(percentage),+ .maxSizingFunction = StyleSizeLength::percent(percentage)};+ }++ constexpr static GridTrackSize minmax(+ StyleSizeLength min,+ StyleSizeLength max) {+ return GridTrackSize{.minSizingFunction = min, .maxSizingFunction = max};+ }++ bool operator==(const GridTrackSize& other) const = default;+};++// Grid track list for grid-template-rows/columns properties+using GridTrackList = std::vector<GridTrackSize>;++} // namespace facebook::yogadiff --git a/third_party/yoga/style/SmallValueBuffer.h b/third_party/yoga/style/SmallValueBuffer.hnew file mode 100644index 000000000..8d78a54dc--- /dev/null+++ b/third_party/yoga/style/SmallValueBuffer.h@@ -0,0 +1,133 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <array>+#include <bitset>+#include <cassert>+#include <cstdint>+#include <memory>+#include <vector>++namespace facebook::yoga {++// Container which allows storing 32 or 64 bit integer values, whose index may+// never change. Values are first stored in a fixed buffer of `BufferSize`+// 32-bit chunks, before falling back to heap allocation.+template <size_t BufferSize>+class SmallValueBuffer {+ public:+ SmallValueBuffer() = default;+ SmallValueBuffer(const SmallValueBuffer& other) {+ *this = other;+ }+ SmallValueBuffer(SmallValueBuffer&& other) noexcept = default;++ // Add a new element to the buffer, returning the index of the element+ uint16_t push(uint32_t value) {+ const auto index = count_++;+ assert(index < 4096 && "SmallValueBuffer can only hold up to 4096 chunks");+ if (index < buffer_.size()) {+ buffer_[index] = value;+ return index;+ }++ if (overflow_ == nullptr) {+ overflow_ = std::make_unique<SmallValueBuffer::Overflow>();+ }++ overflow_->buffer_.push_back(value);+ overflow_->wideElements_.push_back(false);+ return index;+ }++ uint16_t push(uint64_t value) {+ const auto lsb = static_cast<uint32_t>(value & 0xFFFFFFFF);+ const auto msb = static_cast<uint32_t>(value >> 32);++ const auto lsbIndex = push(lsb);+ [[maybe_unused]] const auto msbIndex = push(msb);+ assert(+ msbIndex < 4096 && "SmallValueBuffer can only hold up to 4096 chunks");++ if (lsbIndex < buffer_.size()) {+ wideElements_[lsbIndex] = true;+ } else {+ overflow_->wideElements_[lsbIndex - buffer_.size()] = true;+ }+ return lsbIndex;+ }++ // Replace an existing element in the buffer with a new value. A new index+ // may be returned, e.g. if a new value is wider than the previous.+ [[nodiscard]] uint16_t replace(uint16_t index, uint32_t value) {+ if (index < buffer_.size()) {+ buffer_[index] = value;+ } else {+ overflow_->buffer_.at(index - buffer_.size()) = value;+ }++ return index;+ }++ [[nodiscard]] uint16_t replace(uint16_t index, uint64_t value) {+ const bool isWide = index < wideElements_.size()+ ? wideElements_[index]+ : overflow_->wideElements_.at(index - buffer_.size());++ if (isWide) {+ const auto lsb = static_cast<uint32_t>(value & 0xFFFFFFFF);+ const auto msb = static_cast<uint32_t>(value >> 32);++ [[maybe_unused]] auto lsbIndex = replace(index, lsb);+ [[maybe_unused]] auto msbIndex = replace(index + 1, msb);+ return index;+ } else {+ return push(value);+ }+ }++ // Get a value of a given width+ uint32_t get32(uint16_t index) const {+ if (index < buffer_.size()) {+ return buffer_[index];+ } else {+ return overflow_->buffer_.at(index - buffer_.size());+ }+ }++ uint64_t get64(uint16_t index) const {+ const auto lsb = get32(index);+ const auto msb = get32(index + 1);+ return (static_cast<uint64_t>(msb) << 32) | lsb;+ }++ SmallValueBuffer& operator=(const SmallValueBuffer& other) {+ count_ = other.count_;+ buffer_ = other.buffer_;+ wideElements_ = other.wideElements_;+ overflow_ = other.overflow_ ? std::make_unique<Overflow>(*other.overflow_)+ : nullptr;+ return *this;+ }++ SmallValueBuffer& operator=(SmallValueBuffer&& other) noexcept = default;++ private:+ struct Overflow {+ std::vector<uint32_t> buffer_;+ std::vector<bool> wideElements_;+ };++ uint16_t count_{0};+ std::array<uint32_t, BufferSize> buffer_{};+ std::bitset<BufferSize> wideElements_;+ std::unique_ptr<Overflow> overflow_;+};++} // namespace facebook::yogadiff --git a/third_party/yoga/style/Style.h b/third_party/yoga/style/Style.hnew file mode 100644index 000000000..eedeaba2e--- /dev/null+++ b/third_party/yoga/style/Style.h@@ -0,0 +1,889 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <array>+#include <cstdint>+#include <type_traits>++#include <yoga/Yoga.h>++#include <yoga/algorithm/FlexDirection.h>+#include <yoga/enums/Align.h>+#include <yoga/enums/BoxSizing.h>+#include <yoga/enums/Dimension.h>+#include <yoga/enums/Direction.h>+#include <yoga/enums/Display.h>+#include <yoga/enums/Edge.h>+#include <yoga/enums/FlexDirection.h>+#include <yoga/enums/Gutter.h>+#include <yoga/enums/Justify.h>+#include <yoga/enums/Overflow.h>+#include <yoga/enums/PhysicalEdge.h>+#include <yoga/enums/PositionType.h>+#include <yoga/enums/Unit.h>+#include <yoga/enums/Wrap.h>+#include <yoga/numeric/FloatOptional.h>+#include <yoga/style/GridLine.h>+#include <yoga/style/GridTrack.h>+#include <yoga/style/StyleLength.h>+#include <yoga/style/StyleSizeLength.h>+#include <yoga/style/StyleValuePool.h>++namespace facebook::yoga {++class YG_EXPORT Style {+ public:+ using Length = StyleLength;+ using SizeLength = StyleSizeLength;++ static constexpr float DefaultFlexGrow = 0.0f;+ static constexpr float DefaultFlexShrink = 0.0f;+ static constexpr float WebDefaultFlexShrink = 1.0f;++ Direction direction() const {+ return direction_;+ }+ void setDirection(Direction value) {+ direction_ = value;+ }++ FlexDirection flexDirection() const {+ return flexDirection_;+ }+ void setFlexDirection(FlexDirection value) {+ flexDirection_ = value;+ }++ Justify justifyContent() const {+ return justifyContent_;+ }+ void setJustifyContent(Justify value) {+ justifyContent_ = value;+ }++ Justify justifyItems() const {+ return justifyItems_;+ }+ void setJustifyItems(Justify value) {+ justifyItems_ = value;+ }++ Justify justifySelf() const {+ return justifySelf_;+ }+ void setJustifySelf(Justify value) {+ justifySelf_ = value;+ }++ Align alignContent() const {+ return alignContent_;+ }+ void setAlignContent(Align value) {+ alignContent_ = value;+ }++ Align alignItems() const {+ return alignItems_;+ }+ void setAlignItems(Align value) {+ alignItems_ = value;+ }++ Align alignSelf() const {+ return alignSelf_;+ }+ void setAlignSelf(Align value) {+ alignSelf_ = value;+ }++ PositionType positionType() const {+ return positionType_;+ }+ void setPositionType(PositionType value) {+ positionType_ = value;+ }++ Wrap flexWrap() const {+ return flexWrap_;+ }+ void setFlexWrap(Wrap value) {+ flexWrap_ = value;+ }++ Overflow overflow() const {+ return overflow_;+ }+ void setOverflow(Overflow value) {+ overflow_ = value;+ }++ Display display() const {+ return display_;+ }+ void setDisplay(Display value) {+ display_ = value;+ }++ FloatOptional flex() const {+ return pool_.getNumber(flex_);+ }+ void setFlex(FloatOptional value) {+ pool_.store(flex_, value);+ }++ FloatOptional flexGrow() const {+ return pool_.getNumber(flexGrow_);+ }+ void setFlexGrow(FloatOptional value) {+ pool_.store(flexGrow_, value);+ }++ FloatOptional flexShrink() const {+ return pool_.getNumber(flexShrink_);+ }+ void setFlexShrink(FloatOptional value) {+ pool_.store(flexShrink_, value);+ }++ Style::SizeLength flexBasis() const {+ return pool_.getSize(flexBasis_);+ }+ void setFlexBasis(Style::SizeLength value) {+ pool_.store(flexBasis_, value);+ }++ Style::Length margin(Edge edge) const {+ return pool_.getLength(margin_[yoga::to_underlying(edge)]);+ }+ void setMargin(Edge edge, Style::Length value) {+ pool_.store(margin_[yoga::to_underlying(edge)], value);+ }++ Style::Length position(Edge edge) const {+ return pool_.getLength(position_[yoga::to_underlying(edge)]);+ }+ void setPosition(Edge edge, Style::Length value) {+ pool_.store(position_[yoga::to_underlying(edge)], value);+ }++ Style::Length padding(Edge edge) const {+ return pool_.getLength(padding_[yoga::to_underlying(edge)]);+ }+ void setPadding(Edge edge, Style::Length value) {+ pool_.store(padding_[yoga::to_underlying(edge)], value);+ }++ Style::Length border(Edge edge) const {+ return pool_.getLength(border_[yoga::to_underlying(edge)]);+ }+ void setBorder(Edge edge, Style::Length value) {+ pool_.store(border_[yoga::to_underlying(edge)], value);+ }++ Style::Length gap(Gutter gutter) const {+ return pool_.getLength(gap_[yoga::to_underlying(gutter)]);+ }+ void setGap(Gutter gutter, Style::Length value) {+ pool_.store(gap_[yoga::to_underlying(gutter)], value);+ }++ Style::SizeLength dimension(Dimension axis) const {+ return pool_.getSize(dimensions_[yoga::to_underlying(axis)]);+ }+ void setDimension(Dimension axis, Style::SizeLength value) {+ pool_.store(dimensions_[yoga::to_underlying(axis)], value);+ }++ Style::SizeLength minDimension(Dimension axis) const {+ return pool_.getSize(minDimensions_[yoga::to_underlying(axis)]);+ }+ void setMinDimension(Dimension axis, Style::SizeLength value) {+ pool_.store(minDimensions_[yoga::to_underlying(axis)], value);+ }++ // Grid Container Properties+ const GridTrackList& gridTemplateColumns() const {+ return gridTemplateColumns_;+ }+ void setGridTemplateColumns(GridTrackList value) {+ gridTemplateColumns_ = std::move(value);+ }+ void resizeGridTemplateColumns(size_t count) {+ gridTemplateColumns_.resize(count);+ }+ void setGridTemplateColumnAt(size_t index, GridTrackSize value) {+ gridTemplateColumns_[index] = value;+ }++ const GridTrackList& gridTemplateRows() const {+ return gridTemplateRows_;+ }+ void setGridTemplateRows(GridTrackList value) {+ gridTemplateRows_ = std::move(value);+ }+ void resizeGridTemplateRows(size_t count) {+ gridTemplateRows_.resize(count);+ }+ void setGridTemplateRowAt(size_t index, GridTrackSize value) {+ gridTemplateRows_[index] = value;+ }++ const GridTrackList& gridAutoColumns() const {+ return gridAutoColumns_;+ }+ void setGridAutoColumns(GridTrackList value) {+ gridAutoColumns_ = std::move(value);+ }+ void resizeGridAutoColumns(size_t count) {+ gridAutoColumns_.resize(count);+ }+ void setGridAutoColumnAt(size_t index, GridTrackSize value) {+ gridAutoColumns_[index] = value;+ }++ const GridTrackList& gridAutoRows() const {+ return gridAutoRows_;+ }+ void setGridAutoRows(GridTrackList value) {+ gridAutoRows_ = std::move(value);+ }+ void resizeGridAutoRows(size_t count) {+ gridAutoRows_.resize(count);+ }+ void setGridAutoRowAt(size_t index, GridTrackSize value) {+ gridAutoRows_[index] = value;+ }++ // Grid Item Properties+ const GridLine& gridColumnStart() const {+ return gridColumnStart_;+ }+ void setGridColumnStart(GridLine value) {+ gridColumnStart_ = value;+ }++ const GridLine& gridColumnEnd() const {+ return gridColumnEnd_;+ }+ void setGridColumnEnd(GridLine value) {+ gridColumnEnd_ = value;+ }++ const GridLine& gridRowStart() const {+ return gridRowStart_;+ }+ void setGridRowStart(GridLine value) {+ gridRowStart_ = value;+ }++ const GridLine& gridRowEnd() const {+ return gridRowEnd_;+ }+ void setGridRowEnd(GridLine value) {+ gridRowEnd_ = value;+ }++ FloatOptional resolvedMinDimension(+ Direction direction,+ Dimension axis,+ float referenceLength,+ float ownerWidth) const {+ FloatOptional value = minDimension(axis).resolve(referenceLength);+ if (boxSizing() == BoxSizing::BorderBox) {+ return value;+ }++ FloatOptional dimensionPaddingAndBorder = FloatOptional{+ computePaddingAndBorderForDimension(direction, axis, ownerWidth)};++ return value ++ (dimensionPaddingAndBorder.isDefined() ? dimensionPaddingAndBorder+ : FloatOptional{0.0});+ }++ Style::SizeLength maxDimension(Dimension axis) const {+ return pool_.getSize(maxDimensions_[yoga::to_underlying(axis)]);+ }+ void setMaxDimension(Dimension axis, Style::SizeLength value) {+ pool_.store(maxDimensions_[yoga::to_underlying(axis)], value);+ }++ FloatOptional resolvedMaxDimension(+ Direction direction,+ Dimension axis,+ float referenceLength,+ float ownerWidth) const {+ FloatOptional value = maxDimension(axis).resolve(referenceLength);+ if (boxSizing() == BoxSizing::BorderBox) {+ return value;+ }++ FloatOptional dimensionPaddingAndBorder = FloatOptional{+ computePaddingAndBorderForDimension(direction, axis, ownerWidth)};++ return value ++ (dimensionPaddingAndBorder.isDefined() ? dimensionPaddingAndBorder+ : FloatOptional{0.0});+ }++ FloatOptional aspectRatio() const {+ return pool_.getNumber(aspectRatio_);+ }+ void setAspectRatio(FloatOptional value) {+ // degenerate aspect ratios act as auto.+ // see https://drafts.csswg.org/css-sizing-4/#valdef-aspect-ratio-ratio+ pool_.store(+ aspectRatio_,+ value == 0.0f || std::isinf(value.unwrap()) ? FloatOptional{} : value);+ }++ BoxSizing boxSizing() const {+ return boxSizing_;+ }+ void setBoxSizing(BoxSizing value) {+ boxSizing_ = value;+ }++ bool horizontalInsetsDefined() const {+ return position_[yoga::to_underlying(Edge::Left)].isDefined() ||+ position_[yoga::to_underlying(Edge::Right)].isDefined() ||+ position_[yoga::to_underlying(Edge::All)].isDefined() ||+ position_[yoga::to_underlying(Edge::Horizontal)].isDefined() ||+ position_[yoga::to_underlying(Edge::Start)].isDefined() ||+ position_[yoga::to_underlying(Edge::End)].isDefined();+ }++ bool verticalInsetsDefined() const {+ return position_[yoga::to_underlying(Edge::Top)].isDefined() ||+ position_[yoga::to_underlying(Edge::Bottom)].isDefined() ||+ position_[yoga::to_underlying(Edge::All)].isDefined() ||+ position_[yoga::to_underlying(Edge::Vertical)].isDefined();+ }++ bool isFlexStartPositionDefined(FlexDirection axis, Direction direction)+ const {+ return computePosition(flexStartEdge(axis), direction).isDefined();+ }++ bool isFlexStartPositionAuto(FlexDirection axis, Direction direction) const {+ return computePosition(flexStartEdge(axis), direction).isAuto();+ }++ bool isInlineStartPositionDefined(FlexDirection axis, Direction direction)+ const {+ return computePosition(inlineStartEdge(axis, direction), direction)+ .isDefined();+ }++ bool isInlineStartPositionAuto(FlexDirection axis, Direction direction)+ const {+ return computePosition(inlineStartEdge(axis, direction), direction)+ .isAuto();+ }++ bool isFlexEndPositionDefined(FlexDirection axis, Direction direction) const {+ return computePosition(flexEndEdge(axis), direction).isDefined();+ }++ bool isFlexEndPositionAuto(FlexDirection axis, Direction direction) const {+ return computePosition(flexEndEdge(axis), direction).isAuto();+ }++ bool isInlineEndPositionDefined(FlexDirection axis, Direction direction)+ const {+ return computePosition(inlineEndEdge(axis, direction), direction)+ .isDefined();+ }++ bool isInlineEndPositionAuto(FlexDirection axis, Direction direction) const {+ return computePosition(inlineEndEdge(axis, direction), direction).isAuto();+ }++ float computeFlexStartPosition(+ FlexDirection axis,+ Direction direction,+ float axisSize) const {+ return computePosition(flexStartEdge(axis), direction)+ .resolve(axisSize)+ .unwrapOrDefault(0.0f);+ }++ float computeInlineStartPosition(+ FlexDirection axis,+ Direction direction,+ float axisSize) const {+ return computePosition(inlineStartEdge(axis, direction), direction)+ .resolve(axisSize)+ .unwrapOrDefault(0.0f);+ }++ float computeFlexEndPosition(+ FlexDirection axis,+ Direction direction,+ float axisSize) const {+ return computePosition(flexEndEdge(axis), direction)+ .resolve(axisSize)+ .unwrapOrDefault(0.0f);+ }++ float computeInlineEndPosition(+ FlexDirection axis,+ Direction direction,+ float axisSize) const {+ return computePosition(inlineEndEdge(axis, direction), direction)+ .resolve(axisSize)+ .unwrapOrDefault(0.0f);+ }++ float computeFlexStartMargin(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return computeMargin(flexStartEdge(axis), direction)+ .resolve(widthSize)+ .unwrapOrDefault(0.0f);+ }++ float computeInlineStartMargin(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return computeMargin(inlineStartEdge(axis, direction), direction)+ .resolve(widthSize)+ .unwrapOrDefault(0.0f);+ }++ float computeFlexEndMargin(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return computeMargin(flexEndEdge(axis), direction)+ .resolve(widthSize)+ .unwrapOrDefault(0.0f);+ }++ float computeInlineEndMargin(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return computeMargin(inlineEndEdge(axis, direction), direction)+ .resolve(widthSize)+ .unwrapOrDefault(0.0f);+ }++ float computeFlexStartBorder(FlexDirection axis, Direction direction) const {+ return maxOrDefined(+ computeBorder(flexStartEdge(axis), direction).resolve(0.0f).unwrap(),+ 0.0f);+ }++ float computeInlineStartBorder(FlexDirection axis, Direction direction)+ const {+ return maxOrDefined(+ computeBorder(inlineStartEdge(axis, direction), direction)+ .resolve(0.0f)+ .unwrap(),+ 0.0f);+ }++ float computeFlexEndBorder(FlexDirection axis, Direction direction) const {+ return maxOrDefined(+ computeBorder(flexEndEdge(axis), direction).resolve(0.0f).unwrap(),+ 0.0f);+ }++ float computeInlineEndBorder(FlexDirection axis, Direction direction) const {+ return maxOrDefined(+ computeBorder(inlineEndEdge(axis, direction), direction)+ .resolve(0.0f)+ .unwrap(),+ 0.0f);+ }++ float computeFlexStartPadding(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return maxOrDefined(+ computePadding(flexStartEdge(axis), direction)+ .resolve(widthSize)+ .unwrap(),+ 0.0f);+ }++ float computeInlineStartPadding(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return maxOrDefined(+ computePadding(inlineStartEdge(axis, direction), direction)+ .resolve(widthSize)+ .unwrap(),+ 0.0f);+ }++ float computeFlexEndPadding(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return maxOrDefined(+ computePadding(flexEndEdge(axis), direction)+ .resolve(widthSize)+ .unwrap(),+ 0.0f);+ }++ float computeInlineEndPadding(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return maxOrDefined(+ computePadding(inlineEndEdge(axis, direction), direction)+ .resolve(widthSize)+ .unwrap(),+ 0.0f);+ }++ float computeInlineStartPaddingAndBorder(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return computeInlineStartPadding(axis, direction, widthSize) ++ computeInlineStartBorder(axis, direction);+ }++ float computeFlexStartPaddingAndBorder(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return computeFlexStartPadding(axis, direction, widthSize) ++ computeFlexStartBorder(axis, direction);+ }++ float computeInlineEndPaddingAndBorder(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return computeInlineEndPadding(axis, direction, widthSize) ++ computeInlineEndBorder(axis, direction);+ }++ float computeFlexEndPaddingAndBorder(+ FlexDirection axis,+ Direction direction,+ float widthSize) const {+ return computeFlexEndPadding(axis, direction, widthSize) ++ computeFlexEndBorder(axis, direction);+ }++ float computePaddingAndBorderForDimension(+ Direction direction,+ Dimension dimension,+ float widthSize) const {+ FlexDirection flexDirectionForDimension = dimension == Dimension::Width+ ? FlexDirection::Row+ : FlexDirection::Column;++ return computeFlexStartPaddingAndBorder(+ flexDirectionForDimension, direction, widthSize) ++ computeFlexEndPaddingAndBorder(+ flexDirectionForDimension, direction, widthSize);+ }++ float computeBorderForAxis(FlexDirection axis) const {+ return computeInlineStartBorder(axis, Direction::LTR) ++ computeInlineEndBorder(axis, Direction::LTR);+ }++ float computeMarginForAxis(FlexDirection axis, float widthSize) const {+ // The total margin for a given axis does not depend on the direction+ // so hardcoding LTR here to avoid piping direction to this function+ return computeInlineStartMargin(axis, Direction::LTR, widthSize) ++ computeInlineEndMargin(axis, Direction::LTR, widthSize);+ }++ float computeGapForAxis(FlexDirection axis, float ownerSize) const {+ auto gap = isRow(axis) ? computeColumnGap() : computeRowGap();+ return maxOrDefined(gap.resolve(ownerSize).unwrap(), 0.0f);+ }++ float computeGapForDimension(Dimension dimension, float ownerSize) const {+ auto gap =+ dimension == Dimension::Width ? computeColumnGap() : computeRowGap();+ return maxOrDefined(gap.resolve(ownerSize).unwrap(), 0.0f);+ }++ bool flexStartMarginIsAuto(FlexDirection axis, Direction direction) const {+ return computeMargin(flexStartEdge(axis), direction).isAuto();+ }++ bool flexEndMarginIsAuto(FlexDirection axis, Direction direction) const {+ return computeMargin(flexEndEdge(axis), direction).isAuto();+ }++ bool inlineStartMarginIsAuto(FlexDirection axis, Direction direction) const {+ return computeMargin(inlineStartEdge(axis, direction), direction).isAuto();+ }++ bool inlineEndMarginIsAuto(FlexDirection axis, Direction direction) const {+ return computeMargin(inlineEndEdge(axis, direction), direction).isAuto();+ }++ bool operator==(const Style& other) const {+ return direction_ == other.direction_ &&+ flexDirection_ == other.flexDirection_ &&+ justifyContent_ == other.justifyContent_ &&+ justifyItems_ == other.justifyItems_ &&+ justifySelf_ == other.justifySelf_ &&+ alignContent_ == other.alignContent_ &&+ alignItems_ == other.alignItems_ && alignSelf_ == other.alignSelf_ &&+ positionType_ == other.positionType_ && flexWrap_ == other.flexWrap_ &&+ overflow_ == other.overflow_ && display_ == other.display_ &&+ numbersEqual(flex_, pool_, other.flex_, other.pool_) &&+ numbersEqual(flexGrow_, pool_, other.flexGrow_, other.pool_) &&+ numbersEqual(flexShrink_, pool_, other.flexShrink_, other.pool_) &&+ lengthsEqual(flexBasis_, pool_, other.flexBasis_, other.pool_) &&+ lengthsEqual(margin_, pool_, other.margin_, other.pool_) &&+ lengthsEqual(position_, pool_, other.position_, other.pool_) &&+ lengthsEqual(padding_, pool_, other.padding_, other.pool_) &&+ lengthsEqual(border_, pool_, other.border_, other.pool_) &&+ lengthsEqual(gap_, pool_, other.gap_, other.pool_) &&+ lengthsEqual(dimensions_, pool_, other.dimensions_, other.pool_) &&+ lengthsEqual(+ minDimensions_, pool_, other.minDimensions_, other.pool_) &&+ lengthsEqual(+ maxDimensions_, pool_, other.maxDimensions_, other.pool_) &&+ numbersEqual(aspectRatio_, pool_, other.aspectRatio_, other.pool_) &&+ gridTemplateColumns_ == other.gridTemplateColumns_ &&+ gridTemplateRows_ == other.gridTemplateRows_ &&+ gridAutoColumns_ == other.gridAutoColumns_ &&+ gridAutoRows_ == other.gridAutoRows_ &&+ gridColumnStart_ == other.gridColumnStart_ &&+ gridColumnEnd_ == other.gridColumnEnd_ &&+ gridRowStart_ == other.gridRowStart_ &&+ gridRowEnd_ == other.gridRowEnd_;+ }++ private:+ using Dimensions = std::array<StyleValueHandle, ordinalCount<Dimension>()>;+ using Edges = std::array<StyleValueHandle, ordinalCount<Edge>()>;+ using Gutters = std::array<StyleValueHandle, ordinalCount<Gutter>()>;++ static inline bool numbersEqual(+ const StyleValueHandle& lhsHandle,+ const StyleValuePool& lhsPool,+ const StyleValueHandle& rhsHandle,+ const StyleValuePool& rhsPool) {+ return (lhsHandle.isUndefined() && rhsHandle.isUndefined()) ||+ (lhsPool.getNumber(lhsHandle) == rhsPool.getNumber(rhsHandle));+ }++ static inline bool lengthsEqual(+ const StyleValueHandle& lhsHandle,+ const StyleValuePool& lhsPool,+ const StyleValueHandle& rhsHandle,+ const StyleValuePool& rhsPool) {+ return (lhsHandle.isUndefined() && rhsHandle.isUndefined()) ||+ (lhsPool.getLength(lhsHandle) == rhsPool.getLength(rhsHandle));+ }++ template <size_t N>+ static inline bool lengthsEqual(+ const std::array<StyleValueHandle, N>& lhs,+ const StyleValuePool& lhsPool,+ const std::array<StyleValueHandle, N>& rhs,+ const StyleValuePool& rhsPool) {+ return std::equal(+ lhs.begin(),+ lhs.end(),+ rhs.begin(),+ rhs.end(),+ [&](const auto& lhs, const auto& rhs) {+ return lengthsEqual(lhs, lhsPool, rhs, rhsPool);+ });+ }++ Style::Length computeColumnGap() const {+ if (gap_[yoga::to_underlying(Gutter::Column)].isDefined()) {+ return pool_.getLength(gap_[yoga::to_underlying(Gutter::Column)]);+ } else {+ return pool_.getLength(gap_[yoga::to_underlying(Gutter::All)]);+ }+ }++ Style::Length computeRowGap() const {+ if (gap_[yoga::to_underlying(Gutter::Row)].isDefined()) {+ return pool_.getLength(gap_[yoga::to_underlying(Gutter::Row)]);+ } else {+ return pool_.getLength(gap_[yoga::to_underlying(Gutter::All)]);+ }+ }++ Style::Length computeLeftEdge(const Edges& edges, Direction layoutDirection)+ const {+ if (layoutDirection == Direction::LTR &&+ edges[yoga::to_underlying(Edge::Start)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Start)]);+ } else if (+ layoutDirection == Direction::RTL &&+ edges[yoga::to_underlying(Edge::End)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::End)]);+ } else if (edges[yoga::to_underlying(Edge::Left)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Left)]);+ } else if (edges[yoga::to_underlying(Edge::Horizontal)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Horizontal)]);+ } else {+ return pool_.getLength(edges[yoga::to_underlying(Edge::All)]);+ }+ }++ Style::Length computeTopEdge(const Edges& edges) const {+ if (edges[yoga::to_underlying(Edge::Top)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Top)]);+ } else if (edges[yoga::to_underlying(Edge::Vertical)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Vertical)]);+ } else {+ return pool_.getLength(edges[yoga::to_underlying(Edge::All)]);+ }+ }++ Style::Length computeRightEdge(const Edges& edges, Direction layoutDirection)+ const {+ if (layoutDirection == Direction::LTR &&+ edges[yoga::to_underlying(Edge::End)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::End)]);+ } else if (+ layoutDirection == Direction::RTL &&+ edges[yoga::to_underlying(Edge::Start)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Start)]);+ } else if (edges[yoga::to_underlying(Edge::Right)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Right)]);+ } else if (edges[yoga::to_underlying(Edge::Horizontal)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Horizontal)]);+ } else {+ return pool_.getLength(edges[yoga::to_underlying(Edge::All)]);+ }+ }++ Style::Length computeBottomEdge(const Edges& edges) const {+ if (edges[yoga::to_underlying(Edge::Bottom)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Bottom)]);+ } else if (edges[yoga::to_underlying(Edge::Vertical)].isDefined()) {+ return pool_.getLength(edges[yoga::to_underlying(Edge::Vertical)]);+ } else {+ return pool_.getLength(edges[yoga::to_underlying(Edge::All)]);+ }+ }++ Style::Length computePosition(PhysicalEdge edge, Direction direction) const {+ switch (edge) {+ case PhysicalEdge::Left:+ return computeLeftEdge(position_, direction);+ case PhysicalEdge::Top:+ return computeTopEdge(position_);+ case PhysicalEdge::Right:+ return computeRightEdge(position_, direction);+ case PhysicalEdge::Bottom:+ return computeBottomEdge(position_);+ default:+ fatalWithMessage("Invalid physical edge");+ }+ }++ Style::Length computeMargin(PhysicalEdge edge, Direction direction) const {+ switch (edge) {+ case PhysicalEdge::Left:+ return computeLeftEdge(margin_, direction);+ case PhysicalEdge::Top:+ return computeTopEdge(margin_);+ case PhysicalEdge::Right:+ return computeRightEdge(margin_, direction);+ case PhysicalEdge::Bottom:+ return computeBottomEdge(margin_);+ default:+ fatalWithMessage("Invalid physical edge");+ }+ }++ Style::Length computePadding(PhysicalEdge edge, Direction direction) const {+ switch (edge) {+ case PhysicalEdge::Left:+ return computeLeftEdge(padding_, direction);+ case PhysicalEdge::Top:+ return computeTopEdge(padding_);+ case PhysicalEdge::Right:+ return computeRightEdge(padding_, direction);+ case PhysicalEdge::Bottom:+ return computeBottomEdge(padding_);+ default:+ fatalWithMessage("Invalid physical edge");+ }+ }++ Style::Length computeBorder(PhysicalEdge edge, Direction direction) const {+ switch (edge) {+ case PhysicalEdge::Left:+ return computeLeftEdge(border_, direction);+ case PhysicalEdge::Top:+ return computeTopEdge(border_);+ case PhysicalEdge::Right:+ return computeRightEdge(border_, direction);+ case PhysicalEdge::Bottom:+ return computeBottomEdge(border_);+ default:+ fatalWithMessage("Invalid physical edge");+ }+ }++ Direction direction_ : bitCount<Direction>() = Direction::Inherit;+ FlexDirection flexDirection_+ : bitCount<FlexDirection>() = FlexDirection::Column;+ Justify justifyContent_ : bitCount<Justify>() = Justify::FlexStart;+ Justify justifyItems_ : bitCount<Justify>() = Justify::Stretch;+ Justify justifySelf_ : bitCount<Justify>() = Justify::Auto;+ Align alignContent_ : bitCount<Align>() = Align::FlexStart;+ Align alignItems_ : bitCount<Align>() = Align::Stretch;+ Align alignSelf_ : bitCount<Align>() = Align::Auto;+ PositionType positionType_+ : bitCount<PositionType>() = PositionType::Relative;+ Wrap flexWrap_ : bitCount<Wrap>() = Wrap::NoWrap;+ Overflow overflow_ : bitCount<Overflow>() = Overflow::Visible;+ Display display_ : bitCount<Display>() = Display::Flex;+ BoxSizing boxSizing_ : bitCount<BoxSizing>() = BoxSizing::BorderBox;++ StyleValueHandle flex_{};+ StyleValueHandle flexGrow_{};+ StyleValueHandle flexShrink_{};+ StyleValueHandle flexBasis_{StyleValueHandle::ofAuto()};+ Edges margin_{};+ Edges position_{};+ Edges padding_{};+ Edges border_{};+ Gutters gap_{};+ Dimensions dimensions_{+ StyleValueHandle::ofAuto(),+ StyleValueHandle::ofAuto()};+ Dimensions minDimensions_{};+ Dimensions maxDimensions_{};+ StyleValueHandle aspectRatio_{};++ // Grid properties+ GridTrackList gridTemplateColumns_{};+ GridTrackList gridTemplateRows_{};+ GridTrackList gridAutoColumns_{};+ GridTrackList gridAutoRows_{};+ GridLine gridColumnStart_{};+ GridLine gridColumnEnd_{};+ GridLine gridRowStart_{};+ GridLine gridRowEnd_{};++ StyleValuePool pool_;+};++} // namespace facebook::yogadiff --git a/third_party/yoga/style/StyleLength.h b/third_party/yoga/style/StyleLength.hnew file mode 100644index 000000000..8099ce7df--- /dev/null+++ b/third_party/yoga/style/StyleLength.h@@ -0,0 +1,121 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/enums/Unit.h>+#include <yoga/numeric/FloatOptional.h>++namespace facebook::yoga {++/**+ * Style::Length represents a CSS Value which may be one of:+ * 1. Undefined+ * 2. A keyword (e.g. auto)+ * 3. A CSS <length-percentage> value:+ * a. <length> value (e.g. 10px)+ * b. <percentage> value of a reference <length>+ *+ * References:+ * 1. https://www.w3.org/TR/css-values-4/#lengths+ * 2. https://www.w3.org/TR/css-values-4/#percentage-value+ * 3. https://www.w3.org/TR/css-values-4/#mixed-percentages+ */+class StyleLength {+ public:+ constexpr StyleLength() = default;++ constexpr static StyleLength points(float value) {+ return yoga::isUndefined(value) || yoga::isinf(value)+ ? undefined()+ : StyleLength{FloatOptional{value}, Unit::Point};+ }++ constexpr static StyleLength percent(float value) {+ return yoga::isUndefined(value) || yoga::isinf(value)+ ? undefined()+ : StyleLength{FloatOptional{value}, Unit::Percent};+ }++ constexpr static StyleLength ofAuto() {+ return StyleLength{{}, Unit::Auto};+ }++ constexpr static StyleLength undefined() {+ return StyleLength{{}, Unit::Undefined};+ }++ constexpr bool isAuto() const {+ return unit_ == Unit::Auto;+ }++ constexpr bool isUndefined() const {+ return unit_ == Unit::Undefined;+ }++ constexpr bool isPoints() const {+ return unit_ == Unit::Point;+ }++ constexpr bool isPercent() const {+ return unit_ == Unit::Percent;+ }++ constexpr bool isDefined() const {+ return !isUndefined();+ }++ constexpr FloatOptional value() const {+ return value_;+ }++ constexpr FloatOptional resolve(float referenceLength) {+#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wswitch-enum"+#endif+ switch (unit_) {+#ifdef __clang__+#pragma clang diagnostic pop+#endif+ case Unit::Point:+ return value_;+ case Unit::Percent:+ return FloatOptional{value_.unwrap() * referenceLength * 0.01f};+ default:+ return FloatOptional{};+ }+ }++ explicit constexpr operator YGValue() const {+ return YGValue{value_.unwrap(), unscopedEnum(unit_)};+ }++ constexpr bool operator==(const StyleLength& rhs) const {+ return value_ == rhs.value_ && unit_ == rhs.unit_;+ }++ constexpr bool inexactEquals(const StyleLength& other) const {+ return unit_ == other.unit_ &&+ facebook::yoga::inexactEquals(value_, other.value_);+ }++ private:+ // We intentionally do not allow direct construction using value and unit, to+ // avoid invalid, or redundant combinations.+ constexpr StyleLength(FloatOptional value, Unit unit)+ : value_(value), unit_(unit) {}++ FloatOptional value_{};+ Unit unit_{Unit::Undefined};+};++inline bool inexactEquals(const StyleLength& a, const StyleLength& b) {+ return a.inexactEquals(b);+}++} // namespace facebook::yogadiff --git a/third_party/yoga/style/StyleSizeLength.h b/third_party/yoga/style/StyleSizeLength.hnew file mode 100644index 000000000..76e079b2d--- /dev/null+++ b/third_party/yoga/style/StyleSizeLength.h@@ -0,0 +1,152 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <yoga/enums/Unit.h>+#include <yoga/numeric/FloatOptional.h>++namespace facebook::yoga {++/**+ * This class represents a CSS Value for sizes (e.g. width, height, min-width,+ * etc.). It may be one of:+ * 1. Undefined+ * 2. A keyword (e.g. auto, max-content, stretch, etc.)+ * 3. A CSS <length-percentage> value:+ * a. <length> value (e.g. 10px)+ * b. <percentage> value of a reference <length>+ *+ * References:+ * 1. https://www.w3.org/TR/css-values-4/#lengths+ * 2. https://www.w3.org/TR/css-values-4/#percentage-value+ * 3. https://www.w3.org/TR/css-values-4/#mixed-percentages+ */+class StyleSizeLength {+ public:+ constexpr StyleSizeLength() = default;++ constexpr static StyleSizeLength points(float value) {+ return yoga::isUndefined(value) || yoga::isinf(value)+ ? undefined()+ : StyleSizeLength{FloatOptional{value}, Unit::Point};+ }++ constexpr static StyleSizeLength percent(float value) {+ return yoga::isUndefined(value) || yoga::isinf(value)+ ? undefined()+ : StyleSizeLength{FloatOptional{value}, Unit::Percent};+ }++ constexpr static StyleSizeLength stretch(float fraction) {+ return yoga::isUndefined(fraction) || yoga::isinf(fraction)+ ? undefined()+ : StyleSizeLength{FloatOptional{fraction}, Unit::Stretch};+ }++ constexpr static StyleSizeLength ofAuto() {+ return StyleSizeLength{{}, Unit::Auto};+ }++ constexpr static StyleSizeLength ofMaxContent() {+ return StyleSizeLength{{}, Unit::MaxContent};+ }++ constexpr static StyleSizeLength ofFitContent() {+ return StyleSizeLength{{}, Unit::FitContent};+ }++ constexpr static StyleSizeLength ofStretch() {+ return StyleSizeLength{{}, Unit::Stretch};+ }++ constexpr static StyleSizeLength undefined() {+ return StyleSizeLength{{}, Unit::Undefined};+ }++ constexpr bool isAuto() const {+ return unit_ == Unit::Auto;+ }++ constexpr bool isMaxContent() const {+ return unit_ == Unit::MaxContent;+ }++ constexpr bool isFitContent() const {+ return unit_ == Unit::FitContent;+ }++ constexpr bool isStretch() const {+ return unit_ == Unit::Stretch;+ }++ constexpr bool isUndefined() const {+ return unit_ == Unit::Undefined;+ }++ constexpr bool isDefined() const {+ return !isUndefined();+ }++ constexpr bool isPoints() const {+ return unit_ == Unit::Point;+ }++ constexpr bool isPercent() const {+ return unit_ == Unit::Percent;+ }++ constexpr FloatOptional value() const {+ return value_;+ }++ constexpr FloatOptional resolve(float referenceLength) const {+#ifdef __clang__+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wswitch-enum"+#endif+ switch (unit_) {+#ifdef __clang__+#pragma clang diagnostic pop+#endif+ case Unit::Point:+ return value_;+ case Unit::Percent:+ return FloatOptional{value_.unwrap() * referenceLength * 0.01f};+ default:+ return FloatOptional{};+ }+ }++ explicit constexpr operator YGValue() const {+ return YGValue{value_.unwrap(), unscopedEnum(unit_)};+ }++ constexpr bool operator==(const StyleSizeLength& rhs) const {+ return value_ == rhs.value_ && unit_ == rhs.unit_;+ }++ constexpr bool inexactEquals(const StyleSizeLength& other) const {+ return unit_ == other.unit_ &&+ facebook::yoga::inexactEquals(value_, other.value_);+ }++ private:+ // We intentionally do not allow direct construction using value and unit, to+ // avoid invalid, or redundant combinations.+ constexpr StyleSizeLength(FloatOptional value, Unit unit)+ : value_(value), unit_(unit) {}++ FloatOptional value_{};+ Unit unit_{Unit::Undefined};+};++inline bool inexactEquals(const StyleSizeLength& a, const StyleSizeLength& b) {+ return a.inexactEquals(b);+}++} // namespace facebook::yogadiff --git a/third_party/yoga/style/StyleValueHandle.h b/third_party/yoga/style/StyleValueHandle.hnew file mode 100644index 000000000..d9c6ae057--- /dev/null+++ b/third_party/yoga/style/StyleValueHandle.h@@ -0,0 +1,106 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <cstdint>++#include <yoga/Yoga.h>++#include <yoga/numeric/FloatOptional.h>+#include <yoga/style/SmallValueBuffer.h>+#include <yoga/style/StyleLength.h>++namespace facebook::yoga {++#pragma pack(push)+#pragma pack(1)++/**+ * StyleValueHandle is a small (16-bit) handle to a length or number in a style.+ * The value may be embedded directly in the handle if simple, or the handle may+ * instead point to an index within a StyleValuePool.+ *+ * To read or write a value from a StyleValueHandle, use+ * `StyleValuePool::store()`, and `StyleValuePool::getLength()`/+ * `StyleValuePool::getNumber()`.+ */+class StyleValueHandle {+ public:+ static constexpr StyleValueHandle ofAuto() {+ StyleValueHandle handle;+ handle.setType(Type::Auto);+ return handle;+ }++ constexpr bool isUndefined() const {+ return type() == Type::Undefined;+ }++ constexpr bool isDefined() const {+ return !isUndefined();+ }++ constexpr bool isAuto() const {+ return type() == Type::Auto;+ }++ private:+ friend class StyleValuePool;++ static constexpr uint16_t kHandleTypeMask = 0b0000'0000'0000'0111;+ static constexpr uint16_t kHandleIndexedMask = 0b0000'0000'0000'1000;+ static constexpr uint16_t kHandleValueMask = 0b1111'1111'1111'0000;++ enum class Type : uint8_t {+ Undefined,+ Point,+ Percent,+ Number,+ Auto,+ Keyword+ };++ // Intentionally leaving out auto as a fast path+ enum class Keyword : uint8_t { MaxContent, FitContent, Stretch };++ constexpr bool isKeyword(Keyword keyword) const {+ return type() == Type::Keyword && value() == static_cast<uint16_t>(keyword);+ }++ constexpr Type type() const {+ return static_cast<Type>(repr_ & kHandleTypeMask);+ }++ constexpr void setType(Type handleType) {+ repr_ &= (~kHandleTypeMask);+ repr_ |= static_cast<uint8_t>(handleType);+ }++ constexpr uint16_t value() const {+ return repr_ >> 4;+ }++ constexpr void setValue(uint16_t value) {+ repr_ &= (~kHandleValueMask);+ repr_ |= (value << 4);+ }++ constexpr bool isValueIndexed() const {+ return (repr_ & kHandleIndexedMask) != 0;+ }++ constexpr void setValueIsIndexed() {+ repr_ |= kHandleIndexedMask;+ }++ uint16_t repr_{0};+};++#pragma pack(pop)++} // namespace facebook::yogadiff --git a/third_party/yoga/style/StyleValuePool.h b/third_party/yoga/style/StyleValuePool.hnew file mode 100644index 000000000..dfee30ade--- /dev/null+++ b/third_party/yoga/style/StyleValuePool.h@@ -0,0 +1,184 @@+/*+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */++#pragma once++#include <cassert>+#include <cstdint>++#include <yoga/numeric/FloatOptional.h>+#include <yoga/style/SmallValueBuffer.h>+#include <yoga/style/StyleLength.h>+#include <yoga/style/StyleSizeLength.h>+#include <yoga/style/StyleValueHandle.h>++namespace facebook::yoga {++/**+ * StyleValuePool allows compact storage for a sparse collection of assigned+ * lengths and numbers. Values are referred to using StyleValueHandle. In most+ * cases StyleValueHandle can embed the value directly, but if not, the value is+ * stored within a buffer provided by the pool. The pool contains a fixed number+ * of inline slots before falling back to heap allocating additional slots.+ */+class StyleValuePool {+ public:+ void store(StyleValueHandle& handle, StyleLength length) {+ if (length.isUndefined()) {+ handle.setType(StyleValueHandle::Type::Undefined);+ } else if (length.isAuto()) {+ handle.setType(StyleValueHandle::Type::Auto);+ } else {+ auto type = length.isPoints() ? StyleValueHandle::Type::Point+ : StyleValueHandle::Type::Percent;+ storeValue(handle, length.value().unwrap(), type);+ }+ }++ void store(StyleValueHandle& handle, StyleSizeLength sizeValue) {+ if (sizeValue.isUndefined()) {+ handle.setType(StyleValueHandle::Type::Undefined);+ } else if (sizeValue.isAuto()) {+ handle.setType(StyleValueHandle::Type::Auto);+ } else if (sizeValue.isMaxContent()) {+ storeKeyword(handle, StyleValueHandle::Keyword::MaxContent);+ } else if (sizeValue.isStretch()) {+ storeKeyword(handle, StyleValueHandle::Keyword::Stretch);+ } else if (sizeValue.isFitContent()) {+ storeKeyword(handle, StyleValueHandle::Keyword::FitContent);+ } else {+ auto type = sizeValue.isPoints() ? StyleValueHandle::Type::Point+ : StyleValueHandle::Type::Percent;+ storeValue(handle, sizeValue.value().unwrap(), type);+ }+ }++ void store(StyleValueHandle& handle, FloatOptional number) {+ if (number.isUndefined()) {+ handle.setType(StyleValueHandle::Type::Undefined);+ } else {+ storeValue(handle, number.unwrap(), StyleValueHandle::Type::Number);+ }+ }++ StyleLength getLength(StyleValueHandle handle) const {+ if (handle.isUndefined()) {+ return StyleLength::undefined();+ } else if (handle.isAuto()) {+ return StyleLength::ofAuto();+ } else {+ assert(+ handle.type() == StyleValueHandle::Type::Point ||+ handle.type() == StyleValueHandle::Type::Percent);+ float value = (handle.isValueIndexed())+ ? std::bit_cast<float>(buffer_.get32(handle.value()))+ : unpackInlineInteger(handle.value());++ return handle.type() == StyleValueHandle::Type::Point+ ? StyleLength::points(value)+ : StyleLength::percent(value);+ }+ }++ StyleSizeLength getSize(StyleValueHandle handle) const {+ if (handle.isUndefined()) {+ return StyleSizeLength::undefined();+ } else if (handle.isAuto()) {+ return StyleSizeLength::ofAuto();+ } else if (handle.isKeyword(StyleValueHandle::Keyword::MaxContent)) {+ return StyleSizeLength::ofMaxContent();+ } else if (handle.isKeyword(StyleValueHandle::Keyword::FitContent)) {+ return StyleSizeLength::ofFitContent();+ } else if (handle.isKeyword(StyleValueHandle::Keyword::Stretch)) {+ return StyleSizeLength::ofStretch();+ } else {+ assert(+ handle.type() == StyleValueHandle::Type::Point ||+ handle.type() == StyleValueHandle::Type::Percent);+ float value = (handle.isValueIndexed())+ ? std::bit_cast<float>(buffer_.get32(handle.value()))+ : unpackInlineInteger(handle.value());++ return handle.type() == StyleValueHandle::Type::Point+ ? StyleSizeLength::points(value)+ : StyleSizeLength::percent(value);+ }+ }++ FloatOptional getNumber(StyleValueHandle handle) const {+ if (handle.isUndefined()) {+ return FloatOptional{};+ } else {+ assert(handle.type() == StyleValueHandle::Type::Number);+ float value = (handle.isValueIndexed())+ ? std::bit_cast<float>(buffer_.get32(handle.value()))+ : unpackInlineInteger(handle.value());+ return FloatOptional{value};+ }+ }++ private:+ void storeValue(+ StyleValueHandle& handle,+ float value,+ StyleValueHandle::Type type) {+ handle.setType(type);++ if (handle.isValueIndexed()) {+ auto newIndex =+ buffer_.replace(handle.value(), std::bit_cast<uint32_t>(value));+ handle.setValue(newIndex);+ } else if (isIntegerPackable(value)) {+ handle.setValue(packInlineInteger(value));+ } else {+ auto newIndex = buffer_.push(std::bit_cast<uint32_t>(value));+ handle.setValue(newIndex);+ handle.setValueIsIndexed();+ }+ }++ void storeKeyword(+ StyleValueHandle& handle,+ StyleValueHandle::Keyword keyword) {+ handle.setType(StyleValueHandle::Type::Keyword);++ if (handle.isValueIndexed()) {+ auto newIndex =+ buffer_.replace(handle.value(), static_cast<uint32_t>(keyword));+ handle.setValue(newIndex);+ } else {+ handle.setValue(static_cast<uint16_t>(keyword));+ }+ }++ static constexpr bool isIntegerPackable(float f) {+ constexpr uint16_t kMaxInlineAbsValue = (1 << 11) - 1;++ auto i = static_cast<int32_t>(f);+ return static_cast<float>(i) == f && i >= -kMaxInlineAbsValue &&+ i <= +kMaxInlineAbsValue;+ }++ static constexpr uint16_t packInlineInteger(float value) {+ uint16_t isNegative = value < 0 ? 1 : 0;+ return static_cast<uint16_t>(+ (isNegative << 11) |+ (static_cast<int32_t>(value) * (isNegative != 0u ? -1 : 1)));+ }++ static constexpr float unpackInlineInteger(uint16_t value) {+ constexpr uint16_t kValueSignMask = 0b0000'1000'0000'0000;+ constexpr uint16_t kValueMagnitudeMask = 0b0000'0111'1111'1111;+ const bool isNegative = (value & kValueSignMask) != 0;+ return static_cast<float>(+ (value & kValueMagnitudeMask) * (isNegative ? -1 : 1));+ }++ SmallValueBuffer<4> buffer_;+};++} // namespace facebook::yoga