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
refactor: comprehensive architecture improvements across all modules
esenginee8eac7ac251d
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 118181938..902475db5 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -74,16 +74,10 @@ jobs:key: ${{ runner.os }}-emscriptenmax-size: 500M- - name: Configure CMake- run: emcmake cmake -B build_web -G Ninja -DES_BUILD_WEB=ON -DES_ENABLE_CCACHE=ON-- - name: Build- run: cmake --build build_web-- name: Install dependenciesrun: pnpm install- - name: Build SDK+ - name: Build all targetsrun: node build-tools/cli.js build -t all --manifest --no-sync- name: Track bundle sizesdiff --git a/.github/workflows/publish-sdk.yml b/.github/workflows/publish-sdk.ymlindex 7646fce5b..64508e465 100644--- a/.github/workflows/publish-sdk.yml+++ b/.github/workflows/publish-sdk.yml@@ -32,6 +32,13 @@ jobs:- name: Install dependenciesrun: pnpm install+ - name: Type-check SDK+ run: npx tsc --noEmit -p sdk/tsconfig.json++ - name: Run SDK tests+ working-directory: sdk+ run: pnpm run test+- name: Build SDKworking-directory: sdkrun: pnpm run builddiff --git a/.gitignore b/.gitignoreindex 2d812defe..992687bad 100644--- a/.gitignore+++ b/.gitignore@@ -9,12 +9,10 @@ dist/# Node.jsnode_modules/package-lock.json-pnpm-lock.yamlpnpm-debug.log*# Rust/Tauritarget/-Cargo.lock# IDE.vs/diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex 305dc4b8d..093641eda 100644--- a/desktop/public/sdk/cjs/esengine.wechat.js+++ b/desktop/public/sdk/cjs/esengine.wechat.js@@ -1,2 +1,2 @@-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const u=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],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}],d={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",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},h=new Map,p=new Set;for(const e of u)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function g(e){return h.get(f(e))}function _(e){return p.has(e.toLowerCase())}function m(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function y(e){const t=g(e);return t?.wechatPackInclude??!1}let x=null;function w(){return x||(x=wx.getFileSystemManager()),x}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(y(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 s.includes("no such file")||s.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 b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function T(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let A=!1;const E=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return b(e)}async readTextFile(e){return S(e)}async fileExists(e){return P(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},M=1920,R=1080,I={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const F=4294967295,B=4294967295;function k(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(k);const t={};for(const s in e)t[s]=k(e[s]);return t}let U=0;function D(e,t){const s=++U;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...k(t),...e}:k(t)}}function L(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function $(e,t){const s=L(),n=s.get(e);if(n)return n;const r=D(e,t);return s.set(e,r),O(e,t,!1),r}function W(e){const t=L(),s=t.get(e);if(s)return s;const n=D(e,{});return t.set(e,n),O(e,{},!0),n}function z(e){return L().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function N(e,t){j.set(e,t)}function V(e){return j.get(e)??z(e)}function X(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const G={Perspective:0,Orthographic:1},q={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=X("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=X("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=X("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Z=X("Camera",{projectionType:G.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:q.ColorAndDepth}),ee=X("Canvas",{designResolution:{x:M,y:R},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=X("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=X("Parent",{entity:0}),ne=X("Children",{entities:[]}),re=X("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B}),oe=X("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}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=$("SceneOwner",{scene:"",persistent:!1});N("Name",ie);const le=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=X("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=X("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de=X("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),he={Static:0,Kinematic:1,Dynamic:2};let pe=0;function fe(e,t){const s=++pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ge(e){return{_type:"res",_resource:e}}function _e(e){return{_type:"res_mut",_resource:e}}class me{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class ye{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 me(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const xe=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>we(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class be{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=H(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":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)}}}var Pe;exports.Schedule=void 0,(Pe=exports.Schedule||(exports.Schedule={}))[Pe.Startup=0]="Startup",Pe[Pe.First=1]="First",Pe[Pe.PreUpdate=2]="PreUpdate",Pe[Pe.Update=3]="Update",Pe[Pe.PostUpdate=4]="PostUpdate",Pe[Pe.Last=5]="Last",Pe[Pe.FixedPreUpdate=10]="FixedPreUpdate",Pe[Pe.FixedUpdate=11]="FixedUpdate",Pe[Pe.FixedPostUpdate=12]="FixedPostUpdate";let Te=0;function Ce(e,t,s){const n=++Te;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ee{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Me{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Re=fe(new Me,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Me;e.insertResource(Re,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fe=new Ie;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=ke(t[e]),o=ke(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function ke(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ue(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}function De(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:De(e)}}return t}class Le{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),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.");this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):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.");H(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(Ue(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,De(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(e)}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(Ue(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<i&&(i=s,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const $e=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var We;function ze(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(We=exports.BlendMode||(exports.BlendMode={}))[We.Normal=0]="Normal",We[We.Additive=1]="Additive",We[We.Multiply=2]="Multiply",We[We.Screen=3]="Screen",We[We.PremultipliedAlpha=4]="PremultipliedAlpha";let Oe=null,He=null,je=1;const Ne=new Map;function Ve(e){Oe=e,He=e.getResourceManager(),tt()}function Xe(){0!==Je&&Oe&&(Oe._free(Je),Je=0),Ne.clear(),je=1,Ye=!1,Qe.clear(),Ze=null,He=null,Oe=null}function Ge(){if(!He)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return He}const qe={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=je++,s={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,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ne.set(t,s),t},get:e=>Ne.get(e),setUniform(e,t,s){const n=Ne.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ne.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ne.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ne.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),releaseAll(){Ne.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=je++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ne.set(s,n),s},toAssetData(e,t){const s=Ne.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ye=!1,Je=0;const Ke=4096,Qe=new Map;let Ze=null;function et(e){const t=(0===Je&&Oe&&(Je=Oe._malloc(Ke)),Je);if(0===t||!Oe)return{ptr:0,count:0};let s=0,n=0;const r=Oe.HEAPU8,o=Oe.HEAPU32,i=Oe.HEAPF32;for(const[a,l]of e){if(s+128>Ke)break;let e=Qe.get(a);e||(Ze||(Ze=new TextEncoder),e=Ze.encode(a),Qe.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=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]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function tt(){if(!Oe||Ye)return;Oe.materialDataProvider=(e,t,s,n,r)=>{const o=Ne.get(e);if(!o)return Oe.HEAPU32[t>>2]=0,Oe.HEAPU32[s>>2]=0,Oe.HEAPU32[n>>2]=0,void(Oe.HEAPU32[r>>2]=0);Oe.HEAPU32[t>>2]=o.shader,Oe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=et(o.uniforms);Oe.HEAPU32[n>>2]=i,Oe.HEAPU32[r>>2]=a},Ye=!0}const st={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 nt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&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();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class rt{constructor(e,t=""){this.cache_=new nt,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&&(qe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())qe.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:qe.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ot=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"}]}]]);function it(e){return ot.get(e)?.fields??[]}function at(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)ct(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function lt(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ot.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ot.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=c.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)ct(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ct(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=V(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class ut{constructor(e){this.textureCache_=new nt,this.shaderCache_=new nt,this.jsonCache_=new nt,this.textCache_=new nt,this.binaryCache_=new nt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nt,this.prefabCache_=new nt,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.module_=e,this.canvas_=i(I.textCanvasSize,I.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 rt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);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 s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}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(),qe.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 s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===g(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(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=g(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return lt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}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},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"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 s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return qe.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return qe.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}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 s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(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 s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const dt=fe(null,"Assets");class ht{build(e){const t=e.wasmModule;t?e.insertResource(dt,new ut(t)):console.warn("AssetPlugin: No WASM module available")}}const pt=new ht;async function ft(e,t,s){const{entities:n,rootId:r}=await _t(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await lt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const gt=10;async function _t(e,t,s,n,r,o=0){if(o>gt)throw new Error(`Prefab nesting depth exceeded ${gt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await _t(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};mt(d,t),l.push(d)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function mt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class yt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return ft(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const xt=fe(null,"Prefabs");class wt{constructor(){this.name="PrefabsPlugin",this.dependencies=[dt]}build(e){const t=e.getResource(dt);e.insertResource(xt,new yt(e.world,t))}}const vt=new wt;let bt=null,St=0,Pt=0,Tt=0;const Ct=new Float32Array(256);function At(e){bt=e,St=bt._malloc(64),Pt=bt._malloc(64),Tt=bt._malloc(1024)}function Et(){bt&&(St&&(bt._free(St),St=0),Pt&&(bt._free(Pt),Pt=0),Tt&&(bt._free(Tt),Tt=0)),bt=null}function Mt(){if(!bt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return bt}const Rt={r:1,g:1,b:1,a:1},It={begin(e){const t=Mt();t.HEAPF32.set(e,St/4),t.draw_begin(St)},end(){Mt().draw_end()},line(e,t,s,n=1){Mt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Mt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Mt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Mt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Mt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Rt){Mt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Rt){Mt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Mt().draw_setLayer(e)},setDepth(e){Mt().draw_setDepth(e)},getDrawCallCount:()=>bt?bt.draw_getDrawCallCount():0,getPrimitiveCount:()=>bt?bt.draw_getPrimitiveCount():0,setBlendMode(e){Mt().draw_setBlendMode(e)},setDepthTest(e){Mt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Mt();n.HEAPF32.set(s,Pt/4),n.draw_mesh(e,t,Pt)},drawMeshWithMaterial(e,t,s){const n=Mt(),r=qe.get(t);if(!r)return;if(It.setBlendMode(r.blendMode),It.setDepthTest(r.depthTest),0===r.uniforms.size)return void It.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Pt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Bt(t);if(!(n<0)){if(ze(s))Ct[o++]=10,Ct[o++]=n,Ct[o++]=s.slot??e++,Ct[o++]=s.textureId;else if("number"==typeof s)Ct[o++]=1,Ct[o++]=n,Ct[o++]=s;else if(Array.isArray(s)){Ct[o++]=s.length,Ct[o++]=n;for(let e=0;e<s.length;e++)Ct[o++]=s[e]}else"w"in s?(Ct[o++]=4,Ct[o++]=n,Ct[o++]=s.x,Ct[o++]=s.y,Ct[o++]=s.z,Ct[o++]=s.w):"z"in s?(Ct[o++]=3,Ct[o++]=n,Ct[o++]=s.x,Ct[o++]=s.y,Ct[o++]=s.z):(Ct[o++]=2,Ct[o++]=n,Ct[o++]=s.x,Ct[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(Ct.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Tt/4),n.draw_meshWithUniforms(e,r.shader,Pt,Tt,o)):n.draw_mesh(e,r.shader,Pt)}},Ft={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Bt(e){return Ft[e]??-1}const kt=new Map;function Ut(e,t,s){kt.set(e,{fn:t,scene:s??""})}function Dt(e){kt.delete(e)}function Lt(){kt.clear()}var $t;exports.DataType=void 0,($t=exports.DataType||(exports.DataType={}))[$t.Float=1]="Float",$t[$t.Float2=2]="Float2",$t[$t.Float3=3]="Float3",$t[$t.Float4=4]="Float4",$t[$t.Int=5]="Int",$t[$t.Int2=6]="Int2",$t[$t.Int3=7]="Int3",$t[$t.Int4=8]="Int4";let Wt=null,zt=0,Ot=0,Ht=0;function jt(e){Wt=e,zt=Wt._malloc(262144),Ot=Wt._malloc(65536),Ht=Wt._malloc(256)}function Nt(){Wt&&(zt&&Wt._free(zt),Ot&&Wt._free(Ot),Ht&&Wt._free(Ht),zt=0,Ot=0,Ht=0),Wt=null}function Vt(){if(!Wt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Wt}const Xt={create(e){const t=Vt(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,zt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ht,r).set(o),t.geometry_init(s,zt,n,Ht,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Ot,n).set(e.indices),t.geometry_setIndices16(s,Ot,n)}else{new Uint32Array(t.HEAPU8.buffer,Ot,n).set(e.indices),t.geometry_setIndices32(s,Ot,n)}}return s},updateVertices(e,t,s=0){const n=Vt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,zt/4),n.geometry_updateVertices(e,zt,r,s)},release(e){e>0&&Vt().geometry_release(e)},isValid:e=>!(!Wt||e<=0)&&Wt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Xt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Xt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Xt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Gt=null;function qt(e){Gt=e}function Yt(){Gt&&Kt.isInitialized()&&Kt.shutdown(),Gt=null}function Jt(){if(!Gt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Gt}const Kt={init:(e,t)=>Jt().postprocess_init(e,t),shutdown(){Jt().postprocess_shutdown()},resize(e,t){Jt().postprocess_resize(e,t)},addPass:(e,t)=>Jt().postprocess_addPass(e,t),removePass(e){Jt().postprocess_removePass(e)},setEnabled(e,t){Jt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Jt().postprocess_isPassEnabled(e),setUniform(e,t,s){Jt().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Jt().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Jt().postprocess_begin()},end(){Jt().postprocess_end()},getPassCount:()=>Jt().postprocess_getPassCount(),isInitialized:()=>!!Gt&&Gt.postprocess_isInitialized(),setBypass(e){Jt().postprocess_setBypass(e)},isBypassed:()=>!Gt||Gt.postprocess_isBypassed(),createBlur:()=>qe.createShader(Qt,"#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:()=>qe.createShader(Qt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>qe.createShader(Qt,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>qe.createShader(Qt,"#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")},Qt="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Zt;exports.RenderStage=void 0,(Zt=exports.RenderStage||(exports.RenderStage={}))[Zt.Background=0]="Background",Zt[Zt.Opaque=1]="Opaque",Zt[Zt.Transparent=2]="Transparent",Zt[Zt.Overlay=3]="Overlay";let es=null,ts=0;function ss(e){es=e,ts=es._malloc(64)}function ns(){es&&ts&&(es._free(ts),ts=0),es=null}const rs={init(e,t){es?.renderer_init(e,t)},resize(e,t){es?.renderer_resize(e,t)},begin(e,t){es&&ts&&(es.HEAPF32.set(e,ts/4),es.renderer_begin(ts,t??0))},flush(){es?.renderer_flush()},end(){es?.renderer_end()},submitSprites(e){es&&es.renderer_submitSprites(e._cpp)},submitBitmapText(e){es&&es.renderer_submitBitmapText(e._cpp)},submitSpine(e){es&&es.renderer_submitSpine?.(e._cpp)},setStage(e){es?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>es?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){es?.renderer_releaseTarget(e)},getTargetTexture:e=>es?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>es?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){es?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){es?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){es?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){es?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>es?es.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>es?{drawCalls:es.renderer_getDrawCalls(),triangles:es.renderer_getTriangles(),sprites:es.renderer_getSprites(),text:es.renderer_getText(),spine:es.renderer_getSpine?.()??0,meshes:es.renderer_getMeshes(),culled:es.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let os=null;function is(e){os=e}function as(){os=null}const ls={enable(){os?.gl_enableErrorCheck(!0)},disable(){os?.gl_enableErrorCheck(!1)},check:e=>os?.gl_checkErrors(e)??0,diagnose(){os?.renderer_diagnose()}};class cs{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(rs.resize(n,r),Kt.isInitialized()&&Kt.getPassCount()>0&&Kt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),rs.setViewport(0,0,n,r),rs.clearBuffers(3),rs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),rs.submitSprites(t),rs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):rs.submitSpine(t),rs.flush(),this.executeDrawCallbacks(s,o),rs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;rs.setViewport(n.x,n.y,n.w,n.h),rs.setScissor(n.x,n.y,n.w,n.h,!0),rs.clearBuffers(r),rs.setScissor(0,0,0,0,!1),rs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),rs.submitSprites(t),rs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):rs.submitSpine(t),rs.flush(),this.executeDrawCallbacks(s,o),rs.end()}executeDrawCallbacks(e,t){const s=kt;if(s.size>0){It.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}It.end();for(const e of n)Dt(e)}}}const us="__scene_transition_overlay__";class ds{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class hs{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,ae,{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),Ut(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Kt.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Kt.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ae)){const s=this.app_.world.get(e,ae);s.persistent=t,this.app_.world.insert(e,ae,s)}}}class ps{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.loadPromises_=new Map,this.app_=e}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_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??I.sceneTransitionDuration,r=t.color??{...I.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Ut(us,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;It.setLayer(9999),It.setDepth(9999),It.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}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_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,Dt(us)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Dt(us),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 s=new ds(t);this.scenes_.set(e,s);const n=new hs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(dt)?this.app_.getResource(dt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(dt)&&(t.assetServer=this.app_.getResource(dt));const n=await lt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=gs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 s=new ds(t);this.scenes_.set(e,s);const n=new hs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(dt)?this.app_.getResource(dt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(dt)&&(t.assetServer=this.app_.getResource(dt));const n=await lt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=gs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ae)){if(this.app_.world.get(e,ae).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Dt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Kt.removePass(e)}catch{}s.postProcessPasses.length=0,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)}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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Q,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Q,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Kt.setEnabled(s,t)}catch{}}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,s]of this.scenes_)"running"===s.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 fs=fe(null,"SceneManager");function gs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(fs).getSceneStatus(t)&&s._fn(...n)}}}const _s=Ce([_e(fs),ge(xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ms={name:"SceneManager",build(e){const t=new ps(e);e.insertResource(fs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(fs),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,_s)}};class ys{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_=new Set,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Le,this.resources_=new ye;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ys}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(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}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}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(fs).register(e),this}setInitialScene(e){return this.getResource(fs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ee(this.world_,this.resources_),this.resources_.insert(xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Lt();const e=[as,ns,Yt,Nt,Xe,Et];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){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}}updateTime(e){const t=this.resources_.get(xe);t.delta=e,t.elapsed+=e,t.frameCount++}}const xs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ws(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case Y.FixedWidth:return o;case Y.FixedHeight:return i;case Y.Expand:return Math.max(o,i);case Y.Shrink:return Math.min(o,i);case Y.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function vs(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ae);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,l){h=ws(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=h*a,u=Ss(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Ts(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=As(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Ms(u,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const bs=new Float32Array(16);function Ss(e,t,s,n,r,o){const i=bs;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const Ps=new Float32Array(16);function Ts(e,t,s,n){const r=Ps;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const Cs=new Float32Array(16);function As(e,t,s){const n=Cs;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const Es=new Float32Array(16);function Ms(e,t){const s=Es;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var Rs,Is,Fs;exports.TextAlign=void 0,(Rs=exports.TextAlign||(exports.TextAlign={}))[Rs.Left=0]="Left",Rs[Rs.Center=1]="Center",Rs[Rs.Right=2]="Right",exports.TextVerticalAlign=void 0,(Is=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[Is.Top=0]="Top",Is[Is.Middle=1]="Middle",Is[Is.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Fs=exports.TextOverflow||(exports.TextOverflow={}))[Fs.Visible=0]="Visible",Fs[Fs.Clip=1]="Clip",Fs[Fs.Ellipsis=2]="Ellipsis";const Bs=$("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),ks=$("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Us{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I.textCanvasSize,I.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(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),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const g=Math.round(255*e.color.r),_=Math.round(255*e.color.g),m=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${_}, ${m}, ${y})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-x)/2;break;case exports.TextVerticalAlign.Bottom:w=f-x-u;break;default:w=u}else w=u;let v=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=c}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const C=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:C,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Ds(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Ls(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class $s{build(e){N("Text",Bs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Us(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Bs));for(const e of r.keys())n.valid(e)&&n.has(e,Bs)||r.delete(e);const e=n.getEntitiesWithComponents([Bs]);for(const t of e){const e=n.get(t,Bs),o=n.has(t,ks)?n.get(t,ks):null,i=r.get(t);if(i&&!Ls(i,e,o))continue;n.has(t,Q)||n.insert(t,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),l=n.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Q,l),r.set(t,Ds(e,o))}}))}}const Ws=new $s,zs=$("UIMask",{enabled:!0});function Os(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Hs(e,t,s,n,r,o,i,a,l,c,u){const d=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function g(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*u]}const[_,m]=g(d,p),[y,x]=g(h,f),w=Math.min(_,y),v=Math.max(_,y),b=Math.min(m,x),S=Math.max(m,x);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function js(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=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],_=e[13],m=e[14],y=e[15],x=n*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,T=d*_-h*g,C=d*m-p*g,A=d*y-f*g,E=h*m-p*_,M=h*y-f*_,R=p*y-f*m;let I=x*R-w*M+v*E+b*A-S*C+P*T;return 0===I||(I=1/I,s[0]=(l*R-c*M+u*E)*I,s[1]=(o*M-r*R-i*E)*I,s[2]=(_*P-m*S+y*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*A-a*R-u*C)*I,s[5]=(n*R-o*A+i*C)*I,s[6]=(m*v-g*P-y*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*M-l*A+u*T)*I,s[9]=(r*A-n*M-i*T)*I,s[10]=(g*S-_*v+y*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*C-a*E-c*T)*I,s[13]=(n*E-r*C+o*T)*I,s[14]=(_*w-g*b-m*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function Ns(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function Vs(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)}function Xs(e,t,s,n,r,o,i){if(!e.has(t,ks)||!e.has(t,K))return null;const a=e.get(t,ks),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Hs(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Gs(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([zs]);if(0!==l.length)try{!function(e,t,s,n,r,o,i,a,l){const c=new Set;for(const e of n){t.get(e,zs).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(c.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(c.has(s)){const e=Xs(t,s,r,o,i,a,l);e&&(n=Os(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Xs(t,e,r,o,i,a,l);s&&d(e,s)}}(e,t,s,l,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class qs{build(e){if(N("UIMask",zs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Gs(e.wasmModule,e.world))}}const Ys=new qs,Js=$("Interactable",{enabled:!0}),Ks=$("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Qs;exports.ButtonState=void 0,(Qs=exports.ButtonState||(exports.ButtonState={}))[Qs.Normal=0]="Normal",Qs[Qs.Hovered=1]="Hovered",Qs[Qs.Pressed=2]="Pressed",Qs[Qs.Disabled=3]="Disabled";const Zs=$("Button",{state:exports.ButtonState.Normal,transition:null});class en{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const tn=fe(new en,"UIEvents"),sn=W("ScreenSpace");function nn(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,g;if(l===c&&u===d){const e=l+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,g=t+o}else h=l+s.x,p=u+s.y,f=c+n.x,g=d+n.y;return{centerX:.5*(h+f),centerY:.5*(p+g),width:f-h,height:g-p,rect:{left:h,bottom:p,right:f,top:g}}}function rn(e,t,s,n,r,o){if(!e.has(t,ks))return;const i=e.get(t,ks),a=nn(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,ne))return;const c=e.get(t,ne);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&rn(e,t,a.rect,a.centerX,a.centerY,!1)}class on{build(e){N("UIRect",ks);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge($e)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([sn,ks,J]);for(const e of o)rn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const an=new on,ln=new Float32Array(16),cn=new Float32Array(16);let un=!0,dn=1;class hn{build(e){N("Interactable",Js),N("Button",Zs);const t=e.world,s=new en;e.insertResource(tn,s);let n=null,r=null;dn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Re),ge($e)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Ks]);for(const e of i){const s=t.get(e,Ks);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*dn,l=o.screenH-e.mouseY*dn;!function(e){let t=!1;for(let s=0;s<16;s++)if(cn[s]!==e[s]){t=!0;break}t&&(cn.set(e),un=!0)}(o.viewProjection),un&&(js(o.viewProjection,ln),un=!1);const c=Ns(a,l,ln,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Js,ks,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Ks)||t.insert(e,Ks);if(!t.get(e,Js).enabled)continue;const s=t.get(e,K),n=t.get(e,ks),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Vs(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,Ks)){t.get(n,Ks).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Ks).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ks);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ks)){const e=t.get(r,Ks);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([Zs]);for(const s of e){if(t.has(s,Js)||t.insert(s,Js,{enabled:!0}),!t.has(s,Ks))continue;const e=t.get(s,Ks),n=t.get(s,Zs),r=t.get(s,Js),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const e=t.get(s,Q),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,Q,e)}}},{name:"ButtonSystem"}))}}const pn=new hn,fn=$("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});class gn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){N("TextInput",fn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(I.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=0;const h=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(!h)return;const p=h,f=()=>{l||null===a||x()},g=()=>{l=!0},_=()=>{l=!1,x()},m=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,fn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(tn).emit(a,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==a&&s.valid(a)&&s.has(a,fn)){const e=s.get(a,fn);e.focused=!1,e.dirty=!0}a=null};function x(){if(null===a||!s.valid(a))return;const t=s.get(a,fn);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(tn).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,b()}function w(e){if(a===e)return;v();const t=s.get(e,fn);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),b())}function v(){if(null!==a&&s.valid(a)&&s.has(a,fn)){const e=s.get(a,fn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){c=!0,u=0}function S(e,i,a,l){(r.width<a||r.height<l)&&(r.width=mn(Math.max(r.width,a)),r.height=mn(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=_n(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=_n(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,s=g+(e.length-1)*f,n=f}else t=g+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,a,l),m=new Uint8Array(_.data.buffer),y=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=n.get(e);void 0!==w&&y.releaseTexture(w);const v=y.createTexture(a,l,x,m.length,1,!0);n.set(e,v),t._free(x);const b=s.get(e,Q);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Q,b)}p.addEventListener("input",f),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",_),p.addEventListener("keydown",m),p.addEventListener("blur",y),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",m),p.removeEventListener("blur",y),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(tn)],e=>{const t=s.getEntitiesWithComponents([fn,Js]);for(const e of t){if(!s.has(e,Ks))continue;if(s.get(e,Ks).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([Js]);for(const t of e){if(s.has(t,fn))continue;if(!s.has(t,Ks))continue;if(s.get(t,Ks).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,fn)))){s.get(a,fn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,fn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([fn,ks]);for(const e of i){const t=s.get(e,fn);if(!t.dirty)continue;const n=s.get(e,ks),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,Q)||s.insert(e,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function _n(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function mn(e){let t=1;for(;t<e;)t*=2;return t}const yn=new gn;async function xn(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 wn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),vn=fe(null,"PhysicsAPI");function bn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Sn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Pn{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(wn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=xn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Ce([ge(xe)],a=>{const l=i.getEntitiesWithComponents([le,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,le),l=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=bn(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Tn(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===he.Kinematic){const e=bn(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,J);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=bn(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Sn(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,J,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(wn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(vn,Cn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Tn(e,t,s){const n=e.world;if(n.has(s,ce)){const e=n.get(s,ce);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ue)){const e=n.get(s,ue);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,de)){const e=n.get(s,de);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Cn{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(Cn.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function An(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function En(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Mn(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,g=a*h,_=a*p,m=l*h,y=l*p,x=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(m+x))*r,(g+b)*r,(_-v)*r,0,(g-b)*o,(1-(f+x))*o,(y+w)*o,0,(_+v)*i,(y-w)*i,(1-(f+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Rn(e,t,s,n,r,o,i,a,l){const c=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=An(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let u={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===g(l)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=En(n),_=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=_+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=An(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,s,n)),o){new Pn("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;const i=g(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=An(e,c,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[r]=0}}return n}(t,s,n),p=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=qe.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=qe.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=it(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,h,p);const f=at(e.world,s);if(l&&e.hasResource(fs))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(r&&d){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(d,s,u,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,K)){const e=Mn(c.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],_=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(y,r,x,o,f,g,h),t._free(y),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(dt);t&&t.setAddressableManifest(a)}}class In{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===g(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=g(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,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),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Fn="__preview__";const Bn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=rs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:rs.getTargetTexture(s),width:e.width,height:e.height}},release(e){rs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(rs.releaseRenderTarget(e._handle),Bn.create({width:t,height:s,depth:!0})),begin(e,t){rs.begin(t,e._handle)},end(){rs.end()},getDepthTexture:e=>rs.getTargetDepthTexture(e._handle)};let kn=!1;var Un;exports.LogLevel=void 0,(Un=exports.LogLevel||(exports.LogLevel={}))[Un.Debug=0]="Debug",Un[Un.Info=1]="Info",Un[Un.Warn=2]="Warn",Un[Un.Error=3]="Error";class Dn{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class Ln{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Dn)}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,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const $n=new Ln;const Wn=[Ws,Ys,an,pn,yn];A||(A=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=E,exports.App=ys,exports.AssetPlugin=ht,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.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,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});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=ut,exports.Assets=dt,exports.AsyncCache=nt,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=Zs,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=de,exports.Children=ne,exports.CircleCollider=ue,exports.ClearFlags=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.Draw=It,exports.EntityCommands=be,exports.GLDebug=ls,exports.Geometry=Xt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Me,exports.Interactable=Js,exports.LocalTransform=J,exports.Logger=Ln,exports.Material=qe,exports.MaterialLoader=rt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=Cn,exports.PhysicsEvents=wn,exports.PhysicsPlugin=Pn,exports.PostProcess=Kt,exports.PrefabServer=yt,exports.Prefabs=xt,exports.PrefabsPlugin=wt,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(fs);t.register({name:Fn,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Fn),this.loadPromise_=t.load(Fn).then(()=>{}),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 In(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Rn(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,Fn)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(fs).getScene(Fn),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,J,i);const a={isActive:!0,projectionType:G.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.ColorAndDepth};e.insert(o,Z,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(fs);await e.switchTo(Fn),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.ProjectionType=G,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{we(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=ve,exports.RenderPipeline=cs,exports.RenderTexture=Bn,exports.Renderer=rs,exports.Res=ge,exports.ResMut=_e,exports.RigidBody=le,exports.RuntimeConfig=I,exports.ScaleMode=Y,exports.SceneManager=fs,exports.SceneManagerState=ps,exports.SceneOwner=ae,exports.ScreenSpace=sn,exports.ShaderSources=st,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ee,exports.Text=Bs,exports.TextInput=fn,exports.TextInputPlugin=gn,exports.TextPlugin=$s,exports.TextRenderer=Us,exports.Time=xe,exports.UICameraInfo=$e,exports.UIEventQueue=en,exports.UIEvents=tn,exports.UIInteraction=Ks,exports.UIInteractionPlugin=hn,exports.UILayoutPlugin=on,exports.UIMask=zs,exports.UIMaskPlugin=qs,exports.UIRect=ks,exports.Velocity=te,exports.WebAssetProvider=In,exports.World=Le,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ae().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ae().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ae().push({schedule:e,system:t})},exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=I.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=I.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=I.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=I.canvasMatchWidthOrHeight)},exports.assetPlugin=pt,exports.clearDrawCallbacks=Lt,exports.clearUserComponents=function(){L().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=nn,exports.createMaskProcessor=Gs,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await Rn(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=ys.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),At(e),Ve(e),jt(e),qt(e),ss(e),is(e);const r=new cs;s.pipeline_=r;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r,o){o||(o=vs(e,n,t,r));const i=s.getResource($e);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource($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,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;rs.setClearColor(e.x,e.y,e.z,e.w)}const d=(a()-o)/1e3;let h;if(rs.resize(t,c),Kt.isInitialized()&&Kt.getPassCount()>0&&!Kt.isBypassed()&&Kt.resize(t,c),s.hasResource(fs)){const e=s.getResource(fs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=vs(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:xs,width:t,height:c,elapsed:d});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:d})}rs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(pt),s.addPlugin(vt),s.addPlugin(Fe),s.addPlugin(ms),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Wn,...t})},exports.debug=function(e,t,s){$n.debug(e,t,s)},exports.defineComponent=$,exports.defineResource=fe,exports.defineSystem=Ce,exports.defineTag=W,exports.error=function(e,t,s){$n.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return g(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of u)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return d[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=V,exports.getComponentAssetFields=function(e){const t=ot.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s},exports.getComponentDefaults=function(e){const t=V(e);return t?k(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return $n},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return m().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){$n.info(e,t,s)},exports.initDrawAPI=At,exports.initGLDebugAPI=is,exports.initGeometryAPI=jt,exports.initMaterialAPI=Ve,exports.initPostProcessAPI=qt,exports.initRendererAPI=ss,exports.inputPlugin=Fe,exports.instantiatePrefab=ft,exports.intersectRects=Os,exports.invertMatrix4=js,exports.isBuiltinComponent=H,exports.isCustomExtension=y,exports.isEditor=function(){return kn},exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!kn},exports.isTextureRef=ze,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ct,exports.loadPhysicsModule=xn,exports.loadRuntimeScene=Rn,exports.loadSceneData=at,exports.loadSceneWithAssets=lt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInWorldRect=Vs,exports.prefabsPlugin=vt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=N,exports.registerComponentAssetFields=function(e,t){ot.set(e,t)},exports.registerDrawCallback=Ut,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(dt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=tt,exports.sceneManagerPlugin=ms,exports.screenToWorld=Ns,exports.setEditorMode=function(e){kn=e},exports.setLogLevel=function(e){$n.setMinLevel(e)},exports.shutdownDrawAPI=Et,exports.shutdownGLDebugAPI=as,exports.shutdownGeometryAPI=Nt,exports.shutdownMaterialAPI=Xe,exports.shutdownPostProcessAPI=Yt,exports.shutdownRendererAPI=ns,exports.textInputPlugin=yn,exports.textPlugin=Ws,exports.transitionTo=async function(e,t,s){const n=e.getResource(fs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=pn,exports.uiLayoutPlugin=an,exports.uiMaskPlugin=Ys,exports.uiPlugins=Wn,exports.unregisterDrawCallback=Dt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){$n.warn(e,t,s)},exports.worldRectToScreen=Hs,exports.wrapSceneSystem=gs,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return C(await T(e))},exports.wxReadFile=b,exports.wxReadTextFile=S,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function c(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function l(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const u=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],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}],d={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",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},h=new Map,p=new Set;for(const e of u)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function g(e){return h.get(f(e))}function _(e){return p.has(e.toLowerCase())}function m(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function y(e){const t=g(e);return t?.wechatPackInclude??!1}let x=null;function w(){return x||(x=wx.getFileSystemManager()),x}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(y(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 s.includes("no such file")||s.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 b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function T(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let A=!1;const E=new class{constructor(){this.name="wechat"}async fetch(e,t){return c(e,t)}async readFile(e){return b(e)}async readTextFile(e){return S(e)}async fileExists(e){return P(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return l(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},M=1920,R=1080,I={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const F=4294967295,B=4294967295;function $(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map($);const t={};for(const s in e)t[s]=$(e[s]);return t}let U=0;function k(e,t){const s=++U;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...$(t),...e}:$(t)}}function D(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function L(e,t){const s=D(),n=s.get(e);if(n)return n;const r=k(e,t);return s.set(e,r),O(e,t,!1),r}function W(e){const t=D(),s=t.get(e);if(s)return s;const n=k(e,{});return t.set(e,n),O(e,{},!0),n}function z(e){return D().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function N(e,t){j.set(e,t)}function V(e){return j.get(e)??z(e)}function X(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const G={Perspective:0,Orthographic:1},q={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=X("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=X("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=X("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Z=X("Camera",{projectionType:G.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:q.ColorAndDepth}),ee=X("Canvas",{designResolution:{x:M,y:R},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=X("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=X("Parent",{entity:0}),ne=X("Children",{entities:[]}),re=X("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B}),oe=X("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}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=L("SceneOwner",{scene:"",persistent:!1});N("Name",ie);const ce=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),le=X("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=X("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de=X("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),he={Static:0,Kinematic:1,Dynamic:2};let pe=0;function fe(e,t){const s=++pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ge(e){return{_type:"res",_resource:e}}function _e(e){return{_type:"res_mut",_resource:e}}class me{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class ye{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 me(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const xe=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>we(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=d}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class be{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=H(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":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)}}}var Pe;exports.Schedule=void 0,(Pe=exports.Schedule||(exports.Schedule={}))[Pe.Startup=0]="Startup",Pe[Pe.First=1]="First",Pe[Pe.PreUpdate=2]="PreUpdate",Pe[Pe.Update=3]="Update",Pe[Pe.PostUpdate=4]="PostUpdate",Pe[Pe.Last=5]="Last",Pe[Pe.FixedPreUpdate=10]="FixedPreUpdate",Pe[Pe.FixedUpdate=11]="FixedUpdate",Pe[Pe.FixedPostUpdate=12]="FixedPostUpdate";let Te=0;function Ce(e,t,s){const n=++Te;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ee{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Me{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Re=fe(new Me,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Me;e.insertResource(Re,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fe=new Ie;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=$e(t[e]),o=$e(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ue(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let ke=null;function De(e){ke=e}function Le(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ke&&ke(e,t)}function We(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:We(e)}}return t}class ze{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}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 Le(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Le(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Le(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Le(t,`removeParent(entity=${e})`)}}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Le(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):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.");H(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(Ue(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,We(r))}catch(s){Le(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Le(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Le(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Le(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(Ue(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<i&&(i=s,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=o?o.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const Oe=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var He;function je(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(He=exports.BlendMode||(exports.BlendMode={}))[He.Normal=0]="Normal",He[He.Additive=1]="Additive",He[He.Multiply=2]="Multiply",He[He.Screen=3]="Screen",He[He.PremultipliedAlpha=4]="PremultipliedAlpha";let Ne=null,Ve=null,Xe=1;const Ge=new Map;function qe(e){Ne=e,Ve=e.getResourceManager(),rt()}function Ye(){0!==Ze&&Ne&&(Ne._free(Ze),Ze=0),Ge.clear(),Xe=1,Qe=!1,tt.clear(),st=null,Ve=null,Ne=null}function Je(){if(!Ve)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ve}const Ke={createShader:(e,t)=>Je().createShader(e,t),releaseShader(e){e>0&&Je().releaseShader(e)},create(e){const t=Xe++,s={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,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ge.set(t,s),t},get:e=>Ge.get(e),setUniform(e,t,s){const n=Ge.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ge.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ge.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ge.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ge.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ge.get(e);return t?.shader??0},release(e){Ge.delete(e)},isValid:e=>Ge.has(e),releaseAll(){Ge.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ge.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Xe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ge.set(s,n),s},toAssetData(e,t){const s=Ge.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ge.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Qe=!1,Ze=0;const et=4096,tt=new Map;let st=null;function nt(e){const t=(0===Ze&&Ne&&(Ze=Ne._malloc(et)),Ze);if(0===t||!Ne)return{ptr:0,count:0};let s=0,n=0;const r=Ne.HEAPU8,o=Ne.HEAPU32,i=Ne.HEAPF32;for(const[a,c]of e){if(s+128>et)break;let e=tt.get(a);e||(st||(st=new TextEncoder),e=st.encode(a),tt.set(a,e));const l=e.length,u=4*Math.ceil(l/4);o[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof c)d=0,h[0]=c;else if(Array.isArray(c)){d=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)h[e]=c[e]}else"w"in c?(d=3,h=[c.x,c.y,c.z,c.w]):"z"in c?(d=2,h=[c.x,c.y,c.z,0]):"y"in c&&(d=1,h=[c.x,c.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function rt(){if(!Ne||Qe)return;Ne.materialDataProvider=(e,t,s,n,r)=>{const o=Ge.get(e);if(!o)return Ne.HEAPU32[t>>2]=0,Ne.HEAPU32[s>>2]=0,Ne.HEAPU32[n>>2]=0,void(Ne.HEAPU32[r>>2]=0);Ne.HEAPU32[t>>2]=o.shader,Ne.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=nt(o.uniforms);Ne.HEAPU32[n>>2]=i,Ne.HEAPU32[r>>2]=a},Qe=!0}const ot={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 it{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&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();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class at{constructor(e,t=""){this.cache_=new it,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&&(Ke.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ke.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Ke.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ct=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"}]}]]);function lt(e){return ct.get(e)?.fields??[]}function ut(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)ht(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function dt(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ct.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const l=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);l.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ct.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)ht(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ht(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=V(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class pt{constructor(e){this.textureCache_=new it,this.shaderCache_=new it,this.jsonCache_=new it,this.textCache_=new it,this.binaryCache_=new it,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new it,this.prefabCache_=new it,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.module_=e,this.canvas_=i(I.textCanvasSize,I.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 at(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);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 s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}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(),Ke.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 s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),c=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),u="binary"===g(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=g(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return dt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}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},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"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 s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}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 s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(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 s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ft=fe(null,"Assets");class gt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new pt(t)):console.warn("AssetPlugin: No WASM module available")}}const _t=new gt;async function mt(e,t,s){const{entities:n,rootId:r}=await xt(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await dt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const yt=10;async function xt(e,t,s,n,r,o=0){if(o>yt)throw new Error(`Prefab nesting depth exceeded ${yt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await xt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?i.get(n.parent)??null:null),c.push(...t.entities);continue}const l=i.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};wt(d,t),c.push(d)}const l=i.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function wt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return mt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const bt=fe(null,"Prefabs");class St{constructor(){this.name="PrefabsPlugin",this.dependencies=[ft]}build(e){const t=e.getResource(ft);e.insertResource(bt,new vt(e.world,t))}}const Pt=new St;let Tt=null,Ct=0,At=0,Et=0;const Mt=new Float32Array(256);function Rt(e){Tt=e,Ct=Tt._malloc(64),At=Tt._malloc(64),Et=Tt._malloc(1024)}function It(){Tt&&(Ct&&(Tt._free(Ct),Ct=0),At&&(Tt._free(At),At=0),Et&&(Tt._free(Et),Et=0)),Tt=null}function Ft(){if(!Tt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Tt}const Bt={r:1,g:1,b:1,a:1},$t={begin(e){const t=Ft();try{t.HEAPF32.set(e,Ct/4),t.draw_begin(Ct)}catch(e){Le(e,"Draw.begin")}},end(){try{Ft().draw_end()}catch(e){Le(e,"Draw.end")}},line(e,t,s,n=1){try{Ft().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Le(e,"Draw.line")}},rect(e,t,s,n=!0){try{Ft().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Le(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Ft().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Le(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{Ft().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Le(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{Ft().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Le(e,"Draw.circleOutline")}},texture(e,t,s,n=Bt){try{Ft().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Le(e,"Draw.texture")}},textureRotated(e,t,s,n,r=Bt){try{Ft().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Le(e,"Draw.textureRotated")}},setLayer(e){Ft().draw_setLayer(e)},setDepth(e){Ft().draw_setDepth(e)},getDrawCallCount:()=>Tt?Tt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Tt?Tt.draw_getPrimitiveCount():0,setBlendMode(e){Ft().draw_setBlendMode(e)},setDepthTest(e){Ft().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Ft();n.HEAPF32.set(s,At/4),n.draw_mesh(e,t,At)}catch(s){Le(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Ft(),r=Ke.get(t);if(!r)return;if($t.setBlendMode(r.blendMode),$t.setDepthTest(r.depthTest),0===r.uniforms.size)return void $t.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,At/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Dt(t);if(!(n<0)){if(je(s))Mt[o++]=10,Mt[o++]=n,Mt[o++]=s.slot??e++,Mt[o++]=s.textureId;else if("number"==typeof s)Mt[o++]=1,Mt[o++]=n,Mt[o++]=s;else if(Array.isArray(s)){Mt[o++]=s.length,Mt[o++]=n;for(let e=0;e<s.length;e++)Mt[o++]=s[e]}else"w"in s?(Mt[o++]=4,Mt[o++]=n,Mt[o++]=s.x,Mt[o++]=s.y,Mt[o++]=s.z,Mt[o++]=s.w):"z"in s?(Mt[o++]=3,Mt[o++]=n,Mt[o++]=s.x,Mt[o++]=s.y,Mt[o++]=s.z):(Mt[o++]=2,Mt[o++]=n,Mt[o++]=s.x,Mt[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(Mt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,At);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Et/4),n.draw_meshWithUniforms(e,r.shader,At,Et,o)}catch(s){Le(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Ut={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},kt=new Set;function Dt(e){const t=Ut[e];return void 0!==t?t:(kt.has(e)||(kt.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Ut).join(", ")}`)),-1)}const Lt=new Map;function Wt(e,t,s){Lt.set(e,{fn:t,scene:s??""})}function zt(e){Lt.delete(e)}function Ot(){Lt.clear()}var Ht;exports.DataType=void 0,(Ht=exports.DataType||(exports.DataType={}))[Ht.Float=1]="Float",Ht[Ht.Float2=2]="Float2",Ht[Ht.Float3=3]="Float3",Ht[Ht.Float4=4]="Float4",Ht[Ht.Int=5]="Int",Ht[Ht.Int2=6]="Int2",Ht[Ht.Int3=7]="Int3",Ht[Ht.Int4=8]="Int4";let jt=null,Nt=0,Vt=0,Xt=0;function Gt(e){jt=e,Nt=jt._malloc(262144),Vt=jt._malloc(65536),Xt=jt._malloc(256)}function qt(){jt&&(Nt&&jt._free(Nt),Vt&&jt._free(Vt),Xt&&jt._free(Xt),Nt=0,Vt=0,Xt=0),jt=null}function Yt(){if(!jt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return jt}const Jt={create(e){const t=Yt(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Nt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Xt,r).set(o),t.geometry_init(s,Nt,n,Xt,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Vt,n).set(e.indices),t.geometry_setIndices16(s,Vt,n)}else{new Uint32Array(t.HEAPU8.buffer,Vt,n).set(e.indices),t.geometry_setIndices32(s,Vt,n)}}return s},updateVertices(e,t,s=0){const n=Yt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Nt/4),n.geometry_updateVertices(e,Nt,r,s)},release(e){e>0&&Yt().geometry_release(e)},isValid:e=>!(!jt||e<=0)&&jt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Jt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(o,i,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Jt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Jt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Kt=null;function Qt(e){Kt=e}function Zt(){Kt&&ts.isInitialized()&&ts.shutdown(),Kt=null}function es(){if(!Kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Kt}const ts={init(e,t){try{return es().postprocess_init(e,t)}catch(s){return Le(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{es().postprocess_shutdown()}catch(e){Le(e,"PostProcess.shutdown")}},resize(e,t){try{es().postprocess_resize(e,t)}catch(s){Le(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return es().postprocess_addPass(e,t)}catch(t){return Le(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{es().postprocess_removePass(e)}catch(t){Le(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{es().postprocess_setPassEnabled(e,t)}catch(t){Le(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return es().postprocess_isPassEnabled(e)}catch(t){return Le(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{es().postprocess_setUniformFloat(e,t,s)}catch(s){Le(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Le(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{es().postprocess_begin()}catch(e){Le(e,"PostProcess.begin")}},end(){try{es().postprocess_end()}catch(e){Le(e,"PostProcess.end")}},getPassCount(){try{return es().postprocess_getPassCount()}catch(e){return Le(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Kt)return!1;try{return Kt.postprocess_isInitialized()}catch(e){return Le(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{es().postprocess_setBypass(e)}catch(e){Le(e,"PostProcess.setBypass")}},isBypassed(){if(!Kt)return!0;try{return Kt.postprocess_isBypassed()}catch(e){return Le(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ke.createShader(ss,"#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")},ss="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var ns;exports.RenderStage=void 0,(ns=exports.RenderStage||(exports.RenderStage={}))[ns.Background=0]="Background",ns[ns.Opaque=1]="Opaque",ns[ns.Transparent=2]="Transparent",ns[ns.Overlay=3]="Overlay";let rs=null,os=0;function is(e){rs=e,os=rs._malloc(64)}function as(){rs&&os&&(rs._free(os),os=0),rs=null}const cs={init(e,t){rs?.renderer_init(e,t)},resize(e,t){rs?.renderer_resize(e,t)},begin(e,t){if(rs&&os)try{rs.HEAPF32.set(e,os/4),rs.renderer_begin(os,t??0)}catch(e){Le(e,"Renderer.begin")}},flush(){try{rs?.renderer_flush()}catch(e){Le(e,"Renderer.flush")}},end(){try{rs?.renderer_end()}catch(e){Le(e,"Renderer.end")}},submitSprites(e){if(rs)try{rs.renderer_submitSprites(e._cpp)}catch(e){Le(e,"Renderer.submitSprites")}},submitBitmapText(e){if(rs)try{rs.renderer_submitBitmapText(e._cpp)}catch(e){Le(e,"Renderer.submitBitmapText")}},submitSpine(e){if(rs)try{rs.renderer_submitSpine?.(e._cpp)}catch(e){Le(e,"Renderer.submitSpine")}},setStage(e){rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){rs?.renderer_releaseTarget(e)},getTargetTexture:e=>rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>rs?rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>rs?{drawCalls:rs.renderer_getDrawCalls(),triangles:rs.renderer_getTriangles(),sprites:rs.renderer_getSprites(),text:rs.renderer_getText(),spine:rs.renderer_getSpine?.()??0,meshes:rs.renderer_getMeshes(),culled:rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ls=null;function us(e){ls=e}function ds(){ls=null}const hs={enable(){ls?.gl_enableErrorCheck(!0)},disable(){ls?.gl_enableErrorCheck(!1)},check:e=>ls?.gl_checkErrors(e)??0,diagnose(){ls?.renderer_diagnose()}};class ps{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(cs.resize(n,r),ts.isInitialized()&&ts.getPassCount()>0&&ts.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),cs.setViewport(0,0,n,r),cs.clearBuffers(3),cs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),cs.submitSprites(t),cs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):cs.submitSpine(t),cs.flush(),this.executeDrawCallbacks(s,o),cs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;cs.setViewport(n.x,n.y,n.w,n.h),cs.setScissor(n.x,n.y,n.w,n.h,!0),cs.clearBuffers(r),cs.setScissor(0,0,0,0,!1),cs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),cs.submitSprites(t),cs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):cs.submitSpine(t),cs.flush(),this.executeDrawCallbacks(s,o),cs.end()}executeDrawCallbacks(e,t){const s=Lt;if(s.size>0){$t.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}$t.end();for(const e of n)zt(e)}}}const fs="__scene_transition_overlay__";class gs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class _s{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,ae,{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),Wt(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ts.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ae)){const s=this.app_.world.get(e,ae);s.persistent=t,this.app_.world.insert(e,ae,s)}}}class ms{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.loadPromises_=new Map,this.app_=e}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_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??I.sceneTransitionDuration,r=t.color??{...I.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Wt(fs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;$t.setLayer(9999),$t.setDepth(9999),$t.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}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_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,zt(fs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,zt(fs),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 s=new gs(t);this.scenes_.set(e,s);const n=new _s(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=xs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 s=new gs(t);this.scenes_.set(e,s);const n=new _s(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=xs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ae)){if(this.app_.world.get(e,ae).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())zt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ts.removePass(e)}catch{}s.postProcessPasses.length=0,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)}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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Q,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Q,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ts.setEnabled(s,t)}catch{}}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,s]of this.scenes_)"running"===s.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 ys=fe(null,"SceneManager");function xs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(ys).getSceneStatus(t)&&s._fn(...n)}}}const ws=Ce([_e(ys),ge(xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),vs={name:"SceneManager",build(e){const t=new ms(e);e.insertResource(ys,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ys),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,ws)}};class bs{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_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ze,this.resources_=new ye;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(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}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 De(e),this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(ys).register(e),this}setInitialScene(e){return this.getResource(ys).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ee(this.world_,this.resources_),this.resources_.insert(xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Ot();const e=[ds,as,Zt,qt,Ye,It];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){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(xe);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ss=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ps(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case Y.FixedWidth:return o;case Y.FixedHeight:return i;case Y.Expand:return Math.max(o,i);case Y.Shrink:return Math.min(o,i);case Y.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Ts(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ae);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,c){h=Ps(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}d=h*a,u=As(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Ms(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Is(o.position.x,o.position.y,o.position.z);l.push({entity:e,viewProjection:new Float32Array(Bs(u,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Cs=new Float32Array(16);function As(e,t,s,n,r,o){const i=Cs;i.fill(0);const a=t-e,c=n-s,l=o-r;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(n+s)/c,i[14]=-(o+r)/l,i[15]=1,i}const Es=new Float32Array(16);function Ms(e,t,s,n){const r=Es;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const Rs=new Float32Array(16);function Is(e,t,s){const n=Rs;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const Fs=new Float32Array(16);function Bs(e,t){const s=Fs;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var $s,Us,ks;exports.TextAlign=void 0,($s=exports.TextAlign||(exports.TextAlign={}))[$s.Left=0]="Left",$s[$s.Center=1]="Center",$s[$s.Right=2]="Right",exports.TextVerticalAlign=void 0,(Us=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[Us.Top=0]="Top",Us[Us.Middle=1]="Middle",Us[Us.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ks=exports.TextOverflow||(exports.TextOverflow={}))[ks.Visible=0]="Visible",ks[ks.Clip=1]="Clip",ks[ks.Ellipsis=2]="Ellipsis";const Ds=L("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),Ls=L("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Ws{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I.textCanvasSize,I.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?o:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(c)),h=Math.ceil(c.length*l),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const g=Math.round(255*e.color.r),_=Math.round(255*e.color.g),m=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${_}, ${m}, ${y})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=c.length*l;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-x)/2;break;case exports.TextVerticalAlign.Bottom:w=f-x-u;break;default:w=u}else w=u;let v=w;for(const t of c){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const C=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:C,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function zs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Os(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Hs{build(e){N("Text",Ds);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Ws(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Ds));for(const e of r.keys())n.valid(e)&&n.has(e,Ds)||r.delete(e);const e=n.getEntitiesWithComponents([Ds]);for(const t of e){const e=n.get(t,Ds),o=n.has(t,Ls)?n.get(t,Ls):null,i=r.get(t);if(i&&!Os(i,e,o))continue;n.has(t,Q)||n.insert(t,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),c=n.get(t,Q);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Q,c),r.set(t,zs(e,o))}}))}}const js=new Hs,Ns=L("UIMask",{enabled:!0});function Vs(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Xs(e,t,s,n,r,o,i,a,c,l,u){const d=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function g(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*u]}const[_,m]=g(d,p),[y,x]=g(h,f),w=Math.min(_,y),v=Math.max(_,y),b=Math.min(m,x),S=Math.max(m,x);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Gs(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],c=e[5],l=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],g=e[12],_=e[13],m=e[14],y=e[15],x=n*c-r*a,w=n*l-o*a,v=n*u-i*a,b=r*l-o*c,S=r*u-i*c,P=o*u-i*l,T=d*_-h*g,C=d*m-p*g,A=d*y-f*g,E=h*m-p*_,M=h*y-f*_,R=p*y-f*m;let I=x*R-w*M+v*E+b*A-S*C+P*T;return 0===I||(I=1/I,s[0]=(c*R-l*M+u*E)*I,s[1]=(o*M-r*R-i*E)*I,s[2]=(_*P-m*S+y*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(l*A-a*R-u*C)*I,s[5]=(n*R-o*A+i*C)*I,s[6]=(m*v-g*P-y*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*M-c*A+u*T)*I,s[9]=(r*A-n*M-i*T)*I,s[10]=(g*S-_*v+y*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(c*C-a*E-l*T)*I,s[13]=(n*E-r*C+o*T)*I,s[14]=(_*w-g*b-m*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function qs(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,c=(t-r)/i*2-1,l=s[0]*a+s[4]*c+s[12],u=s[1]*a+s[5]*c+s[13],d=s[3]*a+s[7]*c+s[15];return{x:l/d,y:u/d}}function Ys(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)}function Js(e,t,s,n,r,o,i){if(!e.has(t,Ls)||!e.has(t,K))return null;const a=e.get(t,Ls),c=e.get(t,K),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return Xs(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Ks(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Ns]);if(0!==c.length)try{!function(e,t,s,n,r,o,i,a,c){const l=new Set;for(const e of n){t.get(e,Ns).enabled&&l.add(e)}const u=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(l.has(s)){const e=Js(t,s,r,o,i,a,c);e&&(n=Vs(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Js(t,e,r,o,i,a,c);s&&d(e,s)}}(e,t,s,c,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Qs{build(e){if(N("UIMask",Ns),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ks(e.wasmModule,e.world))}}const Zs=new Qs,en=L("Interactable",{enabled:!0}),tn=L("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var sn;exports.ButtonState=void 0,(sn=exports.ButtonState||(exports.ButtonState={}))[sn.Normal=0]="Normal",sn[sn.Hovered=1]="Hovered",sn[sn.Pressed=2]="Pressed",sn[sn.Disabled=3]="Disabled";const nn=L("Button",{state:exports.ButtonState.Normal,transition:null});class rn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const on=fe(new rn,"UIEvents"),an=W("ScreenSpace");function cn(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,c=o.left+e.x*i,l=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,g;if(c===l&&u===d){const e=c+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,g=t+o}else h=c+s.x,p=u+s.y,f=l+n.x,g=d+n.y;return{centerX:.5*(h+f),centerY:.5*(p+g),width:f-h,height:g-p,rect:{left:h,bottom:p,right:f,top:g}}}function ln(e,t,s,n,r,o){if(!e.has(t,Ls))return;const i=e.get(t,Ls),a=cn(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const c=e.get(t,J);if(o?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,J,c),!e.has(t,ne))return;const l=e.get(t,ne);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&ln(e,t,a.rect,a.centerX,a.centerY,!1)}class un{build(e){N("UIRect",Ls);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Oe)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([an,Ls,J]);for(const e of o)ln(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const dn=new un,hn=new Float32Array(16),pn=new Float32Array(16);let fn=!0,gn=1;class _n{build(e){N("Interactable",en),N("Button",nn);const t=e.world,s=new rn;e.insertResource(on,s);let n=null,r=null;gn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Re),ge(Oe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([tn]);for(const e of i){const s=t.get(e,tn);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*gn,c=o.screenH-e.mouseY*gn;!function(e){let t=!1;for(let s=0;s<16;s++)if(pn[s]!==e[s]){t=!0;break}t&&(pn.set(e),fn=!0)}(o.viewProjection),fn&&(Gs(o.viewProjection,hn),fn=!1);const l=qs(a,c,hn,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([en,Ls,K]);let d=null,h=-1/0;for(const e of u){t.has(e,tn)||t.insert(e,tn);if(!t.get(e,en).enabled)continue;const s=t.get(e,K),n=t.get(e,Ls),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Ys(l.x,l.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,tn)){t.get(n,tn).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,tn).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,tn);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,tn)){const e=t.get(r,tn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([nn]);for(const s of e){if(t.has(s,en)||t.insert(s,en,{enabled:!0}),!t.has(s,tn))continue;const e=t.get(s,tn),n=t.get(s,nn),r=t.get(s,en),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const e=t.get(s,Q),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,Q,e)}}},{name:"ButtonSystem"}))}}const mn=new _n,yn=L("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});class xn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){N("TextInput",yn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(I.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,c=!1,l=!0,u=0,d=0;const h=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(!h)return;const p=h,f=()=>{c||null===a||x()},g=()=>{c=!0},_=()=>{c=!1,x()},m=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,yn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(on).emit(a,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==a&&s.valid(a)&&s.has(a,yn)){const e=s.get(a,yn);e.focused=!1,e.dirty=!0}a=null};function x(){if(null===a||!s.valid(a))return;const t=s.get(a,yn);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(on).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,b()}function w(e){if(a===e)return;v();const t=s.get(e,yn);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),b())}function v(){if(null!==a&&s.valid(a)&&s.has(a,yn)){const e=s.get(a,yn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){l=!0,u=0}function S(e,i,a,c){(r.width<a||r.height<c)&&(r.width=vn(Math.max(r.width,a)),r.height=vn(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=wn(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(c-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=wn(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,s=g+(e.length-1)*f,n=f}else t=g+o.measureText(e).width,s=(c-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,a,c),m=new Uint8Array(_.data.buffer),y=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=n.get(e);void 0!==w&&y.releaseTexture(w);const v=y.createTexture(a,c,x,m.length,1,!0);n.set(e,v),t._free(x);const b=s.get(e,Q);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Q,b)}p.addEventListener("input",f),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",_),p.addEventListener("keydown",m),p.addEventListener("blur",y),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",m),p.removeEventListener("blur",y),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(on)],e=>{const t=s.getEntitiesWithComponents([yn,en]);for(const e of t){if(!s.has(e,tn))continue;if(s.get(e,tn).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([en]);for(const t of e){if(s.has(t,yn))continue;if(!s.has(t,tn))continue;if(s.get(t,tn).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,l=!l,null!==a&&s.valid(a)&&s.has(a,yn)))){s.get(a,yn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,yn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([yn,Ls]);for(const e of i){const t=s.get(e,yn);if(!t.dirty)continue;const n=s.get(e,Ls),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,Q)||s.insert(e,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function wn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function vn(e){let t=1;for(;t<e;)t*=2;return t}const bn=new xn;async function Sn(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 Pn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Tn=fe(null,"PhysicsAPI");function Cn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function An(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class En{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Pn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Sn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Ce([ge(xe)],a=>{const c=i.getEntitiesWithComponents([ce,J,K]),l=new Set;for(const r of c){l.add(r);const a=i.get(r,ce),c=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Cn(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*o,c.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Mn(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===he.Kinematic){const e=Cn(c.rotation);n._physics_setBodyTransform(r,c.position.x*o,c.position.y*o,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,J);if(!u)continue;let d=a,h=c,p=l;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=Cn(s.rotation),r=a-s.position.x,o=c-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=l-n}}u.position.x=d,u.position.y=h;const f=An(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,J,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Pn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Tn,Rn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Mn(e,t,s){const n=e.world;if(n.has(s,le)){const e=n.get(s,le);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ue)){const e=n.get(s,ue);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,de)){const e=n.get(s,de);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Rn{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(Rn.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function In(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function Fn(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Bn(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,d=a+a,h=c+c,p=l+l,f=a*d,g=a*h,_=a*p,m=c*h,y=c*p,x=l*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(m+x))*r,(g+b)*r,(_-v)*r,0,(g-b)*o,(1-(f+x))*o,(y+w)*o,0,(_+v)*i,(y-w)*i,(1-(f+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function $n(e,t,s,n,r,o,i,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=In(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let u={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const c=r.resolvePath(i),l=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===g(c)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=Fn(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=_+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=In(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,s,n)),o){new En("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;const i=g(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${i}`:i;t=await s.readText(c),o=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=o?`${o}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),u=In(e,l,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),p=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ke.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Ke.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=lt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,h,p);const f=ut(e.world,s);if(c&&e.hasResource(ys))for(const t of f.values())e.world.insert(t,ae,{scene:c,persistent:!1});if(r&&d){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const c=n.get(o.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(d,s,u,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let c=a-o;o=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const o=Number(e),i=r[e],a=l.has(o,oe)?l.get(o,oe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,c*d);let h=0;if(l.has(o,K)){const e=Bn(l.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,c=2*o,l=s._malloc(a),u=s._malloc(c),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,l,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],_=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),x=t._malloc(c);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(y,r,x,o,f,g,h),t._free(y),t._free(x),s._free(l),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(ft);t&&t.setAddressableManifest(a)}}class Un{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===g(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=g(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,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),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const kn="__preview__";const Dn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=cs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:cs.getTargetTexture(s),width:e.width,height:e.height}},release(e){cs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(cs.releaseRenderTarget(e._handle),Dn.create({width:t,height:s,depth:!0})),begin(e,t){cs.begin(t,e._handle)},end(){cs.end()},getDepthTexture:e=>cs.getTargetDepthTexture(e._handle)};let Ln=!1;var Wn;exports.LogLevel=void 0,(Wn=exports.LogLevel||(exports.LogLevel={}))[Wn.Debug=0]="Debug",Wn[Wn.Info=1]="Info",Wn[Wn.Warn=2]="Warn",Wn[Wn.Error=3]="Error";class zn{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class On{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new zn)}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,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Hn=new On;const jn=[js,Zs,dn,mn,bn];A||(A=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await c(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return l(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=E,exports.App=bs,exports.AssetPlugin=gt,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.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,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});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=pt,exports.Assets=ft,exports.AsyncCache=it,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=le,exports.Button=nn,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=de,exports.Children=ne,exports.CircleCollider=ue,exports.ClearFlags=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.Draw=$t,exports.EntityCommands=be,exports.GLDebug=hs,exports.Geometry=Jt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Me,exports.Interactable=en,exports.LocalTransform=J,exports.Logger=On,exports.Material=Ke,exports.MaterialLoader=at,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=Rn,exports.PhysicsEvents=Pn,exports.PhysicsPlugin=En,exports.PostProcess=ts,exports.PrefabServer=vt,exports.Prefabs=bt,exports.PrefabsPlugin=St,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(ys);t.register({name:kn,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(kn),this.loadPromise_=t.load(kn).then(()=>{}),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 Un(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await $n(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,kn)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(ys).getScene(kn),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,J,i);const a={isActive:!0,projectionType:G.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.ColorAndDepth};e.insert(o,Z,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(ys);await e.switchTo(kn),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.ProjectionType=G,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{we(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=ve,exports.RenderPipeline=ps,exports.RenderTexture=Dn,exports.Renderer=cs,exports.Res=ge,exports.ResMut=_e,exports.RigidBody=ce,exports.RuntimeConfig=I,exports.ScaleMode=Y,exports.SceneManager=ys,exports.SceneManagerState=ms,exports.SceneOwner=ae,exports.ScreenSpace=an,exports.ShaderSources=ot,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ee,exports.Text=Ds,exports.TextInput=yn,exports.TextInputPlugin=xn,exports.TextPlugin=Hs,exports.TextRenderer=Ws,exports.Time=xe,exports.UICameraInfo=Oe,exports.UIEventQueue=rn,exports.UIEvents=on,exports.UIInteraction=tn,exports.UIInteractionPlugin=_n,exports.UILayoutPlugin=un,exports.UIMask=Ns,exports.UIMaskPlugin=Qs,exports.UIRect=Ls,exports.Velocity=te,exports.WebAssetProvider=Un,exports.World=ze,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ae().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ae().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ae().push({schedule:e,system:t})},exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=I.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=I.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=I.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=I.canvasMatchWidthOrHeight)},exports.assetPlugin=_t,exports.clearDrawCallbacks=Ot,exports.clearUserComponents=function(){D().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=cn,exports.createMaskProcessor=Ks,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await $n(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=bs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Rt(e),qe(e),Gt(e),Qt(e),is(e),us(e);const r=new ps;s.setPipeline(r);let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function c(t,r,o){o||(o=Ts(e,n,t,r));const i=s.getResource(Oe);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(Oe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();c(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;cs.setClearColor(e.x,e.y,e.z,e.w)}const d=(a()-o)/1e3;let h;if(cs.resize(t,l),ts.isInitialized()&&ts.getPassCount()>0&&!ts.isBypassed()&&ts.resize(t,l),s.hasResource(ys)){const e=s.getResource(ys).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=Ts(e,n,t,l,s.world,h);if(c(t,l,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:Ss,width:t,height:l,elapsed:d});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}cs.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(_t),s.addPlugin(Pt),s.addPlugin(Fe),s.addPlugin(vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:jn,...t})},exports.debug=function(e,t,s){Hn.debug(e,t,s)},exports.defineComponent=L,exports.defineResource=fe,exports.defineSystem=Ce,exports.defineTag=W,exports.error=function(e,t,s){Hn.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return g(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of u)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return d[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=V,exports.getComponentAssetFields=function(e){const t=ct.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s},exports.getComponentDefaults=function(e){const t=V(e);return t?$(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Hn},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return m().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Hn.info(e,t,s)},exports.initDrawAPI=Rt,exports.initGLDebugAPI=us,exports.initGeometryAPI=Gt,exports.initMaterialAPI=qe,exports.initPostProcessAPI=Qt,exports.initRendererAPI=is,exports.inputPlugin=Fe,exports.instantiatePrefab=mt,exports.intersectRects=Vs,exports.invertMatrix4=Gs,exports.isBuiltinComponent=H,exports.isCustomExtension=y,exports.isEditor=function(){return Ln},exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Ln},exports.isTextureRef=je,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ht,exports.loadPhysicsModule=Sn,exports.loadRuntimeScene=$n,exports.loadSceneData=ut,exports.loadSceneWithAssets=dt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInWorldRect=Ys,exports.prefabsPlugin=Pt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=N,exports.registerComponentAssetFields=function(e,t){ct.set(e,t)},exports.registerDrawCallback=Wt,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ft);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=rt,exports.sceneManagerPlugin=vs,exports.screenToWorld=qs,exports.setEditorMode=function(e){Ln=e},exports.setLogLevel=function(e){Hn.setMinLevel(e)},exports.setWasmErrorHandler=De,exports.shutdownDrawAPI=It,exports.shutdownGLDebugAPI=ds,exports.shutdownGeometryAPI=qt,exports.shutdownMaterialAPI=Ye,exports.shutdownPostProcessAPI=Zt,exports.shutdownRendererAPI=as,exports.textInputPlugin=bn,exports.textPlugin=js,exports.transitionTo=async function(e,t,s){const n=e.getResource(ys);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=mn,exports.uiLayoutPlugin=dn,exports.uiMaskPlugin=Zs,exports.uiPlugins=jn,exports.unregisterDrawCallback=zt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Hn.warn(e,t,s)},exports.worldRectToScreen=Xs,exports.wrapSceneSystem=xs,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return C(await T(e))},exports.wxReadFile=b,exports.wxReadTextFile=S,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(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 2a6610731..a5f47757f 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 s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function d(){return t().now()}function f(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const _=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],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}],g={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",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},m=new Map,y=new Set;for(const e of _)for(const t of e.extensions)m.set(t,e),y.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return m.get(w(e))}function v(e){return x(e)?.editorType??"unknown"}function b(e){return x(e)?.addressableType??null}function S(e){for(const t of _)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return y.has(e.toLowerCase())}function C(){return y}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function E(){const e=[];for(const t of _)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function M(){return E().map(e=>({type:"suffix",value:e}))}function A(e){return g[e.toLowerCase()]}function R(e){const t=x(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function k(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(R(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 s.includes("no such file")||s.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 B(e){return new Promise((t,s)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(k(e,t.errMsg)))}})})}function U(e,t="utf-8"){return new Promise((s,n)=>{F().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(k(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function z(e,t){return new Promise((s,n)=>{F().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function W(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function O(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}async function L(e){return O(await W(e))}let H=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return B(e)}async readTextFile(e){return U(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},N=1920,X=1080,V=100,q=512,G={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function Y(e){e.Text&&(e.Text._default.fontFamily=G.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=G.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=G.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=G.canvasMatchWidthOrHeight)}const J=0,K=4294967295,Q=4294967295,Z=(e=0,t=0)=>({x:e,y:t}),ee=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),te=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),se=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),ne=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function re(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(re);const t={};for(const s in e)t[s]=re(e[s]);return t}let ie=0;function oe(e,t){const s=++ie;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...re(t),...e}:re(t)}}function ae(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function ce(e,t){const s=ae(),n=s.get(e);if(n)return n;const r=oe(e,t);return s.set(e,r),de(e,t,!1),r}function le(e){const t=ae(),s=t.get(e);if(s)return s;const n=oe(e,{});return t.set(e,n),de(e,{},!0),n}function ue(e){return ae().get(e)}function he(){ae().clear()}function de(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function fe(e){return!0===e._builtin}const pe=new Map;function _e(e,t){pe.set(e,t)}function ge(e){return pe.get(e)??ue(e)}function me(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return pe.set(e,s),s}const ye={Perspective:0,Orthographic:1},we={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},xe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ve=me("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),be=me("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Se=me("Sprite",{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Pe=me("Camera",{projectionType:ye.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:we.ColorAndDepth}),Ce=me("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:xe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Te=me("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ee=me("Parent",{entity:0}),Me=me("Children",{entities:[]}),Ae=me("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:Q}),Re=me("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}),Ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Fe=ce("SceneOwner",{scene:"",persistent:!1});function ke(e){const t=ge(e);return t?re(t._default):null}_e("Name",Ie);const Be=me("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Ue=me("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),$e=me("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),De=me("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ze={Static:0,Kinematic:1,Dynamic:2};let We=0;function Oe(e,t){const s=++We;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Le(e){return{_type:"res",_resource:e}}function He(e){return{_type:"res_mut",_resource:e}}class je{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 Ne{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 je(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Xe=Oe({delta:0,elapsed:0,frameCount:0},"Time");function Ve(e){return{_type:"mut",_component:e}}function qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ge(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{qe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class Ye{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>qe(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let u=null;this.world_.beginIteration();try{for(const h of n){if(null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(h,t[s])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Je(){return{_type:"commands"}}class Ke{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=fe(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Qe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ke(this,null);return this.spawned_.push(e),e}entity(e){return new Ke(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":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)}}}var Ze;!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"}(Ze||(Ze={}));let et=0;function tt(e,t,s){const n=++et;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function st(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function nt(e){st().push({schedule:Ze.Update,system:e})}function rt(e){st().push({schedule:Ze.Startup,system:e})}function it(e,t){st().push({schedule:e,system:t})}class ot{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Qe&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Ye(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Qe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class at{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 ct=Oe(new at,"Input");class lt{constructor(e){this.target_=e??null}build(e){const s=new at;e.insertResource(ct,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Ze.Last,tt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ut=new lt;function ht(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=dt(t[e]),i=dt(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function dt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ft(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}function pt(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:pt(e)}}return t}class _t{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),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.");this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return fe(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return fe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return fe(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(fe(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):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.");fe(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=ht(t._name,t._default,n);if(e.length>0)throw new Error(ft(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,pt(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(e)}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=ht(t._name,t._default,e);if(r.length>0)throw new Error(ft(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!fe(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const gt=Oe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var mt;function yt(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"}(mt||(mt={}));let wt=null,xt=null,vt=1;const bt=new Map;function St(e){wt=e,xt=e.getResourceManager(),kt()}function Pt(){0!==Mt&&wt&&(wt._free(Mt),Mt=0),bt.clear(),vt=1,Et=!1,Rt.clear(),It=null,xt=null,wt=null}function Ct(){if(!xt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return xt}const Tt={createShader:(e,t)=>Ct().createShader(e,t),releaseShader(e){e>0&&Ct().releaseShader(e)},create(e){const t=vt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??mt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return bt.set(t,s),t},get:e=>bt.get(e),setUniform(e,t,s){const n=bt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=bt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=bt.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=bt.get(e);return t?.blendMode??mt.Normal},setDepthTest(e,t){const s=bt.get(e);s&&(s.depthTest=t)},getShader(e){const t=bt.get(e);return t?.shader??0},release(e){bt.delete(e)},isValid:e=>bt.has(e),releaseAll(){bt.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??mt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=bt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=vt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return bt.set(s,n),s},toAssetData(e,t){const s=bt.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=bt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Et=!1,Mt=0;const At=4096,Rt=new Map;let It=null;function Ft(e){const t=(0===Mt&&wt&&(Mt=wt._malloc(At)),Mt);if(0===t||!wt)return{ptr:0,count:0};let s=0,n=0;const r=wt.HEAPU8,i=wt.HEAPU32,o=wt.HEAPF32;for(const[a,c]of e){if(s+128>At)break;let e=Rt.get(a);e||(It||(It=new TextEncoder),e=It.encode(a),Rt.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function kt(){if(!wt||Et)return;wt.materialDataProvider=(e,t,s,n,r)=>{const i=bt.get(e);if(!i)return wt.HEAPU32[t>>2]=0,wt.HEAPU32[s>>2]=0,wt.HEAPU32[n>>2]=0,void(wt.HEAPU32[r>>2]=0);wt.HEAPU32[t>>2]=i.shader,wt.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=Ft(i.uniforms);wt.HEAPU32[n>>2]=o,wt.HEAPU32[r>>2]=a},Et=!0}const Bt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Ut{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&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();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class $t{constructor(e,t=""){this.cache_=new Ut,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&&(Tt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Tt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Tt.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const Dt=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"}]}]]);function zt(e,t){Dt.set(e,t)}function Wt(e){const t=Dt.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function Ot(e){return Dt.get(e)?.fields??[]}function Lt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Ie,{value:n.name}),!1!==n.visible)for(const s of n.components)jt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function Ht(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Dt.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,u=new Map,h=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);h.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Dt.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=h.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ie,{value:s.name}),!1!==s.visible)for(const n of s.components)jt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function jt(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=ge(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Nt(e,t){const s=e.getEntitiesWithComponents([Pe]);for(const n of s){const s=e.get(n,Pe);s&&(s.aspectRatio=t,e.insert(n,Pe,s))}}function Xt(e,t){const s=e.getEntitiesWithComponents([Ie]);for(const n of s){const s=e.get(n,Ie);if(s&&s.value===t)return n}return null}class Vt{constructor(e){this.textureCache_=new Ut,this.shaderCache_=new Ut,this.jsonCache_=new Ut,this.textCache_=new Ut,this.binaryCache_=new Ut,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ut,this.prefabCache_=new Ut,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.module_=e,this.canvas_=h(G.textCanvasSize,G.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 $t(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);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 s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}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(),Tt.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 s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),u="binary"===x(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Ht(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}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},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"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 s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{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 s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Tt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Tt.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const qt=Oe(null,"Assets");class Gt{build(e){const t=e.wasmModule;t?e.insertResource(qt,new Vt(t)):console.warn("AssetPlugin: No WASM module available")}}const Yt=new Gt;class Jt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.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,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});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 Kt(e,t){const s=e.getResource(qt);s&&s.registerEmbeddedAssets(t)}async function Qt(e,t,s){const{entities:n,rootId:r}=await es(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await Ht(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Zt=10;async function es(e,t,s,n,r,i=0){if(i>Zt)throw new Error(`Prefab nesting depth exceeded ${Zt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await es(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,h={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};ts(h,t),c.push(h)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function ts(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class ss{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Qt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ns=Oe(null,"Prefabs");class rs{constructor(){this.name="PrefabsPlugin",this.dependencies=[qt]}build(e){const t=e.getResource(qt);e.insertResource(ns,new ss(e.world,t))}}const is=new rs;let os=null,as=0,cs=0,ls=0;const us=new Float32Array(256);function hs(e){os=e,as=os._malloc(64),cs=os._malloc(64),ls=os._malloc(1024)}function ds(){os&&(as&&(os._free(as),as=0),cs&&(os._free(cs),cs=0),ls&&(os._free(ls),ls=0)),os=null}function fs(){if(!os)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return os}const ps={r:1,g:1,b:1,a:1},_s={begin(e){const t=fs();t.HEAPF32.set(e,as/4),t.draw_begin(as)},end(){fs().draw_end()},line(e,t,s,n=1){fs().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){fs().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){fs().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){fs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){fs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=ps){fs().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=ps){fs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){fs().draw_setLayer(e)},setDepth(e){fs().draw_setDepth(e)},getDrawCallCount:()=>os?os.draw_getDrawCallCount():0,getPrimitiveCount:()=>os?os.draw_getPrimitiveCount():0,setBlendMode(e){fs().draw_setBlendMode(e)},setDepthTest(e){fs().draw_setDepthTest(e)},drawMesh(e,t,s){const n=fs();n.HEAPF32.set(s,cs/4),n.draw_mesh(e,t,cs)},drawMeshWithMaterial(e,t,s){const n=fs(),r=Tt.get(t);if(!r)return;if(_s.setBlendMode(r.blendMode),_s.setDepthTest(r.depthTest),0===r.uniforms.size)return void _s.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,cs/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=ms(t);if(!(n<0)){if(yt(s))us[i++]=10,us[i++]=n,us[i++]=s.slot??e++,us[i++]=s.textureId;else if("number"==typeof s)us[i++]=1,us[i++]=n,us[i++]=s;else if(Array.isArray(s)){us[i++]=s.length,us[i++]=n;for(let e=0;e<s.length;e++)us[i++]=s[e]}else"w"in s?(us[i++]=4,us[i++]=n,us[i++]=s.x,us[i++]=s.y,us[i++]=s.z,us[i++]=s.w):"z"in s?(us[i++]=3,us[i++]=n,us[i++]=s.x,us[i++]=s.y,us[i++]=s.z):(us[i++]=2,us[i++]=n,us[i++]=s.x,us[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(us.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),ls/4),n.draw_meshWithUniforms(e,r.shader,cs,ls,i)):n.draw_mesh(e,r.shader,cs)}},gs={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function ms(e){return gs[e]??-1}const ys=new Map;function ws(e,t,s){ys.set(e,{fn:t,scene:s??""})}function xs(e){ys.delete(e)}function vs(){ys.clear()}var bs;!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"}(bs||(bs={}));let Ss=null,Ps=0,Cs=0,Ts=0;function Es(e){Ss=e,Ps=Ss._malloc(262144),Cs=Ss._malloc(65536),Ts=Ss._malloc(256)}function Ms(){Ss&&(Ps&&Ss._free(Ps),Cs&&Ss._free(Cs),Ts&&Ss._free(Ts),Ps=0,Cs=0,Ts=0),Ss=null}function As(){if(!Ss)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ss}const Rs={create(e){const t=As(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ps/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ts,r).set(i),t.geometry_init(s,Ps,n,Ts,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Cs,n).set(e.indices),t.geometry_setIndices16(s,Cs,n)}else{new Uint32Array(t.HEAPU8.buffer,Cs,n).set(e.indices),t.geometry_setIndices32(s,Cs,n)}}return s},updateVertices(e,t,s=0){const n=As(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Ps/4),n.geometry_updateVertices(e,Ps,r,s)},release(e){e>0&&As().geometry_release(e)},isValid:e=>!(!Ss||e<=0)&&Ss.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Rs.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:bs.Float2},{name:"a_texCoord",type:bs.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Rs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:bs.Float2},{name:"a_texCoord",type:bs.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Rs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:bs.Float2},{name:"a_texCoord",type:bs.Float2}],indices:new Uint16Array(o)})}};let Is=null;function Fs(e){Is=e}function ks(){Is&&Us.isInitialized()&&Us.shutdown(),Is=null}function Bs(){if(!Is)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Is}const Us={init:(e,t)=>Bs().postprocess_init(e,t),shutdown(){Bs().postprocess_shutdown()},resize(e,t){Bs().postprocess_resize(e,t)},addPass:(e,t)=>Bs().postprocess_addPass(e,t),removePass(e){Bs().postprocess_removePass(e)},setEnabled(e,t){Bs().postprocess_setPassEnabled(e,t)},isEnabled:e=>Bs().postprocess_isPassEnabled(e),setUniform(e,t,s){Bs().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Bs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Bs().postprocess_begin()},end(){Bs().postprocess_end()},getPassCount:()=>Bs().postprocess_getPassCount(),isInitialized:()=>!!Is&&Is.postprocess_isInitialized(),setBypass(e){Bs().postprocess_setBypass(e)},isBypassed:()=>!Is||Is.postprocess_isBypassed(),createBlur:()=>Tt.createShader($s,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Tt.createShader($s,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Tt.createShader($s,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Tt.createShader($s,"#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")},$s="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Ds;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ds||(Ds={}));let zs=null,Ws=0;function Os(e){zs=e,Ws=zs._malloc(64)}function Ls(){zs&&Ws&&(zs._free(Ws),Ws=0),zs=null}const Hs={init(e,t){zs?.renderer_init(e,t)},resize(e,t){zs?.renderer_resize(e,t)},begin(e,t){zs&&Ws&&(zs.HEAPF32.set(e,Ws/4),zs.renderer_begin(Ws,t??0))},flush(){zs?.renderer_flush()},end(){zs?.renderer_end()},submitSprites(e){zs&&zs.renderer_submitSprites(e._cpp)},submitBitmapText(e){zs&&zs.renderer_submitBitmapText(e._cpp)},submitSpine(e){zs&&zs.renderer_submitSpine?.(e._cpp)},setStage(e){zs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>zs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){zs?.renderer_releaseTarget(e)},getTargetTexture:e=>zs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){zs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){zs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){zs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){zs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>zs?zs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>zs?{drawCalls:zs.renderer_getDrawCalls(),triangles:zs.renderer_getTriangles(),sprites:zs.renderer_getSprites(),text:zs.renderer_getText(),spine:zs.renderer_getSpine?.()??0,meshes:zs.renderer_getMeshes(),culled:zs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let js=null;function Ns(e){js=e}function Xs(){js=null}const Vs={enable(){js?.gl_enableErrorCheck(!0)},disable(){js?.gl_enableErrorCheck(!1)},check:e=>js?.gl_checkErrors(e)??0,diagnose(){js?.renderer_diagnose()}};class qs{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Hs.resize(n,r),Us.isInitialized()&&Us.getPassCount()>0&&Us.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Hs.setViewport(0,0,n,r),Hs.clearBuffers(3),Hs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Hs.submitSprites(t),Hs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Hs.submitSpine(t),Hs.flush(),this.executeDrawCallbacks(s,i),Hs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Hs.setViewport(n.x,n.y,n.w,n.h),Hs.setScissor(n.x,n.y,n.w,n.h,!0),Hs.clearBuffers(r),Hs.setScissor(0,0,0,0,!1),Hs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Hs.submitSprites(t),Hs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Hs.submitSpine(t),Hs.flush(),this.executeDrawCallbacks(s,i),Hs.end()}executeDrawCallbacks(e,t){const s=ys;if(s.size>0){_s.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}_s.end();for(const e of n)xs(e)}}}const Gs="__scene_transition_overlay__";class Ys{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Js{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,Fe,{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),ws(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Us.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Us.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Fe)){const s=this.app_.world.get(e,Fe);s.persistent=t,this.app_.world.insert(e,Fe,s)}}}class Ks{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.loadPromises_=new Map,this.app_=e}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_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??G.sceneTransitionDuration,r=t.color??{...G.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ws(Gs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;_s.setLayer(9999),_s.setDepth(9999),_s.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}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_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,xs(Gs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,xs(Gs),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 s=new Ys(t);this.scenes_.set(e,s);const n=new Js(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(qt)?this.app_.getResource(qt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(qt)&&(t.assetServer=this.app_.getResource(qt));const n=await Ht(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Zs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 s=new Ys(t);this.scenes_.set(e,s);const n=new Js(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(qt)?this.app_.getResource(qt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(qt)&&(t.assetServer=this.app_.getResource(qt));const n=await Ht(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Zs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,Fe)){if(this.app_.world.get(e,Fe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())xs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Us.removePass(e)}catch{}s.postProcessPasses.length=0,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)}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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Se,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Se,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Us.setEnabled(s,t)}catch{}}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,s]of this.scenes_)"running"===s.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 Qs=Oe(null,"SceneManager");function Zs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Qs).getSceneStatus(t)&&s._fn(...n)}}}const en=tt([He(Qs),Le(Xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),tn={name:"SceneManager",build(e){const t=new Ks(e);e.insertResource(Qs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Qs),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Ze.Startup,s),e.addSystemToSchedule(Ze.Last,en)}};class sn{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_=new Set,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Ze.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ze.FixedPreUpdate),this.runSchedule(Ze.FixedUpdate),this.runSchedule(Ze.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Ze.PreUpdate),this.runSchedule(Ze.Update),this.runSchedule(Ze.PostUpdate),this.runSchedule(Ze.Last),requestAnimationFrame(this.mainLoop)},this.world_=new _t,this.resources_=new Ne;for(const e of Object.values(Ze))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new sn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this}addSystem(e){return this.addSystemToSchedule(Ze.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ze.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(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}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}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(Qs).register(e),this}setInitialScene(e){return this.getResource(Qs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new ot(this.world_,this.resources_),this.resources_.insert(Xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ze.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,vs();const e=[Xs,Ls,ks,Ms,Pt,ds];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){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}}updateTime(e){const t=this.resources_.get(Xe);t.delta=e,t.elapsed+=e,t.frameCount++}}function nn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const rn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function on(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case xe.FixedWidth:return i;case xe.FixedHeight:return o;case xe.Expand:return Math.max(i,o);case xe.Shrink:return Math.min(i,o);case xe.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function an(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,Fe);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let u,h=0,d=0;if(r.projectionType===ye.Orthographic){if(d=r.orthoSize,c){d=on(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}h=d*a,u=ln(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=hn(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=fn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(_n(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const cn=new Float32Array(16);function ln(e,t,s,n,r,i){const o=cn;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const un=new Float32Array(16);function hn(e,t,s,n){const r=un;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const dn=new Float32Array(16);function fn(e,t,s){const n=dn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const pn=new Float32Array(16);function _n(e,t){const s=pn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var gn,mn,yn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(gn||(gn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(mn||(mn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(yn||(yn={}));const wn=ce("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:gn.Left,verticalAlign:mn.Top,wordWrap:!0,overflow:yn.Visible,lineHeight:1.2}),xn=ce("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class vn{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(G.textCanvasSize,G.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===yn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),g=Math.round(255*e.color.g),m=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${g}, ${m}, ${y})`,r&&e.overflow===yn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case mn.Top:x=u;break;case mn.Middle:x=(p-w)/2;break;case mn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case gn.Left:n=u;break;case gn.Center:n=f/2;break;case gn.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===yn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case gn.Left:return"left";case gn.Center:return"center";case gn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function bn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Sn(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Pn{build(e){_e("Text",wn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new vn(t),n=e.world,r=new Map;e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,wn));for(const e of r.keys())n.valid(e)&&n.has(e,wn)||r.delete(e);const e=n.getEntitiesWithComponents([wn]);for(const t of e){const e=n.get(t,wn),i=n.has(t,xn)?n.get(t,xn):null,o=r.get(t);if(o&&!Sn(o,e,i))continue;n.has(t,Se)||n.insert(t,Se,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),c=n.get(t,Se);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Se,c),r.set(t,bn(e,i))}}))}}const Cn=new Pn,Tn=ce("UIMask",{enabled:!0});function En(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function Mn(e,t,s,n,r,i,o,a,c,l,u){const h=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*u]}const[g,m]=_(h,f),[y,w]=_(d,p),x=Math.min(g,y),v=Math.max(g,y),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function An(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],_=e[12],g=e[13],m=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*u-o*a,b=r*l-i*c,S=r*u-o*c,P=i*u-o*l,C=h*g-d*_,T=h*m-f*_,E=h*y-p*_,M=d*m-f*g,A=d*y-p*g,R=f*y-p*m;let I=w*R-x*A+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*R-l*A+u*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-u*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(m*v-_*P-y*x)*I,s[7]=(h*P-f*v+p*x)*I,s[8]=(a*A-c*E+u*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-g*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(g*x-_*b-m*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function Rn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],u=s[1]*a+s[5]*c+s[13],h=s[3]*a+s[7]*c+s[15];return{x:l/h,y:u/h}}function In(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function Fn(e,t,s,n,r,i,o){if(!e.has(t,xn)||!e.has(t,be))return null;const a=e.get(t,xn),c=e.get(t,be),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return Mn(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function kn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Tn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,Tn).enabled&&l.add(e)}const u=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,Ee);){const e=t.get(n,Ee);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(l.has(s)){const e=Fn(t,s,r,i,o,a,c);e&&(n=En(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=Fn(t,e,r,i,o,a,c);s&&h(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Bn{build(e){if(_e("UIMask",Tn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(kn(e.wasmModule,e.world))}}const Un=new Bn,$n=ce("Interactable",{enabled:!0}),Dn=ce("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var zn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(zn||(zn={}));const Wn=ce("Button",{state:zn.Normal,transition:null});class On{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Ln=Oe(new On,"UIEvents"),Hn=le("ScreenSpace");function jn(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,u=i.bottom+e.y*a,h=i.bottom+t.y*a;let d,f,p,_;if(c===l&&u===h){const e=c+s.x,t=u+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=u+s.y,p=l+n.x,_=h+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Nn(e,t,s,n,r,i){if(!e.has(t,xn))return;const o=e.get(t,xn),a=jn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,ve);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,ve,c),!e.has(t,Me))return;const l=e.get(t,Me);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&Nn(e,t,a.rect,a.centerX,a.centerY,!1)}class Xn{build(e){_e("UIRect",xn);const t=e.world;e.addSystemToSchedule(Ze.PreUpdate,tt([Le(gt)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Hn,xn,ve]);for(const e of i)Nn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Vn=new Xn,qn=new Float32Array(16),Gn=new Float32Array(16);let Yn=!0,Jn=1;class Kn{build(e){_e("Interactable",$n),_e("Button",Wn);const t=e.world,s=new On;e.insertResource(Ln,s);let n=null,r=null;Jn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ze.PreUpdate,tt([Le(ct),Le(gt)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([Dn]);for(const e of o){const s=t.get(e,Dn);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*Jn,c=i.screenH-e.mouseY*Jn;!function(e){let t=!1;for(let s=0;s<16;s++)if(Gn[s]!==e[s]){t=!0;break}t&&(Gn.set(e),Yn=!0)}(i.viewProjection),Yn&&(An(i.viewProjection,qn),Yn=!1);const l=Rn(a,c,qn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([$n,xn,be]);let h=null,d=-1/0;for(const e of u){t.has(e,Dn)||t.insert(e,Dn);if(!t.get(e,$n).enabled)continue;const s=t.get(e,be),n=t.get(e,xn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(In(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Se)&&(s=t.get(e,Se).layer),s>=d&&(d=s,h=e)}}if(n!==h){if(null!==n&&t.valid(n)&&t.has(n,Dn)){t.get(n,Dn).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,Dn).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Dn);e.pressed=!0,e.justPressed=!0,r=h,s.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Dn)){const e=t.get(r,Dn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ze.Update,tt([],()=>{const e=t.getEntitiesWithComponents([Wn]);for(const s of e){if(t.has(s,$n)||t.insert(s,$n,{enabled:!0}),!t.has(s,Dn))continue;const e=t.get(s,Dn),n=t.get(s,Wn),r=t.get(s,$n),i=n.state;if(r.enabled?e.pressed?n.state=zn.Pressed:e.hovered?n.state=zn.Hovered:n.state=zn.Normal:n.state=zn.Disabled,i!==n.state&&n.transition&&t.has(s,Se)){const e=t.get(s,Se),r=n.transition;switch(n.state){case zn.Normal:e.color={...r.normalColor};break;case zn.Hovered:e.color={...r.hoveredColor};break;case zn.Pressed:e.color={...r.pressedColor};break;case zn.Disabled:e.color={...r.disabledColor}}t.insert(s,Se,e)}}},{name:"ButtonSystem"}))}}const Qn=new Kn,Zn=ce("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});class er{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){_e("TextInput",Zn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=h(G.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,u=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||w()},_=()=>{a=!0},g=()=>{a=!1,w()},m=t=>{if(null===o)return;if("Escape"===t.key)return void v();const n=s.get(o,Zn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Ln).emit(o,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==o&&s.valid(o)&&s.has(o,Zn)){const e=s.get(o,Zn);e.focused=!1,e.dirty=!0}o=null};function w(){if(null===o||!s.valid(o))return;const t=s.get(o,Zn);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(Ln).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,b()}function x(e){if(o===e)return;v();const t=s.get(e,Zn);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),b())}function v(){if(null!==o&&s.valid(o)&&s.has(o,Zn)){const e=s.get(o,Zn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function b(){c=!0,l=0}function S(e,o,a,l){(r.width<a||r.height<l)&&(r.width=sr(Math.max(r.width,a)),r.height=sr(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const h=0===o.value.length,d=h?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=h?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=tr(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=tr(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const g=i.getImageData(0,0,a,l),m=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,m.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Se);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Se,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",g),f.addEventListener("keydown",m),f.addEventListener("blur",y),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",g),f.removeEventListener("keydown",m),f.removeEventListener("blur",y),f.remove()},e.addSystemToSchedule(Ze.PreUpdate,tt([Le(Ln)],e=>{const t=s.getEntitiesWithComponents([Zn,$n]);for(const e of t){if(!s.has(e,Dn))continue;if(s.get(e,Dn).justPressed)return void x(e)}if(null!==o){const e=s.getEntitiesWithComponents([$n]);for(const t of e){if(s.has(t,Zn))continue;if(!s.has(t,Dn))continue;if(s.get(t,Dn).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,Zn)))){s.get(o,Zn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Zn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Zn,xn]);for(const e of a){const t=s.get(e,Zn);if(!t.dirty)continue;const n=s.get(e,xn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Se)||s.insert(e,Se,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function tr(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function sr(e){let t=1;for(;t<e;)t*=2;return t}const nr=new er;async function rr(e,t,s){const n=e.getResource(Qs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function ir(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 or=Oe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ar=Oe(null,"PhysicsAPI");function cr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function lr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ur{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(or,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=ir(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Ce]);for(const s of t){const t=e.world.get(s,Ce);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Ze.PostUpdate,tt([Le(Xe)],a=>{const c=o.getEntitiesWithComponents([Be,ve,be]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,Be),c=o.get(r,be);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=cr(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),hr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ze.Kinematic){const e=cr(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const u=e.world.get(o,ve);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,Ee)){const t=e.world.get(o,Ee);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,be)){const s=e.world.get(t.entity,be),n=cr(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),u=Math.sin(-n);h=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),d=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}u.position.x=h,u.position.y=d;const p=lr(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,ve,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(or,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(ar,dr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function hr(e,t,s){const n=e.world;if(n.has(s,Ue)){const e=n.get(s,Ue);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,$e)){const e=n.get(s,$e);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,De)){const e=n.get(s,De);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class dr{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(dr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function fr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function pr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function _r(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,g=a*f,m=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(m+w))*r,(_+b)*r,(g-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(g+v)*o,(y-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function gr(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=fr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let u={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===x(c)?.contentType;let h,d;if(u){const e=await r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=pr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=fr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,s,n)),i){new ur("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=x(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),u=fr(e,l,!1),h=e.getResourceManager();n[r]=h.loadBitmapFont(t,u,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Tt.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Tt.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Ot(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=Lt(e.world,s);if(c&&e.hasResource(Qs))for(const t of p.values())e.world.insert(t,Fe,{scene:c,persistent:!1});if(r&&h){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(h,s,u,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,Re)?l.get(i,Re):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(o,c*h);let d=0;if(l.has(i,be)){const e=_r(l.get(i,be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),u=s._malloc(c),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,u,h,f);const p=s.HEAPU32[h>>2],_=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(m),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(e,t,r,h,n)}if(a){const t=e.getResource(qt);t&&t.setAddressableManifest(a)}}function mr(e,t,s){return{name:e,data:t,async setup(){await gr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class yr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===x(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,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),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const wr="__preview__";class xr{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(Qs);t.register({name:wr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(wr),this.loadPromise_=t.load(wr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new yr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await gr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,wr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Pe]);for(const n of s){if(e.get(n,Pe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([Ce]);for(const r of n){const n=e.get(r,Ce);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Qs).getScene(wr),i=r?r.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,ve,o);const a={isActive:!0,projectionType:ye.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:we.ColorAndDepth};e.insert(i,Pe,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(Qs);await e.switchTo(wr),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 vr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Hs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Hs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Hs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Hs.releaseRenderTarget(e._handle),vr.create({width:t,height:s,depth:!0})),begin(e,t){Hs.begin(t,e._handle)},end(){Hs.end()},getDepthTexture:e=>Hs.getTargetDepthTexture(e._handle)};let br=!1;function Sr(e){br=e}function Pr(){return br}function Cr(){return!br}var Tr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Tr||(Tr={}));class Er{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Tr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Tr.Debug:console.debug(t,s);break;case Tr.Info:console.log(t,s);break;case Tr.Warn:console.warn(t,s);break;case Tr.Error:console.error(t,s)}}}class Mr{constructor(){this.handlers_=[],this.minLevel_=Tr.Info,this.addHandler(new Er)}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,s){this.log(Tr.Debug,e,t,s)}info(e,t,s){this.log(Tr.Info,e,t,s)}warn(e,t,s){this.log(Tr.Warn,e,t,s)}error(e,t,s){this.log(Tr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Ar=new Mr;function Rr(){return Ar}function Ir(e){Ar.setMinLevel(e)}function Fr(e,t,s){Ar.debug(e,t,s)}function kr(e,t,s){Ar.info(e,t,s)}function Br(e,t,s){Ar.warn(e,t,s)}function Ur(e,t,s){Ar.error(e,t,s)}const $r=[Cn,Un,Vn,Qn,nr];function Dr(e,t){return function(e,t){const s=sn.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),hs(e),St(e),Es(e),Fs(e),Os(e),Ns(e);const r=new qs;s.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=an(e,n,t,r));const o=s.getResource(gt);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(gt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Hs.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(Hs.resize(t,c),Us.isInitialized()&&Us.getPassCount()>0&&!Us.isBypassed()&&Us.resize(t,c),s.hasResource(Qs)){const e=s.getResource(Qs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=an(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:rn,width:t,height:c,elapsed:u});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}Hs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Ze.First,c),s.addSystemToSchedule(Ze.Last,l),s.addPlugin(Yt),s.addPlugin(is),s.addPlugin(ut),s.addPlugin(tn),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:$r,...t})}H||(H=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{sn as App,Gt as AssetPlugin,Jt as AssetRefCounter,Vt as AssetServer,qt as Assets,Ut as AsyncCache,Ae as BitmapText,mt as BlendMode,ze as BodyType,Ue as BoxCollider,Wn as Button,zn as ButtonState,Pe as Camera,Ce as Canvas,De as CapsuleCollider,Me as Children,$e as CircleCollider,we as ClearFlags,Je as Commands,Qe as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,bs as DataType,_s as Draw,Ke as EntityCommands,Vs as GLDebug,Rs as Geometry,J as INVALID_ENTITY,Q as INVALID_FONT,K as INVALID_TEXTURE,ct as Input,lt as InputPlugin,at as InputState,$n as Interactable,ve as LocalTransform,Tr as LogLevel,Mr as Logger,Tt as Material,$t as MaterialLoader,Ve as Mut,Ie as Name,Ee as Parent,dr as Physics,or as PhysicsEvents,ur as PhysicsPlugin,Us as PostProcess,ss as PrefabServer,ns as Prefabs,rs as PrefabsPlugin,xr as PreviewPlugin,ye as ProjectionType,Ge as Query,Ye as QueryInstance,qs as RenderPipeline,Ds as RenderStage,vr as RenderTexture,Hs as Renderer,Le as Res,He as ResMut,Be as RigidBody,G as RuntimeConfig,xe as ScaleMode,Qs as SceneManager,Ks as SceneManagerState,Fe as SceneOwner,Ze as Schedule,Hn as ScreenSpace,Bt as ShaderSources,Re as SpineAnimation,Se as Sprite,ot as SystemRunner,wn as Text,gn as TextAlign,Zn as TextInput,er as TextInputPlugin,yn as TextOverflow,Pn as TextPlugin,vn as TextRenderer,mn as TextVerticalAlign,Xe as Time,gt as UICameraInfo,On as UIEventQueue,Ln as UIEvents,Dn as UIInteraction,Kn as UIInteractionPlugin,Xn as UILayoutPlugin,Tn as UIMask,Bn as UIMaskPlugin,xn as UIRect,Te as Velocity,yr as WebAssetProvider,_t as World,be as WorldTransform,rt as addStartupSystem,nt as addSystem,it as addSystemToSchedule,Y as applyRuntimeConfig,Yt as assetPlugin,vs as clearDrawCallbacks,he as clearUserComponents,se as color,jn as computeUIRectLayout,kn as createMaskProcessor,mr as createRuntimeSceneConfig,Dr as createWebApp,Fr as debug,ce as defineComponent,Oe as defineResource,tt as defineSystem,le as defineTag,Ur as error,Xt as findEntityByName,nn as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,C as getAllAssetExtensions,A as getAssetMimeType,x as getAssetTypeEntry,ge as getComponent,Wt as getComponentAssetFields,ke as getComponentDefaults,E as getCustomExtensions,v as getEditorType,Rr as getLogger,t as getPlatform,n as getPlatformType,ue as getUserComponent,M as getWeChatPackOptions,kr as info,hs as initDrawAPI,Ns as initGLDebugAPI,Es as initGeometryAPI,St as initMaterialAPI,Fs as initPostProcessAPI,Os as initRendererAPI,ut as inputPlugin,Qt as instantiatePrefab,En as intersectRects,An as invertMatrix4,fe as isBuiltinComponent,R as isCustomExtension,Pr as isEditor,P as isKnownAssetExtension,s as isPlatformInitialized,Cr as isRuntime,yt as isTextureRef,r as isWeChat,i as isWeb,jt as loadComponent,ir as loadPhysicsModule,gr as loadRuntimeScene,Lt as loadSceneData,Ht as loadSceneWithAssets,T as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,In as pointInWorldRect,is as prefabsPlugin,ne as quat,_e as registerComponent,zt as registerComponentAssetFields,ws as registerDrawCallback,Kt as registerEmbeddedAssets,kt as registerMaterialCallback,tn as sceneManagerPlugin,Rn as screenToWorld,Sr as setEditorMode,Ir as setLogLevel,ds as shutdownDrawAPI,Xs as shutdownGLDebugAPI,Ms as shutdownGeometryAPI,Pt as shutdownMaterialAPI,ks as shutdownPostProcessAPI,Ls as shutdownRendererAPI,nr as textInputPlugin,Cn as textPlugin,rr as transitionTo,Qn as uiInteractionPlugin,Vn as uiLayoutPlugin,Un as uiMaskPlugin,$r as uiPlugins,xs as unregisterDrawCallback,Nt as updateCameraAspectRatio,Z as vec2,ee as vec3,te as vec4,Br as warn,Mn as worldRectToScreen,Zs as wrapSceneSystem,$ as wxFileExists,D as wxFileExistsSync,O as wxGetImagePixels,W as wxLoadImage,L as wxLoadImagePixels,B as wxReadFile,U as wxReadTextFile,z 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 s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function h(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function d(){return t().now()}function f(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const _=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],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}],m={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",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},g=new Map,y=new Set;for(const e of _)for(const t of e.extensions)g.set(t,e),y.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return g.get(w(e))}function v(e){return x(e)?.editorType??"unknown"}function b(e){return x(e)?.addressableType??null}function S(e){for(const t of _)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return y.has(e.toLowerCase())}function C(){return y}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function E(){const e=[];for(const t of _)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function M(){return E().map(e=>({type:"suffix",value:e}))}function A(e){return m[e.toLowerCase()]}function R(e){const t=x(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function $(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(R(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 s.includes("no such file")||s.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 k(e){return new Promise((t,s)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error($(e,t.errMsg)))}})})}function B(e,t="utf-8"){return new Promise((s,n)=>{F().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error($(e,t.errMsg)))}})})}function U(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function z(e,t){return new Promise((s,n)=>{F().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function W(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function O(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}async function L(e){return O(await W(e))}let H=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return k(e)}async readTextFile(e){return B(e)}async fileExists(e){return U(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},N=1920,X=1080,V=100,q=512,G={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function Y(e){e.Text&&(e.Text._default.fontFamily=G.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=G.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=G.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=G.canvasMatchWidthOrHeight)}const J=0,K=4294967295,Q=4294967295,Z=(e=0,t=0)=>({x:e,y:t}),ee=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),te=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),se=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),ne=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function re(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(re);const t={};for(const s in e)t[s]=re(e[s]);return t}let ie=0;function oe(e,t){const s=++ie;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...re(t),...e}:re(t)}}function ae(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function ce(e,t){const s=ae(),n=s.get(e);if(n)return n;const r=oe(e,t);return s.set(e,r),de(e,t,!1),r}function le(e){const t=ae(),s=t.get(e);if(s)return s;const n=oe(e,{});return t.set(e,n),de(e,{},!0),n}function he(e){return ae().get(e)}function ue(){ae().clear()}function de(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function fe(e){return!0===e._builtin}const pe=new Map;function _e(e,t){pe.set(e,t)}function me(e){return pe.get(e)??he(e)}function ge(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return pe.set(e,s),s}const ye={Perspective:0,Orthographic:1},we={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},xe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ve=ge("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),be=ge("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Se=ge("Sprite",{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Pe=ge("Camera",{projectionType:ye.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:we.ColorAndDepth}),Ce=ge("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:xe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Te=ge("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ee=ge("Parent",{entity:0}),Me=ge("Children",{entities:[]}),Ae=ge("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:Q}),Re=ge("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}),Ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Fe=ce("SceneOwner",{scene:"",persistent:!1});function $e(e){const t=me(e);return t?re(t._default):null}_e("Name",Ie);const ke=ge("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Be=ge("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=ge("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),De=ge("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ze={Static:0,Kinematic:1,Dynamic:2};let We=0;function Oe(e,t){const s=++We;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Le(e){return{_type:"res",_resource:e}}function He(e){return{_type:"res_mut",_resource:e}}class je{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 Ne{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 je(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Xe=Oe({delta:0,elapsed:0,frameCount:0},"Time");function Ve(e){return{_type:"mut",_component:e}}function qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ge(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{qe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class Ye{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>qe(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let h=null;this.world_.beginIteration();try{for(const u of n){if(null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Je(){return{_type:"commands"}}class Ke{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=fe(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Qe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ke(this,null);return this.spawned_.push(e),e}entity(e){return new Ke(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":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)}}}var Ze;!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"}(Ze||(Ze={}));let et=0;function tt(e,t,s){const n=++et;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function st(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function nt(e){st().push({schedule:Ze.Update,system:e})}function rt(e){st().push({schedule:Ze.Startup,system:e})}function it(e,t){st().push({schedule:e,system:t})}class ot{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Qe&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Ye(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Qe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class at{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 ct=Oe(new at,"Input");class lt{constructor(e){this.target_=e??null}build(e){const s=new at;e.insertResource(ct,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Ze.Last,tt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ht=new lt;function ut(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=dt(t[e]),i=dt(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function dt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ft(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let pt=null;function _t(e){pt=e}function mt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),pt&&pt(e,t)}function gt(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:gt(e)}}return t}class yt{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}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 mt(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){mt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){mt(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){mt(t,`removeParent(entity=${e})`)}}insert(e,t,s){return fe(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return fe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return fe(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(fe(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return mt(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):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.");fe(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=ut(t._name,t._default,n);if(e.length>0)throw new Error(ft(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,gt(r))}catch(s){mt(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return mt(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return mt(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){mt(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=ut(t._name,t._default,e);if(r.length>0)throw new Error(ft(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!fe(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const wt=Oe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var xt;function vt(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"}(xt||(xt={}));let bt=null,St=null,Pt=1;const Ct=new Map;function Tt(e){bt=e,St=e.getResourceManager(),Ut()}function Et(){0!==It&&bt&&(bt._free(It),It=0),Ct.clear(),Pt=1,Rt=!1,$t.clear(),kt=null,St=null,bt=null}function Mt(){if(!St)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return St}const At={createShader:(e,t)=>Mt().createShader(e,t),releaseShader(e){e>0&&Mt().releaseShader(e)},create(e){const t=Pt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??xt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ct.set(t,s),t},get:e=>Ct.get(e),setUniform(e,t,s){const n=Ct.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ct.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ct.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ct.get(e);return t?.blendMode??xt.Normal},setDepthTest(e,t){const s=Ct.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ct.get(e);return t?.shader??0},release(e){Ct.delete(e)},isValid:e=>Ct.has(e),releaseAll(){Ct.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??xt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ct.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Pt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ct.set(s,n),s},toAssetData(e,t){const s=Ct.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ct.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Rt=!1,It=0;const Ft=4096,$t=new Map;let kt=null;function Bt(e){const t=(0===It&&bt&&(It=bt._malloc(Ft)),It);if(0===t||!bt)return{ptr:0,count:0};let s=0,n=0;const r=bt.HEAPU8,i=bt.HEAPU32,o=bt.HEAPF32;for(const[a,c]of e){if(s+128>Ft)break;let e=$t.get(a);e||(kt||(kt=new TextEncoder),e=kt.encode(a),$t.set(a,e));const l=e.length,h=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=h;let u=0,d=[0,0,0,0];if("number"==typeof c)u=0,d[0]=c;else if(Array.isArray(c)){u=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(u=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(u=2,d=[c.x,c.y,c.z,0]):"y"in c&&(u=1,d=[c.x,c.y,0,0]);i[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function Ut(){if(!bt||Rt)return;bt.materialDataProvider=(e,t,s,n,r)=>{const i=Ct.get(e);if(!i)return bt.HEAPU32[t>>2]=0,bt.HEAPU32[s>>2]=0,bt.HEAPU32[n>>2]=0,void(bt.HEAPU32[r>>2]=0);bt.HEAPU32[t>>2]=i.shader,bt.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=Bt(i.uniforms);bt.HEAPU32[n>>2]=o,bt.HEAPU32[r>>2]=a},Rt=!0}const Dt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class zt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&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();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Wt{constructor(e,t=""){this.cache_=new zt,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&&(At.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())At.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:At.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const Ot=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"}]}]]);function Lt(e,t){Ot.set(e,t)}function Ht(e){const t=Ot.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function jt(e){return Ot.get(e)?.fields??[]}function Nt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Ie,{value:n.name}),!1!==n.visible)for(const s of n.components)Vt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function Xt(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);h.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=h.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ie,{value:s.name}),!1!==s.visible)for(const n of s.components)Vt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function Vt(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=me(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function qt(e,t){const s=e.getEntitiesWithComponents([Pe]);for(const n of s){const s=e.get(n,Pe);s&&(s.aspectRatio=t,e.insert(n,Pe,s))}}function Gt(e,t){const s=e.getEntitiesWithComponents([Ie]);for(const n of s){const s=e.get(n,Ie);if(s&&s.value===t)return n}return null}class Yt{constructor(e){this.textureCache_=new zt,this.shaderCache_=new zt,this.jsonCache_=new zt,this.textCache_=new zt,this.binaryCache_=new zt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new zt,this.prefabCache_=new zt,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.module_=e,this.canvas_=u(G.textCanvasSize,G.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 Wt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);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 s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}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(),At.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 s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),h="binary"===x(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,i,h);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Xt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}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},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"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 s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{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 s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return At.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return At.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Jt=Oe(null,"Assets");class Kt{build(e){const t=e.wasmModule;t?e.insertResource(Jt,new Yt(t)):console.warn("AssetPlugin: No WASM module available")}}const Qt=new Kt;class Zt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.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,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});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 es(e,t){const s=e.getResource(Jt);s&&s.registerEmbeddedAssets(t)}async function ts(e,t,s){const{entities:n,rootId:r}=await ns(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await Xt(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const ss=10;async function ns(e,t,s,n,r,i=0){if(i>ss)throw new Error(`Prefab nesting depth exceeded ${ss}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await ns(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),h=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:h?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};rs(u,t),c.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function rs(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class is{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return ts(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const os=Oe(null,"Prefabs");class as{constructor(){this.name="PrefabsPlugin",this.dependencies=[Jt]}build(e){const t=e.getResource(Jt);e.insertResource(os,new is(e.world,t))}}const cs=new as;let ls=null,hs=0,us=0,ds=0;const fs=new Float32Array(256);function ps(e){ls=e,hs=ls._malloc(64),us=ls._malloc(64),ds=ls._malloc(1024)}function _s(){ls&&(hs&&(ls._free(hs),hs=0),us&&(ls._free(us),us=0),ds&&(ls._free(ds),ds=0)),ls=null}function ms(){if(!ls)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ls}const gs={r:1,g:1,b:1,a:1},ys={begin(e){const t=ms();try{t.HEAPF32.set(e,hs/4),t.draw_begin(hs)}catch(e){mt(e,"Draw.begin")}},end(){try{ms().draw_end()}catch(e){mt(e,"Draw.end")}},line(e,t,s,n=1){try{ms().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){mt(e,"Draw.line")}},rect(e,t,s,n=!0){try{ms().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){mt(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ms().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){mt(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{ms().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){mt(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{ms().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){mt(e,"Draw.circleOutline")}},texture(e,t,s,n=gs){try{ms().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){mt(e,"Draw.texture")}},textureRotated(e,t,s,n,r=gs){try{ms().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){mt(e,"Draw.textureRotated")}},setLayer(e){ms().draw_setLayer(e)},setDepth(e){ms().draw_setDepth(e)},getDrawCallCount:()=>ls?ls.draw_getDrawCallCount():0,getPrimitiveCount:()=>ls?ls.draw_getPrimitiveCount():0,setBlendMode(e){ms().draw_setBlendMode(e)},setDepthTest(e){ms().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ms();n.HEAPF32.set(s,us/4),n.draw_mesh(e,t,us)}catch(s){mt(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ms(),r=At.get(t);if(!r)return;if(ys.setBlendMode(r.blendMode),ys.setDepthTest(r.depthTest),0===r.uniforms.size)return void ys.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,us/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=vs(t);if(!(n<0)){if(vt(s))fs[i++]=10,fs[i++]=n,fs[i++]=s.slot??e++,fs[i++]=s.textureId;else if("number"==typeof s)fs[i++]=1,fs[i++]=n,fs[i++]=s;else if(Array.isArray(s)){fs[i++]=s.length,fs[i++]=n;for(let e=0;e<s.length;e++)fs[i++]=s[e]}else"w"in s?(fs[i++]=4,fs[i++]=n,fs[i++]=s.x,fs[i++]=s.y,fs[i++]=s.z,fs[i++]=s.w):"z"in s?(fs[i++]=3,fs[i++]=n,fs[i++]=s.x,fs[i++]=s.y,fs[i++]=s.z):(fs[i++]=2,fs[i++]=n,fs[i++]=s.x,fs[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(fs.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void n.draw_mesh(e,r.shader,us);n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),ds/4),n.draw_meshWithUniforms(e,r.shader,us,ds,i)}catch(s){mt(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ws={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},xs=new Set;function vs(e){const t=ws[e];return void 0!==t?t:(xs.has(e)||(xs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ws).join(", ")}`)),-1)}const bs=new Map;function Ss(e,t,s){bs.set(e,{fn:t,scene:s??""})}function Ps(e){bs.delete(e)}function Cs(){bs.clear()}var Ts;!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"}(Ts||(Ts={}));let Es=null,Ms=0,As=0,Rs=0;function Is(e){Es=e,Ms=Es._malloc(262144),As=Es._malloc(65536),Rs=Es._malloc(256)}function Fs(){Es&&(Ms&&Es._free(Ms),As&&Es._free(As),Rs&&Es._free(Rs),Ms=0,As=0,Rs=0),Es=null}function $s(){if(!Es)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Es}const ks={create(e){const t=$s(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ms/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Rs,r).set(i),t.geometry_init(s,Ms,n,Rs,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,As,n).set(e.indices),t.geometry_setIndices16(s,As,n)}else{new Uint32Array(t.HEAPU8.buffer,As,n).set(e.indices),t.geometry_setIndices32(s,As,n)}}return s},updateVertices(e,t,s=0){const n=$s(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Ms/4),n.geometry_updateVertices(e,Ms,r,s)},release(e){e>0&&$s().geometry_release(e)},isValid:e=>!(!Es||e<=0)&&Es.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return ks.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:Ts.Float2},{name:"a_texCoord",type:Ts.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return ks.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:Ts.Float2},{name:"a_texCoord",type:Ts.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return ks.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Ts.Float2},{name:"a_texCoord",type:Ts.Float2}],indices:new Uint16Array(o)})}};let Bs=null;function Us(e){Bs=e}function Ds(){Bs&&Ws.isInitialized()&&Ws.shutdown(),Bs=null}function zs(){if(!Bs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Bs}const Ws={init(e,t){try{return zs().postprocess_init(e,t)}catch(s){return mt(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{zs().postprocess_shutdown()}catch(e){mt(e,"PostProcess.shutdown")}},resize(e,t){try{zs().postprocess_resize(e,t)}catch(s){mt(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return zs().postprocess_addPass(e,t)}catch(t){return mt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{zs().postprocess_removePass(e)}catch(t){mt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{zs().postprocess_setPassEnabled(e,t)}catch(t){mt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return zs().postprocess_isPassEnabled(e)}catch(t){return mt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{zs().postprocess_setUniformFloat(e,t,s)}catch(s){mt(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{zs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){mt(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{zs().postprocess_begin()}catch(e){mt(e,"PostProcess.begin")}},end(){try{zs().postprocess_end()}catch(e){mt(e,"PostProcess.end")}},getPassCount(){try{return zs().postprocess_getPassCount()}catch(e){return mt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Bs)return!1;try{return Bs.postprocess_isInitialized()}catch(e){return mt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{zs().postprocess_setBypass(e)}catch(e){mt(e,"PostProcess.setBypass")}},isBypassed(){if(!Bs)return!0;try{return Bs.postprocess_isBypassed()}catch(e){return mt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>At.createShader(Os,"#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:()=>At.createShader(Os,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>At.createShader(Os,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>At.createShader(Os,"#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")},Os="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Ls;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ls||(Ls={}));let Hs=null,js=0;function Ns(e){Hs=e,js=Hs._malloc(64)}function Xs(){Hs&&js&&(Hs._free(js),js=0),Hs=null}const Vs={init(e,t){Hs?.renderer_init(e,t)},resize(e,t){Hs?.renderer_resize(e,t)},begin(e,t){if(Hs&&js)try{Hs.HEAPF32.set(e,js/4),Hs.renderer_begin(js,t??0)}catch(e){mt(e,"Renderer.begin")}},flush(){try{Hs?.renderer_flush()}catch(e){mt(e,"Renderer.flush")}},end(){try{Hs?.renderer_end()}catch(e){mt(e,"Renderer.end")}},submitSprites(e){if(Hs)try{Hs.renderer_submitSprites(e._cpp)}catch(e){mt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Hs)try{Hs.renderer_submitBitmapText(e._cpp)}catch(e){mt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Hs)try{Hs.renderer_submitSpine?.(e._cpp)}catch(e){mt(e,"Renderer.submitSpine")}},setStage(e){Hs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Hs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Hs?.renderer_releaseTarget(e)},getTargetTexture:e=>Hs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Hs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Hs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Hs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Hs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Hs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Hs?Hs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Hs?{drawCalls:Hs.renderer_getDrawCalls(),triangles:Hs.renderer_getTriangles(),sprites:Hs.renderer_getSprites(),text:Hs.renderer_getText(),spine:Hs.renderer_getSpine?.()??0,meshes:Hs.renderer_getMeshes(),culled:Hs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let qs=null;function Gs(e){qs=e}function Ys(){qs=null}const Js={enable(){qs?.gl_enableErrorCheck(!0)},disable(){qs?.gl_enableErrorCheck(!1)},check:e=>qs?.gl_checkErrors(e)??0,diagnose(){qs?.renderer_diagnose()}};class Ks{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Vs.resize(n,r),Ws.isInitialized()&&Ws.getPassCount()>0&&Ws.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Vs.setViewport(0,0,n,r),Vs.clearBuffers(3),Vs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(s,i),Vs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Vs.setViewport(n.x,n.y,n.w,n.h),Vs.setScissor(n.x,n.y,n.w,n.h,!0),Vs.clearBuffers(r),Vs.setScissor(0,0,0,0,!1),Vs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(s,i),Vs.end()}executeDrawCallbacks(e,t){const s=bs;if(s.size>0){ys.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}ys.end();for(const e of n)Ps(e)}}}const Qs="__scene_transition_overlay__";class Zs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class en{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,Fe,{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),Ss(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Ws.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Ws.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Fe)){const s=this.app_.world.get(e,Fe);s.persistent=t,this.app_.world.insert(e,Fe,s)}}}class tn{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.loadPromises_=new Map,this.app_=e}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_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??G.sceneTransitionDuration,r=t.color??{...G.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Ss(Qs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;ys.setLayer(9999),ys.setDepth(9999),ys.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}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_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,Ps(Qs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ps(Qs),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 s=new Zs(t);this.scenes_.set(e,s);const n=new en(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Jt)&&(t.assetServer=this.app_.getResource(Jt));const n=await Xt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=nn(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 s=new Zs(t);this.scenes_.set(e,s);const n=new en(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Jt)&&(t.assetServer=this.app_.getResource(Jt));const n=await Xt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=nn(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,Fe)){if(this.app_.world.get(e,Fe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Ps(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Ws.removePass(e)}catch{}s.postProcessPasses.length=0,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)}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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Se,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Se,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Ws.setEnabled(s,t)}catch{}}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,s]of this.scenes_)"running"===s.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 sn=Oe(null,"SceneManager");function nn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(sn).getSceneStatus(t)&&s._fn(...n)}}}const rn=tt([He(sn),Le(Xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),on={name:"SceneManager",build(e){const t=new tn(e);e.insertResource(sn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(sn),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Ze.Startup,s),e.addSystemToSchedule(Ze.Last,rn)}};class an{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_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Ze.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ze.FixedPreUpdate),this.runSchedule(Ze.FixedUpdate),this.runSchedule(Ze.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Ze.PreUpdate),this.runSchedule(Ze.Update),this.runSchedule(Ze.PostUpdate),this.runSchedule(Ze.Last),requestAnimationFrame(this.mainLoop)},this.world_=new yt,this.resources_=new Ne;for(const e of Object.values(Ze))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new an}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Ze.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ze.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(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}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}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(sn).register(e),this}setInitialScene(e){return this.getResource(sn).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new ot(this.world_,this.resources_),this.resources_.insert(Xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ze.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Cs();const e=[Ys,Xs,Ds,Fs,Et,_s];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){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Xe);t.delta=e,t.elapsed+=e,t.frameCount++}}function cn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const ln=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function hn(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case xe.FixedWidth:return i;case xe.FixedHeight:return o;case xe.Expand:return Math.max(i,o);case xe.Shrink:return Math.min(i,o);case xe.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function un(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,Fe);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let h,u=0,d=0;if(r.projectionType===ye.Orthographic){if(d=r.orthoSize,c){d=hn(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}u=d*a,h=fn(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=_n(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=gn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(wn(h,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const dn=new Float32Array(16);function fn(e,t,s,n,r,i){const o=dn;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const pn=new Float32Array(16);function _n(e,t,s,n){const r=pn;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const mn=new Float32Array(16);function gn(e,t,s){const n=mn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const yn=new Float32Array(16);function wn(e,t){const s=yn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var xn,vn,bn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(xn||(xn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(vn||(vn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(bn||(bn={}));const Sn=ce("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:xn.Left,verticalAlign:vn.Top,wordWrap:!0,overflow:bn.Visible,lineHeight:1.2}),Pn=ce("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Cn{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(G.textCanvasSize,G.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):u+2*h,p=r?Math.ceil(o):d+2*h;if(r&&e.overflow===bn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,r&&e.overflow===bn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case vn.Top:x=h;break;case vn.Middle:x=(p-w)/2;break;case vn.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of c){let n;switch(e.align){case xn.Left:n=h;break;case xn.Center:n=f/2;break;case xn.Right:n=f-h;break;default:n=h}s.fillText(t,n,v),v+=l}r&&e.overflow===bn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case xn.Left:return"left";case xn.Center:return"center";case xn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Tn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function En(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Mn{build(e){_e("Text",Sn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Cn(t),n=e.world,r=new Map;e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Sn));for(const e of r.keys())n.valid(e)&&n.has(e,Sn)||r.delete(e);const e=n.getEntitiesWithComponents([Sn]);for(const t of e){const e=n.get(t,Sn),i=n.has(t,Pn)?n.get(t,Pn):null,o=r.get(t);if(o&&!En(o,e,i))continue;n.has(t,Se)||n.insert(t,Se,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),c=n.get(t,Se);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Se,c),r.set(t,Tn(e,i))}}))}}const An=new Mn,Rn=ce("UIMask",{enabled:!0});function In(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function Fn(e,t,s,n,r,i,o,a,c,l,h){const u=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*h]}const[m,g]=_(u,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function $n(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*h-o*a,b=r*l-i*c,S=r*h-o*c,P=i*h-o*l,C=u*m-d*_,T=u*g-f*_,E=u*y-p*_,M=d*g-f*m,A=d*y-p*m,R=f*y-p*g;let I=w*R-x*A+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*R-l*A+h*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-h*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(u*P-f*v+p*x)*I,s[8]=(a*A-c*E+h*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-u*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(u*b-d*x+f*w)*I),s}function kn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],h=s[1]*a+s[5]*c+s[13],u=s[3]*a+s[7]*c+s[15];return{x:l/u,y:h/u}}function Bn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function Un(e,t,s,n,r,i,o){if(!e.has(t,Pn)||!e.has(t,be))return null;const a=e.get(t,Pn),c=e.get(t,be),l=a.size.x*c.scale.x,h=a.size.y*c.scale.y;return Fn(c.position.x,c.position.y,l,h,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Dn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Rn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,Rn).enabled&&l.add(e)}const h=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,Ee);){const e=t.get(n,Ee);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&h.push(e)}function u(n,h){const d=e.getChildEntities(s,n);for(const s of d){let n=h;if(l.has(s)){const e=Un(t,s,r,i,o,a,c);e&&(n=In(h,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of h){const s=Un(t,e,r,i,o,a,c);s&&u(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class zn{build(e){if(_e("UIMask",Rn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Dn(e.wasmModule,e.world))}}const Wn=new zn,On=ce("Interactable",{enabled:!0}),Ln=ce("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Hn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Hn||(Hn={}));const jn=ce("Button",{state:Hn.Normal,transition:null});class Nn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Xn=Oe(new Nn,"UIEvents"),Vn=le("ScreenSpace");function qn(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,h=i.bottom+e.y*a,u=i.bottom+t.y*a;let d,f,p,_;if(c===l&&h===u){const e=c+s.x,t=h+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=h+s.y,p=l+n.x,_=u+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Gn(e,t,s,n,r,i){if(!e.has(t,Pn))return;const o=e.get(t,Pn),a=qn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,ve);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,ve,c),!e.has(t,Me))return;const l=e.get(t,Me);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&Gn(e,t,a.rect,a.centerX,a.centerY,!1)}class Yn{build(e){_e("UIRect",Pn);const t=e.world;e.addSystemToSchedule(Ze.PreUpdate,tt([Le(wt)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Vn,Pn,ve]);for(const e of i)Gn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Jn=new Yn,Kn=new Float32Array(16),Qn=new Float32Array(16);let Zn=!0,er=1;class tr{build(e){_e("Interactable",On),_e("Button",jn);const t=e.world,s=new Nn;e.insertResource(Xn,s);let n=null,r=null;er="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ze.PreUpdate,tt([Le(ct),Le(wt)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([Ln]);for(const e of o){const s=t.get(e,Ln);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*er,c=i.screenH-e.mouseY*er;!function(e){let t=!1;for(let s=0;s<16;s++)if(Qn[s]!==e[s]){t=!0;break}t&&(Qn.set(e),Zn=!0)}(i.viewProjection),Zn&&($n(i.viewProjection,Kn),Zn=!1);const l=kn(a,c,Kn,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([On,Pn,be]);let u=null,d=-1/0;for(const e of h){t.has(e,Ln)||t.insert(e,Ln);if(!t.get(e,On).enabled)continue;const s=t.get(e,be),n=t.get(e,Pn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(Bn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Se)&&(s=t.get(e,Se).layer),s>=d&&(d=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,Ln)){t.get(n,Ln).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,Ln).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,Ln);e.pressed=!0,e.justPressed=!0,r=u,s.emit(u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ln)){const e=t.get(r,Ln);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ze.Update,tt([],()=>{const e=t.getEntitiesWithComponents([jn]);for(const s of e){if(t.has(s,On)||t.insert(s,On,{enabled:!0}),!t.has(s,Ln))continue;const e=t.get(s,Ln),n=t.get(s,jn),r=t.get(s,On),i=n.state;if(r.enabled?e.pressed?n.state=Hn.Pressed:e.hovered?n.state=Hn.Hovered:n.state=Hn.Normal:n.state=Hn.Disabled,i!==n.state&&n.transition&&t.has(s,Se)){const e=t.get(s,Se),r=n.transition;switch(n.state){case Hn.Normal:e.color={...r.normalColor};break;case Hn.Hovered:e.color={...r.hoveredColor};break;case Hn.Pressed:e.color={...r.pressedColor};break;case Hn.Disabled:e.color={...r.disabledColor}}t.insert(s,Se,e)}}},{name:"ButtonSystem"}))}}const sr=new tr,nr=ce("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});class rr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){_e("TextInput",nr);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=u(G.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,h=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||w()},_=()=>{a=!0},m=()=>{a=!1,w()},g=t=>{if(null===o)return;if("Escape"===t.key)return void v();const n=s.get(o,nr);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Xn).emit(o,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==o&&s.valid(o)&&s.has(o,nr)){const e=s.get(o,nr);e.focused=!1,e.dirty=!0}o=null};function w(){if(null===o||!s.valid(o))return;const t=s.get(o,nr);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(Xn).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,b()}function x(e){if(o===e)return;v();const t=s.get(e,nr);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),b())}function v(){if(null!==o&&s.valid(o)&&s.has(o,nr)){const e=s.get(o,nr);e.focused=!1,e.dirty=!0}o=null,f.blur()}function b(){c=!0,l=0}function S(e,o,a,l){(r.width<a||r.height<l)&&(r.width=or(Math.max(r.width,a)),r.height=or(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const h=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const u=0===o.value.length,d=u?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=u?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=ir(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=ir(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,l),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Se);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Se,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",y),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",y),f.remove()},e.addSystemToSchedule(Ze.PreUpdate,tt([Le(Xn)],e=>{const t=s.getEntitiesWithComponents([nr,On]);for(const e of t){if(!s.has(e,Ln))continue;if(s.get(e,Ln).justPressed)return void x(e)}if(null!==o){const e=s.getEntitiesWithComponents([On]);for(const t of e){if(s.has(t,nr))continue;if(!s.has(t,Ln))continue;if(s.get(t,Ln).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,nr)))){s.get(o,nr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,nr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([nr,Pn]);for(const e of a){const t=s.get(e,nr);if(!t.dirty)continue;const n=s.get(e,Pn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Se)||s.insert(e,Se,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function ir(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function or(e){let t=1;for(;t<e;)t*=2;return t}const ar=new rr;async function cr(e,t,s){const n=e.getResource(sn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function lr(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 hr=Oe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ur=Oe(null,"PhysicsAPI");function dr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function fr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class pr{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(hr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=lr(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Ce]);for(const s of t){const t=e.world.get(s,Ce);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Ze.PostUpdate,tt([Le(Xe)],a=>{const c=o.getEntitiesWithComponents([ke,ve,be]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,ke),c=o.get(r,be);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=dr(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),_r(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ze.Kinematic){const e=dr(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const h=e.world.get(o,ve);if(!h)continue;let u=a,d=c,f=l;if(e.world.has(o,Ee)){const t=e.world.get(o,Ee);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,be)){const s=e.world.get(t.entity,be),n=dr(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),h=Math.sin(-n);u=(r*o-i*h)/(0!==s.scale.x?s.scale.x:1),d=(r*h+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}h.position.x=u,h.position.y=d;const p=fr(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(o,ve,h)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<h;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(hr,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(ur,mr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function _r(e,t,s){const n=e.world;if(n.has(s,Be)){const e=n.get(s,Be);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Ue)){const e=n.get(s,Ue);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,De)){const e=n.get(s,De);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class mr{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(mr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function gr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function yr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function wr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,h=e.rotation.w,u=a+a,d=c+c,f=l+l,p=a*u,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function xr(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=gr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),h="binary"===x(c)?.contentType;let u,d;if(h){const e=await r.readBinary(o);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,u=t._malloc(d+1),t.HEAPU8.set(s,u),t.HEAPU8[u+d]=0}const f=s.loadSkeleton(u,d,n,n.length,h);if(t._free(u),f<0)continue;i[o]=f;const p=yr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=gr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,u,s,n)),i){new pr("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=x(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),h=gr(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,h,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=At.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=At.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=jt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=Nt(e.world,s);if(c&&e.hasResource(sn))for(const t of p.values())e.world.insert(t,Fe,{scene:c,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,h,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,Re)?l.get(i,Re):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&n.update(o,c*u);let d=0;if(l.has(i,be)){const e=wr(l.get(i,be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),h=s._malloc(c),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,h,u,f);const p=s.HEAPU32[u>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,l,8*r),g=new Uint16Array(s.HEAPU8.buffer,h,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(h),s._free(u),s._free(f)}d&&t._free(d)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Jt);t&&t.setAddressableManifest(a)}}function vr(e,t,s){return{name:e,data:t,async setup(){await xr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class br{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===x(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,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),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Sr="__preview__";class Pr{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(sn);t.register({name:Sr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Sr),this.loadPromise_=t.load(Sr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new br(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await xr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,Sr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Pe]);for(const n of s){if(e.get(n,Pe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([Ce]);for(const r of n){const n=e.get(r,Ce);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(sn).getScene(Sr),i=r?r.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,ve,o);const a={isActive:!0,projectionType:ye.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:we.ColorAndDepth};e.insert(i,Pe,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(sn);await e.switchTo(Sr),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 Cr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Vs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Vs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Vs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Vs.releaseRenderTarget(e._handle),Cr.create({width:t,height:s,depth:!0})),begin(e,t){Vs.begin(t,e._handle)},end(){Vs.end()},getDepthTexture:e=>Vs.getTargetDepthTexture(e._handle)};let Tr=!1;function Er(e){Tr=e}function Mr(){return Tr}function Ar(){return!Tr}var Rr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Rr||(Rr={}));class Ir{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Rr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Rr.Debug:console.debug(t,s);break;case Rr.Info:console.log(t,s);break;case Rr.Warn:console.warn(t,s);break;case Rr.Error:console.error(t,s)}}}class Fr{constructor(){this.handlers_=[],this.minLevel_=Rr.Info,this.addHandler(new Ir)}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,s){this.log(Rr.Debug,e,t,s)}info(e,t,s){this.log(Rr.Info,e,t,s)}warn(e,t,s){this.log(Rr.Warn,e,t,s)}error(e,t,s){this.log(Rr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const $r=new Fr;function kr(){return $r}function Br(e){$r.setMinLevel(e)}function Ur(e,t,s){$r.debug(e,t,s)}function Dr(e,t,s){$r.info(e,t,s)}function zr(e,t,s){$r.warn(e,t,s)}function Wr(e,t,s){$r.error(e,t,s)}const Or=[An,Wn,Jn,sr,ar];function Lr(e,t){return function(e,t){const s=an.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ps(e),Tt(e),Is(e),Us(e),Ns(e),Gs(e);const r=new Ks;s.setPipeline(r);let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=un(e,n,t,r));const o=s.getResource(wt);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(wt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Vs.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-i)/1e3;let u;if(Vs.resize(t,c),Ws.isInitialized()&&Ws.getPassCount()>0&&!Ws.isBypassed()&&Ws.resize(t,c),s.hasResource(sn)){const e=s.getResource(sn).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=un(e,n,t,c,s.world,u);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:ln,width:t,height:c,elapsed:h});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:h})}Vs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Ze.First,c),s.addSystemToSchedule(Ze.Last,l),s.addPlugin(Qt),s.addPlugin(cs),s.addPlugin(ht),s.addPlugin(on),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Or,...t})}H||(H=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{an as App,Kt as AssetPlugin,Zt as AssetRefCounter,Yt as AssetServer,Jt as Assets,zt as AsyncCache,Ae as BitmapText,xt as BlendMode,ze as BodyType,Be as BoxCollider,jn as Button,Hn as ButtonState,Pe as Camera,Ce as Canvas,De as CapsuleCollider,Me as Children,Ue as CircleCollider,we as ClearFlags,Je as Commands,Qe as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,Ts as DataType,ys as Draw,Ke as EntityCommands,Js as GLDebug,ks as Geometry,J as INVALID_ENTITY,Q as INVALID_FONT,K as INVALID_TEXTURE,ct as Input,lt as InputPlugin,at as InputState,On as Interactable,ve as LocalTransform,Rr as LogLevel,Fr as Logger,At as Material,Wt as MaterialLoader,Ve as Mut,Ie as Name,Ee as Parent,mr as Physics,hr as PhysicsEvents,pr as PhysicsPlugin,Ws as PostProcess,is as PrefabServer,os as Prefabs,as as PrefabsPlugin,Pr as PreviewPlugin,ye as ProjectionType,Ge as Query,Ye as QueryInstance,Ks as RenderPipeline,Ls as RenderStage,Cr as RenderTexture,Vs as Renderer,Le as Res,He as ResMut,ke as RigidBody,G as RuntimeConfig,xe as ScaleMode,sn as SceneManager,tn as SceneManagerState,Fe as SceneOwner,Ze as Schedule,Vn as ScreenSpace,Dt as ShaderSources,Re as SpineAnimation,Se as Sprite,ot as SystemRunner,Sn as Text,xn as TextAlign,nr as TextInput,rr as TextInputPlugin,bn as TextOverflow,Mn as TextPlugin,Cn as TextRenderer,vn as TextVerticalAlign,Xe as Time,wt as UICameraInfo,Nn as UIEventQueue,Xn as UIEvents,Ln as UIInteraction,tr as UIInteractionPlugin,Yn as UILayoutPlugin,Rn as UIMask,zn as UIMaskPlugin,Pn as UIRect,Te as Velocity,br as WebAssetProvider,yt as World,be as WorldTransform,rt as addStartupSystem,nt as addSystem,it as addSystemToSchedule,Y as applyRuntimeConfig,Qt as assetPlugin,Cs as clearDrawCallbacks,ue as clearUserComponents,se as color,qn as computeUIRectLayout,Dn as createMaskProcessor,vr as createRuntimeSceneConfig,Lr as createWebApp,Ur as debug,ce as defineComponent,Oe as defineResource,tt as defineSystem,le as defineTag,Wr as error,Gt as findEntityByName,cn as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,C as getAllAssetExtensions,A as getAssetMimeType,x as getAssetTypeEntry,me as getComponent,Ht as getComponentAssetFields,$e as getComponentDefaults,E as getCustomExtensions,v as getEditorType,kr as getLogger,t as getPlatform,n as getPlatformType,he as getUserComponent,M as getWeChatPackOptions,Dr as info,ps as initDrawAPI,Gs as initGLDebugAPI,Is as initGeometryAPI,Tt as initMaterialAPI,Us as initPostProcessAPI,Ns as initRendererAPI,ht as inputPlugin,ts as instantiatePrefab,In as intersectRects,$n as invertMatrix4,fe as isBuiltinComponent,R as isCustomExtension,Mr as isEditor,P as isKnownAssetExtension,s as isPlatformInitialized,Ar as isRuntime,vt as isTextureRef,r as isWeChat,i as isWeb,Vt as loadComponent,lr as loadPhysicsModule,xr as loadRuntimeScene,Nt as loadSceneData,Xt as loadSceneWithAssets,T as looksLikeAssetPath,o as platformFetch,l as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,Bn as pointInWorldRect,cs as prefabsPlugin,ne as quat,_e as registerComponent,Lt as registerComponentAssetFields,Ss as registerDrawCallback,es as registerEmbeddedAssets,Ut as registerMaterialCallback,on as sceneManagerPlugin,kn as screenToWorld,Er as setEditorMode,Br as setLogLevel,_t as setWasmErrorHandler,_s as shutdownDrawAPI,Ys as shutdownGLDebugAPI,Fs as shutdownGeometryAPI,Et as shutdownMaterialAPI,Ds as shutdownPostProcessAPI,Xs as shutdownRendererAPI,ar as textInputPlugin,An as textPlugin,cr as transitionTo,sr as uiInteractionPlugin,Jn as uiLayoutPlugin,Wn as uiMaskPlugin,Or as uiPlugins,Ps as unregisterDrawCallback,qt as updateCameraAspectRatio,Z as vec2,ee as vec3,te as vec4,zr as warn,Fn as worldRectToScreen,nn as wrapSceneSystem,U as wxFileExists,D as wxFileExistsSync,O as wxGetImagePixels,W as wxLoadImage,L as wxLoadImagePixels,k as wxReadFile,B as wxReadTextFile,z as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 0f307cff2..481a98451 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -1596,6 +1596,7 @@ declare class App {private physicsInitPromise_?;private physicsModule_?;private readonly installed_plugins_;+ private readonly sortedSystemsCache_;private error_handler_;private system_error_handler_;private frame_paused_;@@ -1611,6 +1612,7 @@ declare class App {connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;get wasmModule(): ESEngineModule | null;get pipeline(): RenderPipeline | null;+ setPipeline(pipeline: RenderPipeline): void;setSpineRenderer(fn: SpineRendererFn | null): void;get spineInitPromise(): Promise<unknown> | undefined;set spineInitPromise(p: Promise<unknown> | undefined);@@ -1624,6 +1626,7 @@ declare class App {setMaxFixedSteps(v: number): this;onError(handler: (error: unknown, systemName: string) => void): this;onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;+ onWasmError(handler: (error: unknown, context: string) => void): this;insertResource<T>(resource: ResourceDef<T>, value: T): this;getResource<T>(resource: ResourceDef<T>): T;hasResource<T>(resource: ResourceDef<T>): boolean;@@ -2769,9 +2772,12 @@ declare const GLDebug: {diagnose(): void;};+type WasmErrorHandler = (error: unknown, context: string) => void;+declare function setWasmErrorHandler(handler: WasmErrorHandler | null): void;+declare const uiPlugins: Plugin[];declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;-export { App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_PIXELS_PER_UNIT, DEFAULT_TEXT_CANVAS_SIZE, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, LogLevel, Logger, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProjectionType, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, applyRuntimeConfig, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defineComponent, defineResource, defineSystem, defineTag, error, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFields, getComponentDefaults, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, prefabsPlugin, quat, registerComponent, registerComponentAssetFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, sceneManagerPlugin, screenToWorld, setEditorMode, setLogLevel, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, worldRectToScreen, wrapSceneSystem };+export { App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_PIXELS_PER_UNIT, DEFAULT_TEXT_CANVAS_SIZE, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, LogLevel, Logger, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProjectionType, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, applyRuntimeConfig, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defineComponent, defineResource, defineSystem, defineTag, error, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFields, getComponentDefaults, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, prefabsPlugin, quat, registerComponent, registerComponentAssetFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, sceneManagerPlugin, screenToWorld, setEditorMode, setLogLevel, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, worldRectToScreen, wrapSceneSystem };export type { AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnyComponentDef, AssetBundle, AssetContentType, AssetRefInfo, AssetTypeEntry, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, EditorAssetType, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, LoadedMaterial, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, PrefabData, PrefabEntityData, PrefabOverride, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeSceneOptions, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, TransitionConfig, TransitionOptions, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex bf43a43e5..d9d3c413d 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}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,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),i=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},o=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const s=t;e.onWheel(s.deltaX,s.deltaY)};document.addEventListener("keydown",n),document.addEventListener("keyup",r),s.addEventListener("mousemove",i),s.addEventListener("mousedown",o),s.addEventListener("mouseup",a),s.addEventListener("touchstart",l),s.addEventListener("touchmove",c),s.addEventListener("touchend",u),s.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r),s.removeEventListener("mousemove",i),s.removeEventListener("mousedown",o),s.removeEventListener("mouseup",a),s.removeEventListener("touchstart",l),s.removeEventListener("touchmove",c),s.removeEventListener("touchend",u),s.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,m=100,g=512,y={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function w(e){e.Text&&(e.Text._default.fontFamily=y.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=y.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=y.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=y.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),C=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),T=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),E=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function M(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(M);const t={};for(const s in e)t[s]=M(e[s]);return t}let A=0;function R(e,t){const s=++A;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...M(t),...e}:M(t)}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const s=I(),n=s.get(e);if(n)return n;const r=R(e,t);return s.set(e,r),$(e,t,!1),r}function k(e){const t=I(),s=t.get(e);if(s)return s;const n=R(e,{});return t.set(e,n),$(e,{},!0),n}function B(e){return I().get(e)}function U(){I().clear()}function $(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function D(e){return!0===e._builtin}const z=new Map;function L(e,t){z.set(e,t)}function O(e){return z.get(e)??B(e)}function H(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return z.set(e,s),s}const W={Perspective:0,Orthographic:1},j={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},N={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},V=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),X=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Y=H("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),q=H("Camera",{projectionType:W.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:j.ColorAndDepth}),G=H("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:N.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),J=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),K=H("Parent",{entity:0}),Q=H("Children",{entities:[]}),Z=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),ee=H("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}),te={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=F("SceneOwner",{scene:"",persistent:!1});function ne(e){const t=O(e);return t?M(t._default):null}L("Name",te);const re=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ie=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ae=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),le={Static:0,Kinematic:1,Dynamic:2};let ce=0;function ue(e,t){const s=++ce;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function he(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class pe{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 fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=ue({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ye(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{ge(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class we{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ge(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const h of n){if(null!==u&&i)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(h,t[s])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,s[e]);if(i){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&i)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function xe(){return{_type:"commands"}}class ve{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ve(this,null);return this.spawned_.push(e),e}entity(e){return new ve(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":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)}}}var Se;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Se||(Se={}));let Pe=0;function Ce(e,t,s){const n=++Pe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ee(e){Te().push({schedule:Se.Update,system:e})}function Me(e){Te().push({schedule:Se.Startup,system:e})}function Ae(e,t){Te().push({schedule:e,system:t})}class Re{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof be&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Fe=ue(new Ie,"Input");class ke{constructor(e){this.target_=e??null}build(e){const s=new Ie;e.insertResource(Fe,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Se.Last,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Be=new ke;function Ue(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=$e(t[e]),i=$e(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}function ze(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:ze(e)}}return t}class Le{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),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.");this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return D(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(D(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):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.");D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Ue(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,ze(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(e)}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Ue(t._name,t._default,e);if(r.length>0)throw new Error(De(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!D(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=i?i.keys():this.entities_;for(const t of l){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const Oe=ue({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var He;function We(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"}(He||(He={}));let je=null,Ne=null,Ve=1;const Xe=new Map;function Ye(e){je=e,Ne=e.getResourceManager(),nt()}function qe(){0!==Qe&&je&&(je._free(Qe),Qe=0),Xe.clear(),Ve=1,Ke=!1,et.clear(),tt=null,Ne=null,je=null}function Ge(){if(!Ne)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ne}const Je={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=Ve++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??He.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Xe.set(t,s),t},get:e=>Xe.get(e),setUniform(e,t,s){const n=Xe.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Xe.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Xe.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Xe.get(e);return t?.blendMode??He.Normal},setDepthTest(e,t){const s=Xe.get(e);s&&(s.depthTest=t)},getShader(e){const t=Xe.get(e);return t?.shader??0},release(e){Xe.delete(e)},isValid:e=>Xe.has(e),releaseAll(){Xe.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??He.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Xe.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ve++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Xe.set(s,n),s},toAssetData(e,t){const s=Xe.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Xe.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ke=!1,Qe=0;const Ze=4096,et=new Map;let tt=null;function st(e){const t=(0===Qe&&je&&(Qe=je._malloc(Ze)),Qe);if(0===t||!je)return{ptr:0,count:0};let s=0,n=0;const r=je.HEAPU8,i=je.HEAPU32,o=je.HEAPF32;for(const[a,l]of e){if(s+128>Ze)break;let e=et.get(a);e||(tt||(tt=new TextEncoder),e=tt.encode(a),et.set(a,e));const c=e.length,u=4*Math.ceil(c/4);i[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);i[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function nt(){if(!je||Ke)return;je.materialDataProvider=(e,t,s,n,r)=>{const i=Xe.get(e);if(!i)return je.HEAPU32[t>>2]=0,je.HEAPU32[s>>2]=0,je.HEAPU32[n>>2]=0,void(je.HEAPU32[r>>2]=0);je.HEAPU32[t>>2]=i.shader,je.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=st(i.uniforms);je.HEAPU32[n>>2]=o,je.HEAPU32[r>>2]=a},Ke=!0}const rt={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 it{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&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();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class ot{constructor(e,t=""){this.cache_=new it,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&&(Je.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Je.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 s=await l(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Je.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const at=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"}]}]]);function lt(e,t){at.set(e,t)}function ct(e){const t=at.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function ut(e){return at.get(e)?.fields??[]}function ht(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,te,{value:n.name}),!1!==n.visible)for(const s of n.components)ft(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function dt(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=at.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const c=new Map,u=new Map,h=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);c.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);h.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=at.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=c.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=h.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,te,{value:s.name}),!1!==s.visible)for(const n of s.components)ft(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ft(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function pt(e,t){const s=e.getEntitiesWithComponents([q]);for(const n of s){const s=e.get(n,q);s&&(s.aspectRatio=t,e.insert(n,q,s))}}function _t(e,t){const s=e.getEntitiesWithComponents([te]);for(const n of s){const s=e.get(n,te);if(s&&s.value===t)return n}return null}const mt=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],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}],gt={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",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},yt=new Map,wt=new Set;for(const e of mt)for(const t of e.extensions)yt.set(t,e),wt.add(t);function xt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function vt(e){return yt.get(xt(e))}function bt(e){return vt(e)?.editorType??"unknown"}function St(e){return vt(e)?.addressableType??null}function Pt(e){for(const t of mt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Ct(e){return wt.has(e.toLowerCase())}function Tt(){return wt}function Et(e){return"string"==typeof e&&(!!e.includes("/")&&Ct(xt(e)))}function Mt(){const e=[];for(const t of mt)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function At(){return Mt().map(e=>({type:"suffix",value:e}))}function Rt(e){return gt[e.toLowerCase()]}function It(e){const t=vt(e);return t?.wechatPackInclude??!1}class Ft{constructor(e){this.textureCache_=new it,this.shaderCache_=new it,this.jsonCache_=new it,this.textCache_=new it,this.binaryCache_=new it,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new it,this.prefabCache_=new it,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.module_=e,this.canvas_=h(y.textCanvasSize,y.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 ot(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);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 s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}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(),Je.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 s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),l=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===vt(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(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=vt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return dt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}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},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"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 s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{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 s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const l=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Je.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Je.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await l(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const kt=ue(null,"Assets");class Bt{build(e){const t=e.wasmModule;t?e.insertResource(kt,new Ft(t)):console.warn("AssetPlugin: No WASM module available")}}const Ut=new Bt;class $t{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.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,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});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 Dt(e,t){const s=e.getResource(kt);s&&s.registerEmbeddedAssets(t)}async function zt(e,t,s){const{entities:n,rootId:r}=await Ot(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await dt(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Lt=10;async function Ot(e,t,s,n,r,i=0){if(i>Lt)throw new Error(`Prefab nesting depth exceeded ${Lt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Ot(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?o.get(n.parent)??null:null),l.push(...t.entities);continue}const c=o.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Ht(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Ht(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class Wt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return zt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const jt=ue(null,"Prefabs");class Nt{constructor(){this.name="PrefabsPlugin",this.dependencies=[kt]}build(e){const t=e.getResource(kt);e.insertResource(jt,new Wt(e.world,t))}}const Vt=new Nt;let Xt=null,Yt=0,qt=0,Gt=0;const Jt=new Float32Array(256);function Kt(e){Xt=e,Yt=Xt._malloc(64),qt=Xt._malloc(64),Gt=Xt._malloc(1024)}function Qt(){Xt&&(Yt&&(Xt._free(Yt),Yt=0),qt&&(Xt._free(qt),qt=0),Gt&&(Xt._free(Gt),Gt=0)),Xt=null}function Zt(){if(!Xt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Xt}const es={r:1,g:1,b:1,a:1},ts={begin(e){const t=Zt();t.HEAPF32.set(e,Yt/4),t.draw_begin(Yt)},end(){Zt().draw_end()},line(e,t,s,n=1){Zt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Zt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Zt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Zt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Zt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=es){Zt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=es){Zt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Zt().draw_setLayer(e)},setDepth(e){Zt().draw_setDepth(e)},getDrawCallCount:()=>Xt?Xt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Xt?Xt.draw_getPrimitiveCount():0,setBlendMode(e){Zt().draw_setBlendMode(e)},setDepthTest(e){Zt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Zt();n.HEAPF32.set(s,qt/4),n.draw_mesh(e,t,qt)},drawMeshWithMaterial(e,t,s){const n=Zt(),r=Je.get(t);if(!r)return;if(ts.setBlendMode(r.blendMode),ts.setDepthTest(r.depthTest),0===r.uniforms.size)return void ts.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,qt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=ns(t);if(!(n<0)){if(We(s))Jt[i++]=10,Jt[i++]=n,Jt[i++]=s.slot??e++,Jt[i++]=s.textureId;else if("number"==typeof s)Jt[i++]=1,Jt[i++]=n,Jt[i++]=s;else if(Array.isArray(s)){Jt[i++]=s.length,Jt[i++]=n;for(let e=0;e<s.length;e++)Jt[i++]=s[e]}else"w"in s?(Jt[i++]=4,Jt[i++]=n,Jt[i++]=s.x,Jt[i++]=s.y,Jt[i++]=s.z,Jt[i++]=s.w):"z"in s?(Jt[i++]=3,Jt[i++]=n,Jt[i++]=s.x,Jt[i++]=s.y,Jt[i++]=s.z):(Jt[i++]=2,Jt[i++]=n,Jt[i++]=s.x,Jt[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(Jt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Gt/4),n.draw_meshWithUniforms(e,r.shader,qt,Gt,i)):n.draw_mesh(e,r.shader,qt)}},ss={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function ns(e){return ss[e]??-1}const rs=new Map;function is(e,t,s){rs.set(e,{fn:t,scene:s??""})}function os(e){rs.delete(e)}function as(){rs.clear()}var ls;!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"}(ls||(ls={}));let cs=null,us=0,hs=0,ds=0;function fs(e){cs=e,us=cs._malloc(262144),hs=cs._malloc(65536),ds=cs._malloc(256)}function ps(){cs&&(us&&cs._free(us),hs&&cs._free(hs),ds&&cs._free(ds),us=0,hs=0,ds=0),cs=null}function _s(){if(!cs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return cs}const ms={create(e){const t=_s(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,us/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ds,r).set(i),t.geometry_init(s,us,n,ds,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,hs,n).set(e.indices),t.geometry_setIndices16(s,hs,n)}else{new Uint32Array(t.HEAPU8.buffer,hs,n).set(e.indices),t.geometry_setIndices32(s,hs,n)}}return s},updateVertices(e,t,s=0){const n=_s(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,us/4),n.geometry_updateVertices(e,us,r,s)},release(e){e>0&&_s().geometry_release(e)},isValid:e=>!(!cs||e<=0)&&cs.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return ms.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:ls.Float2},{name:"a_texCoord",type:ls.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(i,o,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return ms.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ls.Float2},{name:"a_texCoord",type:ls.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return ms.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ls.Float2},{name:"a_texCoord",type:ls.Float2}],indices:new Uint16Array(o)})}};let gs=null;function ys(e){gs=e}function ws(){gs&&vs.isInitialized()&&vs.shutdown(),gs=null}function xs(){if(!gs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return gs}const vs={init:(e,t)=>xs().postprocess_init(e,t),shutdown(){xs().postprocess_shutdown()},resize(e,t){xs().postprocess_resize(e,t)},addPass:(e,t)=>xs().postprocess_addPass(e,t),removePass(e){xs().postprocess_removePass(e)},setEnabled(e,t){xs().postprocess_setPassEnabled(e,t)},isEnabled:e=>xs().postprocess_isPassEnabled(e),setUniform(e,t,s){xs().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){xs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){xs().postprocess_begin()},end(){xs().postprocess_end()},getPassCount:()=>xs().postprocess_getPassCount(),isInitialized:()=>!!gs&&gs.postprocess_isInitialized(),setBypass(e){xs().postprocess_setBypass(e)},isBypassed:()=>!gs||gs.postprocess_isBypassed(),createBlur:()=>Je.createShader(bs,"#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:()=>Je.createShader(bs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Je.createShader(bs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Je.createShader(bs,"#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")},bs="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Ss;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ss||(Ss={}));let Ps=null,Cs=0;function Ts(e){Ps=e,Cs=Ps._malloc(64)}function Es(){Ps&&Cs&&(Ps._free(Cs),Cs=0),Ps=null}const Ms={init(e,t){Ps?.renderer_init(e,t)},resize(e,t){Ps?.renderer_resize(e,t)},begin(e,t){Ps&&Cs&&(Ps.HEAPF32.set(e,Cs/4),Ps.renderer_begin(Cs,t??0))},flush(){Ps?.renderer_flush()},end(){Ps?.renderer_end()},submitSprites(e){Ps&&Ps.renderer_submitSprites(e._cpp)},submitBitmapText(e){Ps&&Ps.renderer_submitBitmapText(e._cpp)},submitSpine(e){Ps&&Ps.renderer_submitSpine?.(e._cpp)},setStage(e){Ps?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ps?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ps?.renderer_releaseTarget(e)},getTargetTexture:e=>Ps?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ps?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ps?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ps?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Ps?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Ps?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ps?Ps.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Ps?{drawCalls:Ps.renderer_getDrawCalls(),triangles:Ps.renderer_getTriangles(),sprites:Ps.renderer_getSprites(),text:Ps.renderer_getText(),spine:Ps.renderer_getSpine?.()??0,meshes:Ps.renderer_getMeshes(),culled:Ps.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let As=null;function Rs(e){As=e}function Is(){As=null}const Fs={enable(){As?.gl_enableErrorCheck(!0)},disable(){As?.gl_enableErrorCheck(!1)},check:e=>As?.gl_checkErrors(e)??0,diagnose(){As?.renderer_diagnose()}};class ks{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ms.resize(n,r),vs.isInitialized()&&vs.getPassCount()>0&&vs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ms.setViewport(0,0,n,r),Ms.clearBuffers(3),Ms.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ms.submitSprites(t),Ms.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Ms.submitSpine(t),Ms.flush(),this.executeDrawCallbacks(s,i),Ms.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Ms.setViewport(n.x,n.y,n.w,n.h),Ms.setScissor(n.x,n.y,n.w,n.h,!0),Ms.clearBuffers(r),Ms.setScissor(0,0,0,0,!1),Ms.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ms.submitSprites(t),Ms.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Ms.submitSpine(t),Ms.flush(),this.executeDrawCallbacks(s,i),Ms.end()}executeDrawCallbacks(e,t){const s=rs;if(s.size>0){ts.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}ts.end();for(const e of n)os(e)}}}const Bs="__scene_transition_overlay__";class Us{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class $s{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,se,{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),is(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=vs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){vs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,se)){const s=this.app_.world.get(e,se);s.persistent=t,this.app_.world.insert(e,se,s)}}}class Ds{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.loadPromises_=new Map,this.app_=e}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_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??y.sceneTransitionDuration,r=t.color??{...y.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},is(Bs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;ts.setLayer(9999),ts.setDepth(9999),ts.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}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_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,os(Bs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,os(Bs),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 s=new Us(t);this.scenes_.set(e,s);const n=new $s(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(kt)?this.app_.getResource(kt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(kt)&&(t.assetServer=this.app_.getResource(kt));const n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ls(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 s=new Us(t);this.scenes_.set(e,s);const n=new $s(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(kt)?this.app_.getResource(kt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(kt)&&(t.assetServer=this.app_.getResource(kt));const n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ls(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,se)){if(this.app_.world.get(e,se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())os(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{vs.removePass(e)}catch{}s.postProcessPasses.length=0,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)}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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Y,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Y,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{vs.setEnabled(s,t)}catch{}}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,s]of this.scenes_)"running"===s.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 zs=ue(null,"SceneManager");function Ls(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(zs).getSceneStatus(t)&&s._fn(...n)}}}const Os=Ce([de(zs),he(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Hs={name:"SceneManager",build(e){const t=new Ds(e);e.insertResource(zs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(zs),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Se.Startup,s),e.addSystemToSchedule(Se.Last,Os)}};class Ws{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_=new Set,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Se.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Se.FixedPreUpdate),this.runSchedule(Se.FixedUpdate),this.runSchedule(Se.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Se.PreUpdate),this.runSchedule(Se.Update),this.runSchedule(Se.PostUpdate),this.runSchedule(Se.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Le,this.resources_=new pe;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ws}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this}addSystem(e){return this.addSystemToSchedule(Se.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Se.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(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}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}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(zs).register(e),this}setInitialScene(e){return this.getResource(zs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Re(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,as();const e=[Is,Es,ws,ps,qe,Qt];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){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function js(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const Ns=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Vs(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case N.FixedWidth:return i;case N.FixedHeight:return o;case N.Expand:return Math.max(i,o);case N.Shrink:return Math.min(i,o);case N.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function Xs(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let u,h=0,d=0;if(r.projectionType===W.Orthographic){if(d=r.orthoSize,l){d=Vs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}h=d*a,u=qs(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Js(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=Qs(i.position.x,i.position.y,i.position.z);c.push({entity:e,viewProjection:new Float32Array(en(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Ys=new Float32Array(16);function qs(e,t,s,n,r,i){const o=Ys;o.fill(0);const a=t-e,l=n-s,c=i-r;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(n+s)/l,o[14]=-(i+r)/c,o[15]=1,o}const Gs=new Float32Array(16);function Js(e,t,s,n){const r=Gs;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const Ks=new Float32Array(16);function Qs(e,t,s){const n=Ks;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const Zs=new Float32Array(16);function en(e,t){const s=Zs;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var tn,sn,nn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(tn||(tn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(sn||(sn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(nn||(nn={}));const rn=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:tn.Left,verticalAlign:sn.Top,wordWrap:!0,overflow:nn.Visible,lineHeight:1.2}),on=F("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class an{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(y.textCanvasSize,y.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?i: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=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===nn.Ellipsis&&d>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,r&&e.overflow===nn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case sn.Top:x=u;break;case sn.Middle:x=(p-w)/2;break;case sn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let n;switch(e.align){case tn.Left:n=u;break;case tn.Center:n=f/2;break;case tn.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=c}r&&e.overflow===nn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case tn.Left:return"left";case tn.Center:return"center";case tn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function ln(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function cn(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class un{build(e){L("Text",rn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new an(t),n=e.world,r=new Map;e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,rn));for(const e of r.keys())n.valid(e)&&n.has(e,rn)||r.delete(e);const e=n.getEntitiesWithComponents([rn]);for(const t of e){const e=n.get(t,rn),i=n.has(t,on)?n.get(t,on):null,o=r.get(t);if(o&&!cn(o,e,i))continue;n.has(t,Y)||n.insert(t,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),l=n.get(t,Y);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Y,l),r.set(t,ln(e,i))}}))}}const hn=new un,dn=F("UIMask",{enabled:!0});function fn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function pn(e,t,s,n,r,i,o,a,l,c,u){const h=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*u]}const[m,g]=_(h,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function _n(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=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],_=e[12],m=e[13],g=e[14],y=e[15],w=n*l-r*a,x=n*c-i*a,v=n*u-o*a,b=r*c-i*l,S=r*u-o*l,P=i*u-o*c,C=h*m-d*_,T=h*g-f*_,E=h*y-p*_,M=d*g-f*m,A=d*y-p*m,R=f*y-p*g;let I=w*R-x*A+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(c*E-a*R-u*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(h*P-f*v+p*x)*I,s[8]=(a*A-l*E+u*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(l*T-a*M-c*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function mn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,l=(t-r)/o*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],h=s[3]*a+s[7]*l+s[15];return{x:c/h,y:u/h}}function gn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function yn(e,t,s,n,r,i,o){if(!e.has(t,on)||!e.has(t,X))return null;const a=e.get(t,on),l=e.get(t,X),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return pn(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function wn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([dn]);if(0!==l.length)try{!function(e,t,s,n,r,i,o,a,l){const c=new Set;for(const e of n){t.get(e,dn).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,K);){const e=t.get(n,K);if(c.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(c.has(s)){const e=yn(t,s,r,i,o,a,l);e&&(n=fn(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=yn(t,e,r,i,o,a,l);s&&h(e,s)}}(e,t,s,l,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class xn{build(e){if(L("UIMask",dn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(wn(e.wasmModule,e.world))}}const vn=new xn,bn=F("Interactable",{enabled:!0}),Sn=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Pn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Pn||(Pn={}));const Cn=F("Button",{state:Pn.Normal,transition:null});class Tn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const En=ue(new Tn,"UIEvents"),Mn=k("ScreenSpace");function An(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,l=i.left+e.x*o,c=i.left+t.x*o,u=i.bottom+e.y*a,h=i.bottom+t.y*a;let d,f,p,_;if(l===c&&u===h){const e=l+s.x,t=u+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=l+s.x,f=u+s.y,p=c+n.x,_=h+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Rn(e,t,s,n,r,i){if(!e.has(t,on))return;const o=e.get(t,on),a=An(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const l=e.get(t,V);if(i?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,V,l),!e.has(t,Q))return;const c=e.get(t,Q);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Rn(e,t,a.rect,a.centerX,a.centerY,!1)}class In{build(e){L("UIRect",on);const t=e.world;e.addSystemToSchedule(Se.PreUpdate,Ce([he(Oe)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Mn,on,V]);for(const e of i)Rn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Fn=new In,kn=new Float32Array(16),Bn=new Float32Array(16);let Un=!0,$n=1;class Dn{build(e){L("Interactable",bn),L("Button",Cn);const t=e.world,s=new Tn;e.insertResource(En,s);let n=null,r=null;$n="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Se.PreUpdate,Ce([he(Fe),he(Oe)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([Sn]);for(const e of o){const s=t.get(e,Sn);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*$n,l=i.screenH-e.mouseY*$n;!function(e){let t=!1;for(let s=0;s<16;s++)if(Bn[s]!==e[s]){t=!0;break}t&&(Bn.set(e),Un=!0)}(i.viewProjection),Un&&(_n(i.viewProjection,kn),Un=!1);const c=mn(a,l,kn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([bn,on,X]);let h=null,d=-1/0;for(const e of u){t.has(e,Sn)||t.insert(e,Sn);if(!t.get(e,bn).enabled)continue;const s=t.get(e,X),n=t.get(e,on),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(gn(c.x,c.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Y)&&(s=t.get(e,Y).layer),s>=d&&(d=s,h=e)}}if(n!==h){if(null!==n&&t.valid(n)&&t.has(n,Sn)){t.get(n,Sn).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,Sn).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Sn);e.pressed=!0,e.justPressed=!0,r=h,s.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Sn)){const e=t.get(r,Sn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Se.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([Cn]);for(const s of e){if(t.has(s,bn)||t.insert(s,bn,{enabled:!0}),!t.has(s,Sn))continue;const e=t.get(s,Sn),n=t.get(s,Cn),r=t.get(s,bn),i=n.state;if(r.enabled?e.pressed?n.state=Pn.Pressed:e.hovered?n.state=Pn.Hovered:n.state=Pn.Normal:n.state=Pn.Disabled,i!==n.state&&n.transition&&t.has(s,Y)){const e=t.get(s,Y),r=n.transition;switch(n.state){case Pn.Normal:e.color={...r.normalColor};break;case Pn.Hovered:e.color={...r.hoveredColor};break;case Pn.Pressed:e.color={...r.pressedColor};break;case Pn.Disabled:e.color={...r.disabledColor}}t.insert(s,Y,e)}}},{name:"ButtonSystem"}))}}const zn=new Dn,Ln=F("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});class On{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){L("TextInput",Ln);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=h(y.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,l=!0,c=0,u=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||x()},_=()=>{a=!0},m=()=>{a=!1,x()},g=t=>{if(null===o)return;if("Escape"===t.key)return void S();const n=s.get(o,Ln);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(En).emit(o,"submit"),void S()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,P())},w=()=>{if(null!==o&&s.valid(o)&&s.has(o,Ln)){const e=s.get(o,Ln);e.focused=!1,e.dirty=!0}o=null};function x(){if(null===o||!s.valid(o))return;const t=s.get(o,Ln);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(En).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,P()}function b(e){if(o===e)return;S();const t=s.get(e,Ln);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==o&&s.valid(o)&&s.has(o,Ln)){const e=s.get(o,Ln);e.focused=!1,e.dirty=!0}o=null,f.blur()}function P(){l=!0,c=0}function C(e,o,a,c){(r.width<a||r.height<c)&&(r.width=Wn(Math.max(r.width,a)),r.height=Wn(Math.max(r.height,c))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,i.fillRect(0,0,a,c),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,c),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const h=0===o.value.length,d=h?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=h?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=Hn(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(c-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&l){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=Hn(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(c-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,c),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Y);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Y,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Se.PreUpdate,Ce([he(En)],e=>{const t=s.getEntitiesWithComponents([Ln,bn]);for(const e of t){if(!s.has(e,Sn))continue;if(s.get(e,Sn).justPressed)return void b(e)}if(null!==o){const e=s.getEntitiesWithComponents([bn]);for(const t of e){if(s.has(t,Ln))continue;if(!s.has(t,Sn))continue;if(s.get(t,Sn).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==o&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==o&&s.valid(o)&&s.has(o,Ln)))){s.get(o,Ln).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Ln)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Ln,on]);for(const e of a){const t=s.get(e,Ln);if(!t.dirty)continue;const n=s.get(e,on),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Y)||s.insert(e,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),C(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Hn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Wn(e){let t=1;for(;t<e;)t*=2;return t}const jn=new On;async function Nn(e,t,s){const n=e.getResource(zs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Vn(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 Xn=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Yn=ue(null,"PhysicsAPI");function qn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Gn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Jn{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Xn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Vn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([G]);for(const s of t){const t=e.world.get(s,G);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Se.PostUpdate,Ce([he(_e)],a=>{const l=o.getEntitiesWithComponents([re,V,X]),c=new Set;for(const r of l){c.add(r);const a=o.get(r,re),l=o.get(r,X);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=qn(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*i,l.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Kn(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===le.Kinematic){const e=qn(l.rotation);n._physics_setBodyTransform(r,l.position.x*i,l.position.y*i,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const u=e.world.get(o,V);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(o,K)){const t=e.world.get(o,K);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,X)){const s=e.world.get(t.entity,X),n=qn(s.rotation),r=a-s.position.x,i=l-s.position.y,o=Math.cos(-n),u=Math.sin(-n);h=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),d=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=c-n}}u.position.x=h,u.position.y=d;const p=Gn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,V,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Xn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Yn,Qn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Kn(e,t,s){const n=e.world;if(n.has(s,ie)){const e=n.get(s,ie);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,oe)){const e=n.get(s,oe);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ae)){const e=n.get(s,ae);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Qn{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(Qn.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Zn(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function er(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function tr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,_=a*d,m=a*f,g=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function sr(e,t,s,n,r,i,o,a,l){const c=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=Zn(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let u={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const l=r.resolvePath(o),c=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===vt(l)?.contentType;let h,d;if(u){const e=await r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=er(n),_=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=Zn(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,s,n)),i){new Jn("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=vt(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=Zn(e,c,!1),h=e.getResourceManager();n[r]=h.loadBitmapFont(t,u,c.width,c.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Je.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Je.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ut(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,d,f);const p=ht(e.world,s);if(l&&e.hasResource(zs))for(const t of p.values())e.world.insert(t,se,{scene:l,persistent:!1});if(r&&h){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const l=n.get(i.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(h,s,u,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let l=a-i;i=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const i=Number(e),o=r[e],a=c.has(i,ee)?c.get(i,ee):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(o,l*h);let d=0;if(c.has(i,X)){const e=tr(c.get(i,X),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,l=2*i,c=s._malloc(a),u=s._malloc(l),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,c,u,h,f);const p=s.HEAPU32[h>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,c,8*r),g=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(c),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(e,t,r,h,n)}if(a){const t=e.getResource(kt);t&&t.setAddressableManifest(a)}}function nr(e,t,s){return{name:e,data:t,async setup(){await sr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class rr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===vt(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=vt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,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),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const ir="__preview__";class or{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(zs);t.register({name:ir,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(ir),this.loadPromise_=t.load(ir).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new rr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await sr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,ir)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([q]);for(const n of s){if(e.get(n,q).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([G]);for(const r of n){const n=e.get(r,G);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(zs).getScene(ir),i=r?r.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,V,o);const a={isActive:!0,projectionType:W.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:j.ColorAndDepth};e.insert(i,q,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(zs);await e.switchTo(ir),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 ar={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ms.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ms.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ms.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ms.releaseRenderTarget(e._handle),ar.create({width:t,height:s,depth:!0})),begin(e,t){Ms.begin(t,e._handle)},end(){Ms.end()},getDepthTexture:e=>Ms.getTargetDepthTexture(e._handle)};let lr=!1;function cr(e){lr=e}function ur(){return lr}function hr(){return!lr}var dr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(dr||(dr={}));class fr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${dr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case dr.Debug:console.debug(t,s);break;case dr.Info:console.log(t,s);break;case dr.Warn:console.warn(t,s);break;case dr.Error:console.error(t,s)}}}class pr{constructor(){this.handlers_=[],this.minLevel_=dr.Info,this.addHandler(new fr)}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,s){this.log(dr.Debug,e,t,s)}info(e,t,s){this.log(dr.Info,e,t,s)}warn(e,t,s){this.log(dr.Warn,e,t,s)}error(e,t,s){this.log(dr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const _r=new pr;function mr(){return _r}function gr(e){_r.setMinLevel(e)}function yr(e,t,s){_r.debug(e,t,s)}function wr(e,t,s){_r.info(e,t,s)}function xr(e,t,s){_r.warn(e,t,s)}function vr(e,t,s){_r.error(e,t,s)}const br=[hn,vn,Fn,zn,jn];function Sr(e,t){return function(e,t){const s=Ws.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Kt(e),Ye(e),fs(e),ys(e),Ts(e),Rs(e);const r=new ks;s.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=Xs(e,n,t,r));const o=s.getResource(Oe);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(Oe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Ms.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(Ms.resize(t,l),vs.isInitialized()&&vs.getPassCount()>0&&!vs.isBypassed()&&vs.resize(t,l),s.hasResource(zs)){const e=s.getResource(zs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=Xs(e,n,t,l,s.world,h);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Ns,width:t,height:l,elapsed:u});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Ms.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(Se.First,l),s.addSystemToSchedule(Se.Last,c),s.addPlugin(Ut),s.addPlugin(Vt),s.addPlugin(Be),s.addPlugin(Hs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:br,...t})}e=f;export{Ws as App,Bt as AssetPlugin,$t as AssetRefCounter,Ft as AssetServer,kt as Assets,it as AsyncCache,Z as BitmapText,He as BlendMode,le as BodyType,ie as BoxCollider,Cn as Button,Pn as ButtonState,q as Camera,G as Canvas,ae as CapsuleCollider,Q as Children,oe as CircleCollider,j as ClearFlags,xe as Commands,be as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,ls as DataType,ts as Draw,ve as EntityCommands,Fs as GLDebug,ms as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,Fe as Input,ke as InputPlugin,Ie as InputState,bn as Interactable,V as LocalTransform,dr as LogLevel,pr as Logger,Je as Material,ot as MaterialLoader,me as Mut,te as Name,K as Parent,Qn as Physics,Xn as PhysicsEvents,Jn as PhysicsPlugin,vs as PostProcess,Wt as PrefabServer,jt as Prefabs,Nt as PrefabsPlugin,or as PreviewPlugin,W as ProjectionType,ye as Query,we as QueryInstance,ks as RenderPipeline,Ss as RenderStage,ar as RenderTexture,Ms as Renderer,he as Res,de as ResMut,re as RigidBody,y as RuntimeConfig,N as ScaleMode,zs as SceneManager,Ds as SceneManagerState,se as SceneOwner,Se as Schedule,Mn as ScreenSpace,rt as ShaderSources,ee as SpineAnimation,Y as Sprite,Re as SystemRunner,rn as Text,tn as TextAlign,Ln as TextInput,On as TextInputPlugin,nn as TextOverflow,un as TextPlugin,an as TextRenderer,sn as TextVerticalAlign,_e as Time,Oe as UICameraInfo,Tn as UIEventQueue,En as UIEvents,Sn as UIInteraction,Dn as UIInteractionPlugin,In as UILayoutPlugin,dn as UIMask,xn as UIMaskPlugin,on as UIRect,J as Velocity,rr as WebAssetProvider,Le as World,X as WorldTransform,Me as addStartupSystem,Ee as addSystem,Ae as addSystemToSchedule,w as applyRuntimeConfig,Ut as assetPlugin,as as clearDrawCallbacks,U as clearUserComponents,T as color,An as computeUIRectLayout,wn as createMaskProcessor,nr as createRuntimeSceneConfig,Sr as createWebApp,yr as debug,F as defineComponent,ue as defineResource,Ce as defineSystem,k as defineTag,vr as error,_t as findEntityByName,js as flushPendingSystems,St as getAddressableType,Pt as getAddressableTypeByEditorType,Tt as getAllAssetExtensions,Rt as getAssetMimeType,vt as getAssetTypeEntry,O as getComponent,ct as getComponentAssetFields,ne as getComponentDefaults,Mt as getCustomExtensions,bt as getEditorType,mr as getLogger,t as getPlatform,n as getPlatformType,B as getUserComponent,At as getWeChatPackOptions,wr as info,Kt as initDrawAPI,Rs as initGLDebugAPI,fs as initGeometryAPI,Ye as initMaterialAPI,ys as initPostProcessAPI,Ts as initRendererAPI,Be as inputPlugin,zt as instantiatePrefab,fn as intersectRects,_n as invertMatrix4,D as isBuiltinComponent,It as isCustomExtension,ur as isEditor,Ct as isKnownAssetExtension,s as isPlatformInitialized,hr as isRuntime,We as isTextureRef,r as isWeChat,i as isWeb,ft as loadComponent,Vn as loadPhysicsModule,sr as loadRuntimeScene,ht as loadSceneData,dt as loadSceneWithAssets,Et as looksLikeAssetPath,o as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,gn as pointInWorldRect,Vt as prefabsPlugin,E as quat,L as registerComponent,lt as registerComponentAssetFields,is as registerDrawCallback,Dt as registerEmbeddedAssets,nt as registerMaterialCallback,Hs as sceneManagerPlugin,mn as screenToWorld,cr as setEditorMode,gr as setLogLevel,Qt as shutdownDrawAPI,Is as shutdownGLDebugAPI,ps as shutdownGeometryAPI,qe as shutdownMaterialAPI,ws as shutdownPostProcessAPI,Es as shutdownRendererAPI,jn as textInputPlugin,hn as textPlugin,Nn as transitionTo,zn as uiInteractionPlugin,Fn as uiLayoutPlugin,vn as uiMaskPlugin,br as uiPlugins,os as unregisterDrawCallback,pt as updateCameraAspectRatio,S as vec2,P as vec3,C as vec4,xr as warn,pn as worldRectToScreen,Ls 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 s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function h(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),i=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},o=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},h=()=>{e.onPointerUp(0)},u=t=>{const s=t;e.onWheel(s.deltaX,s.deltaY)};document.addEventListener("keydown",n),document.addEventListener("keyup",r),s.addEventListener("mousemove",i),s.addEventListener("mousedown",o),s.addEventListener("mouseup",a),s.addEventListener("touchstart",c),s.addEventListener("touchmove",l),s.addEventListener("touchend",h),s.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r),s.removeEventListener("mousemove",i),s.removeEventListener("mousedown",o),s.removeEventListener("mouseup",a),s.removeEventListener("touchstart",c),s.removeEventListener("touchmove",l),s.removeEventListener("touchend",h),s.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,m=100,g=512,y={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function w(e){e.Text&&(e.Text._default.fontFamily=y.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=y.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=y.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=y.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),C=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),T=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),E=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function M(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(M);const t={};for(const s in e)t[s]=M(e[s]);return t}let R=0;function A(e,t){const s=++R;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...M(t),...e}:M(t)}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const s=I(),n=s.get(e);if(n)return n;const r=A(e,t);return s.set(e,r),U(e,t,!1),r}function $(e){const t=I(),s=t.get(e);if(s)return s;const n=A(e,{});return t.set(e,n),U(e,{},!0),n}function k(e){return I().get(e)}function B(){I().clear()}function U(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function D(e){return!0===e._builtin}const z=new Map;function L(e,t){z.set(e,t)}function O(e){return z.get(e)??k(e)}function H(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return z.set(e,s),s}const W={Perspective:0,Orthographic:1},j={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},N={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},V=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),X=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Y=H("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),q=H("Camera",{projectionType:W.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:j.ColorAndDepth}),G=H("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:N.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),J=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),K=H("Parent",{entity:0}),Q=H("Children",{entities:[]}),Z=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),ee=H("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}),te={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=F("SceneOwner",{scene:"",persistent:!1});function ne(e){const t=O(e);return t?M(t._default):null}L("Name",te);const re=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ie=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ae=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ce={Static:0,Kinematic:1,Dynamic:2};let le=0;function he(e,t){const s=++le;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ue(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class pe{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 fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=he({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ye(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{ge(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class we{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ge(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let h=null;this.world_.beginIteration();try{for(const u of n){if(null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function xe(){return{_type:"commands"}}class ve{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ve(this,null);return this.spawned_.push(e),e}entity(e){return new ve(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":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)}}}var Se;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Se||(Se={}));let Pe=0;function Ce(e,t,s){const n=++Pe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ee(e){Te().push({schedule:Se.Update,system:e})}function Me(e){Te().push({schedule:Se.Startup,system:e})}function Re(e,t){Te().push({schedule:e,system:t})}class Ae{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof be&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Fe=he(new Ie,"Input");class $e{constructor(e){this.target_=e??null}build(e){const s=new Ie;e.insertResource(Fe,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Se.Last,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ke=new $e;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ue(t[e]),i=Ue(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let ze=null;function Le(e){ze=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ze&&ze(e,t)}function He(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:He(e)}}return t}class We{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}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 Oe(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Oe(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Oe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return D(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(D(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Oe(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):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.");D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(r))}catch(s){Oe(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Oe(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Oe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Oe(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(De(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!D(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const je=he({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Ne;function Ve(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"}(Ne||(Ne={}));let Xe=null,Ye=null,qe=1;const Ge=new Map;function Je(e){Xe=e,Ye=e.getResourceManager(),ot()}function Ke(){0!==tt&&Xe&&(Xe._free(tt),tt=0),Ge.clear(),qe=1,et=!1,nt.clear(),rt=null,Ye=null,Xe=null}function Qe(){if(!Ye)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ye}const Ze={createShader:(e,t)=>Qe().createShader(e,t),releaseShader(e){e>0&&Qe().releaseShader(e)},create(e){const t=qe++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ne.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ge.set(t,s),t},get:e=>Ge.get(e),setUniform(e,t,s){const n=Ge.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ge.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ge.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ge.get(e);return t?.blendMode??Ne.Normal},setDepthTest(e,t){const s=Ge.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ge.get(e);return t?.shader??0},release(e){Ge.delete(e)},isValid:e=>Ge.has(e),releaseAll(){Ge.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??Ne.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ge.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=qe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ge.set(s,n),s},toAssetData(e,t){const s=Ge.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ge.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let et=!1,tt=0;const st=4096,nt=new Map;let rt=null;function it(e){const t=(0===tt&&Xe&&(tt=Xe._malloc(st)),tt);if(0===t||!Xe)return{ptr:0,count:0};let s=0,n=0;const r=Xe.HEAPU8,i=Xe.HEAPU32,o=Xe.HEAPF32;for(const[a,c]of e){if(s+128>st)break;let e=nt.get(a);e||(rt||(rt=new TextEncoder),e=rt.encode(a),nt.set(a,e));const l=e.length,h=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=h;let u=0,d=[0,0,0,0];if("number"==typeof c)u=0,d[0]=c;else if(Array.isArray(c)){u=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(u=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(u=2,d=[c.x,c.y,c.z,0]):"y"in c&&(u=1,d=[c.x,c.y,0,0]);i[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function ot(){if(!Xe||et)return;Xe.materialDataProvider=(e,t,s,n,r)=>{const i=Ge.get(e);if(!i)return Xe.HEAPU32[t>>2]=0,Xe.HEAPU32[s>>2]=0,Xe.HEAPU32[n>>2]=0,void(Xe.HEAPU32[r>>2]=0);Xe.HEAPU32[t>>2]=i.shader,Xe.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=it(i.uniforms);Xe.HEAPU32[n>>2]=o,Xe.HEAPU32[r>>2]=a},et=!0}const at={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 ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&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();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class lt{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&&(Ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ze.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Ze.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ht=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"}]}]]);function ut(e,t){ht.set(e,t)}function dt(e){const t=ht.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function ft(e){return ht.get(e)?.fields??[]}function pt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,te,{value:n.name}),!1!==n.visible)for(const s of n.components)mt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function _t(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);h.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=h.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,te,{value:s.name}),!1!==s.visible)for(const n of s.components)mt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function mt(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function gt(e,t){const s=e.getEntitiesWithComponents([q]);for(const n of s){const s=e.get(n,q);s&&(s.aspectRatio=t,e.insert(n,q,s))}}function yt(e,t){const s=e.getEntitiesWithComponents([te]);for(const n of s){const s=e.get(n,te);if(s&&s.value===t)return n}return null}const wt=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],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}],xt={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",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},vt=new Map,bt=new Set;for(const e of wt)for(const t of e.extensions)vt.set(t,e),bt.add(t);function St(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Pt(e){return vt.get(St(e))}function Ct(e){return Pt(e)?.editorType??"unknown"}function Tt(e){return Pt(e)?.addressableType??null}function Et(e){for(const t of wt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Mt(e){return bt.has(e.toLowerCase())}function Rt(){return bt}function At(e){return"string"==typeof e&&(!!e.includes("/")&&Mt(St(e)))}function It(){const e=[];for(const t of wt)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Ft(){return It().map(e=>({type:"suffix",value:e}))}function $t(e){return xt[e.toLowerCase()]}function kt(e){const t=Pt(e);return t?.wechatPackInclude??!1}class Bt{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.module_=e,this.canvas_=u(y.textCanvasSize,y.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 lt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);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 s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}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(),Ze.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 s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),h="binary"===Pt(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,i,h);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=Pt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return _t(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}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},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"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 s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{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 s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ut=he(null,"Assets");class Dt{build(e){const t=e.wasmModule;t?e.insertResource(Ut,new Bt(t)):console.warn("AssetPlugin: No WASM module available")}}const zt=new Dt;class Lt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.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 s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.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,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});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 Ot(e,t){const s=e.getResource(Ut);s&&s.registerEmbeddedAssets(t)}async function Ht(e,t,s){const{entities:n,rootId:r}=await jt(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await _t(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Wt=10;async function jt(e,t,s,n,r,i=0){if(i>Wt)throw new Error(`Prefab nesting depth exceeded ${Wt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await jt(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),h=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:h?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Nt(u,t),c.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function Nt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class Vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Xt=he(null,"Prefabs");class Yt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ut]}build(e){const t=e.getResource(Ut);e.insertResource(Xt,new Vt(e.world,t))}}const qt=new Yt;let Gt=null,Jt=0,Kt=0,Qt=0;const Zt=new Float32Array(256);function es(e){Gt=e,Jt=Gt._malloc(64),Kt=Gt._malloc(64),Qt=Gt._malloc(1024)}function ts(){Gt&&(Jt&&(Gt._free(Jt),Jt=0),Kt&&(Gt._free(Kt),Kt=0),Qt&&(Gt._free(Qt),Qt=0)),Gt=null}function ss(){if(!Gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Gt}const ns={r:1,g:1,b:1,a:1},rs={begin(e){const t=ss();try{t.HEAPF32.set(e,Jt/4),t.draw_begin(Jt)}catch(e){Oe(e,"Draw.begin")}},end(){try{ss().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,s,n=1){try{ss().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.line")}},rect(e,t,s,n=!0){try{ss().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ss().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{ss().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{ss().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,s,n=ns){try{ss().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,s,n,r=ns){try{ss().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){ss().draw_setLayer(e)},setDepth(e){ss().draw_setDepth(e)},getDrawCallCount:()=>Gt?Gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Gt?Gt.draw_getPrimitiveCount():0,setBlendMode(e){ss().draw_setBlendMode(e)},setDepthTest(e){ss().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ss();n.HEAPF32.set(s,Kt/4),n.draw_mesh(e,t,Kt)}catch(s){Oe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ss(),r=Ze.get(t);if(!r)return;if(rs.setBlendMode(r.blendMode),rs.setDepthTest(r.depthTest),0===r.uniforms.size)return void rs.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,Kt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=as(t);if(!(n<0)){if(Ve(s))Zt[i++]=10,Zt[i++]=n,Zt[i++]=s.slot??e++,Zt[i++]=s.textureId;else if("number"==typeof s)Zt[i++]=1,Zt[i++]=n,Zt[i++]=s;else if(Array.isArray(s)){Zt[i++]=s.length,Zt[i++]=n;for(let e=0;e<s.length;e++)Zt[i++]=s[e]}else"w"in s?(Zt[i++]=4,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z,Zt[i++]=s.w):"z"in s?(Zt[i++]=3,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z):(Zt[i++]=2,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(Zt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void n.draw_mesh(e,r.shader,Kt);n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Qt/4),n.draw_meshWithUniforms(e,r.shader,Kt,Qt,i)}catch(s){Oe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},is={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},os=new Set;function as(e){const t=is[e];return void 0!==t?t:(os.has(e)||(os.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(is).join(", ")}`)),-1)}const cs=new Map;function ls(e,t,s){cs.set(e,{fn:t,scene:s??""})}function hs(e){cs.delete(e)}function us(){cs.clear()}var ds;!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"}(ds||(ds={}));let fs=null,ps=0,_s=0,ms=0;function gs(e){fs=e,ps=fs._malloc(262144),_s=fs._malloc(65536),ms=fs._malloc(256)}function ys(){fs&&(ps&&fs._free(ps),_s&&fs._free(_s),ms&&fs._free(ms),ps=0,_s=0,ms=0),fs=null}function ws(){if(!fs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return fs}const xs={create(e){const t=ws(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,ps/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ms,r).set(i),t.geometry_init(s,ps,n,ms,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices16(s,_s,n)}else{new Uint32Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices32(s,_s,n)}}return s},updateVertices(e,t,s=0){const n=ws(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ps/4),n.geometry_updateVertices(e,ps,r,s)},release(e){e>0&&ws().geometry_release(e)},isValid:e=>!(!fs||e<=0)&&fs.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return xs.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return xs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return xs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(o)})}};let vs=null;function bs(e){vs=e}function Ss(){vs&&Cs.isInitialized()&&Cs.shutdown(),vs=null}function Ps(){if(!vs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vs}const Cs={init(e,t){try{return Ps().postprocess_init(e,t)}catch(s){return Oe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ps().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{Ps().postprocess_resize(e,t)}catch(s){Oe(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ps().postprocess_addPass(e,t)}catch(t){return Oe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ps().postprocess_removePass(e)}catch(t){Oe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ps().postprocess_setPassEnabled(e,t)}catch(t){Oe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ps().postprocess_isPassEnabled(e)}catch(t){return Oe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Ps().postprocess_setUniformFloat(e,t,s)}catch(s){Oe(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Ps().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Oe(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ps().postprocess_begin()}catch(e){Oe(e,"PostProcess.begin")}},end(){try{Ps().postprocess_end()}catch(e){Oe(e,"PostProcess.end")}},getPassCount(){try{return Ps().postprocess_getPassCount()}catch(e){return Oe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!vs)return!1;try{return vs.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ps().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},isBypassed(){if(!vs)return!0;try{return vs.postprocess_isBypassed()}catch(e){return Oe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ze.createShader(Ts,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ze.createShader(Ts,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ze.createShader(Ts,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ze.createShader(Ts,"#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")},Ts="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Es;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Es||(Es={}));let Ms=null,Rs=0;function As(e){Ms=e,Rs=Ms._malloc(64)}function Is(){Ms&&Rs&&(Ms._free(Rs),Rs=0),Ms=null}const Fs={init(e,t){Ms?.renderer_init(e,t)},resize(e,t){Ms?.renderer_resize(e,t)},begin(e,t){if(Ms&&Rs)try{Ms.HEAPF32.set(e,Rs/4),Ms.renderer_begin(Rs,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{Ms?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{Ms?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(Ms)try{Ms.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ms)try{Ms.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ms)try{Ms.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},setStage(e){Ms?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ms?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ms?.renderer_releaseTarget(e)},getTargetTexture:e=>Ms?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ms?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ms?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ms?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Ms?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Ms?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ms?Ms.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Ms?{drawCalls:Ms.renderer_getDrawCalls(),triangles:Ms.renderer_getTriangles(),sprites:Ms.renderer_getSprites(),text:Ms.renderer_getText(),spine:Ms.renderer_getSpine?.()??0,meshes:Ms.renderer_getMeshes(),culled:Ms.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let $s=null;function ks(e){$s=e}function Bs(){$s=null}const Us={enable(){$s?.gl_enableErrorCheck(!0)},disable(){$s?.gl_enableErrorCheck(!1)},check:e=>$s?.gl_checkErrors(e)??0,diagnose(){$s?.renderer_diagnose()}};class Ds{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Fs.resize(n,r),Cs.isInitialized()&&Cs.getPassCount()>0&&Cs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Fs.setViewport(0,0,n,r),Fs.clearBuffers(3),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Fs.setViewport(n.x,n.y,n.w,n.h),Fs.setScissor(n.x,n.y,n.w,n.h,!0),Fs.clearBuffers(r),Fs.setScissor(0,0,0,0,!1),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}executeDrawCallbacks(e,t){const s=cs;if(s.size>0){rs.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}rs.end();for(const e of n)hs(e)}}}const zs="__scene_transition_overlay__";class Ls{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Os{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,se,{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),ls(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Cs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Cs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,se)){const s=this.app_.world.get(e,se);s.persistent=t,this.app_.world.insert(e,se,s)}}}class Hs{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.loadPromises_=new Map,this.app_=e}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_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??y.sceneTransitionDuration,r=t.color??{...y.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ls(zs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;rs.setLayer(9999),rs.setDepth(9999),rs.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}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_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,hs(zs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,hs(zs),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 s=new Ls(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 s=new Ls(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,se)){if(this.app_.world.get(e,se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())hs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Cs.removePass(e)}catch{}s.postProcessPasses.length=0,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)}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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Y,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Y,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Cs.setEnabled(s,t)}catch{}}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,s]of this.scenes_)"running"===s.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 Ws=he(null,"SceneManager");function js(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ws).getSceneStatus(t)&&s._fn(...n)}}}const Ns=Ce([de(Ws),ue(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vs={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Ws,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ws),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Se.Startup,s),e.addSystemToSchedule(Se.Last,Ns)}};class Xs{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_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Se.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Se.FixedPreUpdate),this.runSchedule(Se.FixedUpdate),this.runSchedule(Se.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Se.PreUpdate),this.runSchedule(Se.Update),this.runSchedule(Se.PostUpdate),this.runSchedule(Se.Last),requestAnimationFrame(this.mainLoop)},this.world_=new We,this.resources_=new pe;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Xs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Se.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Se.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(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}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 Le(e),this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Ws).register(e),this}setInitialScene(e){return this.getResource(Ws).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ae(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,us();const e=[Bs,Is,Ss,ys,Ke,ts];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){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ys(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const qs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Gs(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case N.FixedWidth:return i;case N.FixedHeight:return o;case N.Expand:return Math.max(i,o);case N.Shrink:return Math.min(i,o);case N.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function Js(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let h,u=0,d=0;if(r.projectionType===W.Orthographic){if(d=r.orthoSize,c){d=Gs(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}u=d*a,h=Qs(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=en(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=sn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(rn(h,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Ks=new Float32Array(16);function Qs(e,t,s,n,r,i){const o=Ks;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const Zs=new Float32Array(16);function en(e,t,s,n){const r=Zs;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const tn=new Float32Array(16);function sn(e,t,s){const n=tn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const nn=new Float32Array(16);function rn(e,t){const s=nn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var on,an,cn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(on||(on={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(an||(an={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(cn||(cn={}));const ln=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:on.Left,verticalAlign:an.Top,wordWrap:!0,overflow:cn.Visible,lineHeight:1.2}),hn=F("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class un{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(y.textCanvasSize,y.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):u+2*h,p=r?Math.ceil(o):d+2*h;if(r&&e.overflow===cn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,r&&e.overflow===cn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case an.Top:x=h;break;case an.Middle:x=(p-w)/2;break;case an.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of c){let n;switch(e.align){case on.Left:n=h;break;case on.Center:n=f/2;break;case on.Right:n=f-h;break;default:n=h}s.fillText(t,n,v),v+=l}r&&e.overflow===cn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case on.Left:return"left";case on.Center:return"center";case on.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function dn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function fn(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class pn{build(e){L("Text",ln);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new un(t),n=e.world,r=new Map;e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,ln));for(const e of r.keys())n.valid(e)&&n.has(e,ln)||r.delete(e);const e=n.getEntitiesWithComponents([ln]);for(const t of e){const e=n.get(t,ln),i=n.has(t,hn)?n.get(t,hn):null,o=r.get(t);if(o&&!fn(o,e,i))continue;n.has(t,Y)||n.insert(t,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),c=n.get(t,Y);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Y,c),r.set(t,dn(e,i))}}))}}const _n=new pn,mn=F("UIMask",{enabled:!0});function gn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function yn(e,t,s,n,r,i,o,a,c,l,h){const u=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*h]}const[m,g]=_(u,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function wn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*h-o*a,b=r*l-i*c,S=r*h-o*c,P=i*h-o*l,C=u*m-d*_,T=u*g-f*_,E=u*y-p*_,M=d*g-f*m,R=d*y-p*m,A=f*y-p*g;let I=w*A-x*R+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*A-l*R+h*M)*I,s[1]=(i*R-r*A-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*A-h*T)*I,s[5]=(n*A-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(u*P-f*v+p*x)*I,s[8]=(a*R-c*E+h*C)*I,s[9]=(r*E-n*R-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-u*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(u*b-d*x+f*w)*I),s}function xn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],h=s[1]*a+s[5]*c+s[13],u=s[3]*a+s[7]*c+s[15];return{x:l/u,y:h/u}}function vn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function bn(e,t,s,n,r,i,o){if(!e.has(t,hn)||!e.has(t,X))return null;const a=e.get(t,hn),c=e.get(t,X),l=a.size.x*c.scale.x,h=a.size.y*c.scale.y;return yn(c.position.x,c.position.y,l,h,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Sn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([mn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,mn).enabled&&l.add(e)}const h=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,K);){const e=t.get(n,K);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&h.push(e)}function u(n,h){const d=e.getChildEntities(s,n);for(const s of d){let n=h;if(l.has(s)){const e=bn(t,s,r,i,o,a,c);e&&(n=gn(h,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of h){const s=bn(t,e,r,i,o,a,c);s&&u(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Pn{build(e){if(L("UIMask",mn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Sn(e.wasmModule,e.world))}}const Cn=new Pn,Tn=F("Interactable",{enabled:!0}),En=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Mn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Mn||(Mn={}));const Rn=F("Button",{state:Mn.Normal,transition:null});class An{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const In=he(new An,"UIEvents"),Fn=$("ScreenSpace");function $n(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,h=i.bottom+e.y*a,u=i.bottom+t.y*a;let d,f,p,_;if(c===l&&h===u){const e=c+s.x,t=h+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=h+s.y,p=l+n.x,_=u+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function kn(e,t,s,n,r,i){if(!e.has(t,hn))return;const o=e.get(t,hn),a=$n(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,V);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,V,c),!e.has(t,Q))return;const l=e.get(t,Q);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&kn(e,t,a.rect,a.centerX,a.centerY,!1)}class Bn{build(e){L("UIRect",hn);const t=e.world;e.addSystemToSchedule(Se.PreUpdate,Ce([ue(je)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Fn,hn,V]);for(const e of i)kn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Un=new Bn,Dn=new Float32Array(16),zn=new Float32Array(16);let Ln=!0,On=1;class Hn{build(e){L("Interactable",Tn),L("Button",Rn);const t=e.world,s=new An;e.insertResource(In,s);let n=null,r=null;On="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Se.PreUpdate,Ce([ue(Fe),ue(je)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([En]);for(const e of o){const s=t.get(e,En);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*On,c=i.screenH-e.mouseY*On;!function(e){let t=!1;for(let s=0;s<16;s++)if(zn[s]!==e[s]){t=!0;break}t&&(zn.set(e),Ln=!0)}(i.viewProjection),Ln&&(wn(i.viewProjection,Dn),Ln=!1);const l=xn(a,c,Dn,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([Tn,hn,X]);let u=null,d=-1/0;for(const e of h){t.has(e,En)||t.insert(e,En);if(!t.get(e,Tn).enabled)continue;const s=t.get(e,X),n=t.get(e,hn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(vn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Y)&&(s=t.get(e,Y).layer),s>=d&&(d=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,En)){t.get(n,En).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,En).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,En);e.pressed=!0,e.justPressed=!0,r=u,s.emit(u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,En)){const e=t.get(r,En);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Se.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([Rn]);for(const s of e){if(t.has(s,Tn)||t.insert(s,Tn,{enabled:!0}),!t.has(s,En))continue;const e=t.get(s,En),n=t.get(s,Rn),r=t.get(s,Tn),i=n.state;if(r.enabled?e.pressed?n.state=Mn.Pressed:e.hovered?n.state=Mn.Hovered:n.state=Mn.Normal:n.state=Mn.Disabled,i!==n.state&&n.transition&&t.has(s,Y)){const e=t.get(s,Y),r=n.transition;switch(n.state){case Mn.Normal:e.color={...r.normalColor};break;case Mn.Hovered:e.color={...r.hoveredColor};break;case Mn.Pressed:e.color={...r.pressedColor};break;case Mn.Disabled:e.color={...r.disabledColor}}t.insert(s,Y,e)}}},{name:"ButtonSystem"}))}}const Wn=new Hn,jn=F("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});class Nn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){L("TextInput",jn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=u(y.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,h=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||x()},_=()=>{a=!0},m=()=>{a=!1,x()},g=t=>{if(null===o)return;if("Escape"===t.key)return void S();const n=s.get(o,jn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(In).emit(o,"submit"),void S()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,P())},w=()=>{if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null};function x(){if(null===o||!s.valid(o))return;const t=s.get(o,jn);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(In).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,P()}function b(e){if(o===e)return;S();const t=s.get(e,jn);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function P(){c=!0,l=0}function C(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Xn(Math.max(r.width,a)),r.height=Xn(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const h=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const u=0===o.value.length,d=u?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=u?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=Vn(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=Vn(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,l),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Y);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Y,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Se.PreUpdate,Ce([ue(In)],e=>{const t=s.getEntitiesWithComponents([jn,Tn]);for(const e of t){if(!s.has(e,En))continue;if(s.get(e,En).justPressed)return void b(e)}if(null!==o){const e=s.getEntitiesWithComponents([Tn]);for(const t of e){if(s.has(t,jn))continue;if(!s.has(t,En))continue;if(s.get(t,En).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,jn)))){s.get(o,jn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,jn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([jn,hn]);for(const e of a){const t=s.get(e,jn);if(!t.dirty)continue;const n=s.get(e,hn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Y)||s.insert(e,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),C(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Vn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Xn(e){let t=1;for(;t<e;)t*=2;return t}const Yn=new Nn;async function qn(e,t,s){const n=e.getResource(Ws);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Gn(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 Jn=he({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Kn=he(null,"PhysicsAPI");function Qn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Zn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class er{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Jn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Gn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([G]);for(const s of t){const t=e.world.get(s,G);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Se.PostUpdate,Ce([ue(_e)],a=>{const c=o.getEntitiesWithComponents([re,V,X]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,re),c=o.get(r,X);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=Qn(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),tr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ce.Kinematic){const e=Qn(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const h=e.world.get(o,V);if(!h)continue;let u=a,d=c,f=l;if(e.world.has(o,K)){const t=e.world.get(o,K);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,X)){const s=e.world.get(t.entity,X),n=Qn(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),h=Math.sin(-n);u=(r*o-i*h)/(0!==s.scale.x?s.scale.x:1),d=(r*h+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}h.position.x=u,h.position.y=d;const p=Zn(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(o,V,h)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<h;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Jn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Kn,sr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function tr(e,t,s){const n=e.world;if(n.has(s,ie)){const e=n.get(s,ie);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,oe)){const e=n.get(s,oe);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ae)){const e=n.get(s,ae);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class sr{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(sr.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function nr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function rr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ir(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,h=e.rotation.w,u=a+a,d=c+c,f=l+l,p=a*u,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function or(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=nr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),h="binary"===Pt(c)?.contentType;let u,d;if(h){const e=await r.readBinary(o);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,u=t._malloc(d+1),t.HEAPU8.set(s,u),t.HEAPU8[u+d]=0}const f=s.loadSkeleton(u,d,n,n.length,h);if(t._free(u),f<0)continue;i[o]=f;const p=rr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=nr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,u,s,n)),i){new er("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=Pt(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),h=nr(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,h,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Ze.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Ze.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ft(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=pt(e.world,s);if(c&&e.hasResource(Ws))for(const t of p.values())e.world.insert(t,se,{scene:c,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,h,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,ee)?l.get(i,ee):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&n.update(o,c*u);let d=0;if(l.has(i,X)){const e=ir(l.get(i,X),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),h=s._malloc(c),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,h,u,f);const p=s.HEAPU32[u>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,l,8*r),g=new Uint16Array(s.HEAPU8.buffer,h,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(h),s._free(u),s._free(f)}d&&t._free(d)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Ut);t&&t.setAddressableManifest(a)}}function ar(e,t,s){return{name:e,data:t,async setup(){await or(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class cr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===Pt(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=Pt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,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),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const lr="__preview__";class hr{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(Ws);t.register({name:lr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(lr),this.loadPromise_=t.load(lr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new cr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await or(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,lr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([q]);for(const n of s){if(e.get(n,q).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([G]);for(const r of n){const n=e.get(r,G);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Ws).getScene(lr),i=r?r.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,V,o);const a={isActive:!0,projectionType:W.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:j.ColorAndDepth};e.insert(i,q,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(Ws);await e.switchTo(lr),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 ur={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Fs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Fs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Fs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Fs.releaseRenderTarget(e._handle),ur.create({width:t,height:s,depth:!0})),begin(e,t){Fs.begin(t,e._handle)},end(){Fs.end()},getDepthTexture:e=>Fs.getTargetDepthTexture(e._handle)};let dr=!1;function fr(e){dr=e}function pr(){return dr}function _r(){return!dr}var mr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(mr||(mr={}));class gr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${mr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case mr.Debug:console.debug(t,s);break;case mr.Info:console.log(t,s);break;case mr.Warn:console.warn(t,s);break;case mr.Error:console.error(t,s)}}}class yr{constructor(){this.handlers_=[],this.minLevel_=mr.Info,this.addHandler(new gr)}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,s){this.log(mr.Debug,e,t,s)}info(e,t,s){this.log(mr.Info,e,t,s)}warn(e,t,s){this.log(mr.Warn,e,t,s)}error(e,t,s){this.log(mr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const wr=new yr;function xr(){return wr}function vr(e){wr.setMinLevel(e)}function br(e,t,s){wr.debug(e,t,s)}function Sr(e,t,s){wr.info(e,t,s)}function Pr(e,t,s){wr.warn(e,t,s)}function Cr(e,t,s){wr.error(e,t,s)}const Tr=[_n,Cn,Un,Wn,Yn];function Er(e,t){return function(e,t){const s=Xs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),es(e),Je(e),gs(e),bs(e),As(e),ks(e);const r=new Ds;s.setPipeline(r);let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=Js(e,n,t,r));const o=s.getResource(je);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(je,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Fs.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-i)/1e3;let u;if(Fs.resize(t,c),Cs.isInitialized()&&Cs.getPassCount()>0&&!Cs.isBypassed()&&Cs.resize(t,c),s.hasResource(Ws)){const e=s.getResource(Ws).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=Js(e,n,t,c,s.world,u);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:qs,width:t,height:c,elapsed:h});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:h})}Fs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Se.First,c),s.addSystemToSchedule(Se.Last,l),s.addPlugin(zt),s.addPlugin(qt),s.addPlugin(ke),s.addPlugin(Vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Tr,...t})}e=f;export{Xs as App,Dt as AssetPlugin,Lt as AssetRefCounter,Bt as AssetServer,Ut as Assets,ct as AsyncCache,Z as BitmapText,Ne as BlendMode,ce as BodyType,ie as BoxCollider,Rn as Button,Mn as ButtonState,q as Camera,G as Canvas,ae as CapsuleCollider,Q as Children,oe as CircleCollider,j as ClearFlags,xe as Commands,be as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,ds as DataType,rs as Draw,ve as EntityCommands,Us as GLDebug,xs as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,Fe as Input,$e as InputPlugin,Ie as InputState,Tn as Interactable,V as LocalTransform,mr as LogLevel,yr as Logger,Ze as Material,lt as MaterialLoader,me as Mut,te as Name,K as Parent,sr as Physics,Jn as PhysicsEvents,er as PhysicsPlugin,Cs as PostProcess,Vt as PrefabServer,Xt as Prefabs,Yt as PrefabsPlugin,hr as PreviewPlugin,W as ProjectionType,ye as Query,we as QueryInstance,Ds as RenderPipeline,Es as RenderStage,ur as RenderTexture,Fs as Renderer,ue as Res,de as ResMut,re as RigidBody,y as RuntimeConfig,N as ScaleMode,Ws as SceneManager,Hs as SceneManagerState,se as SceneOwner,Se as Schedule,Fn as ScreenSpace,at as ShaderSources,ee as SpineAnimation,Y as Sprite,Ae as SystemRunner,ln as Text,on as TextAlign,jn as TextInput,Nn as TextInputPlugin,cn as TextOverflow,pn as TextPlugin,un as TextRenderer,an as TextVerticalAlign,_e as Time,je as UICameraInfo,An as UIEventQueue,In as UIEvents,En as UIInteraction,Hn as UIInteractionPlugin,Bn as UILayoutPlugin,mn as UIMask,Pn as UIMaskPlugin,hn as UIRect,J as Velocity,cr as WebAssetProvider,We as World,X as WorldTransform,Me as addStartupSystem,Ee as addSystem,Re as addSystemToSchedule,w as applyRuntimeConfig,zt as assetPlugin,us as clearDrawCallbacks,B as clearUserComponents,T as color,$n as computeUIRectLayout,Sn as createMaskProcessor,ar as createRuntimeSceneConfig,Er as createWebApp,br as debug,F as defineComponent,he as defineResource,Ce as defineSystem,$ as defineTag,Cr as error,yt as findEntityByName,Ys as flushPendingSystems,Tt as getAddressableType,Et as getAddressableTypeByEditorType,Rt as getAllAssetExtensions,$t as getAssetMimeType,Pt as getAssetTypeEntry,O as getComponent,dt as getComponentAssetFields,ne as getComponentDefaults,It as getCustomExtensions,Ct as getEditorType,xr as getLogger,t as getPlatform,n as getPlatformType,k as getUserComponent,Ft as getWeChatPackOptions,Sr as info,es as initDrawAPI,ks as initGLDebugAPI,gs as initGeometryAPI,Je as initMaterialAPI,bs as initPostProcessAPI,As as initRendererAPI,ke as inputPlugin,Ht as instantiatePrefab,gn as intersectRects,wn as invertMatrix4,D as isBuiltinComponent,kt as isCustomExtension,pr as isEditor,Mt as isKnownAssetExtension,s as isPlatformInitialized,_r as isRuntime,Ve as isTextureRef,r as isWeChat,i as isWeb,mt as loadComponent,Gn as loadPhysicsModule,or as loadRuntimeScene,pt as loadSceneData,_t as loadSceneWithAssets,At as looksLikeAssetPath,o as platformFetch,l as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,vn as pointInWorldRect,qt as prefabsPlugin,E as quat,L as registerComponent,ut as registerComponentAssetFields,ls as registerDrawCallback,Ot as registerEmbeddedAssets,ot as registerMaterialCallback,Vs as sceneManagerPlugin,xn as screenToWorld,fr as setEditorMode,vr as setLogLevel,Le as setWasmErrorHandler,ts as shutdownDrawAPI,Bs as shutdownGLDebugAPI,ys as shutdownGeometryAPI,Ke as shutdownMaterialAPI,Ss as shutdownPostProcessAPI,Is as shutdownRendererAPI,Yn as textInputPlugin,_n as textPlugin,qn as transitionTo,Wn as uiInteractionPlugin,Un as uiLayoutPlugin,Cn as uiMaskPlugin,Tr as uiPlugins,hs as unregisterDrawCallback,gt as updateCameraAspectRatio,S as vec2,P as vec3,C as vec4,Pr as warn,yn as worldRectToScreen,js as wrapSceneSystem};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.tsindex 387b0c13d..c84a8842a 100644--- a/desktop/public/sdk/esm/physics/index.d.ts+++ b/desktop/public/sdk/esm/physics/index.d.ts@@ -694,6 +694,7 @@ declare class App {private physicsInitPromise_?;private physicsModule_?;private readonly installed_plugins_;+ private readonly sortedSystemsCache_;private error_handler_;private system_error_handler_;private frame_paused_;@@ -709,6 +710,7 @@ declare class App {connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;get wasmModule(): ESEngineModule | null;get pipeline(): RenderPipeline | null;+ setPipeline(pipeline: RenderPipeline): void;setSpineRenderer(fn: SpineRendererFn | null): void;get spineInitPromise(): Promise<unknown> | undefined;set spineInitPromise(p: Promise<unknown> | undefined);@@ -722,6 +724,7 @@ declare class App {setMaxFixedSteps(v: number): this;onError(handler: (error: unknown, systemName: string) => void): this;onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;+ onWasmError(handler: (error: unknown, context: string) => void): this;insertResource<T>(resource: ResourceDef<T>, value: T): this;getResource<T>(resource: ResourceDef<T>): T;hasResource<T>(resource: ResourceDef<T>): boolean;diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.tsindex aa39035a0..60e794452 100644--- a/desktop/public/sdk/esm/spine/index.d.ts+++ b/desktop/public/sdk/esm/spine/index.d.ts@@ -769,6 +769,7 @@ declare class App {private physicsInitPromise_?;private physicsModule_?;private readonly installed_plugins_;+ private readonly sortedSystemsCache_;private error_handler_;private system_error_handler_;private frame_paused_;@@ -784,6 +785,7 @@ declare class App {connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;get wasmModule(): ESEngineModule | null;get pipeline(): RenderPipeline | null;+ setPipeline(pipeline: RenderPipeline): void;setSpineRenderer(fn: SpineRendererFn | null): void;get spineInitPromise(): Promise<unknown> | undefined;set spineInitPromise(p: Promise<unknown> | undefined);@@ -797,6 +799,7 @@ declare class App {setMaxFixedSteps(v: number): this;onError(handler: (error: unknown, systemName: string) => void): this;onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;+ onWasmError(handler: (error: unknown, context: string) => void): this;insertResource<T>(resource: ResourceDef<T>, value: T): this;getResource<T>(resource: ResourceDef<T>): T;hasResource<T>(resource: ResourceDef<T>): boolean;diff --git a/desktop/public/wasm/esengine.js b/desktop/public/wasm/esengine.jsindex fb721ec9c..38c3e29d3 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["$a"]();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 __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 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_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_glDisable=x0=>GLctx.disable(x0);var _glDisable=_emscripten_glDisable;var _emscripten_glDisableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=false;GLctx.disableVertexAttribArray(index)};var _glDisableVertexAttribArray=_emscripten_glDisableVertexAttribArray;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_glGetAttribLocation=(program,name)=>GLctx.getAttribLocation(GL.programs[program],UTF8ToString(name));var _glGetAttribLocation=_emscripten_glGetAttribLocation;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 _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 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_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;function callMaterialProvider(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr){var fn=Module["materialDataProvider"];if(fn){fn(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr)}else{HEAPU32[outShaderIdPtr>>2]=0;HEAPU32[outBlendModePtr>>2]=0;HEAPU32[outUniformBufPtr>>2]=0;HEAPU32[outUniformCountPtr>>2]=0}}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["ab"];_malloc=Module["_malloc"]=wasmExports["bb"];_free=Module["_free"]=wasmExports["cb"];__emscripten_timeout=wasmExports["db"];__emscripten_stack_restore=wasmExports["fb"];__emscripten_stack_alloc=wasmExports["gb"];_emscripten_stack_get_current=wasmExports["hb"];memory=wasmMemory=wasmExports["_a"];__indirect_function_table=wasmTable=wasmExports["eb"]}var wasmImports={ha:___syscall_fcntl64,Ba:___syscall_ioctl,Ca:___syscall_openat,Ga:__abort_js,m:__embind_finalize_value_object,xa:__embind_register_bigint,Qa:__embind_register_bool,qa:__embind_register_class,Ma:__embind_register_class_constructor,c:__embind_register_class_function,Oa:__embind_register_emval,V:__embind_register_enum,t:__embind_register_enum_value,wa:__embind_register_float,b:__embind_register_function,C:__embind_register_integer,n:__embind_register_memory_view,Pa:__embind_register_std_string,fa:__embind_register_std_wstring,l:__embind_register_value_object,a:__embind_register_value_object_field,Ra:__embind_register_void,Ta:__emscripten_runtime_keepalive_clear,N:__emval_create_invoker,A:__emval_decref,M:__emval_invoke,ua:__emval_new_array,Y:__emval_new_cstring,va:__emval_new_object,L:__emval_run_destructors,O:__emval_set_property,Ua:__setitimer_js,Va:__tzset_js,Za:callMaterialProvider,Da:_clock_time_get,Ea:_emscripten_resize_heap,Ya:_emscripten_webgl_create_context,Na:_emscripten_webgl_destroy_context,ya:_emscripten_webgl_make_context_current,Wa:_environ_get,Xa:_environ_sizes_get,ga:_fd_close,Aa:_fd_read,za:_fd_seek,Fa:_fd_write,h:_glActiveTexture,na:_glAttachShader,x:_glBindAttribLocation,d:_glBindBuffer,z:_glBindFramebuffer,f:_glBindTexture,j:_glBindVertexArray,ba:_glBlendFunc,D:_glBlendFuncSeparate,o:_glBufferData,y:_glBufferSubData,Ha:_glCheckFramebufferStatus,I:_glClear,X:_glClearColor,pa:_glCompileShader,La:_glCreateProgram,sa:_glCreateShader,i:_glDeleteBuffers,r:_glDeleteFramebuffers,ta:_glDeleteProgram,H:_glDeleteShader,e:_glDeleteTextures,P:_glDeleteVertexArrays,s:_glDisable,Z:_glDisableVertexAttribArray,ca:_glDrawArrays,E:_glDrawElements,w:_glEnable,u:_glEnableVertexAttribArray,ia:_glFramebufferTexture2D,p:_glGenBuffers,Ia:_glGenFramebuffers,T:_glGenTextures,F:_glGenVertexArrays,Ja:_glGenerateMipmap,_:_glGetAttribLocation,K:_glGetError,da:_glGetIntegerv,Ka:_glGetProgramInfoLog,R:_glGetProgramiv,oa:_glGetShaderInfoLog,Q:_glGetShaderiv,W:_glGetString,g:_glGetUniformLocation,U:_glLinkProgram,ka:_glPixelStorei,ea:_glScissor,ra:_glShaderSource,S:_glTexImage2D,v:_glTexParameteri,ja:_glTexSubImage2D,aa:_glUniform1f,k:_glUniform1i,$:_glUniform2f,ma:_glUniform3f,la:_glUniform4f,G:_glUniformMatrix4fv,B:_glUseProgram,q:_glVertexAttribPointer,J:_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["$a"]();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 __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 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_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_glDisable=x0=>GLctx.disable(x0);var _glDisable=_emscripten_glDisable;var _emscripten_glDisableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=false;GLctx.disableVertexAttribArray(index)};var _glDisableVertexAttribArray=_emscripten_glDisableVertexAttribArray;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_glGetAttribLocation=(program,name)=>GLctx.getAttribLocation(GL.programs[program],UTF8ToString(name));var _glGetAttribLocation=_emscripten_glGetAttribLocation;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 _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 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_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;function callMaterialProvider(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr){var fn=Module["materialDataProvider"];if(fn){fn(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr)}else{HEAPU32[outShaderIdPtr>>2]=0;HEAPU32[outBlendModePtr>>2]=0;HEAPU32[outUniformBufPtr>>2]=0;HEAPU32[outUniformCountPtr>>2]=0}}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["ab"];_malloc=Module["_malloc"]=wasmExports["bb"];_free=Module["_free"]=wasmExports["cb"];__emscripten_timeout=wasmExports["db"];__emscripten_stack_restore=wasmExports["fb"];__emscripten_stack_alloc=wasmExports["gb"];_emscripten_stack_get_current=wasmExports["hb"];memory=wasmMemory=wasmExports["_a"];__indirect_function_table=wasmTable=wasmExports["eb"]}var wasmImports={ha:___syscall_fcntl64,Ba:___syscall_ioctl,Ca:___syscall_openat,Ga:__abort_js,k:__embind_finalize_value_object,xa:__embind_register_bigint,Qa:__embind_register_bool,qa:__embind_register_class,Ma:__embind_register_class_constructor,c:__embind_register_class_function,Oa:__embind_register_emval,V:__embind_register_enum,t:__embind_register_enum_value,wa:__embind_register_float,b:__embind_register_function,C:__embind_register_integer,l:__embind_register_memory_view,Pa:__embind_register_std_string,fa:__embind_register_std_wstring,j:__embind_register_value_object,a:__embind_register_value_object_field,Ra:__embind_register_void,Ta:__emscripten_runtime_keepalive_clear,N:__emval_create_invoker,A:__emval_decref,M:__emval_invoke,ua:__emval_new_array,Y:__emval_new_cstring,va:__emval_new_object,L:__emval_run_destructors,O:__emval_set_property,Ua:__setitimer_js,Va:__tzset_js,Za:callMaterialProvider,Da:_clock_time_get,Ea:_emscripten_resize_heap,Ya:_emscripten_webgl_create_context,Na:_emscripten_webgl_destroy_context,ya:_emscripten_webgl_make_context_current,Wa:_environ_get,Xa:_environ_sizes_get,ga:_fd_close,Aa:_fd_read,za:_fd_seek,Fa:_fd_write,q:_glActiveTexture,na:_glAttachShader,x:_glBindAttribLocation,d:_glBindBuffer,z:_glBindFramebuffer,m:_glBindTexture,h:_glBindVertexArray,ba:_glBlendFunc,D:_glBlendFuncSeparate,n:_glBufferData,y:_glBufferSubData,Ha:_glCheckFramebufferStatus,I:_glClear,X:_glClearColor,pa:_glCompileShader,La:_glCreateProgram,sa:_glCreateShader,g:_glDeleteBuffers,r:_glDeleteFramebuffers,ta:_glDeleteProgram,H:_glDeleteShader,e:_glDeleteTextures,P:_glDeleteVertexArrays,s:_glDisable,Z:_glDisableVertexAttribArray,ca:_glDrawArrays,E:_glDrawElements,w:_glEnable,u:_glEnableVertexAttribArray,ia:_glFramebufferTexture2D,o:_glGenBuffers,Ia:_glGenFramebuffers,T:_glGenTextures,F:_glGenVertexArrays,Ja:_glGenerateMipmap,_:_glGetAttribLocation,K:_glGetError,da:_glGetIntegerv,Ka:_glGetProgramInfoLog,R:_glGetProgramiv,oa:_glGetShaderInfoLog,Q:_glGetShaderiv,W:_glGetString,f:_glGetUniformLocation,U:_glLinkProgram,ka:_glPixelStorei,ea:_glScissor,ra:_glShaderSource,S:_glTexImage2D,v:_glTexParameteri,ja:_glTexSubImage2D,aa:_glUniform1f,i:_glUniform1i,$:_glUniform2f,ma:_glUniform3f,la:_glUniform4f,G:_glUniformMatrix4fv,B:_glUseProgram,p:_glVertexAttribPointer,J:_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/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.locknew file mode 100644index 000000000..c3c29e078--- /dev/null+++ b/desktop/src-tauri/Cargo.lock@@ -0,0 +1,5364 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]++[[package]]+name = "alloc-no-stdlib"+version = "2.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"++[[package]]+name = "alloc-stdlib"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"+dependencies = [+ "alloc-no-stdlib",+]++[[package]]+name = "android_system_properties"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"+dependencies = [+ "libc",+]++[[package]]+name = "anyhow"+version = "1.0.100"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"++[[package]]+name = "arbitrary"+version = "1.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"+dependencies = [+ "derive_arbitrary",+]++[[package]]+name = "ascii"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"++[[package]]+name = "atk"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"+dependencies = [+ "atk-sys",+ "glib",+ "libc",+]++[[package]]+name = "atk-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"++[[package]]+name = "base64"+version = "0.21.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"+dependencies = [+ "serde_core",+]++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "block2"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"+dependencies = [+ "objc2",+]++[[package]]+name = "brotli"+version = "8.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+ "brotli-decompressor",+]++[[package]]+name = "brotli-decompressor"+version = "5.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+]++[[package]]+name = "bumpalo"+version = "3.19.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"++[[package]]+name = "bytemuck"+version = "1.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"++[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"++[[package]]+name = "bytes"+version = "1.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"+dependencies = [+ "serde",+]++[[package]]+name = "cairo-rs"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"+dependencies = [+ "bitflags 2.10.0",+ "cairo-sys-rs",+ "glib",+ "libc",+ "once_cell",+ "thiserror 1.0.69",+]++[[package]]+name = "cairo-sys-rs"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"+dependencies = [+ "glib-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "camino"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e629a66d692cb9ff1a1c664e41771b3dcaf961985a9774c0eb0bd1b51cf60a48"+dependencies = [+ "serde_core",+]++[[package]]+name = "cargo-platform"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"+dependencies = [+ "serde",+]++[[package]]+name = "cargo_metadata"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"+dependencies = [+ "camino",+ "cargo-platform",+ "semver",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+]++[[package]]+name = "cargo_toml"+version = "0.22.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77"+dependencies = [+ "serde",+ "toml 0.9.11+spec-1.1.0",+]++[[package]]+name = "cc"+version = "1.2.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47b26a0954ae34af09b50f0de26458fa95369a0d478d8236d3f93082b219bd29"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "cfb"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f"+dependencies = [+ "byteorder",+ "fnv",+ "uuid",+]++[[package]]+name = "cfg-expr"+version = "0.15.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"+dependencies = [+ "smallvec",+ "target-lexicon",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "chrono"+version = "0.4.43"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118"+dependencies = [+ "iana-time-zone",+ "num-traits",+ "serde",+ "windows-link 0.2.1",+]++[[package]]+name = "chunked_transfer"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"++[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "convert_case"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"++[[package]]+name = "cookie"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"+dependencies = [+ "time",+ "version_check",+]++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "core-graphics"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"+dependencies = [+ "bitflags 2.10.0",+ "core-foundation",+ "core-graphics-types",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-graphics-types"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"+dependencies = [+ "bitflags 2.10.0",+ "core-foundation",+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-channel"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "cssparser"+version = "0.29.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f93d03419cb5950ccfd3daf3ff1c7a36ace64609a1a8746d493df1ca0afde0fa"+dependencies = [+ "cssparser-macros",+ "dtoa-short",+ "itoa",+ "matches",+ "phf 0.10.1",+ "proc-macro2",+ "quote",+ "smallvec",+ "syn 1.0.109",+]++[[package]]+name = "cssparser-macros"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"+dependencies = [+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "ctor"+version = "0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501"+dependencies = [+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "darling"+version = "0.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4"+dependencies = [+ "fnv",+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 2.0.114",+]++[[package]]+name = "darling_macro"+version = "0.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81"+dependencies = [+ "darling_core",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "deranged"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587"+dependencies = [+ "powerfmt",+ "serde_core",+]++[[package]]+name = "derive_arbitrary"+version = "1.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "derive_more"+version = "0.99.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f"+dependencies = [+ "convert_case",+ "proc-macro2",+ "quote",+ "rustc_version",+ "syn 2.0.114",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "dirs"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"+dependencies = [+ "dirs-sys",+]++[[package]]+name = "dirs-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"+dependencies = [+ "libc",+ "option-ext",+ "redox_users",+ "windows-sys 0.61.2",+]++[[package]]+name = "dispatch"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"++[[package]]+name = "dispatch2"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec"+dependencies = [+ "bitflags 2.10.0",+ "block2",+ "libc",+ "objc2",+]++[[package]]+name = "displaydoc"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "dlopen2"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4"+dependencies = [+ "dlopen2_derive",+ "libc",+ "once_cell",+ "winapi",+]++[[package]]+name = "dlopen2_derive"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "dpi"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"+dependencies = [+ "serde",+]++[[package]]+name = "dtoa"+version = "1.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590"++[[package]]+name = "dtoa-short"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87"+dependencies = [+ "dtoa",+]++[[package]]+name = "dunce"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"++[[package]]+name = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"++[[package]]+name = "embed-resource"+version = "3.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55a075fc573c64510038d7ee9abc7990635863992f83ebc52c8b433b8411a02e"+dependencies = [+ "cc",+ "memchr",+ "rustc_version",+ "toml 0.9.11+spec-1.1.0",+ "vswhom",+ "winreg",+]++[[package]]+name = "embed_plist"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"++[[package]]+name = "encoding_rs"+version = "0.8.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"+dependencies = [+ "cfg-if",+]++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "erased-serde"+version = "0.4.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "89e8918065695684b2b0702da20382d5ae6065cf3327bc2d6436bd49a71ce9f3"+dependencies = [+ "serde",+ "serde_core",+ "typeid",+]++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "esengine-editor"+version = "0.1.0"+dependencies = [+ "open",+ "serde",+ "serde_json",+ "tauri",+ "tauri-build",+ "tauri-plugin-dialog",+ "tauri-plugin-fs",+ "tauri-plugin-process",+ "tauri-plugin-shell",+ "tauri-plugin-updater",+ "tiny_http",+ "tokio",+ "urlencoding",+]++[[package]]+name = "fastrand"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "field-offset"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"+dependencies = [+ "memoffset",+ "rustc_version",+]++[[package]]+name = "file-id"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1fc6a637b6dc58414714eddd9170ff187ecb0933d4c7024d1abbd23a3cc26e9"+dependencies = [+ "windows-sys 0.60.2",+]++[[package]]+name = "filetime"+version = "0.2.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db"+dependencies = [+ "cfg-if",+ "libc",+ "libredox",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"++[[package]]+name = "flate2"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"+dependencies = [+ "crc32fast",+ "miniz_oxide",+]++[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"++[[package]]+name = "foreign-types"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"+dependencies = [+ "foreign-types-macros",+ "foreign-types-shared",+]++[[package]]+name = "foreign-types-macros"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "foreign-types-shared"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "fsevent-sys"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"+dependencies = [+ "libc",+]++[[package]]+name = "futf"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843"+dependencies = [+ "mac",+ "new_debug_unreachable",+]++[[package]]+name = "futures-channel"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"+dependencies = [+ "futures-core",+]++[[package]]+name = "futures-core"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"++[[package]]+name = "futures-executor"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-io"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"++[[package]]+name = "futures-macro"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "futures-sink"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"++[[package]]+name = "futures-task"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"++[[package]]+name = "futures-util"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"+dependencies = [+ "futures-core",+ "futures-io",+ "futures-macro",+ "futures-sink",+ "futures-task",+ "memchr",+ "pin-project-lite",+ "pin-utils",+ "slab",+]++[[package]]+name = "fxhash"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c"+dependencies = [+ "byteorder",+]++[[package]]+name = "gdk"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691"+dependencies = [+ "cairo-rs",+ "gdk-pixbuf",+ "gdk-sys",+ "gio",+ "glib",+ "libc",+ "pango",+]++[[package]]+name = "gdk-pixbuf"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"+dependencies = [+ "gdk-pixbuf-sys",+ "gio",+ "glib",+ "libc",+ "once_cell",+]++[[package]]+name = "gdk-pixbuf-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"+dependencies = [+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "gdk-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"+dependencies = [+ "cairo-sys-rs",+ "gdk-pixbuf-sys",+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "pango-sys",+ "pkg-config",+ "system-deps",+]++[[package]]+name = "gdkwayland-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69"+dependencies = [+ "gdk-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "pkg-config",+ "system-deps",+]++[[package]]+name = "gdkx11"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe"+dependencies = [+ "gdk",+ "gdkx11-sys",+ "gio",+ "glib",+ "libc",+ "x11",+]++[[package]]+name = "gdkx11-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d"+dependencies = [+ "gdk-sys",+ "glib-sys",+ "libc",+ "system-deps",+ "x11",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.1.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce"+dependencies = [+ "cfg-if",+ "libc",+ "wasi 0.9.0+wasi-snapshot-preview1",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "libc",+ "wasi 0.11.1+wasi-snapshot-preview1",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+ "wasip2",+]++[[package]]+name = "gio"+version = "0.18.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-util",+ "gio-sys",+ "glib",+ "libc",+ "once_cell",+ "pin-project-lite",+ "smallvec",+ "thiserror 1.0.69",+]++[[package]]+name = "gio-sys"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+ "winapi",+]++[[package]]+name = "glib"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"+dependencies = [+ "bitflags 2.10.0",+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-task",+ "futures-util",+ "gio-sys",+ "glib-macros",+ "glib-sys",+ "gobject-sys",+ "libc",+ "memchr",+ "once_cell",+ "smallvec",+ "thiserror 1.0.69",+]++[[package]]+name = "glib-macros"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"+dependencies = [+ "heck 0.4.1",+ "proc-macro-crate 2.0.2",+ "proc-macro-error",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "glib-sys"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"+dependencies = [+ "libc",+ "system-deps",+]++[[package]]+name = "glob"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"++[[package]]+name = "gobject-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"+dependencies = [+ "glib-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "gtk"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a"+dependencies = [+ "atk",+ "cairo-rs",+ "field-offset",+ "futures-channel",+ "gdk",+ "gdk-pixbuf",+ "gio",+ "glib",+ "gtk-sys",+ "gtk3-macros",+ "libc",+ "pango",+ "pkg-config",+]++[[package]]+name = "gtk-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414"+dependencies = [+ "atk-sys",+ "cairo-sys-rs",+ "gdk-pixbuf-sys",+ "gdk-sys",+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "pango-sys",+ "system-deps",+]++[[package]]+name = "gtk3-macros"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d"+dependencies = [+ "proc-macro-crate 1.3.1",+ "proc-macro-error",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "hashbrown"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"++[[package]]+name = "heck"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "html5ever"+version = "0.29.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b7410cae13cbc75623c98ac4cbfd1f0bedddf3227afc24f370cf0f50a44a11c"+dependencies = [+ "log",+ "mac",+ "markup5ever",+ "match_token",+]++[[package]]+name = "http"+version = "1.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "http-range"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "21dec9db110f5f872ed9699c3ecf50cf16f423502706ba5c72462e28d3157573"++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"++[[package]]+name = "hyper"+version = "1.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-channel",+ "futures-core",+ "http",+ "http-body",+ "httparse",+ "itoa",+ "pin-project-lite",+ "pin-utils",+ "smallvec",+ "tokio",+ "want",+]++[[package]]+name = "hyper-rustls"+version = "0.27.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "rustls-pki-types",+ "tokio",+ "tokio-rustls",+ "tower-service",+]++[[package]]+name = "hyper-util"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-channel",+ "futures-util",+ "http",+ "http-body",+ "hyper",+ "ipnet",+ "libc",+ "percent-encoding",+ "pin-project-lite",+ "socket2",+ "tokio",+ "tower-service",+ "tracing",+]++[[package]]+name = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core 0.62.2",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "ico"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371"+dependencies = [+ "byteorder",+ "png",+]++[[package]]+name = "icu_collections"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43"+dependencies = [+ "displaydoc",+ "potential_utf",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a"++[[package]]+name = "icu_properties"+version = "2.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec"+dependencies = [+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af"++[[package]]+name = "icu_provider"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "indexmap"+version = "1.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"+dependencies = [+ "autocfg",+ "hashbrown 0.12.3",+ "serde",+]++[[package]]+name = "indexmap"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"+dependencies = [+ "equivalent",+ "hashbrown 0.16.1",+ "serde",+ "serde_core",+]++[[package]]+name = "infer"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7"+dependencies = [+ "cfb",+]++[[package]]+name = "inotify"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f37dccff2791ab604f9babef0ba14fbe0be30bd368dc541e2b08d07c8aa908f3"+dependencies = [+ "bitflags 2.10.0",+ "inotify-sys",+ "libc",+]++[[package]]+name = "inotify-sys"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb"+dependencies = [+ "libc",+]++[[package]]+name = "ipnet"+version = "2.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"++[[package]]+name = "iri-string"+version = "0.7.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a"+dependencies = [+ "memchr",+ "serde",+]++[[package]]+name = "is-docker"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"+dependencies = [+ "once_cell",+]++[[package]]+name = "is-wsl"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"+dependencies = [+ "is-docker",+ "once_cell",+]++[[package]]+name = "itoa"+version = "1.0.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"++[[package]]+name = "javascriptcore-rs"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"+dependencies = [+ "bitflags 1.3.2",+ "glib",+ "javascriptcore-rs-sys",+]++[[package]]+name = "javascriptcore-rs-sys"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "jni"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"+dependencies = [+ "cesu8",+ "cfg-if",+ "combine",+ "jni-sys",+ "log",+ "thiserror 1.0.69",+ "walkdir",+ "windows-sys 0.45.0",+]++[[package]]+name = "jni-sys"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"++[[package]]+name = "js-sys"+version = "0.3.85"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3"+dependencies = [+ "once_cell",+ "wasm-bindgen",+]++[[package]]+name = "json-patch"+version = "3.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08"+dependencies = [+ "jsonptr",+ "serde",+ "serde_json",+ "thiserror 1.0.69",+]++[[package]]+name = "jsonptr"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70"+dependencies = [+ "serde",+ "serde_json",+]++[[package]]+name = "keyboard-types"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"+dependencies = [+ "bitflags 2.10.0",+ "serde",+ "unicode-segmentation",+]++[[package]]+name = "kqueue"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a"+dependencies = [+ "kqueue-sys",+ "libc",+]++[[package]]+name = "kqueue-sys"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b"+dependencies = [+ "bitflags 1.3.2",+ "libc",+]++[[package]]+name = "kuchikiki"+version = "0.8.8-speedreader"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02cb977175687f33fa4afa0c95c112b987ea1443e5a51c8f8ff27dc618270cc2"+dependencies = [+ "cssparser",+ "html5ever",+ "indexmap 2.13.0",+ "selectors",+]++[[package]]+name = "lazy_static"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"++[[package]]+name = "libappindicator"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a"+dependencies = [+ "glib",+ "gtk",+ "gtk-sys",+ "libappindicator-sys",+ "log",+]++[[package]]+name = "libappindicator-sys"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf"+dependencies = [+ "gtk-sys",+ "libloading",+ "once_cell",+]++[[package]]+name = "libc"+version = "0.2.180"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc"++[[package]]+name = "libloading"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"+dependencies = [+ "cfg-if",+ "winapi",+]++[[package]]+name = "libredox"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616"+dependencies = [+ "bitflags 2.10.0",+ "libc",+ "redox_syscall 0.7.0",+]++[[package]]+name = "linux-raw-sys"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"++[[package]]+name = "litemap"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"++[[package]]+name = "mac"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"++[[package]]+name = "markup5ever"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7a7213d12e1864c0f002f52c2923d4556935a43dec5e71355c2760e0f6e7a18"+dependencies = [+ "log",+ "phf 0.11.3",+ "phf_codegen 0.11.3",+ "string_cache",+ "string_cache_codegen",+ "tendril",+]++[[package]]+name = "match_token"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88a9689d8d44bf9964484516275f5cd4c9b59457a6940c1d5d0ecbb94510a36b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "matches"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5"++[[package]]+name = "memchr"+version = "2.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"++[[package]]+name = "memoffset"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"+dependencies = [+ "autocfg",+]++[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "minisign-verify"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e856fdd13623a2f5f2f54676a4ee49502a96a80ef4a62bcedd23d52427c44d43"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "mio"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"+dependencies = [+ "libc",+ "log",+ "wasi 0.11.1+wasi-snapshot-preview1",+ "windows-sys 0.61.2",+]++[[package]]+name = "muda"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01c1738382f66ed56b3b9c8119e794a2e23148ac8ea214eda86622d4cb9d415a"+dependencies = [+ "crossbeam-channel",+ "dpi",+ "gtk",+ "keyboard-types",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "once_cell",+ "png",+ "serde",+ "thiserror 2.0.18",+ "windows-sys 0.60.2",+]++[[package]]+name = "ndk"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"+dependencies = [+ "bitflags 2.10.0",+ "jni-sys",+ "log",+ "ndk-sys",+ "num_enum",+ "raw-window-handle",+ "thiserror 1.0.69",+]++[[package]]+name = "ndk-context"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"++[[package]]+name = "ndk-sys"+version = "0.6.0+11769913"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"+dependencies = [+ "jni-sys",+]++[[package]]+name = "new_debug_unreachable"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"++[[package]]+name = "nodrop"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"++[[package]]+name = "notify"+version = "8.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"+dependencies = [+ "bitflags 2.10.0",+ "fsevent-sys",+ "inotify",+ "kqueue",+ "libc",+ "log",+ "mio",+ "notify-types",+ "walkdir",+ "windows-sys 0.60.2",+]++[[package]]+name = "notify-debouncer-full"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "375bd3a138be7bfeff3480e4a623df4cbfb55b79df617c055cd810ba466fa078"+dependencies = [+ "file-id",+ "log",+ "notify",+ "notify-types",+ "walkdir",+]++[[package]]+name = "notify-types"+version = "2.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"+dependencies = [+ "bitflags 2.10.0",+ "serde",+]++[[package]]+name = "num-conv"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050"++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "num_enum"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1207a7e20ad57b847bbddc6776b968420d38292bbfe2089accff5e19e82454c"+dependencies = [+ "num_enum_derive",+ "rustversion",+]++[[package]]+name = "num_enum_derive"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff32365de1b6743cb203b710788263c44a03de03802daf96092f2da4fe6ba4d7"+dependencies = [+ "proc-macro-crate 3.4.0",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "objc2"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7c2599ce0ec54857b29ce62166b0ed9b4f6f1a70ccc9a71165b6154caca8c05"+dependencies = [+ "objc2-encode",+ "objc2-exception-helper",+]++[[package]]+name = "objc2-app-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"+dependencies = [+ "bitflags 2.10.0",+ "block2",+ "libc",+ "objc2",+ "objc2-cloud-kit",+ "objc2-core-data",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-image",+ "objc2-core-text",+ "objc2-core-video",+ "objc2-foundation",+ "objc2-quartz-core",+]++[[package]]+name = "objc2-cloud-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"+dependencies = [+ "bitflags 2.10.0",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-data"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"+dependencies = [+ "bitflags 2.10.0",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.10.0",+ "dispatch2",+ "objc2",+]++[[package]]+name = "objc2-core-graphics"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"+dependencies = [+ "bitflags 2.10.0",+ "dispatch2",+ "objc2",+ "objc2-core-foundation",+ "objc2-io-surface",+]++[[package]]+name = "objc2-core-image"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-text"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"+dependencies = [+ "bitflags 2.10.0",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[package]]+name = "objc2-core-video"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"+dependencies = [+ "bitflags 2.10.0",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-io-surface",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-exception-helper"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a"+dependencies = [+ "cc",+]++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.10.0",+ "block2",+ "libc",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-io-surface"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"+dependencies = [+ "bitflags 2.10.0",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-javascript-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a1e6550c4caed348956ce3370c9ffeca70bb1dbed4fa96112e7c6170e074586"+dependencies = [+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-osa-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"+dependencies = [+ "bitflags 2.10.0",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+]++[[package]]+name = "objc2-quartz-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"+dependencies = [+ "bitflags 2.10.0",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "objc2-security"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a"+dependencies = [+ "bitflags 2.10.0",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-ui-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"+dependencies = [+ "bitflags 2.10.0",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "objc2-web-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"+dependencies = [+ "bitflags 2.10.0",+ "block2",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-javascript-core",+ "objc2-security",+]++[[package]]+name = "once_cell"+version = "1.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"++[[package]]+name = "open"+version = "5.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43bb73a7fa3799b198970490a51174027ba0d4ec504b03cd08caf513d40024bc"+dependencies = [+ "dunce",+ "is-wsl",+ "libc",+ "pathdiff",+]++[[package]]+name = "openssl-probe"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"++[[package]]+name = "option-ext"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"++[[package]]+name = "os_pipe"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "osakit"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"+dependencies = [+ "objc2",+ "objc2-foundation",+ "objc2-osa-kit",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+]++[[package]]+name = "pango"+version = "0.18.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"+dependencies = [+ "gio",+ "glib",+ "libc",+ "once_cell",+ "pango-sys",+]++[[package]]+name = "pango-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall 0.5.18",+ "smallvec",+ "windows-link 0.2.1",+]++[[package]]+name = "pathdiff"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "phf"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12"+dependencies = [+ "phf_shared 0.8.0",+]++[[package]]+name = "phf"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259"+dependencies = [+ "phf_macros 0.10.0",+ "phf_shared 0.10.0",+ "proc-macro-hack",+]++[[package]]+name = "phf"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"+dependencies = [+ "phf_macros 0.11.3",+ "phf_shared 0.11.3",+]++[[package]]+name = "phf_codegen"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cbffee61585b0411840d3ece935cce9cb6321f01c45477d30066498cd5e1a815"+dependencies = [+ "phf_generator 0.8.0",+ "phf_shared 0.8.0",+]++[[package]]+name = "phf_codegen"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a"+dependencies = [+ "phf_generator 0.11.3",+ "phf_shared 0.11.3",+]++[[package]]+name = "phf_generator"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "17367f0cc86f2d25802b2c26ee58a7b23faeccf78a396094c13dced0d0182526"+dependencies = [+ "phf_shared 0.8.0",+ "rand 0.7.3",+]++[[package]]+name = "phf_generator"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6"+dependencies = [+ "phf_shared 0.10.0",+ "rand 0.8.5",+]++[[package]]+name = "phf_generator"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"+dependencies = [+ "phf_shared 0.11.3",+ "rand 0.8.5",+]++[[package]]+name = "phf_macros"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "58fdf3184dd560f160dd73922bea2d5cd6e8f064bf4b13110abd81b03697b4e0"+dependencies = [+ "phf_generator 0.10.0",+ "phf_shared 0.10.0",+ "proc-macro-hack",+ "proc-macro2",+ "quote",+ "syn 1.0.109",+]++[[package]]+name = "phf_macros"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216"+dependencies = [+ "phf_generator 0.11.3",+ "phf_shared 0.11.3",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "phf_shared"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c00cf8b9eafe68dde5e9eaa2cef8ee84a9336a47d566ec55ca16589633b65af7"+dependencies = [+ "siphasher 0.3.11",+]++[[package]]+name = "phf_shared"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096"+dependencies = [+ "siphasher 0.3.11",+]++[[package]]+name = "phf_shared"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"+dependencies = [+ "siphasher 1.0.2",+]++[[package]]+name = "pin-project-lite"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"++[[package]]+name = "pin-utils"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"++[[package]]+name = "pkg-config"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"++[[package]]+name = "plist"+version = "1.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07"+dependencies = [+ "base64 0.22.1",+ "indexmap 2.13.0",+ "quick-xml",+ "serde",+ "time",+]++[[package]]+name = "png"+version = "0.17.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"+dependencies = [+ "bitflags 1.3.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide",+]++[[package]]+name = "potential_utf"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77"+dependencies = [+ "zerovec",+]++[[package]]+name = "powerfmt"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "precomputed-hash"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"++[[package]]+name = "proc-macro-crate"+version = "1.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919"+dependencies = [+ "once_cell",+ "toml_edit 0.19.15",+]++[[package]]+name = "proc-macro-crate"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"+dependencies = [+ "toml_datetime 0.6.3",+ "toml_edit 0.20.2",+]++[[package]]+name = "proc-macro-crate"+version = "3.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983"+dependencies = [+ "toml_edit 0.23.10+spec-1.0.0",+]++[[package]]+name = "proc-macro-error"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"+dependencies = [+ "proc-macro-error-attr",+ "proc-macro2",+ "quote",+ "syn 1.0.109",+ "version_check",+]++[[package]]+name = "proc-macro-error-attr"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"+dependencies = [+ "proc-macro2",+ "quote",+ "version_check",+]++[[package]]+name = "proc-macro-hack"+version = "0.5.20+deprecated"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quick-xml"+version = "0.38.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"+dependencies = [+ "memchr",+]++[[package]]+name = "quote"+version = "1.0.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "rand"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"+dependencies = [+ "getrandom 0.1.16",+ "libc",+ "rand_chacha 0.2.2",+ "rand_core 0.5.1",+ "rand_hc",+ "rand_pcg",+]++[[package]]+name = "rand"+version = "0.8.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"+dependencies = [+ "libc",+ "rand_chacha 0.3.1",+ "rand_core 0.6.4",+]++[[package]]+name = "rand_chacha"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"+dependencies = [+ "ppv-lite86",+ "rand_core 0.5.1",+]++[[package]]+name = "rand_chacha"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"+dependencies = [+ "ppv-lite86",+ "rand_core 0.6.4",+]++[[package]]+name = "rand_core"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"+dependencies = [+ "getrandom 0.1.16",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom 0.2.17",+]++[[package]]+name = "rand_hc"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"+dependencies = [+ "rand_core 0.5.1",+]++[[package]]+name = "rand_pcg"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "16abd0c1b639e9eb4d7c50c0b8100b0d0f849be2349829c740fe8e6eb4816429"+dependencies = [+ "rand_core 0.5.1",+]++[[package]]+name = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.10.0",+]++[[package]]+name = "redox_syscall"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49f3fe0889e69e2ae9e41f4d6c4c0181701d00e4697b356fb1f74173a5e0ee27"+dependencies = [+ "bitflags 2.10.0",+]++[[package]]+name = "redox_users"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"+dependencies = [+ "getrandom 0.2.17",+ "libredox",+ "thiserror 2.0.18",+]++[[package]]+name = "ref-cast"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "regex"+version = "1.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c"++[[package]]+name = "reqwest"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04e9018c9d814e5f30cc16a0f03271aeab3571e609612d9fe78c1aa8d11c2f62"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-core",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "rustls",+ "rustls-pki-types",+ "rustls-platform-verifier",+ "serde",+ "serde_json",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tokio-util",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-streams",+ "web-sys",+]++[[package]]+name = "rfd"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"+dependencies = [+ "block2",+ "dispatch2",+ "glib-sys",+ "gobject-sys",+ "gtk-sys",+ "js-sys",+ "log",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "raw-window-handle",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "windows-sys 0.60.2",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "rustix"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34"+dependencies = [+ "bitflags 2.10.0",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"+dependencies = [+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-native-certs"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"+dependencies = [+ "openssl-probe",+ "rustls-pki-types",+ "schannel",+ "security-framework",+]++[[package]]+name = "rustls-pki-types"+version = "1.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"+dependencies = [+ "zeroize",+]++[[package]]+name = "rustls-platform-verifier"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784"+dependencies = [+ "core-foundation",+ "core-foundation-sys",+ "jni",+ "log",+ "once_cell",+ "rustls",+ "rustls-native-certs",+ "rustls-platform-verifier-android",+ "rustls-webpki",+ "security-framework",+ "security-framework-sys",+ "webpki-root-certs",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls-platform-verifier-android"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"++[[package]]+name = "rustls-webpki"+version = "0.103.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "schannel"+version = "0.1.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "schemars"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615"+dependencies = [+ "dyn-clone",+ "indexmap 1.9.3",+ "schemars_derive",+ "serde",+ "serde_json",+ "url",+ "uuid",+]++[[package]]+name = "schemars"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars_derive"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 2.0.114",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "security-framework"+version = "3.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3297343eaf830f66ede390ea39da1d462b6b0c1b000f420d0a83f898bbbe6ef"+dependencies = [+ "bitflags 2.10.0",+ "core-foundation",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "selectors"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c37578180969d00692904465fb7f6b3d50b9a2b952b87c23d0e2e5cb5013416"+dependencies = [+ "bitflags 1.3.2",+ "cssparser",+ "derive_more",+ "fxhash",+ "log",+ "phf 0.8.0",+ "phf_codegen 0.8.0",+ "precomputed-hash",+ "servo_arc",+ "smallvec",+]++[[package]]+name = "semver"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"+dependencies = [+ "serde",+ "serde_core",+]++[[package]]+name = "serde"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde-untagged"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058"+dependencies = [+ "erased-serde",+ "serde",+ "serde_core",+ "typeid",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "serde_derive_internals"+version = "0.29.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "serde_json"+version = "1.0.149"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_repr"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "serde_spanned"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"+dependencies = [+ "serde",+]++[[package]]+name = "serde_spanned"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776"+dependencies = [+ "serde_core",+]++[[package]]+name = "serde_with"+version = "3.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fa237f2807440d238e0364a218270b98f767a00d3dada77b1c53ae88940e2e7"+dependencies = [+ "base64 0.22.1",+ "chrono",+ "hex",+ "indexmap 1.9.3",+ "indexmap 2.13.0",+ "schemars 0.9.0",+ "schemars 1.2.1",+ "serde_core",+ "serde_json",+ "serde_with_macros",+ "time",+]++[[package]]+name = "serde_with_macros"+version = "3.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52a8e3ca0ca629121f70ab50f95249e5a6f925cc0f6ffe8256c45b728875706c"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "serialize-to-javascript"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5"+dependencies = [+ "serde",+ "serde_json",+ "serialize-to-javascript-impl",+]++[[package]]+name = "serialize-to-javascript-impl"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "servo_arc"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d52aa42f8fdf0fed91e5ce7f23d8138441002fa31dca008acf47e6fd4721f741"+dependencies = [+ "nodrop",+ "stable_deref_trait",+]++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]]+name = "shared_child"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7"+dependencies = [+ "libc",+ "sigchld",+ "windows-sys 0.60.2",+]++[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"++[[package]]+name = "sigchld"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1"+dependencies = [+ "libc",+ "os_pipe",+ "signal-hook",+]++[[package]]+name = "signal-hook"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"+dependencies = [+ "libc",+ "signal-hook-registry",+]++[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]++[[package]]+name = "simd-adler32"+version = "0.3.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"++[[package]]+name = "siphasher"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"++[[package]]+name = "siphasher"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"++[[package]]+name = "socket2"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0"+dependencies = [+ "libc",+ "windows-sys 0.60.2",+]++[[package]]+name = "softbuffer"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3"+dependencies = [+ "bytemuck",+ "js-sys",+ "ndk",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation",+ "objc2-quartz-core",+ "raw-window-handle",+ "redox_syscall 0.5.18",+ "tracing",+ "wasm-bindgen",+ "web-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "soup3"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"+dependencies = [+ "futures-channel",+ "gio",+ "glib",+ "libc",+ "soup3-sys",+]++[[package]]+name = "soup3-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"+dependencies = [+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "string_cache"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f"+dependencies = [+ "new_debug_unreachable",+ "parking_lot",+ "phf_shared 0.11.3",+ "precomputed-hash",+ "serde",+]++[[package]]+name = "string_cache_codegen"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0"+dependencies = [+ "phf_generator 0.11.3",+ "phf_shared 0.11.3",+ "proc-macro2",+ "quote",+]++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "swift-rs"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4057c98e2e852d51fdcfca832aac7b571f6b351ad159f9eda5db1655f8d0c4d7"+dependencies = [+ "base64 0.21.7",+ "serde",+ "serde_json",+]++[[package]]+name = "syn"+version = "1.0.109"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "2.0.114"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+dependencies = [+ "futures-core",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "system-deps"+version = "6.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"+dependencies = [+ "cfg-expr",+ "heck 0.5.0",+ "pkg-config",+ "toml 0.8.2",+ "version-compare",+]++[[package]]+name = "tao"+version = "0.34.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3a753bdc39c07b192151523a3f77cd0394aa75413802c883a0f6f6a0e5ee2e7"+dependencies = [+ "bitflags 2.10.0",+ "block2",+ "core-foundation",+ "core-graphics",+ "crossbeam-channel",+ "dispatch",+ "dlopen2",+ "dpi",+ "gdkwayland-sys",+ "gdkx11-sys",+ "gtk",+ "jni",+ "lazy_static",+ "libc",+ "log",+ "ndk",+ "ndk-context",+ "ndk-sys",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "once_cell",+ "parking_lot",+ "raw-window-handle",+ "scopeguard",+ "tao-macros",+ "unicode-segmentation",+ "url",+ "windows",+ "windows-core 0.61.2",+ "windows-version",+ "x11-dl",+]++[[package]]+name = "tao-macros"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "tar"+version = "0.4.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a"+dependencies = [+ "filetime",+ "libc",+ "xattr",+]++[[package]]+name = "target-lexicon"+version = "0.12.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"++[[package]]+name = "tauri"+version = "2.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1025aa560c1eaa14ef96de5540cbe13ed6be1933ebe4398338c96bc370b807c6"+dependencies = [+ "anyhow",+ "bytes",+ "cookie",+ "dirs",+ "dunce",+ "embed_plist",+ "getrandom 0.3.4",+ "glob",+ "gtk",+ "heck 0.5.0",+ "http",+ "http-range",+ "jni",+ "libc",+ "log",+ "mime",+ "muda",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "objc2-ui-kit",+ "objc2-web-kit",+ "percent-encoding",+ "plist",+ "raw-window-handle",+ "reqwest",+ "serde",+ "serde_json",+ "serde_repr",+ "serialize-to-javascript",+ "swift-rs",+ "tauri-build",+ "tauri-macros",+ "tauri-runtime",+ "tauri-runtime-wry",+ "tauri-utils",+ "thiserror 2.0.18",+ "tokio",+ "tray-icon",+ "url",+ "webkit2gtk",+ "webview2-com",+ "window-vibrancy",+ "windows",+]++[[package]]+name = "tauri-build"+version = "2.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76809f63061c8b25537b87f46b8733b31397cf419706dc874e1602be6479ba90"+dependencies = [+ "anyhow",+ "cargo_toml",+ "dirs",+ "glob",+ "heck 0.5.0",+ "json-patch",+ "schemars 0.8.22",+ "semver",+ "serde",+ "serde_json",+ "tauri-utils",+ "tauri-winres",+ "toml 0.9.11+spec-1.1.0",+ "walkdir",+]++[[package]]+name = "tauri-codegen"+version = "2.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b2ebe49d690ccaea93aa81fff99277d4f445968f085ba13be67859151e9e4b8"+dependencies = [+ "base64 0.22.1",+ "brotli",+ "ico",+ "json-patch",+ "plist",+ "png",+ "proc-macro2",+ "quote",+ "semver",+ "serde",+ "serde_json",+ "sha2",+ "syn 2.0.114",+ "tauri-utils",+ "thiserror 2.0.18",+ "time",+ "url",+ "uuid",+ "walkdir",+]++[[package]]+name = "tauri-macros"+version = "2.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1119f651b0187c686c0fc72c66bba311e560e1b5f61869086ce788d43be6cf41"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+ "tauri-codegen",+ "tauri-utils",+]++[[package]]+name = "tauri-plugin"+version = "2.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "692a77abd8b8773e107a42ec0e05b767b8d2b7ece76ab36c6c3947e34df9f53f"+dependencies = [+ "anyhow",+ "glob",+ "plist",+ "schemars 0.8.22",+ "serde",+ "serde_json",+ "tauri-utils",+ "toml 0.9.11+spec-1.1.0",+ "walkdir",+]++[[package]]+name = "tauri-plugin-dialog"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9204b425d9be8d12aa60c2a83a289cf7d1caae40f57f336ed1155b3a5c0e359b"+dependencies = [+ "log",+ "raw-window-handle",+ "rfd",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "tauri-plugin-fs",+ "thiserror 2.0.18",+ "url",+]++[[package]]+name = "tauri-plugin-fs"+version = "2.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed390cc669f937afeb8b28032ce837bac8ea023d975a2e207375ec05afaf1804"+dependencies = [+ "anyhow",+ "dunce",+ "glob",+ "notify",+ "notify-debouncer-full",+ "percent-encoding",+ "schemars 0.8.22",+ "serde",+ "serde_json",+ "serde_repr",+ "tauri",+ "tauri-plugin",+ "tauri-utils",+ "thiserror 2.0.18",+ "toml 0.9.11+spec-1.1.0",+ "url",+]++[[package]]+name = "tauri-plugin-process"+version = "2.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55511a7bf6cd70c8767b02c97bf8134fa434daf3926cfc1be0a0f94132d165a"+dependencies = [+ "tauri",+ "tauri-plugin",+]++[[package]]+name = "tauri-plugin-shell"+version = "2.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8457dbf9e2bab1edd8df22bb2c20857a59a9868e79cb3eac5ed639eec4d0c73b"+dependencies = [+ "encoding_rs",+ "log",+ "open",+ "os_pipe",+ "regex",+ "schemars 0.8.22",+ "serde",+ "serde_json",+ "shared_child",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.18",+ "tokio",+]++[[package]]+name = "tauri-plugin-updater"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3fe8e9bebd88fc222938ffdfbdcfa0307081423bd01e3252fc337d8bde81fc61"+dependencies = [+ "base64 0.22.1",+ "dirs",+ "flate2",+ "futures-util",+ "http",+ "infer",+ "log",+ "minisign-verify",+ "osakit",+ "percent-encoding",+ "reqwest",+ "rustls",+ "semver",+ "serde",+ "serde_json",+ "tar",+ "tauri",+ "tauri-plugin",+ "tempfile",+ "thiserror 2.0.18",+ "time",+ "tokio",+ "url",+ "windows-sys 0.60.2",+ "zip",+]++[[package]]+name = "tauri-runtime"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b885ffeac82b00f1f6fd292b6e5aabfa7435d537cef57d11e38a489956535651"+dependencies = [+ "cookie",+ "dpi",+ "gtk",+ "http",+ "jni",+ "objc2",+ "objc2-ui-kit",+ "objc2-web-kit",+ "raw-window-handle",+ "serde",+ "serde_json",+ "tauri-utils",+ "thiserror 2.0.18",+ "url",+ "webkit2gtk",+ "webview2-com",+ "windows",+]++[[package]]+name = "tauri-runtime-wry"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5204682391625e867d16584fedc83fc292fb998814c9f7918605c789cd876314"+dependencies = [+ "gtk",+ "http",+ "jni",+ "log",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "once_cell",+ "percent-encoding",+ "raw-window-handle",+ "softbuffer",+ "tao",+ "tauri-runtime",+ "tauri-utils",+ "url",+ "webkit2gtk",+ "webview2-com",+ "windows",+ "wry",+]++[[package]]+name = "tauri-utils"+version = "2.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fcd169fccdff05eff2c1033210b9b94acd07a47e6fa9a3431cf09cfd4f01c87e"+dependencies = [+ "anyhow",+ "brotli",+ "cargo_metadata",+ "ctor",+ "dunce",+ "glob",+ "html5ever",+ "http",+ "infer",+ "json-patch",+ "kuchikiki",+ "log",+ "memchr",+ "phf 0.11.3",+ "proc-macro2",+ "quote",+ "regex",+ "schemars 0.8.22",+ "semver",+ "serde",+ "serde-untagged",+ "serde_json",+ "serde_with",+ "swift-rs",+ "thiserror 2.0.18",+ "toml 0.9.11+spec-1.1.0",+ "url",+ "urlpattern",+ "uuid",+ "walkdir",+]++[[package]]+name = "tauri-winres"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1087b111fe2b005e42dbdc1990fc18593234238d47453b0c99b7de1c9ab2c1e0"+dependencies = [+ "dunce",+ "embed-resource",+ "toml 0.9.11+spec-1.1.0",+]++[[package]]+name = "tempfile"+version = "3.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c"+dependencies = [+ "fastrand",+ "getrandom 0.3.4",+ "once_cell",+ "rustix",+ "windows-sys 0.61.2",+]++[[package]]+name = "tendril"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0"+dependencies = [+ "futf",+ "mac",+ "utf-8",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl 2.0.18",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "time"+version = "0.3.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9da98b7d9b7dad93488a84b8248efc35352b0b2657397d4167e7ad67e5d535e5"+dependencies = [+ "deranged",+ "itoa",+ "num-conv",+ "powerfmt",+ "serde_core",+ "time-core",+ "time-macros",+]++[[package]]+name = "time-core"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"++[[package]]+name = "time-macros"+version = "0.2.26"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78cc610bac2dcee56805c99642447d4c5dbde4d01f752ffea0199aee1f601dc4"+dependencies = [+ "num-conv",+ "time-core",+]++[[package]]+name = "tiny_http"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"+dependencies = [+ "ascii",+ "chunked_transfer",+ "httpdate",+ "log",+]++[[package]]+name = "tinystr"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tokio"+version = "1.49.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "pin-project-lite",+ "signal-hook-registry",+ "socket2",+ "tokio-macros",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-macros"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "tokio-rustls"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-util"+version = "0.7.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "toml"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"+dependencies = [+ "serde",+ "serde_spanned 0.6.9",+ "toml_datetime 0.6.3",+ "toml_edit 0.20.2",+]++[[package]]+name = "toml"+version = "0.9.11+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3afc9a848309fe1aaffaed6e1546a7a14de1f935dc9d89d32afd9a44bab7c46"+dependencies = [+ "indexmap 2.13.0",+ "serde_core",+ "serde_spanned 1.0.4",+ "toml_datetime 0.7.5+spec-1.1.0",+ "toml_parser",+ "toml_writer",+ "winnow 0.7.14",+]++[[package]]+name = "toml_datetime"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"+dependencies = [+ "serde",+]++[[package]]+name = "toml_datetime"+version = "0.7.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.19.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"+dependencies = [+ "indexmap 2.13.0",+ "toml_datetime 0.6.3",+ "winnow 0.5.40",+]++[[package]]+name = "toml_edit"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"+dependencies = [+ "indexmap 2.13.0",+ "serde",+ "serde_spanned 0.6.9",+ "toml_datetime 0.6.3",+ "winnow 0.5.40",+]++[[package]]+name = "toml_edit"+version = "0.23.10+spec-1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "84c8b9f757e028cee9fa244aea147aab2a9ec09d5325a9b01e0a49730c2b5269"+dependencies = [+ "indexmap 2.13.0",+ "toml_datetime 0.7.5+spec-1.1.0",+ "toml_parser",+ "winnow 0.7.14",+]++[[package]]+name = "toml_parser"+version = "1.0.6+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3198b4b0a8e11f09dd03e133c0280504d0801269e9afa46362ffde1cbeebf44"+dependencies = [+ "winnow 0.7.14",+]++[[package]]+name = "toml_writer"+version = "1.0.6+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607"++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+]++[[package]]+name = "tower-http"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"+dependencies = [+ "bitflags 2.10.0",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "iri-string",+ "pin-project-lite",+ "tower",+ "tower-layer",+ "tower-service",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-core",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]++[[package]]+name = "tray-icon"+version = "0.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5e85aa143ceb072062fc4d6356c1b520a51d636e7bc8e77ec94be3608e5e80c"+dependencies = [+ "crossbeam-channel",+ "dirs",+ "libappindicator",+ "muda",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation",+ "once_cell",+ "png",+ "serde",+ "thiserror 2.0.18",+ "windows-sys 0.60.2",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "typeid"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"++[[package]]+name = "typenum"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"++[[package]]+name = "unic-char-property"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221"+dependencies = [+ "unic-char-range",+]++[[package]]+name = "unic-char-range"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc"++[[package]]+name = "unic-common"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc"++[[package]]+name = "unic-ucd-ident"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987"+dependencies = [+ "unic-char-property",+ "unic-char-range",+ "unic-ucd-version",+]++[[package]]+name = "unic-ucd-version"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4"+dependencies = [+ "unic-common",+]++[[package]]+name = "unicode-ident"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"++[[package]]+name = "unicode-segmentation"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+ "serde_derive",+]++[[package]]+name = "urlencoding"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"++[[package]]+name = "urlpattern"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d"+dependencies = [+ "regex",+ "serde",+ "unic-ucd-ident",+ "url",+]++[[package]]+name = "utf-8"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "uuid"+version = "1.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee48d38b119b0cd71fe4141b30f5ba9c7c5d9f4e7a3a8b4a674e4b6ef789976f"+dependencies = [+ "getrandom 0.3.4",+ "js-sys",+ "serde_core",+ "wasm-bindgen",+]++[[package]]+name = "version-compare"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "vswhom"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"+dependencies = [+ "libc",+ "vswhom-sys",+]++[[package]]+name = "vswhom-sys"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "want"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"+dependencies = [+ "try-lock",+]++[[package]]+name = "wasi"+version = "0.9.0+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasip2"+version = "1.0.2+wasi-0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.108"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.58"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70a6e77fd0ae8029c9ea0063f87c46fde723e7d887703d74ad2616d792e51e6f"+dependencies = [+ "cfg-if",+ "futures-util",+ "js-sys",+ "once_cell",+ "wasm-bindgen",+ "web-sys",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.108"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.108"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 2.0.114",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.108"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "wasm-streams"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"+dependencies = [+ "futures-util",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "web-sys"+version = "0.3.85"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "webkit2gtk"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793"+dependencies = [+ "bitflags 1.3.2",+ "cairo-rs",+ "gdk",+ "gdk-sys",+ "gio",+ "gio-sys",+ "glib",+ "glib-sys",+ "gobject-sys",+ "gtk",+ "gtk-sys",+ "javascriptcore-rs",+ "libc",+ "once_cell",+ "soup3",+ "webkit2gtk-sys",+]++[[package]]+name = "webkit2gtk-sys"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5"+dependencies = [+ "bitflags 1.3.2",+ "cairo-sys-rs",+ "gdk-sys",+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "gtk-sys",+ "javascriptcore-rs-sys",+ "libc",+ "pkg-config",+ "soup3-sys",+ "system-deps",+]++[[package]]+name = "webpki-root-certs"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "804f18a4ac2676ffb4e8b5b5fa9ae38af06df08162314f96a68d2a363e21a8ca"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "webview2-com"+version = "0.38.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"+dependencies = [+ "webview2-com-macros",+ "webview2-com-sys",+ "windows",+ "windows-core 0.61.2",+ "windows-implement",+ "windows-interface",+]++[[package]]+name = "webview2-com-macros"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "webview2-com-sys"+version = "0.38.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"+dependencies = [+ "thiserror 2.0.18",+ "windows",+ "windows-core 0.61.2",+]++[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"++[[package]]+name = "window-vibrancy"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c"+dependencies = [+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "raw-window-handle",+ "windows-sys 0.59.0",+ "windows-version",+]++[[package]]+name = "windows"+version = "0.61.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"+dependencies = [+ "windows-collections",+ "windows-core 0.61.2",+ "windows-future",+ "windows-link 0.1.3",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"+dependencies = [+ "windows-core 0.61.2",+]++[[package]]+name = "windows-core"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link 0.1.3",+ "windows-result 0.3.4",+ "windows-strings 0.4.2",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link 0.2.1",+ "windows-result 0.4.1",+ "windows-strings 0.5.1",+]++[[package]]+name = "windows-future"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"+dependencies = [+ "windows-core 0.61.2",+ "windows-link 0.1.3",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "windows-link"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"+dependencies = [+ "windows-core 0.61.2",+ "windows-link 0.1.3",+]++[[package]]+name = "windows-result"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-strings"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets 0.42.2",+]++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"+dependencies = [+ "windows-targets 0.53.5",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm 0.42.2",+ "windows_aarch64_msvc 0.42.2",+ "windows_i686_gnu 0.42.2",+ "windows_i686_msvc 0.42.2",+ "windows_x86_64_gnu 0.42.2",+ "windows_x86_64_gnullvm 0.42.2",+ "windows_x86_64_msvc 0.42.2",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm 0.52.6",+ "windows_aarch64_msvc 0.52.6",+ "windows_i686_gnu 0.52.6",+ "windows_i686_gnullvm 0.52.6",+ "windows_i686_msvc 0.52.6",+ "windows_x86_64_gnu 0.52.6",+ "windows_x86_64_gnullvm 0.52.6",+ "windows_x86_64_msvc 0.52.6",+]++[[package]]+name = "windows-targets"+version = "0.53.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"+dependencies = [+ "windows-link 0.2.1",+ "windows_aarch64_gnullvm 0.53.1",+ "windows_aarch64_msvc 0.53.1",+ "windows_i686_gnu 0.53.1",+ "windows_i686_gnullvm 0.53.1",+ "windows_i686_msvc 0.53.1",+ "windows_x86_64_gnu 0.53.1",+ "windows_x86_64_gnullvm 0.53.1",+ "windows_x86_64_msvc 0.53.1",+]++[[package]]+name = "windows-threading"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-version"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_aarch64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_i686_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "windows_x86_64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"++[[package]]+name = "winnow"+version = "0.5.40"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876"+dependencies = [+ "memchr",+]++[[package]]+name = "winnow"+version = "0.7.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"+dependencies = [+ "memchr",+]++[[package]]+name = "winreg"+version = "0.55.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"+dependencies = [+ "cfg-if",+ "windows-sys 0.59.0",+]++[[package]]+name = "wit-bindgen"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"++[[package]]+name = "writeable"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"++[[package]]+name = "wry"+version = "0.54.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ed1a195b0375491dd15a7066a10251be217ce743cf4bbbbdcf5391d6473bee0"+dependencies = [+ "base64 0.22.1",+ "block2",+ "cookie",+ "crossbeam-channel",+ "dirs",+ "dpi",+ "dunce",+ "gdkx11",+ "gtk",+ "html5ever",+ "http",+ "javascriptcore-rs",+ "jni",+ "kuchikiki",+ "libc",+ "ndk",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-ui-kit",+ "objc2-web-kit",+ "once_cell",+ "percent-encoding",+ "raw-window-handle",+ "sha2",+ "soup3",+ "tao-macros",+ "thiserror 2.0.18",+ "url",+ "webkit2gtk",+ "webkit2gtk-sys",+ "webview2-com",+ "windows",+ "windows-core 0.61.2",+ "windows-version",+ "x11-dl",+]++[[package]]+name = "x11"+version = "2.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e"+dependencies = [+ "libc",+ "pkg-config",+]++[[package]]+name = "x11-dl"+version = "2.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"+dependencies = [+ "libc",+ "once_cell",+ "pkg-config",+]++[[package]]+name = "xattr"+version = "1.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"+dependencies = [+ "libc",+ "rustix",+]++[[package]]+name = "yoke"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+ "synstructure",+]++[[package]]+name = "zerocopy"+version = "0.8.38"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57cf3aa6855b23711ee9852dfc97dfaa51c45feaba5b645d0c777414d494a961"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.38"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a616990af1a287837c4fe6596ad77ef57948f787e46ce28e166facc0cc1cb75"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "zerofrom"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"++[[package]]+name = "zerotrie"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "zip"+version = "4.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"+dependencies = [+ "arbitrary",+ "crc32fast",+ "indexmap 2.13.0",+ "memchr",+]++[[package]]+name = "zmij"+version = "1.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ff05f8caa9038894637571ae6b9e29466c1f4f829d26c9b28f869a29cbe3445"diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex d2d579b73..cf0b411dc 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -83,98 +83,29 @@ fn open_folder(path: String) -> Result<(), String> {}#[tauri::command]-fn get_engine_js() -> Vec<u8> {- embedded_assets::ENGINE_JS.to_vec()-}--#[tauri::command]-fn get_engine_wasm() -> Vec<u8> {- embedded_assets::ENGINE_WASM.to_vec()-}--#[tauri::command]-fn get_engine_single_js() -> Vec<u8> {- embedded_assets::ENGINE_SINGLE_JS.to_vec()-}--#[tauri::command]-fn get_engine_wxgame_js() -> Vec<u8> {- embedded_assets::ENGINE_WXGAME_JS.to_vec()-}--#[tauri::command]-fn get_engine_wxgame_wasm() -> Vec<u8> {- embedded_assets::ENGINE_WXGAME_WASM.to_vec()-}--#[tauri::command]-fn get_sdk_wechat_js() -> Vec<u8> {- embedded_assets::SDK_WECHAT_JS.to_vec()-}--#[tauri::command]-fn get_sdk_esm_js() -> Vec<u8> {- embedded_assets::SDK_ESM_JS.to_vec()-}--#[tauri::command]-fn get_sdk_esm_dts() -> Vec<u8> {- embedded_assets::SDK_ESM_DTS.to_vec()-}--#[tauri::command]-fn get_sdk_wasm_js() -> Vec<u8> {- embedded_assets::SDK_WASM_JS.to_vec()-}--#[tauri::command]-fn get_sdk_wasm_dts() -> Vec<u8> {- embedded_assets::SDK_WASM_DTS.to_vec()-}--#[tauri::command]-fn get_editor_dts() -> Vec<u8> {- embedded_assets::EDITOR_DTS.to_vec()-}--#[tauri::command]-fn get_spine38_js() -> Vec<u8> {- embedded_assets::SPINE38_JS.to_vec()-}--#[tauri::command]-fn get_spine38_wasm() -> Vec<u8> {- embedded_assets::SPINE38_WASM.to_vec()-}--#[tauri::command]-fn get_spine41_js() -> Vec<u8> {- embedded_assets::SPINE41_JS.to_vec()-}--#[tauri::command]-fn get_spine41_wasm() -> Vec<u8> {- embedded_assets::SPINE41_WASM.to_vec()-}--#[tauri::command]-fn get_spine42_js() -> Vec<u8> {- embedded_assets::SPINE42_JS.to_vec()-}--#[tauri::command]-fn get_spine42_wasm() -> Vec<u8> {- embedded_assets::SPINE42_WASM.to_vec()-}--#[tauri::command]-fn get_physics_js() -> Vec<u8> {- embedded_assets::PHYSICS_JS.to_vec()-}--#[tauri::command]-fn get_physics_wasm() -> Vec<u8> {- embedded_assets::PHYSICS_WASM.to_vec()+fn get_embedded_asset(name: String) -> Result<Vec<u8>, String> {+ match name.as_str() {+ "engine.js" => Ok(embedded_assets::ENGINE_JS.to_vec()),+ "engine.wasm" => Ok(embedded_assets::ENGINE_WASM.to_vec()),+ "engine.single.js" => Ok(embedded_assets::ENGINE_SINGLE_JS.to_vec()),+ "engine.wxgame.js" => Ok(embedded_assets::ENGINE_WXGAME_JS.to_vec()),+ "engine.wxgame.wasm" => Ok(embedded_assets::ENGINE_WXGAME_WASM.to_vec()),+ "sdk.wechat.js" => Ok(embedded_assets::SDK_WECHAT_JS.to_vec()),+ "sdk.esm.js" => Ok(embedded_assets::SDK_ESM_JS.to_vec()),+ "sdk.esm.dts" => Ok(embedded_assets::SDK_ESM_DTS.to_vec()),+ "sdk.wasm.js" => Ok(embedded_assets::SDK_WASM_JS.to_vec()),+ "sdk.wasm.dts" => Ok(embedded_assets::SDK_WASM_DTS.to_vec()),+ "editor.dts" => Ok(embedded_assets::EDITOR_DTS.to_vec()),+ "spine38.js" => Ok(embedded_assets::SPINE38_JS.to_vec()),+ "spine38.wasm" => Ok(embedded_assets::SPINE38_WASM.to_vec()),+ "spine41.js" => Ok(embedded_assets::SPINE41_JS.to_vec()),+ "spine41.wasm" => Ok(embedded_assets::SPINE41_WASM.to_vec()),+ "spine42.js" => Ok(embedded_assets::SPINE42_JS.to_vec()),+ "spine42.wasm" => Ok(embedded_assets::SPINE42_WASM.to_vec()),+ "physics.js" => Ok(embedded_assets::PHYSICS_JS.to_vec()),+ "physics.wasm" => Ok(embedded_assets::PHYSICS_WASM.to_vec()),+ _ => Err(format!("Unknown embedded asset: {}", name)),+ }}#[derive(Clone, serde::Serialize)]@@ -262,25 +193,7 @@ pub fn run() {open_preview_in_browser,open_folder,execute_command,- get_engine_js,- get_engine_wasm,- get_engine_single_js,- get_engine_wxgame_js,- get_engine_wxgame_wasm,- get_sdk_wechat_js,- get_sdk_esm_js,- get_sdk_esm_dts,- get_sdk_wasm_js,- get_sdk_wasm_dts,- get_editor_dts,- get_spine38_js,- get_spine38_wasm,- get_spine41_js,- get_spine41_wasm,- get_spine42_js,- get_spine42_wasm,- get_physics_js,- get_physics_wasm,+ get_embedded_asset,]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/desktop/src/native-fs.ts b/desktop/src/native-fs.tsindex dc2553d8d..469e38ec9 100644--- a/desktop/src/native-fs.ts+++ b/desktop/src/native-fs.ts@@ -299,89 +299,89 @@ export const nativeFS: NativeFS = {},async getEngineJs() {- const data = await invoke<number[]>('get_engine_js');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'engine.js' });return new TextDecoder().decode(new Uint8Array(data));},async getEngineWasm() {- const data = await invoke<number[]>('get_engine_wasm');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'engine.wasm' });return new Uint8Array(data);},async getEngineSingleJs() {- const data = await invoke<number[]>('get_engine_single_js');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'engine.single.js' });return new TextDecoder().decode(new Uint8Array(data));},async getEngineWxgameJs() {- const data = await invoke<number[]>('get_engine_wxgame_js');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'engine.wxgame.js' });return new TextDecoder().decode(new Uint8Array(data));},async getEngineWxgameWasm() {- const data = await invoke<number[]>('get_engine_wxgame_wasm');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'engine.wxgame.wasm' });return new Uint8Array(data);},async getSdkWechatJs() {- const data = await invoke<number[]>('get_sdk_wechat_js');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'sdk.wechat.js' });return new TextDecoder().decode(new Uint8Array(data));},async getSdkEsmJs() {- const data = await invoke<number[]>('get_sdk_esm_js');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'sdk.esm.js' });return new TextDecoder().decode(new Uint8Array(data));},async getSdkEsmDts() {- const data = await invoke<number[]>('get_sdk_esm_dts');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'sdk.esm.dts' });return new TextDecoder().decode(new Uint8Array(data));},async getSdkWasmJs() {- const data = await invoke<number[]>('get_sdk_wasm_js');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'sdk.wasm.js' });return new TextDecoder().decode(new Uint8Array(data));},async getSdkWasmDts() {- const data = await invoke<number[]>('get_sdk_wasm_dts');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'sdk.wasm.dts' });return new TextDecoder().decode(new Uint8Array(data));},async getEditorDts() {- const data = await invoke<number[]>('get_editor_dts');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'editor.dts' });return new TextDecoder().decode(new Uint8Array(data));},async getSpineJs(version: string) {- const cmdMap: Record<string, string> = {- '3.8': 'get_spine38_js',- '4.1': 'get_spine41_js',- '4.2': 'get_spine42_js',+ const versionMap: Record<string, string> = {+ '3.8': 'spine38',+ '4.1': 'spine41',+ '4.2': 'spine42',};- const cmd = cmdMap[version] ?? 'get_spine42_js';- const data = await invoke<number[]>(cmd);+ const prefix = versionMap[version] ?? 'spine42';+ const data = await invoke<number[]>('get_embedded_asset', { name: `${prefix}.js` });return new TextDecoder().decode(new Uint8Array(data));},async getSpineWasm(version: string) {- const cmdMap: Record<string, string> = {- '3.8': 'get_spine38_wasm',- '4.1': 'get_spine41_wasm',- '4.2': 'get_spine42_wasm',+ const versionMap: Record<string, string> = {+ '3.8': 'spine38',+ '4.1': 'spine41',+ '4.2': 'spine42',};- const cmd = cmdMap[version] ?? 'get_spine42_wasm';- const data = await invoke<number[]>(cmd);+ const prefix = versionMap[version] ?? 'spine42';+ const data = await invoke<number[]>('get_embedded_asset', { name: `${prefix}.wasm` });return new Uint8Array(data);},async getPhysicsJs() {- const data = await invoke<number[]>('get_physics_js');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'physics.js' });return new TextDecoder().decode(new Uint8Array(data));},async getPhysicsWasm() {- const data = await invoke<number[]>('get_physics_wasm');+ const data = await invoke<number[]>('get_embedded_asset', { name: 'physics.wasm' });return new Uint8Array(data);},};diff --git a/editor/package.json b/editor/package.jsonindex 845a81012..13a95db86 100644--- a/editor/package.json+++ b/editor/package.json@@ -10,7 +10,7 @@"import": "./dist/index.js","types": "./dist/index.d.ts"},- "./styles": "./src/styles/editor.css"+ "./styles": "./src/styles/index.css"},"files": ["dist"diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.tsindex 3cbe4a235..a1f20de7a 100644--- a/editor/src/panels/ContentBrowserPanel.ts+++ b/editor/src/panels/ContentBrowserPanel.ts@@ -1,1717 +1,2 @@-/**- * @file ContentBrowserPanel.ts- * @brief Asset browser panel for managing project files- */--import type { EditorStore, AssetType } from '../store/EditorStore';-import { icons } from '../utils/icons';-import { showContextMenu, type ContextMenuItem } from '../ui/ContextMenu';-import { getContextMenuItems, type ContextMenuContext } from '../ui/ContextMenuRegistry';-import { getPlatformAdapter } from '../platform/PlatformAdapter';-import { showInputDialog, showConfirmDialog } from '../ui/dialog';-import { getEditorContext } from '../context/EditorContext';-import { joinPath, getParentDir } from '../utils/path';-import type { NativeFS, DirectoryEntry } from '../types/NativeFS';-import { getAssetLibrary } from '../asset/AssetLibrary';-import { getGlobalPathResolver } from '../asset';-import { showErrorToast } from '../ui/Toast';-import { createEmptyScene } from '../types/SceneTypes';-import { getSettingsValue } from '../settings';-import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, getEditorType } from 'esengine';-import { fuzzyMatch } from '../utils/fuzzy';--// =============================================================================-// Types-// =============================================================================--interface NativeShell {- openFile(path: string): Promise<void>;- openInEditor(projectPath: string, filePath: string): Promise<void>;-}--interface FolderNode {- name: string;- path: string;- children: FolderNode[];- expanded: boolean;- loaded: boolean;-}--interface AssetItem {- name: string;- path: string;- type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'material' | 'shader' | 'spine' | 'font' | 'prefab' | 'file';- relativePath?: string;-}--type ViewMode = 'grid' | 'list';--export interface ContentBrowserOptions {- projectPath?: string;- onOpenScene?: (scenePath: string) => void;-}--const THUMBNAIL_CACHE_MAX = 200;-const THUMBNAIL_SIZE = 48;-const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp']);-const SEARCH_RESULTS_LIMIT = 100;-const VIEW_MODE_KEY = 'esengine.editor.contentBrowserView';--// =============================================================================-// Helpers-// =============================================================================--function getNativeFS(): NativeFS | null {- return getEditorContext().fs ?? null;-}--function getNativeShell(): NativeShell | null {- return getEditorContext().shell ?? null;-}--function getFileExtension(filename: string): string {- const dotIndex = filename.lastIndexOf('.');- return dotIndex > 0 ? filename.substring(dotIndex).toLowerCase() : '';-}--const EDITOR_TYPE_TO_DISPLAY: Record<string, AssetItem['type']> = {- 'texture': 'image',- 'material': 'material',- 'shader': 'shader',- 'spine-atlas': 'spine',- 'spine-skeleton': 'spine',- 'bitmap-font': 'font',- 'prefab': 'prefab',- 'json': 'json',- 'audio': 'audio',- 'scene': 'scene',-};--function getAssetType(entry: DirectoryEntry): AssetItem['type'] {- if (entry.isDirectory) return 'folder';-- const ext = getFileExtension(entry.name);- if (ext === '.ts' || ext === '.js') return 'script';-- const editorType = getEditorType(entry.name);- return EDITOR_TYPE_TO_DISPLAY[editorType] ?? 'file';-}--function getAssetIcon(type: AssetItem['type'], size: number = 32): string {- switch (type) {- case 'folder':- return icons.folder(size);- case 'prefab':- return icons.package(size);- case 'scene':- return icons.layers(size);- case 'script':- return icons.code(size);- case 'image':- return icons.image(size);- case 'audio':- return icons.volume(size);- case 'json':- return icons.braces(size);- case 'material':- return icons.settings(size);- case 'shader':- return icons.code(size);- case 'spine':- return icons.bone(size);- case 'font':- return icons.type(size);- default:- return icons.file(size);- }-}--function isImageFile(name: string): boolean {- return IMAGE_EXTENSIONS.has(getFileExtension(name));-}--// =============================================================================-// ThumbnailCache-// =============================================================================--class ThumbnailCache {- private cache_ = new Map<string, string>();- private loading_ = new Set<string>();-- get(path: string): string | undefined {- return this.cache_.get(path);- }-- isLoading(path: string): boolean {- return this.loading_.has(path);- }-- async load(path: string, onLoaded: () => void): Promise<void> {- if (this.cache_.has(path) || this.loading_.has(path)) return;-- this.loading_.add(path);-- try {- const fs = getNativeFS();- if (!fs) return;-- const data = await fs.readBinaryFile(path);- if (!data) return;-- const blob = new Blob([data.buffer as ArrayBuffer]);- const url = URL.createObjectURL(blob);-- const img = new Image();- await new Promise<void>((resolve, reject) => {- img.onload = () => resolve();- img.onerror = () => reject();- img.src = url;- });-- const canvas = document.createElement('canvas');- canvas.width = THUMBNAIL_SIZE;- canvas.height = THUMBNAIL_SIZE;- const ctx = canvas.getContext('2d')!;-- const scale = Math.min(THUMBNAIL_SIZE / img.width, THUMBNAIL_SIZE / img.height);- const w = img.width * scale;- const h = img.height * scale;- const x = (THUMBNAIL_SIZE - w) / 2;- const y = (THUMBNAIL_SIZE - h) / 2;-- ctx.drawImage(img, x, y, w, h);-- const dataUrl = canvas.toDataURL('image/png');- URL.revokeObjectURL(url);-- if (this.cache_.size >= THUMBNAIL_CACHE_MAX) {- const firstKey = this.cache_.keys().next().value;- if (firstKey) this.cache_.delete(firstKey);- }-- this.cache_.set(path, dataUrl);- onLoaded();- } catch {- // ignore load failures- } finally {- this.loading_.delete(path);- }- }-}--// =============================================================================-// ContentBrowserPanel-// =============================================================================--export class ContentBrowserPanel {- private container_: HTMLElement;- private store_: EditorStore;- private treeContainer_: HTMLElement | null = null;- private gridContainer_: HTMLElement | null = null;- private footerContainer_: HTMLElement | null = null;- private searchInput_: HTMLInputElement | null = null;- private breadcrumbContainer_: HTMLElement | null = null;-- private projectPath_: string | null = null;- private rootFolder_: FolderNode | null = null;- private currentPath_: string = '';- private searchFilter_: string = '';- private unwatchFn_: (() => void) | null = null;- private refreshing_ = false;- private refreshPending_ = false;- private currentItems_: AssetItem[] = [];- private filteredItems_: AssetItem[] = [];- private onOpenScene_: ((scenePath: string) => void) | null = null;- private selectedPaths_ = new Set<string>();- private lastSelectedPath_: string | null = null;- private thumbnailCache_ = new ThumbnailCache();- private viewMode_: ViewMode;-- constructor(container: HTMLElement, store: EditorStore, options?: ContentBrowserOptions) {- this.container_ = container;- this.store_ = store;- this.projectPath_ = options?.projectPath ?? null;- this.onOpenScene_ = options?.onOpenScene ?? null;- this.viewMode_ = (localStorage.getItem(VIEW_MODE_KEY) as ViewMode) || 'grid';-- if (this.projectPath_) {- this.currentPath_ = getParentDir(this.projectPath_);- }-- this.container_.classList.add('es-content-browser');- this.container_.innerHTML = `- <div class="es-content-browser-header">- <span class="es-content-browser-title">${icons.folder(14)} Content Browser</span>- <div class="es-content-browser-actions">- <button class="es-btn es-btn-icon es-refresh-btn" title="Refresh">${icons.refresh(12)}</button>- </div>- </div>- <div class="es-content-browser-body">- <div class="es-content-browser-tree"></div>- <div class="es-content-browser-main">- <div class="es-content-browser-toolbar">- <button class="es-btn es-btn-icon es-cb-up-btn" title="Parent folder">${icons.arrowUp(14)}</button>- <div class="es-content-breadcrumb"></div>- <input type="text" class="es-input es-content-search" placeholder="Search assets...">- <button class="es-btn es-btn-icon es-cb-view-toggle" title="Toggle view"></button>- </div>- <div class="es-content-browser-grid" tabindex="0" role="grid"></div>- </div>- </div>- <div class="es-content-browser-footer">0 items</div>- `;-- this.treeContainer_ = this.container_.querySelector('.es-content-browser-tree');- this.gridContainer_ = this.container_.querySelector('.es-content-browser-grid');- this.footerContainer_ = this.container_.querySelector('.es-content-browser-footer');- this.searchInput_ = this.container_.querySelector('.es-content-search');- this.breadcrumbContainer_ = this.container_.querySelector('.es-content-breadcrumb');-- this.updateViewToggleButton();- this.setupEvents();- this.initialize();- }-- dispose(): void {- if (this.unwatchFn_) {- this.unwatchFn_();- this.unwatchFn_ = null;- }- }-- async navigateToAsset(assetPath: string): Promise<void> {- if (!this.rootFolder_) return;-- const normalized = assetPath.replace(/\\/g, '/');- const lastSlash = normalized.lastIndexOf('/');- const folderPath = lastSlash > 0 ? normalized.substring(0, lastSlash) : this.rootFolder_.path;-- const projectDir = this.rootFolder_.path;- const targetFolderPath = joinPath(projectDir, folderPath);-- const pathParts = folderPath.split('/').filter(p => p);- let currentNode = this.rootFolder_;-- for (const part of pathParts) {- const childPath = joinPath(currentNode.path, part);- let child = currentNode.children.find(c => c.path === childPath);-- if (!child) {- if (!currentNode.loaded) {- await this.loadFolderChildren(currentNode);- child = currentNode.children.find(c => c.path === childPath);- }- }-- if (child) {- child.expanded = true;- if (!child.loaded) {- await this.loadFolderChildren(child);- }- currentNode = child;- } else {- break;- }- }-- this.currentPath_ = targetFolderPath;- const fullAssetPath = joinPath(projectDir, normalized);- this.selectedPaths_.clear();- this.selectedPaths_.add(fullAssetPath);- this.lastSelectedPath_ = fullAssetPath;-- this.renderTree();- await this.renderGrid();-- requestAnimationFrame(() => {- const selectedItem = this.gridContainer_?.querySelector('.es-selected');- selectedItem?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });- });- }-- private async initialize(): Promise<void> {- if (this.projectPath_) {- await this.loadProjectDirectory();- await this.setupFileWatcher();- } else {- this.rootFolder_ = this.createEmptyFolderStructure();- this.render();- }- }-- private async loadProjectDirectory(): Promise<void> {- const projectDir = getParentDir(this.projectPath_!);- this.currentPath_ = projectDir;-- this.rootFolder_ = {- name: this.getProjectName(),- path: projectDir,- children: [],- expanded: true,- loaded: false,- };-- await this.loadFolderChildren(this.rootFolder_);- this.render();- }-- private getProjectName(): string {- if (!this.projectPath_) return 'Project';- const normalized = this.projectPath_.replace(/\\/g, '/');- const parts = normalized.split('/');- return parts[parts.length - 2] || 'Project';- }-- private async loadFolderChildren(folder: FolderNode): Promise<void> {- const fs = getNativeFS();- if (!fs) return;-- try {- const entries = await fs.listDirectoryDetailed(folder.path);-- folder.children = entries- .filter(e => e.isDirectory && !e.name.startsWith('.'))- .sort((a, b) => a.name.localeCompare(b.name))- .map(e => ({- name: e.name,- path: joinPath(folder.path, e.name),- children: [],- expanded: false,- loaded: false,- }));-- folder.loaded = true;- } catch (err) {- console.error('Failed to load folder:', folder.path, err);- }- }-- private async setupFileWatcher(): Promise<void> {- const fs = getNativeFS();- if (!fs || !this.projectPath_) return;-- const projectDir = getParentDir(this.projectPath_);-- try {- this.unwatchFn_ = await fs.watchDirectory(- projectDir,- () => { this.refresh(); },- { recursive: true }- );- } catch (err) {- console.error('Failed to setup file watcher:', err);- }- }-- async refresh(): Promise<void> {- if (this.refreshing_) {- this.refreshPending_ = true;- return;- }- this.refreshing_ = true;- try {- if (this.rootFolder_ && this.projectPath_) {- this.rootFolder_.loaded = false;- await this.loadFolderChildren(this.rootFolder_);-- const expandedPaths = this.collectExpandedPaths(this.rootFolder_);- for (const path of expandedPaths) {- const folder = this.findFolder(this.rootFolder_, path);- if (folder && !folder.loaded) {- await this.loadFolderChildren(folder);- }- }-- this.render();- }- } finally {- this.refreshing_ = false;- if (this.refreshPending_) {- this.refreshPending_ = false;- this.refresh();- }- }- }-- private collectExpandedPaths(node: FolderNode): string[] {- const paths: string[] = [];- if (node.expanded) {- paths.push(node.path);- for (const child of node.children) {- paths.push(...this.collectExpandedPaths(child));- }- }- return paths;- }-- private createEmptyFolderStructure(): FolderNode {- return {- name: 'Project',- path: '',- expanded: true,- loaded: true,- children: [- { name: 'assets', path: 'assets', expanded: false, loaded: true, children: [] },- { name: 'src', path: 'src', expanded: false, loaded: true, children: [] },- ],- };- }-- private updateViewToggleButton(): void {- const btn = this.container_.querySelector('.es-cb-view-toggle');- if (!btn) return;- btn.innerHTML = this.viewMode_ === 'grid' ? icons.layoutList(14) : icons.layoutGrid(14);- btn.setAttribute('title', this.viewMode_ === 'grid' ? 'Switch to list view' : 'Switch to grid view');- }-- private setupEvents(): void {- this.searchInput_?.addEventListener('input', () => {- this.searchFilter_ = this.searchInput_?.value.toLowerCase() ?? '';- this.renderGrid();- });-- this.breadcrumbContainer_?.addEventListener('click', (e) => {- const target = e.target as HTMLElement;- const item = target.closest('.es-breadcrumb-item') as HTMLElement;- if (!item) return;-- const path = item.dataset.path;- if (path) {- this.selectFolder(path);- }- });-- const upBtn = this.container_.querySelector('.es-cb-up-btn');- upBtn?.addEventListener('click', () => {- this.navigateToParent();- });-- const viewToggle = this.container_.querySelector('.es-cb-view-toggle');- viewToggle?.addEventListener('click', () => {- this.viewMode_ = this.viewMode_ === 'grid' ? 'list' : 'grid';- localStorage.setItem(VIEW_MODE_KEY, this.viewMode_);- this.updateViewToggleButton();- this.renderGrid();- });-- this.treeContainer_?.addEventListener('click', async (e) => {- const target = e.target as HTMLElement;- const item = target.closest('.es-folder-item') as HTMLElement;- if (!item) return;-- const path = item.dataset.path;- if (!path) return;-- if (target.closest('.es-folder-expand')) {- await this.toggleFolder(path);- } else {- this.selectFolder(path);- }- });-- this.gridContainer_?.addEventListener('click', (e) => {- const target = e.target as HTMLElement;- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;-- if (!item) {- this.selectedPaths_.clear();- this.lastSelectedPath_ = null;- this.updateAssetSelection();- return;- }-- const path = item.dataset.path;- if (!path) return;-- if (e.shiftKey && this.lastSelectedPath_) {- this.rangeSelect(this.lastSelectedPath_, path);- } else if (e.ctrlKey || e.metaKey) {- if (this.selectedPaths_.has(path)) {- this.selectedPaths_.delete(path);- } else {- this.selectedPaths_.add(path);- }- this.lastSelectedPath_ = path;- } else {- this.selectedPaths_.clear();- this.selectedPaths_.add(path);- this.lastSelectedPath_ = path;- }-- this.updateAssetSelection();- this.notifyStoreSelection();- });-- this.gridContainer_?.addEventListener('dblclick', async (e) => {- const target = e.target as HTMLElement;- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;- if (!item) return;-- const path = item.dataset.path;- const type = item.dataset.type;-- if (type === 'folder' && path) {- this.selectFolder(path);- await this.expandFolder(path);- } else if (path) {- this.onAssetDoubleClick(path, type as AssetItem['type']);- }- });-- const refreshBtn = this.container_.querySelector('.es-refresh-btn');- refreshBtn?.addEventListener('click', () => {- this.refresh();- });-- this.gridContainer_?.addEventListener('contextmenu', (e) => {- e.preventDefault();- const target = e.target as HTMLElement;- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;-- if (item) {- const path = item.dataset.path;- const type = item.dataset.type;- if (path) {- if (!this.selectedPaths_.has(path)) {- this.selectedPaths_.clear();- this.selectedPaths_.add(path);- this.lastSelectedPath_ = path;- this.updateAssetSelection();- }-- if (this.selectedPaths_.size > 1) {- this.showMultiSelectContextMenu(e);- } else {- this.showAssetContextMenu(e, path, type as AssetItem['type']);- }- }- } else {- this.showFolderContextMenu(e, this.currentPath_);- }- });-- this.treeContainer_?.addEventListener('contextmenu', (e) => {- e.preventDefault();- const target = e.target as HTMLElement;- const item = target.closest('.es-folder-item') as HTMLElement;- const path = item?.dataset.path ?? this.currentPath_;- if (path) {- this.showFolderContextMenu(e, path);- }- });-- this.gridContainer_?.addEventListener('dragstart', (e) => {- const target = e.target as HTMLElement;- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;- if (!item) return;-- const path = item.dataset.path;- const type = item.dataset.type;- if (!path || !type) return;-- if (!this.selectedPaths_.has(path)) {- this.selectedPaths_.clear();- this.selectedPaths_.add(path);- this.lastSelectedPath_ = path;- this.updateAssetSelection();- }-- const dragItems = this.filteredItems_.filter(i => this.selectedPaths_.has(i.path));- const payload = dragItems.map(i => ({ type: i.type, path: i.path, name: i.name }));-- e.dataTransfer?.setData('application/esengine-asset', JSON.stringify(- payload.length === 1 ? payload[0] : payload- ));- e.dataTransfer!.effectAllowed = 'copy';-- item.classList.add('es-dragging');- });-- this.gridContainer_?.addEventListener('dragend', (e) => {- const target = e.target as HTMLElement;- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;- item?.classList.remove('es-dragging');- });-- this.gridContainer_?.addEventListener('dragover', (e) => {- const types = e.dataTransfer?.types ?? [];- const typesArr = Array.from(types);- if (!typesArr.includes('application/esengine-entity') && !typesArr.includes('Files')) return;- e.preventDefault();- e.dataTransfer!.dropEffect = 'copy';- this.gridContainer_?.classList.add('es-drag-over');- });-- this.gridContainer_?.addEventListener('dragleave', (e) => {- const related = e.relatedTarget as HTMLElement;- if (this.gridContainer_?.contains(related)) return;- this.gridContainer_?.classList.remove('es-drag-over');- });-- this.gridContainer_?.addEventListener('drop', (e) => {- this.gridContainer_?.classList.remove('es-drag-over');-- if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {- e.preventDefault();- this.importDroppedFiles(e.dataTransfer.files);- return;- }-- const entityIdStr = e.dataTransfer?.getData('application/esengine-entity');- if (!entityIdStr) return;-- e.preventDefault();- const entityId = parseInt(entityIdStr, 10);- if (isNaN(entityId)) return;-- this.saveDroppedEntityAsPrefab(entityId);- });-- this.gridContainer_?.addEventListener('keydown', (e) => {- this.handleKeyboardNavigation(e);- });- }-- private navigateToParent(): void {- if (!this.rootFolder_) return;- if (this.currentPath_ === this.rootFolder_.path) return;-- const parentPath = getParentDir(this.currentPath_);- if (parentPath) {- this.selectFolder(parentPath);- }- }-- private rangeSelect(fromPath: string, toPath: string): void {- const fromIndex = this.filteredItems_.findIndex(i => i.path === fromPath);- const toIndex = this.filteredItems_.findIndex(i => i.path === toPath);- if (fromIndex < 0 || toIndex < 0) return;-- const start = Math.min(fromIndex, toIndex);- const end = Math.max(fromIndex, toIndex);-- this.selectedPaths_.clear();- for (let i = start; i <= end; i++) {- this.selectedPaths_.add(this.filteredItems_[i].path);- }- }-- private notifyStoreSelection(): void {- if (this.selectedPaths_.size === 1) {- const path = this.selectedPaths_.values().next().value!;- const item = this.filteredItems_.find(i => i.path === path);- if (item) {- this.store_.selectAsset({- path: item.path,- type: item.type as AssetType,- name: item.name,- });- }- }- }-- private handleKeyboardNavigation(e: KeyboardEvent): void {- if (!this.gridContainer_ || this.filteredItems_.length === 0) return;-- const isGrid = this.viewMode_ === 'grid';-- switch (e.key) {- case 'ArrowRight':- case 'ArrowLeft':- case 'ArrowDown':- case 'ArrowUp': {- e.preventDefault();- const currentIndex = this.lastSelectedPath_- ? this.filteredItems_.findIndex(i => i.path === this.lastSelectedPath_)- : -1;-- let cols = 1;- if (isGrid) {- const containerWidth = this.gridContainer_.clientWidth - 24;- cols = Math.max(1, Math.floor(containerWidth / 80));- }-- let nextIndex = currentIndex;- if (e.key === 'ArrowRight') nextIndex = currentIndex + 1;- else if (e.key === 'ArrowLeft') nextIndex = currentIndex - 1;- else if (e.key === 'ArrowDown') nextIndex = currentIndex + cols;- else if (e.key === 'ArrowUp') nextIndex = currentIndex - cols;-- if (nextIndex >= 0 && nextIndex < this.filteredItems_.length) {- this.selectedPaths_.clear();- this.selectedPaths_.add(this.filteredItems_[nextIndex].path);- this.lastSelectedPath_ = this.filteredItems_[nextIndex].path;- this.updateAssetSelection();- this.notifyStoreSelection();-- const el = this.gridContainer_.children[nextIndex] as HTMLElement;- el?.scrollIntoView({ block: 'nearest' });- }- break;- }- case 'Enter': {- e.preventDefault();- if (this.selectedPaths_.size !== 1) return;- const path = this.selectedPaths_.values().next().value!;- const item = this.filteredItems_.find(i => i.path === path);- if (!item) return;-- if (item.type === 'folder') {- this.selectFolder(item.path);- this.expandFolder(item.path);- } else {- this.onAssetDoubleClick(item.path, item.type);- }- break;- }- case 'Delete':- case 'Backspace': {- e.preventDefault();- if (this.selectedPaths_.size === 0) return;- this.deleteSelectedAssets();- break;- }- case 'F2': {- e.preventDefault();- if (this.selectedPaths_.size !== 1) return;- const path = this.selectedPaths_.values().next().value!;- const item = this.filteredItems_.find(i => i.path === path);- if (item) {- this.renameAsset(item.path, item.type);- }- break;- }- case 'a': {- if (e.ctrlKey || e.metaKey) {- e.preventDefault();- this.selectedPaths_.clear();- for (const item of this.filteredItems_) {- this.selectedPaths_.add(item.path);- }- this.updateAssetSelection();- }- break;- }- }- }-- private async deleteSelectedAssets(): Promise<void> {- const paths = Array.from(this.selectedPaths_);- const names = paths.map(p => p.split('/').pop() ?? p);- const message = paths.length === 1- ? `Are you sure you want to delete "${names[0]}"?`- : `Are you sure you want to delete ${paths.length} items?`;-- const confirmed = await showConfirmDialog({- title: 'Delete Assets',- message,- confirmText: 'Delete',- danger: true,- });-- if (!confirmed) return;-- const platform = getPlatformAdapter();- for (const path of paths) {- try {- await platform.remove(path);- const metaPath = `${path}.meta`;- try { await platform.remove(metaPath); } catch { /* no .meta file */ }-- if (this.rootFolder_) {- const projectDir = this.rootFolder_.path;- const prefix = projectDir.endsWith('/') ? projectDir : projectDir + '/';- if (path.startsWith(prefix)) {- getAssetLibrary().unregister(path.substring(prefix.length));- }- }- } catch (err) {- console.error('Failed to delete asset:', err);- showErrorToast('Failed to delete asset', String(err));- }- }-- this.selectedPaths_.clear();- this.lastSelectedPath_ = null;- this.refresh();- }-- private showMultiSelectContextMenu(e: MouseEvent): void {- const count = this.selectedPaths_.size;- const items: ContextMenuItem[] = [- {- label: `Delete ${count} items`,- icon: icons.trash(14),- onClick: () => this.deleteSelectedAssets(),- },- ];-- showContextMenu({ x: e.clientX, y: e.clientY, items });- }-- private showAssetContextMenu(e: MouseEvent, path: string, type: AssetItem['type']): void {- const fs = getNativeFS();- const parentPath = getParentDir(path);- const fileName = path.split('/').pop() ?? path;-- const items: ContextMenuItem[] = [- {- label: 'Show in Folder',- icon: icons.folderOpen(14),- onClick: () => {- fs?.openFolder(parentPath);- },- },- {- label: 'Copy Path',- icon: icons.copy(14),- onClick: () => {- navigator.clipboard.writeText(path);- },- },- {- label: 'Rename',- icon: icons.pencil(14),- onClick: () => this.renameAsset(path, type),- },- { separator: true, label: '' },- {- label: 'Delete',- icon: icons.trash(14),- onClick: () => this.deleteAsset(path, fileName),- },- ];-- const ctx: ContextMenuContext = { location: 'content-browser.asset', assetPath: path, assetType: type };- const extensionItems = getContextMenuItems('content-browser.asset', ctx);- if (extensionItems.length > 0) {- items.push({ label: '', separator: true }, ...extensionItems);- }-- showContextMenu({ x: e.clientX, y: e.clientY, items });- }-- private async deleteAsset(path: string, name: string): Promise<void> {- const confirmed = await showConfirmDialog({- title: 'Delete Asset',- message: `Are you sure you want to delete "${name}"?`,- confirmText: 'Delete',- danger: true,- });-- if (!confirmed) return;-- try {- const platform = getPlatformAdapter();- await platform.remove(path);-- const metaPath = `${path}.meta`;- try { await platform.remove(metaPath); } catch { /* no .meta file */ }-- if (this.rootFolder_) {- const projectDir = this.rootFolder_.path;- const prefix = projectDir.endsWith('/') ? projectDir : projectDir + '/';- if (path.startsWith(prefix)) {- getAssetLibrary().unregister(path.substring(prefix.length));- }- }-- this.refresh();- } catch (err) {- console.error('Failed to delete asset:', err);- showErrorToast('Failed to delete asset', String(err));- }- }-- private async renameAsset(path: string, type: AssetItem['type']): Promise<void> {- const platform = getPlatformAdapter();- const parentPath = getParentDir(path);- const fileName = path.split('/').pop() ?? path;- const dotIndex = fileName.lastIndexOf('.');- const baseName = type === 'folder' || dotIndex <= 0 ? fileName : fileName.substring(0, dotIndex);- const extension = type === 'folder' || dotIndex <= 0 ? '' : fileName.substring(dotIndex);-- const newName = await showInputDialog({- title: 'Rename',- placeholder: 'Name',- defaultValue: baseName,- confirmText: 'Rename',- validator: async (value) => {- if (!value.trim()) return 'Name is required';- if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {- return 'Name contains invalid characters';- }- const newFileName = extension ? value.trim() + extension : value.trim();- if (newFileName === fileName) return null;- const newPath = `${parentPath}/${newFileName}`;- if (await platform.exists(newPath)) {- return 'A file with this name already exists';- }- return null;- },- });-- if (!newName) return;-- const trimmed = newName.trim();- const newFileName = extension ? trimmed + extension : trimmed;- if (newFileName === fileName) return;-- const newPath = `${parentPath}/${newFileName}`;-- try {- await platform.rename(path, newPath);-- const metaPath = `${path}.meta`;- if (await platform.exists(metaPath)) {- await platform.rename(metaPath, `${newPath}.meta`);- }-- if (this.rootFolder_) {- const projectDir = this.rootFolder_.path;- const prefix = projectDir.endsWith('/') ? projectDir : projectDir + '/';- if (path.startsWith(prefix)) {- getAssetLibrary().updatePath(- path.substring(prefix.length),- newPath.substring(prefix.length)- );- }- }-- this.refresh();- } catch (err) {- console.error('Failed to rename asset:', err);- showErrorToast('Failed to rename asset', String(err));- }- }-- private showFolderContextMenu(e: MouseEvent, path: string): void {- const fs = getNativeFS();-- const items: ContextMenuItem[] = [- {- label: 'Create',- icon: icons.plus(14),- children: [- {- label: 'Folder',- icon: icons.folder(14),- onClick: () => this.createNewFolder(path),- },- { label: '', separator: true },- {- label: 'Script',- icon: icons.code(14),- onClick: () => this.createNewScript(path),- },- {- label: 'Material',- icon: icons.settings(14),- onClick: () => this.createNewMaterial(path),- },- {- label: 'Shader',- icon: icons.code(14),- onClick: () => this.createNewShader(path),- },- {- label: 'BitmapFont',- icon: icons.type(14),- onClick: () => this.createNewBitmapFont(path),- },- {- label: 'Scene',- icon: icons.layers(14),- onClick: () => this.createNewScene(path),- },- ],- },- { label: '', separator: true },- {- label: 'Show in Folder',- icon: icons.folderOpen(14),- onClick: () => {- fs?.openFolder(path);- },- },- {- label: 'Copy Path',- icon: icons.copy(14),- onClick: () => {- navigator.clipboard.writeText(path);- },- },- { label: '', separator: true },- {- label: 'Refresh',- icon: icons.refresh(14),- onClick: () => {- this.refresh();- },- },- ];-- const ctx: ContextMenuContext = { location: 'content-browser.folder', assetPath: path, assetType: 'folder' };- const extensionItems = getContextMenuItems('content-browser.folder', ctx);- if (extensionItems.length > 0) {- items.push({ label: '', separator: true }, ...extensionItems);- }-- showContextMenu({ x: e.clientX, y: e.clientY, items });- }-- private async createNewFolder(parentPath: string): Promise<void> {- const name = await this.promptFileName('New Folder', '', parentPath);- if (!name) return;-- const platform = getPlatformAdapter();- const folderPath = `${parentPath}/${name}`;-- try {- await platform.mkdir(folderPath);- this.refresh();- } catch (err) {- console.error('Failed to create folder:', err);- showErrorToast('Failed to create folder', String(err));- }- }-- private async createNewScript(parentPath: string): Promise<void> {- const name = await this.promptFileName('NewScript', '.ts', parentPath);- if (!name) return;-- const platform = getPlatformAdapter();- const filePath = `${parentPath}/${name}`;-- const className = this.toClassName(name);- const content = `import { defineComponent } from 'esengine';--export const ${className} = defineComponent('${className}', {- value: 0,-});-`;-- try {- await platform.writeTextFile(filePath, content);- this.refresh();- } catch (err) {- console.error('Failed to create script:', err);- showErrorToast('Failed to create script', String(err));- }- }-- private async createNewMaterial(parentPath: string): Promise<void> {- const name = await this.promptFileName('NewMaterial', '.esmaterial', parentPath);- if (!name) return;-- const platform = getPlatformAdapter();- const filePath = `${parentPath}/${name}`;-- const content = JSON.stringify({- version: '1.0',- type: 'material',- shader: '',- blendMode: 0,- depthTest: false,- properties: {},- }, null, 2);-- try {- await platform.writeTextFile(filePath, content);- this.refresh();- } catch (err) {- console.error('Failed to create material:', err);- showErrorToast('Failed to create material', String(err));- }- }-- private async createNewScene(parentPath: string): Promise<void> {- const name = await this.promptFileName('NewScene', '.esscene', parentPath);- if (!name) return;-- const platform = getPlatformAdapter();- const filePath = `${parentPath}/${name}`;-- const w = getSettingsValue<number>('project.designWidth') || DEFAULT_DESIGN_WIDTH;- const h = getSettingsValue<number>('project.designHeight') || DEFAULT_DESIGN_HEIGHT;- const scene = createEmptyScene(name.replace('.esscene', ''), { width: w, height: h });- const content = JSON.stringify(scene, null, 2);-- try {- await platform.writeTextFile(filePath, content);- this.refresh();- if (this.onOpenScene_) {- this.onOpenScene_(filePath);- }- } catch (err) {- console.error('Failed to create scene:', err);- showErrorToast('Failed to create scene', String(err));- }- }-- private async createNewShader(parentPath: string): Promise<void> {- const name = await this.promptFileName('NewShader', '.esshader', parentPath);- if (!name) return;-- const platform = getPlatformAdapter();- const filePath = `${parentPath}/${name}`;- const shaderName = name.replace('.esshader', '');-- const content = `#pragma shader "${shaderName}"--#pragma vertex-attribute vec2 a_position;-attribute vec2 a_texCoord;--uniform mat4 u_projection;-uniform mat4 u_model;--varying vec2 v_texCoord;--void main() {- v_texCoord = a_texCoord;- gl_Position = u_projection * u_model * vec4(a_position, 0.0, 1.0);-}-#pragma end--#pragma fragment-precision mediump float;--varying vec2 v_texCoord;--void main() {- gl_FragColor = vec4(v_texCoord, 0.0, 1.0);-}-#pragma end-`;-- try {- await platform.writeTextFile(filePath, content);- this.refresh();- } catch (err) {- console.error('Failed to create shader:', err);- showErrorToast('Failed to create shader', String(err));- }- }-- private async createNewBitmapFont(parentPath: string): Promise<void> {- const name = await this.promptFileName('NewFont', '.bmfont', parentPath);- if (!name) return;-- const platform = getPlatformAdapter();- const filePath = `${parentPath}/${name}`;-- const content = JSON.stringify({- version: '1.0',- type: 'label-atlas',- glyphs: {},- }, null, 2);-- try {- await platform.writeTextFile(filePath, content);- this.refresh();- } catch (err) {- console.error('Failed to create bitmap font:', err);- showErrorToast('Failed to create bitmap font', String(err));- }- }-- private async promptFileName(defaultName: string, extension: string = '', parentPath?: string): Promise<string | null> {- const platform = getPlatformAdapter();-- const name = await showInputDialog({- title: 'Enter Name',- placeholder: 'Name',- defaultValue: defaultName,- confirmText: 'Create',- validator: async (value) => {- if (!value.trim()) return 'Name is required';- if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {- return 'Name contains invalid characters';- }- if (parentPath) {- const fileName = extension && !value.trim().endsWith(extension)- ? value.trim() + extension- : value.trim();- const fullPath = `${parentPath}/${fileName}`;- if (await platform.exists(fullPath)) {- return 'A file with this name already exists';- }- }- return null;- },- });-- if (!name) return null;-- const trimmed = name.trim();- if (extension && !trimmed.endsWith(extension)) {- return trimmed + extension;- }- return trimmed;- }-- private toClassName(filename: string): string {- const name = filename.replace(/\.(ts|js)$/, '');- return name.charAt(0).toUpperCase() + name.slice(1);- }-- private selectAsset(path: string): void {- this.selectedPaths_.clear();- this.selectedPaths_.add(path);- this.lastSelectedPath_ = path;- this.updateAssetSelection();- this.notifyStoreSelection();- }-- private updateAssetSelection(): void {- if (!this.gridContainer_) return;-- const selector = this.viewMode_ === 'list' ? '.es-cb-list-row' : '.es-asset-item';- const items = this.gridContainer_.querySelectorAll(selector);- items.forEach((item) => {- const el = item as HTMLElement;- if (this.selectedPaths_.has(el.dataset.path ?? '')) {- el.classList.add('es-selected');- } else {- el.classList.remove('es-selected');- }- });- }-- private onAssetDoubleClick(path: string, type: AssetItem['type']): void {- if (type === 'scene' && this.onOpenScene_) {- this.onOpenScene_(path);- return;- }-- if (type === 'prefab') {- const resolver = getGlobalPathResolver();- const relativePath = resolver.toRelativePath(path);- this.store_.enterPrefabEditMode(relativePath);- return;- }-- const shell = getNativeShell();- if (!shell) return;-- if (type === 'script') {- const projectDir = this.rootFolder_?.path;- if (projectDir) {- shell.openInEditor(projectDir, path);- }- } else if (type === 'shader' || type === 'json') {- shell.openFile(path);- }- }-- private async toggleFolder(path: string): Promise<void> {- const folder = this.findFolder(this.rootFolder_, path);- if (folder) {- folder.expanded = !folder.expanded;-- if (folder.expanded && !folder.loaded) {- await this.loadFolderChildren(folder);- }-- this.renderTree();- }- }-- private async expandFolder(path: string): Promise<void> {- const folder = this.findFolder(this.rootFolder_, path);- if (folder) {- folder.expanded = true;-- if (!folder.loaded) {- await this.loadFolderChildren(folder);- }-- this.renderTree();- }- }-- private selectFolder(path: string): void {- this.currentPath_ = path;- this.selectedPaths_.clear();- this.lastSelectedPath_ = null;- this.renderTree();- this.renderBreadcrumb();- this.renderGrid();- }-- private findFolder(node: FolderNode | null, path: string): FolderNode | null {- if (!node) return null;- if (node.path === path) return node;- for (const child of node.children) {- const found = this.findFolder(child, path);- if (found) return found;- }- return null;- }-- private render(): void {- this.renderTree();- this.renderBreadcrumb();- this.renderGrid();- }-- private renderTree(): void {- if (!this.treeContainer_ || !this.rootFolder_) return;- this.treeContainer_.innerHTML = this.renderFolderNode(this.rootFolder_, 0);- }-- private renderBreadcrumb(): void {- if (!this.breadcrumbContainer_ || !this.rootFolder_) return;-- const rootPath = this.rootFolder_.path;- const currentPath = this.currentPath_;-- const crumbs: { name: string; path: string }[] = [];-- crumbs.push({ name: this.rootFolder_.name, path: rootPath });-- if (currentPath && currentPath !== rootPath && currentPath.startsWith(rootPath)) {- const relativePath = currentPath.substring(rootPath.length).replace(/^\//, '');- const parts = relativePath.split('/').filter(p => p);-- let accumulatedPath = rootPath;- for (const part of parts) {- accumulatedPath = joinPath(accumulatedPath, part);- crumbs.push({ name: part, path: accumulatedPath });- }- }-- this.breadcrumbContainer_.innerHTML = crumbs- .map((crumb, index) => {- const isLast = index === crumbs.length - 1;- const separator = isLast ? '' : `<span class="es-breadcrumb-separator">${icons.chevronRight(10)}</span>`;- return `<span class="es-breadcrumb-item${isLast ? ' es-active' : ''}" data-path="${crumb.path}">${crumb.name}</span>${separator}`;- })- .join('');- }-- private renderFolderNode(node: FolderNode, depth: number): string {- const isSelected = node.path === this.currentPath_;- const hasChildren = node.children.length > 0 || !node.loaded;- const indent = depth * 16;-- let html = `- <div class="es-folder-item ${isSelected ? 'es-selected' : ''}"- data-path="${node.path}"- style="padding-left: ${indent}px">- ${hasChildren ? `<span class="es-folder-expand">${node.expanded ? icons.chevronDown(10) : icons.chevronRight(10)}</span>` : '<span class="es-folder-spacer"></span>'}- <span class="es-folder-icon">${node.expanded ? icons.folderOpen(14) : icons.folder(14)}</span>- <span class="es-folder-name">${node.name}</span>- </div>- `;-- if (node.expanded) {- for (const child of node.children) {- html += this.renderFolderNode(child, depth + 1);- }- }-- return html;- }-- private async renderGrid(): Promise<void> {- if (!this.gridContainer_) return;-- let items: AssetItem[];- if (this.searchFilter_) {- items = await this.searchRecursive(this.currentPath_, this.searchFilter_);- } else {- items = await this.loadCurrentFolderItems();- }- this.currentItems_ = items;-- let filteredItems = items;- if (this.searchFilter_) {- filteredItems = items.slice(0, SEARCH_RESULTS_LIMIT);- }- this.filteredItems_ = filteredItems;-- if (filteredItems.length === 0) {- this.gridContainer_.innerHTML = this.renderEmptyState();- this.gridContainer_.classList.remove('es-cb-list-view');- if (this.footerContainer_) {- this.footerContainer_.textContent = '0 items';- }- return;- }-- const isDraggable = (type: AssetItem['type']) => type !== 'folder';-- if (this.viewMode_ === 'list') {- this.gridContainer_.classList.add('es-cb-list-view');- this.gridContainer_.innerHTML = filteredItems- .map((item) => {- const iconHtml = this.getItemIconHtml(item, 24);- const subtext = item.relativePath- ? `<span class="es-cb-list-subpath">${item.relativePath}</span>`- : '';- return `- <div class="es-cb-list-row${this.selectedPaths_.has(item.path) ? ' es-selected' : ''}"- data-path="${item.path}"- data-type="${item.type}"- ${isDraggable(item.type) ? 'draggable="true"' : ''}>- <span class="es-cb-list-icon">${iconHtml}</span>- <span class="es-cb-list-name">${item.name}${subtext}</span>- <span class="es-cb-list-type">${item.type}</span>- </div>`;- })- .join('');- } else {- this.gridContainer_.classList.remove('es-cb-list-view');- this.gridContainer_.innerHTML = filteredItems- .map((item) => {- const iconHtml = this.getItemIconHtml(item, 32);- const subtext = item.relativePath- ? `<div class="es-asset-subpath">${item.relativePath}</div>`- : '';- return `- <div class="es-asset-item${this.selectedPaths_.has(item.path) ? ' es-selected' : ''}"- data-path="${item.path}"- data-type="${item.type}"- ${isDraggable(item.type) ? 'draggable="true"' : ''}>- <div class="es-asset-icon">${iconHtml}</div>- <div class="es-asset-name">${item.name}</div>- ${subtext}- </div>`;- })- .join('');- }-- for (const item of filteredItems) {- if (item.type === 'image' && isImageFile(item.name)) {- this.loadThumbnailFor(item.path);- }- }-- if (this.footerContainer_) {- const suffix = this.searchFilter_ && items.length > SEARCH_RESULTS_LIMIT- ? ` (showing ${SEARCH_RESULTS_LIMIT} of ${items.length})`- : '';- this.footerContainer_.textContent = `${filteredItems.length} items${suffix}`;- }- }-- private getItemIconHtml(item: AssetItem, size: number): string {- if (item.type === 'image' && isImageFile(item.name)) {- const cached = this.thumbnailCache_.get(item.path);- if (cached) {- return `<img src="${cached}" width="${size}" height="${size}" class="es-cb-thumbnail" alt="">`;- }- if (this.thumbnailCache_.isLoading(item.path)) {- return `<span class="es-cb-thumb-loading">${getAssetIcon(item.type, size)}</span>`;- }- }- return getAssetIcon(item.type, size);- }-- private loadThumbnailFor(path: string): void {- this.thumbnailCache_.load(path, () => {- this.updateThumbnailInDom(path);- });- }-- private updateThumbnailInDom(path: string): void {- if (!this.gridContainer_) return;- const dataUrl = this.thumbnailCache_.get(path);- if (!dataUrl) return;-- const selector = this.viewMode_ === 'list' ? '.es-cb-list-row' : '.es-asset-item';- const items = this.gridContainer_.querySelectorAll(selector);- for (const el of items) {- const htmlEl = el as HTMLElement;- if (htmlEl.dataset.path !== path) continue;-- const iconContainer = this.viewMode_ === 'list'- ? htmlEl.querySelector('.es-cb-list-icon')- : htmlEl.querySelector('.es-asset-icon');- if (iconContainer) {- const size = this.viewMode_ === 'list' ? 24 : 32;- iconContainer.innerHTML = `<img src="${dataUrl}" width="${size}" height="${size}" class="es-cb-thumbnail" alt="">`;- }- break;- }- }-- private renderEmptyState(): string {- if (this.searchFilter_) {- return `<div class="es-cb-empty-state">- <div class="es-cb-empty-icon">${icons.search(32)}</div>- <div class="es-cb-empty-text">No matching assets found</div>- </div>`;- }- return `<div class="es-cb-empty-state">- <div class="es-cb-empty-icon">${icons.folder(32)}</div>- <div class="es-cb-empty-text">This folder is empty</div>- </div>`;- }-- private async searchRecursive(basePath: string, filter: string): Promise<AssetItem[]> {- const fs = getNativeFS();- if (!fs || !basePath) return [];-- const scored: Array<{ item: AssetItem; score: number }> = [];- const stack = [basePath];-- while (stack.length > 0 && scored.length < SEARCH_RESULTS_LIMIT * 2) {- const dir = stack.pop()!;- try {- const entries = await fs.listDirectoryDetailed(dir);- for (const entry of entries) {- if (entry.name.startsWith('.') || entry.name.endsWith('.meta')) continue;-- const entryPath = joinPath(dir, entry.name);-- if (entry.isDirectory) {- stack.push(entryPath);- const match = fuzzyMatch(filter, entry.name);- if (match) {- const relative = entryPath.substring(basePath.length).replace(/^\//, '');- scored.push({- item: { name: entry.name, path: entryPath, type: 'folder', relativePath: relative },- score: match.score,- });- }- } else {- const match = fuzzyMatch(filter, entry.name);- if (match) {- const relative = entryPath.substring(basePath.length).replace(/^\//, '');- scored.push({- item: { name: entry.name, path: entryPath, type: getAssetType(entry), relativePath: relative },- score: match.score,- });- }- }- }- } catch {- // skip inaccessible directories- }- }-- return scored- .sort((a, b) => {- if (a.item.type === 'folder' && b.item.type !== 'folder') return -1;- if (a.item.type !== 'folder' && b.item.type === 'folder') return 1;- return b.score - a.score;- })- .map(s => s.item);- }-- private async loadCurrentFolderItems(): Promise<AssetItem[]> {- const fs = getNativeFS();- if (!fs || !this.currentPath_) {- return this.getFallbackItems();- }-- try {- const entries = await fs.listDirectoryDetailed(this.currentPath_);-- return entries- .filter(e => !e.name.startsWith('.') && !e.name.endsWith('.meta'))- .sort((a, b) => {- if (a.isDirectory !== b.isDirectory) {- return a.isDirectory ? -1 : 1;- }- return a.name.localeCompare(b.name);- })- .map(e => ({- name: e.name,- path: joinPath(this.currentPath_, e.name),- type: getAssetType(e),- }));- } catch (err) {- console.error('Failed to load folder items:', err);- return this.getFallbackItems();- }- }-- private getFallbackItems(): AssetItem[] {- const currentFolder = this.findFolder(this.rootFolder_, this.currentPath_);- if (!currentFolder) return [];-- return currentFolder.children.map((child) => ({- name: child.name,- path: child.path,- type: 'folder' as const,- }));- }-- private async importDroppedFiles(files: FileList): Promise<void> {- const fs = getNativeFS();- if (!fs || !this.currentPath_) return;-- for (const file of Array.from(files)) {- const destPath = joinPath(this.currentPath_, file.name);- const exists = await fs.exists(destPath);- if (exists) {- const overwrite = await showConfirmDialog({- title: 'File Exists',- message: `"${file.name}" already exists. Overwrite?`,- confirmText: 'Overwrite',- });- if (!overwrite) continue;- }-- const buffer = await file.arrayBuffer();- await fs.writeBinaryFile(destPath, new Uint8Array(buffer));- }- }-- private async saveDroppedEntityAsPrefab(entityId: number): Promise<void> {- const entityData = this.store_.getEntityData(entityId);- if (!entityData) return;-- const targetDir = this.currentPath_;- if (!targetDir) return;-- if (this.rootFolder_) {- const assetsDir = joinPath(this.rootFolder_.path, 'assets');- if (!targetDir.startsWith(assetsDir)) {- showErrorToast('Cannot save prefab outside assets directory', 'Please navigate to the assets folder first');- return;- }- }-- const platform = getPlatformAdapter();-- const name = await showInputDialog({- title: 'Save as Prefab',- placeholder: 'Prefab name',- defaultValue: entityData.name,- confirmText: 'Save',- validator: async (value) => {- if (!value.trim()) return 'Name is required';- if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {- return 'Name contains invalid characters';- }- const fileName = value.trim().endsWith('.esprefab')- ? value.trim()- : `${value.trim()}.esprefab`;- const fullPath = joinPath(targetDir, fileName);- if (await platform.exists(fullPath)) {- return 'A file with this name already exists';- }- return null;- },- });-- if (!name) return;-- const fileName = name.trim().endsWith('.esprefab')- ? name.trim()- : `${name.trim()}.esprefab`;- const filePath = joinPath(targetDir, fileName);-- const success = await this.store_.saveAsPrefab(entityId, filePath);- if (success) {- this.refresh();- } else {- showErrorToast('Failed to save prefab', filePath);- }- }-}+export { ContentBrowserPanel } from './content-browser/ContentBrowserPanel';+export type { ContentBrowserOptions } from './content-browser/ContentBrowserTypes';diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.tsindex 0683bdf65..730c307a1 100644--- a/editor/src/panels/HierarchyPanel.ts+++ b/editor/src/panels/HierarchyPanel.ts@@ -1,1337 +1 @@-/**- * @file HierarchyPanel.ts- * @brief Entity hierarchy tree panel- */--import type { Entity } from 'esengine';-import type { EntityData } from '../types/SceneTypes';-import type { EditorStore, DirtyFlag } from '../store/EditorStore';-import { icons } from '../utils/icons';-import { getGlobalPathResolver } from '../asset';-import { getInitialComponentData } from '../schemas/ComponentSchemas';-import { showContextMenu, type ContextMenuItem } from '../ui/ContextMenu';-import { getContextMenuItems, type ContextMenuContext } from '../ui/ContextMenuRegistry';-import { getEditorContext, getEditorInstance } from '../context/EditorContext';-import { getAssetDatabase, isUUID } from '../asset/AssetDatabase';-import { getPlatformAdapter } from '../platform/PlatformAdapter';-import { generateUniqueName } from '../utils/naming';-import { showInputDialog } from '../ui/dialog';-import { joinPath, getParentDir } from '../utils/path';-import { hasAnyOverrides } from '../prefab';-import { fuzzyFilter, type FuzzyMatch } from '../utils/fuzzy';-import { escapeHtml } from '../utils/html';--type DropPosition = 'before' | 'after' | 'inside';--const ROW_HEIGHT = 22;-const OVERSCAN = 5;-const SLOW_DOUBLE_CLICK_MIN = 300;-const SLOW_DOUBLE_CLICK_MAX = 800;--interface FlattenedRow {- entity: EntityData;- depth: number;- hasChildren: boolean;- isExpanded: boolean;-}--// =============================================================================-// HierarchyPanel-// =============================================================================--export class HierarchyPanel {- private container_: HTMLElement;- private store_: EditorStore;- private treeContainer_: HTMLElement;- private searchInput_: HTMLInputElement | null = null;- private footerContainer_: HTMLElement | null = null;- private prefabEditBar_: HTMLElement | null = null;- private unsubscribe_: (() => void) | null = null;- private searchFilter_: string = '';- private searchResults_: Array<{ entity: EntityData; match: FuzzyMatch }> = [];- private selectedResultIndex_: number = -1;- private expandedIds_: Set<number> = new Set();- private lastSelectedEntity_: Entity | null = null;- private flatRows_: FlattenedRow[] = [];- private scrollContent_!: HTMLElement;- private visibleWindow_!: HTMLElement;- private scrollRafId_: number = 0;- private lastVisibleStart_: number = -1;- private lastVisibleEnd_: number = -1;- private dragOverEntityId_: number | null = null;- private dropPosition_: DropPosition | null = null;- private draggingEntityId_: number | null = null;- private boundOnScroll_: (() => void) | null = null;- private renamingEntityId_: number | null = null;- private lastClickEntityId_: number | null = null;- private lastClickTime_: number = 0;- constructor(container: HTMLElement, store: EditorStore) {- this.container_ = container;- this.store_ = store;-- this.container_.className = 'es-hierarchy-panel';- this.container_.innerHTML = `- <div class="es-panel-header">- <span class="es-panel-title">${icons.list(14)} Hierarchy</span>- </div>- <div class="es-prefab-edit-bar" style="display: none;">- <button class="es-prefab-back-btn">${icons.chevronRight(12)} Back to Scene</button>- <span class="es-prefab-edit-name">${icons.package(12)} </span>- </div>- <div class="es-hierarchy-toolbar">- <input type="text" class="es-input es-hierarchy-search" placeholder="Search...">- <button class="es-btn es-btn-icon" data-action="collapse-all" title="Collapse All">${icons.chevronRight(12)}</button>- <button class="es-btn es-btn-icon" data-action="expand-all" title="Expand All">${icons.chevronDown(12)}</button>- <button class="es-btn es-btn-icon" data-action="add" title="Create Entity">${icons.plus()}</button>- <button class="es-btn es-btn-icon" data-action="duplicate" title="Duplicate">${icons.copy()}</button>- </div>- <div class="es-hierarchy-columns">- <span class="es-hierarchy-col-visibility">${icons.eye(12)}</span>- <span class="es-hierarchy-col-lock">${icons.star(12)}</span>- <span class="es-hierarchy-col-label">Item Label</span>- <span class="es-hierarchy-col-type">Type</span>- </div>- <div class="es-hierarchy-tree" role="tree"></div>- <div class="es-hierarchy-footer">0 entities</div>- `;-- this.treeContainer_ = this.container_.querySelector('.es-hierarchy-tree')!;- this.treeContainer_.tabIndex = 0;- this.scrollContent_ = document.createElement('div');- this.scrollContent_.className = 'es-hierarchy-scroll-content';- this.visibleWindow_ = document.createElement('div');- this.visibleWindow_.className = 'es-hierarchy-visible-window';- this.scrollContent_.appendChild(this.visibleWindow_);- this.treeContainer_.appendChild(this.scrollContent_);- this.boundOnScroll_ = () => this.onScroll();- this.treeContainer_.addEventListener('scroll', this.boundOnScroll_);- this.searchInput_ = this.container_.querySelector('.es-hierarchy-search');- this.footerContainer_ = this.container_.querySelector('.es-hierarchy-footer');- this.prefabEditBar_ = this.container_.querySelector('.es-prefab-edit-bar');-- const backBtn = this.container_.querySelector('.es-prefab-back-btn');- backBtn?.addEventListener('click', () => {- this.store_.exitPrefabEditMode();- });-- this.setupEvents();- this.unsubscribe_ = store.subscribe((_state, dirtyFlags) => this.onStoreNotify(dirtyFlags));- this.render();- }-- dispose(): void {- if (this.unsubscribe_) {- this.unsubscribe_();- this.unsubscribe_ = null;- }- if (this.scrollRafId_) {- cancelAnimationFrame(this.scrollRafId_);- this.scrollRafId_ = 0;- }- if (this.boundOnScroll_) {- this.treeContainer_.removeEventListener('scroll', this.boundOnScroll_);- this.boundOnScroll_ = null;- }- }-- private onStoreNotify(dirtyFlags?: ReadonlySet<DirtyFlag>): void {- if (dirtyFlags && !dirtyFlags.has('scene') && !dirtyFlags.has('hierarchy') && !dirtyFlags.has('selection')) {- return;- }-- const needsRebuild = !dirtyFlags || dirtyFlags.has('scene') || dirtyFlags.has('hierarchy');-- if (needsRebuild) {- this.render();- } else {- this.renderVisibleRows();- this.updateFooter();- }- }-- private setupEvents(): void {- const addBtn = this.container_.querySelector('[data-action="add"]');- addBtn?.addEventListener('click', () => {- const entity = this.store_.createEntity();- this.store_.addComponent(entity, 'LocalTransform', getInitialComponentData('LocalTransform'));- });-- const dupBtn = this.container_.querySelector('[data-action="duplicate"]');- dupBtn?.addEventListener('click', () => {- const selected = this.store_.selectedEntity;- if (selected !== null) {- this.duplicateEntity(selected);- }- });-- const collapseAllBtn = this.container_.querySelector('[data-action="collapse-all"]');- collapseAllBtn?.addEventListener('click', () => {- this.expandedIds_.clear();- this.render();- });-- const expandAllBtn = this.container_.querySelector('[data-action="expand-all"]');- expandAllBtn?.addEventListener('click', () => {- for (const entity of this.store_.scene.entities) {- if (entity.children.length > 0) {- this.expandedIds_.add(entity.id);- }- }- this.render();- });-- this.searchInput_?.addEventListener('input', () => {- this.searchFilter_ = this.searchInput_?.value ?? '';- this.performSearch();- this.render();- });-- this.searchInput_?.addEventListener('keydown', (e) => {- if (e.key === 'ArrowDown') {- e.preventDefault();- this.selectNextResult();- } else if (e.key === 'ArrowUp') {- e.preventDefault();- this.selectPreviousResult();- } else if (e.key === 'Enter') {- e.preventDefault();- this.focusSelectedResult();- } else if (e.key === 'Escape') {- this.clearSearch();- }- });-- this.treeContainer_.addEventListener('click', (e) => {- const target = e.target as HTMLElement;-- if (target.closest('.es-hierarchy-rename-input')) return;-- const visibilityBtn = target.closest('.es-hierarchy-visibility') as HTMLElement;- if (visibilityBtn) {- e.stopPropagation();- const item = visibilityBtn.closest('.es-hierarchy-item') as HTMLElement;- const entityId = parseInt(item?.dataset.entityId ?? '', 10);- if (!isNaN(entityId)) {- this.store_.toggleVisibility(entityId);- }- return;- }-- const expandBtn = target.closest('.es-hierarchy-expand') as HTMLElement;- if (expandBtn) {- e.stopPropagation();- const row = expandBtn.closest('.es-hierarchy-row');- const item = row?.parentElement as HTMLElement;- const entityId = parseInt(item?.dataset.entityId ?? '', 10);- if (!isNaN(entityId)) {- if (this.expandedIds_.has(entityId)) {- this.expandedIds_.delete(entityId);- } else {- this.expandedIds_.add(entityId);- }- this.render();- }- return;- }-- const row = target.closest('.es-hierarchy-row');- const item = row?.parentElement as HTMLElement;- if (!item?.classList.contains('es-hierarchy-item')) return;-- const entityId = parseInt(item.dataset.entityId ?? '', 10);- if (isNaN(entityId)) return;-- const now = Date.now();- const timeSinceLastClick = now - this.lastClickTime_;- const sameEntity = this.lastClickEntityId_ === entityId;- const wasSelected = this.store_.selectedEntities.has(entityId);-- if (e.shiftKey && this.lastSelectedEntity_ !== null) {- this.selectRangeFromFlatRows(this.lastSelectedEntity_ as number, entityId);- this.lastSelectedEntity_ = entityId as Entity;- } else if (e.ctrlKey || e.metaKey) {- this.store_.selectEntity(entityId as Entity, 'toggle');- this.lastSelectedEntity_ = entityId as Entity;- } else {- if (sameEntity && wasSelected && !e.shiftKey && !e.ctrlKey && !e.metaKey- && timeSinceLastClick >= SLOW_DOUBLE_CLICK_MIN- && timeSinceLastClick <= SLOW_DOUBLE_CLICK_MAX) {- this.startInlineRename(entityId);- } else {- this.store_.selectEntity(entityId as Entity, 'replace');- this.lastSelectedEntity_ = entityId as Entity;- }- }-- this.lastClickEntityId_ = entityId;- this.lastClickTime_ = now;- });-- this.treeContainer_.addEventListener('dblclick', (e) => {- const target = e.target as HTMLElement;- if (target.closest('.es-hierarchy-rename-input')) return;- const item = target.closest('.es-hierarchy-item') as HTMLElement;- if (!item) return;-- const entityId = parseInt(item.dataset.entityId ?? '', 10);- if (!isNaN(entityId)) {- this.lastClickEntityId_ = null;- this.lastClickTime_ = 0;- this.store_.focusEntity(entityId);- }- });-- this.treeContainer_.addEventListener('contextmenu', (e) => {- e.preventDefault();- const target = e.target as HTMLElement;- const item = target.closest('.es-hierarchy-item') as HTMLElement;-- if (item) {- const entityId = parseInt(item.dataset.entityId ?? '', 10);- if (!isNaN(entityId)) {- this.showEntityContextMenu(e.clientX, e.clientY, entityId as Entity);- }- } else {- this.showEntityContextMenu(e.clientX, e.clientY, null);- }- });-- this.treeContainer_.addEventListener('keydown', (e) => {- if (this.renamingEntityId_ !== null) {- return;- }-- if (e.key === 'F2') {- e.preventDefault();- const selected = this.store_.selectedEntity;- if (selected !== null) {- this.startInlineRename(selected as number);- }- return;- }-- if ((e.key === 'a' || e.key === 'A') && (e.ctrlKey || e.metaKey)) {- e.preventDefault();- const roots = this.store_.scene.entities.filter(ent => ent.parent === null);- if (roots.length > 0) {- this.store_.selectEntities(roots.map(ent => ent.id));- }- return;- }-- if (e.key === 'Delete' || e.key === 'Backspace') {- e.preventDefault();- if (this.store_.selectedEntities.size > 1) {- this.store_.deleteSelectedEntities();- } else {- const selected = this.store_.selectedEntity;- if (selected !== null) {- this.store_.deleteEntity(selected);- }- }- return;- }-- const selected = this.store_.selectedEntity;- const selectedIndex = selected !== null- ? this.flatRows_.findIndex(r => r.entity.id === (selected as number))- : -1;-- switch (e.key) {- case 'ArrowDown': {- e.preventDefault();- const nextIndex = selectedIndex + 1;- if (nextIndex < this.flatRows_.length) {- const nextEntity = this.flatRows_[nextIndex].entity;- this.store_.selectEntity(nextEntity.id as Entity, 'replace');- this.lastSelectedEntity_ = nextEntity.id as Entity;- this.scrollToEntity(nextEntity.id);- }- break;- }- case 'ArrowUp': {- e.preventDefault();- const prevIndex = selectedIndex - 1;- if (prevIndex >= 0) {- const prevEntity = this.flatRows_[prevIndex].entity;- this.store_.selectEntity(prevEntity.id as Entity, 'replace');- this.lastSelectedEntity_ = prevEntity.id as Entity;- this.scrollToEntity(prevEntity.id);- }- break;- }- case 'ArrowRight': {- e.preventDefault();- if (selectedIndex === -1) break;- const row = this.flatRows_[selectedIndex];- if (row.hasChildren && !row.isExpanded) {- this.expandedIds_.add(row.entity.id);- this.render();- } else if (row.hasChildren && row.isExpanded) {- const nextIndex = selectedIndex + 1;- if (nextIndex < this.flatRows_.length) {- const child = this.flatRows_[nextIndex].entity;- this.store_.selectEntity(child.id as Entity, 'replace');- this.lastSelectedEntity_ = child.id as Entity;- this.scrollToEntity(child.id);- }- }- break;- }- case 'ArrowLeft': {- e.preventDefault();- if (selectedIndex === -1) break;- const row = this.flatRows_[selectedIndex];- if (row.hasChildren && row.isExpanded) {- this.expandedIds_.delete(row.entity.id);- this.render();- } else if (row.entity.parent !== null) {- const parentIdx = this.flatRows_.findIndex(r => r.entity.id === row.entity.parent);- if (parentIdx !== -1) {- const parentEntity = this.flatRows_[parentIdx].entity;- this.store_.selectEntity(parentEntity.id as Entity, 'replace');- this.lastSelectedEntity_ = parentEntity.id as Entity;- this.scrollToEntity(parentEntity.id);- }- }- break;- }- case 'Home': {- e.preventDefault();- if (this.flatRows_.length > 0) {- const first = this.flatRows_[0].entity;- this.store_.selectEntity(first.id as Entity, 'replace');- this.lastSelectedEntity_ = first.id as Entity;- this.scrollToEntity(first.id);- }- break;- }- case 'End': {- e.preventDefault();- if (this.flatRows_.length > 0) {- const last = this.flatRows_[this.flatRows_.length - 1].entity;- this.store_.selectEntity(last.id as Entity, 'replace');- this.lastSelectedEntity_ = last.id as Entity;- this.scrollToEntity(last.id);- }- break;- }- }- });-- this.setupDragAndDrop();- }-- private selectRangeFromFlatRows(fromEntity: number, toEntity: number): void {- const fromIndex = this.flatRows_.findIndex(r => r.entity.id === fromEntity);- const toIndex = this.flatRows_.findIndex(r => r.entity.id === toEntity);-- if (fromIndex === -1 || toIndex === -1) return;-- const start = Math.min(fromIndex, toIndex);- const end = Math.max(fromIndex, toIndex);- const ids = this.flatRows_.slice(start, end + 1).map(r => r.entity.id);- this.store_.selectEntities(ids);- }-- private startInlineRename(entityId: number): void {- const entityData = this.store_.getEntityData(entityId);- if (!entityData) return;-- this.renamingEntityId_ = entityId;-- const item = this.visibleWindow_.querySelector(`[data-entity-id="${entityId}"]`);- if (!item) return;-- const nameSpan = item.querySelector('.es-hierarchy-name') as HTMLElement;- if (!nameSpan) return;-- const input = document.createElement('input');- input.type = 'text';- input.className = 'es-hierarchy-rename-input';- input.value = entityData.name;- input.select();-- const commitRename = () => {- const newName = input.value.trim();- if (newName && newName !== entityData.name) {- this.store_.renameEntity(entityId as Entity, newName);- }- this.renamingEntityId_ = null;- this.renderVisibleRows();- };-- const cancelRename = () => {- this.renamingEntityId_ = null;- this.renderVisibleRows();- };-- input.addEventListener('keydown', (e) => {- if (e.key === 'Enter') {- e.preventDefault();- commitRename();- } else if (e.key === 'Escape') {- e.preventDefault();- cancelRename();- }- e.stopPropagation();- });-- input.addEventListener('blur', commitRename, { once: true });-- nameSpan.textContent = '';- nameSpan.appendChild(input);- input.focus();- input.select();- }-- private setupDragAndDrop(): void {- this.treeContainer_.addEventListener('dragstart', (e) => {- const target = e.target as HTMLElement;- const row = target.closest('.es-hierarchy-row') as HTMLElement;- const item = row?.parentElement as HTMLElement;- if (!item?.classList.contains('es-hierarchy-item')) return;-- const entityId = item.dataset.entityId;- if (!entityId) return;-- e.dataTransfer!.setData('application/esengine-entity', entityId);- e.dataTransfer!.effectAllowed = 'move';- this.draggingEntityId_ = parseInt(entityId, 10);- item.classList.add('es-dragging');-- const onDragEnd = () => {- row.removeEventListener('dragend', onDragEnd);- this.draggingEntityId_ = null;- this.dragOverEntityId_ = null;- this.dropPosition_ = null;- this.treeContainer_.classList.remove('es-drag-over');- this.renderVisibleRows();- };- row.addEventListener('dragend', onDragEnd);- });-- this.treeContainer_.addEventListener('dragover', (e) => {- const types = e.dataTransfer?.types ?? [];- const hasAssetData = Array.from(types).includes('application/esengine-asset');- const hasEntityData = Array.from(types).includes('application/esengine-entity');-- if (!hasAssetData && !hasEntityData) return;-- e.preventDefault();-- const target = e.target as HTMLElement;- const item = target.closest('.es-hierarchy-item') as HTMLElement;- const entityId = item ? parseInt(item.dataset.entityId ?? '', 10) : NaN;- const newEntityId = isNaN(entityId) ? null : entityId;-- if (hasAssetData) {- e.dataTransfer!.dropEffect = 'copy';- if (newEntityId !== this.dragOverEntityId_ || this.dropPosition_ !== null) {- this.dragOverEntityId_ = newEntityId;- this.dropPosition_ = null;- this.treeContainer_.classList.toggle('es-drag-over', !item);- this.renderVisibleRows();- }- return;- }-- e.dataTransfer!.dropEffect = 'move';-- if (!item) {- if (this.dragOverEntityId_ !== null) {- this.dragOverEntityId_ = null;- this.dropPosition_ = null;- this.renderVisibleRows();- }- this.treeContainer_.classList.add('es-drag-over');- return;- }-- this.treeContainer_.classList.remove('es-drag-over');- const position = this.getDropPosition(e, item);- if (newEntityId !== this.dragOverEntityId_ || position !== this.dropPosition_) {- this.dragOverEntityId_ = newEntityId;- this.dropPosition_ = position;- this.renderVisibleRows();- }- });-- this.treeContainer_.addEventListener('dragleave', (e) => {- const relatedTarget = e.relatedTarget as HTMLElement;- if (this.treeContainer_.contains(relatedTarget)) return;- this.dragOverEntityId_ = null;- this.dropPosition_ = null;- this.treeContainer_.classList.remove('es-drag-over');- this.renderVisibleRows();- });-- this.treeContainer_.addEventListener('drop', (e) => {- e.preventDefault();-- const assetDataStr = e.dataTransfer?.getData('application/esengine-asset');- const entityIdStr = e.dataTransfer?.getData('application/esengine-entity');- const target = e.target as HTMLElement;- const dropItem = target.closest('.es-hierarchy-item') as HTMLElement;- const dropTargetId = dropItem ? parseInt(dropItem.dataset.entityId ?? '', 10) : NaN;- const dropPos = dropItem ? this.getDropPosition(e, dropItem) : null;-- this.dragOverEntityId_ = null;- this.dropPosition_ = null;- this.draggingEntityId_ = null;- this.treeContainer_.classList.remove('es-drag-over');-- if (assetDataStr) {- let assetData: { type: string; path: string; name: string };- try {- assetData = JSON.parse(assetDataStr);- } catch {- return;- }- const parentEntity = !isNaN(dropTargetId) ? dropTargetId as Entity : null;- this.createEntityFromAsset(assetData, parentEntity);- return;- }-- if (!entityIdStr) return;-- const draggedId = parseInt(entityIdStr, 10);- if (isNaN(draggedId)) return;-- if (isNaN(dropTargetId)) {- const scene = this.store_.scene;- const roots = scene.entities.filter(e => e.parent === null);- this.store_.moveEntity(draggedId as Entity, null, roots.length);- return;- }-- if (dropTargetId === draggedId || !dropPos) return;- if (this.isDescendantOf(draggedId, dropTargetId)) return;-- const targetEntity = this.store_.getEntityData(dropTargetId);- if (!targetEntity) return;-- if (dropPos === 'inside') {- this.store_.moveEntity(draggedId as Entity, dropTargetId as Entity, targetEntity.children.length);- this.expandedIds_.add(dropTargetId);- } else {- const parentId = targetEntity.parent;- if (parentId !== null) {- const parent = this.store_.getEntityData(parentId);- if (!parent) return;- let idx = parent.children.indexOf(dropTargetId);- if (dropPos === 'after') idx++;- const draggedIdx = parent.children.indexOf(draggedId);- if (draggedIdx !== -1 && draggedIdx < idx) idx--;- this.store_.moveEntity(draggedId as Entity, parentId as Entity, idx);- } else {- const scene = this.store_.scene;- const roots = scene.entities.filter(en => en.parent === null);- let idx = roots.findIndex(en => en.id === dropTargetId);- if (dropPos === 'after') idx++;- const draggedIdx = roots.findIndex(en => en.id === draggedId);- if (draggedIdx !== -1 && draggedIdx < idx) idx--;- this.store_.moveEntity(draggedId as Entity, null, idx);- }- }- });- }-- private getDropPosition(e: DragEvent, item: HTMLElement): DropPosition {- const row = item.querySelector('.es-hierarchy-row') as HTMLElement;- const rect = row.getBoundingClientRect();- const y = e.clientY - rect.top;- const ratio = y / rect.height;- if (ratio < 0.25) return 'before';- if (ratio > 0.75) return 'after';- return 'inside';- }-- private isDescendantOf(entityId: number, ancestorId: number): boolean {- let current: number | null = entityId;- while (current !== null) {- if (current === ancestorId) return true;- const entity = this.store_.getEntityData(current);- current = entity?.parent ?? null;- }- return false;- }-- private async createEntityFromAsset(- asset: { type: string; path: string; name: string },- parent: Entity | null- ): Promise<void> {- if (asset.type === 'prefab') {- await this.createEntityFromPrefab(asset.path, parent);- return;- }-- const baseName = asset.name.replace(/\.[^.]+$/, '');-- if (asset.type === 'spine' || asset.type === 'json') {- const ext = asset.name.substring(asset.name.lastIndexOf('.')).toLowerCase();- if (ext === '.atlas') return;-- const skeletonPath = this.toRelativePath(asset.path);- const atlasPath = await this.findAtlasFile(skeletonPath);-- if (!atlasPath) {- console.error(`[HierarchyPanel] No atlas file found for: ${skeletonPath}`);- alert(`No atlas file found.\nPlease ensure there is an .atlas file in the same directory as the skeleton file.`);- return;- }-- const newEntity = this.store_.createEntity(baseName, parent);-- this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));-- this.store_.addComponent(newEntity, 'SpineAnimation', {- ...getInitialComponentData('SpineAnimation'),- skeletonPath,- atlasPath,- });- } else if (asset.type === 'image') {- const newEntity = this.store_.createEntity(baseName, parent);-- this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));-- this.store_.addComponent(newEntity, 'Sprite', {- ...getInitialComponentData('Sprite'),- texture: this.toRelativePath(asset.path),- });-- this.loadImageSize(asset.path).then(size => {- if (size) {- this.store_.updateProperty(newEntity, 'Sprite', 'size', { x: 32, y: 32 }, size);- }- });- }- }-- private toRelativePath(absolutePath: string): string {- return getGlobalPathResolver().toRelativePath(absolutePath);- }-- private async findAtlasFile(skeletonPath: string): Promise<string | null> {- const pathResolver = getGlobalPathResolver();-- const sameNameAtlas = skeletonPath.replace(/\.(json|skel)$/i, '.atlas');- const validation = await pathResolver.validatePath(sameNameAtlas);- if (validation.exists) {- return sameNameAtlas;- }-- const dir = skeletonPath.substring(0, skeletonPath.lastIndexOf('/'));- const absoluteDir = pathResolver.toAbsolutePath(dir);-- const fs = getEditorContext().fs;- if (!fs) {- return null;- }-- try {- const entries = await fs.listDirectoryDetailed(absoluteDir);- const atlasFiles = entries- .filter(e => e.name.endsWith('.atlas'))- .map(e => e.name);-- if (atlasFiles.length === 1) {- return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];- }-- if (atlasFiles.length > 1) {- const baseName = skeletonPath- .substring(skeletonPath.lastIndexOf('/') + 1)- .replace(/\.(json|skel)$/i, '');-- const matching = atlasFiles.find((name: string) =>- name.replace('.atlas', '').toLowerCase().includes(baseName.toLowerCase().split('-')[0])- );-- if (matching) {- return dir ? `${dir}/${matching}` : matching;- }-- return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];- }- } catch (err) {- console.warn('[HierarchyPanel] Failed to scan directory for atlas files:', err);- }-- return null;- }-- private loadImageSize(absolutePath: string): Promise<{ x: number; y: number } | null> {- return new Promise((resolve) => {- const img = new Image();- img.onload = () => resolve({ x: img.naturalWidth, y: img.naturalHeight });- img.onerror = () => resolve(null);- img.src = getPlatformAdapter().convertFilePathToUrl(absolutePath);- });- }-- private render(): void {- const scene = this.store_.scene;- const selectedEntity = this.store_.selectedEntity;-- if (this.prefabEditBar_) {- if (this.store_.isEditingPrefab) {- this.prefabEditBar_.style.display = '';- const nameEl = this.prefabEditBar_.querySelector('.es-prefab-edit-name');- if (nameEl) {- const rawPath = this.store_.prefabEditingPath ?? '';- const path = isUUID(rawPath) ? (getAssetDatabase().getPath(rawPath) ?? rawPath) : rawPath;- const fileName = path.split('/').pop() ?? path;- nameEl.innerHTML = `${icons.package(12)} ${escapeHtml(fileName)}`;- }- } else {- this.prefabEditBar_.style.display = 'none';- }- }-- const selectionChanged = selectedEntity !== null && selectedEntity !== this.lastSelectedEntity_;- if (selectionChanged) {- this.expandAncestors(selectedEntity);- }- this.lastSelectedEntity_ = selectedEntity;-- this.buildFlatRows();- this.scrollContent_.style.height = `${this.flatRows_.length * ROW_HEIGHT}px`;- this.lastVisibleStart_ = -1;- this.lastVisibleEnd_ = -1;- this.renderVisibleRows();-- this.updateFooter();-- if (selectionChanged) {- this.scrollToEntity(selectedEntity as number);- }- }-- private updateFooter(): void {- if (!this.footerContainer_) return;-- if (this.searchFilter_) {- const count = this.searchResults_.length;- this.footerContainer_.textContent = `${count} ${count === 1 ? 'match' : 'matches'}`;- } else {- const count = this.store_.scene.entities.length;- this.footerContainer_.textContent = `${count} ${count === 1 ? 'entity' : 'entities'}`;- }- }-- private expandAncestors(entityId: Entity): void {- const entity = this.store_.getEntityData(entityId as number);- if (!entity || entity.parent === null) return;-- let parentId: number | null = entity.parent;- while (parentId !== null) {- this.expandedIds_.add(parentId);- const parent = this.store_.getEntityData(parentId);- parentId = parent?.parent ?? null;- }- }-- private getEntityIcon(entity: EntityData): string {- if (entity.prefab?.isRoot) return icons.package(12);-- const hasCamera = entity.components.some(c => c.type === 'Camera');- const hasSprite = entity.components.some(c => c.type === 'Sprite');- const hasText = entity.components.some(c => c.type === 'Text');- const hasBitmapText = entity.components.some(c => c.type === 'BitmapText');- const hasTextInput = entity.components.some(c => c.type === 'TextInput');- const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');-- if (hasCamera) return icons.camera(12);- if (hasSpine) return icons.bone(12);- if (hasText || hasBitmapText || hasTextInput) return icons.type(12);- if (hasSprite) return icons.image(12);- return icons.box(12);- }-- private getEntityType(entity: EntityData): string {- const hasCamera = entity.components.some(c => c.type === 'Camera');- const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');- if (hasCamera) return 'Camera';- if (hasSpine) return 'Spine';- return 'Entity';- }-- private performSearch(): void {- if (!this.searchFilter_) {- this.searchResults_ = [];- this.selectedResultIndex_ = -1;- return;- }-- const scene = this.store_.scene;- const results = fuzzyFilter(- scene.entities,- this.searchFilter_,- (entity) => entity.name- );-- this.searchResults_ = results.map(r => ({ entity: r.item, match: r.match }));- this.selectedResultIndex_ = this.searchResults_.length > 0 ? 0 : -1;- }-- private selectNextResult(): void {- if (this.searchResults_.length === 0) return;- this.selectedResultIndex_ = (this.selectedResultIndex_ + 1) % this.searchResults_.length;- this.render();- }-- private selectPreviousResult(): void {- if (this.searchResults_.length === 0) return;- this.selectedResultIndex_ = (this.selectedResultIndex_ - 1 + this.searchResults_.length) % this.searchResults_.length;- this.render();- }-- private focusSelectedResult(): void {- if (this.selectedResultIndex_ === -1 || this.selectedResultIndex_ >= this.searchResults_.length) return;- const result = this.searchResults_[this.selectedResultIndex_];- this.store_.selectEntity(result.entity.id as Entity);- this.scrollToEntity(result.entity.id);- }-- private clearSearch(): void {- if (this.searchInput_) {- this.searchInput_.value = '';- }- this.searchFilter_ = '';- this.searchResults_ = [];- this.selectedResultIndex_ = -1;- this.render();- }-- private buildFlatRows(): void {- this.flatRows_ = [];- const scene = this.store_.scene;-- if (this.searchFilter_) {- for (const result of this.searchResults_) {- this.flatRows_.push({- entity: result.entity,- depth: 0,- hasChildren: false,- isExpanded: false,- });- }- return;- }-- const roots = scene.entities.filter(e => e.parent === null);- this.flattenDFS(roots, 0);- }-- private flattenDFS(entities: EntityData[], depth: number): void {- for (const entity of entities) {- const children = entity.children- .map(id => this.store_.getEntityData(id))- .filter((e): e is EntityData => e !== null);- const hasChildren = children.length > 0;- const isExpanded = this.expandedIds_.has(entity.id);-- this.flatRows_.push({ entity, depth, hasChildren, isExpanded });-- if (hasChildren && isExpanded) {- this.flattenDFS(children, depth + 1);- }- }- }-- private getVisibleRange(): { start: number; end: number } {- const scrollTop = this.treeContainer_.scrollTop;- const viewHeight = this.treeContainer_.clientHeight;- const totalRows = this.flatRows_.length;-- let start = Math.floor(scrollTop / ROW_HEIGHT) - OVERSCAN;- let end = Math.ceil((scrollTop + viewHeight) / ROW_HEIGHT) + OVERSCAN;-- return { start: Math.max(0, start), end: Math.min(totalRows, end) };- }-- private renderVisibleRows(): void {- const { start, end } = this.getVisibleRange();- const selectedEntity = this.store_.selectedEntity;-- this.visibleWindow_.style.transform = `translateY(${start * ROW_HEIGHT}px)`;-- let html = '';- for (let i = start; i < end; i++) {- html += this.renderSingleRow(this.flatRows_[i], selectedEntity);- }- this.visibleWindow_.innerHTML = html;-- this.lastVisibleStart_ = start;- this.lastVisibleEnd_ = end;-- if (this.renamingEntityId_ !== null) {- const item = this.visibleWindow_.querySelector(`[data-entity-id="${this.renamingEntityId_}"]`);- if (item) {- this.startInlineRename(this.renamingEntityId_);- }- }- }-- private renderSingleRow(row: FlattenedRow, selectedEntity: Entity | null): string {- const { entity, depth, hasChildren, isExpanded } = row;- const icon = this.getEntityIcon(entity);- const type = this.getEntityType(entity);- const expandIcon = isExpanded ? icons.chevronDown(10) : icons.chevronRight(10);- const isVisible = this.store_.isEntityVisible(entity.id);- const visibilityIcon = isVisible ? icons.eye(10) : icons.eyeOff(10);-- let itemClass = 'es-hierarchy-item';- if (this.store_.selectedEntities.has(entity.id)) itemClass += ' es-selected';- if (!isVisible) itemClass += ' es-entity-hidden';- if (entity.prefab?.isRoot) itemClass += ' es-prefab-root';- else if (entity.prefab) itemClass += ' es-prefab-child';- if (hasChildren) itemClass += ' es-has-children';- if (isExpanded) itemClass += ' es-expanded';- if (entity.id === this.draggingEntityId_) itemClass += ' es-dragging';- if (entity.id === this.dragOverEntityId_) {- if (this.dropPosition_) {- itemClass += ` es-drop-${this.dropPosition_}`;- } else {- itemClass += ' es-drag-over';- }- }-- const match = this.searchFilter_ ? this.searchResults_.find(r => r.entity.id === entity.id)?.match : null;- if (this.searchFilter_ && match) {- const resultIdx = this.searchResults_.findIndex(r => r.entity.id === entity.id);- if (resultIdx === this.selectedResultIndex_) {- itemClass += ' es-search-selected';- }- }-- const nameHtml = this.renderEntityName(entity.name, match);-- const ariaExpanded = hasChildren ? ` aria-expanded="${isExpanded}"` : '';-- return `<div class="${itemClass}" data-entity-id="${entity.id}" role="treeitem"${ariaExpanded}>- <div class="es-hierarchy-row" draggable="true" style="padding-left: ${8 + depth * 16}px">- ${hasChildren ? `<span class="es-hierarchy-expand">${expandIcon}</span>` : '<span class="es-hierarchy-spacer"></span>'}- <span class="es-hierarchy-visibility">${visibilityIcon}</span>- <span class="es-hierarchy-icon">${icon}</span>- <span class="es-hierarchy-name">${nameHtml}</span>- <span class="es-hierarchy-type">${type}</span>- </div>- </div>`;- }-- private renderEntityName(name: string, match: FuzzyMatch | null | undefined): string {- if (!match || match.matches.length === 0) {- return escapeHtml(name);- }-- let html = '';- for (let i = 0; i < name.length; i++) {- if (match.matches.includes(i)) {- html += `<mark class="es-search-highlight">${escapeHtml(name[i])}</mark>`;- } else {- html += escapeHtml(name[i]);- }- }- return html;- }-- private scrollToEntity(entityId: number): void {- const index = this.flatRows_.findIndex(r => r.entity.id === entityId);- if (index === -1) return;-- const targetTop = index * ROW_HEIGHT;- const targetBottom = targetTop + ROW_HEIGHT;- const scrollTop = this.treeContainer_.scrollTop;- const viewHeight = this.treeContainer_.clientHeight;-- if (targetTop < scrollTop) {- this.treeContainer_.scrollTop = targetTop;- } else if (targetBottom > scrollTop + viewHeight) {- this.treeContainer_.scrollTop = targetBottom - viewHeight;- }- }-- private onScroll(): void {- if (this.scrollRafId_) return;- this.scrollRafId_ = requestAnimationFrame(() => {- this.scrollRafId_ = 0;- const { start, end } = this.getVisibleRange();- if (start !== this.lastVisibleStart_ || end !== this.lastVisibleEnd_) {- this.renderVisibleRows();- }- });- }-- private showEntityContextMenu(x: number, y: number, entity: Entity | null): void {- const entityData = entity !== null ? this.store_.getEntityData(entity as number) : null;- const has = (type: string) => entityData?.components.some(c => c.type === type) ?? false;- const editor = getEditorInstance();- const multiSelected = this.store_.selectedEntities.size > 1;-- const createChildren: ContextMenuItem[] = [- { label: 'Empty Entity', icon: icons.plus(14), onClick: () => {- const newEntity = this.store_.createEntity(undefined, entity);- this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));- } },- { label: 'Sprite', icon: icons.image(14), onClick: () => this.createEntityWithComponent('Sprite', entity) },- { label: 'Text', icon: icons.type(14), onClick: () => this.createEntityWithComponent('Text', entity) },- { label: 'BitmapText', icon: icons.type(14), onClick: () => this.createEntityWithComponent('BitmapText', entity) },- { label: 'Spine', icon: icons.bone(14), onClick: () => this.createEntityWithComponent('SpineAnimation', entity) },- { label: 'Camera', icon: icons.camera(14), onClick: () => this.createEntityWithComponent('Camera', entity) },- { label: 'Canvas', icon: icons.template(14), onClick: () => this.createEntityWithComponent('Canvas', entity) },- { label: '', separator: true },- { label: 'UI', icon: icons.pointer(14), children: [- { label: 'Button', onClick: () => this.createButtonEntity(entity) },- { label: 'TextInput', onClick: () => this.createTextInputEntity(entity) },- { label: 'Panel', onClick: () => this.createPanelEntity(entity) },- { label: 'ScreenSpace Root', onClick: () => this.createScreenSpaceRootEntity(entity) },- ] },- { label: 'Physics', icon: icons.circle(14), children: [- { label: 'Box Collider', onClick: () => this.createPhysicsEntity('BoxCollider', entity) },- { label: 'Circle Collider', onClick: () => this.createPhysicsEntity('CircleCollider', entity) },- { label: 'Capsule Collider', onClick: () => this.createPhysicsEntity('CapsuleCollider', entity) },- ] },- ];-- const items: ContextMenuItem[] = [];-- if (entity !== null) {- items.push(- { label: 'Rename', icon: icons.pencil(14), onClick: () => this.startInlineRename(entity as number) },- { label: 'Duplicate', icon: icons.copy(14), onClick: () => {- if (multiSelected) {- for (const id of this.store_.selectedEntities) {- this.duplicateEntity(id as Entity);- }- } else {- this.duplicateEntity(entity);- }- } },- { label: 'Copy', icon: icons.copy(14), onClick: () => { this.store_.selectEntity(entity); editor?.copySelected(); } },- { label: 'Cut', icon: icons.copy(14), onClick: () => {- this.store_.selectEntity(entity);- editor?.copySelected();- if (multiSelected) {- this.store_.deleteSelectedEntities();- } else {- this.store_.deleteEntity(entity);- }- } },- { label: 'Paste', icon: icons.template(14), disabled: !editor?.hasClipboard(), onClick: () => { this.store_.selectEntity(entity); editor?.pasteEntity(); } },- { label: 'Delete', icon: icons.trash(14), onClick: () => {- if (multiSelected) {- this.store_.deleteSelectedEntities();- } else {- this.store_.deleteEntity(entity);- }- } },- { label: '', separator: true },- );- }-- items.push({ label: 'Create', icon: icons.plus(14), children: createChildren });-- if (entity === null) {- items.push({ label: 'Paste', icon: icons.template(14), disabled: !editor?.hasClipboard(), onClick: () => { editor?.pasteEntity(); } });- }-- if (entity !== null) {- items.push({- label: 'Add Component', children: [- { label: 'Interactable', disabled: has('Interactable'), onClick: () => this.addComponentToEntity(entity, 'Interactable') },- { label: 'Button', disabled: has('Button'), onClick: () => this.addComponentToEntity(entity, 'Button') },- { label: 'ScreenSpace', disabled: has('ScreenSpace'), onClick: () => this.addComponentToEntity(entity, 'ScreenSpace') },- { label: '', separator: true },- { label: 'RigidBody', disabled: has('RigidBody'), onClick: () => this.addComponentToEntity(entity, 'RigidBody') },- { label: 'BoxCollider', disabled: has('BoxCollider'), onClick: () => this.addComponentToEntity(entity, 'BoxCollider') },- { label: 'CircleCollider', disabled: has('CircleCollider'), onClick: () => this.addComponentToEntity(entity, 'CircleCollider') },- { label: 'CapsuleCollider', disabled: has('CapsuleCollider'), onClick: () => this.addComponentToEntity(entity, 'CapsuleCollider') },- ],- });-- items.push({ label: '', separator: true });-- const prefabChildren: ContextMenuItem[] = [- { label: 'Save as Prefab...', icon: icons.package(14), onClick: () => this.saveEntityAsPrefab(entity) },- ];- if (this.store_.isPrefabRoot(entity as number)) {- const instanceId = this.store_.getPrefabInstanceId(entity as number);- const prefabPath = this.store_.getPrefabPath(entity as number);- if (instanceId && prefabPath) {- const overridden = hasAnyOverrides(this.store_.scene, instanceId);- prefabChildren.push(- { label: '', separator: true },- { label: 'Revert Prefab', icon: icons.rotateCw(14), disabled: !overridden, onClick: () => this.store_.revertPrefabInstance(instanceId, prefabPath) },- { label: 'Apply to Prefab', icon: icons.check(14), disabled: !overridden, onClick: () => this.store_.applyPrefabOverrides(instanceId, prefabPath) },- { label: 'Unpack Prefab', icon: icons.package(14), onClick: () => this.store_.unpackPrefab(instanceId) },- );- }- }- items.push({ label: 'Prefab', icon: icons.package(14), children: prefabChildren });- }-- const location = entity !== null ? 'hierarchy.entity' : 'hierarchy.background';- const ctx: ContextMenuContext = { location, entity: entity ?? undefined, entityData: entityData ?? undefined };- const extensionItems = getContextMenuItems(location, ctx);- if (extensionItems.length > 0) {- items.push({ label: '', separator: true }, ...extensionItems);- }-- showContextMenu({ x, y, items });- }-- private createEntityWithComponent(componentType: string, parent: Entity | null): void {- const newEntity = this.store_.createEntity(componentType, parent);-- this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));-- if (componentType === 'Text') {- this.store_.addComponent(newEntity, 'UIRect', getInitialComponentData('UIRect'));- }-- this.store_.addComponent(newEntity, componentType, getInitialComponentData(componentType));- }-- private addComponentToEntity(entity: Entity, componentType: string): void {- this.store_.addComponent(entity, componentType, getInitialComponentData(componentType));- }-- private createPhysicsEntity(colliderType: string, parent: Entity | null): void {- const newEntity = this.store_.createEntity(colliderType, parent);- this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));- this.store_.addComponent(newEntity, 'RigidBody', getInitialComponentData('RigidBody'));- this.store_.addComponent(newEntity, colliderType, getInitialComponentData(colliderType));- }-- private createButtonEntity(parent: Entity | null): void {- const newEntity = this.store_.createEntity('Button', parent);- this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));- this.store_.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));- this.store_.addComponent(newEntity, 'UIRect', getInitialComponentData('UIRect'));- this.store_.addComponent(newEntity, 'Interactable', getInitialComponentData('Interactable'));- this.store_.addComponent(newEntity, 'Button', getInitialComponentData('Button'));- }-- private createTextInputEntity(parent: Entity | null): void {- const newEntity = this.store_.createEntity('TextInput', parent);- this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));- const tiDefaults = getInitialComponentData('TextInput');- this.store_.addComponent(newEntity, 'Sprite', {- ...getInitialComponentData('Sprite'),- color: tiDefaults.backgroundColor,- size: { x: 200, y: 36 },- });- this.store_.addComponent(newEntity, 'UIRect', {- ...getInitialComponentData('UIRect'),- size: { x: 200, y: 36 },- });- this.store_.addComponent(newEntity, 'Interactable', getInitialComponentData('Interactable'));- this.store_.addComponent(newEntity, 'TextInput', getInitialComponentData('TextInput'));- }-- private createPanelEntity(parent: Entity | null): void {- const newEntity = this.store_.createEntity('Panel', parent);- this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));- this.store_.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));- this.store_.addComponent(newEntity, 'UIRect', getInitialComponentData('UIRect'));- this.store_.addComponent(newEntity, 'UIMask', getInitialComponentData('UIMask'));- }-- private createScreenSpaceRootEntity(parent: Entity | null): void {- const newEntity = this.store_.createEntity('ScreenSpace Root', parent);- this.store_.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));- this.store_.addComponent(newEntity, 'UIRect', {- ...getInitialComponentData('UIRect'),- anchorMin: { x: 0, y: 0 },- anchorMax: { x: 1, y: 1 },- });- this.store_.addComponent(newEntity, 'ScreenSpace', {});- }-- private duplicateEntity(entity: Entity): void {- const entityData = this.store_.getEntityData(entity as number);- if (!entityData) return;-- const scene = this.store_.scene;- const siblings = scene.entities- .filter(e => e.parent === entityData.parent)- .map(e => e.name);- const siblingNames = new Set(siblings);- const newName = generateUniqueName(entityData.name, siblingNames);-- const newEntity = this.store_.createEntity(- newName,- entityData.parent as Entity | null- );-- for (const comp of entityData.components) {- this.store_.addComponent(newEntity, comp.type, JSON.parse(JSON.stringify(comp.data)));- }-- this.duplicateChildren(entityData, newEntity);- }-- private duplicateChildren(sourceEntity: EntityData, newParent: Entity): void {- for (const childId of sourceEntity.children) {- const childData = this.store_.getEntityData(childId);- if (!childData) continue;-- const childEntity = this.store_.createEntity(childData.name, newParent);-- for (const comp of childData.components) {- this.store_.addComponent(childEntity, comp.type, JSON.parse(JSON.stringify(comp.data)));- }-- this.duplicateChildren(childData, childEntity);- }- }-- private async saveEntityAsPrefab(entity: Entity): Promise<void> {- const entityData = this.store_.getEntityData(entity as number);- if (!entityData) return;-- const projectPath = getEditorInstance()?.projectPath;- if (!projectPath) return;-- const projectDir = getParentDir(projectPath);- const assetsDir = joinPath(projectDir, 'assets');-- const name = await showInputDialog({- title: 'Save as Prefab',- placeholder: 'Prefab name',- defaultValue: entityData.name,- confirmText: 'Save',- validator: async (value) => {- if (!value.trim()) return 'Name is required';- if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {- return 'Name contains invalid characters';- }- return null;- },- });-- if (!name) return;-- const fileName = name.trim().endsWith('.esprefab')- ? name.trim()- : `${name.trim()}.esprefab`;- const filePath = joinPath(assetsDir, fileName);-- const success = await this.store_.saveAsPrefab(entity as number, filePath);- if (!success) {- console.error('[HierarchyPanel] Failed to save prefab:', filePath);- }- }-- private async createEntityFromPrefab(- prefabPath: string,- parent: Entity | null- ): Promise<void> {- const relativePath = this.toRelativePath(prefabPath);- const uuid = getAssetDatabase().getUuid(relativePath) ?? relativePath;- await this.store_.instantiatePrefab(uuid, parent);- }--}+export { HierarchyPanel } from './hierarchy/HierarchyPanel';diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex 117e00993..23e51b7e8 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -1,1871 +1,2 @@-/**- * @file SceneViewPanel.ts- * @brief Scene viewport panel with WebGL rendering and gizmo overlay- */--import type { Entity, App } from 'esengine';-import { Renderer } from 'esengine';-import type { SpineModuleController } from 'esengine/spine';-import type { EditorStore } from '../store/EditorStore';-import type { EditorBridge } from '../bridge/EditorBridge';-import { getPlatformAdapter } from '../platform/PlatformAdapter';-import { getDefaultComponentData, getInitialComponentData } from '../schemas/ComponentSchemas';-import { getGlobalPathResolver } from '../asset';-import { isUUID, getAssetLibrary } from '../asset/AssetDatabase';-import { icons } from '../utils/icons';-import { EditorSceneRenderer } from '../renderer/EditorSceneRenderer';-import { quatToEuler, eulerToQuat, findCanvasWorldRect } from '../math/Transform';-import { getEntityBounds } from '../bounds';-import { GizmoManager, getAllGizmos } from '../gizmos';-import type { GizmoContext } from '../gizmos';-import { ColliderOverlay } from '../gizmos/ColliderOverlay';-import { getSettingsValue, setSettingsValue, onSettingsChange } from '../settings/SettingsRegistry';-import { getEditorInstance } from '../context/EditorContext';--const CAMERA_COLORS = [- '#ffaa00',- '#00ccff',- '#ff55aa',- '#55ff55',-];--// =============================================================================-// SceneViewPanel-// =============================================================================--export interface SceneViewPanelOptions {- projectPath?: string;- app?: App;-}--export class SceneViewPanel {- private container_: HTMLElement;- private store_: EditorStore;- private bridge_: EditorBridge | null = null;- private canvas_: HTMLCanvasElement;- private webglCanvas_: HTMLCanvasElement | null = null;- private overlayCanvas_: HTMLCanvasElement | null = null;- private unsubscribe_: (() => void) | null = null;- private unsubscribeSceneSync_: (() => void) | null = null;- private unsubscribeFocus_: (() => void) | null = null;- private animationId_: number | null = null;- private continuousRender_ = false;- private isDirty_ = true;- private resizeObserver_: ResizeObserver | null = null;- private projectPath_: string | null = null;- private app_: App | null = null;-- private sceneRenderer_: EditorSceneRenderer | null = null;- private useWebGL_ = false;- private webglInitialized_ = false;- private webglInitPending_ = false;-- private panX_ = 0;- private panY_ = 0;- private zoom_ = 1;- private isDragging_ = false;- private lastMouseX_ = 0;- private lastMouseY_ = 0;-- private gizmoManager_: GizmoManager;- private colliderOverlay_: ColliderOverlay;- private keydownHandler_: ((e: KeyboardEvent) => void) | null = null;- private skipNextClick_ = false;- private mouseDownX_ = 0;- private mouseDownY_ = 0;- private boundOnDocumentMouseMove_: ((e: MouseEvent) => void) | null = null;- private boundOnDocumentMouseUp_: ((e: MouseEvent) => void) | null = null;-- private boundOnMouseDown_: ((e: MouseEvent) => void) | null = null;- private boundOnMouseMove_: ((e: MouseEvent) => void) | null = null;- private boundOnMouseUp_: ((e: MouseEvent) => void) | null = null;- private boundOnMouseLeave_: ((e: MouseEvent) => void) | null = null;- private boundOnWheel_: ((e: WheelEvent) => void) | null = null;- private boundOnCanvasClick_: ((e: MouseEvent) => void) | null = null;-- private static readonly MAX_CACHE_SIZE = 100;- private textureCache_: Map<string, HTMLImageElement | null> = new Map();- private loadingTextures_: Set<string> = new Set();-- private settingsDropdown_: HTMLElement | null = null;- private settingsDropdownClickHandler_: ((e: MouseEvent) => void) | null = null;- private unsubscribeSettings_: (() => void) | null = null;-- private spaceDown_ = false;- private keyupHandler_: ((e: KeyboardEvent) => void) | null = null;-- private marqueeActive_ = false;- private marqueeStartX_ = 0;- private marqueeStartY_ = 0;- private marqueeEndX_ = 0;- private marqueeEndY_ = 0;-- private getEntityBoundsWithSpine(entityData: import('../types/SceneTypes').EntityData): { width: number; height: number; offsetX?: number; offsetY?: number } {- const hasSpine = entityData.components.some(c => c.type === 'SpineAnimation');- if (hasSpine && this.sceneRenderer_) {- const spineBounds = this.sceneRenderer_.getSpineBounds(entityData.id);- if (spineBounds) {- return {- width: Math.abs(spineBounds.width),- height: Math.abs(spineBounds.height),- offsetX: spineBounds.x + spineBounds.width / 2,- offsetY: spineBounds.y + spineBounds.height / 2- };- }- }-- const hasBitmapText = entityData.components.some(c => c.type === 'BitmapText');- if (hasBitmapText && this.sceneRenderer_) {- const textBounds = this.sceneRenderer_.getBitmapTextBounds(entityData.id);- if (textBounds) {- return {- width: textBounds.width,- height: textBounds.height,- offsetX: textBounds.offsetX,- offsetY: textBounds.offsetY,- };- }- }-- return getEntityBounds(entityData.components);- }-- constructor(container: HTMLElement, store: EditorStore, options?: SceneViewPanelOptions) {- this.container_ = container;- this.store_ = store;- this.projectPath_ = options?.projectPath ?? null;- this.app_ = options?.app ?? null;- this.gizmoManager_ = new GizmoManager();- this.colliderOverlay_ = new ColliderOverlay();-- this.container_.className = 'es-sceneview-panel';- this.container_.innerHTML = `- <div class="es-panel-header">- <span class="es-panel-title">Scene</span>- <div class="es-sceneview-tools">- <div class="es-gizmo-toolbar">- ${this.buildGizmoToolbarHTML()}- </div>- <div class="es-toolbar-divider"></div>- <button class="es-btn es-btn-icon" data-action="reset-view" title="Reset View">${icons.refresh(14)}</button>- <span class="es-zoom-display">100%</span>- <span class="es-snap-indicator" style="display: none;">SNAP</span>- <div class="es-toolbar-divider"></div>- <div class="es-gizmo-settings-wrapper">- <button class="es-btn es-btn-icon" data-action="gizmo-settings" title="Gizmo Settings">${icons.settings(14)}</button>- <div class="es-gizmo-settings-dropdown" style="display: none;">- <div class="es-settings-row">- <label class="es-settings-checkbox">- <input type="checkbox" data-setting="scene.showGrid" ${getSettingsValue<boolean>('scene.showGrid') ? 'checked' : ''}>- <span>Show Grid</span>- </label>- </div>- <div class="es-settings-row">- <label class="es-settings-label">Grid Color</label>- <input type="color" data-setting="scene.gridColor" value="${getSettingsValue<string>('scene.gridColor')}" class="es-color-input">- </div>- <div class="es-settings-row">- <label class="es-settings-label">Grid Opacity</label>- <input type="range" data-setting="scene.gridOpacity" min="0" max="1" step="0.1" value="${getSettingsValue<number>('scene.gridOpacity')}" class="es-slider-input">- </div>- <div class="es-settings-row">- <label class="es-settings-label">Grid Size</label>- <input type="number" data-setting="scene.gridSize" min="1" max="500" step="1" value="${getSettingsValue<number>('scene.gridSize') ?? 50}" class="es-number-input">- </div>- <div class="es-settings-divider"></div>- <div class="es-settings-row">- <label class="es-settings-checkbox">- <input type="checkbox" data-setting="scene.showGizmos" ${getSettingsValue<boolean>('scene.showGizmos') ? 'checked' : ''}>- <span>Show Gizmos</span>- </label>- </div>- <div class="es-settings-row">- <label class="es-settings-checkbox">- <input type="checkbox" data-setting="scene.showSelectionBox" ${getSettingsValue<boolean>('scene.showSelectionBox') ? 'checked' : ''}>- <span>Show Selection Box</span>- </label>- </div>- <div class="es-settings-row">- <label class="es-settings-checkbox">- <input type="checkbox" data-setting="scene.showColliders" ${getSettingsValue<boolean>('scene.showColliders') ? 'checked' : ''}>- <span>Show Colliders</span>- </label>- </div>- <div class="es-settings-divider"></div>- <div class="es-settings-row">- <label class="es-settings-checkbox">- <input type="checkbox" data-setting="scene.showStats" ${getSettingsValue<boolean>('scene.showStats') ? 'checked' : ''}>- <span>Show Stats</span>- </label>- </div>- </div>- </div>- </div>- </div>- <div class="es-sceneview-viewport">- <canvas class="es-sceneview-webgl"></canvas>- <canvas class="es-sceneview-overlay"></canvas>- </div>- `;-- this.webglCanvas_ = this.container_.querySelector('.es-sceneview-webgl')!;- this.overlayCanvas_ = this.container_.querySelector('.es-sceneview-overlay')!;- this.canvas_ = this.overlayCanvas_;-- this.setupEvents();- this.unsubscribe_ = store.subscribe(() => this.onSceneChanged());- this.unsubscribeSceneSync_ = store.subscribeToSceneSync(() => this.onSceneSyncNeeded());- this.unsubscribeFocus_ = store.onFocusEntity((entityId) => this.focusOnEntity(entityId));- this.resize();-- if (this.app_?.wasmModule) {- this.initWebGLRenderer();- } else {- this.startContinuousRender();- }- }-- private buildGizmoToolbarHTML(): string {- const gizmos = getAllGizmos();- return gizmos.map(g => {- const isActive = g.id === this.gizmoManager_.getActiveId();- const shortcutLabel = g.shortcut ? ` (${g.shortcut.toUpperCase()})` : '';- return `<button class="es-btn es-btn-icon es-gizmo-btn${isActive ? ' es-active' : ''}" data-mode="${g.id}" title="${g.name}${shortcutLabel}">${g.icon}</button>`;- }).join('');- }-- dispose(): void {- this.continuousRender_ = false;- if (this.animationId_ !== null) {- cancelAnimationFrame(this.animationId_);- this.animationId_ = null;- }- if (this.unsubscribe_) {- this.unsubscribe_();- this.unsubscribe_ = null;- }- if (this.unsubscribeSceneSync_) {- this.unsubscribeSceneSync_();- this.unsubscribeSceneSync_ = null;- }- if (this.unsubscribeFocus_) {- this.unsubscribeFocus_();- this.unsubscribeFocus_ = null;- }- if (this.resizeObserver_) {- this.resizeObserver_.disconnect();- this.resizeObserver_ = null;- }- if (this.keydownHandler_) {- document.removeEventListener('keydown', this.keydownHandler_);- this.keydownHandler_ = null;- }- if (this.keyupHandler_) {- document.removeEventListener('keyup', this.keyupHandler_);- this.keyupHandler_ = null;- }- if (this.settingsDropdownClickHandler_) {- document.removeEventListener('click', this.settingsDropdownClickHandler_);- this.settingsDropdownClickHandler_ = null;- }- if (this.unsubscribeSettings_) {- this.unsubscribeSettings_();- this.unsubscribeSettings_ = null;- }- if (this.sceneRenderer_) {- this.sceneRenderer_.dispose();- this.sceneRenderer_ = null;- }- this.stopDocumentDrag();- if (this.boundOnMouseDown_) {- this.canvas_.removeEventListener('mousedown', this.boundOnMouseDown_);- this.boundOnMouseDown_ = null;- }- if (this.boundOnMouseMove_) {- this.canvas_.removeEventListener('mousemove', this.boundOnMouseMove_);- this.boundOnMouseMove_ = null;- }- if (this.boundOnMouseUp_) {- this.canvas_.removeEventListener('mouseup', this.boundOnMouseUp_);- this.boundOnMouseUp_ = null;- }- if (this.boundOnMouseLeave_) {- this.canvas_.removeEventListener('mouseleave', this.boundOnMouseLeave_);- this.boundOnMouseLeave_ = null;- }- if (this.boundOnWheel_) {- this.canvas_.removeEventListener('wheel', this.boundOnWheel_);- this.boundOnWheel_ = null;- }- if (this.boundOnCanvasClick_) {- this.canvas_.removeEventListener('click', this.boundOnCanvasClick_);- this.boundOnCanvasClick_ = null;- }- }-- setBridge(bridge: EditorBridge): void {- this.bridge_ = bridge;- this.requestRender();- }-- setProjectPath(path: string): void {- this.projectPath_ = path;- this.textureCache_.clear();- this.loadingTextures_.clear();-- if (this.sceneRenderer_) {- const projectDir = path.replace(/\\/g, '/').replace(/\/[^/]+$/, '');- this.sceneRenderer_.setProjectDir(projectDir);- this.syncSceneToRenderer();- }-- this.requestRender();- }-- setApp(app: App): void {- this.app_ = app;- if (app.wasmModule && !this.webglInitialized_ && !this.webglInitPending_) {- this.initWebGLRenderer();- }- }-- setSpineController(controller: SpineModuleController | null): void {- this.sceneRenderer_?.setSpineController(controller);- }-- getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {- return this.sceneRenderer_?.getSpineSkeletonInfo(entityId) ?? null;- }-- onSpineInstanceReady(listener: (entityId: number) => void): () => void {- return this.sceneRenderer_?.onSpineInstanceReady(listener) ?? (() => {});- }-- private async initWebGLRenderer(): Promise<void> {- if (this.webglInitPending_ || this.webglInitialized_) return;- if (!this.app_?.wasmModule || !this.webglCanvas_) return;-- this.webglInitPending_ = true;-- const canvasId = `es-sceneview-webgl-${Date.now()}`;- this.webglCanvas_.id = canvasId;-- this.sceneRenderer_ = new EditorSceneRenderer();- this.sceneRenderer_.setStore(this.store_);- const success = await this.sceneRenderer_.init(this.app_.wasmModule, `#${canvasId}`);-- if (success) {- this.webglInitialized_ = true;- this.useWebGL_ = true;-- if (this.projectPath_) {- const projectDir = this.projectPath_.replace(/\\/g, '/').replace(/\/[^/]+$/, '');- this.sceneRenderer_.setProjectDir(projectDir);- }-- await this.syncSceneToRenderer();- this.startContinuousRender();- } else {- console.warn('WebGL init failed, falling back to Canvas 2D');- this.sceneRenderer_ = null;- this.startContinuousRender();- }-- this.webglInitPending_ = false;- }-- private async syncSceneToRenderer(): Promise<void> {- if (!this.sceneRenderer_) return;- await this.sceneRenderer_.syncScene(this.store_.scene);- }-- private async onSceneSyncNeeded(): Promise<void> {- try {- if (this.sceneRenderer_ && this.useWebGL_) {- await this.syncSceneToRenderer();- }- } catch (e) {- console.warn('[SceneViewPanel] Scene sync error:', e);- }- }-- private onSceneChanged(): void {- this.requestRender();- }-- private loadTexture(texturePath: string): HTMLImageElement | null {- if (!this.projectPath_ || !texturePath) return null;-- const resolved = isUUID(texturePath)- ? (getAssetLibrary().getPath(texturePath) ?? texturePath)- : texturePath;-- if (this.textureCache_.has(resolved)) {- return this.textureCache_.get(resolved) ?? null;- }-- if (this.loadingTextures_.has(resolved)) {- return null;- }-- this.loadingTextures_.add(resolved);-- const projectDir = this.projectPath_.replace(/\\/g, '/').replace(/\/[^/]+$/, '');- const fullPath = `${projectDir}/${resolved}`;- const img = new Image();-- img.onload = () => {- this.loadingTextures_.delete(resolved);- this.evictCache(this.textureCache_);- this.textureCache_.set(resolved, img);- this.requestRender();- };-- img.onerror = () => {- this.loadingTextures_.delete(resolved);- this.evictCache(this.textureCache_);- this.textureCache_.set(resolved, null);- console.warn(`Failed to load texture: ${fullPath}`);- };-- img.src = getPlatformAdapter().convertFilePathToUrl(fullPath);-- return null;- }-- private evictCache<T>(cache: Map<string, T>): void {- if (cache.size >= SceneViewPanel.MAX_CACHE_SIZE) {- const firstKey = cache.keys().next().value;- if (firstKey !== undefined) {- cache.delete(firstKey);- }- }- }-- get canvas(): HTMLCanvasElement {- return this.canvas_;- }-- get assetServer() {- return this.sceneRenderer_?.assetServer ?? null;- }-- resize(): void {- const viewport = this.container_.querySelector('.es-sceneview-viewport') as HTMLElement;- if (!viewport) return;-- const rect = viewport.getBoundingClientRect();- const dpr = window.devicePixelRatio || 1;-- if (this.webglCanvas_) {- this.webglCanvas_.width = rect.width * dpr;- this.webglCanvas_.height = rect.height * dpr;- this.webglCanvas_.style.width = `${rect.width}px`;- this.webglCanvas_.style.height = `${rect.height}px`;- }-- if (this.overlayCanvas_) {- this.overlayCanvas_.width = rect.width * dpr;- this.overlayCanvas_.height = rect.height * dpr;- this.overlayCanvas_.style.width = `${rect.width}px`;- this.overlayCanvas_.style.height = `${rect.height}px`;- }-- this.canvas_.width = rect.width * dpr;- this.canvas_.height = rect.height * dpr;- this.canvas_.style.width = `${rect.width}px`;- this.canvas_.style.height = `${rect.height}px`;-- this.requestRender();- }-- private createGizmoContext(ctx: CanvasRenderingContext2D): GizmoContext {- return {- store: this.store_,- ctx,- zoom: this.zoom_,- screenToWorld: (clientX, clientY) => this.screenToWorld(clientX, clientY),- getWorldTransform: (entityId) => this.store_.getWorldTransform(entityId),- getEntityBounds: (entityData) => this.getEntityBoundsWithSpine(entityData),- requestRender: () => this.requestRender(),- };- }-- private setupEvents(): void {- const resetBtn = this.container_.querySelector('[data-action="reset-view"]');- resetBtn?.addEventListener('click', () => {- this.panX_ = 0;- this.panY_ = 0;- this.zoom_ = 1;- this.updateZoomDisplay();- this.requestRender();- });-- this.setupGizmoSettingsDropdown();-- const gizmoButtons = this.container_.querySelectorAll('.es-gizmo-btn');- gizmoButtons.forEach(btn => {- btn.addEventListener('click', () => {- const mode = (btn as HTMLElement).dataset.mode;- if (mode) this.setGizmoMode(mode);- });- });-- this.keydownHandler_ = (e: KeyboardEvent) => {- if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {- return;- }-- if (e.key === ' ' && !this.spaceDown_) {- this.spaceDown_ = true;- if (!this.isDragging_) {- this.canvas_.style.cursor = 'grab';- }- e.preventDefault();- return;- }-- const gizmos = getAllGizmos();- for (const g of gizmos) {- if (g.shortcut && e.key.toLowerCase() === g.shortcut) {- this.setGizmoMode(g.id);- return;- }- }-- if (e.key === 'f' || e.key === 'F') {- const entity = this.store_.selectedEntity;- if (entity !== null) {- this.focusOnEntity(entity as number);- }- return;- }-- if (e.key === 'Delete' || e.key === 'Backspace') {- if (this.store_.selectedEntities.size > 0) {- this.store_.deleteSelectedEntities();- }- return;- }-- if ((e.key === 'd' || e.key === 'D') && (e.ctrlKey || e.metaKey)) {- e.preventDefault();- getEditorInstance()?.duplicateSelected();- return;- }-- if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {- this.nudgeSelection(e);- return;- }-- if (e.key === '+' || e.key === '=') {- this.zoom_ = Math.min(10, this.zoom_ * 1.1);- this.updateZoomDisplay();- this.requestRender();- return;- }-- if (e.key === '-') {- this.zoom_ = Math.max(0.1, this.zoom_ * 0.9);- this.updateZoomDisplay();- this.requestRender();- return;- }-- if (e.key === 'Control' || e.key === 'Meta') {- this.updateSnapIndicator(true);- }- };- document.addEventListener('keydown', this.keydownHandler_);-- this.keyupHandler_ = (e: KeyboardEvent) => {- if (e.key === ' ') {- this.spaceDown_ = false;- if (!this.isDragging_) {- this.canvas_.style.cursor = 'default';- }- }- if (e.key === 'Control' || e.key === 'Meta') {- this.updateSnapIndicator(false);- }- };- document.addEventListener('keyup', this.keyupHandler_);-- this.boundOnMouseDown_ = this.onMouseDown.bind(this);- this.boundOnMouseMove_ = this.onMouseMove.bind(this);- this.boundOnMouseUp_ = this.onMouseUp.bind(this);- this.boundOnMouseLeave_ = this.onMouseLeave.bind(this);- this.boundOnWheel_ = this.onWheel.bind(this);- this.boundOnCanvasClick_ = this.onCanvasClick.bind(this);-- this.canvas_.addEventListener('mousedown', this.boundOnMouseDown_);- this.canvas_.addEventListener('mousemove', this.boundOnMouseMove_);- this.canvas_.addEventListener('mouseup', this.boundOnMouseUp_);- this.canvas_.addEventListener('mouseleave', this.boundOnMouseLeave_);- this.canvas_.addEventListener('wheel', this.boundOnWheel_);- this.canvas_.addEventListener('click', this.boundOnCanvasClick_);-- const viewport = this.container_.querySelector('.es-sceneview-viewport');- if (viewport) {- this.resizeObserver_ = new ResizeObserver(() => {- this.resize();- });- this.resizeObserver_.observe(viewport);- }-- this.canvas_.addEventListener('dragover', (e) => {- const types = e.dataTransfer?.types ?? [];- if (!Array.from(types).includes('application/esengine-asset')) return;- e.preventDefault();- e.dataTransfer!.dropEffect = 'copy';- });-- this.canvas_.addEventListener('drop', (e) => {- e.preventDefault();- const assetDataStr = e.dataTransfer?.getData('application/esengine-asset');- if (!assetDataStr) return;-- let assetData: { type: string; path: string; name: string };- try {- assetData = JSON.parse(assetDataStr);- } catch {- return;- }-- if (assetData.type !== 'image') return;-- const { worldX, worldY } = this.screenToWorld(e.clientX, e.clientY);- this.createSpriteFromDrop(assetData, worldX, worldY);- });- }-- private setGizmoMode(mode: string): void {- this.gizmoManager_.setActive(mode);- const buttons = this.container_.querySelectorAll('.es-gizmo-btn');- buttons.forEach(btn => {- const btnMode = (btn as HTMLElement).dataset.mode;- btn.classList.toggle('es-active', btnMode === mode);- });- this.requestRender();- }-- private setupGizmoSettingsDropdown(): void {- const settingsBtn = this.container_.querySelector('[data-action="gizmo-settings"]');- this.settingsDropdown_ = this.container_.querySelector('.es-gizmo-settings-dropdown');-- if (!settingsBtn || !this.settingsDropdown_) return;-- settingsBtn.addEventListener('click', (e) => {- e.stopPropagation();- const isVisible = this.settingsDropdown_!.style.display !== 'none';- this.settingsDropdown_!.style.display = isVisible ? 'none' : 'block';- });-- this.settingsDropdownClickHandler_ = (e: MouseEvent) => {- if (this.settingsDropdown_ && !this.settingsDropdown_.contains(e.target as Node) &&- !settingsBtn.contains(e.target as Node)) {- this.settingsDropdown_.style.display = 'none';- }- };- document.addEventListener('click', this.settingsDropdownClickHandler_);-- this.settingsDropdown_.querySelectorAll('input').forEach(input => {- const settingId = input.dataset.setting;- if (!settingId) return;-- input.addEventListener('change', () => {- if (input.type === 'checkbox') {- setSettingsValue(settingId, input.checked);- } else if (input.type === 'range' || input.type === 'number') {- setSettingsValue(settingId, parseFloat(input.value));- } else if (input.type === 'color') {- setSettingsValue(settingId, input.value);- }- this.requestRender();- });-- if (input.type === 'range') {- input.addEventListener('input', () => {- setSettingsValue(settingId, parseFloat(input.value));- this.requestRender();- });- }- });-- this.unsubscribeSettings_ = onSettingsChange((id, value) => {- if (!id.startsWith('scene.')) return;- const input = this.settingsDropdown_?.querySelector(`[data-setting="${id}"]`) as HTMLInputElement | null;- if (!input) return;- if (input.type === 'checkbox') {- input.checked = value as boolean;- } else {- input.value = String(value);- }- this.requestRender();- });- }-- private updateGizmoContext(): void {- const ctx = this.overlayCanvas_?.getContext('2d') ?? this.canvas_.getContext('2d');- if (ctx) {- this.gizmoManager_.setContext(this.createGizmoContext(ctx));- }- }-- private createOverlayContext(): import('../gizmos/ColliderOverlay').OverlayContext | null {- const ctx = this.overlayCanvas_?.getContext('2d') ?? this.canvas_.getContext('2d');- if (!ctx) return null;- return { ctx, zoom: this.zoom_, store: this.store_ };- }-- private onMouseDown(e: MouseEvent): void {- if (e.button === 1 || (e.button === 0 && e.altKey) || (e.button === 0 && this.spaceDown_)) {- this.isDragging_ = true;- this.lastMouseX_ = e.clientX;- this.lastMouseY_ = e.clientY;- this.canvas_.style.cursor = 'grabbing';- this.startDocumentDrag();- return;- }-- if (e.button !== 0) return;-- this.mouseDownX_ = e.clientX;- this.mouseDownY_ = e.clientY;-- const { worldX, worldY } = this.screenToWorld(e.clientX, e.clientY);-- const hasSelection = this.store_.selectedEntities.size > 0;-- if (this.gizmoManager_.getActiveId() !== 'select' && hasSelection) {- this.updateGizmoContext();- if (this.gizmoManager_.onMouseDown(worldX, worldY)) {- this.startDocumentDrag();- return;- }- }-- if (getSettingsValue<boolean>('scene.showColliders') && hasSelection) {- const octx = this.createOverlayContext();- if (octx && this.colliderOverlay_.onDragStart(worldX, worldY, octx)) {- this.startDocumentDrag();- return;- }- }-- if (this.gizmoManager_.getActiveId() === 'select') {- const hits = this.findEntitiesAtPosition(worldX, worldY);- if (hits.length === 0) {- this.marqueeActive_ = true;- this.marqueeStartX_ = worldX;- this.marqueeStartY_ = worldY;- this.marqueeEndX_ = worldX;- this.marqueeEndY_ = worldY;- this.startDocumentDrag();- return;- }- }-- this.lastMouseX_ = e.clientX;- this.lastMouseY_ = e.clientY;- }-- private startDocumentDrag(): void {- this.boundOnDocumentMouseMove_ = this.onDocumentMouseMove.bind(this);- this.boundOnDocumentMouseUp_ = this.onDocumentMouseUp.bind(this);- document.addEventListener('mousemove', this.boundOnDocumentMouseMove_);- document.addEventListener('mouseup', this.boundOnDocumentMouseUp_);- }-- private stopDocumentDrag(): void {- if (this.boundOnDocumentMouseMove_) {- document.removeEventListener('mousemove', this.boundOnDocumentMouseMove_);- this.boundOnDocumentMouseMove_ = null;- }- if (this.boundOnDocumentMouseUp_) {- document.removeEventListener('mouseup', this.boundOnDocumentMouseUp_);- this.boundOnDocumentMouseUp_ = null;- }- }-- private onDocumentMouseMove(e: MouseEvent): void {- this.onMouseMove(e);- }-- private onDocumentMouseUp(e: MouseEvent): void {- this.onMouseUp(e);- this.stopDocumentDrag();- }-- private onMouseMove(e: MouseEvent): void {- const { worldX, worldY } = this.screenToWorld(e.clientX, e.clientY);-- if (this.isDragging_) {- const dx = e.clientX - this.lastMouseX_;- const dy = e.clientY - this.lastMouseY_;-- this.panX_ += dx / this.zoom_;- this.panY_ += dy / this.zoom_;-- this.lastMouseX_ = e.clientX;- this.lastMouseY_ = e.clientY;- this.requestRender();- return;- }-- if (this.marqueeActive_) {- this.marqueeEndX_ = worldX;- this.marqueeEndY_ = worldY;- this.requestRender();- return;- }-- if (this.gizmoManager_.isDragging()) {- this.updateGizmoContext();- this.gizmoManager_.onMouseMove(worldX, worldY, e);- return;- }-- if (this.colliderOverlay_.isDragging()) {- const octx = this.createOverlayContext();- if (octx) {- this.colliderOverlay_.onDrag(worldX, worldY, octx);- this.requestRender();- }- return;- }-- const hasSelection = this.store_.selectedEntities.size > 0;-- if (this.gizmoManager_.getActiveId() !== 'select' && hasSelection) {- this.updateGizmoContext();- this.gizmoManager_.onMouseMove(worldX, worldY, e);- this.canvas_.style.cursor = this.gizmoManager_.getCursor();- }-- if (getSettingsValue<boolean>('scene.showColliders') && hasSelection) {- const octx = this.createOverlayContext();- if (octx) {- this.colliderOverlay_.hitTest(worldX, worldY, octx);- const colliderCursor = this.colliderOverlay_.getCursor();- if (colliderCursor) {- this.canvas_.style.cursor = colliderCursor;- }- }- }- }-- private onMouseUp(_e: MouseEvent): void {- const dx = _e.clientX - this.mouseDownX_;- const dy = _e.clientY - this.mouseDownY_;- const didMove = dx * dx + dy * dy > 9;-- if (this.isDragging_) {- this.isDragging_ = false;- this.canvas_.style.cursor = this.spaceDown_ ? 'grab' : 'default';- this.skipNextClick_ = true;- }-- if (this.marqueeActive_) {- this.marqueeActive_ = false;- const { worldX, worldY } = this.screenToWorld(_e.clientX, _e.clientY);- this.marqueeEndX_ = worldX;- this.marqueeEndY_ = worldY;- this.finishMarqueeSelection(_e.ctrlKey || _e.metaKey);- this.skipNextClick_ = true;- this.requestRender();- }-- if (this.gizmoManager_.isDragging()) {- const { worldX, worldY } = this.screenToWorld(_e.clientX, _e.clientY);- this.updateGizmoContext();- this.gizmoManager_.onMouseUp(worldX, worldY);- this.skipNextClick_ = didMove;- }-- if (this.colliderOverlay_.isDragging()) {- const octx = this.createOverlayContext();- if (octx) {- this.colliderOverlay_.onDragEnd(octx);- }- this.skipNextClick_ = didMove;- }- }-- private onMouseLeave(_e: MouseEvent): void {- if (this.isDragging_ || this.gizmoManager_.isDragging() || this.colliderOverlay_.isDragging() || this.marqueeActive_) {- return;- }- this.gizmoManager_.resetHover();- this.requestRender();- }-- private onCanvasClick(e: MouseEvent): void {- if (this.skipNextClick_) {- this.skipNextClick_ = false;- return;- }-- if (this.isDragging_ || this.gizmoManager_.isDragging()) return;-- const { worldX, worldY } = this.screenToWorld(e.clientX, e.clientY);-- const hasSelection = this.store_.selectedEntities.size > 0;-- if (this.gizmoManager_.getActiveId() !== 'select' && hasSelection) {- this.updateGizmoContext();- const result = this.gizmoManager_.hitTest(worldX, worldY);- if (result.hit) return;- }-- const hits = this.findEntitiesAtPosition(worldX, worldY);- if (hits.length === 0) {- this.store_.selectEntity(null);- return;- }-- const current = this.store_.selectedEntity;- const idx = current !== null ? hits.indexOf(current as Entity) : -1;- const next = idx >= 0 ? hits[(idx + 1) % hits.length] : hits[0];- this.store_.selectEntity(next);- }-- private focusOnEntity(entityId: number): void {- const worldTransform = this.store_.getWorldTransform(entityId);- this.panX_ = -worldTransform.position.x;- this.panY_ = worldTransform.position.y;- this.updateZoomDisplay();- this.requestRender();- }-- private screenToWorld(clientX: number, clientY: number): { worldX: number; worldY: number } {- const rect = this.canvas_.getBoundingClientRect();- const dpr = window.devicePixelRatio || 1;- const x = (clientX - rect.left) * dpr;- const y = (clientY - rect.top) * dpr;- const w = this.canvas_.width;- const h = this.canvas_.height;-- return {- worldX: (x - w / 2) / this.zoom_ - this.panX_,- worldY: -(y - h / 2) / this.zoom_ + this.panY_,- };- }-- private onWheel(e: WheelEvent): void {- e.preventDefault();-- const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;- const newZoom = Math.max(0.1, Math.min(10, this.zoom_ * zoomFactor));-- const rect = this.canvas_.getBoundingClientRect();- const dpr = window.devicePixelRatio;- const mouseX = (e.clientX - rect.left) * dpr;- const mouseY = (e.clientY - rect.top) * dpr;-- const worldX = (mouseX - this.canvas_.width / 2) / this.zoom_ - this.panX_;- const worldY = (mouseY - this.canvas_.height / 2) / this.zoom_ - this.panY_;-- this.zoom_ = newZoom;-- this.panX_ = (mouseX - this.canvas_.width / 2) / this.zoom_ - worldX;- this.panY_ = (mouseY - this.canvas_.height / 2) / this.zoom_ - worldY;-- this.updateZoomDisplay();- this.requestRender();- }-- private findEntitiesAtPosition(worldX: number, worldY: number): Entity[] {- const scene = this.store_.scene;- const result: Entity[] = [];-- for (let i = scene.entities.length - 1; i >= 0; i--) {- const entity = scene.entities[i];- if (!this.store_.isEntityVisible(entity.id)) continue;-- const transform = entity.components.find(c => c.type === 'LocalTransform');-- if (!transform) continue;-- const worldTransform = this.store_.getWorldTransform(entity.id);- const pos = worldTransform.position;- const scale = worldTransform.scale;-- const bounds = this.getEntityBoundsWithSpine(entity);- const w = bounds.width * Math.abs(scale.x);- const h = bounds.height * Math.abs(scale.y);- const offsetX = (bounds.offsetX ?? 0) * scale.x;- const offsetY = (bounds.offsetY ?? 0) * scale.y;-- const centerX = pos.x + offsetX;- const centerY = pos.y + offsetY;- const halfW = w / 2;- const halfH = h / 2;-- if (- worldX >= centerX - halfW &&- worldX <= centerX + halfW &&- worldY >= centerY - halfH &&- worldY <= centerY + halfH- ) {- result.push(entity.id as Entity);- }- }-- return result;- }-- private findEntitiesInRect(x1: number, y1: number, x2: number, y2: number): Entity[] {- const minX = Math.min(x1, x2);- const maxX = Math.max(x1, x2);- const minY = Math.min(y1, y2);- const maxY = Math.max(y1, y2);-- const scene = this.store_.scene;- const result: Entity[] = [];-- for (const entity of scene.entities) {- if (!this.store_.isEntityVisible(entity.id)) continue;- const transform = entity.components.find(c => c.type === 'LocalTransform');- if (!transform) continue;-- const worldTransform = this.store_.getWorldTransform(entity.id);- const pos = worldTransform.position;- const scale = worldTransform.scale;- const bounds = this.getEntityBoundsWithSpine(entity);- const w = bounds.width * Math.abs(scale.x);- const h = bounds.height * Math.abs(scale.y);- const offsetX = (bounds.offsetX ?? 0) * scale.x;- const offsetY = (bounds.offsetY ?? 0) * scale.y;-- const centerX = pos.x + offsetX;- const centerY = pos.y + offsetY;- const halfW = w / 2;- const halfH = h / 2;-- if (centerX + halfW >= minX && centerX - halfW <= maxX &&- centerY + halfH >= minY && centerY - halfH <= maxY) {- result.push(entity.id as Entity);- }- }-- return result;- }-- private finishMarqueeSelection(addToExisting: boolean): void {- const hits = this.findEntitiesInRect(- this.marqueeStartX_, this.marqueeStartY_,- this.marqueeEndX_, this.marqueeEndY_,- );-- if (addToExisting) {- const existing = Array.from(this.store_.selectedEntities);- const merged = new Set([...existing, ...hits.map(h => h as number)]);- this.store_.selectEntities(Array.from(merged));- } else {- this.store_.selectEntities(hits.map(h => h as number));- }- }-- private nudgeSelection(e: KeyboardEvent): void {- const entity = this.store_.selectedEntity;- if (entity === null) return;-- const entityData = this.store_.getEntityData(entity as number);- if (!entityData) return;-- const transform = entityData.components.find(c => c.type === 'LocalTransform');- if (!transform) return;-- const pos = transform.data.position as { x: number; y: number; z: number };- if (!pos) return;-- const snapOn = e.ctrlKey || e.metaKey;- const step = snapOn ? (getSettingsValue<number>('scene.gridSize') ?? 50) : 1;-- let dx = 0;- let dy = 0;- if (e.key === 'ArrowLeft') dx = -step;- if (e.key === 'ArrowRight') dx = step;- if (e.key === 'ArrowUp') dy = step;- if (e.key === 'ArrowDown') dy = -step;-- const oldPos = { ...pos };- const newPos = { x: pos.x + dx, y: pos.y + dy, z: pos.z };-- this.store_.updateProperty(entity as number, 'LocalTransform', 'position', oldPos, newPos);- e.preventDefault();- }-- private updateZoomDisplay(): void {- const display = this.container_.querySelector('.es-zoom-display');- if (display) {- display.textContent = `${Math.round(this.zoom_ * 100)}%`;- }- }-- private updateSnapIndicator(active: boolean): void {- const indicator = this.container_.querySelector('.es-snap-indicator') as HTMLElement | null;- if (indicator) {- indicator.style.display = active ? 'inline' : 'none';- }- }-- private requestRender(): void {- this.isDirty_ = true;- if (this.animationId_ !== null) return;-- this.animationId_ = requestAnimationFrame(() => {- this.animationId_ = null;- if (this.isDirty_) {- this.isDirty_ = false;- try {- this.render();- } catch (e) {- console.warn('[SceneViewPanel] Render error, skipping frame:', e);- }- }- if (this.continuousRender_) {- this.scheduleNextFrame();- }- });- }-- private scheduleNextFrame(): void {- if (this.animationId_ !== null) return;- this.animationId_ = requestAnimationFrame(() => {- this.animationId_ = null;- if (this.isDirty_) {- this.isDirty_ = false;- try {- this.render();- } catch (e) {- console.warn('[SceneViewPanel] Render error, skipping frame:', e);- }- }- if (this.continuousRender_) {- this.scheduleNextFrame();- }- });- }-- startContinuousRender(): void {- if (!this.continuousRender_) {- this.continuousRender_ = true;- this.requestRender();- }- }-- stopContinuousRender(): void {- this.continuousRender_ = false;- }-- private render(): void {- if (this.useWebGL_ && this.sceneRenderer_ && this.webglCanvas_) {- const w = this.webglCanvas_.width;- const h = this.webglCanvas_.height;- if (w === 0 || h === 0) return;-- this.sceneRenderer_.camera.panX = this.panX_;- this.sceneRenderer_.camera.panY = this.panY_;- this.sceneRenderer_.camera.zoom = this.zoom_;-- this.sceneRenderer_.render(w, h);- this.renderOverlay();- } else if (this.bridge_) {- const w = this.canvas_.width;- const h = this.canvas_.height;- if (w === 0 || h === 0) return;-- this.bridge_.render(w, h);- } else {- this.renderPreview();- }- }-- private renderOverlay(): void {- if (!this.overlayCanvas_) return;-- const ctx = this.overlayCanvas_.getContext('2d');- if (!ctx) return;-- const w = this.overlayCanvas_.width;- const h = this.overlayCanvas_.height;-- ctx.clearRect(0, 0, w, h);-- ctx.save();- ctx.translate(w / 2 + this.panX_ * this.zoom_, h / 2 + this.panY_ * this.zoom_);- ctx.scale(this.zoom_, this.zoom_);-- this.drawGrid(ctx, w, h);-- this.drawCameraFrustums(ctx);- this.drawScreenSpaceBounds(ctx);-- if (getSettingsValue<boolean>('scene.showColliders')) {- this.colliderOverlay_.drawAll({- ctx,- zoom: this.zoom_,- store: this.store_,- });- }-- const hasSelection = this.store_.selectedEntities.size > 0;-- if (hasSelection) {- if (getSettingsValue<boolean>('scene.showSelectionBox')) {- this.drawSelectionBox(ctx);- }-- if (this.gizmoManager_.getActiveId() !== 'select' && getSettingsValue<boolean>('scene.showGizmos')) {- this.gizmoManager_.setContext(this.createGizmoContext(ctx));- this.gizmoManager_.draw();- }- }-- if (this.marqueeActive_) {- this.drawMarquee(ctx);- }-- ctx.restore();-- this.drawStats(ctx, w, h);- this.drawViewportPreview(ctx, w, h);-- if (!this.store_.scene.entities.some(- e => e.components.some(c => c.type === 'Camera'))) {- ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';- ctx.font = '14px system-ui, sans-serif';- ctx.textAlign = 'center';- ctx.fillText('No Camera in Scene', w / 2, h / 2);- }- }-- private drawSelectionBox(ctx: CanvasRenderingContext2D): void {- const selectedEntities = this.store_.getSelectedEntitiesData();-- for (const entityData of selectedEntities) {- if (!this.store_.isEntityVisible(entityData.id)) continue;-- const transform = entityData.components.find(c => c.type === 'LocalTransform');- if (!transform) continue;-- const worldTransform = this.store_.getWorldTransform(entityData.id);- const pos = worldTransform.position;- const scale = worldTransform.scale;-- const bounds = this.getEntityBoundsWithSpine(entityData);- const w = bounds.width * Math.abs(scale.x);- const h = bounds.height * Math.abs(scale.y);- const offsetX = (bounds.offsetX ?? 0) * scale.x;- const offsetY = (bounds.offsetY ?? 0) * scale.y;-- ctx.save();- ctx.translate(pos.x + offsetX, -pos.y - offsetY);-- ctx.strokeStyle = '#00aaff';- ctx.lineWidth = 2 / this.zoom_;- ctx.setLineDash([]);- ctx.strokeRect(-w / 2, -h / 2, w, h);-- if (selectedEntities.length === 1) {- ctx.fillStyle = '#00aaff';- const handleSize = 6 / this.zoom_;- const corners = [- [-w / 2, -h / 2],- [w / 2, -h / 2],- [-w / 2, h / 2],- [w / 2, h / 2],- ];- for (const [cx, cy] of corners) {- ctx.fillRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);- }- }-- ctx.restore();- }- }-- private drawMarquee(ctx: CanvasRenderingContext2D): void {- const x = Math.min(this.marqueeStartX_, this.marqueeEndX_);- const y = Math.min(-this.marqueeStartY_, -this.marqueeEndY_);- const w = Math.abs(this.marqueeEndX_ - this.marqueeStartX_);- const h = Math.abs(this.marqueeEndY_ - this.marqueeStartY_);-- ctx.fillStyle = 'rgba(0, 170, 255, 0.1)';- ctx.fillRect(x, y, w, h);-- ctx.strokeStyle = '#00aaff';- ctx.lineWidth = 1 / this.zoom_;- ctx.setLineDash([]);- ctx.strokeRect(x, y, w, h);- }-- private drawCameraFrustums(ctx: CanvasRenderingContext2D): void {- const selectedEntity = this.store_.selectedEntity;-- let aspectRatio = 750 / 1650;- const canvasEntity = this.store_.scene.entities.find(- e => e.components.some(c => c.type === 'Canvas')- );- if (canvasEntity) {- const canvas = canvasEntity.components.find(c => c.type === 'Canvas');- const resolution = canvas?.data.designResolution as { x: number; y: number };- if (resolution && resolution.y > 0) {- aspectRatio = resolution.x / resolution.y;- }- }-- let cameraIndex = 0;- for (const entity of this.store_.scene.entities) {- const camera = entity.components.find(c => c.type === 'Camera');- if (!camera) continue;-- const transform = entity.components.find(c => c.type === 'LocalTransform');- if (!transform) { cameraIndex++; continue; }-- const isSelected = entity.id === selectedEntity;- const showFrustum = (camera.data.showFrustum as boolean) ?? true;-- if (!showFrustum && !isSelected) { cameraIndex++; continue; }-- const color = CAMERA_COLORS[cameraIndex % CAMERA_COLORS.length];- const worldTransform = this.store_.getWorldTransform(entity.id);- const pos = worldTransform.position;-- const orthoSize = (camera.data.orthoSize as number) ?? 400;- const projectionType = (camera.data.projectionType as number) ?? 0;- const priority = (camera.data.priority as number) ?? 0;- const vpX = (camera.data.viewportX as number) ?? 0;- const vpY = (camera.data.viewportY as number) ?? 0;- const vpW = (camera.data.viewportW as number) ?? 1;- const vpH = (camera.data.viewportH as number) ?? 1;-- ctx.save();- ctx.translate(pos.x, -pos.y);-- if (projectionType === 1) {- const halfHeight = orthoSize;- const halfWidth = halfHeight * aspectRatio;-- ctx.strokeStyle = color;- ctx.lineWidth = 2 / this.zoom_;-- if (isSelected) {- ctx.globalAlpha = 1;- ctx.setLineDash([]);- } else {- ctx.globalAlpha = 0.5;- ctx.setLineDash([8 / this.zoom_, 4 / this.zoom_]);- }-- ctx.strokeRect(-halfWidth, -halfHeight, halfWidth * 2, halfHeight * 2);-- const [cr, cg, cb] = this.hexToRgb(color);- ctx.fillStyle = isSelected- ? `rgba(${cr}, ${cg}, ${cb}, 0.1)`- : `rgba(${cr}, ${cg}, ${cb}, 0.05)`;- ctx.fillRect(-halfWidth, -halfHeight, halfWidth * 2, halfHeight * 2);-- ctx.setLineDash([]);- ctx.globalAlpha = isSelected ? 1 : 0.5;-- this.drawCameraIcon(ctx, color);-- const fontSize = 12 / this.zoom_;- ctx.font = `bold ${fontSize}px system-ui, sans-serif`;- ctx.textBaseline = 'bottom';-- ctx.textAlign = 'left';- const nameText = entity.name;- const nameMetrics = ctx.measureText(nameText);- const labelPad = 2 / this.zoom_;- const labelH = fontSize + labelPad * 2;- ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';- ctx.fillRect(- -halfWidth,- -halfHeight - labelH - labelPad,- nameMetrics.width + labelPad * 2,- labelH- );- ctx.fillStyle = color;- ctx.fillText(nameText, -halfWidth + labelPad, -halfHeight - labelPad * 2);-- ctx.textAlign = 'right';- const prioText = `P${priority}`;- const prioMetrics = ctx.measureText(prioText);- ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';- ctx.fillRect(- halfWidth - prioMetrics.width - labelPad * 2,- -halfHeight - labelH - labelPad,- prioMetrics.width + labelPad * 2,- labelH- );- ctx.fillStyle = color;- ctx.fillText(prioText, halfWidth - labelPad, -halfHeight - labelPad * 2);-- const isFullscreen = vpX === 0 && vpY === 0 && vpW === 1 && vpH === 1;- if (!isFullscreen) {- ctx.textAlign = 'left';- ctx.textBaseline = 'top';- ctx.font = `${fontSize * 0.9}px system-ui, sans-serif`;- const pctW = Math.round(vpW * 100);- const pctH = Math.round(vpH * 100);- const vpText = `viewport: ${vpX}, ${vpY} ${pctW}%\u00d7${pctH}%`;- const vpMetrics = ctx.measureText(vpText);- ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';- ctx.fillRect(- -halfWidth,- halfHeight + labelPad,- vpMetrics.width + labelPad * 2,- labelH- );- ctx.fillStyle = color;- ctx.fillText(vpText, -halfWidth + labelPad, halfHeight + labelPad * 2);- }- }-- ctx.globalAlpha = 1;- ctx.restore();- cameraIndex++;- }- }-- private drawScreenSpaceBounds(ctx: CanvasRenderingContext2D): void {- const hasScreenSpace = this.store_.scene.entities.some(- e => e.components.some(c => c.type === 'ScreenSpace')- );- if (!hasScreenSpace) return;-- const canvasRect = findCanvasWorldRect(this.store_.scene.entities);- if (!canvasRect) return;-- const x = canvasRect.left;- const y = -(canvasRect.top);- const w = canvasRect.right - canvasRect.left;- const h = canvasRect.top - canvasRect.bottom;-- ctx.save();-- ctx.strokeStyle = '#ffb400';- ctx.lineWidth = 2 / this.zoom_;- ctx.setLineDash([6 / this.zoom_, 4 / this.zoom_]);- ctx.strokeRect(x, y, w, h);-- ctx.fillStyle = 'rgba(255, 180, 0, 0.04)';- ctx.fillRect(x, y, w, h);-- ctx.setLineDash([]);- const fontSize = 11 / this.zoom_;- ctx.font = `bold ${fontSize}px system-ui, sans-serif`;- ctx.textAlign = 'left';- ctx.textBaseline = 'bottom';- const label = 'ScreenSpace';- const pad = 2 / this.zoom_;- const metrics = ctx.measureText(label);- ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';- ctx.fillRect(x, y - fontSize - pad * 2, metrics.width + pad * 2, fontSize + pad * 2);- ctx.fillStyle = '#ffb400';- ctx.fillText(label, x + pad, y - pad);-- ctx.restore();- }-- private drawCameraIcon(ctx: CanvasRenderingContext2D, color: string): void {- const s = 1 / this.zoom_;- const bodyW = 16 * s;- const bodyH = 12 * s;- const lensW = 6 * s;- const lensH1 = 8 * s;- const lensH2 = 12 * s;-- ctx.strokeStyle = color;- ctx.fillStyle = color;- ctx.lineWidth = 1.5 * s;-- ctx.beginPath();- ctx.rect(-bodyW / 2, -bodyH / 2, bodyW, bodyH);- ctx.stroke();-- ctx.beginPath();- ctx.moveTo(bodyW / 2, -lensH1 / 2);- ctx.lineTo(bodyW / 2 + lensW, -lensH2 / 2);- ctx.lineTo(bodyW / 2 + lensW, lensH2 / 2);- ctx.lineTo(bodyW / 2, lensH1 / 2);- ctx.closePath();- ctx.stroke();-- const dotR = 2 * s;- ctx.beginPath();- ctx.arc(-bodyW / 4, -bodyH / 2 - dotR - 1 * s, dotR, 0, Math.PI * 2);- ctx.fill();- }-- private hexToRgb(hex: string): [number, number, number] {- const num = parseInt(hex.replace('#', ''), 16);- return [(num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff];- }-- private drawStats(ctx: CanvasRenderingContext2D, canvasWidth: number, canvasHeight: number): void {- if (!getSettingsValue<boolean>('scene.showStats') || !this.useWebGL_) return;-- const stats = Renderer.getStats();- const spineCount = this.sceneRenderer_?.spineInstanceCount ?? stats.spine;-- const lines = [- `DC: ${stats.drawCalls} Tri: ${stats.triangles}`,- `Sprite: ${stats.sprites} Spine: ${spineCount}`,- `Text: ${stats.text} Mesh: ${stats.meshes}`,- `Culled: ${stats.culled}`,- ];-- const fontSize = 12;- const lineHeight = 18;- const padding = 8;- const panelW = 180;- const panelH = lines.length * lineHeight + padding * 2;- const x0 = 12;- const y0 = canvasHeight - panelH - 12;-- ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';- ctx.fillRect(x0, y0, panelW, panelH);-- ctx.fillStyle = '#ffffff';- ctx.font = `${fontSize}px monospace`;- ctx.textAlign = 'left';- ctx.textBaseline = 'top';-- for (let i = 0; i < lines.length; i++) {- ctx.fillText(lines[i], x0 + padding, y0 + padding + i * lineHeight);- }- }-- private drawViewportPreview(ctx: CanvasRenderingContext2D, canvasWidth: number, canvasHeight: number): void {- const cameraEntities: Array<{ name: string; color: string; vpX: number; vpY: number; vpW: number; vpH: number }> = [];-- let idx = 0;- for (const entity of this.store_.scene.entities) {- const camera = entity.components.find(c => c.type === 'Camera');- if (!camera) continue;- cameraEntities.push({- name: entity.name,- color: CAMERA_COLORS[idx % CAMERA_COLORS.length],- vpX: (camera.data.viewportX as number) ?? 0,- vpY: (camera.data.viewportY as number) ?? 0,- vpW: (camera.data.viewportW as number) ?? 1,- vpH: (camera.data.viewportH as number) ?? 1,- });- idx++;- }-- if (cameraEntities.length < 2) return;-- const previewW = 160;- const previewH = 90;- const padding = 12;- const x0 = canvasWidth - previewW - padding;- const y0 = canvasHeight - previewH - padding;-- ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';- ctx.fillRect(x0 - 1, y0 - 1, previewW + 2, previewH + 2);-- ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';- ctx.lineWidth = 1;- ctx.setLineDash([]);- ctx.strokeRect(x0, y0, previewW, previewH);-- for (const cam of cameraEntities) {- const rx = x0 + cam.vpX * previewW;- const ry = y0 + cam.vpY * previewH;- const rw = cam.vpW * previewW;- const rh = cam.vpH * previewH;-- const [cr, cg, cb] = this.hexToRgb(cam.color);- ctx.fillStyle = `rgba(${cr}, ${cg}, ${cb}, 0.25)`;- ctx.fillRect(rx, ry, rw, rh);-- ctx.strokeStyle = cam.color;- ctx.lineWidth = 1;- ctx.strokeRect(rx, ry, rw, rh);-- ctx.fillStyle = cam.color;- ctx.font = '9px system-ui, sans-serif';- ctx.textAlign = 'left';- ctx.textBaseline = 'top';- ctx.fillText(cam.name, rx + 3, ry + 2, rw - 6);- }- }-- private renderPreview(): void {- const ctx = this.canvas_.getContext('2d');- if (!ctx) return;-- const w = this.canvas_.width;- const h = this.canvas_.height;-- ctx.fillStyle = '#1a1a1a';- ctx.fillRect(0, 0, w, h);-- ctx.save();- ctx.translate(w / 2 + this.panX_ * this.zoom_, h / 2 + this.panY_ * this.zoom_);- ctx.scale(this.zoom_, this.zoom_);-- this.drawGrid(ctx, w, h);-- const scene = this.store_.scene;- const selectedEntity = this.store_.selectedEntity;-- for (const entity of scene.entities) {- if (!this.store_.isEntityVisible(entity.id)) continue;- this.drawEntity(ctx, entity, entity.id === selectedEntity);- }-- this.drawCameraFrustums(ctx);- this.drawScreenSpaceBounds(ctx);-- if (getSettingsValue<boolean>('scene.showColliders')) {- this.colliderOverlay_.drawAll({- ctx,- zoom: this.zoom_,- store: this.store_,- });- }-- if (selectedEntity !== null && this.store_.isEntityVisible(selectedEntity as number)) {- if (this.gizmoManager_.getActiveId() !== 'select' && getSettingsValue<boolean>('scene.showGizmos')) {- this.gizmoManager_.setContext(this.createGizmoContext(ctx));- this.gizmoManager_.draw();- }- }-- if (this.marqueeActive_) {- this.drawMarquee(ctx);- }-- ctx.restore();- }-- private drawGrid(ctx: CanvasRenderingContext2D, w: number, h: number): void {- if (!getSettingsValue<boolean>('scene.showGrid')) return;-- const gridSize = getSettingsValue<number>('scene.gridSize') ?? 50;- const baseOpacity = getSettingsValue<number>('scene.gridOpacity');- const gridColor = getSettingsValue<string>('scene.gridColor');- const halfW = w / 2 / this.zoom_;- const halfH = h / 2 / this.zoom_;-- const screenGridSize = gridSize * this.zoom_;-- if (screenGridSize > 100) {- const subDiv = screenGridSize > 250 ? 10 : 5;- const subSize = gridSize / subDiv;- this.drawGridLines(ctx, subSize, halfW, halfH, gridColor, baseOpacity * 0.3);- }-- this.drawGridLines(ctx, gridSize, halfW, halfH, gridColor, baseOpacity);-- if (screenGridSize < 15) {- const majorSize = gridSize * (screenGridSize < 5 ? 10 : 5);- this.drawGridLines(ctx, majorSize, halfW, halfH, gridColor, baseOpacity);- }-- ctx.globalAlpha = baseOpacity;- ctx.strokeStyle = this.lightenColor(gridColor, 30);- ctx.lineWidth = 2 / this.zoom_;- const startX = Math.floor((-halfW - this.panX_) / gridSize) * gridSize;- const endX = Math.ceil((halfW - this.panX_) / gridSize) * gridSize;- const startY = Math.floor((-halfH - this.panY_) / gridSize) * gridSize;- const endY = Math.ceil((halfH - this.panY_) / gridSize) * gridSize;- ctx.beginPath();- ctx.moveTo(startX, 0);- ctx.lineTo(endX, 0);- ctx.stroke();- ctx.beginPath();- ctx.moveTo(0, startY);- ctx.lineTo(0, endY);- ctx.stroke();-- ctx.globalAlpha = 1;- }-- private drawGridLines(- ctx: CanvasRenderingContext2D,- step: number,- halfW: number,- halfH: number,- color: string,- opacity: number,- ): void {- const startX = Math.floor((-halfW - this.panX_) / step) * step;- const endX = Math.ceil((halfW - this.panX_) / step) * step;- const startY = Math.floor((-halfH - this.panY_) / step) * step;- const endY = Math.ceil((halfH - this.panY_) / step) * step;-- ctx.globalAlpha = opacity;- ctx.strokeStyle = color;- ctx.lineWidth = 1 / this.zoom_;-- for (let x = startX; x <= endX; x += step) {- if (x === 0) continue;- ctx.beginPath();- ctx.moveTo(x, startY);- ctx.lineTo(x, endY);- ctx.stroke();- }-- for (let y = startY; y <= endY; y += step) {- if (y === 0) continue;- ctx.beginPath();- ctx.moveTo(startX, y);- ctx.lineTo(endX, y);- ctx.stroke();- }- }-- private lightenColor(hex: string, percent: number): string {- const num = parseInt(hex.replace('#', ''), 16);- const r = Math.min(255, ((num >> 16) & 0xff) + Math.round(255 * percent / 100));- const g = Math.min(255, ((num >> 8) & 0xff) + Math.round(255 * percent / 100));- const b = Math.min(255, (num & 0xff) + Math.round(255 * percent / 100));- return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, '0')}`;- }-- private createSpriteFromDrop(- asset: { type: string; path: string; name: string },- worldX: number,- worldY: number- ): void {- const baseName = asset.name.replace(/\.[^.]+$/, '');- const newEntity = this.store_.createEntity(baseName);-- const transformData = getInitialComponentData('LocalTransform');- transformData.position = { x: worldX, y: worldY, z: 0 };- this.store_.addComponent(newEntity, 'LocalTransform', transformData);-- const relativePath = getGlobalPathResolver().toRelativePath(asset.path);- this.store_.addComponent(newEntity, 'Sprite', {- ...getInitialComponentData('Sprite'),- texture: relativePath,- });-- this.loadImageSize(asset.path).then(size => {- if (size) {- const defaultSize = getDefaultComponentData('Sprite').size;- this.store_.updateProperty(newEntity, 'Sprite', 'size', defaultSize, size);- }- });- }-- private loadImageSize(absolutePath: string): Promise<{ x: number; y: number } | null> {- return new Promise((resolve) => {- const img = new Image();- img.onload = () => resolve({ x: img.naturalWidth, y: img.naturalHeight });- img.onerror = () => resolve(null);- img.src = getPlatformAdapter().convertFilePathToUrl(absolutePath);- });- }-- private drawEntity(- ctx: CanvasRenderingContext2D,- entity: import('../types/SceneTypes').EntityData,- isSelected: boolean- ): void {- const transform = entity.components.find(c => c.type === 'LocalTransform');- const sprite = entity.components.find(c => c.type === 'Sprite');-- if (!transform) return;-- const worldTransform = this.store_.getWorldTransform(entity.id);- const pos = worldTransform.position;- const scale = worldTransform.scale;-- let w = 50;- let h = 50;- let color: { r: number; g: number; b: number; a: number } | null = null;- const hasSprite = !!sprite;- let textureImg: HTMLImageElement | null = null;- let flipX = false;- let flipY = false;-- if (sprite) {- const size = sprite.data.size as { x: number; y: number };- const col = sprite.data.color as { r: number; g: number; b: number; a: number };- const texturePath = sprite.data.texture;-- if (size) {- w = size.x * Math.abs(scale.x);- h = size.y * Math.abs(scale.y);- }- if (col) {- color = col;- }-- flipX = sprite.data.flipX === true;- flipY = sprite.data.flipY === true;-- if (typeof texturePath === 'string' && texturePath) {- textureImg = this.loadTexture(texturePath);- }- }-- ctx.save();- ctx.translate(pos.x, -pos.y);-- if (flipX || flipY) {- ctx.scale(flipX ? -1 : 1, flipY ? -1 : 1);- }-- if (hasSprite) {- if (textureImg) {- ctx.globalAlpha = color?.a ?? 1;- ctx.drawImage(textureImg, -w / 2, -h / 2, w, h);-- if (color && (color.r !== 1 || color.g !== 1 || color.b !== 1)) {- ctx.globalCompositeOperation = 'multiply';- const r = Math.round(color.r * 255);- const g = Math.round(color.g * 255);- const b = Math.round(color.b * 255);- ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;- ctx.fillRect(-w / 2, -h / 2, w, h);- ctx.globalCompositeOperation = 'source-over';- }- ctx.globalAlpha = 1;- } else {- const r = Math.round((color?.r ?? 0.4) * 255);- const g = Math.round((color?.g ?? 0.4) * 255);- const b = Math.round((color?.b ?? 0.8) * 255);- const a = color?.a ?? 0.5;- ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;- ctx.fillRect(-w / 2, -h / 2, w, h);- }- }-- ctx.restore();-- if (isSelected && hasSprite) {- ctx.save();- ctx.translate(pos.x, -pos.y);-- ctx.strokeStyle = '#00aaff';- ctx.lineWidth = 2 / this.zoom_;- ctx.setLineDash([]);- ctx.strokeRect(-w / 2, -h / 2, w, h);-- ctx.fillStyle = '#00aaff';- const handleSize = 6 / this.zoom_;- const corners = [- [-w / 2, -h / 2],- [w / 2, -h / 2],- [-w / 2, h / 2],- [w / 2, h / 2],- ];- for (const [cx, cy] of corners) {- ctx.fillRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);- }-- ctx.restore();- }- }-}+export { SceneViewPanel } from './scene-view/SceneViewPanel';+export type { SceneViewPanelOptions } from './scene-view/SceneViewPanel';diff --git a/editor/src/panels/builtinPanels.ts b/editor/src/panels/builtinPanels.tsindex 17f636869..e5429060f 100644--- a/editor/src/panels/builtinPanels.ts+++ b/editor/src/panels/builtinPanels.ts@@ -1,8 +1,8 @@import { registerPanel } from './PanelRegistry';-import { HierarchyPanel } from './HierarchyPanel';+import { HierarchyPanel } from './hierarchy/HierarchyPanel';import { InspectorPanel } from './InspectorPanel';-import { SceneViewPanel } from './SceneViewPanel';-import { ContentBrowserPanel } from './ContentBrowserPanel';+import { SceneViewPanel } from './scene-view/SceneViewPanel';+import { ContentBrowserPanel } from './content-browser/ContentBrowserPanel';import { OutputPanel } from './OutputPanel';import { icons } from '../utils/icons';diff --git a/editor/src/panels/content-browser/AssetContextMenu.ts b/editor/src/panels/content-browser/AssetContextMenu.tsnew file mode 100644index 000000000..b8e08c5d9--- /dev/null+++ b/editor/src/panels/content-browser/AssetContextMenu.ts@@ -0,0 +1,514 @@+import { icons } from '../../utils/icons';+import { showContextMenu, type ContextMenuItem } from '../../ui/ContextMenu';+import { getContextMenuItems, type ContextMenuContext } from '../../ui/ContextMenuRegistry';+import { getPlatformAdapter } from '../../platform/PlatformAdapter';+import { showInputDialog, showConfirmDialog } from '../../ui/dialog';+import { joinPath, getParentDir } from '../../utils/path';+import { getAssetLibrary } from '../../asset/AssetLibrary';+import { showErrorToast } from '../../ui/Toast';+import { createEmptyScene } from '../../types/SceneTypes';+import { getSettingsValue } from '../../settings';+import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT } from 'esengine';+import type { AssetItem, ContentBrowserState } from './ContentBrowserTypes';+import { getNativeFS } from './ContentBrowserTypes';++export function showAssetContextMenu(state: ContentBrowserState, e: MouseEvent, path: string, type: AssetItem['type']): void {+ const fs = getNativeFS();+ const parentPath = getParentDir(path);+ const fileName = path.split('/').pop() ?? path;++ const items: ContextMenuItem[] = [+ {+ label: 'Show in Folder',+ icon: icons.folderOpen(14),+ onClick: () => { fs?.openFolder(parentPath); },+ },+ {+ label: 'Copy Path',+ icon: icons.copy(14),+ onClick: () => { navigator.clipboard.writeText(path); },+ },+ {+ label: 'Rename',+ icon: icons.pencil(14),+ onClick: () => renameAsset(state, path, type),+ },+ { separator: true, label: '' },+ {+ label: 'Delete',+ icon: icons.trash(14),+ onClick: () => deleteAsset(state, path, fileName),+ },+ ];++ const ctx: ContextMenuContext = { location: 'content-browser.asset', assetPath: path, assetType: type };+ const extensionItems = getContextMenuItems('content-browser.asset', ctx);+ if (extensionItems.length > 0) {+ items.push({ label: '', separator: true }, ...extensionItems);+ }++ showContextMenu({ x: e.clientX, y: e.clientY, items });+}++export function showMultiSelectContextMenu(state: ContentBrowserState, e: MouseEvent): void {+ const count = state.selectedPaths.size;+ const items: ContextMenuItem[] = [+ {+ label: `Delete ${count} items`,+ icon: icons.trash(14),+ onClick: () => deleteSelectedAssets(state),+ },+ ];++ showContextMenu({ x: e.clientX, y: e.clientY, items });+}++export function showFolderContextMenu(state: ContentBrowserState, e: MouseEvent, path: string): void {+ const fs = getNativeFS();++ const items: ContextMenuItem[] = [+ {+ label: 'Create',+ icon: icons.plus(14),+ children: [+ { label: 'Folder', icon: icons.folder(14), onClick: () => createNewFolder(state, path) },+ { label: '', separator: true },+ { label: 'Script', icon: icons.code(14), onClick: () => createNewScript(state, path) },+ { label: 'Material', icon: icons.settings(14), onClick: () => createNewMaterial(state, path) },+ { label: 'Shader', icon: icons.code(14), onClick: () => createNewShader(state, path) },+ { label: 'BitmapFont', icon: icons.type(14), onClick: () => createNewBitmapFont(state, path) },+ { label: 'Scene', icon: icons.layers(14), onClick: () => createNewScene(state, path) },+ ],+ },+ { label: '', separator: true },+ {+ label: 'Show in Folder',+ icon: icons.folderOpen(14),+ onClick: () => { fs?.openFolder(path); },+ },+ {+ label: 'Copy Path',+ icon: icons.copy(14),+ onClick: () => { navigator.clipboard.writeText(path); },+ },+ { label: '', separator: true },+ {+ label: 'Refresh',+ icon: icons.refresh(14),+ onClick: () => { state.refresh(); },+ },+ ];++ const ctx: ContextMenuContext = { location: 'content-browser.folder', assetPath: path, assetType: 'folder' };+ const extensionItems = getContextMenuItems('content-browser.folder', ctx);+ if (extensionItems.length > 0) {+ items.push({ label: '', separator: true }, ...extensionItems);+ }++ showContextMenu({ x: e.clientX, y: e.clientY, items });+}++export async function deleteSelectedAssets(state: ContentBrowserState): Promise<void> {+ const paths = Array.from(state.selectedPaths);+ const names = paths.map(p => p.split('/').pop() ?? p);+ const message = paths.length === 1+ ? `Are you sure you want to delete "${names[0]}"?`+ : `Are you sure you want to delete ${paths.length} items?`;++ const confirmed = await showConfirmDialog({+ title: 'Delete Assets',+ message,+ confirmText: 'Delete',+ danger: true,+ });++ if (!confirmed) return;++ const platform = getPlatformAdapter();+ for (const path of paths) {+ try {+ await platform.remove(path);+ const metaPath = `${path}.meta`;+ try { await platform.remove(metaPath); } catch { /* no .meta file */ }++ if (state.rootFolder) {+ const projectDir = state.rootFolder.path;+ const prefix = projectDir.endsWith('/') ? projectDir : projectDir + '/';+ if (path.startsWith(prefix)) {+ getAssetLibrary().unregister(path.substring(prefix.length));+ }+ }+ } catch (err) {+ console.error('Failed to delete asset:', err);+ showErrorToast('Failed to delete asset', String(err));+ }+ }++ state.selectedPaths.clear();+ state.lastSelectedPath = null;+ state.refresh();+}++async function deleteAsset(state: ContentBrowserState, path: string, name: string): Promise<void> {+ const confirmed = await showConfirmDialog({+ title: 'Delete Asset',+ message: `Are you sure you want to delete "${name}"?`,+ confirmText: 'Delete',+ danger: true,+ });++ if (!confirmed) return;++ try {+ const platform = getPlatformAdapter();+ await platform.remove(path);++ const metaPath = `${path}.meta`;+ try { await platform.remove(metaPath); } catch { /* no .meta file */ }++ if (state.rootFolder) {+ const projectDir = state.rootFolder.path;+ const prefix = projectDir.endsWith('/') ? projectDir : projectDir + '/';+ if (path.startsWith(prefix)) {+ getAssetLibrary().unregister(path.substring(prefix.length));+ }+ }++ state.refresh();+ } catch (err) {+ console.error('Failed to delete asset:', err);+ showErrorToast('Failed to delete asset', String(err));+ }+}++export async function renameAsset(state: ContentBrowserState, path: string, type: AssetItem['type']): Promise<void> {+ const platform = getPlatformAdapter();+ const parentPath = getParentDir(path);+ const fileName = path.split('/').pop() ?? path;+ const dotIndex = fileName.lastIndexOf('.');+ const baseName = type === 'folder' || dotIndex <= 0 ? fileName : fileName.substring(0, dotIndex);+ const extension = type === 'folder' || dotIndex <= 0 ? '' : fileName.substring(dotIndex);++ const newName = await showInputDialog({+ title: 'Rename',+ placeholder: 'Name',+ defaultValue: baseName,+ confirmText: 'Rename',+ validator: async (value) => {+ if (!value.trim()) return 'Name is required';+ if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {+ return 'Name contains invalid characters';+ }+ const newFileName = extension ? value.trim() + extension : value.trim();+ if (newFileName === fileName) return null;+ const newPath = `${parentPath}/${newFileName}`;+ if (await platform.exists(newPath)) {+ return 'A file with this name already exists';+ }+ return null;+ },+ });++ if (!newName) return;++ const trimmed = newName.trim();+ const newFileName = extension ? trimmed + extension : trimmed;+ if (newFileName === fileName) return;++ const newPath = `${parentPath}/${newFileName}`;++ try {+ await platform.rename(path, newPath);++ const metaPath = `${path}.meta`;+ if (await platform.exists(metaPath)) {+ await platform.rename(metaPath, `${newPath}.meta`);+ }++ if (state.rootFolder) {+ const projectDir = state.rootFolder.path;+ const prefix = projectDir.endsWith('/') ? projectDir : projectDir + '/';+ if (path.startsWith(prefix)) {+ getAssetLibrary().updatePath(+ path.substring(prefix.length),+ newPath.substring(prefix.length)+ );+ }+ }++ state.refresh();+ } catch (err) {+ console.error('Failed to rename asset:', err);+ showErrorToast('Failed to rename asset', String(err));+ }+}++async function createNewFolder(state: ContentBrowserState, parentPath: string): Promise<void> {+ const name = await promptFileName('New Folder', '', parentPath);+ if (!name) return;++ const platform = getPlatformAdapter();+ const folderPath = `${parentPath}/${name}`;++ try {+ await platform.mkdir(folderPath);+ state.refresh();+ } catch (err) {+ console.error('Failed to create folder:', err);+ showErrorToast('Failed to create folder', String(err));+ }+}++async function createNewScript(state: ContentBrowserState, parentPath: string): Promise<void> {+ const name = await promptFileName('NewScript', '.ts', parentPath);+ if (!name) return;++ const platform = getPlatformAdapter();+ const filePath = `${parentPath}/${name}`;++ const className = toClassName(name);+ const content = `import { defineComponent } from 'esengine';++export const ${className} = defineComponent('${className}', {+ value: 0,+});+`;++ try {+ await platform.writeTextFile(filePath, content);+ state.refresh();+ } catch (err) {+ console.error('Failed to create script:', err);+ showErrorToast('Failed to create script', String(err));+ }+}++async function createNewMaterial(state: ContentBrowserState, parentPath: string): Promise<void> {+ const name = await promptFileName('NewMaterial', '.esmaterial', parentPath);+ if (!name) return;++ const platform = getPlatformAdapter();+ const filePath = `${parentPath}/${name}`;++ const content = JSON.stringify({+ version: '1.0',+ type: 'material',+ shader: '',+ blendMode: 0,+ depthTest: false,+ properties: {},+ }, null, 2);++ try {+ await platform.writeTextFile(filePath, content);+ state.refresh();+ } catch (err) {+ console.error('Failed to create material:', err);+ showErrorToast('Failed to create material', String(err));+ }+}++async function createNewScene(state: ContentBrowserState, parentPath: string): Promise<void> {+ const name = await promptFileName('NewScene', '.esscene', parentPath);+ if (!name) return;++ const platform = getPlatformAdapter();+ const filePath = `${parentPath}/${name}`;++ const w = getSettingsValue<number>('project.designWidth') || DEFAULT_DESIGN_WIDTH;+ const h = getSettingsValue<number>('project.designHeight') || DEFAULT_DESIGN_HEIGHT;+ const scene = createEmptyScene(name.replace('.esscene', ''), { width: w, height: h });+ const content = JSON.stringify(scene, null, 2);++ try {+ await platform.writeTextFile(filePath, content);+ state.refresh();+ if (state.onOpenScene) {+ state.onOpenScene(filePath);+ }+ } catch (err) {+ console.error('Failed to create scene:', err);+ showErrorToast('Failed to create scene', String(err));+ }+}++async function createNewShader(state: ContentBrowserState, parentPath: string): Promise<void> {+ const name = await promptFileName('NewShader', '.esshader', parentPath);+ if (!name) return;++ const platform = getPlatformAdapter();+ const filePath = `${parentPath}/${name}`;+ const shaderName = name.replace('.esshader', '');++ const content = `#pragma shader "${shaderName}"++#pragma vertex+attribute vec2 a_position;+attribute vec2 a_texCoord;++uniform mat4 u_projection;+uniform mat4 u_model;++varying vec2 v_texCoord;++void main() {+ v_texCoord = a_texCoord;+ gl_Position = u_projection * u_model * vec4(a_position, 0.0, 1.0);+}+#pragma end++#pragma fragment+precision mediump float;++varying vec2 v_texCoord;++void main() {+ gl_FragColor = vec4(v_texCoord, 0.0, 1.0);+}+#pragma end+`;++ try {+ await platform.writeTextFile(filePath, content);+ state.refresh();+ } catch (err) {+ console.error('Failed to create shader:', err);+ showErrorToast('Failed to create shader', String(err));+ }+}++async function createNewBitmapFont(state: ContentBrowserState, parentPath: string): Promise<void> {+ const name = await promptFileName('NewFont', '.bmfont', parentPath);+ if (!name) return;++ const platform = getPlatformAdapter();+ const filePath = `${parentPath}/${name}`;++ const content = JSON.stringify({+ version: '1.0',+ type: 'label-atlas',+ glyphs: {},+ }, null, 2);++ try {+ await platform.writeTextFile(filePath, content);+ state.refresh();+ } catch (err) {+ console.error('Failed to create bitmap font:', err);+ showErrorToast('Failed to create bitmap font', String(err));+ }+}++async function promptFileName(defaultName: string, extension: string = '', parentPath?: string): Promise<string | null> {+ const platform = getPlatformAdapter();++ const name = await showInputDialog({+ title: 'Enter Name',+ placeholder: 'Name',+ defaultValue: defaultName,+ confirmText: 'Create',+ validator: async (value) => {+ if (!value.trim()) return 'Name is required';+ if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {+ return 'Name contains invalid characters';+ }+ if (parentPath) {+ const fileName = extension && !value.trim().endsWith(extension)+ ? value.trim() + extension+ : value.trim();+ const fullPath = `${parentPath}/${fileName}`;+ if (await platform.exists(fullPath)) {+ return 'A file with this name already exists';+ }+ }+ return null;+ },+ });++ if (!name) return null;++ const trimmed = name.trim();+ if (extension && !trimmed.endsWith(extension)) {+ return trimmed + extension;+ }+ return trimmed;+}++function toClassName(filename: string): string {+ const name = filename.replace(/\.(ts|js)$/, '');+ return name.charAt(0).toUpperCase() + name.slice(1);+}++export async function importDroppedFiles(state: ContentBrowserState, files: FileList): Promise<void> {+ const fs = getNativeFS();+ if (!fs || !state.currentPath) return;++ for (const file of Array.from(files)) {+ const destPath = joinPath(state.currentPath, file.name);+ const exists = await fs.exists(destPath);+ if (exists) {+ const overwrite = await showConfirmDialog({+ title: 'File Exists',+ message: `"${file.name}" already exists. Overwrite?`,+ confirmText: 'Overwrite',+ });+ if (!overwrite) continue;+ }++ const buffer = await file.arrayBuffer();+ await fs.writeBinaryFile(destPath, new Uint8Array(buffer));+ }+}++export async function saveDroppedEntityAsPrefab(state: ContentBrowserState, entityId: number): Promise<void> {+ const entityData = state.store.getEntityData(entityId);+ if (!entityData) return;++ const targetDir = state.currentPath;+ if (!targetDir) return;++ if (state.rootFolder) {+ const assetsDir = joinPath(state.rootFolder.path, 'assets');+ if (!targetDir.startsWith(assetsDir)) {+ showErrorToast('Cannot save prefab outside assets directory', 'Please navigate to the assets folder first');+ return;+ }+ }++ const platform = getPlatformAdapter();++ const name = await showInputDialog({+ title: 'Save as Prefab',+ placeholder: 'Prefab name',+ defaultValue: entityData.name,+ confirmText: 'Save',+ validator: async (value) => {+ if (!value.trim()) return 'Name is required';+ if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {+ return 'Name contains invalid characters';+ }+ const fileName = value.trim().endsWith('.esprefab')+ ? value.trim()+ : `${value.trim()}.esprefab`;+ const fullPath = joinPath(targetDir, fileName);+ if (await platform.exists(fullPath)) {+ return 'A file with this name already exists';+ }+ return null;+ },+ });++ if (!name) return;++ const fileName = name.trim().endsWith('.esprefab')+ ? name.trim()+ : `${name.trim()}.esprefab`;+ const filePath = joinPath(targetDir, fileName);++ const success = await state.store.saveAsPrefab(entityId, filePath);+ if (success) {+ state.refresh();+ } else {+ showErrorToast('Failed to save prefab', filePath);+ }+}diff --git a/editor/src/panels/content-browser/AssetGrid.ts b/editor/src/panels/content-browser/AssetGrid.tsnew file mode 100644index 000000000..8ac46ac4e--- /dev/null+++ b/editor/src/panels/content-browser/AssetGrid.ts@@ -0,0 +1,182 @@+import { icons } from '../../utils/icons';+import { joinPath } from '../../utils/path';+import type { AssetItem, ContentBrowserState } from './ContentBrowserTypes';+import { getNativeFS, getAssetType, getAssetIcon, isImageFile, SEARCH_RESULTS_LIMIT } from './ContentBrowserTypes';+import type { ThumbnailCache } from './ThumbnailCache';+import { searchRecursive } from './AssetSearch';+import { findFolder } from './FolderTree';++export async function renderGrid(state: ContentBrowserState, thumbnailCache: ThumbnailCache): Promise<void> {+ if (!state.gridContainer) return;++ let items: AssetItem[];+ if (state.searchFilter) {+ items = await searchRecursive(state.currentPath, state.searchFilter);+ } else {+ items = await loadCurrentFolderItems(state);+ }+ state.currentItems = items;++ let filteredItems = items;+ if (state.searchFilter) {+ filteredItems = items.slice(0, SEARCH_RESULTS_LIMIT);+ }+ state.filteredItems = filteredItems;++ if (filteredItems.length === 0) {+ state.gridContainer.innerHTML = renderEmptyState(state.searchFilter);+ state.gridContainer.classList.remove('es-cb-list-view');+ if (state.footerContainer) {+ state.footerContainer.textContent = '0 items';+ }+ return;+ }++ const isDraggable = (type: AssetItem['type']) => type !== 'folder';++ if (state.viewMode === 'list') {+ state.gridContainer.classList.add('es-cb-list-view');+ state.gridContainer.innerHTML = filteredItems+ .map((item) => {+ const iconHtml = getItemIconHtml(item, 24, thumbnailCache);+ const subtext = item.relativePath+ ? `<span class="es-cb-list-subpath">${item.relativePath}</span>`+ : '';+ return `+ <div class="es-cb-list-row${state.selectedPaths.has(item.path) ? ' es-selected' : ''}"+ data-path="${item.path}"+ data-type="${item.type}"+ ${isDraggable(item.type) ? 'draggable="true"' : ''}>+ <span class="es-cb-list-icon">${iconHtml}</span>+ <span class="es-cb-list-name">${item.name}${subtext}</span>+ <span class="es-cb-list-type">${item.type}</span>+ </div>`;+ })+ .join('');+ } else {+ state.gridContainer.classList.remove('es-cb-list-view');+ state.gridContainer.innerHTML = filteredItems+ .map((item) => {+ const iconHtml = getItemIconHtml(item, 32, thumbnailCache);+ const subtext = item.relativePath+ ? `<div class="es-asset-subpath">${item.relativePath}</div>`+ : '';+ return `+ <div class="es-asset-item${state.selectedPaths.has(item.path) ? ' es-selected' : ''}"+ data-path="${item.path}"+ data-type="${item.type}"+ ${isDraggable(item.type) ? 'draggable="true"' : ''}>+ <div class="es-asset-icon">${iconHtml}</div>+ <div class="es-asset-name">${item.name}</div>+ ${subtext}+ </div>`;+ })+ .join('');+ }++ for (const item of filteredItems) {+ if (item.type === 'image' && isImageFile(item.name)) {+ loadThumbnailFor(state, item.path, thumbnailCache);+ }+ }++ if (state.footerContainer) {+ const suffix = state.searchFilter && items.length > SEARCH_RESULTS_LIMIT+ ? ` (showing ${SEARCH_RESULTS_LIMIT} of ${items.length})`+ : '';+ state.footerContainer.textContent = `${filteredItems.length} items${suffix}`;+ }+}++function getItemIconHtml(item: AssetItem, size: number, thumbnailCache: ThumbnailCache): string {+ if (item.type === 'image' && isImageFile(item.name)) {+ const cached = thumbnailCache.get(item.path);+ if (cached) {+ return `<img src="${cached}" width="${size}" height="${size}" class="es-cb-thumbnail" alt="">`;+ }+ if (thumbnailCache.isLoading(item.path)) {+ return `<span class="es-cb-thumb-loading">${getAssetIcon(item.type, size)}</span>`;+ }+ }+ return getAssetIcon(item.type, size);+}++function loadThumbnailFor(state: ContentBrowserState, path: string, thumbnailCache: ThumbnailCache): void {+ thumbnailCache.load(path, () => {+ updateThumbnailInDom(state, path, thumbnailCache);+ });+}++function updateThumbnailInDom(state: ContentBrowserState, path: string, thumbnailCache: ThumbnailCache): void {+ if (!state.gridContainer) return;+ const dataUrl = thumbnailCache.get(path);+ if (!dataUrl) return;++ const selector = state.viewMode === 'list' ? '.es-cb-list-row' : '.es-asset-item';+ const items = state.gridContainer.querySelectorAll(selector);+ for (const el of items) {+ const htmlEl = el as HTMLElement;+ if (htmlEl.dataset.path !== path) continue;++ const iconContainer = state.viewMode === 'list'+ ? htmlEl.querySelector('.es-cb-list-icon')+ : htmlEl.querySelector('.es-asset-icon');+ if (iconContainer) {+ const size = state.viewMode === 'list' ? 24 : 32;+ iconContainer.innerHTML = `<img src="${dataUrl}" width="${size}" height="${size}" class="es-cb-thumbnail" alt="">`;+ }+ break;+ }+}++function renderEmptyState(searchFilter: string): string {+ if (searchFilter) {+ return `<div class="es-cb-empty-state">+ <div class="es-cb-empty-icon">${icons.search(32)}</div>+ <div class="es-cb-empty-text">No matching assets found</div>+ </div>`;+ }+ return `<div class="es-cb-empty-state">+ <div class="es-cb-empty-icon">${icons.folder(32)}</div>+ <div class="es-cb-empty-text">This folder is empty</div>+ </div>`;+}++async function loadCurrentFolderItems(state: ContentBrowserState): Promise<AssetItem[]> {+ const fs = getNativeFS();+ if (!fs || !state.currentPath) {+ return getFallbackItems(state);+ }++ try {+ const entries = await fs.listDirectoryDetailed(state.currentPath);++ return entries+ .filter(e => !e.name.startsWith('.') && !e.name.endsWith('.meta'))+ .sort((a, b) => {+ if (a.isDirectory !== b.isDirectory) {+ return a.isDirectory ? -1 : 1;+ }+ return a.name.localeCompare(b.name);+ })+ .map(e => ({+ name: e.name,+ path: joinPath(state.currentPath, e.name),+ type: getAssetType(e),+ }));+ } catch (err) {+ console.error('Failed to load folder items:', err);+ return getFallbackItems(state);+ }+}++function getFallbackItems(state: ContentBrowserState): AssetItem[] {+ const currentFolder = findFolder(state.rootFolder, state.currentPath);+ if (!currentFolder) return [];++ return currentFolder.children.map((child) => ({+ name: child.name,+ path: child.path,+ type: 'folder' as const,+ }));+}diff --git a/editor/src/panels/content-browser/AssetSearch.ts b/editor/src/panels/content-browser/AssetSearch.tsnew file mode 100644index 000000000..427d26523--- /dev/null+++ b/editor/src/panels/content-browser/AssetSearch.ts@@ -0,0 +1,55 @@+import { joinPath } from '../../utils/path';+import { fuzzyMatch } from '../../utils/fuzzy';+import type { AssetItem } from './ContentBrowserTypes';+import { getNativeFS, getAssetType, SEARCH_RESULTS_LIMIT } from './ContentBrowserTypes';++export async function searchRecursive(basePath: string, filter: string): Promise<AssetItem[]> {+ const fs = getNativeFS();+ if (!fs || !basePath) return [];++ const scored: Array<{ item: AssetItem; score: number }> = [];+ const stack = [basePath];++ while (stack.length > 0 && scored.length < SEARCH_RESULTS_LIMIT * 2) {+ const dir = stack.pop()!;+ try {+ const entries = await fs.listDirectoryDetailed(dir);+ for (const entry of entries) {+ if (entry.name.startsWith('.') || entry.name.endsWith('.meta')) continue;++ const entryPath = joinPath(dir, entry.name);++ if (entry.isDirectory) {+ stack.push(entryPath);+ const match = fuzzyMatch(filter, entry.name);+ if (match) {+ const relative = entryPath.substring(basePath.length).replace(/^\//, '');+ scored.push({+ item: { name: entry.name, path: entryPath, type: 'folder', relativePath: relative },+ score: match.score,+ });+ }+ } else {+ const match = fuzzyMatch(filter, entry.name);+ if (match) {+ const relative = entryPath.substring(basePath.length).replace(/^\//, '');+ scored.push({+ item: { name: entry.name, path: entryPath, type: getAssetType(entry), relativePath: relative },+ score: match.score,+ });+ }+ }+ }+ } catch {+ // skip inaccessible directories+ }+ }++ return scored+ .sort((a, b) => {+ if (a.item.type === 'folder' && b.item.type !== 'folder') return -1;+ if (a.item.type !== 'folder' && b.item.type === 'folder') return 1;+ return b.score - a.score;+ })+ .map(s => s.item);+}diff --git a/editor/src/panels/content-browser/ContentBrowserPanel.ts b/editor/src/panels/content-browser/ContentBrowserPanel.tsnew file mode 100644index 000000000..fd1fb4279--- /dev/null+++ b/editor/src/panels/content-browser/ContentBrowserPanel.ts@@ -0,0 +1,654 @@+import type { EditorStore, AssetType } from '../../store/EditorStore';+import { icons } from '../../utils/icons';+import { getParentDir, joinPath } from '../../utils/path';+import { getGlobalPathResolver } from '../../asset';+import type { ContentBrowserState, ContentBrowserOptions, FolderNode, AssetItem, ViewMode } from './ContentBrowserTypes';+import { getNativeFS, getNativeShell, VIEW_MODE_KEY, SEARCH_RESULTS_LIMIT } from './ContentBrowserTypes';+import { ThumbnailCache } from './ThumbnailCache';+import { loadFolderChildren, toggleFolder, expandFolder, selectFolder, findFolder, collectExpandedPaths, renderFolderNode } from './FolderTree';+import { renderGrid } from './AssetGrid';+import {+ showAssetContextMenu, showMultiSelectContextMenu, showFolderContextMenu,+ deleteSelectedAssets, renameAsset,+ importDroppedFiles, saveDroppedEntityAsPrefab,+} from './AssetContextMenu';++export class ContentBrowserPanel implements ContentBrowserState {+ container: HTMLElement;+ store: EditorStore;+ treeContainer: HTMLElement | null = null;+ gridContainer: HTMLElement | null = null;+ footerContainer: HTMLElement | null = null;+ searchInput: HTMLInputElement | null = null;+ breadcrumbContainer: HTMLElement | null = null;++ projectPath: string | null = null;+ rootFolder: FolderNode | null = null;+ currentPath: string = '';+ searchFilter: string = '';+ currentItems: AssetItem[] = [];+ filteredItems: AssetItem[] = [];+ onOpenScene: ((scenePath: string) => void) | null = null;+ selectedPaths = new Set<string>();+ lastSelectedPath: string | null = null;+ viewMode: ViewMode;++ private unwatchFn_: (() => void) | null = null;+ private refreshing_ = false;+ private refreshPending_ = false;+ private thumbnailCache_ = new ThumbnailCache();++ constructor(container: HTMLElement, store: EditorStore, options?: ContentBrowserOptions) {+ this.container = container;+ this.store = store;+ this.projectPath = options?.projectPath ?? null;+ this.onOpenScene = options?.onOpenScene ?? null;+ this.viewMode = (localStorage.getItem(VIEW_MODE_KEY) as ViewMode) || 'grid';++ if (this.projectPath) {+ this.currentPath = getParentDir(this.projectPath);+ }++ this.container.classList.add('es-content-browser');+ this.container.innerHTML = `+ <div class="es-content-browser-header">+ <span class="es-content-browser-title">${icons.folder(14)} Content Browser</span>+ <div class="es-content-browser-actions">+ <button class="es-btn es-btn-icon es-refresh-btn" title="Refresh">${icons.refresh(12)}</button>+ </div>+ </div>+ <div class="es-content-browser-body">+ <div class="es-content-browser-tree"></div>+ <div class="es-content-browser-main">+ <div class="es-content-browser-toolbar">+ <button class="es-btn es-btn-icon es-cb-up-btn" title="Parent folder">${icons.arrowUp(14)}</button>+ <div class="es-content-breadcrumb"></div>+ <input type="text" class="es-input es-content-search" placeholder="Search assets...">+ <button class="es-btn es-btn-icon es-cb-view-toggle" title="Toggle view"></button>+ </div>+ <div class="es-content-browser-grid" tabindex="0" role="grid"></div>+ </div>+ </div>+ <div class="es-content-browser-footer">0 items</div>+ `;++ this.treeContainer = this.container.querySelector('.es-content-browser-tree');+ this.gridContainer = this.container.querySelector('.es-content-browser-grid');+ this.footerContainer = this.container.querySelector('.es-content-browser-footer');+ this.searchInput = this.container.querySelector('.es-content-search');+ this.breadcrumbContainer = this.container.querySelector('.es-content-breadcrumb');++ this.updateViewToggleButton();+ this.setupEvents();+ this.initialize();+ }++ dispose(): void {+ if (this.unwatchFn_) {+ this.unwatchFn_();+ this.unwatchFn_ = null;+ }+ }++ async navigateToAsset(assetPath: string): Promise<void> {+ if (!this.rootFolder) return;++ const normalized = assetPath.replace(/\\/g, '/');+ const lastSlash = normalized.lastIndexOf('/');+ const folderPath = lastSlash > 0 ? normalized.substring(0, lastSlash) : this.rootFolder.path;++ const projectDir = this.rootFolder.path;+ const targetFolderPath = joinPath(projectDir, folderPath);++ const pathParts = folderPath.split('/').filter(p => p);+ let currentNode = this.rootFolder;++ for (const part of pathParts) {+ const childPath = joinPath(currentNode.path, part);+ let child = currentNode.children.find(c => c.path === childPath);++ if (!child) {+ if (!currentNode.loaded) {+ await loadFolderChildren(currentNode);+ child = currentNode.children.find(c => c.path === childPath);+ }+ }++ if (child) {+ child.expanded = true;+ if (!child.loaded) {+ await loadFolderChildren(child);+ }+ currentNode = child;+ } else {+ break;+ }+ }++ this.currentPath = targetFolderPath;+ const fullAssetPath = joinPath(projectDir, normalized);+ this.selectedPaths.clear();+ this.selectedPaths.add(fullAssetPath);+ this.lastSelectedPath = fullAssetPath;++ this.renderTree();+ await this.renderGrid();++ requestAnimationFrame(() => {+ const selectedItem = this.gridContainer?.querySelector('.es-selected');+ selectedItem?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });+ });+ }++ render(): void {+ this.renderTree();+ this.renderBreadcrumb();+ this.renderGrid();+ }++ renderTree(): void {+ if (!this.treeContainer || !this.rootFolder) return;+ this.treeContainer.innerHTML = renderFolderNode(this.rootFolder, 0, this.currentPath);+ }++ renderBreadcrumb(): void {+ if (!this.breadcrumbContainer || !this.rootFolder) return;++ const rootPath = this.rootFolder.path;+ const crumbs: { name: string; path: string }[] = [];+ crumbs.push({ name: this.rootFolder.name, path: rootPath });++ if (this.currentPath && this.currentPath !== rootPath && this.currentPath.startsWith(rootPath)) {+ const relativePath = this.currentPath.substring(rootPath.length).replace(/^\//, '');+ const parts = relativePath.split('/').filter(p => p);++ let accumulatedPath = rootPath;+ for (const part of parts) {+ accumulatedPath = joinPath(accumulatedPath, part);+ crumbs.push({ name: part, path: accumulatedPath });+ }+ }++ this.breadcrumbContainer.innerHTML = crumbs+ .map((crumb, index) => {+ const isLast = index === crumbs.length - 1;+ const separator = isLast ? '' : `<span class="es-breadcrumb-separator">${icons.chevronRight(10)}</span>`;+ return `<span class="es-breadcrumb-item${isLast ? ' es-active' : ''}" data-path="${crumb.path}">${crumb.name}</span>${separator}`;+ })+ .join('');+ }++ async renderGrid(): Promise<void> {+ await renderGrid(this, this.thumbnailCache_);+ }++ async refresh(): Promise<void> {+ if (this.refreshing_) {+ this.refreshPending_ = true;+ return;+ }+ this.refreshing_ = true;+ try {+ if (this.rootFolder && this.projectPath) {+ this.rootFolder.loaded = false;+ await loadFolderChildren(this.rootFolder);++ const expandedPaths = collectExpandedPaths(this.rootFolder);+ for (const path of expandedPaths) {+ const folder = findFolder(this.rootFolder, path);+ if (folder && !folder.loaded) {+ await loadFolderChildren(folder);+ }+ }++ this.render();+ }+ } finally {+ this.refreshing_ = false;+ if (this.refreshPending_) {+ this.refreshPending_ = false;+ this.refresh();+ }+ }+ }++ private async initialize(): Promise<void> {+ if (this.projectPath) {+ await this.loadProjectDirectory();+ await this.setupFileWatcher();+ } else {+ this.rootFolder = this.createEmptyFolderStructure();+ this.render();+ }+ }++ private async loadProjectDirectory(): Promise<void> {+ const projectDir = getParentDir(this.projectPath!);+ this.currentPath = projectDir;++ this.rootFolder = {+ name: this.getProjectName(),+ path: projectDir,+ children: [],+ expanded: true,+ loaded: false,+ };++ await loadFolderChildren(this.rootFolder);+ this.render();+ }++ private getProjectName(): string {+ if (!this.projectPath) return 'Project';+ const normalized = this.projectPath.replace(/\\/g, '/');+ const parts = normalized.split('/');+ return parts[parts.length - 2] || 'Project';+ }++ private async setupFileWatcher(): Promise<void> {+ const fs = getNativeFS();+ if (!fs || !this.projectPath) return;++ const projectDir = getParentDir(this.projectPath);++ try {+ this.unwatchFn_ = await fs.watchDirectory(+ projectDir,+ () => { this.refresh(); },+ { recursive: true }+ );+ } catch (err) {+ console.error('Failed to setup file watcher:', err);+ }+ }++ private createEmptyFolderStructure(): FolderNode {+ return {+ name: 'Project',+ path: '',+ expanded: true,+ loaded: true,+ children: [+ { name: 'assets', path: 'assets', expanded: false, loaded: true, children: [] },+ { name: 'src', path: 'src', expanded: false, loaded: true, children: [] },+ ],+ };+ }++ private updateViewToggleButton(): void {+ const btn = this.container.querySelector('.es-cb-view-toggle');+ if (!btn) return;+ btn.innerHTML = this.viewMode === 'grid' ? icons.layoutList(14) : icons.layoutGrid(14);+ btn.setAttribute('title', this.viewMode === 'grid' ? 'Switch to list view' : 'Switch to grid view');+ }++ private setupEvents(): void {+ this.searchInput?.addEventListener('input', () => {+ this.searchFilter = this.searchInput?.value.toLowerCase() ?? '';+ this.renderGrid();+ });++ this.breadcrumbContainer?.addEventListener('click', (e) => {+ const target = e.target as HTMLElement;+ const item = target.closest('.es-breadcrumb-item') as HTMLElement;+ if (!item) return;+ const path = item.dataset.path;+ if (path) {+ selectFolder(this, path);+ }+ });++ const upBtn = this.container.querySelector('.es-cb-up-btn');+ upBtn?.addEventListener('click', () => {+ this.navigateToParent();+ });++ const viewToggle = this.container.querySelector('.es-cb-view-toggle');+ viewToggle?.addEventListener('click', () => {+ this.viewMode = this.viewMode === 'grid' ? 'list' : 'grid';+ localStorage.setItem(VIEW_MODE_KEY, this.viewMode);+ this.updateViewToggleButton();+ this.renderGrid();+ });++ this.treeContainer?.addEventListener('click', async (e) => {+ const target = e.target as HTMLElement;+ const item = target.closest('.es-folder-item') as HTMLElement;+ if (!item) return;+ const path = item.dataset.path;+ if (!path) return;++ if (target.closest('.es-folder-expand')) {+ await toggleFolder(this, path);+ } else {+ selectFolder(this, path);+ }+ });++ this.gridContainer?.addEventListener('click', (e) => {+ const target = e.target as HTMLElement;+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;++ if (!item) {+ this.selectedPaths.clear();+ this.lastSelectedPath = null;+ this.updateAssetSelection();+ return;+ }++ const path = item.dataset.path;+ if (!path) return;++ if (e.shiftKey && this.lastSelectedPath) {+ this.rangeSelect(this.lastSelectedPath, path);+ } else if (e.ctrlKey || e.metaKey) {+ if (this.selectedPaths.has(path)) {+ this.selectedPaths.delete(path);+ } else {+ this.selectedPaths.add(path);+ }+ this.lastSelectedPath = path;+ } else {+ this.selectedPaths.clear();+ this.selectedPaths.add(path);+ this.lastSelectedPath = path;+ }++ this.updateAssetSelection();+ this.notifyStoreSelection();+ });++ this.gridContainer?.addEventListener('dblclick', async (e) => {+ const target = e.target as HTMLElement;+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;+ if (!item) return;++ const path = item.dataset.path;+ const type = item.dataset.type;++ if (type === 'folder' && path) {+ selectFolder(this, path);+ await expandFolder(this, path);+ } else if (path) {+ this.onAssetDoubleClick(path, type as AssetItem['type']);+ }+ });++ const refreshBtn = this.container.querySelector('.es-refresh-btn');+ refreshBtn?.addEventListener('click', () => {+ this.refresh();+ });++ this.gridContainer?.addEventListener('contextmenu', (e) => {+ e.preventDefault();+ const target = e.target as HTMLElement;+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;++ if (item) {+ const path = item.dataset.path;+ const type = item.dataset.type;+ if (path) {+ if (!this.selectedPaths.has(path)) {+ this.selectedPaths.clear();+ this.selectedPaths.add(path);+ this.lastSelectedPath = path;+ this.updateAssetSelection();+ }++ if (this.selectedPaths.size > 1) {+ showMultiSelectContextMenu(this, e);+ } else {+ showAssetContextMenu(this, e, path, type as AssetItem['type']);+ }+ }+ } else {+ showFolderContextMenu(this, e, this.currentPath);+ }+ });++ this.treeContainer?.addEventListener('contextmenu', (e) => {+ e.preventDefault();+ const target = e.target as HTMLElement;+ const item = target.closest('.es-folder-item') as HTMLElement;+ const path = item?.dataset.path ?? this.currentPath;+ if (path) {+ showFolderContextMenu(this, e, path);+ }+ });++ this.gridContainer?.addEventListener('dragstart', (e) => {+ const target = e.target as HTMLElement;+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;+ if (!item) return;++ const path = item.dataset.path;+ const type = item.dataset.type;+ if (!path || !type) return;++ if (!this.selectedPaths.has(path)) {+ this.selectedPaths.clear();+ this.selectedPaths.add(path);+ this.lastSelectedPath = path;+ this.updateAssetSelection();+ }++ const dragItems = this.filteredItems.filter(i => this.selectedPaths.has(i.path));+ const payload = dragItems.map(i => ({ type: i.type, path: i.path, name: i.name }));++ e.dataTransfer?.setData('application/esengine-asset', JSON.stringify(+ payload.length === 1 ? payload[0] : payload+ ));+ e.dataTransfer!.effectAllowed = 'copy';++ item.classList.add('es-dragging');+ });++ this.gridContainer?.addEventListener('dragend', (e) => {+ const target = e.target as HTMLElement;+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;+ item?.classList.remove('es-dragging');+ });++ this.gridContainer?.addEventListener('dragover', (e) => {+ const types = e.dataTransfer?.types ?? [];+ const typesArr = Array.from(types);+ if (!typesArr.includes('application/esengine-entity') && !typesArr.includes('Files')) return;+ e.preventDefault();+ e.dataTransfer!.dropEffect = 'copy';+ this.gridContainer?.classList.add('es-drag-over');+ });++ this.gridContainer?.addEventListener('dragleave', (e) => {+ const related = e.relatedTarget as HTMLElement;+ if (this.gridContainer?.contains(related)) return;+ this.gridContainer?.classList.remove('es-drag-over');+ });++ this.gridContainer?.addEventListener('drop', (e) => {+ this.gridContainer?.classList.remove('es-drag-over');++ if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {+ e.preventDefault();+ importDroppedFiles(this, e.dataTransfer.files);+ return;+ }++ const entityIdStr = e.dataTransfer?.getData('application/esengine-entity');+ if (!entityIdStr) return;++ e.preventDefault();+ const entityId = parseInt(entityIdStr, 10);+ if (isNaN(entityId)) return;++ saveDroppedEntityAsPrefab(this, entityId);+ });++ this.gridContainer?.addEventListener('keydown', (e) => {+ this.handleKeyboardNavigation(e);+ });+ }++ private navigateToParent(): void {+ if (!this.rootFolder) return;+ if (this.currentPath === this.rootFolder.path) return;++ const parentPath = getParentDir(this.currentPath);+ if (parentPath) {+ selectFolder(this, parentPath);+ }+ }++ private rangeSelect(fromPath: string, toPath: string): void {+ const fromIndex = this.filteredItems.findIndex(i => i.path === fromPath);+ const toIndex = this.filteredItems.findIndex(i => i.path === toPath);+ if (fromIndex < 0 || toIndex < 0) return;++ const start = Math.min(fromIndex, toIndex);+ const end = Math.max(fromIndex, toIndex);++ this.selectedPaths.clear();+ for (let i = start; i <= end; i++) {+ this.selectedPaths.add(this.filteredItems[i].path);+ }+ }++ private notifyStoreSelection(): void {+ if (this.selectedPaths.size === 1) {+ const path = this.selectedPaths.values().next().value!;+ const item = this.filteredItems.find(i => i.path === path);+ if (item) {+ this.store.selectAsset({+ path: item.path,+ type: item.type as AssetType,+ name: item.name,+ });+ }+ }+ }++ private handleKeyboardNavigation(e: KeyboardEvent): void {+ if (!this.gridContainer || this.filteredItems.length === 0) return;++ const isGrid = this.viewMode === 'grid';++ switch (e.key) {+ case 'ArrowRight':+ case 'ArrowLeft':+ case 'ArrowDown':+ case 'ArrowUp': {+ e.preventDefault();+ const currentIndex = this.lastSelectedPath+ ? this.filteredItems.findIndex(i => i.path === this.lastSelectedPath)+ : -1;++ let cols = 1;+ if (isGrid) {+ const containerWidth = this.gridContainer.clientWidth - 24;+ cols = Math.max(1, Math.floor(containerWidth / 80));+ }++ let nextIndex = currentIndex;+ if (e.key === 'ArrowRight') nextIndex = currentIndex + 1;+ else if (e.key === 'ArrowLeft') nextIndex = currentIndex - 1;+ else if (e.key === 'ArrowDown') nextIndex = currentIndex + cols;+ else if (e.key === 'ArrowUp') nextIndex = currentIndex - cols;++ if (nextIndex >= 0 && nextIndex < this.filteredItems.length) {+ this.selectedPaths.clear();+ this.selectedPaths.add(this.filteredItems[nextIndex].path);+ this.lastSelectedPath = this.filteredItems[nextIndex].path;+ this.updateAssetSelection();+ this.notifyStoreSelection();++ const el = this.gridContainer.children[nextIndex] as HTMLElement;+ el?.scrollIntoView({ block: 'nearest' });+ }+ break;+ }+ case 'Enter': {+ e.preventDefault();+ if (this.selectedPaths.size !== 1) return;+ const path = this.selectedPaths.values().next().value!;+ const item = this.filteredItems.find(i => i.path === path);+ if (!item) return;++ if (item.type === 'folder') {+ selectFolder(this, item.path);+ expandFolder(this, item.path);+ } else {+ this.onAssetDoubleClick(item.path, item.type);+ }+ break;+ }+ case 'Delete':+ case 'Backspace': {+ e.preventDefault();+ if (this.selectedPaths.size === 0) return;+ deleteSelectedAssets(this);+ break;+ }+ case 'F2': {+ e.preventDefault();+ if (this.selectedPaths.size !== 1) return;+ const path = this.selectedPaths.values().next().value!;+ const item = this.filteredItems.find(i => i.path === path);+ if (item) {+ renameAsset(this, item.path, item.type);+ }+ break;+ }+ case 'a': {+ if (e.ctrlKey || e.metaKey) {+ e.preventDefault();+ this.selectedPaths.clear();+ for (const item of this.filteredItems) {+ this.selectedPaths.add(item.path);+ }+ this.updateAssetSelection();+ }+ break;+ }+ }+ }++ private updateAssetSelection(): void {+ if (!this.gridContainer) return;++ const selector = this.viewMode === 'list' ? '.es-cb-list-row' : '.es-asset-item';+ const items = this.gridContainer.querySelectorAll(selector);+ items.forEach((item) => {+ const el = item as HTMLElement;+ if (this.selectedPaths.has(el.dataset.path ?? '')) {+ el.classList.add('es-selected');+ } else {+ el.classList.remove('es-selected');+ }+ });+ }++ private onAssetDoubleClick(path: string, type: AssetItem['type']): void {+ if (type === 'scene' && this.onOpenScene) {+ this.onOpenScene(path);+ return;+ }++ if (type === 'prefab') {+ const resolver = getGlobalPathResolver();+ const relativePath = resolver.toRelativePath(path);+ this.store.enterPrefabEditMode(relativePath);+ return;+ }++ const shell = getNativeShell();+ if (!shell) return;++ if (type === 'script') {+ const projectDir = this.rootFolder?.path;+ if (projectDir) {+ shell.openInEditor(projectDir, path);+ }+ } else if (type === 'shader' || type === 'json') {+ shell.openFile(path);+ }+ }+}diff --git a/editor/src/panels/content-browser/ContentBrowserTypes.ts b/editor/src/panels/content-browser/ContentBrowserTypes.tsnew file mode 100644index 000000000..123e203f2--- /dev/null+++ b/editor/src/panels/content-browser/ContentBrowserTypes.ts@@ -0,0 +1,120 @@+import type { EditorStore, AssetType } from '../../store/EditorStore';+import type { NativeFS, DirectoryEntry } from '../../types/NativeFS';+import { icons } from '../../utils/icons';+import { getEditorContext } from '../../context/EditorContext';+import { getEditorType } from 'esengine';++export interface NativeShell {+ openFile(path: string): Promise<void>;+ openInEditor(projectPath: string, filePath: string): Promise<void>;+}++export interface FolderNode {+ name: string;+ path: string;+ children: FolderNode[];+ expanded: boolean;+ loaded: boolean;+}++export interface AssetItem {+ name: string;+ path: string;+ type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'material' | 'shader' | 'spine' | 'font' | 'prefab' | 'file';+ relativePath?: string;+}++export type ViewMode = 'grid' | 'list';++export interface ContentBrowserOptions {+ projectPath?: string;+ onOpenScene?: (scenePath: string) => void;+}++export const THUMBNAIL_CACHE_MAX = 200;+export const THUMBNAIL_SIZE = 48;+export const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp']);+export const SEARCH_RESULTS_LIMIT = 100;+export const VIEW_MODE_KEY = 'esengine.editor.contentBrowserView';++export interface ContentBrowserState {+ store: EditorStore;+ container: HTMLElement;+ treeContainer: HTMLElement | null;+ gridContainer: HTMLElement | null;+ footerContainer: HTMLElement | null;+ searchInput: HTMLInputElement | null;+ breadcrumbContainer: HTMLElement | null;+ projectPath: string | null;+ rootFolder: FolderNode | null;+ currentPath: string;+ searchFilter: string;+ currentItems: AssetItem[];+ filteredItems: AssetItem[];+ onOpenScene: ((scenePath: string) => void) | null;+ selectedPaths: Set<string>;+ lastSelectedPath: string | null;+ viewMode: ViewMode;+ render(): void;+ renderTree(): void;+ renderBreadcrumb(): void;+ renderGrid(): Promise<void>;+ refresh(): Promise<void>;+}++export function getNativeFS(): NativeFS | null {+ return getEditorContext().fs ?? null;+}++export function getNativeShell(): NativeShell | null {+ return getEditorContext().shell ?? null;+}++export function getFileExtension(filename: string): string {+ const dotIndex = filename.lastIndexOf('.');+ return dotIndex > 0 ? filename.substring(dotIndex).toLowerCase() : '';+}++const EDITOR_TYPE_TO_DISPLAY: Record<string, AssetItem['type']> = {+ 'texture': 'image',+ 'material': 'material',+ 'shader': 'shader',+ 'spine-atlas': 'spine',+ 'spine-skeleton': 'spine',+ 'bitmap-font': 'font',+ 'prefab': 'prefab',+ 'json': 'json',+ 'audio': 'audio',+ 'scene': 'scene',+};++export function getAssetType(entry: DirectoryEntry): AssetItem['type'] {+ if (entry.isDirectory) return 'folder';++ const ext = getFileExtension(entry.name);+ if (ext === '.ts' || ext === '.js') return 'script';++ const editorType = getEditorType(entry.name);+ return EDITOR_TYPE_TO_DISPLAY[editorType] ?? 'file';+}++export function getAssetIcon(type: AssetItem['type'], size: number = 32): string {+ switch (type) {+ case 'folder': return icons.folder(size);+ case 'prefab': return icons.package(size);+ case 'scene': return icons.layers(size);+ case 'script': return icons.code(size);+ case 'image': return icons.image(size);+ case 'audio': return icons.volume(size);+ case 'json': return icons.braces(size);+ case 'material': return icons.settings(size);+ case 'shader': return icons.code(size);+ case 'spine': return icons.bone(size);+ case 'font': return icons.type(size);+ default: return icons.file(size);+ }+}++export function isImageFile(name: string): boolean {+ return IMAGE_EXTENSIONS.has(getFileExtension(name));+}diff --git a/editor/src/panels/content-browser/FolderTree.ts b/editor/src/panels/content-browser/FolderTree.tsnew file mode 100644index 000000000..676b67a4c--- /dev/null+++ b/editor/src/panels/content-browser/FolderTree.ts@@ -0,0 +1,108 @@+import { icons } from '../../utils/icons';+import { joinPath } from '../../utils/path';+import type { FolderNode, ContentBrowserState } from './ContentBrowserTypes';+import { getNativeFS } from './ContentBrowserTypes';++export async function loadFolderChildren(folder: FolderNode): Promise<void> {+ const fs = getNativeFS();+ if (!fs) return;++ try {+ const entries = await fs.listDirectoryDetailed(folder.path);++ folder.children = entries+ .filter(e => e.isDirectory && !e.name.startsWith('.'))+ .sort((a, b) => a.name.localeCompare(b.name))+ .map(e => ({+ name: e.name,+ path: joinPath(folder.path, e.name),+ children: [],+ expanded: false,+ loaded: false,+ }));++ folder.loaded = true;+ } catch (err) {+ console.error('Failed to load folder:', folder.path, err);+ }+}++export async function toggleFolder(state: ContentBrowserState, path: string): Promise<void> {+ const folder = findFolder(state.rootFolder, path);+ if (folder) {+ folder.expanded = !folder.expanded;++ if (folder.expanded && !folder.loaded) {+ await loadFolderChildren(folder);+ }++ state.renderTree();+ }+}++export async function expandFolder(state: ContentBrowserState, path: string): Promise<void> {+ const folder = findFolder(state.rootFolder, path);+ if (folder) {+ folder.expanded = true;++ if (!folder.loaded) {+ await loadFolderChildren(folder);+ }++ state.renderTree();+ }+}++export function selectFolder(state: ContentBrowserState, path: string): void {+ state.currentPath = path;+ state.selectedPaths.clear();+ state.lastSelectedPath = null;+ state.renderTree();+ state.renderBreadcrumb();+ state.renderGrid();+}++export function findFolder(node: FolderNode | null, path: string): FolderNode | null {+ if (!node) return null;+ if (node.path === path) return node;+ for (const child of node.children) {+ const found = findFolder(child, path);+ if (found) return found;+ }+ return null;+}++export function collectExpandedPaths(node: FolderNode): string[] {+ const paths: string[] = [];+ if (node.expanded) {+ paths.push(node.path);+ for (const child of node.children) {+ paths.push(...collectExpandedPaths(child));+ }+ }+ return paths;+}++export function renderFolderNode(node: FolderNode, depth: number, currentPath: string): string {+ const isSelected = node.path === currentPath;+ const hasChildren = node.children.length > 0 || !node.loaded;+ const indent = depth * 16;++ let html = `+ <div class="es-folder-item ${isSelected ? 'es-selected' : ''}"+ data-path="${node.path}"+ style="padding-left: ${indent}px">+ ${hasChildren ? `<span class="es-folder-expand">${node.expanded ? icons.chevronDown(10) : icons.chevronRight(10)}</span>` : '<span class="es-folder-spacer"></span>'}+ <span class="es-folder-icon">${node.expanded ? icons.folderOpen(14) : icons.folder(14)}</span>+ <span class="es-folder-name">${node.name}</span>+ </div>+ `;++ if (node.expanded) {+ for (const child of node.children) {+ html += renderFolderNode(child, depth + 1, currentPath);+ }+ }++ return html;+}diff --git a/editor/src/panels/content-browser/ThumbnailCache.ts b/editor/src/panels/content-browser/ThumbnailCache.tsnew file mode 100644index 000000000..f9d43573e--- /dev/null+++ b/editor/src/panels/content-browser/ThumbnailCache.ts@@ -0,0 +1,66 @@+import { getNativeFS, THUMBNAIL_CACHE_MAX, THUMBNAIL_SIZE } from './ContentBrowserTypes';++export class ThumbnailCache {+ private cache_ = new Map<string, string>();+ private loading_ = new Set<string>();++ get(path: string): string | undefined {+ return this.cache_.get(path);+ }++ isLoading(path: string): boolean {+ return this.loading_.has(path);+ }++ async load(path: string, onLoaded: () => void): Promise<void> {+ if (this.cache_.has(path) || this.loading_.has(path)) return;++ this.loading_.add(path);++ try {+ const fs = getNativeFS();+ if (!fs) return;++ const data = await fs.readBinaryFile(path);+ if (!data) return;++ const blob = new Blob([data.buffer as ArrayBuffer]);+ const url = URL.createObjectURL(blob);++ const img = new Image();+ await new Promise<void>((resolve, reject) => {+ img.onload = () => resolve();+ img.onerror = () => reject();+ img.src = url;+ });++ const canvas = document.createElement('canvas');+ canvas.width = THUMBNAIL_SIZE;+ canvas.height = THUMBNAIL_SIZE;+ const ctx = canvas.getContext('2d')!;++ const scale = Math.min(THUMBNAIL_SIZE / img.width, THUMBNAIL_SIZE / img.height);+ const w = img.width * scale;+ const h = img.height * scale;+ const x = (THUMBNAIL_SIZE - w) / 2;+ const y = (THUMBNAIL_SIZE - h) / 2;++ ctx.drawImage(img, x, y, w, h);++ const dataUrl = canvas.toDataURL('image/png');+ URL.revokeObjectURL(url);++ if (this.cache_.size >= THUMBNAIL_CACHE_MAX) {+ const firstKey = this.cache_.keys().next().value;+ if (firstKey) this.cache_.delete(firstKey);+ }++ this.cache_.set(path, dataUrl);+ onLoaded();+ } catch {+ // ignore load failures+ } finally {+ this.loading_.delete(path);+ }+ }+}diff --git a/editor/src/panels/content-browser/index.ts b/editor/src/panels/content-browser/index.tsnew file mode 100644index 000000000..387f3067c--- /dev/null+++ b/editor/src/panels/content-browser/index.ts@@ -0,0 +1,2 @@+export { ContentBrowserPanel } from './ContentBrowserPanel';+export type { ContentBrowserOptions } from './ContentBrowserTypes';diff --git a/editor/src/panels/hierarchy/HierarchyContextMenu.ts b/editor/src/panels/hierarchy/HierarchyContextMenu.tsnew file mode 100644index 000000000..093c51992--- /dev/null+++ b/editor/src/panels/hierarchy/HierarchyContextMenu.ts@@ -0,0 +1,399 @@+import type { Entity } from 'esengine';+import type { EntityData } from '../../types/SceneTypes';+import { icons } from '../../utils/icons';+import { getInitialComponentData } from '../../schemas/ComponentSchemas';+import { showContextMenu, type ContextMenuItem } from '../../ui/ContextMenu';+import { getContextMenuItems, type ContextMenuContext } from '../../ui/ContextMenuRegistry';+import { getEditorContext, getEditorInstance } from '../../context/EditorContext';+import { getAssetDatabase, isUUID } from '../../asset/AssetDatabase';+import { getGlobalPathResolver } from '../../asset';+import { getPlatformAdapter } from '../../platform/PlatformAdapter';+import { generateUniqueName } from '../../utils/naming';+import { showInputDialog } from '../../ui/dialog';+import { joinPath, getParentDir } from '../../utils/path';+import { hasAnyOverrides } from '../../prefab';+import type { HierarchyState } from './HierarchyTypes';++export function showEntityContextMenu(state: HierarchyState, x: number, y: number, entity: Entity | null): void {+ const entityData = entity !== null ? state.store.getEntityData(entity as number) : null;+ const has = (type: string) => entityData?.components.some(c => c.type === type) ?? false;+ const editor = getEditorInstance();+ const multiSelected = state.store.selectedEntities.size > 1;++ const createChildren: ContextMenuItem[] = [+ { label: 'Empty Entity', icon: icons.plus(14), onClick: () => {+ const newEntity = state.store.createEntity(undefined, entity);+ state.store.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ } },+ { label: 'Sprite', icon: icons.image(14), onClick: () => createEntityWithComponent(state, 'Sprite', entity) },+ { label: 'Text', icon: icons.type(14), onClick: () => createEntityWithComponent(state, 'Text', entity) },+ { label: 'BitmapText', icon: icons.type(14), onClick: () => createEntityWithComponent(state, 'BitmapText', entity) },+ { label: 'Spine', icon: icons.bone(14), onClick: () => createEntityWithComponent(state, 'SpineAnimation', entity) },+ { label: 'Camera', icon: icons.camera(14), onClick: () => createEntityWithComponent(state, 'Camera', entity) },+ { label: 'Canvas', icon: icons.template(14), onClick: () => createEntityWithComponent(state, 'Canvas', entity) },+ { label: '', separator: true },+ { label: 'UI', icon: icons.pointer(14), children: [+ { label: 'Button', onClick: () => createButtonEntity(state, entity) },+ { label: 'TextInput', onClick: () => createTextInputEntity(state, entity) },+ { label: 'Panel', onClick: () => createPanelEntity(state, entity) },+ { label: 'ScreenSpace Root', onClick: () => createScreenSpaceRootEntity(state, entity) },+ ] },+ { label: 'Physics', icon: icons.circle(14), children: [+ { label: 'Box Collider', onClick: () => createPhysicsEntity(state, 'BoxCollider', entity) },+ { label: 'Circle Collider', onClick: () => createPhysicsEntity(state, 'CircleCollider', entity) },+ { label: 'Capsule Collider', onClick: () => createPhysicsEntity(state, 'CapsuleCollider', entity) },+ ] },+ ];++ const items: ContextMenuItem[] = [];++ if (entity !== null) {+ items.push(+ { label: 'Rename', icon: icons.pencil(14), onClick: () => {+ state.renamingEntityId = entity as number;+ state.renderVisibleRows();+ } },+ { label: 'Duplicate', icon: icons.copy(14), onClick: () => {+ if (multiSelected) {+ for (const id of state.store.selectedEntities) {+ duplicateEntity(state, id as Entity);+ }+ } else {+ duplicateEntity(state, entity);+ }+ } },+ { label: 'Copy', icon: icons.copy(14), onClick: () => { state.store.selectEntity(entity); editor?.copySelected(); } },+ { label: 'Cut', icon: icons.copy(14), onClick: () => {+ state.store.selectEntity(entity);+ editor?.copySelected();+ if (multiSelected) {+ state.store.deleteSelectedEntities();+ } else {+ state.store.deleteEntity(entity);+ }+ } },+ { label: 'Paste', icon: icons.template(14), disabled: !editor?.hasClipboard(), onClick: () => { state.store.selectEntity(entity); editor?.pasteEntity(); } },+ { label: 'Delete', icon: icons.trash(14), onClick: () => {+ if (multiSelected) {+ state.store.deleteSelectedEntities();+ } else {+ state.store.deleteEntity(entity);+ }+ } },+ { label: '', separator: true },+ );+ }++ items.push({ label: 'Create', icon: icons.plus(14), children: createChildren });++ if (entity === null) {+ items.push({ label: 'Paste', icon: icons.template(14), disabled: !editor?.hasClipboard(), onClick: () => { editor?.pasteEntity(); } });+ }++ if (entity !== null) {+ items.push({+ label: 'Add Component', children: [+ { label: 'Interactable', disabled: has('Interactable'), onClick: () => state.store.addComponent(entity, 'Interactable', getInitialComponentData('Interactable')) },+ { label: 'Button', disabled: has('Button'), onClick: () => state.store.addComponent(entity, 'Button', getInitialComponentData('Button')) },+ { label: 'ScreenSpace', disabled: has('ScreenSpace'), onClick: () => state.store.addComponent(entity, 'ScreenSpace', getInitialComponentData('ScreenSpace')) },+ { label: '', separator: true },+ { label: 'RigidBody', disabled: has('RigidBody'), onClick: () => state.store.addComponent(entity, 'RigidBody', getInitialComponentData('RigidBody')) },+ { label: 'BoxCollider', disabled: has('BoxCollider'), onClick: () => state.store.addComponent(entity, 'BoxCollider', getInitialComponentData('BoxCollider')) },+ { label: 'CircleCollider', disabled: has('CircleCollider'), onClick: () => state.store.addComponent(entity, 'CircleCollider', getInitialComponentData('CircleCollider')) },+ { label: 'CapsuleCollider', disabled: has('CapsuleCollider'), onClick: () => state.store.addComponent(entity, 'CapsuleCollider', getInitialComponentData('CapsuleCollider')) },+ ],+ });++ items.push({ label: '', separator: true });++ const prefabChildren: ContextMenuItem[] = [+ { label: 'Save as Prefab...', icon: icons.package(14), onClick: () => saveEntityAsPrefab(state, entity) },+ ];+ if (state.store.isPrefabRoot(entity as number)) {+ const instanceId = state.store.getPrefabInstanceId(entity as number);+ const prefabPath = state.store.getPrefabPath(entity as number);+ if (instanceId && prefabPath) {+ const overridden = hasAnyOverrides(state.store.scene, instanceId);+ prefabChildren.push(+ { label: '', separator: true },+ { label: 'Revert Prefab', icon: icons.rotateCw(14), disabled: !overridden, onClick: () => state.store.revertPrefabInstance(instanceId, prefabPath) },+ { label: 'Apply to Prefab', icon: icons.check(14), disabled: !overridden, onClick: () => state.store.applyPrefabOverrides(instanceId, prefabPath) },+ { label: 'Unpack Prefab', icon: icons.package(14), onClick: () => state.store.unpackPrefab(instanceId) },+ );+ }+ }+ items.push({ label: 'Prefab', icon: icons.package(14), children: prefabChildren });+ }++ const location = entity !== null ? 'hierarchy.entity' : 'hierarchy.background';+ const ctx: ContextMenuContext = { location, entity: entity ?? undefined, entityData: entityData ?? undefined };+ const extensionItems = getContextMenuItems(location, ctx);+ if (extensionItems.length > 0) {+ items.push({ label: '', separator: true }, ...extensionItems);+ }++ showContextMenu({ x, y, items });+}++function createEntityWithComponent(state: HierarchyState, componentType: string, parent: Entity | null): void {+ const newEntity = state.store.createEntity(componentType, parent);++ state.store.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));++ if (componentType === 'Text') {+ state.store.addComponent(newEntity, 'UIRect', getInitialComponentData('UIRect'));+ }++ state.store.addComponent(newEntity, componentType, getInitialComponentData(componentType));+}++function createPhysicsEntity(state: HierarchyState, colliderType: string, parent: Entity | null): void {+ const newEntity = state.store.createEntity(colliderType, parent);+ state.store.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ state.store.addComponent(newEntity, 'RigidBody', getInitialComponentData('RigidBody'));+ state.store.addComponent(newEntity, colliderType, getInitialComponentData(colliderType));+}++function createButtonEntity(state: HierarchyState, parent: Entity | null): void {+ const newEntity = state.store.createEntity('Button', parent);+ state.store.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ state.store.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));+ state.store.addComponent(newEntity, 'UIRect', getInitialComponentData('UIRect'));+ state.store.addComponent(newEntity, 'Interactable', getInitialComponentData('Interactable'));+ state.store.addComponent(newEntity, 'Button', getInitialComponentData('Button'));+}++function createTextInputEntity(state: HierarchyState, parent: Entity | null): void {+ const newEntity = state.store.createEntity('TextInput', parent);+ state.store.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ const tiDefaults = getInitialComponentData('TextInput');+ state.store.addComponent(newEntity, 'Sprite', {+ ...getInitialComponentData('Sprite'),+ color: tiDefaults.backgroundColor,+ size: { x: 200, y: 36 },+ });+ state.store.addComponent(newEntity, 'UIRect', {+ ...getInitialComponentData('UIRect'),+ size: { x: 200, y: 36 },+ });+ state.store.addComponent(newEntity, 'Interactable', getInitialComponentData('Interactable'));+ state.store.addComponent(newEntity, 'TextInput', getInitialComponentData('TextInput'));+}++function createPanelEntity(state: HierarchyState, parent: Entity | null): void {+ const newEntity = state.store.createEntity('Panel', parent);+ state.store.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ state.store.addComponent(newEntity, 'Sprite', getInitialComponentData('Sprite'));+ state.store.addComponent(newEntity, 'UIRect', getInitialComponentData('UIRect'));+ state.store.addComponent(newEntity, 'UIMask', getInitialComponentData('UIMask'));+}++function createScreenSpaceRootEntity(state: HierarchyState, parent: Entity | null): void {+ const newEntity = state.store.createEntity('ScreenSpace Root', parent);+ state.store.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ state.store.addComponent(newEntity, 'UIRect', {+ ...getInitialComponentData('UIRect'),+ anchorMin: { x: 0, y: 0 },+ anchorMax: { x: 1, y: 1 },+ });+ state.store.addComponent(newEntity, 'ScreenSpace', {});+}++export function duplicateEntity(state: HierarchyState, entity: Entity): void {+ const entityData = state.store.getEntityData(entity as number);+ if (!entityData) return;++ const scene = state.store.scene;+ const siblings = scene.entities+ .filter(e => e.parent === entityData.parent)+ .map(e => e.name);+ const siblingNames = new Set(siblings);+ const newName = generateUniqueName(entityData.name, siblingNames);++ const newEntity = state.store.createEntity(+ newName,+ entityData.parent as Entity | null+ );++ for (const comp of entityData.components) {+ state.store.addComponent(newEntity, comp.type, JSON.parse(JSON.stringify(comp.data)));+ }++ duplicateChildren(state, entityData, newEntity);+}++function duplicateChildren(state: HierarchyState, sourceEntity: EntityData, newParent: Entity): void {+ for (const childId of sourceEntity.children) {+ const childData = state.store.getEntityData(childId);+ if (!childData) continue;++ const childEntity = state.store.createEntity(childData.name, newParent);++ for (const comp of childData.components) {+ state.store.addComponent(childEntity, comp.type, JSON.parse(JSON.stringify(comp.data)));+ }++ duplicateChildren(state, childData, childEntity);+ }+}++async function saveEntityAsPrefab(state: HierarchyState, entity: Entity): Promise<void> {+ const entityData = state.store.getEntityData(entity as number);+ if (!entityData) return;++ const projectPath = getEditorInstance()?.projectPath;+ if (!projectPath) return;++ const projectDir = getParentDir(projectPath);+ const assetsDir = joinPath(projectDir, 'assets');++ const name = await showInputDialog({+ title: 'Save as Prefab',+ placeholder: 'Prefab name',+ defaultValue: entityData.name,+ confirmText: 'Save',+ validator: async (value) => {+ if (!value.trim()) return 'Name is required';+ if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {+ return 'Name contains invalid characters';+ }+ return null;+ },+ });++ if (!name) return;++ const fileName = name.trim().endsWith('.esprefab')+ ? name.trim()+ : `${name.trim()}.esprefab`;+ const filePath = joinPath(assetsDir, fileName);++ const success = await state.store.saveAsPrefab(entity as number, filePath);+ if (!success) {+ console.error('[HierarchyPanel] Failed to save prefab:', filePath);+ }+}++export async function createEntityFromAsset(+ state: HierarchyState,+ asset: { type: string; path: string; name: string },+ parent: Entity | null,+): Promise<void> {+ if (asset.type === 'prefab') {+ await createEntityFromPrefab(state, asset.path, parent);+ return;+ }++ const baseName = asset.name.replace(/\.[^.]+$/, '');++ if (asset.type === 'spine' || asset.type === 'json') {+ const ext = asset.name.substring(asset.name.lastIndexOf('.')).toLowerCase();+ if (ext === '.atlas') return;++ const skeletonPath = toRelativePath(asset.path);+ const atlasPath = await findAtlasFile(skeletonPath);++ if (!atlasPath) {+ console.error(`[HierarchyPanel] No atlas file found for: ${skeletonPath}`);+ alert(`No atlas file found.\nPlease ensure there is an .atlas file in the same directory as the skeleton file.`);+ return;+ }++ const newEntity = state.store.createEntity(baseName, parent);++ state.store.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));++ state.store.addComponent(newEntity, 'SpineAnimation', {+ ...getInitialComponentData('SpineAnimation'),+ skeletonPath,+ atlasPath,+ });+ } else if (asset.type === 'image') {+ const newEntity = state.store.createEntity(baseName, parent);++ state.store.addComponent(newEntity, 'LocalTransform', getInitialComponentData('LocalTransform'));++ state.store.addComponent(newEntity, 'Sprite', {+ ...getInitialComponentData('Sprite'),+ texture: toRelativePath(asset.path),+ });++ loadImageSize(asset.path).then(size => {+ if (size) {+ state.store.updateProperty(newEntity, 'Sprite', 'size', { x: 32, y: 32 }, size);+ }+ });+ }+}++function toRelativePath(absolutePath: string): string {+ return getGlobalPathResolver().toRelativePath(absolutePath);+}++async function findAtlasFile(skeletonPath: string): Promise<string | null> {+ const pathResolver = getGlobalPathResolver();++ const sameNameAtlas = skeletonPath.replace(/\.(json|skel)$/i, '.atlas');+ const validation = await pathResolver.validatePath(sameNameAtlas);+ if (validation.exists) {+ return sameNameAtlas;+ }++ const dir = skeletonPath.substring(0, skeletonPath.lastIndexOf('/'));+ const absoluteDir = pathResolver.toAbsolutePath(dir);++ const fs = getEditorContext().fs;+ if (!fs) {+ return null;+ }++ try {+ const entries = await fs.listDirectoryDetailed(absoluteDir);+ const atlasFiles = entries+ .filter(e => e.name.endsWith('.atlas'))+ .map(e => e.name);++ if (atlasFiles.length === 1) {+ return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];+ }++ if (atlasFiles.length > 1) {+ const baseName = skeletonPath+ .substring(skeletonPath.lastIndexOf('/') + 1)+ .replace(/\.(json|skel)$/i, '');++ const matching = atlasFiles.find((name: string) =>+ name.replace('.atlas', '').toLowerCase().includes(baseName.toLowerCase().split('-')[0])+ );++ if (matching) {+ return dir ? `${dir}/${matching}` : matching;+ }++ return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];+ }+ } catch (err) {+ console.warn('[HierarchyPanel] Failed to scan directory for atlas files:', err);+ }++ return null;+}++function loadImageSize(absolutePath: string): Promise<{ x: number; y: number } | null> {+ return new Promise((resolve) => {+ const img = new Image();+ img.onload = () => resolve({ x: img.naturalWidth, y: img.naturalHeight });+ img.onerror = () => resolve(null);+ img.src = getPlatformAdapter().convertFilePathToUrl(absolutePath);+ });+}++async function createEntityFromPrefab(+ state: HierarchyState,+ prefabPath: string,+ parent: Entity | null,+): Promise<void> {+ const relativePath = toRelativePath(prefabPath);+ const uuid = getAssetDatabase().getUuid(relativePath) ?? relativePath;+ await state.store.instantiatePrefab(uuid, parent);+}diff --git a/editor/src/panels/hierarchy/HierarchyDragDrop.ts b/editor/src/panels/hierarchy/HierarchyDragDrop.tsnew file mode 100644index 000000000..48b56ff75--- /dev/null+++ b/editor/src/panels/hierarchy/HierarchyDragDrop.ts@@ -0,0 +1,177 @@+import type { Entity } from 'esengine';+import type { DropPosition, HierarchyState } from './HierarchyTypes';++export function setupDragAndDrop(+ state: HierarchyState,+ createEntityFromAsset: (asset: { type: string; path: string; name: string }, parent: Entity | null) => Promise<void>,+): void {+ state.treeContainer.addEventListener('dragstart', (e) => {+ const target = e.target as HTMLElement;+ const row = target.closest('.es-hierarchy-row') as HTMLElement;+ const item = row?.parentElement as HTMLElement;+ if (!item?.classList.contains('es-hierarchy-item')) return;++ const entityId = item.dataset.entityId;+ if (!entityId) return;++ e.dataTransfer!.setData('application/esengine-entity', entityId);+ e.dataTransfer!.effectAllowed = 'move';+ state.draggingEntityId = parseInt(entityId, 10);+ item.classList.add('es-dragging');++ const onDragEnd = () => {+ row.removeEventListener('dragend', onDragEnd);+ state.draggingEntityId = null;+ state.dragOverEntityId = null;+ state.dropPosition = null;+ state.treeContainer.classList.remove('es-drag-over');+ state.renderVisibleRows();+ };+ row.addEventListener('dragend', onDragEnd);+ });++ state.treeContainer.addEventListener('dragover', (e) => {+ const types = e.dataTransfer?.types ?? [];+ const hasAssetData = Array.from(types).includes('application/esengine-asset');+ const hasEntityData = Array.from(types).includes('application/esengine-entity');++ if (!hasAssetData && !hasEntityData) return;++ e.preventDefault();++ const target = e.target as HTMLElement;+ const item = target.closest('.es-hierarchy-item') as HTMLElement;+ const entityId = item ? parseInt(item.dataset.entityId ?? '', 10) : NaN;+ const newEntityId = isNaN(entityId) ? null : entityId;++ if (hasAssetData) {+ e.dataTransfer!.dropEffect = 'copy';+ if (newEntityId !== state.dragOverEntityId || state.dropPosition !== null) {+ state.dragOverEntityId = newEntityId;+ state.dropPosition = null;+ state.treeContainer.classList.toggle('es-drag-over', !item);+ state.renderVisibleRows();+ }+ return;+ }++ e.dataTransfer!.dropEffect = 'move';++ if (!item) {+ if (state.dragOverEntityId !== null) {+ state.dragOverEntityId = null;+ state.dropPosition = null;+ state.renderVisibleRows();+ }+ state.treeContainer.classList.add('es-drag-over');+ return;+ }++ state.treeContainer.classList.remove('es-drag-over');+ const position = getDropPosition(e, item);+ if (newEntityId !== state.dragOverEntityId || position !== state.dropPosition) {+ state.dragOverEntityId = newEntityId;+ state.dropPosition = position;+ state.renderVisibleRows();+ }+ });++ state.treeContainer.addEventListener('dragleave', (e) => {+ const relatedTarget = e.relatedTarget as HTMLElement;+ if (state.treeContainer.contains(relatedTarget)) return;+ state.dragOverEntityId = null;+ state.dropPosition = null;+ state.treeContainer.classList.remove('es-drag-over');+ state.renderVisibleRows();+ });++ state.treeContainer.addEventListener('drop', (e) => {+ e.preventDefault();++ const assetDataStr = e.dataTransfer?.getData('application/esengine-asset');+ const entityIdStr = e.dataTransfer?.getData('application/esengine-entity');+ const target = e.target as HTMLElement;+ const dropItem = target.closest('.es-hierarchy-item') as HTMLElement;+ const dropTargetId = dropItem ? parseInt(dropItem.dataset.entityId ?? '', 10) : NaN;+ const dropPos = dropItem ? getDropPosition(e, dropItem) : null;++ state.dragOverEntityId = null;+ state.dropPosition = null;+ state.draggingEntityId = null;+ state.treeContainer.classList.remove('es-drag-over');++ if (assetDataStr) {+ let assetData: { type: string; path: string; name: string };+ try {+ assetData = JSON.parse(assetDataStr);+ } catch {+ return;+ }+ const parentEntity = !isNaN(dropTargetId) ? dropTargetId as Entity : null;+ createEntityFromAsset(assetData, parentEntity);+ return;+ }++ if (!entityIdStr) return;++ const draggedId = parseInt(entityIdStr, 10);+ if (isNaN(draggedId)) return;++ if (isNaN(dropTargetId)) {+ const scene = state.store.scene;+ const roots = scene.entities.filter(e => e.parent === null);+ state.store.moveEntity(draggedId as Entity, null, roots.length);+ return;+ }++ if (dropTargetId === draggedId || !dropPos) return;+ if (isDescendantOf(state, draggedId, dropTargetId)) return;++ const targetEntity = state.store.getEntityData(dropTargetId);+ if (!targetEntity) return;++ if (dropPos === 'inside') {+ state.store.moveEntity(draggedId as Entity, dropTargetId as Entity, targetEntity.children.length);+ state.expandedIds.add(dropTargetId);+ } else {+ const parentId = targetEntity.parent;+ if (parentId !== null) {+ const parent = state.store.getEntityData(parentId);+ if (!parent) return;+ let idx = parent.children.indexOf(dropTargetId);+ if (dropPos === 'after') idx++;+ const draggedIdx = parent.children.indexOf(draggedId);+ if (draggedIdx !== -1 && draggedIdx < idx) idx--;+ state.store.moveEntity(draggedId as Entity, parentId as Entity, idx);+ } else {+ const scene = state.store.scene;+ const roots = scene.entities.filter(en => en.parent === null);+ let idx = roots.findIndex(en => en.id === dropTargetId);+ if (dropPos === 'after') idx++;+ const draggedIdx = roots.findIndex(en => en.id === draggedId);+ if (draggedIdx !== -1 && draggedIdx < idx) idx--;+ state.store.moveEntity(draggedId as Entity, null, idx);+ }+ }+ });+}++function getDropPosition(e: DragEvent, item: HTMLElement): DropPosition {+ const row = item.querySelector('.es-hierarchy-row') as HTMLElement;+ const rect = row.getBoundingClientRect();+ const y = e.clientY - rect.top;+ const ratio = y / rect.height;+ if (ratio < 0.25) return 'before';+ if (ratio > 0.75) return 'after';+ return 'inside';+}++function isDescendantOf(state: HierarchyState, entityId: number, ancestorId: number): boolean {+ let current: number | null = entityId;+ while (current !== null) {+ if (current === ancestorId) return true;+ const entity = state.store.getEntityData(current);+ current = entity?.parent ?? null;+ }+ return false;+}diff --git a/editor/src/panels/hierarchy/HierarchyKeyboard.ts b/editor/src/panels/hierarchy/HierarchyKeyboard.tsnew file mode 100644index 000000000..bc93e7983--- /dev/null+++ b/editor/src/panels/hierarchy/HierarchyKeyboard.ts@@ -0,0 +1,140 @@+import type { Entity } from 'esengine';+import type { HierarchyState } from './HierarchyTypes';++export function setupKeyboard(state: HierarchyState, scrollToEntity: (id: number) => void): void {+ state.treeContainer.addEventListener('keydown', (e) => {+ if (state.renamingEntityId !== null) {+ return;+ }++ if (e.key === 'F2') {+ e.preventDefault();+ const selected = state.store.selectedEntity;+ if (selected !== null) {+ state.renamingEntityId = selected as number;+ state.renderVisibleRows();+ }+ return;+ }++ if ((e.key === 'a' || e.key === 'A') && (e.ctrlKey || e.metaKey)) {+ e.preventDefault();+ const roots = state.store.scene.entities.filter(ent => ent.parent === null);+ if (roots.length > 0) {+ state.store.selectEntities(roots.map(ent => ent.id));+ }+ return;+ }++ if (e.key === 'Delete' || e.key === 'Backspace') {+ e.preventDefault();+ if (state.store.selectedEntities.size > 1) {+ state.store.deleteSelectedEntities();+ } else {+ const selected = state.store.selectedEntity;+ if (selected !== null) {+ state.store.deleteEntity(selected);+ }+ }+ return;+ }++ const selected = state.store.selectedEntity;+ const selectedIndex = selected !== null+ ? state.flatRows.findIndex(r => r.entity.id === (selected as number))+ : -1;++ switch (e.key) {+ case 'ArrowDown': {+ e.preventDefault();+ const nextIndex = selectedIndex + 1;+ if (nextIndex < state.flatRows.length) {+ const nextEntity = state.flatRows[nextIndex].entity;+ state.store.selectEntity(nextEntity.id as Entity, 'replace');+ state.lastSelectedEntity = nextEntity.id as Entity;+ scrollToEntity(nextEntity.id);+ }+ break;+ }+ case 'ArrowUp': {+ e.preventDefault();+ const prevIndex = selectedIndex - 1;+ if (prevIndex >= 0) {+ const prevEntity = state.flatRows[prevIndex].entity;+ state.store.selectEntity(prevEntity.id as Entity, 'replace');+ state.lastSelectedEntity = prevEntity.id as Entity;+ scrollToEntity(prevEntity.id);+ }+ break;+ }+ case 'ArrowRight': {+ e.preventDefault();+ if (selectedIndex === -1) break;+ const row = state.flatRows[selectedIndex];+ if (row.hasChildren && !row.isExpanded) {+ state.expandedIds.add(row.entity.id);+ state.render();+ } else if (row.hasChildren && row.isExpanded) {+ const nextIndex = selectedIndex + 1;+ if (nextIndex < state.flatRows.length) {+ const child = state.flatRows[nextIndex].entity;+ state.store.selectEntity(child.id as Entity, 'replace');+ state.lastSelectedEntity = child.id as Entity;+ scrollToEntity(child.id);+ }+ }+ break;+ }+ case 'ArrowLeft': {+ e.preventDefault();+ if (selectedIndex === -1) break;+ const row = state.flatRows[selectedIndex];+ if (row.hasChildren && row.isExpanded) {+ state.expandedIds.delete(row.entity.id);+ state.render();+ } else if (row.entity.parent !== null) {+ const parentIdx = state.flatRows.findIndex(r => r.entity.id === row.entity.parent);+ if (parentIdx !== -1) {+ const parentEntity = state.flatRows[parentIdx].entity;+ state.store.selectEntity(parentEntity.id as Entity, 'replace');+ state.lastSelectedEntity = parentEntity.id as Entity;+ scrollToEntity(parentEntity.id);+ }+ }+ break;+ }+ case 'Home': {+ e.preventDefault();+ if (state.flatRows.length > 0) {+ const first = state.flatRows[0].entity;+ state.store.selectEntity(first.id as Entity, 'replace');+ state.lastSelectedEntity = first.id as Entity;+ scrollToEntity(first.id);+ }+ break;+ }+ case 'End': {+ e.preventDefault();+ if (state.flatRows.length > 0) {+ const last = state.flatRows[state.flatRows.length - 1].entity;+ state.store.selectEntity(last.id as Entity, 'replace');+ state.lastSelectedEntity = last.id as Entity;+ scrollToEntity(last.id);+ }+ break;+ }+ }+ });+}++export function selectRange(state: HierarchyState, fromEntity: number, toEntity: number): void {+ const fromIndex = state.flatRows.findIndex(r => r.entity.id === fromEntity);+ const toIndex = state.flatRows.findIndex(r => r.entity.id === toEntity);++ if (fromIndex === -1 || toIndex === -1) return;++ const start = Math.min(fromIndex, toIndex);+ const end = Math.max(fromIndex, toIndex);+ const ids = state.flatRows.slice(start, end + 1).map(r => r.entity.id);+ state.store.selectEntities(ids);+}diff --git a/editor/src/panels/hierarchy/HierarchyPanel.ts b/editor/src/panels/hierarchy/HierarchyPanel.tsnew file mode 100644index 000000000..28ece6c0a--- /dev/null+++ b/editor/src/panels/hierarchy/HierarchyPanel.ts@@ -0,0 +1,438 @@+import type { Entity } from 'esengine';+import type { EditorStore, DirtyFlag } from '../../store/EditorStore';+import { icons } from '../../utils/icons';+import { getAssetDatabase, isUUID } from '../../asset/AssetDatabase';+import { escapeHtml } from '../../utils/html';+import { getInitialComponentData } from '../../schemas/ComponentSchemas';+import type { HierarchyState, FlattenedRow } from './HierarchyTypes';+import { ROW_HEIGHT, OVERSCAN, SLOW_DOUBLE_CLICK_MIN, SLOW_DOUBLE_CLICK_MAX } from './HierarchyTypes';+import { buildFlatRows, expandAncestors, renderSingleRow } from './HierarchyTree';+import { performSearch, selectNextResult, selectPreviousResult, focusSelectedResult, clearSearch } from './HierarchySearch';+import { setupKeyboard, selectRange } from './HierarchyKeyboard';+import { setupDragAndDrop } from './HierarchyDragDrop';+import { showEntityContextMenu, duplicateEntity, createEntityFromAsset } from './HierarchyContextMenu';++export class HierarchyPanel implements HierarchyState {+ private container_: HTMLElement;+ store: EditorStore;+ treeContainer: HTMLElement;+ searchInput: HTMLInputElement | null = null;+ private footerContainer_: HTMLElement | null = null;+ private prefabEditBar_: HTMLElement | null = null;+ private unsubscribe_: (() => void) | null = null;+ searchFilter: string = '';+ searchResults: HierarchyState['searchResults'] = [];+ selectedResultIndex: number = -1;+ expandedIds: Set<number> = new Set();+ lastSelectedEntity: Entity | null = null;+ flatRows: FlattenedRow[] = [];+ scrollContent: HTMLElement;+ visibleWindow: HTMLElement;+ private scrollRafId_: number = 0;+ private lastVisibleStart_: number = -1;+ private lastVisibleEnd_: number = -1;+ dragOverEntityId: number | null = null;+ dropPosition: HierarchyState['dropPosition'] = null;+ draggingEntityId: number | null = null;+ private boundOnScroll_: (() => void) | null = null;+ renamingEntityId: number | null = null;+ lastClickEntityId: number | null = null;+ lastClickTime: number = 0;++ constructor(container: HTMLElement, store: EditorStore) {+ this.container_ = container;+ this.store = store;++ this.container_.className = 'es-hierarchy-panel';+ this.container_.innerHTML = `+ <div class="es-panel-header">+ <span class="es-panel-title">${icons.list(14)} Hierarchy</span>+ </div>+ <div class="es-prefab-edit-bar" style="display: none;">+ <button class="es-prefab-back-btn">${icons.chevronRight(12)} Back to Scene</button>+ <span class="es-prefab-edit-name">${icons.package(12)} </span>+ </div>+ <div class="es-hierarchy-toolbar">+ <input type="text" class="es-input es-hierarchy-search" placeholder="Search...">+ <button class="es-btn es-btn-icon" data-action="collapse-all" title="Collapse All">${icons.chevronRight(12)}</button>+ <button class="es-btn es-btn-icon" data-action="expand-all" title="Expand All">${icons.chevronDown(12)}</button>+ <button class="es-btn es-btn-icon" data-action="add" title="Create Entity">${icons.plus()}</button>+ <button class="es-btn es-btn-icon" data-action="duplicate" title="Duplicate">${icons.copy()}</button>+ </div>+ <div class="es-hierarchy-columns">+ <span class="es-hierarchy-col-visibility">${icons.eye(12)}</span>+ <span class="es-hierarchy-col-lock">${icons.star(12)}</span>+ <span class="es-hierarchy-col-label">Item Label</span>+ <span class="es-hierarchy-col-type">Type</span>+ </div>+ <div class="es-hierarchy-tree" role="tree"></div>+ <div class="es-hierarchy-footer">0 entities</div>+ `;++ this.treeContainer = this.container_.querySelector('.es-hierarchy-tree')!;+ this.treeContainer.tabIndex = 0;+ this.scrollContent = document.createElement('div');+ this.scrollContent.className = 'es-hierarchy-scroll-content';+ this.visibleWindow = document.createElement('div');+ this.visibleWindow.className = 'es-hierarchy-visible-window';+ this.scrollContent.appendChild(this.visibleWindow);+ this.treeContainer.appendChild(this.scrollContent);+ this.boundOnScroll_ = () => this.onScroll();+ this.treeContainer.addEventListener('scroll', this.boundOnScroll_);+ this.searchInput = this.container_.querySelector('.es-hierarchy-search');+ this.footerContainer_ = this.container_.querySelector('.es-hierarchy-footer');+ this.prefabEditBar_ = this.container_.querySelector('.es-prefab-edit-bar');++ const backBtn = this.container_.querySelector('.es-prefab-back-btn');+ backBtn?.addEventListener('click', () => {+ this.store.exitPrefabEditMode();+ });++ this.setupEvents();+ this.unsubscribe_ = store.subscribe((_state, dirtyFlags) => this.onStoreNotify(dirtyFlags));+ this.render();+ }++ dispose(): void {+ if (this.unsubscribe_) {+ this.unsubscribe_();+ this.unsubscribe_ = null;+ }+ if (this.scrollRafId_) {+ cancelAnimationFrame(this.scrollRafId_);+ this.scrollRafId_ = 0;+ }+ if (this.boundOnScroll_) {+ this.treeContainer.removeEventListener('scroll', this.boundOnScroll_);+ this.boundOnScroll_ = null;+ }+ }++ private onStoreNotify(dirtyFlags?: ReadonlySet<DirtyFlag>): void {+ if (dirtyFlags && !dirtyFlags.has('scene') && !dirtyFlags.has('hierarchy') && !dirtyFlags.has('selection')) {+ return;+ }++ const needsRebuild = !dirtyFlags || dirtyFlags.has('scene') || dirtyFlags.has('hierarchy');++ if (needsRebuild) {+ this.render();+ } else {+ this.renderVisibleRows();+ this.updateFooter();+ }+ }++ private setupEvents(): void {+ const addBtn = this.container_.querySelector('[data-action="add"]');+ addBtn?.addEventListener('click', () => {+ const entity = this.store.createEntity();+ this.store.addComponent(entity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ });++ const dupBtn = this.container_.querySelector('[data-action="duplicate"]');+ dupBtn?.addEventListener('click', () => {+ const selected = this.store.selectedEntity;+ if (selected !== null) {+ duplicateEntity(this, selected);+ }+ });++ const collapseAllBtn = this.container_.querySelector('[data-action="collapse-all"]');+ collapseAllBtn?.addEventListener('click', () => {+ this.expandedIds.clear();+ this.render();+ });++ const expandAllBtn = this.container_.querySelector('[data-action="expand-all"]');+ expandAllBtn?.addEventListener('click', () => {+ for (const entity of this.store.scene.entities) {+ if (entity.children.length > 0) {+ this.expandedIds.add(entity.id);+ }+ }+ this.render();+ });++ this.searchInput?.addEventListener('input', () => {+ this.searchFilter = this.searchInput?.value ?? '';+ performSearch(this);+ this.render();+ });++ this.searchInput?.addEventListener('keydown', (e) => {+ if (e.key === 'ArrowDown') {+ e.preventDefault();+ selectNextResult(this);+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ selectPreviousResult(this);+ } else if (e.key === 'Enter') {+ e.preventDefault();+ focusSelectedResult(this);+ } else if (e.key === 'Escape') {+ clearSearch(this);+ }+ });++ this.treeContainer.addEventListener('click', (e) => {+ const target = e.target as HTMLElement;++ if (target.closest('.es-hierarchy-rename-input')) return;++ const visibilityBtn = target.closest('.es-hierarchy-visibility') as HTMLElement;+ if (visibilityBtn) {+ e.stopPropagation();+ const item = visibilityBtn.closest('.es-hierarchy-item') as HTMLElement;+ const entityId = parseInt(item?.dataset.entityId ?? '', 10);+ if (!isNaN(entityId)) {+ this.store.toggleVisibility(entityId);+ }+ return;+ }++ const expandBtn = target.closest('.es-hierarchy-expand') as HTMLElement;+ if (expandBtn) {+ e.stopPropagation();+ const row = expandBtn.closest('.es-hierarchy-row');+ const item = row?.parentElement as HTMLElement;+ const entityId = parseInt(item?.dataset.entityId ?? '', 10);+ if (!isNaN(entityId)) {+ if (this.expandedIds.has(entityId)) {+ this.expandedIds.delete(entityId);+ } else {+ this.expandedIds.add(entityId);+ }+ this.render();+ }+ return;+ }++ const row = target.closest('.es-hierarchy-row');+ const item = row?.parentElement as HTMLElement;+ if (!item?.classList.contains('es-hierarchy-item')) return;++ const entityId = parseInt(item.dataset.entityId ?? '', 10);+ if (isNaN(entityId)) return;++ const now = Date.now();+ const timeSinceLastClick = now - this.lastClickTime;+ const sameEntity = this.lastClickEntityId === entityId;+ const wasSelected = this.store.selectedEntities.has(entityId);++ if (e.shiftKey && this.lastSelectedEntity !== null) {+ selectRange(this, this.lastSelectedEntity as number, entityId);+ this.lastSelectedEntity = entityId as Entity;+ } else if (e.ctrlKey || e.metaKey) {+ this.store.selectEntity(entityId as Entity, 'toggle');+ this.lastSelectedEntity = entityId as Entity;+ } else {+ if (sameEntity && wasSelected && !e.shiftKey && !e.ctrlKey && !e.metaKey+ && timeSinceLastClick >= SLOW_DOUBLE_CLICK_MIN+ && timeSinceLastClick <= SLOW_DOUBLE_CLICK_MAX) {+ this.startInlineRename(entityId);+ } else {+ this.store.selectEntity(entityId as Entity, 'replace');+ this.lastSelectedEntity = entityId as Entity;+ }+ }++ this.lastClickEntityId = entityId;+ this.lastClickTime = now;+ });++ this.treeContainer.addEventListener('dblclick', (e) => {+ const target = e.target as HTMLElement;+ if (target.closest('.es-hierarchy-rename-input')) return;+ const item = target.closest('.es-hierarchy-item') as HTMLElement;+ if (!item) return;++ const entityId = parseInt(item.dataset.entityId ?? '', 10);+ if (!isNaN(entityId)) {+ this.lastClickEntityId = null;+ this.lastClickTime = 0;+ this.store.focusEntity(entityId);+ }+ });++ this.treeContainer.addEventListener('contextmenu', (e) => {+ e.preventDefault();+ const target = e.target as HTMLElement;+ const item = target.closest('.es-hierarchy-item') as HTMLElement;++ if (item) {+ const entityId = parseInt(item.dataset.entityId ?? '', 10);+ if (!isNaN(entityId)) {+ showEntityContextMenu(this, e.clientX, e.clientY, entityId as Entity);+ }+ } else {+ showEntityContextMenu(this, e.clientX, e.clientY, null);+ }+ });++ setupKeyboard(this, (id) => this.scrollToEntity(id));+ setupDragAndDrop(this, (asset, parent) => createEntityFromAsset(this, asset, parent));+ }++ private startInlineRename(entityId: number): void {+ const entityData = this.store.getEntityData(entityId);+ if (!entityData) return;++ this.renamingEntityId = entityId;++ const item = this.visibleWindow.querySelector(`[data-entity-id="${entityId}"]`);+ if (!item) return;++ const nameSpan = item.querySelector('.es-hierarchy-name') as HTMLElement;+ if (!nameSpan) return;++ const input = document.createElement('input');+ input.type = 'text';+ input.className = 'es-hierarchy-rename-input';+ input.value = entityData.name;+ input.select();++ const commitRename = () => {+ const newName = input.value.trim();+ if (newName && newName !== entityData.name) {+ this.store.renameEntity(entityId as Entity, newName);+ }+ this.renamingEntityId = null;+ this.renderVisibleRows();+ };++ const cancelRename = () => {+ this.renamingEntityId = null;+ this.renderVisibleRows();+ };++ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ commitRename();+ } else if (e.key === 'Escape') {+ e.preventDefault();+ cancelRename();+ }+ e.stopPropagation();+ });++ input.addEventListener('blur', commitRename, { once: true });++ nameSpan.textContent = '';+ nameSpan.appendChild(input);+ input.focus();+ input.select();+ }++ render(): void {+ const scene = this.store.scene;+ const selectedEntity = this.store.selectedEntity;++ if (this.prefabEditBar_) {+ if (this.store.isEditingPrefab) {+ this.prefabEditBar_.style.display = '';+ const nameEl = this.prefabEditBar_.querySelector('.es-prefab-edit-name');+ if (nameEl) {+ const rawPath = this.store.prefabEditingPath ?? '';+ const path = isUUID(rawPath) ? (getAssetDatabase().getPath(rawPath) ?? rawPath) : rawPath;+ const fileName = path.split('/').pop() ?? path;+ nameEl.innerHTML = `${icons.package(12)} ${escapeHtml(fileName)}`;+ }+ } else {+ this.prefabEditBar_.style.display = 'none';+ }+ }++ const selectionChanged = selectedEntity !== null && selectedEntity !== this.lastSelectedEntity;+ if (selectionChanged) {+ expandAncestors(this, selectedEntity);+ }+ this.lastSelectedEntity = selectedEntity;++ this.flatRows = buildFlatRows(this);+ this.scrollContent.style.height = `${this.flatRows.length * ROW_HEIGHT}px`;+ this.lastVisibleStart_ = -1;+ this.lastVisibleEnd_ = -1;+ this.renderVisibleRows();++ this.updateFooter();++ if (selectionChanged) {+ this.scrollToEntity(selectedEntity as number);+ }+ }++ private updateFooter(): void {+ if (!this.footerContainer_) return;++ if (this.searchFilter) {+ const count = this.searchResults.length;+ this.footerContainer_.textContent = `${count} ${count === 1 ? 'match' : 'matches'}`;+ } else {+ const count = this.store.scene.entities.length;+ this.footerContainer_.textContent = `${count} ${count === 1 ? 'entity' : 'entities'}`;+ }+ }++ renderVisibleRows(): void {+ const { start, end } = this.getVisibleRange();+ const selectedEntity = this.store.selectedEntity;++ this.visibleWindow.style.transform = `translateY(${start * ROW_HEIGHT}px)`;++ let html = '';+ for (let i = start; i < end; i++) {+ html += renderSingleRow(this, this.flatRows[i], selectedEntity);+ }+ this.visibleWindow.innerHTML = html;++ this.lastVisibleStart_ = start;+ this.lastVisibleEnd_ = end;++ if (this.renamingEntityId !== null) {+ const item = this.visibleWindow.querySelector(`[data-entity-id="${this.renamingEntityId}"]`);+ if (item) {+ this.startInlineRename(this.renamingEntityId);+ }+ }+ }++ private getVisibleRange(): { start: number; end: number } {+ const scrollTop = this.treeContainer.scrollTop;+ const viewHeight = this.treeContainer.clientHeight;+ const totalRows = this.flatRows.length;++ let start = Math.floor(scrollTop / ROW_HEIGHT) - OVERSCAN;+ let end = Math.ceil((scrollTop + viewHeight) / ROW_HEIGHT) + OVERSCAN;++ return { start: Math.max(0, start), end: Math.min(totalRows, end) };+ }++ private scrollToEntity(entityId: number): void {+ const index = this.flatRows.findIndex(r => r.entity.id === entityId);+ if (index === -1) return;++ const targetTop = index * ROW_HEIGHT;+ const targetBottom = targetTop + ROW_HEIGHT;+ const scrollTop = this.treeContainer.scrollTop;+ const viewHeight = this.treeContainer.clientHeight;++ if (targetTop < scrollTop) {+ this.treeContainer.scrollTop = targetTop;+ } else if (targetBottom > scrollTop + viewHeight) {+ this.treeContainer.scrollTop = targetBottom - viewHeight;+ }+ }++ private onScroll(): void {+ if (this.scrollRafId_) return;+ this.scrollRafId_ = requestAnimationFrame(() => {+ this.scrollRafId_ = 0;+ const { start, end } = this.getVisibleRange();+ if (start !== this.lastVisibleStart_ || end !== this.lastVisibleEnd_) {+ this.renderVisibleRows();+ }+ });+ }+}diff --git a/editor/src/panels/hierarchy/HierarchySearch.ts b/editor/src/panels/hierarchy/HierarchySearch.tsnew file mode 100644index 000000000..d81d689bc--- /dev/null+++ b/editor/src/panels/hierarchy/HierarchySearch.ts@@ -0,0 +1,49 @@+import type { Entity } from 'esengine';+import { fuzzyFilter } from '../../utils/fuzzy';+import type { HierarchyState } from './HierarchyTypes';++export function performSearch(state: HierarchyState): void {+ if (!state.searchFilter) {+ state.searchResults = [];+ state.selectedResultIndex = -1;+ return;+ }++ const scene = state.store.scene;+ const results = fuzzyFilter(+ scene.entities,+ state.searchFilter,+ (entity) => entity.name+ );++ state.searchResults = results.map(r => ({ entity: r.item, match: r.match }));+ state.selectedResultIndex = state.searchResults.length > 0 ? 0 : -1;+}++export function selectNextResult(state: HierarchyState): void {+ if (state.searchResults.length === 0) return;+ state.selectedResultIndex = (state.selectedResultIndex + 1) % state.searchResults.length;+ state.render();+}++export function selectPreviousResult(state: HierarchyState): void {+ if (state.searchResults.length === 0) return;+ state.selectedResultIndex = (state.selectedResultIndex - 1 + state.searchResults.length) % state.searchResults.length;+ state.render();+}++export function focusSelectedResult(state: HierarchyState): void {+ if (state.selectedResultIndex === -1 || state.selectedResultIndex >= state.searchResults.length) return;+ const result = state.searchResults[state.selectedResultIndex];+ state.store.selectEntity(result.entity.id as Entity);+}++export function clearSearch(state: HierarchyState): void {+ if (state.searchInput) {+ state.searchInput.value = '';+ }+ state.searchFilter = '';+ state.searchResults = [];+ state.selectedResultIndex = -1;+ state.render();+}diff --git a/editor/src/panels/hierarchy/HierarchyTree.ts b/editor/src/panels/hierarchy/HierarchyTree.tsnew file mode 100644index 000000000..b358d5098--- /dev/null+++ b/editor/src/panels/hierarchy/HierarchyTree.ts@@ -0,0 +1,143 @@+import type { Entity } from 'esengine';+import type { EntityData } from '../../types/SceneTypes';+import type { FuzzyMatch } from '../../utils/fuzzy';+import { icons } from '../../utils/icons';+import { escapeHtml } from '../../utils/html';+import type { FlattenedRow, HierarchyState } from './HierarchyTypes';++export function buildFlatRows(state: HierarchyState): FlattenedRow[] {+ const rows: FlattenedRow[] = [];+ const scene = state.store.scene;++ if (state.searchFilter) {+ for (const result of state.searchResults) {+ rows.push({+ entity: result.entity,+ depth: 0,+ hasChildren: false,+ isExpanded: false,+ });+ }+ return rows;+ }++ const roots = scene.entities.filter(e => e.parent === null);+ flattenDFS(state, roots, 0, rows);+ return rows;+}++function flattenDFS(state: HierarchyState, entities: EntityData[], depth: number, rows: FlattenedRow[]): void {+ for (const entity of entities) {+ const children = entity.children+ .map(id => state.store.getEntityData(id))+ .filter((e): e is EntityData => e !== null);+ const hasChildren = children.length > 0;+ const isExpanded = state.expandedIds.has(entity.id);++ rows.push({ entity, depth, hasChildren, isExpanded });++ if (hasChildren && isExpanded) {+ flattenDFS(state, children, depth + 1, rows);+ }+ }+}++export function expandAncestors(state: HierarchyState, entityId: Entity): void {+ const entity = state.store.getEntityData(entityId as number);+ if (!entity || entity.parent === null) return;++ let parentId: number | null = entity.parent;+ while (parentId !== null) {+ state.expandedIds.add(parentId);+ const parent = state.store.getEntityData(parentId);+ parentId = parent?.parent ?? null;+ }+}++export function getEntityIcon(entity: EntityData): string {+ if (entity.prefab?.isRoot) return icons.package(12);++ const hasCamera = entity.components.some(c => c.type === 'Camera');+ const hasSprite = entity.components.some(c => c.type === 'Sprite');+ const hasText = entity.components.some(c => c.type === 'Text');+ const hasBitmapText = entity.components.some(c => c.type === 'BitmapText');+ const hasTextInput = entity.components.some(c => c.type === 'TextInput');+ const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');++ if (hasCamera) return icons.camera(12);+ if (hasSpine) return icons.bone(12);+ if (hasText || hasBitmapText || hasTextInput) return icons.type(12);+ if (hasSprite) return icons.image(12);+ return icons.box(12);+}++export function getEntityType(entity: EntityData): string {+ const hasCamera = entity.components.some(c => c.type === 'Camera');+ const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');+ if (hasCamera) return 'Camera';+ if (hasSpine) return 'Spine';+ return 'Entity';+}++export function renderSingleRow(state: HierarchyState, row: FlattenedRow, selectedEntity: Entity | null): string {+ const { entity, depth, hasChildren, isExpanded } = row;+ const icon = getEntityIcon(entity);+ const type = getEntityType(entity);+ const expandIcon = isExpanded ? icons.chevronDown(10) : icons.chevronRight(10);+ const isVisible = state.store.isEntityVisible(entity.id);+ const visibilityIcon = isVisible ? icons.eye(10) : icons.eyeOff(10);++ let itemClass = 'es-hierarchy-item';+ if (state.store.selectedEntities.has(entity.id)) itemClass += ' es-selected';+ if (!isVisible) itemClass += ' es-entity-hidden';+ if (entity.prefab?.isRoot) itemClass += ' es-prefab-root';+ else if (entity.prefab) itemClass += ' es-prefab-child';+ if (hasChildren) itemClass += ' es-has-children';+ if (isExpanded) itemClass += ' es-expanded';+ if (entity.id === state.draggingEntityId) itemClass += ' es-dragging';+ if (entity.id === state.dragOverEntityId) {+ if (state.dropPosition) {+ itemClass += ` es-drop-${state.dropPosition}`;+ } else {+ itemClass += ' es-drag-over';+ }+ }++ const match = state.searchFilter ? state.searchResults.find(r => r.entity.id === entity.id)?.match : null;+ if (state.searchFilter && match) {+ const resultIdx = state.searchResults.findIndex(r => r.entity.id === entity.id);+ if (resultIdx === state.selectedResultIndex) {+ itemClass += ' es-search-selected';+ }+ }++ const nameHtml = renderEntityName(entity.name, match);++ const ariaExpanded = hasChildren ? ` aria-expanded="${isExpanded}"` : '';++ return `<div class="${itemClass}" data-entity-id="${entity.id}" role="treeitem"${ariaExpanded}>+ <div class="es-hierarchy-row" draggable="true" style="padding-left: ${8 + depth * 16}px">+ ${hasChildren ? `<span class="es-hierarchy-expand">${expandIcon}</span>` : '<span class="es-hierarchy-spacer"></span>'}+ <span class="es-hierarchy-visibility">${visibilityIcon}</span>+ <span class="es-hierarchy-icon">${icon}</span>+ <span class="es-hierarchy-name">${nameHtml}</span>+ <span class="es-hierarchy-type">${type}</span>+ </div>+ </div>`;+}++function renderEntityName(name: string, match: FuzzyMatch | null | undefined): string {+ if (!match || match.matches.length === 0) {+ return escapeHtml(name);+ }++ let html = '';+ for (let i = 0; i < name.length; i++) {+ if (match.matches.includes(i)) {+ html += `<mark class="es-search-highlight">${escapeHtml(name[i])}</mark>`;+ } else {+ html += escapeHtml(name[i]);+ }+ }+ return html;+}diff --git a/editor/src/panels/hierarchy/HierarchyTypes.ts b/editor/src/panels/hierarchy/HierarchyTypes.tsnew file mode 100644index 000000000..d88297ba4--- /dev/null+++ b/editor/src/panels/hierarchy/HierarchyTypes.ts@@ -0,0 +1,40 @@+import type { Entity } from 'esengine';+import type { EntityData } from '../../types/SceneTypes';+import type { EditorStore } from '../../store/EditorStore';+import type { FuzzyMatch } from '../../utils/fuzzy';++export type DropPosition = 'before' | 'after' | 'inside';++export const ROW_HEIGHT = 22;+export const OVERSCAN = 5;+export const SLOW_DOUBLE_CLICK_MIN = 300;+export const SLOW_DOUBLE_CLICK_MAX = 800;++export interface FlattenedRow {+ entity: EntityData;+ depth: number;+ hasChildren: boolean;+ isExpanded: boolean;+}++export interface HierarchyState {+ store: EditorStore;+ treeContainer: HTMLElement;+ visibleWindow: HTMLElement;+ scrollContent: HTMLElement;+ searchInput: HTMLInputElement | null;+ expandedIds: Set<number>;+ flatRows: FlattenedRow[];+ searchFilter: string;+ searchResults: Array<{ entity: EntityData; match: FuzzyMatch }>;+ selectedResultIndex: number;+ lastSelectedEntity: Entity | null;+ dragOverEntityId: number | null;+ dropPosition: DropPosition | null;+ draggingEntityId: number | null;+ renamingEntityId: number | null;+ lastClickEntityId: number | null;+ lastClickTime: number;+ render(): void;+ renderVisibleRows(): void;+}diff --git a/editor/src/panels/hierarchy/index.ts b/editor/src/panels/hierarchy/index.tsnew file mode 100644index 000000000..243d427df--- /dev/null+++ b/editor/src/panels/hierarchy/index.ts@@ -0,0 +1 @@+export { HierarchyPanel } from './HierarchyPanel';diff --git a/editor/src/panels/index.ts b/editor/src/panels/index.tsindex 1a7782e8a..1a3353b03 100644--- a/editor/src/panels/index.ts+++ b/editor/src/panels/index.ts@@ -3,9 +3,9 @@* @brief Editor panels exports*/-export { HierarchyPanel } from './HierarchyPanel';+export { HierarchyPanel } from './hierarchy/HierarchyPanel';export { InspectorPanel } from './InspectorPanel';-export { SceneViewPanel } from './SceneViewPanel';+export { SceneViewPanel } from './scene-view/SceneViewPanel';export { OutputPanel } from './OutputPanel';export {diff --git a/editor/src/panels/inspector/EntityInspector.ts b/editor/src/panels/inspector/EntityInspector.tsindex aa8b0dc80..d68b9fd95 100644--- a/editor/src/panels/inspector/EntityInspector.ts+++ b/editor/src/panels/inspector/EntityInspector.ts@@ -32,6 +32,7 @@ import {type InspectorContext,type InspectorSectionInstance,} from './InspectorRegistry';+import { deepEqual } from './SharedEditors';// =============================================================================// Global Augmentation@@ -168,6 +169,8 @@ export function renderComponent(return;}+ const defaults = getDefaultComponentData(component.type);+const section = document.createElement('div');section.className = 'es-component-section es-collapsible es-expanded';@@ -197,7 +200,6 @@ export function renderComponent(header.addEventListener('contextmenu', (e) => {e.preventDefault();- const defaults = getDefaultComponentData(component.type);const menuItems: ContextMenuItem[] = [{label: 'Reset to Default',@@ -317,7 +319,6 @@ export function renderComponent(const editorContainer = document.createElement('div');editorContainer.className = 'es-property-editor es-property-editor-full';- const defaults = getDefaultComponentData(component.type);const fullData = { ...defaults, ...component.data };const editor = createPropertyEditor(editorContainer, {@@ -365,7 +366,6 @@ export function renderComponent(let currentValue = component.data[propMeta.name];if (currentValue === undefined) {- const defaults = getDefaultComponentData(component.type);currentValue = defaults[propMeta.name];}const editor = createPropertyEditor(editorContainer, {@@ -396,10 +396,9 @@ export function renderComponent(row.appendChild(label);row.appendChild(editorContainer);- const defaults = getDefaultComponentData(component.type);const defaultValue = defaults[propMeta.name];const isModified = currentValue !== undefined &&- JSON.stringify(currentValue) !== JSON.stringify(defaultValue);+ !deepEqual(currentValue, defaultValue);if (isModified) {const resetBtn = document.createElement('button');diff --git a/editor/src/panels/scene-view/CameraController.ts b/editor/src/panels/scene-view/CameraController.tsnew file mode 100644index 000000000..ba8528727--- /dev/null+++ b/editor/src/panels/scene-view/CameraController.ts@@ -0,0 +1,157 @@+import { getSettingsValue } from '../../settings/SettingsRegistry';++export class CameraController {+ panX = 0;+ panY = 0;+ zoom = 1;++ private isDragging_ = false;+ private lastMouseX_ = 0;+ private lastMouseY_ = 0;+ private spaceDown_ = false;+ private canvas_: HTMLCanvasElement;+ private onRender_: () => void;++ constructor(canvas: HTMLCanvasElement, onRender: () => void) {+ this.canvas_ = canvas;+ this.onRender_ = onRender;+ }++ setCanvas(canvas: HTMLCanvasElement): void {+ this.canvas_ = canvas;+ }++ get isDragging(): boolean {+ return this.isDragging_;+ }++ get spaceDown(): boolean {+ return this.spaceDown_;+ }++ set spaceDown(value: boolean) {+ this.spaceDown_ = value;+ }++ reset(): void {+ this.panX = 0;+ this.panY = 0;+ this.zoom = 1;+ }++ startDrag(clientX: number, clientY: number): void {+ this.isDragging_ = true;+ this.lastMouseX_ = clientX;+ this.lastMouseY_ = clientY;+ this.canvas_.style.cursor = 'grabbing';+ }++ drag(clientX: number, clientY: number): boolean {+ if (!this.isDragging_) return false;++ const dx = clientX - this.lastMouseX_;+ const dy = clientY - this.lastMouseY_;++ this.panX += dx / this.zoom;+ this.panY += dy / this.zoom;++ this.lastMouseX_ = clientX;+ this.lastMouseY_ = clientY;+ this.onRender_();+ return true;+ }++ stopDrag(): void {+ this.isDragging_ = false;+ this.canvas_.style.cursor = this.spaceDown_ ? 'grab' : 'default';+ }++ wheel(e: WheelEvent): void {+ e.preventDefault();++ const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;+ const newZoom = Math.max(0.1, Math.min(10, this.zoom * zoomFactor));++ const rect = this.canvas_.getBoundingClientRect();+ const dpr = window.devicePixelRatio;+ const mouseX = (e.clientX - rect.left) * dpr;+ const mouseY = (e.clientY - rect.top) * dpr;++ const worldX = (mouseX - this.canvas_.width / 2) / this.zoom - this.panX;+ const worldY = (mouseY - this.canvas_.height / 2) / this.zoom - this.panY;++ this.zoom = newZoom;++ this.panX = (mouseX - this.canvas_.width / 2) / this.zoom - worldX;+ this.panY = (mouseY - this.canvas_.height / 2) / this.zoom - worldY;++ this.onRender_();+ }++ zoomIn(): void {+ this.zoom = Math.min(10, this.zoom * 1.1);+ this.onRender_();+ }++ zoomOut(): void {+ this.zoom = Math.max(0.1, this.zoom * 0.9);+ this.onRender_();+ }++ focusOnEntity(worldX: number, worldY: number): void {+ this.panX = -worldX;+ this.panY = worldY;+ this.onRender_();+ }++ screenToWorld(clientX: number, clientY: number): { worldX: number; worldY: number } {+ const rect = this.canvas_.getBoundingClientRect();+ const dpr = window.devicePixelRatio || 1;+ const x = (clientX - rect.left) * dpr;+ const y = (clientY - rect.top) * dpr;+ const w = this.canvas_.width;+ const h = this.canvas_.height;++ return {+ worldX: (x - w / 2) / this.zoom - this.panX,+ worldY: -(y - h / 2) / this.zoom + this.panY,+ };+ }++ nudgeSelection(+ e: KeyboardEvent,+ store: { selectedEntity: number | null; getEntityData: (id: number) => any; updateProperty: (...args: any[]) => void },+ ): void {+ const entity = store.selectedEntity;+ if (entity === null) return;++ const entityData = store.getEntityData(entity);+ if (!entityData) return;++ const transform = entityData.components.find((c: any) => c.type === 'LocalTransform');+ if (!transform) return;++ const pos = transform.data.position as { x: number; y: number; z: number };+ if (!pos) return;++ const snapOn = e.ctrlKey || e.metaKey;+ const step = snapOn ? (getSettingsValue<number>('scene.gridSize') ?? 50) : 1;++ let dx = 0;+ let dy = 0;+ if (e.key === 'ArrowLeft') dx = -step;+ if (e.key === 'ArrowRight') dx = step;+ if (e.key === 'ArrowUp') dy = step;+ if (e.key === 'ArrowDown') dy = -step;++ const oldPos = { ...pos };+ const newPos = { x: pos.x + dx, y: pos.y + dy, z: pos.z };++ store.updateProperty(entity, 'LocalTransform', 'position', oldPos, newPos);+ e.preventDefault();+ }++ shouldStartDrag(e: MouseEvent): boolean {+ return e.button === 1 || (e.button === 0 && e.altKey) || (e.button === 0 && this.spaceDown_);+ }+}diff --git a/editor/src/panels/scene-view/EntityDropHandler.ts b/editor/src/panels/scene-view/EntityDropHandler.tsnew file mode 100644index 000000000..72d7f78a1--- /dev/null+++ b/editor/src/panels/scene-view/EntityDropHandler.ts@@ -0,0 +1,77 @@+import type { EditorStore } from '../../store/EditorStore';+import { getDefaultComponentData, getInitialComponentData } from '../../schemas/ComponentSchemas';+import { getGlobalPathResolver } from '../../asset';+import { getPlatformAdapter } from '../../platform/PlatformAdapter';++export class EntityDropHandler {+ private store_: EditorStore;++ constructor(store: EditorStore) {+ this.store_ = store;+ }++ setupListeners(+ canvas: HTMLCanvasElement,+ screenToWorld: (clientX: number, clientY: number) => { worldX: number; worldY: number },+ ): void {+ canvas.addEventListener('dragover', (e) => {+ const types = e.dataTransfer?.types ?? [];+ if (!Array.from(types).includes('application/esengine-asset')) return;+ e.preventDefault();+ e.dataTransfer!.dropEffect = 'copy';+ });++ canvas.addEventListener('drop', (e) => {+ e.preventDefault();+ const assetDataStr = e.dataTransfer?.getData('application/esengine-asset');+ if (!assetDataStr) return;++ let assetData: { type: string; path: string; name: string };+ try {+ assetData = JSON.parse(assetDataStr);+ } catch {+ return;+ }++ if (assetData.type !== 'image') return;++ const { worldX, worldY } = screenToWorld(e.clientX, e.clientY);+ this.createSpriteFromDrop(assetData, worldX, worldY);+ });+ }++ private createSpriteFromDrop(+ asset: { type: string; path: string; name: string },+ worldX: number,+ worldY: number,+ ): void {+ const baseName = asset.name.replace(/\.[^.]+$/, '');+ const newEntity = this.store_.createEntity(baseName);++ const transformData = getInitialComponentData('LocalTransform');+ transformData.position = { x: worldX, y: worldY, z: 0 };+ this.store_.addComponent(newEntity, 'LocalTransform', transformData);++ const relativePath = getGlobalPathResolver().toRelativePath(asset.path);+ this.store_.addComponent(newEntity, 'Sprite', {+ ...getInitialComponentData('Sprite'),+ texture: relativePath,+ });++ this.loadImageSize(asset.path).then(size => {+ if (size) {+ const defaultSize = getDefaultComponentData('Sprite').size;+ this.store_.updateProperty(newEntity, 'Sprite', 'size', defaultSize, size);+ }+ });+ }++ private loadImageSize(absolutePath: string): Promise<{ x: number; y: number } | null> {+ return new Promise((resolve) => {+ const img = new Image();+ img.onload = () => resolve({ x: img.naturalWidth, y: img.naturalHeight });+ img.onerror = () => resolve(null);+ img.src = getPlatformAdapter().convertFilePathToUrl(absolutePath);+ });+ }+}diff --git a/editor/src/panels/scene-view/GizmoToolbar.ts b/editor/src/panels/scene-view/GizmoToolbar.tsnew file mode 100644index 000000000..7b985a2f1--- /dev/null+++ b/editor/src/panels/scene-view/GizmoToolbar.ts@@ -0,0 +1,194 @@+import { GizmoManager, getAllGizmos } from '../../gizmos';+import { getSettingsValue, setSettingsValue, onSettingsChange } from '../../settings/SettingsRegistry';+import { icons } from '../../utils/icons';++export class GizmoToolbar {+ private container_: HTMLElement;+ private gizmoManager_: GizmoManager;+ private settingsDropdown_: HTMLElement | null = null;+ private settingsDropdownClickHandler_: ((e: MouseEvent) => void) | null = null;+ private unsubscribeSettings_: (() => void) | null = null;+ private onRender_: () => void;++ constructor(container: HTMLElement, gizmoManager: GizmoManager, onRender: () => void) {+ this.container_ = container;+ this.gizmoManager_ = gizmoManager;+ this.onRender_ = onRender;+ }++ buildToolbarHTML(): string {+ const gizmos = getAllGizmos();+ return gizmos.map(g => {+ const isActive = g.id === this.gizmoManager_.getActiveId();+ const shortcutLabel = g.shortcut ? ` (${g.shortcut.toUpperCase()})` : '';+ return `<button class="es-btn es-btn-icon es-gizmo-btn${isActive ? ' es-active' : ''}" data-mode="${g.id}" title="${g.name}${shortcutLabel}">${g.icon}</button>`;+ }).join('');+ }++ buildSettingsHTML(): string {+ return `+ <div class="es-gizmo-settings-wrapper">+ <button class="es-btn es-btn-icon" data-action="gizmo-settings" title="Gizmo Settings">${icons.settings(14)}</button>+ <div class="es-gizmo-settings-dropdown" style="display: none;">+ <div class="es-settings-row">+ <label class="es-settings-checkbox">+ <input type="checkbox" data-setting="scene.showGrid" ${getSettingsValue<boolean>('scene.showGrid') ? 'checked' : ''}>+ <span>Show Grid</span>+ </label>+ </div>+ <div class="es-settings-row">+ <label class="es-settings-label">Grid Color</label>+ <input type="color" data-setting="scene.gridColor" value="${getSettingsValue<string>('scene.gridColor')}" class="es-color-input">+ </div>+ <div class="es-settings-row">+ <label class="es-settings-label">Grid Opacity</label>+ <input type="range" data-setting="scene.gridOpacity" min="0" max="1" step="0.1" value="${getSettingsValue<number>('scene.gridOpacity')}" class="es-slider-input">+ </div>+ <div class="es-settings-row">+ <label class="es-settings-label">Grid Size</label>+ <input type="number" data-setting="scene.gridSize" min="1" max="500" step="1" value="${getSettingsValue<number>('scene.gridSize') ?? 50}" class="es-number-input">+ </div>+ <div class="es-settings-divider"></div>+ <div class="es-settings-row">+ <label class="es-settings-checkbox">+ <input type="checkbox" data-setting="scene.showGizmos" ${getSettingsValue<boolean>('scene.showGizmos') ? 'checked' : ''}>+ <span>Show Gizmos</span>+ </label>+ </div>+ <div class="es-settings-row">+ <label class="es-settings-checkbox">+ <input type="checkbox" data-setting="scene.showSelectionBox" ${getSettingsValue<boolean>('scene.showSelectionBox') ? 'checked' : ''}>+ <span>Show Selection Box</span>+ </label>+ </div>+ <div class="es-settings-row">+ <label class="es-settings-checkbox">+ <input type="checkbox" data-setting="scene.showColliders" ${getSettingsValue<boolean>('scene.showColliders') ? 'checked' : ''}>+ <span>Show Colliders</span>+ </label>+ </div>+ <div class="es-settings-divider"></div>+ <div class="es-settings-row">+ <label class="es-settings-checkbox">+ <input type="checkbox" data-setting="scene.showStats" ${getSettingsValue<boolean>('scene.showStats') ? 'checked' : ''}>+ <span>Show Stats</span>+ </label>+ </div>+ </div>+ </div>`;+ }++ setupEvents(): void {+ const gizmoButtons = this.container_.querySelectorAll('.es-gizmo-btn');+ gizmoButtons.forEach(btn => {+ btn.addEventListener('click', () => {+ const mode = (btn as HTMLElement).dataset.mode;+ if (mode) this.setMode(mode);+ });+ });++ this.setupSettingsDropdown();+ }++ setMode(mode: string): void {+ this.gizmoManager_.setActive(mode);+ const buttons = this.container_.querySelectorAll('.es-gizmo-btn');+ buttons.forEach(btn => {+ const btnMode = (btn as HTMLElement).dataset.mode;+ btn.classList.toggle('es-active', btnMode === mode);+ });+ this.onRender_();+ }++ handleKeyShortcut(key: string): boolean {+ const gizmos = getAllGizmos();+ for (const g of gizmos) {+ if (g.shortcut && key.toLowerCase() === g.shortcut) {+ this.setMode(g.id);+ return true;+ }+ }+ return false;+ }++ updateZoomDisplay(zoom: number): void {+ const display = this.container_.querySelector('.es-zoom-display');+ if (display) {+ display.textContent = `${Math.round(zoom * 100)}%`;+ }+ }++ updateSnapIndicator(active: boolean): void {+ const indicator = this.container_.querySelector('.es-snap-indicator') as HTMLElement | null;+ if (indicator) {+ indicator.style.display = active ? 'inline' : 'none';+ }+ }++ private setupSettingsDropdown(): void {+ const settingsBtn = this.container_.querySelector('[data-action="gizmo-settings"]');+ this.settingsDropdown_ = this.container_.querySelector('.es-gizmo-settings-dropdown');++ if (!settingsBtn || !this.settingsDropdown_) return;++ settingsBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ const isVisible = this.settingsDropdown_!.style.display !== 'none';+ this.settingsDropdown_!.style.display = isVisible ? 'none' : 'block';+ });++ this.settingsDropdownClickHandler_ = (e: MouseEvent) => {+ if (this.settingsDropdown_ && !this.settingsDropdown_.contains(e.target as Node) &&+ !settingsBtn.contains(e.target as Node)) {+ this.settingsDropdown_.style.display = 'none';+ }+ };+ document.addEventListener('click', this.settingsDropdownClickHandler_);++ this.settingsDropdown_.querySelectorAll('input').forEach(input => {+ const settingId = input.dataset.setting;+ if (!settingId) return;++ input.addEventListener('change', () => {+ if (input.type === 'checkbox') {+ setSettingsValue(settingId, input.checked);+ } else if (input.type === 'range' || input.type === 'number') {+ setSettingsValue(settingId, parseFloat(input.value));+ } else if (input.type === 'color') {+ setSettingsValue(settingId, input.value);+ }+ this.onRender_();+ });++ if (input.type === 'range') {+ input.addEventListener('input', () => {+ setSettingsValue(settingId, parseFloat(input.value));+ this.onRender_();+ });+ }+ });++ this.unsubscribeSettings_ = onSettingsChange((id, value) => {+ if (!id.startsWith('scene.')) return;+ const input = this.settingsDropdown_?.querySelector(`[data-setting="${id}"]`) as HTMLInputElement | null;+ if (!input) return;+ if (input.type === 'checkbox') {+ input.checked = value as boolean;+ } else {+ input.value = String(value);+ }+ this.onRender_();+ });+ }++ dispose(): void {+ if (this.settingsDropdownClickHandler_) {+ document.removeEventListener('click', this.settingsDropdownClickHandler_);+ this.settingsDropdownClickHandler_ = null;+ }+ if (this.unsubscribeSettings_) {+ this.unsubscribeSettings_();+ this.unsubscribeSettings_ = null;+ }+ }+}diff --git a/editor/src/panels/scene-view/MarqueeSelection.ts b/editor/src/panels/scene-view/MarqueeSelection.tsnew file mode 100644index 000000000..d7f9402a3--- /dev/null+++ b/editor/src/panels/scene-view/MarqueeSelection.ts@@ -0,0 +1,91 @@+import type { Entity } from 'esengine';+import type { EditorStore } from '../../store/EditorStore';+import type { EntityData } from '../../types/SceneTypes';++export type BoundsProvider = (entityData: EntityData) => { width: number; height: number; offsetX?: number; offsetY?: number };++export class MarqueeSelection {+ active = false;+ startX = 0;+ startY = 0;+ endX = 0;+ endY = 0;++ start(worldX: number, worldY: number): void {+ this.active = true;+ this.startX = worldX;+ this.startY = worldY;+ this.endX = worldX;+ this.endY = worldY;+ }++ update(worldX: number, worldY: number): void {+ this.endX = worldX;+ this.endY = worldY;+ }++ finish(store: EditorStore, getBounds: BoundsProvider, addToExisting: boolean): void {+ this.active = false;+ const hits = this.findEntitiesInRect(store, getBounds);++ if (addToExisting) {+ const existing = Array.from(store.selectedEntities);+ const merged = new Set([...existing, ...hits.map(h => h as number)]);+ store.selectEntities(Array.from(merged));+ } else {+ store.selectEntities(hits.map(h => h as number));+ }+ }++ findEntitiesInRect(store: EditorStore, getBounds: BoundsProvider): Entity[] {+ const minX = Math.min(this.startX, this.endX);+ const maxX = Math.max(this.startX, this.endX);+ const minY = Math.min(this.startY, this.endY);+ const maxY = Math.max(this.startY, this.endY);++ const scene = store.scene;+ const result: Entity[] = [];++ for (const entity of scene.entities) {+ if (!store.isEntityVisible(entity.id)) continue;+ const transform = entity.components.find(c => c.type === 'LocalTransform');+ if (!transform) continue;++ const worldTransform = store.getWorldTransform(entity.id);+ const pos = worldTransform.position;+ const scale = worldTransform.scale;+ const bounds = getBounds(entity);+ const w = bounds.width * Math.abs(scale.x);+ const h = bounds.height * Math.abs(scale.y);+ const offsetX = (bounds.offsetX ?? 0) * scale.x;+ const offsetY = (bounds.offsetY ?? 0) * scale.y;++ const centerX = pos.x + offsetX;+ const centerY = pos.y + offsetY;+ const halfW = w / 2;+ const halfH = h / 2;++ if (centerX + halfW >= minX && centerX - halfW <= maxX &&+ centerY + halfH >= minY && centerY - halfH <= maxY) {+ result.push(entity.id as Entity);+ }+ }++ return result;+ }++ draw(ctx: CanvasRenderingContext2D, zoom: number): void {+ const x = Math.min(this.startX, this.endX);+ const y = Math.min(-this.startY, -this.endY);+ const w = Math.abs(this.endX - this.startX);+ const h = Math.abs(this.endY - this.startY);++ ctx.fillStyle = 'rgba(0, 170, 255, 0.1)';+ ctx.fillRect(x, y, w, h);++ ctx.strokeStyle = '#00aaff';+ ctx.lineWidth = 1 / zoom;+ ctx.setLineDash([]);+ ctx.strokeRect(x, y, w, h);+ }+}diff --git a/editor/src/panels/scene-view/SceneViewInput.ts b/editor/src/panels/scene-view/SceneViewInput.tsnew file mode 100644index 000000000..300dc9355--- /dev/null+++ b/editor/src/panels/scene-view/SceneViewInput.ts@@ -0,0 +1,438 @@+import type { Entity } from 'esengine';+import type { EditorStore } from '../../store/EditorStore';+import type { GizmoContext } from '../../gizmos';+import { GizmoManager } from '../../gizmos';+import { ColliderOverlay } from '../../gizmos/ColliderOverlay';+import { getSettingsValue } from '../../settings/SettingsRegistry';+import { getEditorInstance } from '../../context/EditorContext';+import type { CameraController } from './CameraController';+import type { GizmoToolbar } from './GizmoToolbar';+import type { MarqueeSelection, BoundsProvider } from './MarqueeSelection';++export interface InputDeps {+ store: EditorStore;+ canvas: HTMLCanvasElement;+ overlayCanvas: HTMLCanvasElement | null;+ camera: CameraController;+ toolbar: GizmoToolbar;+ marquee: MarqueeSelection;+ gizmoManager: GizmoManager;+ colliderOverlay: ColliderOverlay;+ getBounds: BoundsProvider;+ createGizmoContext: (ctx: CanvasRenderingContext2D) => GizmoContext;+ createOverlayContext: () => { ctx: CanvasRenderingContext2D; zoom: number; store: EditorStore } | null;+ requestRender: () => void;+}++export class SceneViewInput {+ private deps_: InputDeps;++ private skipNextClick_ = false;+ private mouseDownX_ = 0;+ private mouseDownY_ = 0;++ private boundOnDocumentMouseMove_: ((e: MouseEvent) => void) | null = null;+ private boundOnDocumentMouseUp_: ((e: MouseEvent) => void) | null = null;++ private boundOnMouseDown_: ((e: MouseEvent) => void) | null = null;+ private boundOnMouseMove_: ((e: MouseEvent) => void) | null = null;+ private boundOnMouseUp_: ((e: MouseEvent) => void) | null = null;+ private boundOnMouseLeave_: ((e: MouseEvent) => void) | null = null;+ private boundOnWheel_: ((e: WheelEvent) => void) | null = null;+ private boundOnCanvasClick_: ((e: MouseEvent) => void) | null = null;++ private keydownHandler_: ((e: KeyboardEvent) => void) | null = null;+ private keyupHandler_: ((e: KeyboardEvent) => void) | null = null;++ constructor(deps: InputDeps) {+ this.deps_ = deps;+ }++ setup(): void {+ const { canvas, camera } = this.deps_;++ const resetBtn = canvas.closest('.es-sceneview-panel')?.querySelector('[data-action="reset-view"]');+ resetBtn?.addEventListener('click', () => {+ camera.reset();+ this.deps_.toolbar.updateZoomDisplay(camera.zoom);+ this.deps_.requestRender();+ });++ this.setupKeyboard();+ this.setupMouse();+ }++ private setupKeyboard(): void {+ const { camera, toolbar, store } = this.deps_;++ this.keydownHandler_ = (e: KeyboardEvent) => {+ if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {+ return;+ }++ if (e.key === ' ' && !camera.spaceDown) {+ camera.spaceDown = true;+ if (!camera.isDragging) {+ this.deps_.canvas.style.cursor = 'grab';+ }+ e.preventDefault();+ return;+ }++ if (toolbar.handleKeyShortcut(e.key)) return;++ if (e.key === 'f' || e.key === 'F') {+ const entity = store.selectedEntity;+ if (entity !== null) {+ const worldTransform = store.getWorldTransform(entity as number);+ camera.focusOnEntity(worldTransform.position.x, worldTransform.position.y);+ toolbar.updateZoomDisplay(camera.zoom);+ }+ return;+ }++ if (e.key === 'Delete' || e.key === 'Backspace') {+ if (store.selectedEntities.size > 0) {+ store.deleteSelectedEntities();+ }+ return;+ }++ if ((e.key === 'd' || e.key === 'D') && (e.ctrlKey || e.metaKey)) {+ e.preventDefault();+ getEditorInstance()?.duplicateSelected();+ return;+ }++ if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {+ camera.nudgeSelection(e, store as any);+ return;+ }++ if (e.key === '+' || e.key === '=') {+ camera.zoomIn();+ toolbar.updateZoomDisplay(camera.zoom);+ return;+ }++ if (e.key === '-') {+ camera.zoomOut();+ toolbar.updateZoomDisplay(camera.zoom);+ return;+ }++ if (e.key === 'Control' || e.key === 'Meta') {+ toolbar.updateSnapIndicator(true);+ }+ };+ document.addEventListener('keydown', this.keydownHandler_);++ this.keyupHandler_ = (e: KeyboardEvent) => {+ if (e.key === ' ') {+ camera.spaceDown = false;+ if (!camera.isDragging) {+ this.deps_.canvas.style.cursor = 'default';+ }+ }+ if (e.key === 'Control' || e.key === 'Meta') {+ toolbar.updateSnapIndicator(false);+ }+ };+ document.addEventListener('keyup', this.keyupHandler_);+ }++ private setupMouse(): void {+ const { canvas } = this.deps_;++ this.boundOnMouseDown_ = this.onMouseDown.bind(this);+ this.boundOnMouseMove_ = this.onMouseMove.bind(this);+ this.boundOnMouseUp_ = this.onMouseUp.bind(this);+ this.boundOnMouseLeave_ = this.onMouseLeave.bind(this);+ this.boundOnWheel_ = (e: WheelEvent) => {+ this.deps_.camera.wheel(e);+ this.deps_.toolbar.updateZoomDisplay(this.deps_.camera.zoom);+ };+ this.boundOnCanvasClick_ = this.onCanvasClick.bind(this);++ canvas.addEventListener('mousedown', this.boundOnMouseDown_);+ canvas.addEventListener('mousemove', this.boundOnMouseMove_);+ canvas.addEventListener('mouseup', this.boundOnMouseUp_);+ canvas.addEventListener('mouseleave', this.boundOnMouseLeave_);+ canvas.addEventListener('wheel', this.boundOnWheel_);+ canvas.addEventListener('click', this.boundOnCanvasClick_);+ }++ private onMouseDown(e: MouseEvent): void {+ const { camera, store, gizmoManager, colliderOverlay, marquee } = this.deps_;++ if (camera.shouldStartDrag(e)) {+ camera.startDrag(e.clientX, e.clientY);+ this.startDocumentDrag();+ return;+ }++ if (e.button !== 0) return;++ this.mouseDownX_ = e.clientX;+ this.mouseDownY_ = e.clientY;++ const { worldX, worldY } = camera.screenToWorld(e.clientX, e.clientY);+ const hasSelection = store.selectedEntities.size > 0;++ if (gizmoManager.getActiveId() !== 'select' && hasSelection) {+ this.updateGizmoContext();+ if (gizmoManager.onMouseDown(worldX, worldY)) {+ this.startDocumentDrag();+ return;+ }+ }++ if (getSettingsValue<boolean>('scene.showColliders') && hasSelection) {+ const octx = this.deps_.createOverlayContext();+ if (octx && colliderOverlay.onDragStart(worldX, worldY, octx)) {+ this.startDocumentDrag();+ return;+ }+ }++ if (gizmoManager.getActiveId() === 'select') {+ const hits = this.findEntitiesAtPosition(worldX, worldY);+ if (hits.length === 0) {+ marquee.start(worldX, worldY);+ this.startDocumentDrag();+ return;+ }+ }+ }++ private onMouseMove(e: MouseEvent): void {+ const { camera, store, gizmoManager, colliderOverlay, marquee } = this.deps_;+ const { worldX, worldY } = camera.screenToWorld(e.clientX, e.clientY);++ if (camera.drag(e.clientX, e.clientY)) return;++ if (marquee.active) {+ marquee.update(worldX, worldY);+ this.deps_.requestRender();+ return;+ }++ if (gizmoManager.isDragging()) {+ this.updateGizmoContext();+ gizmoManager.onMouseMove(worldX, worldY, e);+ return;+ }++ if (colliderOverlay.isDragging()) {+ const octx = this.deps_.createOverlayContext();+ if (octx) {+ colliderOverlay.onDrag(worldX, worldY, octx);+ this.deps_.requestRender();+ }+ return;+ }++ const hasSelection = store.selectedEntities.size > 0;++ if (gizmoManager.getActiveId() !== 'select' && hasSelection) {+ this.updateGizmoContext();+ gizmoManager.onMouseMove(worldX, worldY, e);+ this.deps_.canvas.style.cursor = gizmoManager.getCursor();+ }++ if (getSettingsValue<boolean>('scene.showColliders') && hasSelection) {+ const octx = this.deps_.createOverlayContext();+ if (octx) {+ colliderOverlay.hitTest(worldX, worldY, octx);+ const colliderCursor = colliderOverlay.getCursor();+ if (colliderCursor) {+ this.deps_.canvas.style.cursor = colliderCursor;+ }+ }+ }+ }++ private onMouseUp(e: MouseEvent): void {+ const { camera, gizmoManager, colliderOverlay, marquee } = this.deps_;++ const dx = e.clientX - this.mouseDownX_;+ const dy = e.clientY - this.mouseDownY_;+ const didMove = dx * dx + dy * dy > 9;++ if (camera.isDragging) {+ camera.stopDrag();+ this.skipNextClick_ = true;+ }++ if (marquee.active) {+ const { worldX, worldY } = camera.screenToWorld(e.clientX, e.clientY);+ marquee.update(worldX, worldY);+ marquee.finish(this.deps_.store, this.deps_.getBounds, e.ctrlKey || e.metaKey);+ this.skipNextClick_ = true;+ this.deps_.requestRender();+ }++ if (gizmoManager.isDragging()) {+ const { worldX, worldY } = camera.screenToWorld(e.clientX, e.clientY);+ this.updateGizmoContext();+ gizmoManager.onMouseUp(worldX, worldY);+ this.skipNextClick_ = didMove;+ }++ if (colliderOverlay.isDragging()) {+ const octx = this.deps_.createOverlayContext();+ if (octx) {+ colliderOverlay.onDragEnd(octx);+ }+ this.skipNextClick_ = didMove;+ }+ }++ private onMouseLeave(_e: MouseEvent): void {+ const { camera, gizmoManager, colliderOverlay, marquee } = this.deps_;+ if (camera.isDragging || gizmoManager.isDragging() || colliderOverlay.isDragging() || marquee.active) {+ return;+ }+ gizmoManager.resetHover();+ this.deps_.requestRender();+ }++ private onCanvasClick(e: MouseEvent): void {+ if (this.skipNextClick_) {+ this.skipNextClick_ = false;+ return;+ }++ const { camera, store, gizmoManager } = this.deps_;++ if (camera.isDragging || gizmoManager.isDragging()) return;++ const { worldX, worldY } = camera.screenToWorld(e.clientX, e.clientY);+ const hasSelection = store.selectedEntities.size > 0;++ if (gizmoManager.getActiveId() !== 'select' && hasSelection) {+ this.updateGizmoContext();+ const result = gizmoManager.hitTest(worldX, worldY);+ if (result.hit) return;+ }++ const hits = this.findEntitiesAtPosition(worldX, worldY);+ if (hits.length === 0) {+ store.selectEntity(null);+ return;+ }++ const current = store.selectedEntity;+ const idx = current !== null ? hits.indexOf(current as Entity) : -1;+ const next = idx >= 0 ? hits[(idx + 1) % hits.length] : hits[0];+ store.selectEntity(next);+ }++ findEntitiesAtPosition(worldX: number, worldY: number): Entity[] {+ const { store, getBounds } = this.deps_;+ const scene = store.scene;+ const result: Entity[] = [];++ for (let i = scene.entities.length - 1; i >= 0; i--) {+ const entity = scene.entities[i];+ if (!store.isEntityVisible(entity.id)) continue;++ const transform = entity.components.find(c => c.type === 'LocalTransform');+ if (!transform) continue;++ const worldTransform = store.getWorldTransform(entity.id);+ const pos = worldTransform.position;+ const scale = worldTransform.scale;++ const bounds = getBounds(entity);+ const w = bounds.width * Math.abs(scale.x);+ const h = bounds.height * Math.abs(scale.y);+ const offsetX = (bounds.offsetX ?? 0) * scale.x;+ const offsetY = (bounds.offsetY ?? 0) * scale.y;++ const centerX = pos.x + offsetX;+ const centerY = pos.y + offsetY;+ const halfW = w / 2;+ const halfH = h / 2;++ if (+ worldX >= centerX - halfW &&+ worldX <= centerX + halfW &&+ worldY >= centerY - halfH &&+ worldY <= centerY + halfH+ ) {+ result.push(entity.id as Entity);+ }+ }++ return result;+ }++ private updateGizmoContext(): void {+ const ctx = (this.deps_.overlayCanvas ?? this.deps_.canvas).getContext('2d');+ if (ctx) {+ this.deps_.gizmoManager.setContext(this.deps_.createGizmoContext(ctx));+ }+ }++ private startDocumentDrag(): void {+ this.boundOnDocumentMouseMove_ = (e: MouseEvent) => this.onMouseMove(e);+ this.boundOnDocumentMouseUp_ = (e: MouseEvent) => {+ this.onMouseUp(e);+ this.stopDocumentDrag();+ };+ document.addEventListener('mousemove', this.boundOnDocumentMouseMove_);+ document.addEventListener('mouseup', this.boundOnDocumentMouseUp_);+ }++ private stopDocumentDrag(): void {+ if (this.boundOnDocumentMouseMove_) {+ document.removeEventListener('mousemove', this.boundOnDocumentMouseMove_);+ this.boundOnDocumentMouseMove_ = null;+ }+ if (this.boundOnDocumentMouseUp_) {+ document.removeEventListener('mouseup', this.boundOnDocumentMouseUp_);+ this.boundOnDocumentMouseUp_ = null;+ }+ }++ dispose(): void {+ const { canvas } = this.deps_;++ if (this.keydownHandler_) {+ document.removeEventListener('keydown', this.keydownHandler_);+ this.keydownHandler_ = null;+ }+ if (this.keyupHandler_) {+ document.removeEventListener('keyup', this.keyupHandler_);+ this.keyupHandler_ = null;+ }++ this.stopDocumentDrag();++ if (this.boundOnMouseDown_) {+ canvas.removeEventListener('mousedown', this.boundOnMouseDown_);+ this.boundOnMouseDown_ = null;+ }+ if (this.boundOnMouseMove_) {+ canvas.removeEventListener('mousemove', this.boundOnMouseMove_);+ this.boundOnMouseMove_ = null;+ }+ if (this.boundOnMouseUp_) {+ canvas.removeEventListener('mouseup', this.boundOnMouseUp_);+ this.boundOnMouseUp_ = null;+ }+ if (this.boundOnMouseLeave_) {+ canvas.removeEventListener('mouseleave', this.boundOnMouseLeave_);+ this.boundOnMouseLeave_ = null;+ }+ if (this.boundOnWheel_) {+ canvas.removeEventListener('wheel', this.boundOnWheel_);+ this.boundOnWheel_ = null;+ }+ if (this.boundOnCanvasClick_) {+ canvas.removeEventListener('click', this.boundOnCanvasClick_);+ this.boundOnCanvasClick_ = null;+ }+ }+}diff --git a/editor/src/panels/scene-view/SceneViewPanel.ts b/editor/src/panels/scene-view/SceneViewPanel.tsnew file mode 100644index 000000000..1625edf32--- /dev/null+++ b/editor/src/panels/scene-view/SceneViewPanel.ts@@ -0,0 +1,1145 @@+import type { Entity, App } from 'esengine';+import { Renderer } from 'esengine';+import type { SpineModuleController } from 'esengine/spine';+import type { EditorStore } from '../../store/EditorStore';+import type { EditorBridge } from '../../bridge/EditorBridge';+import { getPlatformAdapter } from '../../platform/PlatformAdapter';+import { isUUID, getAssetLibrary } from '../../asset/AssetDatabase';+import { icons } from '../../utils/icons';+import { EditorSceneRenderer } from '../../renderer/EditorSceneRenderer';+import { findCanvasWorldRect } from '../../math/Transform';+import { getEntityBounds } from '../../bounds';+import { GizmoManager } from '../../gizmos';+import type { GizmoContext } from '../../gizmos';+import { ColliderOverlay } from '../../gizmos/ColliderOverlay';+import { getSettingsValue } from '../../settings/SettingsRegistry';+import type { EntityData } from '../../types/SceneTypes';++import { CameraController } from './CameraController';+import { GizmoToolbar } from './GizmoToolbar';+import { MarqueeSelection } from './MarqueeSelection';+import { EntityDropHandler } from './EntityDropHandler';+import { SceneViewInput } from './SceneViewInput';++const CAMERA_COLORS = [+ '#ffaa00',+ '#00ccff',+ '#ff55aa',+ '#55ff55',+];++export interface SceneViewPanelOptions {+ projectPath?: string;+ app?: App;+}++export class SceneViewPanel {+ private container_: HTMLElement;+ private store_: EditorStore;+ private bridge_: EditorBridge | null = null;+ private canvas_: HTMLCanvasElement;+ private webglCanvas_: HTMLCanvasElement | null = null;+ private overlayCanvas_: HTMLCanvasElement | null = null;+ private unsubscribe_: (() => void) | null = null;+ private unsubscribeSceneSync_: (() => void) | null = null;+ private unsubscribeFocus_: (() => void) | null = null;+ private animationId_: number | null = null;+ private continuousRender_ = false;+ private isDirty_ = true;+ private resizeObserver_: ResizeObserver | null = null;+ private projectPath_: string | null = null;+ private app_: App | null = null;++ private sceneRenderer_: EditorSceneRenderer | null = null;+ private useWebGL_ = false;+ private webglInitialized_ = false;+ private webglInitPending_ = false;++ private gizmoManager_: GizmoManager;+ private colliderOverlay_: ColliderOverlay;++ private camera_: CameraController;+ private toolbar_: GizmoToolbar;+ private marquee_: MarqueeSelection;+ private dropHandler_: EntityDropHandler;+ private input_: SceneViewInput;++ private static readonly MAX_CACHE_SIZE = 100;+ private textureCache_: Map<string, HTMLImageElement | null> = new Map();+ private loadingTextures_: Set<string> = new Set();++ constructor(container: HTMLElement, store: EditorStore, options?: SceneViewPanelOptions) {+ this.container_ = container;+ this.store_ = store;+ this.projectPath_ = options?.projectPath ?? null;+ this.app_ = options?.app ?? null;+ this.gizmoManager_ = new GizmoManager();+ this.colliderOverlay_ = new ColliderOverlay();++ this.camera_ = new CameraController(null!, () => this.requestRender());+ this.toolbar_ = new GizmoToolbar(container, this.gizmoManager_, () => this.requestRender());+ this.marquee_ = new MarqueeSelection();+ this.dropHandler_ = new EntityDropHandler(store);++ this.container_.className = 'es-sceneview-panel';+ this.container_.innerHTML = `+ <div class="es-panel-header">+ <span class="es-panel-title">Scene</span>+ <div class="es-sceneview-tools">+ <div class="es-gizmo-toolbar">+ ${this.toolbar_.buildToolbarHTML()}+ </div>+ <div class="es-toolbar-divider"></div>+ <button class="es-btn es-btn-icon" data-action="reset-view" title="Reset View">${icons.refresh(14)}</button>+ <span class="es-zoom-display">100%</span>+ <span class="es-snap-indicator" style="display: none;">SNAP</span>+ <div class="es-toolbar-divider"></div>+ ${this.toolbar_.buildSettingsHTML()}+ </div>+ </div>+ <div class="es-sceneview-viewport">+ <canvas class="es-sceneview-webgl"></canvas>+ <canvas class="es-sceneview-overlay"></canvas>+ </div>+ `;++ this.webglCanvas_ = this.container_.querySelector('.es-sceneview-webgl')!;+ this.overlayCanvas_ = this.container_.querySelector('.es-sceneview-overlay')!;+ this.canvas_ = this.overlayCanvas_;++ this.camera_.setCanvas(this.canvas_);++ this.input_ = new SceneViewInput({+ store,+ canvas: this.canvas_,+ overlayCanvas: this.overlayCanvas_,+ camera: this.camera_,+ toolbar: this.toolbar_,+ marquee: this.marquee_,+ gizmoManager: this.gizmoManager_,+ colliderOverlay: this.colliderOverlay_,+ getBounds: (entityData) => this.getEntityBoundsWithSpine(entityData),+ createGizmoContext: (ctx) => this.createGizmoContext(ctx),+ createOverlayContext: () => this.createOverlayContext(),+ requestRender: () => this.requestRender(),+ });++ this.toolbar_.setupEvents();+ this.input_.setup();+ this.dropHandler_.setupListeners(+ this.canvas_,+ (cx, cy) => this.camera_.screenToWorld(cx, cy),+ );++ this.unsubscribe_ = store.subscribe(() => this.onSceneChanged());+ this.unsubscribeSceneSync_ = store.subscribeToSceneSync(() => this.onSceneSyncNeeded());+ this.unsubscribeFocus_ = store.onFocusEntity((entityId) => {+ const worldTransform = this.store_.getWorldTransform(entityId);+ this.camera_.focusOnEntity(worldTransform.position.x, worldTransform.position.y);+ this.toolbar_.updateZoomDisplay(this.camera_.zoom);+ });++ const viewport = this.container_.querySelector('.es-sceneview-viewport');+ if (viewport) {+ this.resizeObserver_ = new ResizeObserver(() => this.resize());+ this.resizeObserver_.observe(viewport);+ }++ this.resize();++ if (this.app_?.wasmModule) {+ this.initWebGLRenderer();+ } else {+ this.startContinuousRender();+ }+ }++ private getEntityBoundsWithSpine(entityData: EntityData): { width: number; height: number; offsetX?: number; offsetY?: number } {+ const hasSpine = entityData.components.some(c => c.type === 'SpineAnimation');+ if (hasSpine && this.sceneRenderer_) {+ const spineBounds = this.sceneRenderer_.getSpineBounds(entityData.id);+ if (spineBounds) {+ return {+ width: Math.abs(spineBounds.width),+ height: Math.abs(spineBounds.height),+ offsetX: spineBounds.x + spineBounds.width / 2,+ offsetY: spineBounds.y + spineBounds.height / 2+ };+ }+ }++ const hasBitmapText = entityData.components.some(c => c.type === 'BitmapText');+ if (hasBitmapText && this.sceneRenderer_) {+ const textBounds = this.sceneRenderer_.getBitmapTextBounds(entityData.id);+ if (textBounds) {+ return {+ width: textBounds.width,+ height: textBounds.height,+ offsetX: textBounds.offsetX,+ offsetY: textBounds.offsetY,+ };+ }+ }++ return getEntityBounds(entityData.components);+ }++ dispose(): void {+ this.continuousRender_ = false;+ if (this.animationId_ !== null) {+ cancelAnimationFrame(this.animationId_);+ this.animationId_ = null;+ }+ if (this.unsubscribe_) {+ this.unsubscribe_();+ this.unsubscribe_ = null;+ }+ if (this.unsubscribeSceneSync_) {+ this.unsubscribeSceneSync_();+ this.unsubscribeSceneSync_ = null;+ }+ if (this.unsubscribeFocus_) {+ this.unsubscribeFocus_();+ this.unsubscribeFocus_ = null;+ }+ if (this.resizeObserver_) {+ this.resizeObserver_.disconnect();+ this.resizeObserver_ = null;+ }+ if (this.sceneRenderer_) {+ this.sceneRenderer_.dispose();+ this.sceneRenderer_ = null;+ }+ this.input_.dispose();+ this.toolbar_.dispose();+ }++ setBridge(bridge: EditorBridge): void {+ this.bridge_ = bridge;+ this.requestRender();+ }++ setProjectPath(path: string): void {+ this.projectPath_ = path;+ this.textureCache_.clear();+ this.loadingTextures_.clear();++ if (this.sceneRenderer_) {+ const projectDir = path.replace(/\\/g, '/').replace(/\/[^/]+$/, '');+ this.sceneRenderer_.setProjectDir(projectDir);+ this.syncSceneToRenderer();+ }++ this.requestRender();+ }++ setApp(app: App): void {+ this.app_ = app;+ if (app.wasmModule && !this.webglInitialized_ && !this.webglInitPending_) {+ this.initWebGLRenderer();+ }+ }++ setSpineController(controller: SpineModuleController | null): void {+ this.sceneRenderer_?.setSpineController(controller);+ }++ getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {+ return this.sceneRenderer_?.getSpineSkeletonInfo(entityId) ?? null;+ }++ onSpineInstanceReady(listener: (entityId: number) => void): () => void {+ return this.sceneRenderer_?.onSpineInstanceReady(listener) ?? (() => {});+ }++ get canvas(): HTMLCanvasElement {+ return this.canvas_;+ }++ get assetServer() {+ return this.sceneRenderer_?.assetServer ?? null;+ }++ resize(): void {+ const viewport = this.container_.querySelector('.es-sceneview-viewport') as HTMLElement;+ if (!viewport) return;++ const rect = viewport.getBoundingClientRect();+ const dpr = window.devicePixelRatio || 1;++ if (this.webglCanvas_) {+ this.webglCanvas_.width = rect.width * dpr;+ this.webglCanvas_.height = rect.height * dpr;+ this.webglCanvas_.style.width = `${rect.width}px`;+ this.webglCanvas_.style.height = `${rect.height}px`;+ }++ if (this.overlayCanvas_) {+ this.overlayCanvas_.width = rect.width * dpr;+ this.overlayCanvas_.height = rect.height * dpr;+ this.overlayCanvas_.style.width = `${rect.width}px`;+ this.overlayCanvas_.style.height = `${rect.height}px`;+ }++ this.canvas_.width = rect.width * dpr;+ this.canvas_.height = rect.height * dpr;+ this.canvas_.style.width = `${rect.width}px`;+ this.canvas_.style.height = `${rect.height}px`;++ this.requestRender();+ }++ startContinuousRender(): void {+ if (!this.continuousRender_) {+ this.continuousRender_ = true;+ this.requestRender();+ }+ }++ stopContinuousRender(): void {+ this.continuousRender_ = false;+ }++ // =========================================================================+ // WebGL / Scene Renderer+ // =========================================================================++ private async initWebGLRenderer(): Promise<void> {+ if (this.webglInitPending_ || this.webglInitialized_) return;+ if (!this.app_?.wasmModule || !this.webglCanvas_) return;++ this.webglInitPending_ = true;++ const canvasId = `es-sceneview-webgl-${Date.now()}`;+ this.webglCanvas_.id = canvasId;++ this.sceneRenderer_ = new EditorSceneRenderer();+ this.sceneRenderer_.setStore(this.store_);+ const success = await this.sceneRenderer_.init(this.app_.wasmModule, `#${canvasId}`);++ if (success) {+ this.webglInitialized_ = true;+ this.useWebGL_ = true;++ if (this.projectPath_) {+ const projectDir = this.projectPath_.replace(/\\/g, '/').replace(/\/[^/]+$/, '');+ this.sceneRenderer_.setProjectDir(projectDir);+ }++ await this.syncSceneToRenderer();+ this.startContinuousRender();+ } else {+ console.warn('WebGL init failed, falling back to Canvas 2D');+ this.sceneRenderer_ = null;+ this.startContinuousRender();+ }++ this.webglInitPending_ = false;+ }++ private async syncSceneToRenderer(): Promise<void> {+ if (!this.sceneRenderer_) return;+ await this.sceneRenderer_.syncScene(this.store_.scene);+ }++ private async onSceneSyncNeeded(): Promise<void> {+ try {+ if (this.sceneRenderer_ && this.useWebGL_) {+ await this.syncSceneToRenderer();+ }+ } catch (e) {+ console.warn('[SceneViewPanel] Scene sync error:', e);+ }+ }++ private onSceneChanged(): void {+ this.requestRender();+ }++ // =========================================================================+ // Texture Cache+ // =========================================================================++ private loadTexture(texturePath: string): HTMLImageElement | null {+ if (!this.projectPath_ || !texturePath) return null;++ const resolved = isUUID(texturePath)+ ? (getAssetLibrary().getPath(texturePath) ?? texturePath)+ : texturePath;++ if (this.textureCache_.has(resolved)) {+ return this.textureCache_.get(resolved) ?? null;+ }++ if (this.loadingTextures_.has(resolved)) {+ return null;+ }++ this.loadingTextures_.add(resolved);++ const projectDir = this.projectPath_.replace(/\\/g, '/').replace(/\/[^/]+$/, '');+ const fullPath = `${projectDir}/${resolved}`;+ const img = new Image();++ img.onload = () => {+ this.loadingTextures_.delete(resolved);+ this.evictCache(this.textureCache_);+ this.textureCache_.set(resolved, img);+ this.requestRender();+ };++ img.onerror = () => {+ this.loadingTextures_.delete(resolved);+ this.evictCache(this.textureCache_);+ this.textureCache_.set(resolved, null);+ console.warn(`Failed to load texture: ${fullPath}`);+ };++ img.src = getPlatformAdapter().convertFilePathToUrl(fullPath);++ return null;+ }++ private evictCache<T>(cache: Map<string, T>): void {+ if (cache.size >= SceneViewPanel.MAX_CACHE_SIZE) {+ const firstKey = cache.keys().next().value;+ if (firstKey !== undefined) {+ cache.delete(firstKey);+ }+ }+ }++ // =========================================================================+ // Gizmo Context+ // =========================================================================++ private createGizmoContext(ctx: CanvasRenderingContext2D): GizmoContext {+ return {+ store: this.store_,+ ctx,+ zoom: this.camera_.zoom,+ screenToWorld: (clientX, clientY) => this.camera_.screenToWorld(clientX, clientY),+ getWorldTransform: (entityId) => this.store_.getWorldTransform(entityId),+ getEntityBounds: (entityData) => this.getEntityBoundsWithSpine(entityData),+ requestRender: () => this.requestRender(),+ };+ }++ private createOverlayContext(): import('../../gizmos/ColliderOverlay').OverlayContext | null {+ const ctx = (this.overlayCanvas_ ?? this.canvas_).getContext('2d');+ if (!ctx) return null;+ return { ctx, zoom: this.camera_.zoom, store: this.store_ };+ }++ // =========================================================================+ // Render Loop+ // =========================================================================++ private requestRender(): void {+ this.isDirty_ = true;+ if (this.animationId_ !== null) return;++ this.animationId_ = requestAnimationFrame(() => {+ this.animationId_ = null;+ if (this.isDirty_) {+ this.isDirty_ = false;+ try {+ this.render();+ } catch (e) {+ console.warn('[SceneViewPanel] Render error, skipping frame:', e);+ }+ }+ if (this.continuousRender_) {+ this.scheduleNextFrame();+ }+ });+ }++ private scheduleNextFrame(): void {+ if (this.animationId_ !== null) return;+ this.animationId_ = requestAnimationFrame(() => {+ this.animationId_ = null;+ if (this.isDirty_) {+ this.isDirty_ = false;+ try {+ this.render();+ } catch (e) {+ console.warn('[SceneViewPanel] Render error, skipping frame:', e);+ }+ }+ if (this.continuousRender_) {+ this.scheduleNextFrame();+ }+ });+ }++ private render(): void {+ if (this.useWebGL_ && this.sceneRenderer_ && this.webglCanvas_) {+ const w = this.webglCanvas_.width;+ const h = this.webglCanvas_.height;+ if (w === 0 || h === 0) return;++ this.sceneRenderer_.camera.panX = this.camera_.panX;+ this.sceneRenderer_.camera.panY = this.camera_.panY;+ this.sceneRenderer_.camera.zoom = this.camera_.zoom;++ this.sceneRenderer_.render(w, h);+ this.renderOverlay();+ } else if (this.bridge_) {+ const w = this.canvas_.width;+ const h = this.canvas_.height;+ if (w === 0 || h === 0) return;++ this.bridge_.render(w, h);+ } else {+ this.renderPreview();+ }+ }++ // =========================================================================+ // Overlay Rendering+ // =========================================================================++ private renderOverlay(): void {+ if (!this.overlayCanvas_) return;++ const ctx = this.overlayCanvas_.getContext('2d');+ if (!ctx) return;++ const w = this.overlayCanvas_.width;+ const h = this.overlayCanvas_.height;++ ctx.clearRect(0, 0, w, h);++ ctx.save();+ ctx.translate(w / 2 + this.camera_.panX * this.camera_.zoom, h / 2 + this.camera_.panY * this.camera_.zoom);+ ctx.scale(this.camera_.zoom, this.camera_.zoom);++ this.drawGrid(ctx, w, h);++ this.drawCameraFrustums(ctx);+ this.drawScreenSpaceBounds(ctx);++ if (getSettingsValue<boolean>('scene.showColliders')) {+ this.colliderOverlay_.drawAll({+ ctx,+ zoom: this.camera_.zoom,+ store: this.store_,+ });+ }++ const hasSelection = this.store_.selectedEntities.size > 0;++ if (hasSelection) {+ if (getSettingsValue<boolean>('scene.showSelectionBox')) {+ this.drawSelectionBox(ctx);+ }++ if (this.gizmoManager_.getActiveId() !== 'select' && getSettingsValue<boolean>('scene.showGizmos')) {+ this.gizmoManager_.setContext(this.createGizmoContext(ctx));+ this.gizmoManager_.draw();+ }+ }++ if (this.marquee_.active) {+ this.marquee_.draw(ctx, this.camera_.zoom);+ }++ ctx.restore();++ this.drawStats(ctx, w, h);+ this.drawViewportPreview(ctx, w, h);++ if (!this.store_.scene.entities.some(+ e => e.components.some(c => c.type === 'Camera'))) {+ ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';+ ctx.font = '14px system-ui, sans-serif';+ ctx.textAlign = 'center';+ ctx.fillText('No Camera in Scene', w / 2, h / 2);+ }+ }++ // =========================================================================+ // Canvas 2D Preview (fallback)+ // =========================================================================++ private renderPreview(): void {+ const ctx = this.canvas_.getContext('2d');+ if (!ctx) return;++ const w = this.canvas_.width;+ const h = this.canvas_.height;++ ctx.fillStyle = '#1a1a1a';+ ctx.fillRect(0, 0, w, h);++ ctx.save();+ ctx.translate(w / 2 + this.camera_.panX * this.camera_.zoom, h / 2 + this.camera_.panY * this.camera_.zoom);+ ctx.scale(this.camera_.zoom, this.camera_.zoom);++ this.drawGrid(ctx, w, h);++ const scene = this.store_.scene;+ const selectedEntity = this.store_.selectedEntity;++ for (const entity of scene.entities) {+ if (!this.store_.isEntityVisible(entity.id)) continue;+ this.drawEntity(ctx, entity, entity.id === selectedEntity);+ }++ this.drawCameraFrustums(ctx);+ this.drawScreenSpaceBounds(ctx);++ if (getSettingsValue<boolean>('scene.showColliders')) {+ this.colliderOverlay_.drawAll({+ ctx,+ zoom: this.camera_.zoom,+ store: this.store_,+ });+ }++ if (selectedEntity !== null && this.store_.isEntityVisible(selectedEntity as number)) {+ if (this.gizmoManager_.getActiveId() !== 'select' && getSettingsValue<boolean>('scene.showGizmos')) {+ this.gizmoManager_.setContext(this.createGizmoContext(ctx));+ this.gizmoManager_.draw();+ }+ }++ if (this.marquee_.active) {+ this.marquee_.draw(ctx, this.camera_.zoom);+ }++ ctx.restore();+ }++ // =========================================================================+ // Drawing Helpers+ // =========================================================================++ private drawSelectionBox(ctx: CanvasRenderingContext2D): void {+ const selectedEntities = this.store_.getSelectedEntitiesData();++ for (const entityData of selectedEntities) {+ if (!this.store_.isEntityVisible(entityData.id)) continue;++ const transform = entityData.components.find(c => c.type === 'LocalTransform');+ if (!transform) continue;++ const worldTransform = this.store_.getWorldTransform(entityData.id);+ const pos = worldTransform.position;+ const scale = worldTransform.scale;++ const bounds = this.getEntityBoundsWithSpine(entityData);+ const w = bounds.width * Math.abs(scale.x);+ const h = bounds.height * Math.abs(scale.y);+ const offsetX = (bounds.offsetX ?? 0) * scale.x;+ const offsetY = (bounds.offsetY ?? 0) * scale.y;++ ctx.save();+ ctx.translate(pos.x + offsetX, -pos.y - offsetY);++ ctx.strokeStyle = '#00aaff';+ ctx.lineWidth = 2 / this.camera_.zoom;+ ctx.setLineDash([]);+ ctx.strokeRect(-w / 2, -h / 2, w, h);++ if (selectedEntities.length === 1) {+ ctx.fillStyle = '#00aaff';+ const handleSize = 6 / this.camera_.zoom;+ const corners = [+ [-w / 2, -h / 2],+ [w / 2, -h / 2],+ [-w / 2, h / 2],+ [w / 2, h / 2],+ ];+ for (const [cx, cy] of corners) {+ ctx.fillRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);+ }+ }++ ctx.restore();+ }+ }++ private drawCameraFrustums(ctx: CanvasRenderingContext2D): void {+ const selectedEntity = this.store_.selectedEntity;++ let aspectRatio = 750 / 1650;+ const canvasEntity = this.store_.scene.entities.find(+ e => e.components.some(c => c.type === 'Canvas')+ );+ if (canvasEntity) {+ const canvas = canvasEntity.components.find(c => c.type === 'Canvas');+ const resolution = canvas?.data.designResolution as { x: number; y: number };+ if (resolution && resolution.y > 0) {+ aspectRatio = resolution.x / resolution.y;+ }+ }++ let cameraIndex = 0;+ for (const entity of this.store_.scene.entities) {+ const camera = entity.components.find(c => c.type === 'Camera');+ if (!camera) continue;++ const transform = entity.components.find(c => c.type === 'LocalTransform');+ if (!transform) { cameraIndex++; continue; }++ const isSelected = entity.id === selectedEntity;+ const showFrustum = (camera.data.showFrustum as boolean) ?? true;++ if (!showFrustum && !isSelected) { cameraIndex++; continue; }++ const color = CAMERA_COLORS[cameraIndex % CAMERA_COLORS.length];+ const worldTransform = this.store_.getWorldTransform(entity.id);+ const pos = worldTransform.position;++ const orthoSize = (camera.data.orthoSize as number) ?? 400;+ const projectionType = (camera.data.projectionType as number) ?? 0;+ const priority = (camera.data.priority as number) ?? 0;+ const vpX = (camera.data.viewportX as number) ?? 0;+ const vpY = (camera.data.viewportY as number) ?? 0;+ const vpW = (camera.data.viewportW as number) ?? 1;+ const vpH = (camera.data.viewportH as number) ?? 1;++ ctx.save();+ ctx.translate(pos.x, -pos.y);++ if (projectionType === 1) {+ const halfHeight = orthoSize;+ const halfWidth = halfHeight * aspectRatio;++ ctx.strokeStyle = color;+ ctx.lineWidth = 2 / this.camera_.zoom;++ if (isSelected) {+ ctx.globalAlpha = 1;+ ctx.setLineDash([]);+ } else {+ ctx.globalAlpha = 0.5;+ ctx.setLineDash([8 / this.camera_.zoom, 4 / this.camera_.zoom]);+ }++ ctx.strokeRect(-halfWidth, -halfHeight, halfWidth * 2, halfHeight * 2);++ const [cr, cg, cb] = this.hexToRgb(color);+ ctx.fillStyle = isSelected+ ? `rgba(${cr}, ${cg}, ${cb}, 0.1)`+ : `rgba(${cr}, ${cg}, ${cb}, 0.05)`;+ ctx.fillRect(-halfWidth, -halfHeight, halfWidth * 2, halfHeight * 2);++ ctx.setLineDash([]);+ ctx.globalAlpha = isSelected ? 1 : 0.5;++ this.drawCameraIcon(ctx, color);++ const fontSize = 12 / this.camera_.zoom;+ ctx.font = `bold ${fontSize}px system-ui, sans-serif`;+ ctx.textBaseline = 'bottom';++ ctx.textAlign = 'left';+ const nameText = entity.name;+ const nameMetrics = ctx.measureText(nameText);+ const labelPad = 2 / this.camera_.zoom;+ const labelH = fontSize + labelPad * 2;+ ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';+ ctx.fillRect(+ -halfWidth,+ -halfHeight - labelH - labelPad,+ nameMetrics.width + labelPad * 2,+ labelH+ );+ ctx.fillStyle = color;+ ctx.fillText(nameText, -halfWidth + labelPad, -halfHeight - labelPad * 2);++ ctx.textAlign = 'right';+ const prioText = `P${priority}`;+ const prioMetrics = ctx.measureText(prioText);+ ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';+ ctx.fillRect(+ halfWidth - prioMetrics.width - labelPad * 2,+ -halfHeight - labelH - labelPad,+ prioMetrics.width + labelPad * 2,+ labelH+ );+ ctx.fillStyle = color;+ ctx.fillText(prioText, halfWidth - labelPad, -halfHeight - labelPad * 2);++ const isFullscreen = vpX === 0 && vpY === 0 && vpW === 1 && vpH === 1;+ if (!isFullscreen) {+ ctx.textAlign = 'left';+ ctx.textBaseline = 'top';+ ctx.font = `${fontSize * 0.9}px system-ui, sans-serif`;+ const pctW = Math.round(vpW * 100);+ const pctH = Math.round(vpH * 100);+ const vpText = `viewport: ${vpX}, ${vpY} ${pctW}%\u00d7${pctH}%`;+ const vpMetrics = ctx.measureText(vpText);+ ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';+ ctx.fillRect(+ -halfWidth,+ halfHeight + labelPad,+ vpMetrics.width + labelPad * 2,+ labelH+ );+ ctx.fillStyle = color;+ ctx.fillText(vpText, -halfWidth + labelPad, halfHeight + labelPad * 2);+ }+ }++ ctx.globalAlpha = 1;+ ctx.restore();+ cameraIndex++;+ }+ }++ private drawScreenSpaceBounds(ctx: CanvasRenderingContext2D): void {+ const hasScreenSpace = this.store_.scene.entities.some(+ e => e.components.some(c => c.type === 'ScreenSpace')+ );+ if (!hasScreenSpace) return;++ const canvasRect = findCanvasWorldRect(this.store_.scene.entities);+ if (!canvasRect) return;++ const x = canvasRect.left;+ const y = -(canvasRect.top);+ const w = canvasRect.right - canvasRect.left;+ const h = canvasRect.top - canvasRect.bottom;++ ctx.save();++ ctx.strokeStyle = '#ffb400';+ ctx.lineWidth = 2 / this.camera_.zoom;+ ctx.setLineDash([6 / this.camera_.zoom, 4 / this.camera_.zoom]);+ ctx.strokeRect(x, y, w, h);++ ctx.fillStyle = 'rgba(255, 180, 0, 0.04)';+ ctx.fillRect(x, y, w, h);++ ctx.setLineDash([]);+ const fontSize = 11 / this.camera_.zoom;+ ctx.font = `bold ${fontSize}px system-ui, sans-serif`;+ ctx.textAlign = 'left';+ ctx.textBaseline = 'bottom';+ const label = 'ScreenSpace';+ const pad = 2 / this.camera_.zoom;+ const metrics = ctx.measureText(label);+ ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';+ ctx.fillRect(x, y - fontSize - pad * 2, metrics.width + pad * 2, fontSize + pad * 2);+ ctx.fillStyle = '#ffb400';+ ctx.fillText(label, x + pad, y - pad);++ ctx.restore();+ }++ private drawCameraIcon(ctx: CanvasRenderingContext2D, color: string): void {+ const s = 1 / this.camera_.zoom;+ const bodyW = 16 * s;+ const bodyH = 12 * s;+ const lensW = 6 * s;+ const lensH1 = 8 * s;+ const lensH2 = 12 * s;++ ctx.strokeStyle = color;+ ctx.fillStyle = color;+ ctx.lineWidth = 1.5 * s;++ ctx.beginPath();+ ctx.rect(-bodyW / 2, -bodyH / 2, bodyW, bodyH);+ ctx.stroke();++ ctx.beginPath();+ ctx.moveTo(bodyW / 2, -lensH1 / 2);+ ctx.lineTo(bodyW / 2 + lensW, -lensH2 / 2);+ ctx.lineTo(bodyW / 2 + lensW, lensH2 / 2);+ ctx.lineTo(bodyW / 2, lensH1 / 2);+ ctx.closePath();+ ctx.stroke();++ const dotR = 2 * s;+ ctx.beginPath();+ ctx.arc(-bodyW / 4, -bodyH / 2 - dotR - 1 * s, dotR, 0, Math.PI * 2);+ ctx.fill();+ }++ private hexToRgb(hex: string): [number, number, number] {+ const num = parseInt(hex.replace('#', ''), 16);+ return [(num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff];+ }++ private drawStats(ctx: CanvasRenderingContext2D, canvasWidth: number, canvasHeight: number): void {+ if (!getSettingsValue<boolean>('scene.showStats') || !this.useWebGL_) return;++ const stats = Renderer.getStats();+ const spineCount = this.sceneRenderer_?.spineInstanceCount ?? stats.spine;++ const lines = [+ `DC: ${stats.drawCalls} Tri: ${stats.triangles}`,+ `Sprite: ${stats.sprites} Spine: ${spineCount}`,+ `Text: ${stats.text} Mesh: ${stats.meshes}`,+ `Culled: ${stats.culled}`,+ ];++ const fontSize = 12;+ const lineHeight = 18;+ const padding = 8;+ const panelW = 180;+ const panelH = lines.length * lineHeight + padding * 2;+ const x0 = 12;+ const y0 = canvasHeight - panelH - 12;++ ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';+ ctx.fillRect(x0, y0, panelW, panelH);++ ctx.fillStyle = '#ffffff';+ ctx.font = `${fontSize}px monospace`;+ ctx.textAlign = 'left';+ ctx.textBaseline = 'top';++ for (let i = 0; i < lines.length; i++) {+ ctx.fillText(lines[i], x0 + padding, y0 + padding + i * lineHeight);+ }+ }++ private drawViewportPreview(ctx: CanvasRenderingContext2D, canvasWidth: number, canvasHeight: number): void {+ const cameraEntities: Array<{ name: string; color: string; vpX: number; vpY: number; vpW: number; vpH: number }> = [];++ let idx = 0;+ for (const entity of this.store_.scene.entities) {+ const camera = entity.components.find(c => c.type === 'Camera');+ if (!camera) continue;+ cameraEntities.push({+ name: entity.name,+ color: CAMERA_COLORS[idx % CAMERA_COLORS.length],+ vpX: (camera.data.viewportX as number) ?? 0,+ vpY: (camera.data.viewportY as number) ?? 0,+ vpW: (camera.data.viewportW as number) ?? 1,+ vpH: (camera.data.viewportH as number) ?? 1,+ });+ idx++;+ }++ if (cameraEntities.length < 2) return;++ const previewW = 160;+ const previewH = 90;+ const padding = 12;+ const x0 = canvasWidth - previewW - padding;+ const y0 = canvasHeight - previewH - padding;++ ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';+ ctx.fillRect(x0 - 1, y0 - 1, previewW + 2, previewH + 2);++ ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';+ ctx.lineWidth = 1;+ ctx.setLineDash([]);+ ctx.strokeRect(x0, y0, previewW, previewH);++ for (const cam of cameraEntities) {+ const rx = x0 + cam.vpX * previewW;+ const ry = y0 + cam.vpY * previewH;+ const rw = cam.vpW * previewW;+ const rh = cam.vpH * previewH;++ const [cr, cg, cb] = this.hexToRgb(cam.color);+ ctx.fillStyle = `rgba(${cr}, ${cg}, ${cb}, 0.25)`;+ ctx.fillRect(rx, ry, rw, rh);++ ctx.strokeStyle = cam.color;+ ctx.lineWidth = 1;+ ctx.strokeRect(rx, ry, rw, rh);++ ctx.fillStyle = cam.color;+ ctx.font = '9px system-ui, sans-serif';+ ctx.textAlign = 'left';+ ctx.textBaseline = 'top';+ ctx.fillText(cam.name, rx + 3, ry + 2, rw - 6);+ }+ }++ private drawGrid(ctx: CanvasRenderingContext2D, w: number, h: number): void {+ if (!getSettingsValue<boolean>('scene.showGrid')) return;++ const gridSize = getSettingsValue<number>('scene.gridSize') ?? 50;+ const baseOpacity = getSettingsValue<number>('scene.gridOpacity');+ const gridColor = getSettingsValue<string>('scene.gridColor');+ const halfW = w / 2 / this.camera_.zoom;+ const halfH = h / 2 / this.camera_.zoom;++ const screenGridSize = gridSize * this.camera_.zoom;++ if (screenGridSize > 100) {+ const subDiv = screenGridSize > 250 ? 10 : 5;+ const subSize = gridSize / subDiv;+ this.drawGridLines(ctx, subSize, halfW, halfH, gridColor, baseOpacity * 0.3);+ }++ this.drawGridLines(ctx, gridSize, halfW, halfH, gridColor, baseOpacity);++ if (screenGridSize < 15) {+ const majorSize = gridSize * (screenGridSize < 5 ? 10 : 5);+ this.drawGridLines(ctx, majorSize, halfW, halfH, gridColor, baseOpacity);+ }++ ctx.globalAlpha = baseOpacity;+ ctx.strokeStyle = this.lightenColor(gridColor, 30);+ ctx.lineWidth = 2 / this.camera_.zoom;+ const startX = Math.floor((-halfW - this.camera_.panX) / gridSize) * gridSize;+ const endX = Math.ceil((halfW - this.camera_.panX) / gridSize) * gridSize;+ const startY = Math.floor((-halfH - this.camera_.panY) / gridSize) * gridSize;+ const endY = Math.ceil((halfH - this.camera_.panY) / gridSize) * gridSize;+ ctx.beginPath();+ ctx.moveTo(startX, 0);+ ctx.lineTo(endX, 0);+ ctx.stroke();+ ctx.beginPath();+ ctx.moveTo(0, startY);+ ctx.lineTo(0, endY);+ ctx.stroke();++ ctx.globalAlpha = 1;+ }++ private drawGridLines(+ ctx: CanvasRenderingContext2D,+ step: number,+ halfW: number,+ halfH: number,+ color: string,+ opacity: number,+ ): void {+ const startX = Math.floor((-halfW - this.camera_.panX) / step) * step;+ const endX = Math.ceil((halfW - this.camera_.panX) / step) * step;+ const startY = Math.floor((-halfH - this.camera_.panY) / step) * step;+ const endY = Math.ceil((halfH - this.camera_.panY) / step) * step;++ ctx.globalAlpha = opacity;+ ctx.strokeStyle = color;+ ctx.lineWidth = 1 / this.camera_.zoom;++ for (let x = startX; x <= endX; x += step) {+ if (x === 0) continue;+ ctx.beginPath();+ ctx.moveTo(x, startY);+ ctx.lineTo(x, endY);+ ctx.stroke();+ }++ for (let y = startY; y <= endY; y += step) {+ if (y === 0) continue;+ ctx.beginPath();+ ctx.moveTo(startX, y);+ ctx.lineTo(endX, y);+ ctx.stroke();+ }+ }++ private lightenColor(hex: string, percent: number): string {+ const num = parseInt(hex.replace('#', ''), 16);+ const r = Math.min(255, ((num >> 16) & 0xff) + Math.round(255 * percent / 100));+ const g = Math.min(255, ((num >> 8) & 0xff) + Math.round(255 * percent / 100));+ const b = Math.min(255, (num & 0xff) + Math.round(255 * percent / 100));+ return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, '0')}`;+ }++ private drawEntity(+ ctx: CanvasRenderingContext2D,+ entity: EntityData,+ isSelected: boolean,+ ): void {+ const transform = entity.components.find(c => c.type === 'LocalTransform');+ const sprite = entity.components.find(c => c.type === 'Sprite');++ if (!transform) return;++ const worldTransform = this.store_.getWorldTransform(entity.id);+ const pos = worldTransform.position;+ const scale = worldTransform.scale;++ let w = 50;+ let h = 50;+ let color: { r: number; g: number; b: number; a: number } | null = null;+ const hasSprite = !!sprite;+ let textureImg: HTMLImageElement | null = null;+ let flipX = false;+ let flipY = false;++ if (sprite) {+ const size = sprite.data.size as { x: number; y: number };+ const col = sprite.data.color as { r: number; g: number; b: number; a: number };+ const texturePath = sprite.data.texture;++ if (size) {+ w = size.x * Math.abs(scale.x);+ h = size.y * Math.abs(scale.y);+ }+ if (col) {+ color = col;+ }++ flipX = sprite.data.flipX === true;+ flipY = sprite.data.flipY === true;++ if (typeof texturePath === 'string' && texturePath) {+ textureImg = this.loadTexture(texturePath);+ }+ }++ ctx.save();+ ctx.translate(pos.x, -pos.y);++ if (flipX || flipY) {+ ctx.scale(flipX ? -1 : 1, flipY ? -1 : 1);+ }++ if (hasSprite) {+ if (textureImg) {+ ctx.globalAlpha = color?.a ?? 1;+ ctx.drawImage(textureImg, -w / 2, -h / 2, w, h);++ if (color && (color.r !== 1 || color.g !== 1 || color.b !== 1)) {+ ctx.globalCompositeOperation = 'multiply';+ const r = Math.round(color.r * 255);+ const g = Math.round(color.g * 255);+ const b = Math.round(color.b * 255);+ ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;+ ctx.fillRect(-w / 2, -h / 2, w, h);+ ctx.globalCompositeOperation = 'source-over';+ }+ ctx.globalAlpha = 1;+ } else {+ const r = Math.round((color?.r ?? 0.4) * 255);+ const g = Math.round((color?.g ?? 0.4) * 255);+ const b = Math.round((color?.b ?? 0.8) * 255);+ const a = color?.a ?? 0.5;+ ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;+ ctx.fillRect(-w / 2, -h / 2, w, h);+ }+ }++ ctx.restore();++ if (isSelected && hasSprite) {+ ctx.save();+ ctx.translate(pos.x, -pos.y);++ ctx.strokeStyle = '#00aaff';+ ctx.lineWidth = 2 / this.camera_.zoom;+ ctx.setLineDash([]);+ ctx.strokeRect(-w / 2, -h / 2, w, h);++ ctx.fillStyle = '#00aaff';+ const handleSize = 6 / this.camera_.zoom;+ const corners = [+ [-w / 2, -h / 2],+ [w / 2, -h / 2],+ [-w / 2, h / 2],+ [w / 2, h / 2],+ ];+ for (const [cx, cy] of corners) {+ ctx.fillRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);+ }++ ctx.restore();+ }+ }+}diff --git a/editor/src/panels/scene-view/index.ts b/editor/src/panels/scene-view/index.tsnew file mode 100644index 000000000..533b2b39e--- /dev/null+++ b/editor/src/panels/scene-view/index.ts@@ -0,0 +1,2 @@+export { SceneViewPanel } from './SceneViewPanel';+export type { SceneViewPanelOptions } from './SceneViewPanel';diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.tsindex 1975feee5..871a3fcc4 100644--- a/editor/src/store/EditorStore.ts+++ b/editor/src/store/EditorStore.ts@@ -1,49 +1,12 @@-/**- * @file EditorStore.ts- * @brief Editor state management- */-import type { Entity } from 'esengine';import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';import { createEmptyScene } from '../types/SceneTypes';-import {- CommandHistory,- PropertyCommand,- CompoundCommand,- CreateEntityCommand,- DeleteEntityCommand,- ReparentCommand,- MoveEntityCommand,- AddComponentCommand,- RemoveComponentCommand,- ReorderComponentCommand,- RenameEntityCommand,- ToggleVisibilityCommand,- InstantiatePrefabCommand,- InstantiateNestedPrefabCommand,- UnpackPrefabCommand,- RevertPrefabInstanceCommand,- ApplyPrefabOverridesCommand,-} from '../commands';-import {- entityTreeToPrefab,- savePrefabToPath,- loadPrefabFromPath,- prefabToSceneData,- sceneDataToPrefab,- instantiatePrefabRecursive,- syncPrefabInstances,- recordPropertyOverride,- recordNameOverride,- recordVisibilityOverride,- recordComponentAddedOverride,- recordComponentRemovedOverride,-} from '../prefab';-import { getGlobalPathResolver, getAssetDatabase, isUUID } from '../asset';+import { CommandHistory } from '../commands';import { WorldTransformCache } from '../transform/WorldTransformCache';import type { Transform } from '../math/Transform';-import { isComponentRemovable } from '../schemas/ComponentSchemas';-import { showConfirmDialog } from '../ui/dialog';+import { SelectionService } from './SelectionService';+import { SceneOperations } from './SceneOperations';+import { PrefabEditService } from './PrefabEditService';// =============================================================================// Types@@ -114,32 +77,28 @@ export type ComponentChangeListener = (event: ComponentChangeEvent) => void;// =============================================================================export class EditorStore {- private state_: EditorState;+ state_: EditorState;private history_: CommandHistory;- private listeners_: Set<EditorListener> = new Set();- private propertyListeners_: Set<PropertyChangeListener> = new Set();- private hierarchyListeners_: Set<HierarchyChangeListener> = new Set();- private focusListeners_: Set<(entityId: number) => void> = new Set();- private visibilityListeners_: Set<VisibilityChangeListener> = new Set();- private entityLifecycleListeners_: Set<EntityLifecycleListener> = new Set();- private componentChangeListeners_: Set<ComponentChangeListener> = new Set();- private sceneSyncListeners_: Set<() => void> = new Set();+ private listeners_ = new Set<EditorListener>();+ private propertyListeners_ = new Set<PropertyChangeListener>();+ private hierarchyListeners_ = new Set<HierarchyChangeListener>();+ private visibilityListeners_ = new Set<VisibilityChangeListener>();+ private entityLifecycleListeners_ = new Set<EntityLifecycleListener>();+ private componentChangeListeners_ = new Set<ComponentChangeListener>();+ private sceneSyncListeners_ = new Set<() => void>();private pendingNotify_ = false;- private dirtyFlags_: Set<DirtyFlag> = new Set();- private nextEntityId_ = 1;+ private dirtyFlags_ = new Set<DirtyFlag>();+ nextEntityId_ = 1;private sceneVersion_ = 0;- private worldTransforms_ = new WorldTransformCache();- private entityMap_ = new Map<number, EntityData>();-- private prefabLock_: Promise<void> | null = null;- private prefabEditingPath_: string | null = null;- private savedSceneState_: {- scene: SceneData;- filePath: string | null;- isDirty: boolean;- } | null = null;+ worldTransforms_ = new WorldTransformCache();+ entityMap_ = new Map<number, EntityData>();+private autoSaveTimer_: ReturnType<typeof setInterval> | null = null;+ private readonly selection_: SelectionService;+ private readonly sceneOps_: SceneOperations;+ private readonly prefabEdit_: PrefabEditService;+private static readonly AUTOSAVE_KEY = 'esengine.autosave';private static readonly AUTOSAVE_INTERVAL = 60_000;@@ -156,6 +115,11 @@ export class EditorStore {this.nextEntityId_ = this.computeNextEntityId(scene);this.rebuildEntityMap();this.worldTransforms_.setScene(scene);++ this.selection_ = new SelectionService(this);+ this.sceneOps_ = new SceneOperations(this);+ this.prefabEdit_ = new PrefabEditService(this);+this.startAutoSave();}@@ -185,8 +149,8 @@ export class EditorStore {}get selectedEntity(): Entity | null {- const arr = Array.from(this.state_.selectedEntities);- return arr.length === 1 ? (arr[0] as Entity) : null;+ if (this.state_.selectedEntities.size !== 1) return null;+ return this.state_.selectedEntities.values().next().value as Entity;}get selectedAsset(): AssetSelection | null {@@ -194,11 +158,11 @@ export class EditorStore {}get prefabEditingPath(): string | null {- return this.prefabEditingPath_;+ return this.prefabEdit_.prefabEditingPath;}get isEditingPrefab(): boolean {- return this.prefabEditingPath_ !== null;+ return this.prefabEdit_.isEditingPrefab;}get canUndo(): boolean {@@ -299,107 +263,31 @@ export class EditorStore {}// =========================================================================- // Selection+ // Selection (delegated to SelectionService)// =========================================================================selectEntity(entity: Entity | null, mode: 'replace' | 'add' | 'toggle' = 'replace'): void {- const oldSelection = new Set(this.state_.selectedEntities);-- if (entity === null) {- this.state_.selectedEntities.clear();- } else {- const id = entity as number;- if (mode === 'replace') {- this.state_.selectedEntities.clear();- this.state_.selectedEntities.add(id);- } else if (mode === 'add') {- this.state_.selectedEntities.add(id);- } else if (mode === 'toggle') {- if (this.state_.selectedEntities.has(id)) {- this.state_.selectedEntities.delete(id);- } else {- this.state_.selectedEntities.add(id);- }- }- }-- if (!this.setsEqual(oldSelection, this.state_.selectedEntities)) {- this.state_.selectedAsset = null;- this.notify('selection');- }+ this.selection_.selectEntity(entity, mode);}selectEntities(entities: number[]): void {- this.state_.selectedEntities.clear();- for (const id of entities) {- this.state_.selectedEntities.add(id);- }- this.state_.selectedAsset = null;- this.notify('selection');+ this.selection_.selectEntities(entities);}selectRange(fromEntity: number, toEntity: number): void {- const flatList: number[] = [];- const visited = new Set<number>();-- const traverse = (entityId: number | null) => {- if (entityId === null) return;- const entity = this.entityMap_.get(entityId);- if (!entity || visited.has(entityId)) return;- visited.add(entityId);- flatList.push(entityId);- for (const childId of entity.children) {- traverse(childId);- }- };-- for (const entity of this.state_.scene.entities) {- if (entity.parent === null) {- traverse(entity.id);- }- }-- const fromIndex = flatList.indexOf(fromEntity);- const toIndex = flatList.indexOf(toEntity);-- if (fromIndex === -1 || toIndex === -1) return;-- const start = Math.min(fromIndex, toIndex);- const end = Math.max(fromIndex, toIndex);- const range = flatList.slice(start, end + 1);-- this.selectEntities(range);- }-- private setsEqual(a: Set<number>, b: Set<number>): boolean {- if (a.size !== b.size) return false;- for (const item of a) {- if (!b.has(item)) return false;- }- return true;+ this.selection_.selectRange(fromEntity, toEntity);}selectAsset(asset: AssetSelection | null): void {- this.state_.selectedAsset = asset;- this.state_.selectedEntities.clear();- this.notify('selection');+ this.selection_.selectAsset(asset);}getSelectedEntityData(): EntityData | null {- const arr = Array.from(this.state_.selectedEntities);- if (arr.length !== 1) return null;- return this.entityMap_.get(arr[0]) ?? null;+ return this.selection_.getSelectedEntityData();}getSelectedEntitiesData(): EntityData[] {- const result: EntityData[] = [];- for (const id of this.state_.selectedEntities) {- const entity = this.entityMap_.get(id);- if (entity) {- result.push(entity);- }- }- return result;+ return this.selection_.getSelectedEntitiesData();}getEntityData(entityId: number): EntityData | null {@@ -407,35 +295,19 @@ export class EditorStore {}focusEntity(entityId: number): void {- for (const listener of this.focusListeners_) {- listener(entityId);- }+ this.selection_.focusEntity(entityId);}onFocusEntity(listener: (entityId: number) => void): () => void {- this.focusListeners_.add(listener);- return () => this.focusListeners_.delete(listener);+ return this.selection_.onFocusEntity(listener);}// =========================================================================- // Visibility+ // Visibility (delegated to SceneOperations)// =========================================================================toggleVisibility(entityId: number): void {- const entityData = this.entityMap_.get(entityId);- if (!entityData) return;-- const cmd = new ToggleVisibilityCommand(- this.state_.scene,- this.entityMap_,- entityId,- (id, visible) => this.notifyVisibilityChange({ entity: id, visible })- );- this.executeCommand(cmd);-- if (entityData.prefab) {- recordVisibilityOverride(this.state_.scene, entityId, entityData.visible);- }+ this.sceneOps_.toggleVisibility(entityId);}isEntityVisible(entityId: number): boolean {@@ -457,160 +329,48 @@ export class EditorStore {return () => this.visibilityListeners_.delete(listener);}- private notifyVisibilityChange(event: VisibilityChangeEvent): void {- for (const listener of this.visibilityListeners_) {- listener(event);- }- }-// =========================================================================- // Entity Operations+ // Entity Operations (delegated to SceneOperations)// =========================================================================createEntity(name?: string, parent: Entity | null = null): Entity {- const id = this.nextEntityId_++;- const entityName = name ?? `Entity_${id}`;-- const cmd = new CreateEntityCommand(- this.state_.scene,- this.entityMap_,- id,- entityName,- parent- );- this.executeCommand(cmd);-- this.notifyEntityLifecycle({ entity: id, type: 'created', parent: parent as number | null });-- if (parent !== null) {- const parentData = this.entityMap_.get(parent as number);- if (parentData && !parentData.visible) {- const newEntityData = this.entityMap_.get(id);- if (newEntityData) {- newEntityData.visible = false;- this.notifyVisibilityChange({ entity: id, visible: false });- }- }- }-- this.selectEntity(id as Entity);-- return id as Entity;+ return this.sceneOps_.createEntity(name, parent);}deleteEntity(entity: Entity): void {- const descendants = this.collectDescendantIds(entity as number);- const cmd = new DeleteEntityCommand(this.state_.scene, this.entityMap_, entity);- this.executeCommand(cmd);-- const hadSelection = this.state_.selectedEntities.size > 0;- this.state_.selectedEntities.delete(entity as number);- for (const id of descendants) {- this.state_.selectedEntities.delete(id);- }- if (hadSelection) {- this.notify('selection');- }-- for (const id of descendants) {- this.notifyEntityLifecycle({ entity: id, type: 'deleted', parent: null });- }- this.notifyEntityLifecycle({ entity: entity as number, type: 'deleted', parent: null });+ this.sceneOps_.deleteEntity(entity);}deleteSelectedEntities(): void {- const toDelete = Array.from(this.state_.selectedEntities);-- const descendantMap = new Map<number, number[]>();- for (const id of toDelete) {- descendantMap.set(id, this.collectDescendantIds(id));- }-- const commands = toDelete.map(id => new DeleteEntityCommand(this.state_.scene, this.entityMap_, id as Entity));- const compound = new CompoundCommand(commands, 'Delete entities');- this.executeCommand(compound);-- this.state_.selectedEntities.clear();-- for (const id of toDelete) {- const descendants = descendantMap.get(id)!;- for (const descId of descendants) {- this.notifyEntityLifecycle({ entity: descId, type: 'deleted', parent: null });- }- this.notifyEntityLifecycle({ entity: id, type: 'deleted', parent: null });- }+ this.sceneOps_.deleteSelectedEntities();}reparentEntity(entity: Entity, newParent: Entity | null): void {- const cmd = new ReparentCommand(this.state_.scene, this.entityMap_, entity, newParent);- this.executeCommand(cmd);- this.notifyHierarchyChange({- entity: entity as number,- newParent: newParent as number | null,- });+ this.sceneOps_.reparentEntity(entity, newParent);}moveEntity(entity: Entity, newParent: Entity | null, index: number): void {- const cmd = new MoveEntityCommand(this.state_.scene, this.entityMap_, entity, newParent, index);- this.executeCommand(cmd);- this.notifyHierarchyChange({- entity: entity as number,- newParent: newParent as number | null,- });+ this.sceneOps_.moveEntity(entity, newParent, index);}renameEntity(entity: Entity, name: string): void {- const entityData = this.entityMap_.get(entity as number);- if (!entityData) return;-- const oldName = entityData.name;- const cmd = new RenameEntityCommand(- this.state_.scene,- this.entityMap_,- entity,- oldName,- name- );- this.executeCommand(cmd);-- if (entityData.prefab) {- recordNameOverride(this.state_.scene, entity as number, name);- }+ this.sceneOps_.renameEntity(entity, name);}// =========================================================================- // Component Operations+ // Component Operations (delegated to SceneOperations)// =========================================================================addComponent(entity: Entity, type: string, data: Record<string, unknown>): void {- const cmd = new AddComponentCommand(this.state_.scene, this.entityMap_, entity, type, data);- this.executeCommand(cmd);-- if (this.isPrefabInstance(entity as number)) {- recordComponentAddedOverride(this.state_.scene, entity as number, type, data);- }-- this.notifyComponentChange({ entity: entity as number, componentType: type, action: 'added' });+ this.sceneOps_.addComponent(entity, type, data);}removeComponent(entity: Entity, type: string): void {- if (!isComponentRemovable(type)) return;-- if (this.isPrefabInstance(entity as number)) {- recordComponentRemovedOverride(this.state_.scene, entity as number, type);- }-- const cmd = new RemoveComponentCommand(this.state_.scene, this.entityMap_, entity, type);- this.executeCommand(cmd);- this.notifyComponentChange({ entity: entity as number, componentType: type, action: 'removed' });+ this.sceneOps_.removeComponent(entity, type);}reorderComponent(entity: Entity, fromIndex: number, toIndex: number): void {- const cmd = new ReorderComponentCommand(- this.state_.scene, this.entityMap_, entity as number, fromIndex, toIndex- );- this.executeCommand(cmd);- this.notify('selection');+ this.sceneOps_.reorderComponent(entity, fromIndex, toIndex);}updateProperty(@@ -620,34 +380,7 @@ export class EditorStore {oldValue: unknown,newValue: unknown): void {- const cmd = new PropertyCommand(- this.state_.scene,- this.entityMap_,- entity,- componentType,- propertyName,- oldValue,- newValue- );- this.executeCommand(cmd);-- if (this.isPrefabInstance(entity as number)) {- recordPropertyOverride(- this.state_.scene,- entity as number,- componentType,- propertyName,- newValue- );- }-- this.notifyPropertyChange({- entity: entity as number,- componentType,- propertyName,- oldValue,- newValue,- });+ this.sceneOps_.updateProperty(entity, componentType, propertyName, oldValue, newValue);}updateProperties(@@ -655,32 +388,11 @@ export class EditorStore {componentType: string,changes: { property: string; oldValue: unknown; newValue: unknown }[]): void {- const commands = changes.map(c => new PropertyCommand(- this.state_.scene,- this.entityMap_,- entity,- componentType,- c.property,- c.oldValue,- c.newValue- ));- const compound = new CompoundCommand(commands, `Change ${componentType} properties`);- this.executeCommand(compound);- for (const c of changes) {- this.notifyPropertyChange({- entity: entity as number,- componentType,- propertyName: c.property,- oldValue: c.oldValue,- newValue: c.newValue,- });- }+ this.sceneOps_.updateProperties(entity, componentType, changes);}getComponent(entity: Entity, type: string): ComponentData | null {- const entityData = this.entityMap_.get(entity as number);- if (!entityData) return null;- return entityData.components.find(c => c.type === type) ?? null;+ return this.sceneOps_.getComponent(entity, type);}updatePropertyDirect(@@ -689,316 +401,71 @@ export class EditorStore {propertyName: string,newValue: unknown): void {- const entityData = this.entityMap_.get(entity as number);- if (!entityData) return;-- const component = entityData.components.find(c => c.type === componentType);- if (!component) return;-- const oldValue = component.data[propertyName];- component.data[propertyName] = newValue;- this.state_.isDirty = true;-- if (componentType === 'LocalTransform') {- this.worldTransforms_.updateEntity(entityData);- this.worldTransforms_.markDirty(entity as number);- }-- this.notifyPropertyChange({- entity: entity as number,- componentType,- propertyName,- oldValue,- newValue,- });+ this.sceneOps_.updatePropertyDirect(entity, componentType, propertyName, newValue);}// =========================================================================// World Transform// =========================================================================- /**- * @brief Get cached world transform for an entity- */getWorldTransform(entityId: number): Transform {return this.worldTransforms_.getWorldTransform(entityId);}- /**- * @brief Invalidate all cached transforms (force recalculation)- */invalidateAllTransforms(): void {this.worldTransforms_.invalidateAll();}// =========================================================================- // Prefab Operations+ // Prefab Operations (delegated to PrefabEditService)// =========================================================================- async instantiatePrefab(- prefabPath: string,- parentEntity: Entity | null = null- ): Promise<Entity | null> {- if (this.prefabLock_) {- await this.prefabLock_;- }-- let resolve: () => void;- this.prefabLock_ = new Promise<void>(r => { resolve = r; });-- try {- return await this.instantiatePrefabInner(prefabPath, parentEntity);- } finally {- this.prefabLock_ = null;- resolve!();- }- }-- private async instantiatePrefabInner(- prefabPath: string,- parentEntity: Entity | null- ): Promise<Entity | null> {- const hasNested = await this.prefabHasNested(prefabPath);-- if (hasNested) {- return this.instantiatePrefabNested(prefabPath, parentEntity);- }-- const prefab = await loadPrefabFromPath(prefabPath);- if (!prefab) return null;-- const cmd = new InstantiatePrefabCommand(- this.state_.scene,- this.entityMap_,- prefab,- prefabPath,- parentEntity as number | null,- this.nextEntityId_- );- this.executeCommand(cmd);-- const createdIds = cmd.createdEntityIds;- this.nextEntityId_ = Math.max(this.nextEntityId_, ...createdIds.map(id => id + 1));-- for (const id of createdIds) {- this.notifyEntityLifecycle({ entity: id, type: 'created', parent: null });- }-- const rootId = cmd.rootEntityId;- if (rootId !== -1) {- this.selectEntity(rootId as Entity);- }-- return rootId as Entity;- }-- private async instantiatePrefabNested(- prefabPath: string,- parentEntity: Entity | null- ): Promise<Entity | null> {- const result = await instantiatePrefabRecursive(- prefabPath,- this.state_.scene,- parentEntity as number | null,- this.nextEntityId_- );- if (!result) return null;-- const cmd = new InstantiateNestedPrefabCommand(- this.state_.scene,- this.entityMap_,- result.createdEntities,- result.rootEntityId,- parentEntity as number | null- );- this.executeCommand(cmd);-- this.nextEntityId_ = Math.max(- this.nextEntityId_,- ...result.createdEntities.map(e => e.id + 1)- );-- for (const entity of result.createdEntities) {- this.notifyEntityLifecycle({ entity: entity.id, type: 'created', parent: entity.parent });- }-- this.selectEntity(result.rootEntityId as Entity);-- return result.rootEntityId as Entity;- }-- private async prefabHasNested(prefabPath: string): Promise<boolean> {- const prefab = await loadPrefabFromPath(prefabPath);- if (!prefab) return false;- return prefab.entities.some(e => e.nestedPrefab !== undefined);+ async instantiatePrefab(prefabPath: string, parentEntity: Entity | null = null): Promise<Entity | null> {+ return this.prefabEdit_.instantiatePrefab(prefabPath, parentEntity);}async saveAsPrefab(entityId: number, filePath: string): Promise<boolean> {- const entityData = this.entityMap_.get(entityId);- if (!entityData) return false;-- const name = filePath.split('/').pop()?.replace('.esprefab', '') ?? entityData.name;- const entities = this.collectEntityTree(entityId);- const { prefab, idMapping } = entityTreeToPrefab(name, entityId, entities);-- const saved = await savePrefabToPath(prefab, filePath);- if (!saved) return false;-- const relativePath = getGlobalPathResolver().toRelativePath(filePath);- const uuid = await getAssetDatabase().ensureMeta(relativePath);- const instanceId = `prefab_${Date.now()}_${entityId}`;-- for (const [sceneId, prefabEntityId] of idMapping) {- const entity = this.entityMap_.get(sceneId);- if (!entity) continue;-- entity.prefab = {- prefabPath: uuid,- prefabEntityId,- isRoot: sceneId === entityId,- instanceId,- overrides: [],- };- }-- this.state_.isDirty = true;- this.notify('scene');- return true;+ return this.prefabEdit_.saveAsPrefab(entityId, filePath);}async revertPrefabInstance(instanceId: string, prefabPath: string): Promise<void> {- const prefab = await loadPrefabFromPath(prefabPath);- if (!prefab) return;-- const cmd = new RevertPrefabInstanceCommand(- this.state_.scene,- instanceId,- prefab,- prefabPath- );- this.executeCommand(cmd);-+ return this.prefabEdit_.revertPrefabInstance(instanceId, prefabPath);}async applyPrefabOverrides(instanceId: string, prefabPath: string): Promise<void> {- const prefab = await loadPrefabFromPath(prefabPath);- if (!prefab) return;-- const cmd = new ApplyPrefabOverridesCommand(- this.state_.scene,- instanceId,- prefab,- prefabPath,- async (p, path) => { await savePrefabToPath(p, path); }- );- this.executeCommand(cmd);-+ return this.prefabEdit_.applyPrefabOverrides(instanceId, prefabPath);}unpackPrefab(instanceId: string): void {- const cmd = new UnpackPrefabCommand(this.state_.scene, instanceId);- this.executeCommand(cmd);-+ this.prefabEdit_.unpackPrefab(instanceId);}isPrefabInstance(entityId: number): boolean {- const entity = this.entityMap_.get(entityId);- return entity?.prefab !== undefined;+ return this.prefabEdit_.isPrefabInstance(entityId);}isPrefabRoot(entityId: number): boolean {- const entity = this.entityMap_.get(entityId);- return entity?.prefab?.isRoot === true;+ return this.prefabEdit_.isPrefabRoot(entityId);}getPrefabInstanceId(entityId: number): string | undefined {- return this.entityMap_.get(entityId)?.prefab?.instanceId;+ return this.prefabEdit_.getPrefabInstanceId(entityId);}getPrefabPath(entityId: number): string | undefined {- return this.entityMap_.get(entityId)?.prefab?.prefabPath;+ return this.prefabEdit_.getPrefabPath(entityId);}async enterPrefabEditMode(prefabPath: string): Promise<boolean> {- const prefab = await loadPrefabFromPath(prefabPath);- if (!prefab) return false;-- this.savedSceneState_ = {- scene: JSON.parse(JSON.stringify(this.state_.scene)),- filePath: this.state_.filePath,- isDirty: this.state_.isDirty,- };-- if (!isUUID(prefabPath)) {- const uuid = getAssetDatabase().getUuid(prefabPath);- if (uuid) prefabPath = uuid;- }- this.prefabEditingPath_ = prefabPath;- const scene = prefabToSceneData(prefab);- this.loadScene(scene, null);-- return true;+ return this.prefabEdit_.enterPrefabEditMode(prefabPath);}async exitPrefabEditMode(): Promise<void> {- if (!this.savedSceneState_) return;-- let saveFailed = false;- if (this.state_.isDirty) {- saveFailed = !(await this.trySavePrefabWithRetry());- }-- const saved = this.savedSceneState_;- const editedPrefabPath = this.prefabEditingPath_!;- this.prefabEditingPath_ = null;- this.savedSceneState_ = null;-- const synced = await syncPrefabInstances(saved.scene, editedPrefabPath);- this.loadScene(saved.scene, saved.filePath);- this.state_.isDirty = saved.isDirty || synced || saveFailed;- this.notify('scene');- }-- private async trySavePrefabWithRetry(): Promise<boolean> {- while (true) {- try {- await this.savePrefabEditing();- return true;- } catch (e) {- const retry = await showConfirmDialog({- title: 'Failed to save prefab',- message: `${String(e)}\n\nRetry saving, or discard changes?`,- confirmText: 'Retry',- cancelText: 'Discard',- danger: true,- });- if (!retry) return false;- }- }+ return this.prefabEdit_.exitPrefabEditMode();}async savePrefabEditing(): Promise<boolean> {- if (!this.prefabEditingPath_) return false;-- const prefab = sceneDataToPrefab(this.state_.scene);- const saved = await savePrefabToPath(prefab, this.prefabEditingPath_);- if (saved) {- this.state_.isDirty = false;- this.notify('scene');- }- return saved;- }-- private collectEntityTree(rootId: number): import('../types/SceneTypes').EntityData[] {- const result: import('../types/SceneTypes').EntityData[] = [];- const entity = this.entityMap_.get(rootId);- if (!entity) return result;-- result.push(entity);- for (const childId of entity.children) {- result.push(...this.collectEntityTree(childId));- }- return result;+ return this.prefabEdit_.savePrefabEditing();}// =========================================================================@@ -1065,10 +532,10 @@ export class EditorStore {}// =========================================================================- // Private+ // Internal (used by services via host interfaces)// =========================================================================- private executeCommand(cmd: import('../commands').Command): void {+ executeCommand(cmd: import('../commands').Command): void {this.history_.execute(cmd);this.state_.isDirty = true;this.applyCommandSideEffects(cmd, false);@@ -1095,7 +562,7 @@ export class EditorStore {}}- private notify(flag: DirtyFlag = 'scene'): void {+ notify(flag: DirtyFlag = 'scene'): void {this.dirtyFlags_.add(flag);if (this.pendingNotify_) return;this.pendingNotify_ = true;@@ -1110,7 +577,7 @@ export class EditorStore {});}- private notifyPropertyChange(event: PropertyChangeEvent): void {+ notifyPropertyChange(event: PropertyChangeEvent): void {if (event.componentType === 'TextInput' && event.propertyName === 'backgroundColor') {const entityData = this.entityMap_.get(event.entity);const spriteComp = entityData?.components.find(c => c.type === 'Sprite');@@ -1146,33 +613,28 @@ export class EditorStore {}}- private notifyHierarchyChange(event: HierarchyChangeEvent): void {+ notifyHierarchyChange(event: HierarchyChangeEvent): void {for (const listener of this.hierarchyListeners_) {listener(event);}}- private notifyEntityLifecycle(event: EntityLifecycleEvent): void {+ notifyEntityLifecycle(event: EntityLifecycleEvent): void {for (const listener of this.entityLifecycleListeners_) {listener(event);}}- private notifyComponentChange(event: ComponentChangeEvent): void {+ notifyComponentChange(event: ComponentChangeEvent): void {for (const listener of this.componentChangeListeners_) {listener(event);}}- private collectDescendantIds(entityId: number): number[] {- const result: number[] = [];- const entityData = this.entityMap_.get(entityId);- if (!entityData) return result;- for (const childId of entityData.children) {- result.push(...this.collectDescendantIds(childId));- result.push(childId);+ notifyVisibilityChange(event: VisibilityChangeEvent): void {+ for (const listener of this.visibilityListeners_) {+ listener(event);}- return result;}private rebuildEntityMap(): void {diff --git a/editor/src/store/PrefabEditService.ts b/editor/src/store/PrefabEditService.tsnew file mode 100644index 000000000..be0294b9b--- /dev/null+++ b/editor/src/store/PrefabEditService.ts@@ -0,0 +1,322 @@+import type { Entity } from 'esengine';+import type { SceneData, EntityData } from '../types/SceneTypes';+import {+ InstantiatePrefabCommand,+ InstantiateNestedPrefabCommand,+ UnpackPrefabCommand,+ RevertPrefabInstanceCommand,+ ApplyPrefabOverridesCommand,+} from '../commands';+import {+ entityTreeToPrefab,+ savePrefabToPath,+ loadPrefabFromPath,+ prefabToSceneData,+ sceneDataToPrefab,+ instantiatePrefabRecursive,+ syncPrefabInstances,+} from '../prefab';+import { getGlobalPathResolver, getAssetDatabase, isUUID } from '../asset';+import { showConfirmDialog } from '../ui/dialog';+import type { DirtyFlag, EntityLifecycleEvent } from './EditorStore';++export interface PrefabEditHost {+ readonly state_: {+ scene: SceneData;+ filePath: string | null;+ isDirty: boolean;+ };+ readonly entityMap_: Map<number, EntityData>;+ nextEntityId_: number;+ executeCommand(cmd: import('../commands').Command): void;+ notify(flag: DirtyFlag): void;+ notifyEntityLifecycle(event: EntityLifecycleEvent): void;+ selectEntity(entity: Entity | null): void;+ loadScene(scene: SceneData, filePath: string | null): void;+}++export class PrefabEditService {+ private host_: PrefabEditHost;+ private prefabLock_: Promise<void> | null = null;+ private prefabEditingPath_: string | null = null;+ private savedSceneState_: {+ scene: SceneData;+ filePath: string | null;+ isDirty: boolean;+ } | null = null;++ constructor(host: PrefabEditHost) {+ this.host_ = host;+ }++ get prefabEditingPath(): string | null {+ return this.prefabEditingPath_;+ }++ get isEditingPrefab(): boolean {+ return this.prefabEditingPath_ !== null;+ }++ async instantiatePrefab(+ prefabPath: string,+ parentEntity: Entity | null = null+ ): Promise<Entity | null> {+ if (this.prefabLock_) {+ await this.prefabLock_;+ }++ let resolve: () => void;+ this.prefabLock_ = new Promise<void>(r => { resolve = r; });++ try {+ return await this.instantiatePrefabInner(prefabPath, parentEntity);+ } finally {+ this.prefabLock_ = null;+ resolve!();+ }+ }++ private async instantiatePrefabInner(+ prefabPath: string,+ parentEntity: Entity | null+ ): Promise<Entity | null> {+ const hasNested = await this.prefabHasNested(prefabPath);++ if (hasNested) {+ return this.instantiatePrefabNested(prefabPath, parentEntity);+ }++ const prefab = await loadPrefabFromPath(prefabPath);+ if (!prefab) return null;++ const cmd = new InstantiatePrefabCommand(+ this.host_.state_.scene,+ this.host_.entityMap_,+ prefab,+ prefabPath,+ parentEntity as number | null,+ this.host_.nextEntityId_+ );+ this.host_.executeCommand(cmd);++ const createdIds = cmd.createdEntityIds;+ this.host_.nextEntityId_ = Math.max(this.host_.nextEntityId_, ...createdIds.map(id => id + 1));++ for (const id of createdIds) {+ this.host_.notifyEntityLifecycle({ entity: id, type: 'created', parent: null });+ }++ const rootId = cmd.rootEntityId;+ if (rootId !== -1) {+ this.host_.selectEntity(rootId as Entity);+ }++ return rootId as Entity;+ }++ private async instantiatePrefabNested(+ prefabPath: string,+ parentEntity: Entity | null+ ): Promise<Entity | null> {+ const result = await instantiatePrefabRecursive(+ prefabPath,+ this.host_.state_.scene,+ parentEntity as number | null,+ this.host_.nextEntityId_+ );+ if (!result) return null;++ const cmd = new InstantiateNestedPrefabCommand(+ this.host_.state_.scene,+ this.host_.entityMap_,+ result.createdEntities,+ result.rootEntityId,+ parentEntity as number | null+ );+ this.host_.executeCommand(cmd);++ this.host_.nextEntityId_ = Math.max(+ this.host_.nextEntityId_,+ ...result.createdEntities.map(e => e.id + 1)+ );++ for (const entity of result.createdEntities) {+ this.host_.notifyEntityLifecycle({ entity: entity.id, type: 'created', parent: entity.parent });+ }++ this.host_.selectEntity(result.rootEntityId as Entity);++ return result.rootEntityId as Entity;+ }++ private async prefabHasNested(prefabPath: string): Promise<boolean> {+ const prefab = await loadPrefabFromPath(prefabPath);+ if (!prefab) return false;+ return prefab.entities.some(e => e.nestedPrefab !== undefined);+ }++ async saveAsPrefab(entityId: number, filePath: string): Promise<boolean> {+ const entityData = this.host_.entityMap_.get(entityId);+ if (!entityData) return false;++ const name = filePath.split('/').pop()?.replace('.esprefab', '') ?? entityData.name;+ const entities = this.collectEntityTree(entityId);+ const { prefab, idMapping } = entityTreeToPrefab(name, entityId, entities);++ const saved = await savePrefabToPath(prefab, filePath);+ if (!saved) return false;++ const relativePath = getGlobalPathResolver().toRelativePath(filePath);+ const uuid = await getAssetDatabase().ensureMeta(relativePath);+ const instanceId = `prefab_${Date.now()}_${entityId}`;++ for (const [sceneId, prefabEntityId] of idMapping) {+ const entity = this.host_.entityMap_.get(sceneId);+ if (!entity) continue;++ entity.prefab = {+ prefabPath: uuid,+ prefabEntityId,+ isRoot: sceneId === entityId,+ instanceId,+ overrides: [],+ };+ }++ this.host_.state_.isDirty = true;+ this.host_.notify('scene');+ return true;+ }++ async revertPrefabInstance(instanceId: string, prefabPath: string): Promise<void> {+ const prefab = await loadPrefabFromPath(prefabPath);+ if (!prefab) return;++ const cmd = new RevertPrefabInstanceCommand(+ this.host_.state_.scene,+ instanceId,+ prefab,+ prefabPath+ );+ this.host_.executeCommand(cmd);+ }++ async applyPrefabOverrides(instanceId: string, prefabPath: string): Promise<void> {+ const prefab = await loadPrefabFromPath(prefabPath);+ if (!prefab) return;++ const cmd = new ApplyPrefabOverridesCommand(+ this.host_.state_.scene,+ instanceId,+ prefab,+ prefabPath,+ async (p, path) => { await savePrefabToPath(p, path); }+ );+ this.host_.executeCommand(cmd);+ }++ unpackPrefab(instanceId: string): void {+ const cmd = new UnpackPrefabCommand(this.host_.state_.scene, instanceId);+ this.host_.executeCommand(cmd);+ }++ isPrefabInstance(entityId: number): boolean {+ const entity = this.host_.entityMap_.get(entityId);+ return entity?.prefab !== undefined;+ }++ isPrefabRoot(entityId: number): boolean {+ const entity = this.host_.entityMap_.get(entityId);+ return entity?.prefab?.isRoot === true;+ }++ getPrefabInstanceId(entityId: number): string | undefined {+ return this.host_.entityMap_.get(entityId)?.prefab?.instanceId;+ }++ getPrefabPath(entityId: number): string | undefined {+ return this.host_.entityMap_.get(entityId)?.prefab?.prefabPath;+ }++ async enterPrefabEditMode(prefabPath: string): Promise<boolean> {+ const prefab = await loadPrefabFromPath(prefabPath);+ if (!prefab) return false;++ this.savedSceneState_ = {+ scene: JSON.parse(JSON.stringify(this.host_.state_.scene)),+ filePath: this.host_.state_.filePath,+ isDirty: this.host_.state_.isDirty,+ };++ if (!isUUID(prefabPath)) {+ const uuid = getAssetDatabase().getUuid(prefabPath);+ if (uuid) prefabPath = uuid;+ }+ this.prefabEditingPath_ = prefabPath;+ const scene = prefabToSceneData(prefab);+ this.host_.loadScene(scene, null);++ return true;+ }++ async exitPrefabEditMode(): Promise<void> {+ if (!this.savedSceneState_) return;++ let saveFailed = false;+ if (this.host_.state_.isDirty) {+ saveFailed = !(await this.trySavePrefabWithRetry());+ }++ const saved = this.savedSceneState_;+ const editedPrefabPath = this.prefabEditingPath_!;+ this.prefabEditingPath_ = null;+ this.savedSceneState_ = null;++ const synced = await syncPrefabInstances(saved.scene, editedPrefabPath);+ this.host_.loadScene(saved.scene, saved.filePath);+ this.host_.state_.isDirty = saved.isDirty || synced || saveFailed;+ this.host_.notify('scene');+ }++ async savePrefabEditing(): Promise<boolean> {+ if (!this.prefabEditingPath_) return false;++ const prefab = sceneDataToPrefab(this.host_.state_.scene);+ const saved = await savePrefabToPath(prefab, this.prefabEditingPath_);+ if (saved) {+ this.host_.state_.isDirty = false;+ this.host_.notify('scene');+ }+ return saved;+ }++ private async trySavePrefabWithRetry(): Promise<boolean> {+ while (true) {+ try {+ await this.savePrefabEditing();+ return true;+ } catch (e) {+ const retry = await showConfirmDialog({+ title: 'Failed to save prefab',+ message: `${String(e)}\n\nRetry saving, or discard changes?`,+ confirmText: 'Retry',+ cancelText: 'Discard',+ danger: true,+ });+ if (!retry) return false;+ }+ }+ }++ private collectEntityTree(rootId: number): EntityData[] {+ const result: EntityData[] = [];+ const entity = this.host_.entityMap_.get(rootId);+ if (!entity) return result;++ result.push(entity);+ for (const childId of entity.children) {+ result.push(...this.collectEntityTree(childId));+ }+ return result;+ }+}diff --git a/editor/src/store/SceneOperations.ts b/editor/src/store/SceneOperations.tsnew file mode 100644index 000000000..a2f2c6706--- /dev/null+++ b/editor/src/store/SceneOperations.ts@@ -0,0 +1,338 @@+import type { Entity } from 'esengine';+import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';+import {+ PropertyCommand,+ CompoundCommand,+ CreateEntityCommand,+ DeleteEntityCommand,+ ReparentCommand,+ MoveEntityCommand,+ AddComponentCommand,+ RemoveComponentCommand,+ ReorderComponentCommand,+ RenameEntityCommand,+ ToggleVisibilityCommand,+} from '../commands';+import {+ recordPropertyOverride,+ recordNameOverride,+ recordVisibilityOverride,+ recordComponentAddedOverride,+ recordComponentRemovedOverride,+} from '../prefab';+import { isComponentRemovable } from '../schemas/ComponentSchemas';+import type {+ DirtyFlag,+ PropertyChangeEvent,+ VisibilityChangeEvent,+ HierarchyChangeEvent,+ EntityLifecycleEvent,+ ComponentChangeEvent,+} from './EditorStore';++export interface SceneOperationsHost {+ readonly state_: {+ scene: SceneData;+ selectedEntities: Set<number>;+ isDirty: boolean;+ };+ readonly entityMap_: Map<number, EntityData>;+ nextEntityId_: number;+ executeCommand(cmd: import('../commands').Command): void;+ notify(flag: DirtyFlag): void;+ notifyPropertyChange(event: PropertyChangeEvent): void;+ notifyVisibilityChange(event: VisibilityChangeEvent): void;+ notifyHierarchyChange(event: HierarchyChangeEvent): void;+ notifyEntityLifecycle(event: EntityLifecycleEvent): void;+ notifyComponentChange(event: ComponentChangeEvent): void;+ selectEntity(entity: Entity | null): void;+ worldTransforms_: {+ updateEntity(entity: EntityData): void;+ markDirty(entityId: number): void;+ };+}++export class SceneOperations {+ private host_: SceneOperationsHost;++ constructor(host: SceneOperationsHost) {+ this.host_ = host;+ }++ createEntity(name?: string, parent: Entity | null = null): Entity {+ const id = this.host_.nextEntityId_++;+ const entityName = name ?? `Entity_${id}`;++ const cmd = new CreateEntityCommand(+ this.host_.state_.scene,+ this.host_.entityMap_,+ id,+ entityName,+ parent+ );+ this.host_.executeCommand(cmd);++ this.host_.notifyEntityLifecycle({ entity: id, type: 'created', parent: parent as number | null });++ if (parent !== null) {+ const parentData = this.host_.entityMap_.get(parent as number);+ if (parentData && !parentData.visible) {+ const newEntityData = this.host_.entityMap_.get(id);+ if (newEntityData) {+ newEntityData.visible = false;+ this.host_.notifyVisibilityChange({ entity: id, visible: false });+ }+ }+ }++ this.host_.selectEntity(id as Entity);++ return id as Entity;+ }++ deleteEntity(entity: Entity): void {+ const descendants = this.collectDescendantIds(entity as number);+ const cmd = new DeleteEntityCommand(this.host_.state_.scene, this.host_.entityMap_, entity);+ this.host_.executeCommand(cmd);++ const hadSelection = this.host_.state_.selectedEntities.size > 0;+ this.host_.state_.selectedEntities.delete(entity as number);+ for (const id of descendants) {+ this.host_.state_.selectedEntities.delete(id);+ }+ if (hadSelection) {+ this.host_.notify('selection');+ }++ for (const id of descendants) {+ this.host_.notifyEntityLifecycle({ entity: id, type: 'deleted', parent: null });+ }+ this.host_.notifyEntityLifecycle({ entity: entity as number, type: 'deleted', parent: null });+ }++ deleteSelectedEntities(): void {+ const toDelete = Array.from(this.host_.state_.selectedEntities);++ const descendantMap = new Map<number, number[]>();+ for (const id of toDelete) {+ descendantMap.set(id, this.collectDescendantIds(id));+ }++ const commands = toDelete.map(id =>+ new DeleteEntityCommand(this.host_.state_.scene, this.host_.entityMap_, id as Entity)+ );+ const compound = new CompoundCommand(commands, 'Delete entities');+ this.host_.executeCommand(compound);++ this.host_.state_.selectedEntities.clear();++ for (const id of toDelete) {+ const descendants = descendantMap.get(id)!;+ for (const descId of descendants) {+ this.host_.notifyEntityLifecycle({ entity: descId, type: 'deleted', parent: null });+ }+ this.host_.notifyEntityLifecycle({ entity: id, type: 'deleted', parent: null });+ }+ }++ reparentEntity(entity: Entity, newParent: Entity | null): void {+ const cmd = new ReparentCommand(this.host_.state_.scene, this.host_.entityMap_, entity, newParent);+ this.host_.executeCommand(cmd);+ this.host_.notifyHierarchyChange({+ entity: entity as number,+ newParent: newParent as number | null,+ });+ }++ moveEntity(entity: Entity, newParent: Entity | null, index: number): void {+ const cmd = new MoveEntityCommand(this.host_.state_.scene, this.host_.entityMap_, entity, newParent, index);+ this.host_.executeCommand(cmd);+ this.host_.notifyHierarchyChange({+ entity: entity as number,+ newParent: newParent as number | null,+ });+ }++ renameEntity(entity: Entity, name: string): void {+ const entityData = this.host_.entityMap_.get(entity as number);+ if (!entityData) return;++ const oldName = entityData.name;+ const cmd = new RenameEntityCommand(+ this.host_.state_.scene,+ this.host_.entityMap_,+ entity,+ oldName,+ name+ );+ this.host_.executeCommand(cmd);++ if (entityData.prefab) {+ recordNameOverride(this.host_.state_.scene, entity as number, name);+ }+ }++ toggleVisibility(entityId: number): void {+ const entityData = this.host_.entityMap_.get(entityId);+ if (!entityData) return;++ const cmd = new ToggleVisibilityCommand(+ this.host_.state_.scene,+ this.host_.entityMap_,+ entityId,+ (id, visible) => this.host_.notifyVisibilityChange({ entity: id, visible })+ );+ this.host_.executeCommand(cmd);++ if (entityData.prefab) {+ recordVisibilityOverride(this.host_.state_.scene, entityId, entityData.visible);+ }+ }++ addComponent(entity: Entity, type: string, data: Record<string, unknown>): void {+ const cmd = new AddComponentCommand(this.host_.state_.scene, this.host_.entityMap_, entity, type, data);+ this.host_.executeCommand(cmd);++ if (this.isPrefabInstance(entity as number)) {+ recordComponentAddedOverride(this.host_.state_.scene, entity as number, type, data);+ }++ this.host_.notifyComponentChange({ entity: entity as number, componentType: type, action: 'added' });+ }++ removeComponent(entity: Entity, type: string): void {+ if (!isComponentRemovable(type)) return;++ if (this.isPrefabInstance(entity as number)) {+ recordComponentRemovedOverride(this.host_.state_.scene, entity as number, type);+ }++ const cmd = new RemoveComponentCommand(this.host_.state_.scene, this.host_.entityMap_, entity, type);+ this.host_.executeCommand(cmd);+ this.host_.notifyComponentChange({ entity: entity as number, componentType: type, action: 'removed' });+ }++ reorderComponent(entity: Entity, fromIndex: number, toIndex: number): void {+ const cmd = new ReorderComponentCommand(+ this.host_.state_.scene, this.host_.entityMap_, entity as number, fromIndex, toIndex+ );+ this.host_.executeCommand(cmd);+ this.host_.notify('selection');+ }++ updateProperty(+ entity: Entity,+ componentType: string,+ propertyName: string,+ oldValue: unknown,+ newValue: unknown+ ): void {+ const cmd = new PropertyCommand(+ this.host_.state_.scene,+ this.host_.entityMap_,+ entity,+ componentType,+ propertyName,+ oldValue,+ newValue+ );+ this.host_.executeCommand(cmd);++ if (this.isPrefabInstance(entity as number)) {+ recordPropertyOverride(+ this.host_.state_.scene,+ entity as number,+ componentType,+ propertyName,+ newValue+ );+ }++ this.host_.notifyPropertyChange({+ entity: entity as number,+ componentType,+ propertyName,+ oldValue,+ newValue,+ });+ }++ updateProperties(+ entity: Entity,+ componentType: string,+ changes: { property: string; oldValue: unknown; newValue: unknown }[]+ ): void {+ const commands = changes.map(c => new PropertyCommand(+ this.host_.state_.scene,+ this.host_.entityMap_,+ entity,+ componentType,+ c.property,+ c.oldValue,+ c.newValue+ ));+ const compound = new CompoundCommand(commands, `Change ${componentType} properties`);+ this.host_.executeCommand(compound);+ for (const c of changes) {+ this.host_.notifyPropertyChange({+ entity: entity as number,+ componentType,+ propertyName: c.property,+ oldValue: c.oldValue,+ newValue: c.newValue,+ });+ }+ }++ getComponent(entity: Entity, type: string): ComponentData | null {+ const entityData = this.host_.entityMap_.get(entity as number);+ if (!entityData) return null;+ return entityData.components.find(c => c.type === type) ?? null;+ }++ updatePropertyDirect(+ entity: Entity,+ componentType: string,+ propertyName: string,+ newValue: unknown+ ): void {+ const entityData = this.host_.entityMap_.get(entity as number);+ if (!entityData) return;++ const component = entityData.components.find(c => c.type === componentType);+ if (!component) return;++ const oldValue = component.data[propertyName];+ component.data[propertyName] = newValue;+ this.host_.state_.isDirty = true;++ if (componentType === 'LocalTransform') {+ this.host_.worldTransforms_.updateEntity(entityData);+ this.host_.worldTransforms_.markDirty(entity as number);+ }++ this.host_.notifyPropertyChange({+ entity: entity as number,+ componentType,+ propertyName,+ oldValue,+ newValue,+ });+ }++ isPrefabInstance(entityId: number): boolean {+ const entity = this.host_.entityMap_.get(entityId);+ return entity?.prefab !== undefined;+ }++ collectDescendantIds(entityId: number): number[] {+ const result: number[] = [];+ const entityData = this.host_.entityMap_.get(entityId);+ if (!entityData) return result;+ for (const childId of entityData.children) {+ result.push(...this.collectDescendantIds(childId));+ result.push(childId);+ }+ return result;+ }+}diff --git a/editor/src/store/SelectionService.ts b/editor/src/store/SelectionService.tsnew file mode 100644index 000000000..705912188--- /dev/null+++ b/editor/src/store/SelectionService.ts@@ -0,0 +1,135 @@+import type { Entity } from 'esengine';+import type { EntityData } from '../types/SceneTypes';+import type { AssetSelection, DirtyFlag } from './EditorStore';++export interface SelectionHost {+ readonly state_: {+ selectedEntities: Set<number>;+ selectedAsset: AssetSelection | null;+ scene: { entities: EntityData[] };+ };+ readonly entityMap_: Map<number, EntityData>;+ notify(flag: DirtyFlag): void;+}++export class SelectionService {+ private host_: SelectionHost;+ private focusListeners_ = new Set<(entityId: number) => void>();++ constructor(host: SelectionHost) {+ this.host_ = host;+ }++ selectEntity(entity: Entity | null, mode: 'replace' | 'add' | 'toggle' = 'replace'): void {+ const sel = this.host_.state_.selectedEntities;+ const oldSize = sel.size;+ const oldSnapshot = new Set(sel);++ if (entity === null) {+ sel.clear();+ } else {+ const id = entity as number;+ if (mode === 'replace') {+ sel.clear();+ sel.add(id);+ } else if (mode === 'add') {+ sel.add(id);+ } else if (mode === 'toggle') {+ if (sel.has(id)) {+ sel.delete(id);+ } else {+ sel.add(id);+ }+ }+ }++ if (!this.setsEqual(oldSnapshot, sel)) {+ this.host_.state_.selectedAsset = null;+ this.host_.notify('selection');+ }+ }++ selectEntities(entities: number[]): void {+ const sel = this.host_.state_.selectedEntities;+ sel.clear();+ for (const id of entities) {+ sel.add(id);+ }+ this.host_.state_.selectedAsset = null;+ this.host_.notify('selection');+ }++ selectRange(fromEntity: number, toEntity: number): void {+ const flatList: number[] = [];+ const visited = new Set<number>();++ const traverse = (entityId: number | null) => {+ if (entityId === null) return;+ const entity = this.host_.entityMap_.get(entityId);+ if (!entity || visited.has(entityId)) return;+ visited.add(entityId);+ flatList.push(entityId);+ for (const childId of entity.children) {+ traverse(childId);+ }+ };++ for (const entity of this.host_.state_.scene.entities) {+ if (entity.parent === null) {+ traverse(entity.id);+ }+ }++ const fromIndex = flatList.indexOf(fromEntity);+ const toIndex = flatList.indexOf(toEntity);++ if (fromIndex === -1 || toIndex === -1) return;++ const start = Math.min(fromIndex, toIndex);+ const end = Math.max(fromIndex, toIndex);+ this.selectEntities(flatList.slice(start, end + 1));+ }++ selectAsset(asset: AssetSelection | null): void {+ this.host_.state_.selectedAsset = asset;+ this.host_.state_.selectedEntities.clear();+ this.host_.notify('selection');+ }++ getSelectedEntityData(): EntityData | null {+ const sel = this.host_.state_.selectedEntities;+ if (sel.size !== 1) return null;+ const id = sel.values().next().value as number;+ return this.host_.entityMap_.get(id) ?? null;+ }++ getSelectedEntitiesData(): EntityData[] {+ const result: EntityData[] = [];+ for (const id of this.host_.state_.selectedEntities) {+ const entity = this.host_.entityMap_.get(id);+ if (entity) {+ result.push(entity);+ }+ }+ return result;+ }++ focusEntity(entityId: number): void {+ for (const listener of this.focusListeners_) {+ listener(entityId);+ }+ }++ onFocusEntity(listener: (entityId: number) => void): () => void {+ this.focusListeners_.add(listener);+ return () => this.focusListeners_.delete(listener);+ }++ private setsEqual(a: Set<number>, b: Set<number>): boolean {+ if (a.size !== b.size) return false;+ for (const item of a) {+ if (!b.has(item)) return false;+ }+ return true;+ }+}diff --git a/editor/src/styles/base.css b/editor/src/styles/base.cssnew file mode 100644index 000000000..593526454--- /dev/null+++ b/editor/src/styles/base.css@@ -0,0 +1,607 @@+/* =============================================================================+ * Variables+ * ============================================================================= */++:root {+ --es-bg-primary: #1e1e1e;+ --es-bg-secondary: #252526;+ --es-bg-tertiary: #2d2d30;+ --es-bg-hover: #3e3e42;+ --es-border: #3c3c3c;+ --es-text-primary: #cccccc;+ --es-text-secondary: #8c8c8c;+ --es-accent: #0078d4;+ --es-accent-hover: #1084d8;+ --es-danger: #f44336;+ --es-success: #4caf50;+ --es-warning: #f0ad4e;+ --es-error: #d9534f;+ --es-input-bg: #2d2d2d;+ --es-text-disabled: #555555;+ --es-text-muted: #737373;+ --es-scrollbar-track: #1e1e1e;+ --es-scrollbar-thumb: #424242;+ --es-scrollbar-thumb-hover: #555555;+ --es-accent-gold: #d19a66;+ --es-prefab: #4fc1ff;+ --es-drag: #61afef;+ --es-selection-bg: rgba(209, 154, 102, 0.2);+ --es-radius-sm: 3px;+ --es-radius-md: 4px;+ --es-radius-lg: 6px;+ --es-font-xs: 10px;+ --es-font-sm: 11px;+ --es-font-md: 12px;+ --es-font-base: 13px;+ --es-font-lg: 14px;+}++*, *::before, *::after {+ box-sizing: border-box;+}++/* =============================================================================+ * Scrollbar+ * ============================================================================= */++::-webkit-scrollbar {+ width: 8px;+ height: 8px;+}++::-webkit-scrollbar-track {+ background: var(--es-scrollbar-track);+}++::-webkit-scrollbar-thumb {+ background: var(--es-scrollbar-thumb);+ border-radius: 4px;+}++::-webkit-scrollbar-thumb:hover {+ background: var(--es-scrollbar-thumb-hover);+}++::-webkit-scrollbar-corner {+ background: var(--es-scrollbar-track);+}++/* =============================================================================+ * SVG Icons+ * ============================================================================= */++.es-editor svg {+ display: inline-block;+ vertical-align: middle;+}++.es-btn-icon svg {+ stroke: var(--es-text-primary);+}++.es-btn-icon:hover svg {+ stroke: #e0e0e0;+}++.es-btn-icon.es-active {+ background: var(--es-accent);+ border-radius: 3px;+}++.es-btn-icon.es-active svg {+ stroke: white;+}++.es-hierarchy-visibility svg,+.es-hierarchy-expand svg,+.es-hierarchy-icon svg {+ stroke: var(--es-text-secondary);+}++.es-hierarchy-item.es-selected .es-hierarchy-icon svg {+ stroke: var(--es-accent-gold);+}++.es-btn-remove svg {+ stroke: var(--es-text-secondary);+}++.es-btn-remove:hover svg {+ stroke: var(--es-danger);+}++/* =============================================================================+ * Editor Layout+ * ============================================================================= */++.es-editor {+ display: flex;+ flex-direction: column;+ width: 100%;+ height: 100%;+ background: var(--es-bg-primary);+ color: var(--es-text-primary);+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ font-size: 13px;+}++/* =============================================================================+ * Common Elements+ * ============================================================================= */++.es-btn {+ padding: 4px 10px;+ background: var(--es-bg-tertiary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 11px;+ cursor: pointer;+ transition: background 0.15s;+}++.es-btn:hover:not(:disabled) {+ background: var(--es-bg-hover);+}++.es-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.es-btn-icon {+ padding: 2px 6px;+ min-width: 20px;+ cursor: pointer;+ transition: background 0.15s;+}++.es-btn-remove {+ background: transparent;+ border: none;+ color: var(--es-text-secondary);+ font-size: 16px;+}++.es-btn-remove:hover {+ color: var(--es-danger);+}++.es-btn-clear {+ background: transparent !important;+ border: none !important;+ opacity: 0.5;+}++.es-btn-clear:hover {+ opacity: 1;+}++.es-btn-clear svg {+ stroke: var(--es-text-secondary);+}++.es-btn-clear:hover svg {+ stroke: var(--es-danger);+}++.es-input {+ padding: 4px 6px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 11px;+ width: 100%;+}++.es-input:focus {+ outline: none;+ border-color: var(--es-accent);+}++.es-input-number {+ width: 100%;+ -moz-appearance: textfield;+}++.es-input-number::-webkit-outer-spin-button,+.es-input-number::-webkit-inner-spin-button {+ -webkit-appearance: none;+ margin: 0;+}++.es-validation-error {+ border-color: var(--es-danger) !important;+ animation: shake 0.3s;+}++@keyframes shake {+ 0%, 100% { transform: translateX(0); }+ 25% { transform: translateX(-4px); }+ 75% { transform: translateX(4px); }+}++.es-number-editor {+ display: flex;+ align-items: center;+ width: 100%;+ border: 1px solid var(--es-border);+ border-radius: 4px;+ overflow: hidden;+}++.es-number-editor .es-input-number {+ border: none;+ border-radius: 0;+}++.es-number-drag-label {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 16px;+ height: 24px;+ background: var(--es-input-bg);+ color: #666;+ font-size: 10px;+ cursor: ew-resize;+ user-select: none;+ border-right: 1px solid var(--es-border);+ letter-spacing: -2px;+}++.es-number-drag-label:hover {+ background: var(--es-bg-hover);+ color: #999;+}++.es-input-checkbox {+ width: 14px;+ height: 14px;+ margin: 0;+ cursor: pointer;+ accent-color: var(--es-accent-gold);+}++.es-input-select {+ width: 100%;+ cursor: pointer;+ appearance: none;+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23808080' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");+ background-repeat: no-repeat;+ background-position: right 8px center;+ padding-right: 28px;+}++/* =============================================================================+ * Vector Editors+ * ============================================================================= */++.es-vec-editor {+ display: flex;+ gap: 2px;+ width: 100%;+}++.es-vec-field {+ display: flex;+ align-items: center;+ flex: 1;+ min-width: 0;+ border: 1px solid var(--es-border);+}++.es-vec-label {+ width: 18px;+ height: 22px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 10px;+ font-weight: 600;+ color: #fff;+ background: var(--es-text-secondary);+ flex-shrink: 0;+ cursor: ew-resize;+ user-select: none;+}++.es-vec-field.es-vec-x .es-vec-label {+ background: #c94c4c;+}++.es-vec-field.es-vec-y .es-vec-label {+ background: #5cb85c;+}++.es-vec-field.es-vec-z .es-vec-label {+ background: #5bc0de;+}++.es-vec-field.es-vec-w .es-vec-label {+ background: #9b59b6;+}++.es-vec-field .es-input {+ flex: 1;+ min-width: 0;+ width: 100%;+ border: none;+ padding: 2px 4px;+ height: 22px;+ font-size: 11px;+ -moz-appearance: textfield;+}++.es-vec-field .es-input::-webkit-outer-spin-button,+.es-vec-field .es-input::-webkit-inner-spin-button {+ -webkit-appearance: none;+ margin: 0;+}++.es-vec-field .es-input:focus {+ outline: none;+ background: var(--es-bg-tertiary);+}++/* =============================================================================+ * Color Editor+ * ============================================================================= */++.es-color-editor {+ display: flex;+ align-items: center;+ gap: 4px;+ width: 100%;+}++.es-input-color {+ width: 32px;+ height: 22px;+ padding: 0;+ border: 1px solid var(--es-border);+ cursor: pointer;+ background: none;+}++.es-input-color::-webkit-color-swatch-wrapper {+ padding: 1px;+}++.es-input-color::-webkit-color-swatch {+ border: none;+}++.es-input-hex {+ flex: 2;+ min-width: 60px;+ font-family: monospace;+ font-size: 11px;+ text-transform: uppercase;+}++.es-input-alpha {+ flex: 1;+ min-width: 40px;+}++/* =============================================================================+ * Button Transition Editor+ * ============================================================================= */++.es-btn-transition-section {+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ overflow: hidden;+}++.es-btn-transition-header {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ background: var(--es-bg-tertiary);+ cursor: pointer;+ border-bottom: 1px solid transparent;+}++.es-btn-transition-section.es-expanded .es-btn-transition-header {+ border-bottom-color: var(--es-border);+}++.es-btn-transition-header:hover {+ background: var(--es-bg-hover);+}++.es-btn-transition-title {+ flex: 1;+ font-weight: 500;+ font-size: 11px;+}++.es-btn-transition-content {+ padding: 6px 8px;+}++.es-btn-transition-content .es-property-row {+ margin-bottom: 4px;+}++.es-btn-transition-content .es-property-row:last-child {+ margin-bottom: 0;+}++/* =============================================================================+ * Container Classes+ * ============================================================================= */++.es-hierarchy-container,+.es-inspector-container,+.es-sceneview-container {+ height: 100%;+}++.es-panel-container {+ width: 100%;+ height: 100%;+ overflow: hidden;+}++/* =============================================================================+ * Error Boundaries+ * ============================================================================= */++.es-error-fallback {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 40px;+ text-align: center;+ background: rgba(224, 108, 117, 0.05);+ border: 2px dashed rgba(224, 108, 117, 0.3);+ border-radius: 8px;+ margin: 20px;+ min-height: 200px;+}++.es-error-fallback-icon {+ color: #e06c75;+ margin-bottom: 16px;+}++.es-error-fallback-title {+ font-size: 18px;+ font-weight: 600;+ margin: 0 0 8px 0;+ color: #e06c75;+}++.es-error-fallback-message {+ font-size: 14px;+ margin: 0 0 16px 0;+ color: var(--es-text-secondary);+ max-width: 600px;+}++.es-error-fallback-details {+ margin: 16px 0;+ width: 100%;+ max-width: 700px;+ text-align: left;+}++.es-error-fallback-details summary {+ cursor: pointer;+ padding: 8px 12px;+ background: var(--es-bg-secondary);+ border-radius: 4px;+ font-size: 12px;+ color: var(--es-text-secondary);+ user-select: none;+}++.es-error-fallback-details summary:hover {+ background: var(--es-bg-tertiary);+}++.es-error-fallback-stack {+ background: var(--es-bg-tertiary);+ padding: 12px;+ border-radius: 4px;+ font-size: 11px;+ font-family: 'Consolas', 'Monaco', monospace;+ overflow-x: auto;+ max-height: 200px;+ overflow-y: auto;+ margin-top: 8px;+ color: var(--es-text-primary);+ white-space: pre-wrap;+ word-break: break-all;+}++.es-error-fallback-actions {+ display: flex;+ gap: 8px;+ margin-top: 16px;+}++.es-hidden {+ display: none !important;+}++.es-muted {+ color: var(--es-text-secondary);+ font-size: 11px;+ padding: 8px;+}++/* =============================================================================+ * Focus Visible+ * ============================================================================= */++.es-btn:focus-visible,+.es-btn-icon:focus-visible,+.es-gizmo-btn:focus-visible,+.es-menu-trigger:focus-visible,+.es-menu-item:focus-visible,+.es-context-menu-item:focus-visible,+.es-input:focus-visible,+.es-input-checkbox:focus-visible,+.es-statusbar-btn:focus-visible {+ outline: 2px solid var(--es-accent);+ outline-offset: 2px;+}++/* =============================================================================+ * Active / Pressed States+ * ============================================================================= */++.es-btn:active:not(:disabled) {+ background: var(--es-bg-primary);+}++.es-btn-icon:active {+ background: var(--es-bg-primary);+}++.es-gizmo-btn:active {+ background: var(--es-bg-primary);+}++/* =============================================================================+ * Splitter+ * ============================================================================= */++.es-splitter {+ background: var(--es-border);+ flex-shrink: 0;+ transition: background 0.15s;+}++.es-splitter:hover {+ background: var(--es-accent);+}++.es-splitter-horizontal {+ width: 100%;+ height: 4px;+ cursor: ns-resize;+}++.es-splitter-vertical {+ width: 4px;+ height: 100%;+ cursor: ew-resize;+}++/* =============================================================================+ * Reduced Motion+ * ============================================================================= */++@media (prefers-reduced-motion: reduce) {+ *, *::before, *::after {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ }+}diff --git a/editor/src/styles/builder.css b/editor/src/styles/builder.cssnew file mode 100644index 000000000..03d61afd8--- /dev/null+++ b/editor/src/styles/builder.css@@ -0,0 +1,1643 @@+/* =============================================================================+ * Build Settings Dialog+ * ============================================================================= */++.es-build-dialog {+ width: 90%;+ max-width: 800px;+ max-height: 80vh;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 6px;+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++.es-build-toolbar {+ display: flex;+ padding: 8px 12px;+ border-bottom: 1px solid var(--es-border);+ background: var(--es-bg-tertiary);+}++.es-build-toolbar .es-btn {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 4px 10px;+ font-size: 12px;+}++.es-build-body {+ display: flex;+ flex: 1;+ min-height: 400px;+ max-height: 60vh;+ overflow: hidden;+}++.es-build-sidebar {+ width: 200px;+ flex-shrink: 0;+ background: var(--es-bg-primary);+ border-right: 1px solid var(--es-border);+ overflow-y: auto;+ padding: 8px 0;+}++.es-build-section-title {+ font-size: 11px;+ font-weight: 600;+ color: var(--es-text-secondary);+ text-transform: uppercase;+ padding: 8px 12px 4px;+ letter-spacing: 0.5px;+}++.es-build-platform {+ padding: 8px 12px;+ display: flex;+ align-items: center;+ gap: 8px;+ cursor: pointer;+ color: var(--es-text-primary);+ transition: background 0.15s;+}++.es-build-platform:hover {+ background: var(--es-bg-hover);+}++.es-build-platform.es-active {+ background: var(--es-bg-tertiary);+}++.es-build-platform-header {+ display: flex;+ align-items: center;+ gap: 8px;+ flex: 1;+}++.es-build-badge {+ font-size: 10px;+ padding: 2px 6px;+ background: var(--es-accent);+ color: white;+ border-radius: 3px;+ margin-left: auto;+}++.es-build-config-item {+ position: relative;+ padding: 6px 12px 6px 32px;+ display: flex;+ align-items: center;+ gap: 8px;+ cursor: pointer;+ color: var(--es-text-secondary);+ font-size: 12px;+ transition: background 0.15s, color 0.15s;+}++.es-build-config-item:hover {+ background: var(--es-bg-hover);+ color: var(--es-text-primary);+}++.es-build-config-item.es-active {+ background: var(--es-bg-tertiary);+ color: var(--es-text-primary);+}++.es-build-config-item.es-active::before {+ content: '';+ position: absolute;+ left: 0;+ width: 3px;+ top: 0;+ bottom: 0;+ background: var(--es-accent);+}++.es-build-config-name {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-build-config-delete {+ opacity: 0;+ transition: opacity 0.15s;+ color: var(--es-text-secondary);+ padding: 2px;+}++.es-build-config-item:hover .es-build-config-delete {+ opacity: 1;+}++.es-build-config-delete:hover {+ color: var(--es-danger);+}++.es-build-detail {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ overflow-y: auto;+ padding: 16px;+}++.es-build-detail-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding-bottom: 16px;+ border-bottom: 1px solid var(--es-border);+ margin-bottom: 16px;+}++.es-build-detail-title h3 {+ margin: 0;+ font-size: 16px;+ font-weight: 600;+ color: var(--es-text-primary);+}++.es-build-detail-platform {+ font-size: 12px;+ color: var(--es-text-secondary);+}++.es-build-detail-actions {+ display: flex;+ gap: 8px;+}++.es-build-detail-actions .es-btn {+ padding: 6px 12px;+ font-size: 12px;+}++.es-build-detail-actions .es-btn-primary {+ display: flex;+ align-items: center;+ gap: 6px;+}++.es-build-detail-content {+ display: flex;+ flex-direction: column;+ gap: 24px;+}++.es-build-data-section h4,+.es-build-settings-section h4 {+ margin: 0 0 12px;+ font-size: 12px;+ font-weight: 600;+ color: var(--es-text-secondary);+ text-transform: uppercase;+ letter-spacing: 0.5px;+}++.es-build-collapse {+ border: 1px solid var(--es-border);+ border-radius: 4px;+ overflow: hidden;+ margin-bottom: 8px;+}++.es-build-collapse-header {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 8px 12px;+ background: var(--es-bg-tertiary);+ cursor: pointer;+ font-size: 12px;+ font-weight: 500;+ color: var(--es-text-primary);+ transition: background 0.15s;+}++.es-build-collapse-header:hover {+ background: var(--es-bg-hover);+}++.es-build-collapse-content {+ display: none;+ padding: 12px;+ background: var(--es-bg-primary);+}++.es-build-collapse.es-expanded .es-build-collapse-content {+ display: block;+}++.es-build-scene-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+ margin-bottom: 8px;+}++.es-build-scene-item {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 8px;+ background: var(--es-bg-secondary);+ border-radius: 3px;+ font-size: 12px;+}++.es-build-scene-item input[type="checkbox"] {+ flex-shrink: 0;+}++.es-build-scene-item span {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--es-text-primary);+}++.es-build-scene-item .es-btn-icon {+ opacity: 0;+ transition: opacity 0.15s;+}++.es-build-scene-item:hover .es-btn-icon {+ opacity: 1;+}++.es-build-empty-list {+ text-align: center;+ color: var(--es-text-secondary);+ font-size: 12px;+ padding: 12px;+}++.es-build-define-list {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ margin-bottom: 8px;+}++.es-build-define-item {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 4px 8px;+ background: var(--es-bg-secondary);+ border-radius: 3px;+ font-size: 11px;+ font-family: monospace;+ color: var(--es-accent);+}++.es-build-define-item .es-btn-icon {+ padding: 2px;+ opacity: 0.6;+}++.es-build-define-item:hover .es-btn-icon {+ opacity: 1;+}++.es-build-define-add {+ display: flex;+ gap: 6px;+}++.es-build-define-add .es-input {+ flex: 1;+ min-width: 0;+ padding: 4px 8px;+ font-size: 12px;+}++.es-build-field {+ margin-bottom: 12px;+}++.es-build-field:last-child {+ margin-bottom: 0;+}++.es-build-field label {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 12px;+ color: var(--es-text-primary);+ cursor: pointer;+}++.es-build-field input[type="checkbox"] {+ width: 14px;+ height: 14px;+}++.es-build-label {+ display: block;+ margin-bottom: 4px;+ font-size: 12px;+ color: var(--es-text-secondary);+}++.es-build-path-row {+ display: flex;+ gap: 6px;+}++.es-build-path-row .es-input {+ flex: 1;+ min-width: 0;+}++.es-build-path-row .es-btn {+ flex-shrink: 0;+ padding: 6px 10px;+}++.es-build-hint {+ margin-top: 4px;+ font-size: 11px;+ color: var(--es-text-muted);+}++.es-build-empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ height: 200px;+ color: var(--es-text-secondary);+ text-align: center;+}++.es-build-empty p {+ margin: 4px 0;+ font-size: 13px;+}++.es-build-add-dialog {+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: rgba(0, 0, 0, 0.5);+ display: flex;+ align-items: center;+ justify-content: center;+}++.es-build-dialog .es-input {+ padding: 6px 10px;+ border-radius: 3px;+ font-size: 12px;+}++.es-build-dialog .es-select {+ width: 100%;+ padding: 6px 10px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ border-radius: 3px;+ color: var(--es-text-primary);+ font-size: 12px;+ cursor: pointer;+}++.es-build-dialog .es-select:focus {+ outline: none;+ border-color: var(--es-accent);+}++.es-build-dialog .es-btn {+ border-radius: 3px;+}++.es-build-dialog .es-btn-primary {+ background: var(--es-accent);+ border-color: var(--es-accent);+ color: white;+}++.es-build-dialog .es-btn-primary:hover {+ background: #3d9ee0;+ border-color: #3d9ee0;+}++.es-btn-link {+ background: none;+ border: none;+ color: var(--es-accent);+ font-size: 12px;+ cursor: pointer;+ padding: 4px 0;+ text-decoration: underline;+}++.es-btn-link:hover {+ color: #3d9ee0;+}++.es-build-dialog .es-btn-icon {+ background: transparent;+ border: none;+ color: var(--es-text-secondary);+ padding: 4px;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 3px;+}++.es-build-dialog .es-btn-icon:hover {+ background: var(--es-bg-hover);+ color: var(--es-text-primary);+}++.es-build-define-add .es-btn-icon {+ background: var(--es-bg-tertiary);+ border: 1px solid var(--es-border);+}++.es-build-define-add .es-btn-icon:hover {+ background: var(--es-bg-hover);+}++/* =============================================================================+ * Toast Notifications+ * ============================================================================= */++.es-toast-container {+ position: fixed;+ bottom: 44px;+ right: 20px;+ z-index: 10000;+ display: flex;+ flex-direction: column-reverse;+ gap: 10px;+ pointer-events: none;+}++.es-toast {+ display: flex;+ align-items: flex-start;+ gap: 12px;+ min-width: 320px;+ max-width: 420px;+ padding: 14px 16px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 6px;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);+ pointer-events: auto;+ transform: translateX(100%);+ opacity: 0;+ transition: transform 0.2s ease, opacity 0.2s ease;+}++.es-toast-show {+ transform: translateX(0);+ opacity: 1;+}++.es-toast-hide {+ transform: translateX(100%);+ opacity: 0;+}++.es-toast-icon {+ flex-shrink: 0;+ width: 24px;+ height: 24px;+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--es-text-secondary);+}++.es-toast-success .es-toast-icon {+ color: var(--es-success, #4caf50);+}++.es-toast-error .es-toast-icon {+ color: var(--es-danger, #f44336);+}++.es-toast-progress .es-toast-icon {+ color: var(--es-accent, #0078d4);+}++.es-toast-content {+ flex: 1;+ min-width: 0;+}++.es-toast-title {+ font-size: 13px;+ font-weight: 500;+ color: var(--es-text-primary);+ margin-bottom: 2px;+}++.es-toast-message {+ font-size: 12px;+ color: var(--es-text-secondary);+ margin-top: 4px;+ word-break: break-word;+}++.es-toast-close {+ flex-shrink: 0;+ width: 20px;+ height: 20px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: none;+ border: none;+ color: var(--es-text-muted);+ cursor: pointer;+ border-radius: 3px;+ transition: background 0.15s, color 0.15s;+}++.es-toast-close:hover {+ background: var(--es-bg-hover);+ color: var(--es-text-primary);+}++.es-toast-progress-bar {+ margin-top: 10px;+ height: 4px;+ background: var(--es-bg-tertiary);+ border-radius: 2px;+ overflow: hidden;+}++.es-toast-progress-fill {+ height: 100%;+ background: var(--es-accent, #0078d4);+ border-radius: 2px;+ transition: width 0.3s ease;+}++.es-toast-spinner {+ width: 18px;+ height: 18px;+ border: 2px solid var(--es-bg-tertiary);+ border-top-color: var(--es-accent, #0078d4);+ border-radius: 50%;+ animation: es-toast-spin 0.8s linear infinite;+}++@keyframes es-toast-spin {+ to { transform: rotate(360deg); }+}++.es-toast-actions {+ display: flex;+ gap: 8px;+ margin-top: 12px;+}++.es-toast-btn {+ padding: 6px 12px;+ font-size: 12px;+ border: 1px solid var(--es-border);+ border-radius: 4px;+ background: var(--es-bg-tertiary);+ color: var(--es-text-primary);+ cursor: pointer;+ transition: background 0.15s, border-color 0.15s;+}++.es-toast-btn:hover {+ background: var(--es-bg-hover);+}++.es-toast-btn-primary {+ background: var(--es-accent, #0078d4);+ border-color: var(--es-accent, #0078d4);+ color: white;+}++.es-toast-btn-primary:hover {+ background: #3d9ee0;+ border-color: #3d9ee0;+}++/* =============================================================================+ * Output Panel+ * ============================================================================= */++.es-output-container {+ height: 100%;+}++.es-output-panel {+ display: flex;+ flex-direction: column;+ height: 100%;+ background: var(--es-bg-primary);+}++.es-output-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 6px 12px;+ background: var(--es-bg-secondary);+ border-bottom: 1px solid var(--es-border);+}++.es-output-title {+ display: flex;+ align-items: center;+ gap: 6px;+ font-weight: 600;+ font-size: 12px;+}++.es-output-title svg {+ stroke: var(--es-text-secondary);+}++.es-output-actions {+ display: flex;+ gap: 4px;+}++.es-output-content {+ flex: 1;+ overflow: auto;+ padding: 8px;+ font-family: 'Consolas', 'Monaco', monospace;+ font-size: 12px;+ user-select: text;+ cursor: text;+}++.es-output-empty {+ color: var(--es-text-secondary);+ text-align: center;+ padding: 20px;+}++/* =============================================================================+ * Output Panel Lines+ * ============================================================================= */++.es-output-line {+ font-family: 'Consolas', 'Monaco', monospace;+ font-size: 12px;+ line-height: 1.5;+ white-space: pre-wrap;+ word-break: break-all;+}++.es-output-badge {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ min-width: 18px;+ height: 16px;+ padding: 0 5px;+ margin-right: 6px;+ border-radius: 8px;+ background: var(--es-accent);+ color: #fff;+ font-size: 10px;+ font-weight: 600;+ line-height: 1;+ vertical-align: middle;+}++.es-output-command {+ color: var(--es-accent);+ font-weight: 500;+ margin-top: 8px;+}++.es-output-stdout {+ color: var(--es-text-primary);+}++.es-output-stderr {+ color: #e5c07b;+}++.es-output-error {+ color: var(--es-danger);+}++.es-output-success {+ color: var(--es-success);+}++/* =============================================================================+ * Build Settings Dialog - Three Column Layout+ * ============================================================================= */++.es-build-dialog-wide {+ max-width: 1000px;+}++.es-build-body-three-col {+ display: flex;+ flex: 1;+ min-height: 450px;+ max-height: 65vh;+ overflow: hidden;+}++.es-build-body-three-col .es-build-sidebar {+ width: 180px;+ min-width: 160px;+}++.es-build-body-three-col .es-build-detail {+ flex: 1;+ min-width: 300px;+ border-right: 1px solid var(--es-border);+}++.es-build-body-three-col .es-build-output {+ width: 220px;+ min-width: 180px;+ flex-shrink: 0;+ display: flex;+ flex-direction: column;+ background: var(--es-bg-primary);+ padding: 12px;+ overflow-y: auto;+}++.es-build-toolbar-left,+.es-build-toolbar-right {+ display: flex;+ align-items: center;+ gap: 6px;+}++.es-build-toolbar-left {+ flex: 1;+}++.es-build-output-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 12px;+}++.es-build-output-latest {+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 4px;+ padding: 12px;+ margin-bottom: 16px;+}++.es-build-output-empty {+ text-align: center;+ color: var(--es-text-secondary);+ font-size: 12px;+ padding: 24px 8px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 4px;+}++.es-build-output-stat {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 8px;+ font-size: 12px;+}++.es-build-output-stat:last-child {+ margin-bottom: 0;+}++.es-build-output-label {+ color: var(--es-text-secondary);+}++.es-build-output-value {+ color: var(--es-text-primary);+ font-weight: 500;+}++.es-build-output-actions {+ display: flex;+ gap: 8px;+ margin-top: 12px;+ padding-top: 12px;+ border-top: 1px solid var(--es-border);+}++.es-btn-small {+ padding: 4px 8px;+ font-size: 11px;+ display: flex;+ align-items: center;+ gap: 4px;+}++/* Build Status Indicators */+.es-build-status-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ flex-shrink: 0;+}++.es-build-status-dot.es-build-status-success {+ background: var(--es-success);+}++.es-build-status-dot.es-build-status-failed {+ background: var(--es-danger);+}++.es-build-status-dot.es-build-status-cancelled {+ background: var(--es-text-secondary);+}++.es-build-status-success {+ color: var(--es-success);+}++.es-build-status-failed {+ color: var(--es-danger);+}++.es-build-status-cancelled {+ color: var(--es-text-secondary);+}++/* Build History */+.es-build-history {+ margin-top: 8px;+}++.es-build-history-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+ margin-top: 8px;+}++.es-build-history-item {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 8px;+ background: var(--es-bg-secondary);+ border-radius: 3px;+ font-size: 11px;+}++.es-build-history-icon {+ font-size: 12px;+}++.es-build-history-time {+ flex: 1;+ color: var(--es-text-primary);+}++.es-build-history-duration {+ color: var(--es-text-secondary);+}++/* Config Name Input */+.es-build-name-input {+ background: transparent;+ border: 1px solid transparent;+ color: var(--es-text-primary);+ font-size: 16px;+ font-weight: 600;+ padding: 4px 8px;+ border-radius: 3px;+ width: 200px;+}++.es-build-name-input:hover {+ background: var(--es-bg-tertiary);+}++.es-build-name-input:focus {+ outline: none;+ background: var(--es-bg-primary);+ border-color: var(--es-accent);+}++/* Collapse Count Badge */+.es-build-collapse-count {+ margin-left: auto;+ font-size: 10px;+ background: var(--es-bg-hover);+ color: var(--es-text-secondary);+ padding: 2px 6px;+ border-radius: 10px;+}++/* Build Templates */+.es-build-templates-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ max-height: 400px;+ overflow-y: auto;+}++.es-build-template-item {+ padding: 12px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ border-radius: 4px;+ cursor: pointer;+ transition: all 0.15s;+}++.es-build-template-item:hover {+ border-color: var(--es-accent);+ background: var(--es-bg-tertiary);+}++.es-build-template-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 4px;+}++.es-build-template-name {+ font-size: 13px;+ font-weight: 500;+ color: var(--es-text-primary);+}++.es-build-template-platform {+ font-size: 10px;+ padding: 2px 6px;+ background: var(--es-bg-tertiary);+ color: var(--es-text-secondary);+ border-radius: 3px;+ text-transform: uppercase;+}++.es-build-template-desc {+ font-size: 11px;+ color: var(--es-text-secondary);+}++/* =============================================================================+ * Build Progress Panel+ * ============================================================================= */++.build-progress-panel {+ position: fixed;+ bottom: 20px;+ right: 20px;+ width: 420px;+ max-height: 400px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 8px;+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);+ display: none;+ flex-direction: column;+ z-index: 10000;+ overflow: hidden;+}++.build-progress-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 12px 16px;+ background: var(--es-bg-tertiary);+ border-bottom: 1px solid var(--es-border);+}++.build-progress-title {+ font-size: 13px;+ font-weight: 500;+ color: var(--es-text-primary);+}++.build-progress-close {+ background: none;+ border: none;+ color: var(--es-text-secondary);+ font-size: 18px;+ line-height: 1;+ cursor: pointer;+ padding: 0 4px;+}++.build-progress-close:hover {+ color: var(--es-text-primary);+}++.build-progress-phase-section {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 12px 16px 8px;+}++.build-progress-phase {+ font-size: 14px;+ font-weight: 500;+ color: var(--es-accent);+}++.build-progress-phase.build-progress-success {+ color: var(--es-success);+}++.build-progress-phase.build-progress-error {+ color: var(--es-danger);+}++.build-progress-time {+ font-size: 11px;+ color: var(--es-text-secondary);+}++.build-progress-bar-section {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 0 16px 8px;+}++.build-progress-bar-track {+ flex: 1;+ height: 6px;+ background: var(--es-bg-tertiary);+ border-radius: 3px;+ overflow: hidden;+}++.build-progress-bar-fill {+ height: 100%;+ background: var(--es-accent);+ border-radius: 3px;+ transition: width 0.2s ease;+ width: 0%;+}++.build-progress-bar-fill.build-progress-bar-error {+ background: var(--es-danger);+}++.build-progress-percent {+ font-size: 12px;+ font-weight: 500;+ color: var(--es-text-primary);+ min-width: 36px;+ text-align: right;+}++.build-progress-task {+ padding: 0 16px 12px;+ font-size: 11px;+ color: var(--es-text-secondary);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.build-progress-logs {+ flex: 1;+ min-height: 120px;+ max-height: 180px;+ overflow-y: auto;+ background: var(--es-bg-primary);+ margin: 0 12px;+ border-radius: 4px;+ font-family: 'SF Mono', 'Monaco', 'Menlo', monospace;+ font-size: 11px;+ line-height: 1.5;+}++.build-progress-log-line {+ padding: 2px 8px;+ color: var(--es-text-secondary);+ border-bottom: 1px solid var(--es-bg-secondary);+}++.build-progress-log-line:last-child {+ border-bottom: none;+}++.build-progress-log-line .log-time {+ color: var(--es-text-secondary);+ opacity: 0.6;+ margin-right: 4px;+}++.build-progress-log-line.progress-log-info {+ color: var(--es-text-primary);+}++.build-progress-log-line.progress-log-warn {+ color: #e6a700;+}++.build-progress-log-line.progress-log-error {+ color: var(--es-danger);+}++.build-progress-log-line.progress-log-debug {+ color: var(--es-text-secondary);+ opacity: 0.7;+}++.build-progress-footer {+ display: flex;+ justify-content: flex-end;+ padding: 12px 16px;+ border-top: 1px solid var(--es-border);+}++.build-progress-cancel-btn {+ padding: 6px 16px;+ background: var(--es-bg-tertiary);+ border: 1px solid var(--es-border);+ border-radius: 4px;+ color: var(--es-text-primary);+ font-size: 12px;+ cursor: pointer;+}++.build-progress-cancel-btn:hover:not(:disabled) {+ background: var(--es-bg-hover);+}++.build-progress-cancel-btn:disabled {+ opacity: 0.5;+ cursor: default;+}++/* =============================================================================+ * Addressable Panel+ * ============================================================================= */++.es-addressable-panel {+ display: flex;+ flex-direction: column;+ height: 100%;+ background: var(--es-bg-primary);+}++.es-addressable-body {+ display: flex;+ flex: 1;+ overflow: hidden;+}++.es-addressable-sidebar {+ width: 180px;+ min-width: 140px;+ background: var(--es-bg-secondary);+ border-right: 1px solid var(--es-border);+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++.es-addressable-main {+ flex: 1;+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++.es-addressable-sidebar-section {+ display: flex;+ flex-direction: column;+ min-height: 0;+}++.es-addressable-sidebar-section + .es-addressable-sidebar-section {+ border-top: 1px solid var(--es-border);+}++.es-sidebar-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px;+ font-size: 10px;+ text-transform: uppercase;+ color: var(--es-text-secondary);+ user-select: none;+}++.es-sidebar-header .es-btn-icon {+ padding: 0;+ min-width: 16px;+ height: 16px;+ display: flex;+ align-items: center;+ justify-content: center;+}++.es-addr-group-list,+.es-addr-label-list {+ overflow-y: auto;+ flex: 1;+ min-height: 0;+}++.es-addr-group-item {+ display: flex;+ align-items: center;+ gap: 6px;+ height: 28px;+ padding: 0 12px 0 8px;+ cursor: pointer;+ user-select: none;+ font-size: 12px;+ border-left: 2px solid transparent;+}++.es-addr-group-item:hover {+ background: var(--es-bg-hover);+}++.es-addr-group-item.es-selected {+ background: rgba(209, 154, 102, 0.25);+ border-left-color: var(--es-accent-gold);+ color: var(--es-accent-gold);+}++.es-addr-group-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: var(--es-accent);+ flex-shrink: 0;+}++.es-addr-group-item.es-selected .es-addr-group-dot {+ background: var(--es-accent-gold);+}++.es-addr-group-count {+ margin-left: auto;+ font-size: 10px;+ color: var(--es-text-secondary);+ background: var(--es-bg-tertiary);+ padding: 1px 6px;+ border-radius: 8px;+}++.es-addr-label-item {+ height: 24px;+ display: flex;+ align-items: center;+ padding: 0 8px;+}++.es-addr-label-item:hover {+ background: var(--es-bg-hover);+}++.es-addr-label-check {+ display: flex;+ align-items: center;+ gap: 6px;+ font-size: 11px;+ cursor: pointer;+ user-select: none;+}++.es-addr-label-check input[type="checkbox"] {+ accent-color: var(--es-accent-gold);+}++.es-addressable-toolbar {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 8px;+ background: var(--es-bg-secondary);+ border-bottom: 1px solid var(--es-border);+}++.es-addr-search {+ flex: 1;+}++.es-addr-asset-table {+ display: flex;+ flex-direction: column;+ flex: 1;+ overflow: hidden;+}++.es-addr-table-header {+ display: flex;+ align-items: center;+ height: 28px;+ padding: 0 12px 0 8px;+ background: var(--es-bg-secondary);+ border-bottom: 1px solid var(--es-border);+ font-size: 11px;+ color: var(--es-text-secondary);+ user-select: none;+}++.es-addr-table-header [data-col] {+ cursor: pointer;+}++.es-addr-table-header [data-col]:hover {+ color: var(--es-text-primary);+}++.es-addr-table-header [data-col].es-sorted {+ color: var(--es-text-primary);+}++.es-addr-table-body {+ flex: 1;+ overflow-y: auto;+}++.es-addr-table-row {+ display: flex;+ align-items: center;+ height: 28px;+ padding: 0 12px 0 8px;+ font-size: 12px;+ cursor: default;+}++.es-addr-table-row:hover {+ background: var(--es-bg-hover);+}++.es-addr-table-row:nth-child(even) {+ background: rgba(255, 255, 255, 0.02);+}++.es-addr-table-row:nth-child(even):hover {+ background: var(--es-bg-hover);+}++.es-addr-table-row.es-selected {+ background: var(--es-selection-bg);+}++.es-addr-table-row.es-selected .es-addr-col-name {+ color: var(--es-accent-gold);+}++.es-addr-table-row:active {+ background: rgba(255, 255, 255, 0.05);+}++.es-addr-col-name {+ flex: 2;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-addr-col-address {+ flex: 2;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-addr-col-labels {+ flex: 1.5;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-addr-col-type {+ width: 80px;+ flex-shrink: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-addr-col-size {+ width: 70px;+ flex-shrink: 0;+ text-align: right;+}++.es-addr-sort-icon {+ margin-left: 2px;+ font-size: 9px;+}++.es-addr-empty {+ display: flex;+ align-items: center;+ justify-content: center;+ flex: 1;+ color: var(--es-text-secondary);+ font-size: 12px;+ padding: 24px;+}++.es-addr-tag {+ display: inline-block;+ padding: 0 5px;+ margin-right: 3px;+ border-radius: 3px;+ font-size: 10px;+ background: color-mix(in srgb, var(--tag-color) 20%, transparent);+ color: var(--tag-color);+ line-height: 16px;+}++.es-addr-label-toggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 2px 6px;+ margin: 1px 3px 1px 0;+ border-radius: 3px;+ font-size: 11px;+ cursor: pointer;+ user-select: none;+ background: color-mix(in srgb, var(--tag-color) 10%, transparent);+ color: var(--es-text-secondary);+ transition: background 0.1s;+}++.es-addr-label-toggle:has(input:checked) {+ background: color-mix(in srgb, var(--tag-color) 25%, transparent);+ color: var(--tag-color);+}++.es-addr-label-toggle input[type="checkbox"] {+ width: 12px;+ height: 12px;+ accent-color: var(--tag-color);+}++.es-addr-inspector-labels {+ display: flex;+ flex-wrap: wrap;+ gap: 0;+}++.es-addr-label-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ display: inline-block;+ flex-shrink: 0;+}++.es-addr-table-row[draggable="true"] { cursor: grab; }+.es-addr-table-row.es-dragging { opacity: 0.5; }++.es-addr-group-item.es-drag-over {+ background: rgba(97, 175, 239, 0.25);+ border-left-color: var(--es-drag);+}++.es-addr-config-toggle {+ padding: 6px 8px;+ font-size: 10px;+ color: var(--es-text-secondary);+ cursor: pointer;+ user-select: none;+ border-top: 1px solid var(--es-border);+}++.es-addr-config-toggle:hover {+ color: var(--es-text-primary);+}++.es-addr-group-config-body {+ padding: 4px 8px 8px;+}++.es-addr-config-field {+ display: flex;+ flex-direction: column;+ gap: 2px;+ margin-bottom: 6px;+}++.es-addr-config-label {+ color: var(--es-text-secondary);+ font-size: 10px;+ text-transform: uppercase;+}++.es-addr-config-field .es-input {+ font-size: 11px;+ height: 22px;+}++.es-addr-include-list {+ font-size: 11px;+}++.es-addr-include-item {+ padding: 2px 0;+ color: var(--es-text-primary);+ font-family: monospace;+ font-size: 10px;+}++.es-addr-unreferenced {+ border-top: 1px solid var(--es-border);+ background: var(--es-bg-secondary);+ max-height: 200px;+ overflow-y: auto;+}++.es-addr-unreferenced-header {+ padding: 6px 12px;+ font-size: 11px;+ font-weight: 600;+ color: #e06c75;+ border-bottom: 1px solid var(--es-border);+}++.es-addr-unreferenced-list {+ padding: 0;+}++.es-addr-unreferenced-row {+ display: flex;+ align-items: center;+ height: 24px;+ padding: 0 12px 0 8px;+ font-size: 11px;+ cursor: default;+}++.es-addr-unreferenced-row:hover {+ background: var(--es-bg-hover);+}++.es-addr-unreferenced-row .es-addr-col-name {+ flex: 2;+}++.es-addr-unreferenced-row .es-addr-col-type {+ width: 60px;+}++.es-addr-unreferenced-row .es-addr-col-size {+ width: 60px;+}++.es-addressable-status {+ padding: 6px 12px;+ font-size: 11px;+ color: var(--es-text-secondary);+ background: var(--es-bg-secondary);+ border-top: 1px solid var(--es-border);+}++.es-addressable-window {+ width: 900px;+ height: 600px;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ resize: both;+ min-width: 600px;+ min-height: 400px;+}+.es-addressable-window .es-addressable-panel > .es-panel-header {+ display: none;+}diff --git a/editor/src/styles/content-browser.css b/editor/src/styles/content-browser.cssnew file mode 100644index 000000000..cb856c972--- /dev/null+++ b/editor/src/styles/content-browser.css@@ -0,0 +1,472 @@+/* =============================================================================+ * Content Browser+ * ============================================================================= */++.es-content-browser {+ display: flex;+ flex-direction: column;+ height: 100%;+ background: var(--es-bg-primary);+}++.es-content-browser-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 6px 12px;+ background: var(--es-bg-secondary);+ border-bottom: 1px solid var(--es-border);+}++.es-content-browser-title {+ display: flex;+ align-items: center;+ gap: 6px;+ font-weight: 600;+ font-size: 12px;+}++.es-content-browser-title svg {+ stroke: var(--es-text-secondary);+}++.es-content-browser-actions {+ display: flex;+ gap: 4px;+}++.es-content-browser-body {+ display: flex;+ flex: 1;+ overflow: hidden;+}++.es-content-browser-tree {+ width: 160px;+ min-width: 120px;+ background: var(--es-bg-secondary);+ border-right: 1px solid var(--es-border);+ overflow: auto;+ padding: 4px 0;+}++.es-content-browser-main {+ flex: 1;+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++.es-content-browser-toolbar {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 8px;+ background: var(--es-bg-secondary);+ border-bottom: 1px solid var(--es-border);+}++.es-content-breadcrumb {+ display: flex;+ align-items: center;+ flex: 1;+ min-width: 0;+ overflow: hidden;+}++.es-breadcrumb-item {+ color: var(--es-text-secondary);+ cursor: pointer;+ padding: 2px 4px;+ border-radius: 3px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ font-size: 12px;+}++.es-breadcrumb-item:hover {+ color: var(--es-text-primary);+ background: var(--es-bg-hover);+}++.es-breadcrumb-item.es-active {+ color: var(--es-text-primary);+ cursor: default;+}++.es-breadcrumb-item.es-active:hover {+ background: transparent;+}++.es-breadcrumb-separator {+ color: var(--es-text-muted);+ display: flex;+ align-items: center;+ flex-shrink: 0;+}++.es-content-search {+ max-width: 200px;+ flex-shrink: 0;+}++.es-content-browser-grid {+ flex: 1;+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ padding: 12px;+ overflow: auto;+ align-content: flex-start;+}++.es-content-browser-footer {+ padding: 6px 12px;+ font-size: 11px;+ color: var(--es-text-secondary);+ background: var(--es-bg-secondary);+ border-top: 1px solid var(--es-border);+}++/* Folder Tree */+.es-folder-item {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 4px 8px;+ cursor: pointer;+ user-select: none;+ transition: background 0.15s;+}++.es-folder-item:hover {+ background: var(--es-bg-hover);+}++.es-folder-item.es-selected {+ background: var(--es-selection-bg);+}++.es-folder-item.es-selected .es-folder-name {+ color: var(--es-accent-gold);+}++.es-folder-expand {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 14px;+}++.es-folder-expand svg {+ stroke: var(--es-text-secondary);+}++.es-folder-spacer {+ width: 14px;+}++.es-folder-icon {+ display: inline-flex;+ align-items: center;+}++.es-folder-icon svg {+ stroke: #e8c36a;+}++.es-folder-name {+ font-size: 12px;+}++/* Asset Grid */+.es-asset-item {+ display: flex;+ flex-direction: column;+ align-items: center;+ width: 72px;+ padding: 8px;+ border-radius: 4px;+ cursor: pointer;+ user-select: none;+ transition: background 0.15s;+}++.es-asset-item:hover {+ background: var(--es-bg-hover);+}++.es-asset-item.es-selected {+ background: var(--es-selection-bg);+}++.es-asset-item.es-dragging {+ opacity: 0.5;+}++.es-asset-item[draggable="true"] {+ cursor: grab;+}++.es-asset-item[draggable="true"]:active {+ cursor: grabbing;+}++.es-asset-icon {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 48px;+ height: 48px;+ margin-bottom: 4px;+}++.es-asset-icon svg {+ stroke: #e8c36a;+}++.es-asset-name {+ font-size: 11px;+ text-align: center;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ width: 100%;+}++.es-asset-subpath {+ font-size: 9px;+ color: var(--es-text-muted);+ text-align: center;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ width: 100%;+}++/* Thumbnail */+.es-cb-thumbnail {+ object-fit: contain;+ border-radius: 2px;+}++.es-cb-thumb-loading {+ opacity: 0.5;+}++/* Up Button */+.es-cb-up-btn {+ flex-shrink: 0;+}++/* View Toggle */+.es-cb-view-toggle {+ flex-shrink: 0;+}++/* List View */+.es-cb-list-view {+ flex-direction: column;+ flex-wrap: nowrap;+ gap: 0;+ padding: 4px 0;+}++.es-cb-list-row {+ display: flex;+ align-items: center;+ height: 24px;+ padding: 0 8px;+ cursor: pointer;+ user-select: none;+ gap: 8px;+}++.es-cb-list-row:hover {+ background: var(--es-bg-hover);+}++.es-cb-list-row.es-selected {+ background: var(--es-selection-bg);+}++.es-cb-list-row[draggable="true"] {+ cursor: grab;+}++.es-cb-list-icon {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 24px;+ height: 24px;+ flex-shrink: 0;+}++.es-cb-list-icon svg {+ stroke: #e8c36a;+}++.es-cb-list-name {+ flex: 1;+ font-size: 12px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ min-width: 0;+}++.es-cb-list-subpath {+ color: var(--es-text-muted);+ font-size: 10px;+ margin-left: 6px;+}++.es-cb-list-type {+ font-size: 10px;+ color: var(--es-text-muted);+ flex-shrink: 0;+ width: 60px;+ text-align: right;+}++/* Empty State */+.es-cb-empty-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ width: 100%;+ height: 100%;+ gap: 8px;+ pointer-events: none;+}++.es-cb-empty-icon {+ opacity: 0.3;+}++.es-cb-empty-icon svg {+ stroke: var(--es-text-muted);+}++.es-cb-empty-text {+ font-size: 12px;+ color: var(--es-text-muted);+}++/* Grid focus */+.es-content-browser-grid:focus {+ outline: none;+}++/* =============================================================================+ * Content Drawer+ * ============================================================================= */++.es-content-drawer {+ position: relative;+ height: 0;+ overflow: hidden;+ transition: height 0.2s ease;+ border-top: 1px solid var(--es-border);+ display: flex;+ flex-direction: column;+ flex-shrink: 0;+}++.es-content-drawer.es-drawer-open {+ height: var(--drawer-height, 300px);+ box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.15);+}++.es-content-drawer.es-drawer-resizing {+ transition: none;+}++.es-content-drawer-resize {+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ height: 4px;+ cursor: ns-resize;+ z-index: 10;+}++.es-content-drawer-resize:hover,+.es-content-drawer-resize:active {+ background: var(--es-accent);+}++.es-content-drawer-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ height: 28px;+ min-height: 28px;+ padding: 0 8px;+ background: var(--es-bg-tertiary);+ border-bottom: 1px solid var(--es-border);+ user-select: none;+}++.es-content-drawer-title {+ display: flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ color: var(--es-text-primary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-content-drawer-title svg {+ stroke: var(--es-text-secondary);+}++.es-content-drawer-actions {+ display: flex;+ align-items: center;+ gap: 2px;+}++.es-content-drawer-actions .es-btn-icon {+ width: 22px;+ height: 22px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ border: none;+ border-radius: 3px;+ cursor: pointer;+ padding: 0;+}++.es-content-drawer-actions .es-btn-icon:hover {+ background: var(--es-bg-hover);+}++.es-content-drawer-actions .es-btn-icon svg {+ stroke: var(--es-text-secondary);+}++.es-content-drawer-actions .es-btn-icon:hover svg {+ stroke: var(--es-text-primary);+}++.es-content-drawer-actions .es-btn-icon.es-active svg {+ stroke: var(--es-accent);+}++.es-content-drawer-body {+ flex: 1;+ overflow: hidden;+}++.es-content-drawer-body .es-content-browser-header {+ display: none;+}diff --git a/editor/src/styles/dialogs.css b/editor/src/styles/dialogs.cssnew file mode 100644index 000000000..1d86688f8--- /dev/null+++ b/editor/src/styles/dialogs.css@@ -0,0 +1,673 @@+/* =============================================================================+ * Project Launcher+ * ============================================================================= */++.es-launcher {+ width: 100%;+ height: 100%;+ background: var(--es-bg-primary);+ display: flex;+ align-items: center;+ justify-content: center;+}++.es-launcher-content {+ width: 100%;+ max-width: 600px;+ padding: 40px;+}++.es-launcher-header {+ text-align: center;+ margin-bottom: 40px;+}++.es-launcher-logo {+ display: inline-flex;+ align-items: center;+ gap: 16px;+}++.es-launcher-logo-icon {+ width: 64px;+ height: 64px;+ display: flex;+ align-items: center;+ justify-content: center;+}++.es-launcher-logo-icon svg {+ width: 64px;+ height: 64px;+ border-radius: 12px;+}++.es-launcher-logo-text {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+}++.es-launcher-title {+ font-size: 28px;+ font-weight: 600;+ color: var(--es-text-primary);+}++.es-launcher-subtitle {+ font-size: 16px;+ color: var(--es-text-secondary);+}++.es-launcher-actions {+ display: flex;+ gap: 12px;+ margin-bottom: 32px;+}++.es-launcher-btn {+ flex: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ padding: 16px 24px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 14px;+ cursor: pointer;+ transition: all 0.15s;+}++.es-launcher-btn:hover {+ background: var(--es-bg-hover);+ border-color: var(--es-text-secondary);+}++.es-launcher-btn-primary {+ background: var(--es-accent-gold);+ border-color: var(--es-accent-gold);+ color: #1e1e1e;+ font-weight: 500;+}++.es-launcher-btn-primary:hover {+ background: #e5c07b;+ border-color: #e5c07b;+}++.es-launcher-btn-icon {+ font-size: 18px;+ display: flex;+ align-items: center;+ justify-content: center;+}++.es-launcher-btn-icon svg {+ width: 18px;+ height: 18px;+ stroke: currentColor;+}++.es-launcher-recent {+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+}++.es-launcher-recent-header {+ padding: 12px 16px;+ border-bottom: 1px solid var(--es-border);+ color: var(--es-text-secondary);+ font-size: 12px;+ text-transform: uppercase;+ letter-spacing: 0.5px;+}++.es-launcher-recent-list {+ max-height: 300px;+ overflow-y: auto;+}++.es-launcher-recent-empty {+ padding: 40px 20px;+ text-align: center;+ color: var(--es-text-secondary);+}++.es-launcher-recent-item {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 12px 16px;+ cursor: pointer;+ transition: background 0.15s;+}++.es-launcher-recent-item:hover {+ background: var(--es-bg-hover);+}++.es-launcher-recent-icon {+ width: 20px;+ height: 20px;+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: center;+}++.es-launcher-recent-icon svg {+ width: 20px;+ height: 20px;+ stroke: var(--es-text-secondary);+}++.es-launcher-recent-info {+ flex: 1;+ min-width: 0;+}++.es-launcher-recent-name {+ color: var(--es-text-primary);+ font-size: 14px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.es-launcher-recent-path {+ color: var(--es-text-secondary);+ font-size: 12px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.es-launcher-recent-time {+ color: var(--es-text-secondary);+ font-size: 12px;+ flex-shrink: 0;+}++.es-launcher-recent-remove {+ width: 24px;+ height: 24px;+ background: transparent;+ border: none;+ color: var(--es-text-secondary);+ font-size: 16px;+ cursor: pointer;+ opacity: 0;+ transition: opacity 0.15s;+}++.es-launcher-recent-item:hover .es-launcher-recent-remove {+ opacity: 1;+}++.es-launcher-recent-remove:hover {+ color: var(--es-danger);+}++.es-launcher-footer {+ margin-top: 24px;+ text-align: center;+ color: var(--es-text-secondary);+ font-size: 12px;+}++/* =============================================================================+ * Dialog Overlay+ * ============================================================================= */++.es-dialog-overlay {+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: rgba(0, 0, 0, 0.6);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 3000;+ color: var(--es-text-primary);+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ font-size: 13px;+}++.es-dialog {+ width: 100%;+ max-width: 480px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);+}++.es-dialog-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 16px 20px;+ border-bottom: 1px solid var(--es-border);+}++.es-dialog-title {+ font-size: 16px;+ font-weight: 500;+ color: var(--es-text-primary);+}++.es-dialog-close {+ width: 28px;+ height: 28px;+ background: transparent;+ border: none;+ color: var(--es-text-secondary);+ font-size: 20px;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+}++.es-dialog-close:hover {+ color: var(--es-text-primary);+}++.es-dialog-body {+ padding: 20px;+}++.es-dialog-field {+ margin-bottom: 16px;+}++.es-dialog-field:last-child {+ margin-bottom: 0;+}++.es-dialog-label {+ display: block;+ margin-bottom: 6px;+ font-size: 13px;+ color: var(--es-text-secondary);+}++.es-dialog-input {+ width: 100%;+ padding: 8px 12px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 14px;+}++.es-dialog-input:focus {+ outline: none;+ border-color: var(--es-accent);+}++.es-dialog-path-row {+ display: flex;+ gap: 8px;+}++.es-dialog-path {+ flex: 1;+}++.es-dialog-browse {+ padding: 8px 16px;+ background: var(--es-bg-tertiary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ cursor: pointer;+}++.es-dialog-browse:hover {+ background: var(--es-bg-hover);+}++.es-dialog-templates {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.es-dialog-template {+ display: flex;+ align-items: flex-start;+ gap: 12px;+ padding: 12px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ cursor: pointer;+ transition: all 0.15s;+}++.es-dialog-template:hover:not(.disabled) {+ border-color: var(--es-text-secondary);+}++.es-dialog-template.selected {+ border-color: var(--es-accent-gold);+ background: rgba(209, 154, 102, 0.1);+}++.es-dialog-template.disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.es-dialog-template input {+ margin-top: 2px;+}++.es-dialog-template-name {+ display: block;+ color: var(--es-text-primary);+ font-size: 14px;+ font-weight: 500;+}++.es-dialog-template-desc {+ display: block;+ color: var(--es-text-secondary);+ font-size: 12px;+ margin-top: 2px;+}++.es-dialog-footer {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ padding: 16px 20px;+ border-top: 1px solid var(--es-border);+}++.es-dialog-btn {+ padding: 8px 20px;+ background: var(--es-bg-tertiary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 14px;+ cursor: pointer;+ transition: all 0.15s;+}++.es-dialog-btn:hover {+ background: var(--es-bg-hover);+}++.es-dialog-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.es-dialog-btn-primary {+ background: var(--es-accent-gold);+ border-color: var(--es-accent-gold);+ color: #1e1e1e;+ font-weight: 500;+}++.es-dialog-btn-primary:hover:not(:disabled) {+ background: #e5c07b;+ border-color: #e5c07b;+}++.es-dialog-message {+ margin: 0;+ color: var(--es-text-primary);+ font-size: 14px;+ line-height: 1.5;+}++.es-dialog-error {+ margin-top: 8px;+ padding: 8px 12px;+ background: rgba(244, 67, 54, 0.1);+ border: 1px solid rgba(244, 67, 54, 0.3);+ border-radius: 4px;+ color: var(--es-danger);+ font-size: 12px;+}++.es-dialog-danger .es-dialog-btn-primary {+ background: var(--es-danger);+ border-color: var(--es-danger);+}++.es-dialog-danger .es-dialog-btn-primary:hover:not(:disabled) {+ background: #e53935;+ border-color: #e53935;+}++/* =============================================================================+ * Settings Dialog+ * ============================================================================= */++.es-settings-dialog {+ max-width: 640px !important;+}++.es-settings-dialog .es-dialog-body {+ padding: 0;+}++.es-settings-dialog-body {+ display: flex;+ min-height: 400px;+}++.es-settings-nav {+ width: 180px;+ min-width: 180px;+ background: var(--es-bg-primary);+ border-right: 1px solid var(--es-border);+ padding: 8px 0;+ overflow-y: auto;+}++.es-settings-nav-item {+ display: block;+ width: 100%;+ padding: 8px 16px;+ background: transparent;+ border: none;+ color: var(--es-text-secondary);+ font-size: 13px;+ text-align: left;+ cursor: pointer;+ transition: all 0.15s;+}++.es-settings-nav-item:hover {+ color: var(--es-text-primary);+ background: var(--es-bg-hover);+}++.es-settings-nav-item.es-active {+ color: var(--es-text-primary);+ background: var(--es-bg-tertiary);+ border-left: 2px solid var(--es-accent-gold);+ padding-left: 14px;+}++.es-settings-content {+ flex: 1;+ padding: 20px;+ overflow-y: auto;+}++.es-settings-section-title {+ margin: 0 0 16px;+ font-size: 15px;+ font-weight: 500;+ color: var(--es-text-primary);+}++.es-settings-item {+ margin-bottom: 14px;+}++.es-settings-item:last-child {+ margin-bottom: 0;+}++.es-settings-label {+ display: block;+ margin-bottom: 6px;+ font-size: 13px;+ color: var(--es-text-secondary);+}++.es-settings-checkbox-row {+ display: flex;+ align-items: center;+ gap: 8px;+ cursor: pointer;+ font-size: 13px;+ color: var(--es-text-primary);+}++.es-settings-checkbox-row input[type="checkbox"] {+ margin: 0;+}++.es-settings-input {+ width: 100%;+ padding: 6px 10px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 13px;+ box-sizing: border-box;+}++.es-settings-input:focus {+ outline: none;+ border-color: var(--es-accent);+}++.es-settings-select {+ width: 100%;+ padding: 6px 10px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+ font-size: 13px;+ box-sizing: border-box;+}++.es-settings-select:focus {+ outline: none;+ border-color: var(--es-accent);+}++.es-settings-color-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+}++.es-settings-color-row .es-color-input {+ width: 60px;+ height: 28px;+ padding: 2px;+ border: 1px solid var(--es-border);+ background: var(--es-bg-primary);+ cursor: pointer;+}++.es-settings-range-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+}++.es-settings-range-value {+ font-size: 12px;+ color: var(--es-text-secondary);+ min-width: 32px;+ text-align: right;+}++.es-settings-description {+ font-size: 11px;+ color: var(--es-text-secondary);+ margin: 2px 0 6px;+ opacity: 0.7;+}++.es-settings-item-header {+ display: flex;+ align-items: center;+ gap: 6px;+}++.es-settings-item-header .es-settings-label {+ margin-bottom: 0;+}++.es-settings-reset-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 18px;+ height: 18px;+ padding: 0;+ background: transparent;+ border: 1px solid var(--es-border);+ border-radius: 3px;+ color: var(--es-text-secondary);+ font-size: 12px;+ cursor: pointer;+ flex-shrink: 0;+}++.es-settings-reset-btn:hover {+ background: var(--es-bg-hover);+ color: var(--es-text-primary);+}++/* =============================================================================+ * Floating Window+ * ============================================================================= */++.es-floating-window {+ position: fixed;+ z-index: 5000;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 6px;+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ color: var(--es-text-primary);+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ font-size: 13px;+}+.es-floating-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 12px;+ background: var(--es-bg-tertiary);+ border-bottom: 1px solid var(--es-border);+ cursor: move;+ user-select: none;+ flex-shrink: 0;+}+.es-floating-title {+ font-size: 13px;+ font-weight: 500;+}+.es-floating-body {+ flex: 1;+ min-height: 0;+ overflow: hidden;+}diff --git a/editor/src/styles/hierarchy.css b/editor/src/styles/hierarchy.cssnew file mode 100644index 000000000..b7e441576--- /dev/null+++ b/editor/src/styles/hierarchy.css@@ -0,0 +1,305 @@+/* =============================================================================+ * Hierarchy Panel+ * ============================================================================= */++.es-hierarchy-panel {+ height: 100%;+ display: flex;+ flex-direction: column;+ background: var(--es-bg-primary);+}++.es-hierarchy-toolbar {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 8px;+ background: var(--es-bg-secondary);+ border-bottom: 1px solid var(--es-border);+}++.es-hierarchy-search {+ flex: 1;+ min-width: 80px;+}++.es-hierarchy-columns {+ display: flex;+ align-items: center;+ padding: 4px 8px;+ background: var(--es-bg-tertiary);+ border-bottom: 1px solid var(--es-border);+ font-size: 11px;+ color: var(--es-text-secondary);+}++.es-hierarchy-col-visibility,+.es-hierarchy-col-lock {+ width: 20px;+ text-align: center;+}++.es-hierarchy-col-label {+ flex: 1;+ padding-left: 24px;+}++.es-hierarchy-col-type {+ width: 60px;+ text-align: right;+}++.es-hierarchy-tree {+ flex: 1;+ overflow: auto;+ padding: 4px 0;+}++.es-hierarchy-scroll-content {+ position: relative;+ min-height: 100%;+}++.es-hierarchy-visible-window {+ position: absolute;+ left: 0;+ right: 0;+ will-change: transform;+}++.es-hierarchy-item {+ user-select: none;+ position: relative;+}++.es-hierarchy-row {+ display: flex;+ align-items: center;+ padding: 3px 8px;+ min-width: fit-content;+ cursor: pointer;+ border-left: 2px solid transparent;+ position: relative;+ height: 22px;+ box-sizing: border-box;+ transition: background 0.15s;+}++.es-hierarchy-row:hover {+ background: var(--es-bg-hover);+}++.es-hierarchy-item.es-selected > .es-hierarchy-row {+ background: rgba(209, 154, 102, 0.3);+ border-left-color: var(--es-accent-gold);+}++.es-hierarchy-item.es-selected > .es-hierarchy-row .es-hierarchy-name {+ color: var(--es-accent-gold);+}++.es-hierarchy-item.es-drag-over > .es-hierarchy-row {+ background: rgba(97, 175, 239, 0.3);+ border-left-color: var(--es-drag);+}++.es-hierarchy-tree.es-drag-over {+ background: rgba(97, 175, 239, 0.1);+ outline: 1px dashed var(--es-drag);+ outline-offset: -2px;+}++.es-hierarchy-item.es-drop-before > .es-hierarchy-row::before {+ content: '';+ position: absolute;+ top: 0;+ left: 20px;+ right: 0;+ height: 2px;+ background: var(--es-drag);+ pointer-events: none;+}++.es-hierarchy-item.es-drop-after > .es-hierarchy-row::after {+ content: '';+ position: absolute;+ bottom: 0;+ left: 20px;+ right: 0;+ height: 2px;+ background: var(--es-drag);+ pointer-events: none;+}++.es-hierarchy-item.es-drop-inside > .es-hierarchy-row {+ background: rgba(97, 175, 239, 0.3);+ border-left-color: var(--es-drag);+}++.es-hierarchy-item.es-dragging {+ opacity: 0.5;+}++.es-hierarchy-visibility {+ width: 16px;+ flex-shrink: 0;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+}++.es-hierarchy-visibility svg {+ stroke: var(--es-text-secondary);+}++.es-hierarchy-expand {+ width: 16px;+ flex-shrink: 0;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ transition: transform 0.15s;+}++.es-hierarchy-expand svg {+ stroke: var(--es-text-secondary);+}++.es-hierarchy-item.es-expanded > .es-hierarchy-row > .es-hierarchy-expand {+ transform: rotate(90deg);+}++.es-hierarchy-spacer {+ width: 16px;+ flex-shrink: 0;+}++.es-hierarchy-icon {+ width: 18px;+ flex-shrink: 0;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ margin-right: 4px;+}++.es-hierarchy-icon svg {+ stroke: var(--es-text-secondary);+}++.es-hierarchy-name {+ flex: 1;+ min-width: 80px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 12px;+}++.es-hierarchy-type {+ width: 60px;+ flex-shrink: 0;+ text-align: right;+ font-size: 11px;+ color: var(--es-text-secondary);+}++.es-hierarchy-rename-input {+ width: 100%;+ height: 18px;+ padding: 0 4px;+ margin: 0;+ border: 1px solid var(--es-accent-gold);+ border-radius: 2px;+ background: var(--es-bg-primary);+ color: var(--es-text-primary);+ font-size: 12px;+ font-family: inherit;+ outline: none;+ box-sizing: border-box;+}++.es-hierarchy-item.es-entity-hidden > .es-hierarchy-row {+ opacity: 0.4;+}++.es-prefab-edit-bar {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ background: rgba(79, 193, 255, 0.1);+ border-bottom: 1px solid rgba(79, 193, 255, 0.25);+ font-size: 11px;+ color: var(--es-prefab);+}++.es-prefab-back-btn {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 2px 8px;+ font-size: 11px;+ color: var(--es-text-primary);+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 3px;+ cursor: pointer;+}++.es-prefab-back-btn:hover {+ background: var(--es-bg-hover);+}++.es-prefab-back-btn svg {+ transform: rotate(180deg);+}++.es-prefab-edit-name {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ font-weight: 600;+}++.es-prefab-edit-name svg {+ stroke: var(--es-prefab);+}++.es-hierarchy-item.es-prefab-root > .es-hierarchy-row .es-hierarchy-name {+ color: var(--es-prefab);+ font-weight: 600;+}++.es-hierarchy-item.es-prefab-root > .es-hierarchy-row .es-hierarchy-icon svg {+ stroke: var(--es-prefab);+}++.es-hierarchy-item.es-prefab-child > .es-hierarchy-row .es-hierarchy-name {+ color: #87d7ff;+}++.es-search-highlight {+ background: rgba(229, 192, 123, 0.3);+ color: #e5c07b;+ font-weight: 600;+ padding: 0 1px;+ border-radius: 2px;+}++.es-hierarchy-item.es-search-selected {+ background: rgba(97, 175, 239, 0.2);+}++.es-hierarchy-item.es-search-selected > .es-hierarchy-row {+ border-left: 2px solid var(--es-drag);+}++.es-hierarchy-footer {+ padding: 6px 12px;+ font-size: 11px;+ color: var(--es-text-secondary);+ background: var(--es-bg-secondary);+ border-top: 1px solid var(--es-border);+}diff --git a/editor/src/styles/index.css b/editor/src/styles/index.cssnew file mode 100644index 000000000..d98c752e1--- /dev/null+++ b/editor/src/styles/index.css@@ -0,0 +1,9 @@+@import './base.css';+@import './panels.css';+@import './menus.css';+@import './hierarchy.css';+@import './inspector.css';+@import './scene-view.css';+@import './content-browser.css';+@import './dialogs.css';+@import './builder.css';diff --git a/editor/src/styles/index.ts b/editor/src/styles/index.tsindex f7d9ecbd3..d78e3865f 100644--- a/editor/src/styles/index.ts+++ b/editor/src/styles/index.ts@@ -3,7 +3,7 @@* @brief Editor styles loader*/-export const EDITOR_STYLES_URL = new URL('./editor.css', import.meta.url).href;+export const EDITOR_STYLES_URL = new URL('./index.css', import.meta.url).href;export function injectEditorStyles(): void {if (document.querySelector('link[data-es-editor-styles]')) {diff --git a/editor/src/styles/inspector.css b/editor/src/styles/inspector.cssnew file mode 100644index 000000000..115f05e3f--- /dev/null+++ b/editor/src/styles/inspector.css@@ -0,0 +1,1148 @@+/* =============================================================================+ * Inspector Panel+ * ============================================================================= */++.es-inspector-panel {+ height: 100%;+ display: flex;+ flex-direction: column;+ background: var(--es-bg-primary);+}++.es-inspector-toolbar {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 8px;+ background: var(--es-bg-secondary);+ border-bottom: 1px solid var(--es-border);+}++.es-inspector-content {+ flex: 1;+ overflow: auto;+ padding: 4px;+}++.es-inspector-empty {+ color: var(--es-text-secondary);+ text-align: center;+ padding: 20px;+}++.es-inspector-multi-header {+ padding: 16px;+ text-align: center;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ margin-bottom: 8px;+}++.es-inspector-multi-header h3 {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ margin: 0 0 8px 0;+ color: var(--es-text-primary);+ font-size: 14px;+ font-weight: 600;+}++.es-inspector-multi-header p {+ margin: 0;+ color: var(--es-text-secondary);+ font-size: 12px;+}++.es-inspector-entity-header {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 8px;+ margin-bottom: 4px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+}++.es-entity-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+}++.es-entity-icon svg {+ stroke: var(--es-accent-gold);+}++.es-entity-name {+ flex: 1;+ font-weight: 600;+ font-size: 12px;+ color: var(--es-accent-gold);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-entity-visibility {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ padding: 2px;+ border-radius: 3px;+}++.es-entity-visibility:hover {+ background: var(--es-bg-hover);+}++.es-entity-visibility svg {+ stroke: var(--es-text-secondary);+}++.es-entity-id {+ font-size: 10px;+ color: var(--es-text-secondary);+}++.es-entity-name-input {+ flex: 1;+ min-width: 0;+ padding: 2px 4px;+ font-size: 12px;+ font-weight: 600;+ color: var(--es-accent-gold);+ background: transparent;+ border: 1px solid transparent;+ border-radius: 2px;+ outline: none;+}++.es-entity-name-input:hover {+ background: var(--es-bg-primary);+}++.es-entity-name-input:focus {+ background: var(--es-bg-primary);+ border-color: var(--es-accent);+}++.es-prefab-info-bar {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ margin-bottom: 4px;+ background: rgba(79, 193, 255, 0.08);+ border: 1px solid rgba(79, 193, 255, 0.25);+ border-radius: 3px;+ font-size: 11px;+ color: var(--es-prefab);+}++.es-prefab-info-bar svg {+ stroke: var(--es-prefab);+ flex-shrink: 0;+}++.es-prefab-info-path {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-prefab-info-link {+ cursor: pointer;+ text-decoration: underline;+ text-decoration-color: transparent;+ transition: text-decoration-color 0.15s;+}++.es-prefab-info-link:hover {+ text-decoration-color: var(--es-prefab);+}++.es-prefab-info-bar .es-btn {+ font-size: 10px;+ padding: 1px 6px;+ border: 1px solid rgba(79, 193, 255, 0.3);+ color: var(--es-prefab);+ background: transparent;+ cursor: pointer;+ border-radius: 3px;+}++.es-prefab-info-bar .es-btn:hover {+ background: rgba(79, 193, 255, 0.15);+}++.es-property-row.es-overridden .es-property-label {+ font-weight: 700;+ color: var(--es-prefab);+}++.es-property-row.es-overridden .es-property-label::before {+ content: '';+ display: inline-block;+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--es-prefab);+ margin-right: 4px;+ vertical-align: middle;+}++.es-component-section {+ background: var(--es-bg-secondary);+ margin-bottom: 4px;+ overflow: hidden;+ border: 1px solid var(--es-border);+}++.es-component-tag-row {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ background: var(--es-bg-tertiary);+}++.es-component-tag-row .es-component-title {+ flex: 1;+}++.es-component-tag-row:hover {+ background: var(--es-bg-hover);+}++.es-component-header {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ background: var(--es-bg-tertiary);+ cursor: pointer;+ border-bottom: 1px solid transparent;+}++.es-collapsible.es-expanded .es-component-header {+ border-bottom-color: var(--es-border);+}++.es-component-header:hover {+ background: var(--es-bg-hover);+}++.es-collapse-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 14px;+ height: 14px;+ transition: transform 0.15s;+}++.es-collapsible:not(.es-expanded) .es-collapse-icon {+ transform: rotate(-90deg);+}++.es-collapse-icon svg {+ stroke: var(--es-text-secondary);+}++.es-component-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+}++.es-component-icon svg {+ stroke: var(--es-accent-gold);+}++.es-component-title {+ flex: 1;+ font-weight: 500;+ font-size: 11px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-collapsible-content {+ display: block;+}++.es-collapsible:not(.es-expanded) .es-collapsible-content {+ display: none;+}++.es-component-properties {+ padding: 6px 8px;+}++.es-component-raw {+ padding: 6px;+ font-size: 10px;+ overflow: auto;+ background: var(--es-bg-primary);+ margin: 0;+}++.es-property-row {+ display: flex;+ align-items: center;+ min-height: 24px;+ margin-bottom: 4px;+}++.es-property-row:last-child {+ margin-bottom: 0;+}++.es-property-label {+ width: 35%;+ max-width: 80px;+ flex-shrink: 1;+ padding-right: 8px;+ color: var(--es-text-secondary);+ font-size: 11px;+ text-overflow: ellipsis;+ overflow: hidden;+ white-space: nowrap;+ line-height: 1.3;+}++.es-property-reset {+ flex-shrink: 0;+ margin-left: 2px;+ padding: 0;+ width: 16px;+ height: 16px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ border: none;+ opacity: 0;+ cursor: pointer;+ color: var(--es-text-secondary);+}++.es-property-row:hover .es-property-reset {+ opacity: 0.5;+}++.es-property-reset:hover {+ opacity: 1 !important;+}++.es-property-editor {+ flex: 1;+ display: flex;+ align-items: center;+}++.es-btn-reset-size {+ flex-shrink: 0;+ margin-left: 4px;+ padding: 2px !important;+ min-width: 18px !important;+ background: transparent !important;+ border: none !important;+ opacity: 0.5;+ cursor: pointer;+}++.es-btn-reset-size:hover {+ opacity: 1;+}++.es-btn-reset-size svg {+ stroke: var(--es-text-secondary);+}++.es-add-component-wrapper {+ margin-top: 8px;+ padding: 0 4px;+}++.es-btn-add-component {+ width: 100%;+ padding: 6px 8px;+ background: var(--es-bg-tertiary);+ border: 1px dashed var(--es-border);+ color: var(--es-text-secondary);+ font-size: 11px;+}++.es-btn-add-component:hover {+ background: var(--es-bg-hover);+ color: var(--es-text-primary);+ border-style: solid;+}++.es-inspector-footer {+ padding: 6px 12px;+ font-size: 11px;+ color: var(--es-text-secondary);+ background: var(--es-bg-secondary);+ border-top: 1px solid var(--es-border);+}++/* Asset Inspector */++.es-inspector-asset-header {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 8px 10px;+ margin-bottom: 4px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+}++.es-asset-header-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+}++.es-asset-header-icon svg {+ stroke: var(--es-accent);+}++.es-asset-header-name {+ flex: 1;+ font-weight: 600;+ font-size: 13px;+ color: var(--es-text-primary);+ word-break: break-all;+}++.es-asset-meta-info {+ padding: 2px 10px 6px;+ background: var(--es-bg-secondary);+ border-left: 1px solid var(--es-border);+ border-right: 1px solid var(--es-border);+ border-bottom: 1px solid var(--es-border);+ margin-top: -5px;+ margin-bottom: 4px;+}++.es-asset-meta-uuid {+ font-size: 11px;+ color: var(--es-text-muted);+ cursor: pointer;+ user-select: all;+}++.es-asset-meta-uuid:hover {+ color: var(--es-text-secondary);+}++.es-asset-preview-section {+ margin-bottom: 4px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+}++.es-asset-preview-loading,+.es-asset-preview-error {+ padding: 20px;+ text-align: center;+ color: var(--es-text-secondary);+ font-size: 12px;+}++.es-asset-preview-error {+ color: #e74c3c;+}++.es-image-preview-container {+ padding: 10px;+ display: flex;+ justify-content: center;+ align-items: center;+ background: repeating-conic-gradient(#222 0% 25%, #2a2a2a 0% 50%) 50% / 16px 16px;+ min-height: 100px;+ max-height: 200px;+}++.es-image-preview {+ max-width: 100%;+ max-height: 180px;+ object-fit: contain;+ border: 1px solid var(--es-border);+}++.es-property-value {+ flex: 1;+ font-size: 11px;+ color: var(--es-text-primary);+ background: var(--es-bg-tertiary);+ padding: 4px 8px;+ border-radius: 3px;+}++.es-code-preview {+ margin: 0;+ padding: 10px;+ font-family: 'Consolas', 'Monaco', monospace;+ font-size: 11px;+ line-height: 1.5;+ color: var(--es-text-secondary);+ background: var(--es-bg-primary);+ overflow: auto;+ max-height: 150px;+ white-space: pre-wrap;+ word-break: break-all;+}++.es-asset-actions {+ padding: 8px;+ display: flex;+ justify-content: center;+}++.es-btn-primary {+ background: var(--es-accent);+ color: white;+ border: none;+ padding: 6px 16px;+ font-size: 12px;+ border-radius: 4px;+ cursor: pointer;+}++.es-btn-primary:hover {+ background: #5a9cf5;+}++/* =============================================================================+ * Add Component Popup+ * ============================================================================= */++.es-popup-overlay {+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: rgba(0, 0, 0, 0.5);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 5000;+}++.es-popup-container {+ max-width: 400px;+ width: 90%;+ max-height: 80vh;+}++.es-add-component-popup {+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 6px;+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);+ overflow: hidden;+ display: flex;+ flex-direction: column;+ max-height: 80vh;+}++.es-add-component-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 12px 16px;+ border-bottom: 1px solid var(--es-border);+ background: var(--es-bg-tertiary);+}++.es-add-component-title {+ font-size: 14px;+ font-weight: 500;+ color: var(--es-text-primary);+}++.es-add-component-close {+ background: none;+ border: none;+ cursor: pointer;+ padding: 4px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 4px;+}++.es-add-component-close:hover {+ background: var(--es-bg-hover);+}++.es-add-component-close svg {+ stroke: var(--es-text-secondary);+}++.es-add-component-close:hover svg {+ stroke: var(--es-text-primary);+}++.es-add-component-search {+ display: flex;+ align-items: center;+ padding: 8px 12px;+ border-bottom: 1px solid var(--es-border);+ gap: 8px;+}++.es-search-icon svg {+ stroke: var(--es-text-secondary);+}++.es-add-component-search .es-search-input {+ flex: 1;+ background: transparent;+ border: none;+ color: var(--es-text-primary);+ font-size: 13px;+ outline: none;+}++.es-add-component-search .es-search-input::placeholder {+ color: var(--es-text-secondary);+}++.es-add-component-list {+ overflow-y: auto;+ max-height: 400px;+ padding: 8px 0;+}++.es-component-category {+ margin-bottom: 4px;+}++.es-category-header {+ display: flex;+ align-items: center;+ padding: 6px 12px;+ cursor: pointer;+ user-select: none;+ gap: 6px;+}++.es-category-header:hover {+ background: var(--es-bg-hover);+}++.es-category-chevron svg {+ stroke: var(--es-text-secondary);+}++.es-category-label {+ flex: 1;+ font-size: 11px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ color: var(--es-text-secondary);+}++.es-category-count {+ font-size: 11px;+ color: var(--es-text-secondary);+ background: var(--es-bg-tertiary);+ padding: 1px 6px;+ border-radius: 10px;+}++.es-category-items {+ padding-left: 12px;+}++.es-category-items.es-hidden {+ display: none;+}++.es-component-item {+ display: flex;+ align-items: center;+ padding: 6px 12px;+ cursor: pointer;+ gap: 8px;+ border-radius: 4px;+ margin: 2px 8px;+}++.es-component-item:hover,+.es-component-item.es-highlighted {+ background: var(--es-bg-hover);+}++.es-component-icon svg {+ stroke: var(--es-text-secondary);+}++.es-component-item:hover .es-component-icon svg,+.es-component-item.es-highlighted .es-component-icon svg {+ stroke: var(--es-accent);+}++.es-component-item mark {+ background: var(--es-accent);+ color: var(--es-bg-primary);+ border-radius: 2px;+ padding: 0 1px;+}++.es-component-name {+ font-size: 13px;+ color: var(--es-text-primary);+}++.es-no-components {+ padding: 24px;+ text-align: center;+ color: var(--es-text-secondary);+ font-size: 13px;+}++/* =============================================================================+ * Nine-Slice Editor+ * ============================================================================= */++.es-nine-slice-editor {+ margin-bottom: 12px;+}++.es-nine-slice-preview {+ position: relative;+ width: 100%;+ background: repeating-conic-gradient(#333 0% 25%, #444 0% 50%) 50% / 16px 16px;+ border: 1px solid var(--es-border);+ overflow: hidden;+}++.es-nine-slice-image {+ display: block;+ width: 100%;+ height: auto;+ image-rendering: pixelated;+}++.es-nine-slice-line {+ position: absolute;+ background: #00ff00;+ z-index: 10;+}++.es-nine-slice-left,+.es-nine-slice-right {+ top: 0;+ bottom: 0;+ width: 2px;+ cursor: ew-resize;+}++.es-nine-slice-left {+ left: 0;+}++.es-nine-slice-right {+ right: 0;+}++.es-nine-slice-top,+.es-nine-slice-bottom {+ left: 0;+ right: 0;+ height: 2px;+ cursor: ns-resize;+}++.es-nine-slice-top {+ top: 0;+}++.es-nine-slice-bottom {+ bottom: 0;+}++.es-nine-slice-line:hover {+ background: #00ff88;+}++.es-nine-slice-line::before {+ content: '';+ position: absolute;+ background: transparent;+}++.es-nine-slice-left::before,+.es-nine-slice-right::before {+ top: 0;+ bottom: 0;+ left: -4px;+ right: -4px;+}++.es-nine-slice-top::before,+.es-nine-slice-bottom::before {+ left: 0;+ right: 0;+ top: -4px;+ bottom: -4px;+}++.es-nine-slice-inputs {+ margin-top: 8px;+}++/* =============================================================================+ * Texture Editor+ * ============================================================================= */++.es-texture-editor {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.es-texture-preview {+ width: 64px;+ height: 64px;+ background: repeating-conic-gradient(#333 0% 25%, #444 0% 50%) 50% / 8px 8px;+ border: 1px solid var(--es-border);+ border-radius: 4px;+ overflow: hidden;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: border-color 0.15s;+}++.es-texture-preview:hover {+ border-color: var(--es-accent);+}++.es-texture-preview.es-has-preview:hover {+ opacity: 0.9;+}++.es-texture-preview-img {+ max-width: 100%;+ max-height: 100%;+ object-fit: contain;+ display: none;+ image-rendering: pixelated;+}++.es-texture-preview::before {+ content: '';+ display: block;+}++.es-texture-preview.es-has-preview::before {+ display: none;+}++.es-texture-input-row {+ display: flex;+ gap: 4px;+}++.es-texture-input-row .es-input-texture {+ flex: 1;+ min-width: 0;+}++.es-btn-locate {+ flex-shrink: 0;+}++/* =============================================================================+ * Spine File Editor+ * ============================================================================= */++.es-file-editor {+ display: flex;+ gap: 4px;+}++.es-file-editor .es-input-file {+ flex: 1;+ min-width: 0;+}++.es-file-editor .es-btn-browse {+ flex-shrink: 0;+}++.es-file-editor.es-drag-over,+.es-texture-editor.es-drag-over {+ outline: 2px solid var(--es-accent);+ outline-offset: -2px;+ border-radius: 3px;+}++.es-asset-link {+ cursor: pointer;+}++.es-asset-link:not(:placeholder-shown):hover {+ color: var(--es-accent);+ text-decoration: underline;+}++.es-missing-asset {+ color: #ff6b6b !important;+}++/* =============================================================================+ * Spine Animation/Skin Editor+ * ============================================================================= */++.es-spine-animation-editor,+.es-spine-skin-editor {+ display: flex;+ gap: 4px;+}++.es-spine-animation-editor .es-input-select,+.es-spine-skin-editor .es-input-select {+ flex: 1;+ min-width: 0;+}++.es-btn-refresh {+ flex-shrink: 0;+}++.es-btn-refresh:hover {+ color: var(--es-accent);+}++/* =============================================================================+ * Material Preview Panel+ * ============================================================================= */++.es-material-preview-panel {+ border-top: 1px solid var(--es-border);+ background: var(--es-bg-secondary);+}++.es-material-preview-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 8px 12px;+ cursor: pointer;+ user-select: none;+}++.es-material-preview-header:hover {+ background: var(--es-bg-hover);+}++.es-material-preview-title {+ display: flex;+ align-items: center;+ gap: 6px;+ font-weight: 600;+ font-size: 12px;+}++.es-material-preview-title svg {+ stroke: var(--es-text-secondary);+ transition: transform 0.15s;+}++.es-material-preview-panel.es-expanded .es-material-preview-title svg {+ transform: rotate(90deg);+}++.es-material-preview-open-btn {+ padding: 2px 8px !important;+ font-size: 10px !important;+ background: transparent !important;+ border: 1px solid var(--es-border) !important;+ color: var(--es-text-secondary) !important;+}++.es-material-preview-open-btn:hover {+ background: var(--es-bg-hover) !important;+ color: var(--es-text-primary) !important;+}++.es-material-preview-content {+ display: none;+ padding: 8px 12px;+ background: var(--es-bg-primary);+}++.es-material-preview-panel.es-expanded .es-material-preview-content {+ display: block;+}++.es-material-preview-name {+ font-size: 11px;+ color: var(--es-text-secondary);+ margin-bottom: 8px;+ padding-bottom: 6px;+ border-bottom: 1px solid var(--es-border);+}++.es-material-preview-empty {+ padding: 16px;+ text-align: center;+ color: var(--es-text-secondary);+ font-size: 11px;+ font-style: italic;+}++.es-material-preview-row {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 4px 0;+}++.es-material-preview-row .es-property-label {+ width: 90px;+ flex-shrink: 0;+ font-size: 11px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.es-material-preview-row.es-overridden .es-property-label {+ color: #4fc3f7;+}++.es-material-preview-row .es-property-editor {+ flex: 1;+ min-width: 0;+}++.es-btn-reset-override {+ padding: 2px !important;+ min-width: 16px !important;+ background: transparent !important;+ border: none !important;+ opacity: 0;+ transition: opacity 0.15s;+}++.es-material-preview-row:hover .es-btn-reset-override {+ opacity: 0.6;+}++.es-btn-reset-override:hover {+ opacity: 1 !important;+}++.es-btn-reset-override svg {+ stroke: var(--es-text-secondary);+}++.es-material-preview-status {+ font-size: 10px;+ color: var(--es-text-secondary);+ padding: 6px 0;+ border-top: 1px solid var(--es-border);+ margin-top: 8px;+}++/* =============================================================================+ * UIRect Editor+ * ============================================================================= */++.es-uirect-editor { display: flex; flex-direction: column; gap: 6px; width: 100%; }++.es-property-editor-full { width: 100%; }++.es-anchor-section { display: flex; flex-direction: column; gap: 4px; }+.es-anchor-title {+ font-size: 11px;+ color: var(--es-text-secondary);+ letter-spacing: 0.02em;+}+.es-anchor-mode-label {+ font-size: 10px;+ color: var(--es-text-secondary);+ min-height: 14px;+}+.es-anchor-presets {+ display: flex; gap: 0; align-items: start;+ padding: 5px;+ background: var(--es-bg-secondary);+ border-radius: 4px;+ border: 1px solid var(--es-border);+}+.es-anchor-group {+ display: flex; flex-direction: column; align-items: center; gap: 3px;+}+.es-anchor-group + .es-anchor-group {+ margin-left: 6px;+ padding-left: 6px;+ border-left: 1px solid var(--es-border);+}+.es-anchor-caption {+ font-size: 9px;+ color: var(--es-text-secondary);+ opacity: 0.6;+ text-transform: uppercase;+ letter-spacing: 0.05em;+}+.es-anchor-grid {+ display: grid;+ grid-template-columns: repeat(3, 28px);+ gap: 2px;+}+.es-anchor-stretch {+ display: flex; flex-direction: column; gap: 2px;+}+.es-anchor-cell {+ width: 28px; height: 28px;+ border: 1px solid transparent;+ background: transparent;+ cursor: pointer;+ display: flex; align-items: center; justify-content: center;+ border-radius: 3px;+ padding: 0;+ color: var(--es-text-secondary);+ transition: background 0.1s, border-color 0.1s, color 0.1s;+}+.es-anchor-cell:hover {+ background: var(--es-bg-hover);+ border-color: var(--es-border);+ color: var(--es-text-primary);+}+.es-anchor-cell.es-active {+ background: var(--es-accent);+ border-color: var(--es-accent);+ color: #fff;+}+.es-anchor-cell svg { width: 20px; height: 20px; }++.es-uirect-fields { display: flex; flex-direction: column; gap: 4px; }+.es-uirect-row { display: flex; align-items: center; min-height: 22px; }+.es-uirect-label { width: 72px; flex-shrink: 0; color: var(--es-text-secondary); font-size: 11px; }+.es-uirect-row .es-vec-editor { flex: 1; }+.es-uirect-pair { display: flex; gap: 8px; flex: 1; }+.es-uirect-pair-item { display: flex; align-items: center; flex: 1; gap: 4px; }+.es-uirect-pair-label { color: var(--es-text-secondary); font-size: 10px; flex-shrink: 0; cursor: ew-resize; }++.es-property-row-top {+ align-items: flex-start;+}diff --git a/editor/src/styles/menus.css b/editor/src/styles/menus.cssnew file mode 100644index 000000000..c4c249736--- /dev/null+++ b/editor/src/styles/menus.css@@ -0,0 +1,504 @@+/* =============================================================================+ * Menubar+ * ============================================================================= */++.es-editor-menubar {+ display: flex;+ align-items: center;+ height: 32px;+ background: var(--es-bg-secondary);+ border-bottom: 1px solid var(--es-border);+ user-select: none;+}++.es-menubar-logo {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 40px;+ height: 32px;+ padding: 0 8px;+}++.es-menubar-logo svg {+ width: 20px;+ height: 20px;+ border-radius: 3px;+}++.es-menubar-spacer {+ flex: 1;+ display: flex;+ justify-content: center;+ align-items: center;+}++.es-menubar-scene-name {+ font-size: 12px;+ color: var(--es-text-secondary);+ opacity: 0.8;+}++.es-menu {+ position: relative;+ height: 100%;+}++.es-menu-trigger {+ display: flex;+ align-items: center;+ height: 100%;+ padding: 0 12px;+ font-size: 12px;+ color: var(--es-text-primary);+ cursor: pointer;+ transition: background 0.1s;+}++.es-menu-trigger:hover,+.es-menu.es-open .es-menu-trigger {+ background: var(--es-bg-hover);+}++.es-menu-dropdown {+ display: none;+ position: absolute;+ top: 100%;+ left: 0;+ min-width: 200px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);+ z-index: 1000;+ padding: 4px 0;+}++.es-menu.es-open .es-menu-dropdown {+ display: block;+}++.es-menu-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 6px 12px;+ font-size: 12px;+ color: var(--es-text-primary);+ cursor: pointer;+ transition: background 0.1s;+}++.es-menu-item:hover {+ background: var(--es-accent);+ color: white;+}++.es-menu-item:hover .es-menu-item-shortcut {+ color: rgba(255, 255, 255, 0.8);+}++.es-menu-item.es-disabled {+ color: var(--es-text-secondary);+ cursor: not-allowed;+ pointer-events: none;+}++.es-menu-item.es-disabled:hover {+ background: transparent;+ color: var(--es-text-secondary);+}++.es-menu-item.es-disabled:hover .es-menu-item-shortcut {+ color: var(--es-text-secondary);+}++.es-menu-item-text {+ flex: 1;+}++.es-menu-item-shortcut {+ margin-left: 24px;+ font-size: 11px;+ color: var(--es-text-secondary);+}++.es-menu-divider {+ height: 1px;+ margin: 4px 8px;+ background: var(--es-border);+}++.es-editor-menubar .es-btn-preview {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0 8px;+ padding: 4px 12px;+ background: var(--es-success);+ border: none;+ color: white;+ font-size: 11px;+ font-weight: 500;+ border-radius: 3px;+ cursor: pointer;+ transition: background 0.15s;+}++.es-editor-menubar .es-btn-preview:hover {+ background: #5cb85c;+}++.es-editor-menubar .es-btn-preview svg {+ stroke: white;+}++.es-editor-menubar .es-btn-preview.es-btn-danger {+ background: var(--es-error);+}++.es-editor-menubar .es-btn-preview.es-btn-danger:hover {+ background: #c9302c;+}++.es-editor-dock {+ flex: 1;+ overflow: hidden;+}++.dockview-theme-dark {+ --dv-background-color: var(--es-bg-primary);+ --dv-group-view-background-color: var(--es-bg-primary);+ --dv-tabs-and-actions-container-background-color: var(--es-bg-secondary);+ --dv-tabs-and-actions-container-height: 30px;+ --dv-tabs-and-actions-container-font-size: 12px;+ --dv-activegroup-visiblepanel-tab-background-color: var(--es-bg-primary);+ --dv-activegroup-hiddenpanel-tab-background-color: var(--es-bg-secondary);+ --dv-inactivegroup-visiblepanel-tab-background-color: var(--es-bg-tertiary);+ --dv-inactivegroup-hiddenpanel-tab-background-color: var(--es-bg-secondary);+ --dv-activegroup-visiblepanel-tab-color: var(--es-accent-gold);+ --dv-activegroup-hiddenpanel-tab-color: var(--es-text-secondary);+ --dv-inactivegroup-visiblepanel-tab-color: var(--es-text-primary);+ --dv-inactivegroup-hiddenpanel-tab-color: var(--es-text-secondary);+ --dv-separator-border: var(--es-border);+ --dv-tab-divider-color: var(--es-border);+ --dv-active-sash-color: var(--es-accent);+ --dv-drag-over-background-color: rgba(0, 120, 212, 0.15);+ --dv-drag-over-border-color: var(--es-accent);+}++/* =============================================================================+ * Context Menu+ * ============================================================================= */++.es-context-menu {+ position: fixed;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 4px;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);+ min-width: 160px;+ padding: 4px 0;+ z-index: 2000;+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ font-size: 12px;+}++.es-context-menu-item {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 12px;+ color: var(--es-text-primary);+ cursor: pointer;+ position: relative;+ transition: background 0.15s;+}++.es-context-menu-item:hover {+ background: var(--es-accent);+ color: white;+}++.es-context-menu-item.es-disabled {+ color: var(--es-text-disabled);+ cursor: default;+}++.es-context-menu-item.es-disabled:hover {+ background: transparent;+ color: var(--es-text-disabled);+}++.es-context-menu-icon {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 16px;+ flex-shrink: 0;+}++.es-context-menu-label {+ flex: 1;+}++.es-context-menu-shortcut {+ color: var(--es-text-secondary);+ font-size: 11px;+ margin-left: auto;+}++.es-context-menu-item:hover .es-context-menu-shortcut {+ color: rgba(255, 255, 255, 0.7);+}++.es-context-menu-arrow {+ display: flex;+ align-items: center;+ margin-left: auto;+}++.es-context-menu-separator {+ height: 1px;+ margin: 4px 8px;+ background: var(--es-border);+}++/* =============================================================================+ * Status Bar+ * ============================================================================= */++.es-editor-statusbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ height: 24px;+ padding: 0 4px;+ background: var(--es-bg-tertiary);+ border-top: 1px solid var(--es-border);+ font-size: 11px;+}++.es-statusbar-left,+.es-statusbar-right {+ display: flex;+ align-items: center;+ gap: 2px;+ height: 100%;+ flex-shrink: 0;+}++.es-statusbar-left {+ flex-shrink: 1;+ min-width: 0;+ overflow: hidden;+}++.es-statusbar-left > span,+.es-statusbar-right > span,+.es-statusbar-cmd-wrapper {+ display: contents;+}++.es-btn-dropdown,+.es-btn-tab {+ display: flex;+ align-items: center;+ gap: 4px;+ height: 100%;+ padding: 0 10px;+ background: transparent;+ border: none;+ border-radius: 0;+ color: var(--es-text-secondary);+ font-size: 11px;+ cursor: pointer;+}++.es-btn-dropdown:hover,+.es-btn-tab:hover {+ background: var(--es-bg-hover);+ color: var(--es-text-primary);+}++.es-btn-dropdown svg,+.es-btn-tab svg {+ stroke: var(--es-text-secondary);+}++.es-btn-dropdown:hover svg,+.es-btn-tab:hover svg {+ stroke: var(--es-text-primary);+}++.es-status-indicator {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 0 8px;+ height: 100%;+ color: var(--es-text-secondary);+}++.es-status-indicator svg {+ stroke: var(--es-text-secondary);+}++.es-status-saved {+ color: var(--es-text-secondary);+}++.es-status-saved svg {+ stroke: var(--es-text-secondary);+}++.es-status-unsaved {+ color: var(--es-warning);+}++.es-unsaved-dot {+ display: inline-block;+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--es-warning);+}++.es-statusbar-message {+ padding: 0 8px;+ font-size: 11px;+ color: var(--es-text-secondary);+ white-space: nowrap;+}++.es-statusbar-icons {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 0 8px;+ border-left: 1px solid var(--es-border);+}++.es-statusbar-icons button {+ display: flex;+ align-items: center;+ justify-content: center;+ min-width: 20px;+ height: 20px;+ padding: 0 4px;+ background: transparent;+ border: none;+ border-radius: 2px;+ cursor: pointer;+ color: var(--es-text-secondary);+ font-size: 11px;+}++.es-statusbar-icons button:hover {+ background: var(--es-bg-hover);+}++.es-statusbar-icons svg {+ stroke: var(--es-text-secondary);+}++/* Active state for statusbar buttons */+.es-btn-dropdown.es-active,+.es-btn-tab.es-active {+ color: var(--es-accent-gold);+}++.es-btn-dropdown.es-active svg,+.es-btn-tab.es-active svg {+ stroke: var(--es-accent-gold);+}++/* =============================================================================+ * Statusbar Command Input+ * ============================================================================= */++.es-statusbar-divider {+ width: 1px;+ height: 14px;+ background: var(--es-border);+ margin: 0 6px;+}++.es-statusbar-btn {+ display: flex;+ align-items: center;+ gap: 4px;+ height: 20px;+ padding: 0 8px;+ background: transparent;+ border: none;+ border-radius: 3px;+ color: var(--es-text-secondary);+ font-size: 11px;+ cursor: pointer;+ white-space: nowrap;+}++.es-statusbar-btn:hover {+ background: var(--es-bg-hover);+ color: var(--es-text-primary);+}++.es-statusbar-btn svg {+ stroke: var(--es-text-secondary);+}++.es-statusbar-btn:hover svg {+ stroke: var(--es-text-primary);+}++.es-statusbar-btn-primary {+ background: var(--es-bg-tertiary);+ border: 1px solid var(--es-border);+ color: var(--es-text-primary);+}++.es-statusbar-btn-primary:hover {+ background: var(--es-bg-hover);+ border-color: var(--es-text-secondary);+}++.es-statusbar-btn-primary svg {+ stroke: var(--es-text-primary);+}++.es-statusbar-btn.es-active {+ color: var(--es-text-primary);+}++.es-statusbar-btn.es-active svg {+ stroke: var(--es-text-primary);+}++.es-cmd-prompt {+ color: var(--es-text-secondary);+ font-size: 12px;+ font-weight: 500;+ margin: 0 4px;+}++.es-cmd-input {+ flex: 1;+ min-width: 150px;+ max-width: 300px;+ height: 20px;+ padding: 0 8px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ border-radius: 3px;+ color: var(--es-text-primary);+ font-size: 11px;+ outline: none;+}++.es-cmd-input::placeholder {+ color: var(--es-text-secondary);+}++.es-cmd-input:focus {+ border-color: var(--es-accent);+}diff --git a/editor/src/styles/panels.css b/editor/src/styles/panels.cssnew file mode 100644index 000000000..35470e4a6--- /dev/null+++ b/editor/src/styles/panels.css@@ -0,0 +1,29 @@+/* =============================================================================+ * Panels+ * ============================================================================= */++.es-panel-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 6px 12px;+ background: var(--es-bg-secondary);+ border-bottom: 1px solid var(--es-border);+}++.es-panel-title {+ display: flex;+ align-items: center;+ gap: 6px;+ font-weight: 600;+ font-size: 12px;+}++.es-panel-title svg {+ stroke: var(--es-text-secondary);+}++.es-panel-actions {+ display: flex;+ gap: 4px;+}diff --git a/editor/src/styles/scene-view.css b/editor/src/styles/scene-view.cssnew file mode 100644index 000000000..6c141ace7--- /dev/null+++ b/editor/src/styles/scene-view.css@@ -0,0 +1,192 @@+/* =============================================================================+ * SceneView Panel+ * ============================================================================= */++.es-sceneview-panel {+ height: 100%;+ display: flex;+ flex-direction: column;+}++.es-sceneview-tools {+ display: flex;+ align-items: center;+ gap: 8px;+}++.es-zoom-display {+ font-size: 11px;+ color: var(--es-text-secondary);+ min-width: 40px;+}++.es-sceneview-viewport {+ flex: 1;+ position: relative;+ overflow: hidden;+ background: #1a1a1a;+}++.es-sceneview-webgl {+ position: absolute;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ display: block;+ pointer-events: none;+}++.es-sceneview-overlay {+ position: absolute;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ display: block;+ pointer-events: auto;+}++.es-sceneview-canvas {+ display: block;+}++.es-gizmo-toolbar {+ display: flex;+ gap: 2px;+ background: var(--es-bg-tertiary);+ border-radius: 4px;+ padding: 2px;+}++.es-gizmo-btn {+ background: transparent;+ border: none;+ border-radius: 3px;+ padding: 4px;+ opacity: 0.6;+}++.es-gizmo-btn:hover {+ background: var(--es-bg-hover);+ opacity: 1;+}++.es-gizmo-btn.es-active {+ background: var(--es-accent);+ opacity: 1;+}++.es-gizmo-btn.es-active svg {+ stroke: white;+}++.es-toolbar-divider {+ width: 1px;+ height: 20px;+ background: var(--es-border);+ margin: 0 4px;+}++/* Gizmo Settings Dropdown */+.es-gizmo-settings-wrapper {+ position: relative;+}++.es-gizmo-settings-dropdown {+ position: absolute;+ top: 100%;+ right: 0;+ margin-top: 4px;+ min-width: 180px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 4px;+ padding: 8px;+ z-index: 1000;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);+}++.es-settings-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 4px 0;+ gap: 8px;+}++.es-settings-label {+ font-size: 11px;+ color: var(--es-text-secondary);+ white-space: nowrap;+}++.es-settings-checkbox {+ display: flex;+ align-items: center;+ gap: 6px;+ font-size: 11px;+ color: var(--es-text-primary);+ cursor: pointer;+}++.es-settings-checkbox input[type="checkbox"] {+ width: 14px;+ height: 14px;+ cursor: pointer;+ accent-color: var(--es-accent);+}++.es-settings-divider {+ height: 1px;+ background: var(--es-border);+ margin: 6px 0;+}++.es-color-input {+ width: 32px;+ height: 22px;+ padding: 0;+ border: 1px solid var(--es-border);+ border-radius: 3px;+ background: transparent;+ cursor: pointer;+}++.es-color-input::-webkit-color-swatch-wrapper {+ padding: 2px;+}++.es-color-input::-webkit-color-swatch {+ border: none;+ border-radius: 2px;+}++.es-slider-input {+ width: 80px;+ height: 4px;+ -webkit-appearance: none;+ appearance: none;+ background: var(--es-bg-tertiary);+ border-radius: 2px;+ cursor: pointer;+}++.es-slider-input::-webkit-slider-thumb {+ -webkit-appearance: none;+ appearance: none;+ width: 12px;+ height: 12px;+ border-radius: 50%;+ background: var(--es-accent);+ cursor: pointer;+}++.es-slider-input::-moz-range-thumb {+ width: 12px;+ height: 12px;+ border-radius: 50%;+ background: var(--es-accent);+ border: none;+ cursor: pointer;+}diff --git a/editor/src/ui/ContentDrawer.ts b/editor/src/ui/ContentDrawer.tsindex d176c3000..ea33fb04d 100644--- a/editor/src/ui/ContentDrawer.ts+++ b/editor/src/ui/ContentDrawer.ts@@ -1,6 +1,7 @@import type { DockLayoutManager } from '../DockLayoutManager';import type { EditorStore } from '../store/EditorStore';-import { ContentBrowserPanel, type ContentBrowserOptions } from '../panels/ContentBrowserPanel';+import { ContentBrowserPanel } from '../panels/content-browser/ContentBrowserPanel';+import type { ContentBrowserOptions } from '../panels/content-browser/ContentBrowserTypes';import { icons } from '../utils/icons';type DrawerState = 'hidden' | 'open';diff --git a/sdk/package.json b/sdk/package.jsonindex 94f22e961..1138dcc59 100644--- a/sdk/package.json+++ b/sdk/package.json@@ -15,17 +15,16 @@"import": "./dist/wasm.js","types": "./dist/wasm.d.ts"},- "./scene": {- "import": "./dist/scene/index.js",- "types": "./dist/scene/index.d.ts"- },- "./assets": {- "import": "./dist/assets/index.js",- "types": "./dist/assets/index.d.ts"+ "./wechat": {+ "import": "./dist/index.wechat.js"},"./spine": {"import": "./dist/spine/index.js","types": "./dist/spine/index.d.ts"+ },+ "./physics": {+ "import": "./dist/physics/index.js",+ "types": "./dist/physics/index.d.ts"}},"files": [diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 166eb6b4e..dd12a79e2 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -18,6 +18,7 @@ import { initGeometryAPI, shutdownGeometryAPI } from './geometry';import { initPostProcessAPI, shutdownPostProcessAPI } from './postprocess';import { initRendererAPI, shutdownRendererAPI } from './renderer';import { initGLDebugAPI, shutdownGLDebugAPI } from './glDebug';+import { setWasmErrorHandler } from './wasmError';import { platformNow } from './platform';import { ProjectionType, ScaleMode, SceneOwner } from './component';import type { Entity } from './types';@@ -71,6 +72,7 @@ export class App {private physicsInitPromise_?: Promise<unknown>;private physicsModule_?: unknown;private readonly installed_plugins_ = new Set<Plugin>();+ private readonly sortedSystemsCache_ = new Map<Schedule, SystemEntry[]>();private error_handler_: ((error: unknown, systemName: string) => void) | null = null;private system_error_handler_: ((error: Error, systemName?: string) => 'continue' | 'pause') | null = null;private frame_paused_ = false;@@ -124,6 +126,7 @@ export class App {runBefore: options?.runBefore,runAfter: options?.runAfter,});+ this.sortedSystemsCache_.delete(schedule);return this;}@@ -157,6 +160,10 @@ export class App {return this.pipeline_;}+ setPipeline(pipeline: RenderPipeline): void {+ this.pipeline_ = pipeline;+ }+setSpineRenderer(fn: SpineRendererFn | null): void {this.pipeline_?.setSpineRenderer(fn);}@@ -222,6 +229,11 @@ export class App {return this;}+ onWasmError(handler: (error: unknown, context: string) => void): this {+ setWasmErrorHandler(handler);+ return this;+ }+// =========================================================================// Resource Access// =========================================================================@@ -406,13 +418,19 @@ export class App {}private runSchedule(schedule: Schedule): void {- let systems = this.systems_.get(schedule);- if (!systems || !this.runner_ || this.frame_paused_) {+ const rawSystems = this.systems_.get(schedule);+ if (!rawSystems || !this.runner_ || this.frame_paused_) {return;}- if (systems.some(s => s.runBefore || s.runAfter)) {- systems = this.sortSystems(systems);+ let systems = this.sortedSystemsCache_.get(schedule);+ if (!systems) {+ if (rawSystems.some(s => s.runBefore || s.runAfter)) {+ systems = this.sortSystems(rawSystems);+ } else {+ systems = rawSystems;+ }+ this.sortedSystemsCache_.set(schedule, systems);}for (const entry of systems) {@@ -474,7 +492,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): AinitGLDebugAPI(module);const pipeline = new RenderPipeline();- (app as any).pipeline_ = pipeline;+ app.setPipeline(pipeline);let startTime = platformNow();const getViewportSize = options?.getViewportSize ?? (() => ({diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex 26134f97a..cf15a3cbd 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -527,3 +527,9 @@ export {initGLDebugAPI,shutdownGLDebugAPI,} from './glDebug';++// =============================================================================+// WASM Error Handling+// =============================================================================++export { setWasmErrorHandler } from './wasmError';diff --git a/sdk/src/draw.ts b/sdk/src/draw.tsindex d2ab5543a..582267d40 100644--- a/sdk/src/draw.ts+++ b/sdk/src/draw.ts@@ -11,6 +11,7 @@ import type { GeometryHandle } from './geometry';import type { ShaderHandle, MaterialHandle } from './material';import { Material, isTextureRef } from './material';import { BlendMode } from './blend';+import { handleWasmError } from './wasmError';export { BlendMode } from './blend';@@ -205,78 +206,114 @@ const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 };export const Draw: DrawAPI = {begin(viewProjection: Float32Array): void {const m = getModule();- m.HEAPF32.set(viewProjection, viewProjectionPtr / 4);- m.draw_begin(viewProjectionPtr);+ try {+ m.HEAPF32.set(viewProjection, viewProjectionPtr / 4);+ m.draw_begin(viewProjectionPtr);+ } catch (e) {+ handleWasmError(e, 'Draw.begin');+ }},end(): void {- getModule().draw_end();+ try {+ getModule().draw_end();+ } catch (e) {+ handleWasmError(e, 'Draw.end');+ }},line(from: Vec2, to: Vec2, color: Color, thickness = 1): void {- getModule().draw_line(- from.x, from.y,- to.x, to.y,- color.r, color.g, color.b, color.a,- thickness- );+ try {+ getModule().draw_line(+ from.x, from.y,+ to.x, to.y,+ color.r, color.g, color.b, color.a,+ thickness+ );+ } catch (e) {+ handleWasmError(e, 'Draw.line');+ }},rect(position: Vec2, size: Vec2, color: Color, filled = true): void {- getModule().draw_rect(- position.x, position.y,- size.x, size.y,- color.r, color.g, color.b, color.a,- filled- );+ try {+ getModule().draw_rect(+ position.x, position.y,+ size.x, size.y,+ color.r, color.g, color.b, color.a,+ filled+ );+ } catch (e) {+ handleWasmError(e, 'Draw.rect');+ }},rectOutline(position: Vec2, size: Vec2, color: Color, thickness = 1): void {- getModule().draw_rectOutline(- position.x, position.y,- size.x, size.y,- color.r, color.g, color.b, color.a,- thickness- );+ try {+ getModule().draw_rectOutline(+ position.x, position.y,+ size.x, size.y,+ color.r, color.g, color.b, color.a,+ thickness+ );+ } catch (e) {+ handleWasmError(e, 'Draw.rectOutline');+ }},circle(center: Vec2, radius: number, color: Color, filled = true, segments = 32): void {- getModule().draw_circle(- center.x, center.y,- radius,- color.r, color.g, color.b, color.a,- filled,- segments- );+ try {+ getModule().draw_circle(+ center.x, center.y,+ radius,+ color.r, color.g, color.b, color.a,+ filled,+ segments+ );+ } catch (e) {+ handleWasmError(e, 'Draw.circle');+ }},circleOutline(center: Vec2, radius: number, color: Color, thickness = 1, segments = 32): void {- getModule().draw_circleOutline(- center.x, center.y,- radius,- color.r, color.g, color.b, color.a,- thickness,- segments- );+ try {+ getModule().draw_circleOutline(+ center.x, center.y,+ radius,+ color.r, color.g, color.b, color.a,+ thickness,+ segments+ );+ } catch (e) {+ handleWasmError(e, 'Draw.circleOutline');+ }},texture(position: Vec2, size: Vec2, textureHandle: number, tint: Color = WHITE): void {- getModule().draw_texture(- position.x, position.y,- size.x, size.y,- textureHandle,- tint.r, tint.g, tint.b, tint.a- );+ try {+ getModule().draw_texture(+ position.x, position.y,+ size.x, size.y,+ textureHandle,+ tint.r, tint.g, tint.b, tint.a+ );+ } catch (e) {+ handleWasmError(e, 'Draw.texture');+ }},textureRotated(position: Vec2, size: Vec2, rotation: number, textureHandle: number, tint: Color = WHITE): void {- getModule().draw_textureRotated(- position.x, position.y,- size.x, size.y,- rotation,- textureHandle,- tint.r, tint.g, tint.b, tint.a- );+ try {+ getModule().draw_textureRotated(+ position.x, position.y,+ size.x, size.y,+ rotation,+ textureHandle,+ tint.r, tint.g, tint.b, tint.a+ );+ } catch (e) {+ handleWasmError(e, 'Draw.textureRotated');+ }},setLayer(layer: number): void {@@ -306,92 +343,100 @@ export const Draw: DrawAPI = {},drawMesh(geometry: GeometryHandle, shader: ShaderHandle, transform: Float32Array): void {- const m = getModule();- m.HEAPF32.set(transform, transformPtr / 4);- m.draw_mesh(geometry, shader, transformPtr);+ try {+ const m = getModule();+ m.HEAPF32.set(transform, transformPtr / 4);+ m.draw_mesh(geometry, shader, transformPtr);+ } catch (e) {+ handleWasmError(e, `Draw.drawMesh(geometry=${geometry}, shader=${shader})`);+ }},drawMeshWithMaterial(geometry: GeometryHandle, material: MaterialHandle, transform: Float32Array): void {- const m = getModule();- const matData = Material.get(material);- if (!matData) return;+ try {+ const m = getModule();+ const matData = Material.get(material);+ if (!matData) return;- Draw.setBlendMode(matData.blendMode);- Draw.setDepthTest(matData.depthTest);+ Draw.setBlendMode(matData.blendMode);+ Draw.setDepthTest(matData.depthTest);- if (matData.uniforms.size === 0) {- Draw.drawMesh(geometry, matData.shader, transform);- return;- }+ if (matData.uniforms.size === 0) {+ Draw.drawMesh(geometry, matData.shader, transform);+ return;+ }- m.HEAPF32.set(transform, transformPtr / 4);-- let idx: number;- if (!matData.dirty_ && matData.cachedBuffer_) {- idx = matData.cachedIdx_;- } else {- idx = 0;- let autoTextureSlot = 0;- for (const [name, value] of matData.uniforms) {- const nameId = getUniformNameId(name);- if (nameId < 0) continue;-- if (isTextureRef(value)) {- uniformBuffer[idx++] = 10;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.slot ?? autoTextureSlot++;- uniformBuffer[idx++] = value.textureId;- } else if (typeof value === 'number') {- uniformBuffer[idx++] = 1;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value;- } else if (Array.isArray(value)) {- uniformBuffer[idx++] = value.length;- uniformBuffer[idx++] = nameId;- for (let i = 0; i < value.length; i++) {- uniformBuffer[idx++] = value[i];+ m.HEAPF32.set(transform, transformPtr / 4);++ let idx: number;+ if (!matData.dirty_ && matData.cachedBuffer_) {+ idx = matData.cachedIdx_;+ } else {+ idx = 0;+ let autoTextureSlot = 0;+ for (const [name, value] of matData.uniforms) {+ const nameId = getUniformNameId(name);+ if (nameId < 0) continue;++ if (isTextureRef(value)) {+ uniformBuffer[idx++] = 10;+ uniformBuffer[idx++] = nameId;+ uniformBuffer[idx++] = value.slot ?? autoTextureSlot++;+ uniformBuffer[idx++] = value.textureId;+ } else if (typeof value === 'number') {+ uniformBuffer[idx++] = 1;+ uniformBuffer[idx++] = nameId;+ uniformBuffer[idx++] = value;+ } else if (Array.isArray(value)) {+ uniformBuffer[idx++] = value.length;+ uniformBuffer[idx++] = nameId;+ for (let i = 0; i < value.length; i++) {+ uniformBuffer[idx++] = value[i];+ }+ } else if ('w' in value) {+ uniformBuffer[idx++] = 4;+ uniformBuffer[idx++] = nameId;+ uniformBuffer[idx++] = value.x;+ uniformBuffer[idx++] = value.y;+ uniformBuffer[idx++] = value.z;+ uniformBuffer[idx++] = value.w;+ } else if ('z' in value) {+ uniformBuffer[idx++] = 3;+ uniformBuffer[idx++] = nameId;+ uniformBuffer[idx++] = value.x;+ uniformBuffer[idx++] = value.y;+ uniformBuffer[idx++] = value.z;+ } else {+ uniformBuffer[idx++] = 2;+ uniformBuffer[idx++] = nameId;+ uniformBuffer[idx++] = value.x;+ uniformBuffer[idx++] = value.y;+ }++ if (idx > UNIFORMS_BUFFER_SIZE - 6) {+ console.warn('Uniform buffer overflow, some uniforms will be ignored');+ break;}- } else if ('w' in value) {- uniformBuffer[idx++] = 4;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- uniformBuffer[idx++] = value.w;- } else if ('z' in value) {- uniformBuffer[idx++] = 3;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;- uniformBuffer[idx++] = value.z;- } else {- uniformBuffer[idx++] = 2;- uniformBuffer[idx++] = nameId;- uniformBuffer[idx++] = value.x;- uniformBuffer[idx++] = value.y;}- if (idx > UNIFORMS_BUFFER_SIZE - 6) {- console.warn('Uniform buffer overflow, some uniforms will be ignored');- break;+ if (!matData.cachedBuffer_ || matData.cachedBuffer_.length < idx) {+ matData.cachedBuffer_ = new Float32Array(idx);}+ matData.cachedBuffer_.set(uniformBuffer.subarray(0, idx));+ matData.cachedIdx_ = idx;+ matData.dirty_ = false;}- if (!matData.cachedBuffer_ || matData.cachedBuffer_.length < idx) {- matData.cachedBuffer_ = new Float32Array(idx);+ if (idx === 0) {+ m.draw_mesh(geometry, matData.shader, transformPtr);+ return;}- matData.cachedBuffer_.set(uniformBuffer.subarray(0, idx));- matData.cachedIdx_ = idx;- matData.dirty_ = false;- }- if (idx === 0) {- m.draw_mesh(geometry, matData.shader, transformPtr);- return;+ m.HEAPF32.set(matData.cachedBuffer_!.subarray(0, idx), uniformsPtr / 4);+ m.draw_meshWithUniforms(geometry, matData.shader, transformPtr, uniformsPtr, idx);+ } catch (e) {+ handleWasmError(e, `Draw.drawMeshWithMaterial(geometry=${geometry}, material=${material})`);}-- m.HEAPF32.set(matData.cachedBuffer_!.subarray(0, idx), uniformsPtr / 4);- m.draw_meshWithUniforms(geometry, matData.shader, transformPtr, uniformsPtr, idx);},};@@ -416,6 +461,17 @@ const UNIFORM_NAME_MAP: Record<string, number> = {'u_texture3': 17,};+const warnedUniforms = new Set<string>();+function getUniformNameId(name: string): number {- return UNIFORM_NAME_MAP[name] ?? -1;+ const id = UNIFORM_NAME_MAP[name];+ if (id !== undefined) return id;+ if (!warnedUniforms.has(name)) {+ warnedUniforms.add(name);+ console.warn(+ `[ESEngine] Unknown uniform name "${name}" - ` ++ `supported names: ${Object.keys(UNIFORM_NAME_MAP).join(', ')}`+ );+ }+ return -1;}diff --git a/sdk/src/postprocess.ts b/sdk/src/postprocess.tsindex 80e872709..d4e113601 100644--- a/sdk/src/postprocess.ts+++ b/sdk/src/postprocess.ts@@ -7,6 +7,7 @@import type { ESEngineModule } from './wasm';import type { ShaderHandle, Vec4 } from './material';import { Material } from './material';+import { handleWasmError } from './wasmError';// =============================================================================// Internal State@@ -48,14 +49,23 @@ export const PostProcess = {* @returns True on success*/init(width: number, height: number): boolean {- return getModule().postprocess_init(width, height);+ try {+ return getModule().postprocess_init(width, height);+ } catch (e) {+ handleWasmError(e, `PostProcess.init(${width}x${height})`);+ return false;+ }},/*** Shuts down the post-processing pipeline.*/shutdown(): void {- getModule().postprocess_shutdown();+ try {+ getModule().postprocess_shutdown();+ } catch (e) {+ handleWasmError(e, 'PostProcess.shutdown');+ }},/**@@ -64,7 +74,11 @@ export const PostProcess = {* @param height New height*/resize(width: number, height: number): void {- getModule().postprocess_resize(width, height);+ try {+ getModule().postprocess_resize(width, height);+ } catch (e) {+ handleWasmError(e, `PostProcess.resize(${width}x${height})`);+ }},/**@@ -74,7 +88,12 @@ export const PostProcess = {* @returns Pass index*/addPass(name: string, shader: ShaderHandle): number {- return getModule().postprocess_addPass(name, shader);+ try {+ return getModule().postprocess_addPass(name, shader);+ } catch (e) {+ handleWasmError(e, `PostProcess.addPass("${name}")`);+ return -1;+ }},/**@@ -82,7 +101,11 @@ export const PostProcess = {* @param name Pass name*/removePass(name: string): void {- getModule().postprocess_removePass(name);+ try {+ getModule().postprocess_removePass(name);+ } catch (e) {+ handleWasmError(e, `PostProcess.removePass("${name}")`);+ }},/**@@ -91,7 +114,11 @@ export const PostProcess = {* @param enabled Whether to enable the pass*/setEnabled(name: string, enabled: boolean): void {- getModule().postprocess_setPassEnabled(name, enabled);+ try {+ getModule().postprocess_setPassEnabled(name, enabled);+ } catch (e) {+ handleWasmError(e, `PostProcess.setEnabled("${name}")`);+ }},/**@@ -100,7 +127,12 @@ export const PostProcess = {* @returns True if enabled*/isEnabled(name: string): boolean {- return getModule().postprocess_isPassEnabled(name);+ try {+ return getModule().postprocess_isPassEnabled(name);+ } catch (e) {+ handleWasmError(e, `PostProcess.isEnabled("${name}")`);+ return false;+ }},/**@@ -110,7 +142,11 @@ export const PostProcess = {* @param value Float value*/setUniform(passName: string, uniform: string, value: number): void {- getModule().postprocess_setUniformFloat(passName, uniform, value);+ try {+ getModule().postprocess_setUniformFloat(passName, uniform, value);+ } catch (e) {+ handleWasmError(e, `PostProcess.setUniform("${passName}", "${uniform}")`);+ }},/**@@ -120,7 +156,11 @@ export const PostProcess = {* @param value Vec4 value*/setUniformVec4(passName: string, uniform: string, value: Vec4): void {- getModule().postprocess_setUniformVec4(passName, uniform, value.x, value.y, value.z, value.w);+ try {+ getModule().postprocess_setUniformVec4(passName, uniform, value.x, value.y, value.z, value.w);+ } catch (e) {+ handleWasmError(e, `PostProcess.setUniformVec4("${passName}", "${uniform}")`);+ }},/**@@ -128,7 +168,11 @@ export const PostProcess = {* Call this before rendering your scene.*/begin(): void {- getModule().postprocess_begin();+ try {+ getModule().postprocess_begin();+ } catch (e) {+ handleWasmError(e, 'PostProcess.begin');+ }},/**@@ -136,14 +180,23 @@ export const PostProcess = {* Call this after rendering your scene.*/end(): void {- getModule().postprocess_end();+ try {+ getModule().postprocess_end();+ } catch (e) {+ handleWasmError(e, 'PostProcess.end');+ }},/*** Gets the number of passes.*/getPassCount(): number {- return getModule().postprocess_getPassCount();+ try {+ return getModule().postprocess_getPassCount();+ } catch (e) {+ handleWasmError(e, 'PostProcess.getPassCount');+ return 0;+ }},/**@@ -151,7 +204,12 @@ export const PostProcess = {*/isInitialized(): boolean {if (!module) return false;- return module.postprocess_isInitialized();+ try {+ return module.postprocess_isInitialized();+ } catch (e) {+ handleWasmError(e, 'PostProcess.isInitialized');+ return false;+ }},/**@@ -161,7 +219,11 @@ export const PostProcess = {* @param bypass Whether to bypass the pipeline*/setBypass(bypass: boolean): void {- getModule().postprocess_setBypass(bypass);+ try {+ getModule().postprocess_setBypass(bypass);+ } catch (e) {+ handleWasmError(e, 'PostProcess.setBypass');+ }},/**@@ -170,7 +232,12 @@ export const PostProcess = {*/isBypassed(): boolean {if (!module) return true;- return module.postprocess_isBypassed();+ try {+ return module.postprocess_isBypassed();+ } catch (e) {+ handleWasmError(e, 'PostProcess.isBypassed');+ return true;+ }},// =========================================================================diff --git a/sdk/src/renderer.ts b/sdk/src/renderer.tsindex e6af8a4d6..8ab362185 100644--- a/sdk/src/renderer.ts+++ b/sdk/src/renderer.ts@@ -1,4 +1,5 @@import type { ESEngineModule, CppRegistry } from './wasm';+import { handleWasmError } from './wasmError';export enum RenderStage {Background = 0,@@ -46,31 +47,55 @@ export const Renderer = {begin(viewProjection: Float32Array, target?: RenderTargetHandle): void {if (!module || !viewProjectionPtr) return;- module.HEAPF32.set(viewProjection, viewProjectionPtr / 4);- module.renderer_begin(viewProjectionPtr, target ?? 0);+ try {+ module.HEAPF32.set(viewProjection, viewProjectionPtr / 4);+ module.renderer_begin(viewProjectionPtr, target ?? 0);+ } catch (e) {+ handleWasmError(e, 'Renderer.begin');+ }},flush(): void {- module?.renderer_flush();+ try {+ module?.renderer_flush();+ } catch (e) {+ handleWasmError(e, 'Renderer.flush');+ }},end(): void {- module?.renderer_end();+ try {+ module?.renderer_end();+ } catch (e) {+ handleWasmError(e, 'Renderer.end');+ }},submitSprites(registry: { _cpp: CppRegistry }): void {if (!module) return;- module.renderer_submitSprites(registry._cpp);+ try {+ module.renderer_submitSprites(registry._cpp);+ } catch (e) {+ handleWasmError(e, 'Renderer.submitSprites');+ }},submitBitmapText(registry: { _cpp: CppRegistry }): void {if (!module) return;- module.renderer_submitBitmapText(registry._cpp);+ try {+ module.renderer_submitBitmapText(registry._cpp);+ } catch (e) {+ handleWasmError(e, 'Renderer.submitBitmapText');+ }},submitSpine(registry: { _cpp: CppRegistry }): void {if (!module) return;- module.renderer_submitSpine?.(registry._cpp);+ try {+ module.renderer_submitSpine?.(registry._cpp);+ } catch (e) {+ handleWasmError(e, 'Renderer.submitSpine');+ }},setStage(stage: RenderStage): void {diff --git a/sdk/src/wasmError.ts b/sdk/src/wasmError.tsnew file mode 100644index 000000000..bc6059cd1--- /dev/null+++ b/sdk/src/wasmError.ts@@ -0,0 +1,14 @@+type WasmErrorHandler = (error: unknown, context: string) => void;++let errorHandler: WasmErrorHandler | null = null;++export function setWasmErrorHandler(handler: WasmErrorHandler | null): void {+ errorHandler = handler;+}++export function handleWasmError(error: unknown, context: string): void {+ console.error(`[ESEngine] WASM error in ${context}:`, error);+ if (errorHandler) {+ errorHandler(error, context);+ }+}diff --git a/sdk/src/world.ts b/sdk/src/world.tsindex c3419fdc0..e7993e6c2 100644--- a/sdk/src/world.ts+++ b/sdk/src/world.ts@@ -7,6 +7,7 @@ import { Entity } from './types';import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent } from './component';import type { CppRegistry } from './wasm';import { validateComponentData, formatValidationErrors } from './validation';+import { handleWasmError } from './wasmError';function convertForWasm(obj: Record<string, unknown>): Record<string, unknown> {const result: Record<string, unknown> = {};@@ -78,7 +79,12 @@ export class World {let entity: Entity;if (this.cppRegistry_) {- entity = this.cppRegistry_.create();+ try {+ entity = this.cppRegistry_.create();+ } catch (e) {+ handleWasmError(e, 'spawn');+ throw e;+ }} else {entity = (this.entities_.size + 1) as Entity;}@@ -96,7 +102,11 @@ export class World {}if (this.cppRegistry_) {- this.cppRegistry_.destroy(entity);+ try {+ this.cppRegistry_.destroy(entity);+ } catch (e) {+ handleWasmError(e, `despawn(entity=${entity})`);+ }}this.entities_.delete(entity);this.worldVersion_++;@@ -150,13 +160,21 @@ export class World {setParent(child: Entity, parent: Entity): void {if (this.cppRegistry_) {- this.cppRegistry_.setParent(child, parent);+ try {+ this.cppRegistry_.setParent(child, parent);+ } catch (e) {+ handleWasmError(e, `setParent(child=${child}, parent=${parent})`);+ }}}removeParent(entity: Entity): void {if (this.cppRegistry_) {- this.cppRegistry_.removeParent(entity);+ try {+ this.cppRegistry_.removeParent(entity);+ } catch (e) {+ handleWasmError(e, `removeParent(entity=${entity})`);+ }}}@@ -188,9 +206,14 @@ export class World {tryGet<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> | null {if (isBuiltinComponent(component)) {if (!this.cppRegistry_) return null;- const methods = this.getBuiltinMethods(component._cppName);- if (!methods.has(entity)) return null;- return methods.get(entity) as ComponentData<C>;+ try {+ const methods = this.getBuiltinMethods(component._cppName);+ if (!methods.has(entity)) return null;+ return methods.get(entity) as ComponentData<C>;+ } catch (e) {+ handleWasmError(e, `tryGet(${component._name}, entity=${entity})`);+ return null;+ }}if (!this.hasScript(entity, component as ComponentDef<any>)) return null;return this.getScript(entity, component as ComponentDef<any>) as ComponentData<C>;@@ -251,7 +274,11 @@ export class World {const merged = { ...component._default, ...filtered } as T;if (this.cppRegistry_) {- this.getBuiltinMethods(component._cppName).add(entity, convertForWasm(merged as Record<string, unknown>));+ try {+ this.getBuiltinMethods(component._cppName).add(entity, convertForWasm(merged as Record<string, unknown>));+ } catch (e) {+ handleWasmError(e, `insertBuiltin(${component._name}, entity=${entity})`);+ }}return merged;@@ -261,21 +288,35 @@ export class World {if (!this.cppRegistry_) {throw new Error('C++ Registry not connected');}- return this.getBuiltinMethods(component._cppName).get(entity) as T;+ try {+ return this.getBuiltinMethods(component._cppName).get(entity) as T;+ } catch (e) {+ handleWasmError(e, `getBuiltin(${component._name}, entity=${entity})`);+ return { ...component._default } as T;+ }}private hasBuiltin(entity: Entity, component: BuiltinComponentDef<any>): boolean {if (!this.cppRegistry_) {return false;}- return this.getBuiltinMethods(component._cppName).has(entity);+ try {+ return this.getBuiltinMethods(component._cppName).has(entity);+ } catch (e) {+ handleWasmError(e, `hasBuiltin(${component._name}, entity=${entity})`);+ return false;+ }}private removeBuiltin(entity: Entity, component: BuiltinComponentDef<any>): void {if (!this.cppRegistry_) {return;}- this.getBuiltinMethods(component._cppName).remove(entity);+ try {+ this.getBuiltinMethods(component._cppName).remove(entity);+ } catch (e) {+ handleWasmError(e, `removeBuiltin(${component._name}, entity=${entity})`);+ }}// =========================================================================diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex 02961a160..67f62480f 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -407,6 +407,12 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {.function("valid", optional_override([](Registry& r, u32 e) {return r.valid(static_cast<Entity>(e));}))+ .function("generation", optional_override([](Registry& r, u32 e) {+ return r.generation(static_cast<Entity>(e));+ }))+ .function("validWithGeneration", optional_override([](Registry& r, u32 e, u32 gen) {+ return r.valid(static_cast<Entity>(e), gen);+ })).function("entityCount", &Registry::entityCount)// BoxColliderdiff --git a/src/esengine/core/Log.cpp b/src/esengine/core/Log.cppindex bcc1abef9..d14969300 100644--- a/src/esengine/core/Log.cpp+++ b/src/esengine/core/Log.cpp@@ -19,7 +19,9 @@ namespace esengine {LogLevel Log::level_ = LogLevel::Info;std::vector<std::pair<u32, LogSink>> Log::sinks_;+#ifndef ES_PLATFORM_WEBstd::mutex Log::sinkMutex_;+#endifu32 Log::nextSinkId_ = 1;void Log::init() {@@ -56,14 +58,18 @@ const char* Log::levelToString(LogLevel level) {}u32 Log::addSink(LogSink sink) {+#ifndef ES_PLATFORM_WEBstd::lock_guard<std::mutex> lock(sinkMutex_);+#endifu32 id = nextSinkId_++;sinks_.emplace_back(id, std::move(sink));return id;}void Log::removeSink(u32 sinkId) {+#ifndef ES_PLATFORM_WEBstd::lock_guard<std::mutex> lock(sinkMutex_);+#endifsinks_.erase(std::remove_if(sinks_.begin(), sinks_.end(),[sinkId](const auto& pair) { return pair.first == sinkId; }),@@ -71,7 +77,9 @@ void Log::removeSink(u32 sinkId) {}void Log::notifySinks(LogLevel level, const std::string& message) {+#ifndef ES_PLATFORM_WEBstd::lock_guard<std::mutex> lock(sinkMutex_);+#endifauto now = std::chrono::system_clock::now();auto duration = now.time_since_epoch();diff --git a/src/esengine/core/Log.hpp b/src/esengine/core/Log.hppindex fcfca4335..32172f3fb 100644--- a/src/esengine/core/Log.hpp+++ b/src/esengine/core/Log.hpp@@ -23,7 +23,9 @@#include <functional>#include <iomanip>#include <iostream>+#ifndef ES_PLATFORM_WEB#include <mutex>+#endif#include <sstream>#include <string>#include <vector>@@ -185,7 +187,9 @@ public:private:static LogLevel level_;static std::vector<std::pair<u32, LogSink>> sinks_;+#ifndef ES_PLATFORM_WEBstatic std::mutex sinkMutex_;+#endifstatic u32 nextSinkId_;template<typename... Args>diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hppindex cc7e0e484..f185526ad 100644--- a/src/esengine/ecs/Registry.hpp+++ b/src/esengine/ecs/Registry.hpp@@ -93,8 +93,10 @@ public:if (entity >= entityValid_.size()) {entityValid_.resize(entity + 1, false);+ generations_.resize(entity + 1, 0);}entityValid_[entity] = true;+ generations_[entity]++;++entity_count_;ES_LOG_TRACE("Created entity {}", entity);@@ -127,8 +129,10 @@ public:if (entity >= entityValid_.size()) {entityValid_.resize(entity + 1, false);+ generations_.resize(entity + 1, 0);}entityValid_[entity] = true;+ generations_[entity]++;++entity_count_;if (entity >= nextEntity_) {@@ -173,10 +177,22 @@ public:return entity < entityValid_.size() && entityValid_[entity];}- /**- * @brief Gets the number of active (non-destroyed) entities- * @return Count of valid entities- */+ bool valid(Entity entity, u32 generation) const {+ return valid(entity) && entity < generations_.size() &&+ generations_[entity] == generation;+ }++ u32 generation(Entity entity) const {+ if (entity < generations_.size()) {+ return generations_[entity];+ }+ return 0;+ }++ u64 entityHandle(Entity entity) const {+ return makeEntityHandle(entity, generation(entity));+ }+usize entityCount() const {return entity_count_;}@@ -390,6 +406,7 @@ public:pool->clear();}entityValid_.clear();+ generations_.clear();while (!recycled_.empty()) recycled_.pop();nextEntity_ = 0;entity_count_ = 0;@@ -551,13 +568,10 @@ private:// Data Members// =========================================================================- /** @brief Validity flags for each entity ID */std::vector<bool> entityValid_;- /** @brief Queue of recycled entity IDs */+ std::vector<u32> generations_;std::queue<Entity> recycled_;- /** @brief Next entity ID to allocate */Entity nextEntity_ = 0;- /** @brief Cached count of valid entities */usize entity_count_ = 0;/** @brief Type-erased component pools indexed by TypeId */diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cppindex c37a2ba3b..65a0c4186 100644--- a/src/esengine/renderer/RenderFrame.cpp+++ b/src/esengine/renderer/RenderFrame.cpp@@ -119,6 +119,13 @@ void RenderFrame::init(u32 width, u32 height) {post_process_->init(width, height);items_.reserve(1024);+ sorted_indices_.reserve(1024);+ sprite_data_.reserve(512);+ text_data_.reserve(64);+ ext_data_.reserve(32);+#ifdef ES_ENABLE_SPINE+ spine_data_.reserve(32);+#endif#ifdef ES_ENABLE_SPINEspine_vertices_.reserve(1024);@@ -183,9 +190,7 @@ void RenderFrame::init(u32 width, u32 height) {}}- for (u32 i = 0; i < SPINE_MAX_TEXTURE_SLOTS; ++i) {- spine_texture_slots_[i] = context_.getWhiteTextureId();- }+ spine_tex_slots_.init(context_.getWhiteTextureId());#endifglGenVertexArrays(1, &ext_mesh_vao_);@@ -251,6 +256,13 @@ void RenderFrame::shutdown() {mat_sprite_ebo_initialized_ = false;items_.clear();+ sorted_indices_.clear();+ sprite_data_.clear();+ text_data_.clear();+ ext_data_.clear();+#ifdef ES_ENABLE_SPINE+ spine_data_.clear();+#endifES_LOG_INFO("RenderFrame shutdown");}@@ -271,6 +283,13 @@ void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::Hin_frame_ = true;items_.clear();+ sorted_indices_.clear();+ sprite_data_.clear();+ text_data_.clear();+ ext_data_.clear();+#ifdef ES_ENABLE_SPINE+ spine_data_.clear();+#endifext_storage_count_ = 0;ext_submit_order_ = 0;stats_ = Stats{};@@ -368,47 +387,51 @@ void RenderFrame::submitSprites(ecs::Registry& registry) {continue;}- RenderItem item;- item.entity = entity;- item.type = RenderType::Sprite;- item.stage = current_stage_;+ RenderItemBase base;+ base.entity = entity;+ base.type = RenderType::Sprite;+ base.stage = current_stage_;- item.world_position = position;- item.world_scale = glm::vec2(scale);+ base.world_position = position;+ base.world_scale = glm::vec2(scale);f32 sinHalfAngle = rotation.z;f32 cosHalfAngle = rotation.w;- item.world_angle = 2.0f * std::atan2(sinHalfAngle, cosHalfAngle);+ base.world_angle = 2.0f * std::atan2(sinHalfAngle, cosHalfAngle);++ base.layer = sprite.layer;+ base.depth = position.z;+ base.color = sprite.color;++ base.texture_id = context_.getWhiteTextureId();++ SpriteData sd;+ sd.size = sprite.size;+ sd.uv_offset = sprite.uvOffset;+ sd.uv_scale = sprite.uvScale;+ sd.flip_x = sprite.flipX;+ sd.flip_y = sprite.flipY;+ sd.material_id = sprite.material;if (sprite.material != 0) {- item.transform = glm::mat4(1.0f);- item.transform = glm::translate(item.transform, position);- item.transform *= glm::mat4_cast(rotation);- item.transform = glm::scale(item.transform, scale);+ sd.transform = glm::mat4(1.0f);+ sd.transform = glm::translate(sd.transform, position);+ sd.transform *= glm::mat4_cast(rotation);+ sd.transform = glm::scale(sd.transform, scale);}- item.layer = sprite.layer;- item.depth = position.z;- item.size = sprite.size;- item.color = sprite.color;- item.uv_offset = sprite.uvOffset;- item.uv_scale = sprite.uvScale;- item.flip_x = sprite.flipX;- item.flip_y = sprite.flipY;-- item.texture_id = context_.getWhiteTextureId();if (sprite.texture.isValid()) {Texture* tex = resource_manager_.getTexture(sprite.texture);if (tex) {- item.texture_id = tex->getId();- item.texture_size = glm::vec2(+ base.texture_id = tex->getId();+ sd.texture_size = glm::vec2(static_cast<f32>(tex->getWidth()),static_cast<f32>(tex->getHeight()));const auto* metadata = resource_manager_.getTextureMetadata(sprite.texture);if (metadata && metadata->sliceBorder.hasSlicing()) {- item.use_nine_slice = true;- item.slice_border = glm::vec4(+ sd.use_nine_slice = true;+ sd.slice_border = glm::vec4(metadata->sliceBorder.left,metadata->sliceBorder.right,metadata->sliceBorder.top,@@ -418,17 +441,17 @@ void RenderFrame::submitSprites(ecs::Registry& registry) {}}- item.material_id = sprite.material;-if (!clip_rects_.empty()) {auto it = clip_rects_.find(static_cast<u32>(entity));if (it != clip_rects_.end()) {- item.scissor_enabled = true;- item.scissor = it->second;+ base.scissor_enabled = true;+ base.scissor = it->second;}}- items_.push_back(item);+ base.data_index = static_cast<u32>(sprite_data_.size());+ sprite_data_.push_back(sd);+ items_.push_back(base);stats_.sprites++;}}@@ -476,34 +499,37 @@ void RenderFrame::submitBitmapText(ecs::Registry& registry) {continue;}- RenderItem item;- item.entity = entity;- item.type = RenderType::Text;- item.stage = current_stage_;-- item.world_position = position;- item.world_scale = glm::vec2(scale);- item.layer = bt.layer;- item.depth = position.z;- item.color = bt.color;- item.texture_id = tex->getId();-- item.font_data = font;- item.text_data = bt.text.c_str();- item.text_length = static_cast<u16>(bt.text.size());- item.font_size = bt.fontSize;- item.text_align = static_cast<u8>(bt.align);- item.text_spacing = bt.spacing;+ RenderItemBase base;+ base.entity = entity;+ base.type = RenderType::Text;+ base.stage = current_stage_;++ base.world_position = position;+ base.world_scale = glm::vec2(scale);+ base.layer = bt.layer;+ base.depth = position.z;+ base.color = bt.color;+ base.texture_id = tex->getId();++ TextData td;+ td.font_data = font;+ td.text_data = bt.text.c_str();+ td.text_length = static_cast<u16>(bt.text.size());+ td.font_size = bt.fontSize;+ td.text_align = static_cast<u8>(bt.align);+ td.text_spacing = bt.spacing;if (!clip_rects_.empty()) {auto it = clip_rects_.find(static_cast<u32>(entity));if (it != clip_rects_.end()) {- item.scissor_enabled = true;- item.scissor = it->second;+ base.scissor_enabled = true;+ base.scissor = it->second;}}- items_.push_back(item);+ base.data_index = static_cast<u32>(text_data_.size());+ text_data_.push_back(td);+ items_.push_back(base);stats_.text++;}}@@ -534,36 +560,41 @@ void RenderFrame::submitSpine(ecs::Registry& registry, spine::SpineSystem& spinescale = local.scale;}- RenderItem item;- item.entity = entity;- item.type = RenderType::Spine;- item.stage = current_stage_;-- item.transform = glm::mat4(1.0f);- item.transform = glm::translate(item.transform, position);- item.transform *= glm::mat4_cast(rotation);- item.transform = glm::scale(item.transform, scale);-- item.world_position = position;- item.world_scale = glm::vec2(scale);-- item.layer = comp.layer;- item.depth = position.z;- item.skeleton = instance->skeleton.get();- item.tint_color = comp.color;- item.material_id = comp.material;-- items_.push_back(item);+ RenderItemBase base;+ base.entity = entity;+ base.type = RenderType::Spine;+ base.stage = current_stage_;++ base.world_position = position;+ base.world_scale = glm::vec2(scale);+ base.layer = comp.layer;+ base.depth = position.z;++ SpineData sd;+ sd.transform = glm::mat4(1.0f);+ sd.transform = glm::translate(sd.transform, position);+ sd.transform *= glm::mat4_cast(rotation);+ sd.transform = glm::scale(sd.transform, scale);+ sd.skeleton = instance->skeleton.get();+ sd.tint_color = comp.color;+ sd.material_id = comp.material;++ base.data_index = static_cast<u32>(spine_data_.size());+ spine_data_.push_back(sd);+ items_.push_back(base);stats_.spine++;}}#endif-void RenderFrame::submit(const RenderItem& item) {- RenderItem copy = item;+void RenderFrame::submit(const RenderItemBase& item, const SpriteData& data) {+ RenderItemBase copy = item;if (copy.stage == RenderStage::Transparent && copy.stage != current_stage_) {copy.stage = current_stage_;}++ copy.data_index = static_cast<u32>(sprite_data_.size());+ sprite_data_.push_back(data);items_.push_back(copy);switch (copy.type) {@@ -596,30 +627,39 @@ void RenderFrame::submitExternalTriangles(}u32 storageIdx = ext_storage_count_++;+ RenderItemBase base;+ base.type = RenderType::ExternalMesh;+ base.stage = current_stage_;+ base.texture_id = 0;+ base.depth = 1.0f - static_cast<f32>(ext_submit_order_++) * 0.0001f;+ base.blend_mode = static_cast<BlendMode>(blendMode);- RenderItem item;- item.type = RenderType::ExternalMesh;- item.stage = current_stage_;- item.ext_bind_texture = textureId;- item.texture_id = 0;- item.depth = 1.0f - static_cast<f32>(ext_submit_order_++) * 0.0001f;- item.blend_mode = static_cast<BlendMode>(blendMode);- item.ext_vertices = ext_vertex_storage_[storageIdx].data();- item.ext_vertex_count = vertexCount;- item.ext_indices = ext_index_storage_[storageIdx].data();- item.ext_index_count = indexCount;+ ExternalMeshData ed;+ ed.ext_bind_texture = textureId;+ ed.ext_vertices = ext_vertex_storage_[storageIdx].data();+ ed.ext_vertex_count = vertexCount;+ ed.ext_indices = ext_index_storage_[storageIdx].data();+ ed.ext_index_count = indexCount;if (transform16) {- item.transform = glm::make_mat4(transform16);+ ed.transform = glm::make_mat4(transform16);}- items_.push_back(item);+ base.data_index = static_cast<u32>(ext_data_.size());+ ext_data_.push_back(ed);+ items_.push_back(base);}void RenderFrame::sortAndBucket() {- std::sort(items_.begin(), items_.end(),- [](const RenderItem& a, const RenderItem& b) {- return a.sortKey() < b.sortKey();+ u32 n = static_cast<u32>(items_.size());+ sorted_indices_.resize(n);+ for (u32 i = 0; i < n; ++i) {+ sorted_indices_[i] = i;+ }++ std::sort(sorted_indices_.begin(), sorted_indices_.end(),+ [this](u32 a, u32 b) {+ return items_[a].sortKey() < items_[b].sortKey();});for (auto& sb : stage_boundaries_) {@@ -627,16 +667,15 @@ void RenderFrame::sortAndBucket() {sb.end = 0;}- if (items_.empty()) return;+ if (n == 0) return;- u32 n = static_cast<u32>(items_.size());u32 i = 0;while (i < n) {- auto stage = items_[i].stage;+ auto stage = items_[sorted_indices_[i]].stage;u32 stageIdx = static_cast<u32>(stage);if (stageIdx < STAGE_COUNT) {stage_boundaries_[stageIdx].begin = i;- while (i < n && items_[i].stage == stage) {+ while (i < n && items_[sorted_indices_[i]].stage == stage) {++i;}stage_boundaries_[stageIdx].end = i;@@ -654,7 +693,7 @@ void RenderFrame::executeStage(RenderStage stage) {if (sb.begin >= sb.end) return;u32 batchStart = sb.begin;- RenderType currentType = items_[batchStart].type;+ RenderType currentType = items_[sorted_indices_[batchStart]].type;auto flushBatch = [&](u32 begin, u32 end) {switch (currentType) {@@ -681,10 +720,10 @@ void RenderFrame::executeStage(RenderStage stage) {};for (u32 i = sb.begin; i < sb.end; ++i) {- if (items_[i].type != currentType) {+ if (items_[sorted_indices_[i]].type != currentType) {flushBatch(batchStart, i);batchStart = i;- currentType = items_[i].type;+ currentType = items_[sorted_indices_[i]].type;}}@@ -699,68 +738,69 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {ScissorRect curRect{};for (u32 i = begin; i < end; ++i) {- auto* item = &items_[i];+ const auto& base = items_[sorted_indices_[i]];+ const auto& sd = sprite_data_[base.data_index];- if (item->scissor_enabled != curScissorOn ||- (item->scissor_enabled && item->scissor != curRect)) {+ if (base.scissor_enabled != curScissorOn ||+ (base.scissor_enabled && base.scissor != curRect)) {batcher_->flush();- if (item->scissor_enabled) {+ if (base.scissor_enabled) {glEnable(GL_SCISSOR_TEST);- glScissor(item->scissor.x, item->scissor.y,- item->scissor.w, item->scissor.h);+ glScissor(base.scissor.x, base.scissor.y,+ base.scissor.w, base.scissor.h);} else {glDisable(GL_SCISSOR_TEST);}- curScissorOn = item->scissor_enabled;- curRect = item->scissor;+ curScissorOn = base.scissor_enabled;+ curRect = base.scissor;}- if (item->material_id != 0) {+ if (sd.material_id != 0) {batcher_->flush();- renderSpriteWithMaterial(item);+ renderSpriteWithMaterial(base, sd);continue;}- glm::vec2 position(item->world_position);- glm::vec2 finalSize = item->size * item->world_scale;- f32 angle = item->world_angle;+ glm::vec2 position(base.world_position);+ glm::vec2 finalSize = sd.size * base.world_scale;+ f32 angle = base.world_angle;- if (item->use_nine_slice) {+ if (sd.use_nine_slice) {resource::SliceBorder border;- border.left = item->slice_border.x;- border.right = item->slice_border.y;- border.top = item->slice_border.z;- border.bottom = item->slice_border.w;+ border.left = sd.slice_border.x;+ border.right = sd.slice_border.y;+ border.top = sd.slice_border.z;+ border.bottom = sd.slice_border.w;batcher_->drawNineSlice(position,finalSize,- item->texture_id,- item->texture_size,+ base.texture_id,+ sd.texture_size,border,- item->color,+ base.color,angle,- item->uv_offset,- item->uv_scale+ sd.uv_offset,+ sd.uv_scale);} else if (std::abs(angle) > 0.001f) {batcher_->drawRotatedQuad(position,finalSize,angle,- item->texture_id,- item->color,- item->uv_offset,- item->uv_scale+ base.texture_id,+ base.color,+ sd.uv_offset,+ sd.uv_scale);} else {batcher_->drawQuad(- glm::vec3(position.x, position.y, item->depth),+ glm::vec3(position.x, position.y, base.depth),finalSize,- item->texture_id,- item->color,- item->uv_offset,- item->uv_scale+ base.texture_id,+ base.color,+ sd.uv_offset,+ sd.uv_scale);}}@@ -779,16 +819,14 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {void RenderFrame::renderSpine(u32 begin, u32 end) {spine_vertices_.clear();spine_indices_.clear();- spine_texture_slot_index_ = 1;- for (u32 i = 0; i < SPINE_MAX_TEXTURE_SLOTS; ++i) {- spine_texture_slots_[i] = context_.getWhiteTextureId();- }+ spine_tex_slots_.reset();static ::spine::SkeletonClipping clipper;for (u32 idx = begin; idx < end; ++idx) {- auto* item = &items_[idx];- auto* skeleton = static_cast<::spine::Skeleton*>(item->skeleton);+ const auto& base = items_[sorted_indices_[idx]];+ const auto& sd = spine_data_[base.data_index];+ auto* skeleton = static_cast<::spine::Skeleton*>(sd.skeleton);if (!skeleton) continue;auto& drawOrder = skeleton->getDrawOrder();@@ -851,24 +889,10 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {RenderCommand::setBlendMode(blendMode);}- f32 texIndex = 0.0f;- if (textureId != 0) {- bool found = false;- for (u32 s = 0; s < spine_texture_slot_index_; ++s) {- if (spine_texture_slots_[s] == textureId) {- texIndex = static_cast<f32>(s);- found = true;- break;- }- }- if (!found) {- if (spine_texture_slot_index_ >= SPINE_MAX_TEXTURE_SLOTS) {- flushSpineBatch();- }- spine_texture_slots_[spine_texture_slot_index_] = textureId;- texIndex = static_cast<f32>(spine_texture_slot_index_);- spine_texture_slot_index_++;- }+ f32 texIndex = spine_tex_slots_.findOrAllocate(textureId);+ if (texIndex < 0.0f) {+ flushSpineBatch();+ texIndex = spine_tex_slots_.findOrAllocate(textureId);}if (spine_vertices_.size() + 4 > 65535) {@@ -878,10 +902,10 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {auto& uvs = region->getUVs();auto& attachColor = region->getColor();- f32 a = skelColor.a * slotColor.a * attachColor.a * item->tint_color.a;- f32 r = skelColor.r * slotColor.r * attachColor.r * item->tint_color.r;- f32 g = skelColor.g * slotColor.g * attachColor.g * item->tint_color.g;- f32 b = skelColor.b * slotColor.b * attachColor.b * item->tint_color.b;+ f32 a = skelColor.a * slotColor.a * attachColor.a * sd.tint_color.a;+ f32 r = skelColor.r * slotColor.r * attachColor.r * sd.tint_color.r;+ f32 g = skelColor.g * slotColor.g * attachColor.g * sd.tint_color.g;+ f32 b = skelColor.b * slotColor.b * attachColor.b * sd.tint_color.b;if (blendMode == BlendMode::PremultipliedAlpha || blendMode == BlendMode::PmaAdditive) {r *= a;@@ -893,10 +917,10 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {for (size_t j = 0; j < 4; ++j) {glm::vec4 pos(spine_world_vertices_[j * 2], spine_world_vertices_[j * 2 + 1], 0.0f, 1.0f);- pos = item->transform * pos;+ pos = sd.transform * pos;SpineVertex vertex;- vertex.position = glm::vec3(pos.x, pos.y, item->depth);+ vertex.position = glm::vec3(pos.x, pos.y, base.depth);vertex.color = glm::vec4(r, g, b, a);vertex.uv = glm::vec2(uvs[j * 2], uvs[j * 2 + 1]);vertex.texIndex = texIndex;@@ -942,24 +966,10 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {RenderCommand::setBlendMode(blendMode);}- f32 texIndex = 0.0f;- if (textureId != 0) {- bool found = false;- for (u32 s = 0; s < spine_texture_slot_index_; ++s) {- if (spine_texture_slots_[s] == textureId) {- texIndex = static_cast<f32>(s);- found = true;- break;- }- }- if (!found) {- if (spine_texture_slot_index_ >= SPINE_MAX_TEXTURE_SLOTS) {- flushSpineBatch();- }- spine_texture_slots_[spine_texture_slot_index_] = textureId;- texIndex = static_cast<f32>(spine_texture_slot_index_);- spine_texture_slot_index_++;- }+ f32 texIndex = spine_tex_slots_.findOrAllocate(textureId);+ if (texIndex < 0.0f) {+ flushSpineBatch();+ texIndex = spine_tex_slots_.findOrAllocate(textureId);}if (spine_vertices_.size() + vertexCount > 65535) {@@ -970,10 +980,10 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {auto& triangles = mesh->getTriangles();auto& attachColor = mesh->getColor();- f32 a = skelColor.a * slotColor.a * attachColor.a * item->tint_color.a;- f32 r = skelColor.r * slotColor.r * attachColor.r * item->tint_color.r;- f32 g = skelColor.g * slotColor.g * attachColor.g * item->tint_color.g;- f32 b = skelColor.b * slotColor.b * attachColor.b * item->tint_color.b;+ f32 a = skelColor.a * slotColor.a * attachColor.a * sd.tint_color.a;+ f32 r = skelColor.r * slotColor.r * attachColor.r * sd.tint_color.r;+ f32 g = skelColor.g * slotColor.g * attachColor.g * sd.tint_color.g;+ f32 b = skelColor.b * slotColor.b * attachColor.b * sd.tint_color.b;if (blendMode == BlendMode::PremultipliedAlpha || blendMode == BlendMode::PmaAdditive) {r *= a;@@ -985,10 +995,10 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {for (size_t j = 0; j < vertexCount; ++j) {glm::vec4 pos(spine_world_vertices_[j * 2], spine_world_vertices_[j * 2 + 1], 0.0f, 1.0f);- pos = item->transform * pos;+ pos = sd.transform * pos;SpineVertex vertex;- vertex.position = glm::vec3(pos.x, pos.y, item->depth);+ vertex.position = glm::vec3(pos.x, pos.y, base.depth);vertex.color = glm::vec4(r, g, b, a);vertex.uv = glm::vec2(uvs[j * 2], uvs[j * 2 + 1]);vertex.texIndex = texIndex;@@ -1019,13 +1029,10 @@ void RenderFrame::flushSpineBatch() {return;}- for (u32 i = 0; i < SPINE_MAX_TEXTURE_SLOTS; ++i) {- glActiveTexture(GL_TEXTURE0 + i);- glBindTexture(GL_TEXTURE_2D, spine_texture_slots_[i]);- }+ spine_tex_slots_.bindAll();shader->bind();- shader->setUniform("u_projection", view_projection_);+ shader->setUniform(shader->getUniformLocation("u_projection"), view_projection_);glBindVertexArray(spine_vao_);@@ -1055,10 +1062,7 @@ void RenderFrame::flushSpineBatch() {spine_vertices_.clear();spine_indices_.clear();- spine_texture_slot_index_ = 1;- for (u32 i = 0; i < SPINE_MAX_TEXTURE_SLOTS; ++i) {- spine_texture_slots_[i] = context_.getWhiteTextureId();- }+ spine_tex_slots_.reset();}#endif@@ -1067,59 +1071,65 @@ void RenderFrame::renderExternalMeshes(u32 begin, u32 end) {if (!shader) shader = context_.getTextureShader();if (!shader) return;+ i32 locProjection = shader->getUniformLocation("u_projection");+ i32 locModel = shader->getUniformLocation("u_model");+ i32 locTexture = shader->getUniformLocation("u_texture");+for (u32 idx = begin; idx < end; ++idx) {- auto* item = &items_[idx];- if (!item->ext_vertices || !item->ext_indices ||- item->ext_vertex_count <= 0 || item->ext_index_count <= 0) {+ const auto& base = items_[sorted_indices_[idx]];+ const auto& ed = ext_data_[base.data_index];+ if (!ed.ext_vertices || !ed.ext_indices ||+ ed.ext_vertex_count <= 0 || ed.ext_index_count <= 0) {continue;}- RenderCommand::setBlendMode(item->blend_mode);+ RenderCommand::setBlendMode(base.blend_mode);shader->bind();- shader->setUniform("u_projection", view_projection_);- shader->setUniform("u_model", item->transform);+ shader->setUniform(locProjection, view_projection_);+ shader->setUniform(locModel, ed.transform);glActiveTexture(GL_TEXTURE0);- glBindTexture(GL_TEXTURE_2D, item->ext_bind_texture);- shader->setUniform("u_texture", 0);+ glBindTexture(GL_TEXTURE_2D, ed.ext_bind_texture);+ shader->setUniform(locTexture, 0);glBindVertexArray(ext_mesh_vao_);auto vboBytes = static_cast<GLsizeiptr>(- item->ext_vertex_count * 8 * sizeof(f32));+ ed.ext_vertex_count * 8 * sizeof(f32));glBindBuffer(GL_ARRAY_BUFFER, ext_mesh_vbo_);if (static_cast<u32>(vboBytes) > ext_mesh_vbo_capacity_) {ext_mesh_vbo_capacity_ = static_cast<u32>(vboBytes) * 2;glBufferData(GL_ARRAY_BUFFER, ext_mesh_vbo_capacity_,nullptr, GL_STREAM_DRAW);}- glBufferSubData(GL_ARRAY_BUFFER, 0, vboBytes, item->ext_vertices);+ glBufferSubData(GL_ARRAY_BUFFER, 0, vboBytes, ed.ext_vertices);auto eboBytes = static_cast<GLsizeiptr>(- item->ext_index_count * sizeof(u16));+ ed.ext_index_count * sizeof(u16));glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ext_mesh_ebo_);if (static_cast<u32>(eboBytes) > ext_mesh_ebo_capacity_) {ext_mesh_ebo_capacity_ = static_cast<u32>(eboBytes) * 2;glBufferData(GL_ELEMENT_ARRAY_BUFFER, ext_mesh_ebo_capacity_,nullptr, GL_STREAM_DRAW);}- glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, eboBytes, item->ext_indices);+ glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, eboBytes, ed.ext_indices);- glDrawElements(GL_TRIANGLES, item->ext_index_count,+ glDrawElements(GL_TRIANGLES, ed.ext_index_count,GL_UNSIGNED_SHORT, nullptr);glBindVertexArray(0);- stats_.triangles += static_cast<u32>(item->ext_index_count / 3);+ stats_.triangles += static_cast<u32>(ed.ext_index_count / 3);stats_.draw_calls++;}}void RenderFrame::renderMeshes(u32 begin, u32 end) {for (u32 i = begin; i < end; ++i) {- auto* item = &items_[i];- if (!item->geometry || !item->shader) continue;+ const auto& base = items_[sorted_indices_[i]];+ const auto& sd = sprite_data_[base.data_index];+ if (!sd.geometry || !sd.shader) continue;stats_.draw_calls++;}}@@ -1161,24 +1171,25 @@ void RenderFrame::renderText(u32 begin, u32 end) {ScissorRect curRect{};for (u32 i = begin; i < end; ++i) {- auto* item = &items_[i];+ const auto& base = items_[sorted_indices_[i]];+ const auto& td = text_data_[base.data_index];- if (item->scissor_enabled != curScissorOn ||- (item->scissor_enabled && item->scissor != curRect)) {+ if (base.scissor_enabled != curScissorOn ||+ (base.scissor_enabled && base.scissor != curRect)) {batcher_->flush();- if (item->scissor_enabled) {+ if (base.scissor_enabled) {glEnable(GL_SCISSOR_TEST);- glScissor(item->scissor.x, item->scissor.y,- item->scissor.w, item->scissor.h);+ glScissor(base.scissor.x, base.scissor.y,+ base.scissor.w, base.scissor.h);} else {glDisable(GL_SCISSOR_TEST);}- curScissorOn = item->scissor_enabled;- curRect = item->scissor;+ curScissorOn = base.scissor_enabled;+ curRect = base.scissor;}- auto* font = static_cast<const text::BitmapFont*>(item->font_data);- if (!font || !item->text_data || item->text_length == 0) {+ auto* font = static_cast<const text::BitmapFont*>(td.font_data);+ if (!font || !td.text_data || td.text_length == 0) {continue;}@@ -1194,15 +1205,15 @@ void RenderFrame::renderText(u32 begin, u32 end) {continue;}- f32 scale = item->font_size * item->world_scale.x;- f32 spacing = item->text_spacing;+ f32 scale = td.font_size * base.world_scale.x;+ f32 spacing = td.text_spacing;f32 fontBase = font->getBase();f32 totalWidth = 0;- if (item->text_align != 0) {+ if (td.text_align != 0) {u32 prevChar = 0;- for (u16 j = 0; j < item->text_length; ++j) {- u32 charCode = decodeUtf8(item->text_data, item->text_length, j);+ for (u16 j = 0; j < td.text_length; ++j) {+ u32 charCode = decodeUtf8(td.text_data, td.text_length, j);auto* glyph = font->getGlyph(charCode);if (!glyph) {continue;@@ -1216,18 +1227,18 @@ void RenderFrame::renderText(u32 begin, u32 end) {}f32 alignOffset = 0;- if (item->text_align == 1) {+ if (td.text_align == 1) {alignOffset = -totalWidth * 0.5f;- } else if (item->text_align == 2) {+ } else if (td.text_align == 2) {alignOffset = -totalWidth;}- f32 cursorX = item->world_position.x + alignOffset;- f32 baseY = item->world_position.y;+ f32 cursorX = base.world_position.x + alignOffset;+ f32 baseY = base.world_position.y;u32 prevChar = 0;- for (u16 j = 0; j < item->text_length; ++j) {- u32 charCode = decodeUtf8(item->text_data, item->text_length, j);+ for (u16 j = 0; j < td.text_length; ++j) {+ u32 charCode = decodeUtf8(td.text_data, td.text_length, j);auto* glyph = font->getGlyph(charCode);if (!glyph) {continue;@@ -1253,7 +1264,7 @@ void RenderFrame::renderText(u32 begin, u32 end) {glm::vec2(posX, posY),glm::vec2(glyphW, glyphH),textureId,- item->color,+ base.color,uvOffset,uvScale);@@ -1274,13 +1285,13 @@ void RenderFrame::renderText(u32 begin, u32 end) {stats_.triangles += batcher_->getQuadCount() * 2;}-void RenderFrame::renderSpriteWithMaterial(RenderItem* item) {+void RenderFrame::renderSpriteWithMaterial(const RenderItemBase& base, const SpriteData& sd) {u32 shaderId = 0;u32 blendMode = 0;static std::vector<UniformData> uniforms;uniforms.clear();- if (!getMaterialDataWithUniforms(item->material_id, shaderId, blendMode, uniforms)) {+ if (!getMaterialDataWithUniforms(sd.material_id, shaderId, blendMode, uniforms)) {return;}@@ -1288,34 +1299,41 @@ void RenderFrame::renderSpriteWithMaterial(RenderItem* item) {if (!shader) return;shader->bind();- shader->setUniform("u_projection", view_projection_);- shader->setUniform("u_model", item->transform);- shader->setUniform("u_color", item->color);++ i32 locProj = shader->getUniformLocation("u_projection");+ i32 locModel = shader->getUniformLocation("u_model");+ i32 locColor = shader->getUniformLocation("u_color");+ i32 locTex = shader->getUniformLocation("u_texture");++ shader->setUniform(locProj, view_projection_);+ shader->setUniform(locModel, sd.transform);+ shader->setUniform(locColor, base.color);glActiveTexture(GL_TEXTURE0);- glBindTexture(GL_TEXTURE_2D, item->texture_id);- shader->setUniform("u_texture", 0);+ glBindTexture(GL_TEXTURE_2D, base.texture_id);+ shader->setUniform(locTex, 0);for (const auto& ud : uniforms) {+ i32 loc = shader->getUniformLocation(ud.name);switch (ud.type) {case 0:- shader->setUniform(ud.name, ud.values[0]);+ shader->setUniform(loc, ud.values[0]);break;case 1:- shader->setUniform(ud.name, glm::vec2(ud.values[0], ud.values[1]));+ shader->setUniform(loc, glm::vec2(ud.values[0], ud.values[1]));break;case 2:- shader->setUniform(ud.name, glm::vec3(ud.values[0], ud.values[1], ud.values[2]));+ shader->setUniform(loc, glm::vec3(ud.values[0], ud.values[1], ud.values[2]));break;case 3:- shader->setUniform(ud.name, glm::vec4(ud.values[0], ud.values[1], ud.values[2], ud.values[3]));+ shader->setUniform(loc, glm::vec4(ud.values[0], ud.values[1], ud.values[2], ud.values[3]));break;}}RenderCommand::setBlendMode(static_cast<BlendMode>(blendMode));- glm::vec2 halfSize = item->size * 0.5f;+ glm::vec2 halfSize = sd.size * 0.5f;struct MatSpriteVertex {f32 px, py;@@ -1324,10 +1342,10 @@ void RenderFrame::renderSpriteWithMaterial(RenderItem* item) {};MatSpriteVertex vertices[4] = {- { -halfSize.x, -halfSize.y, 0.0f, 1.0f, item->color.r, item->color.g, item->color.b, item->color.a },- { halfSize.x, -halfSize.y, 1.0f, 1.0f, item->color.r, item->color.g, item->color.b, item->color.a },- { halfSize.x, halfSize.y, 1.0f, 0.0f, item->color.r, item->color.g, item->color.b, item->color.a },- { -halfSize.x, halfSize.y, 0.0f, 0.0f, item->color.r, item->color.g, item->color.b, item->color.a },+ { -halfSize.x, -halfSize.y, 0.0f, 1.0f, base.color.r, base.color.g, base.color.b, base.color.a },+ { halfSize.x, -halfSize.y, 1.0f, 1.0f, base.color.r, base.color.g, base.color.b, base.color.a },+ { halfSize.x, halfSize.y, 1.0f, 0.0f, base.color.r, base.color.g, base.color.b, base.color.a },+ { -halfSize.x, halfSize.y, 0.0f, 0.0f, base.color.r, base.color.g, base.color.b, base.color.a },};glBindVertexArray(mat_sprite_vao_);@@ -1339,24 +1357,24 @@ void RenderFrame::renderSpriteWithMaterial(RenderItem* item) {}glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);- GLint locPos = shader->getAttribLocation("a_position");- if (locPos >= 0) {- glEnableVertexAttribArray(locPos);- glVertexAttribPointer(locPos, 2, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),+ GLint attrPos = shader->getAttribLocation("a_position");+ if (attrPos >= 0) {+ glEnableVertexAttribArray(attrPos);+ glVertexAttribPointer(attrPos, 2, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),reinterpret_cast<void*>(0));}- GLint locTex = shader->getAttribLocation("a_texCoord");- if (locTex >= 0) {- glEnableVertexAttribArray(locTex);- glVertexAttribPointer(locTex, 2, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),+ GLint attrTex = shader->getAttribLocation("a_texCoord");+ if (attrTex >= 0) {+ glEnableVertexAttribArray(attrTex);+ glVertexAttribPointer(attrTex, 2, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),reinterpret_cast<void*>(2 * sizeof(f32)));}- GLint locColor = shader->getAttribLocation("a_color");- if (locColor >= 0) {- glEnableVertexAttribArray(locColor);- glVertexAttribPointer(locColor, 4, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),+ GLint attrColor = shader->getAttribLocation("a_color");+ if (attrColor >= 0) {+ glEnableVertexAttribArray(attrColor);+ glVertexAttribPointer(attrColor, 4, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),reinterpret_cast<void*>(4 * sizeof(f32)));}@@ -1371,9 +1389,9 @@ void RenderFrame::renderSpriteWithMaterial(RenderItem* item) {glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);- if (locPos >= 0) glDisableVertexAttribArray(locPos);- if (locTex >= 0) glDisableVertexAttribArray(locTex);- if (locColor >= 0) glDisableVertexAttribArray(locColor);+ if (attrPos >= 0) glDisableVertexAttribArray(attrPos);+ if (attrTex >= 0) glDisableVertexAttribArray(attrTex);+ if (attrColor >= 0) glDisableVertexAttribArray(attrColor);glBindVertexArray(0);diff --git a/src/esengine/renderer/RenderFrame.hpp b/src/esengine/renderer/RenderFrame.hppindex 8802ce7fd..6c3a8f062 100644--- a/src/esengine/renderer/RenderFrame.hpp+++ b/src/esengine/renderer/RenderFrame.hpp@@ -2,6 +2,7 @@#include "../core/Types.hpp"#include "RenderItem.hpp"+#include "TextureSlotAllocator.hpp"#include "RenderTarget.hpp"#include "RenderContext.hpp"#include "PostProcessPipeline.hpp"@@ -73,7 +74,7 @@ public:void clearEntityClipRect(u32 entity);void clearAllClipRects();- void submit(const RenderItem& item);+ void submit(const RenderItemBase& item, const SpriteData& data);void submitExternalTriangles(const f32* vertices, i32 vertexCount,const u16* indices, i32 indexCount,@@ -93,7 +94,7 @@ private:void sortAndBucket();void executeStage(RenderStage stage);void renderSprites(u32 begin, u32 end);- void renderSpriteWithMaterial(RenderItem* item);+ void renderSpriteWithMaterial(const RenderItemBase& base, const SpriteData& data);#ifdef ES_ENABLE_SPINEvoid renderSpine(u32 begin, u32 end);void flushSpineBatch();@@ -109,7 +110,16 @@ private:Unique<PostProcessPipeline> post_process_;RenderTargetManager target_manager_;- std::vector<RenderItem> items_;+ std::vector<RenderItemBase> items_;+ std::vector<u32> sorted_indices_;++ std::vector<SpriteData> sprite_data_;+ std::vector<TextData> text_data_;+#ifdef ES_ENABLE_SPINE+ std::vector<SpineData> spine_data_;+#endif+ std::vector<ExternalMeshData> ext_data_;+glm::mat4 view_projection_{1.0f};Frustum frustum_;RenderTargetManager::Handle current_target_ = 0;@@ -140,8 +150,7 @@ private:BlendMode spine_current_blend_ = BlendMode::Normal;static constexpr u32 SPINE_MAX_TEXTURE_SLOTS = 8;- std::array<u32, SPINE_MAX_TEXTURE_SLOTS> spine_texture_slots_{};- u32 spine_texture_slot_index_ = 1;+ TextureSlotAllocator<SPINE_MAX_TEXTURE_SLOTS> spine_tex_slots_;resource::ShaderHandle spine_shader_handle_;u32 spine_vao_ = 0;diff --git a/src/esengine/renderer/RenderItem.hpp b/src/esengine/renderer/RenderItem.hppindex 30d92a9cf..58ffe2084 100644--- a/src/esengine/renderer/RenderItem.hpp+++ b/src/esengine/renderer/RenderItem.hpp@@ -26,12 +26,12 @@ enum class RenderType : u8 {Text = 4,};-struct RenderItem {+struct RenderItemBase {Entity entity = INVALID_ENTITY;RenderType type = RenderType::Sprite;RenderStage stage = RenderStage::Transparent;+ BlendMode blend_mode = BlendMode::Normal;- glm::mat4 transform{1.0f};glm::vec3 world_position{0.0f};f32 world_angle = 0.0f;glm::vec2 world_scale{1.0f};@@ -39,10 +39,38 @@ struct RenderItem {i32 layer = 0;f32 depth = 0.0f;u32 texture_id = 0;- BlendMode blend_mode = BlendMode::Normal;- glm::vec2 size{0.0f};glm::vec4 color{1.0f};++ bool scissor_enabled = false;+ ScissorRect scissor;++ u32 data_index = 0;++ u64 sortKey() const {+ u64 stageKey = static_cast<u64>(stage) << 60;++ i32 normalizedLayer = layer + 32768;+ u64 layerKey = static_cast<u64>(normalizedLayer & 0xFFFF) << 44;++ u64 textureKey = static_cast<u64>(texture_id & 0xFFFFF) << 24;++ u32 depthBits;+ if (stage == RenderStage::Transparent) {+ f32 invDepth = 1.0f - (depth * 0.5f + 0.5f);+ depthBits = static_cast<u32>(invDepth * 16777215.0f);+ } else {+ f32 normDepth = depth * 0.5f + 0.5f;+ depthBits = static_cast<u32>(normDepth * 16777215.0f);+ }+ u64 depthKey = static_cast<u64>(depthBits & 0xFFFFFF);++ return stageKey | layerKey | textureKey | depthKey;+ }+};++struct SpriteData {+ glm::vec2 size{0.0f};glm::vec2 uv_offset{0.0f};glm::vec2 uv_scale{1.0f};bool flip_x = false;@@ -50,53 +78,37 @@ struct RenderItem {bool use_nine_slice = false;glm::vec4 slice_border{0.0f};glm::vec2 texture_size{0.0f};+ glm::mat4 transform{1.0f};+ u32 material_id = 0;+ void* geometry = nullptr;+ void* shader = nullptr;+};#ifdef ES_ENABLE_SPINE+struct SpineData {+ glm::mat4 transform{1.0f};void* skeleton = nullptr;glm::vec4 tint_color{1.0f};-#endif-- void* geometry = nullptr;- void* shader = nullptr;-u32 material_id = 0;+};+#endif+struct TextData {const void* font_data = nullptr;const char* text_data = nullptr;u16 text_length = 0;f32 font_size = 1.0f;u8 text_align = 0;f32 text_spacing = 0.0f;+};+struct ExternalMeshData {+ glm::mat4 transform{1.0f};const f32* ext_vertices = nullptr;i32 ext_vertex_count = 0;const u16* ext_indices = nullptr;i32 ext_index_count = 0;u32 ext_bind_texture = 0;-- bool scissor_enabled = false;- ScissorRect scissor;-- u64 sortKey() const {- u64 stageKey = static_cast<u64>(stage) << 60;-- i32 normalizedLayer = layer + 32768;- u64 layerKey = static_cast<u64>(normalizedLayer & 0xFFFF) << 44;-- u64 textureKey = static_cast<u64>(texture_id & 0xFFFFF) << 24;-- u32 depthBits;- if (stage == RenderStage::Transparent) {- f32 invDepth = 1.0f - (depth * 0.5f + 0.5f);- depthBits = static_cast<u32>(invDepth * 16777215.0f);- } else {- f32 normDepth = depth * 0.5f + 0.5f;- depthBits = static_cast<u32>(normDepth * 16777215.0f);- }- u64 depthKey = static_cast<u64>(depthBits & 0xFFFFFF);-- return stageKey | layerKey | textureKey | depthKey;- }};} // namespace esenginediff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cppindex 90d8b5ed6..38fd8eece 100644--- a/src/esengine/renderer/Renderer.cpp+++ b/src/esengine/renderer/Renderer.cpp@@ -12,6 +12,7 @@#include "Renderer.hpp"#include "RenderCommand.hpp"+#include "TextureSlotAllocator.hpp"#include "../core/Log.hpp"#include "../resource/ResourceManager.hpp"@@ -298,8 +299,7 @@ struct BatchRenderer2D::BatchData {u32 indexCount = 0;u32 triangleCount = 0;- std::array<u32, MAX_TEXTURE_SLOTS> textureSlots;- u32 textureSlotIndex = 1;+ TextureSlotAllocator<MAX_TEXTURE_SLOTS> texSlots;glm::mat4 projection{1.0f};@@ -399,10 +399,7 @@ void BatchRenderer2D::init() {ES_LOG_ERROR("All batch shader variants FAILED!");}- for (u32 i = 0; i < MAX_TEXTURE_SLOTS; ++i) {- data_->textureSlots[i] = context_.getWhiteTextureId();- }-+ data_->texSlots.init(context_.getWhiteTextureId());data_->initialized = true;}@@ -421,7 +418,7 @@ void BatchRenderer2D::beginBatch() {data_->triVertices.clear();data_->indexCount = 0;data_->triangleCount = 0;- data_->textureSlotIndex = 1;+ data_->texSlots.reset();data_->drawCallCount = 0;data_->quadCount = 0;}@@ -450,10 +447,7 @@ void BatchRenderer2D::flush() {data_->vbo->setDataRaw(data_->triVertices.data(), triBytes);}- for (u32 i = 0; i < MAX_TEXTURE_SLOTS; ++i) {- glActiveTexture(GL_TEXTURE0 + i);- glBindTexture(GL_TEXTURE_2D, data_->textureSlots[i]);- }+ data_->texSlots.bindAll();shader->bind();shader->setUniform("u_projection", data_->projection);@@ -487,7 +481,7 @@ void BatchRenderer2D::flush() {data_->triVertices.clear();data_->indexCount = 0;data_->triangleCount = 0;- data_->textureSlotIndex = 1;+ data_->texSlots.reset();}void BatchRenderer2D::drawQuad(const glm::vec2& position, const glm::vec2& size,@@ -503,32 +497,19 @@ void BatchRenderer2D::drawQuad(const glm::vec3& position, const glm::vec2& size,flush();}- f32 texIndex = 0.0f;- if (textureId != 0) {- bool found = false;- for (u32 i = 0; i < data_->textureSlotIndex; ++i) {- if (data_->textureSlots[i] == textureId) {- texIndex = static_cast<f32>(i);- found = true;- break;- }- }- if (!found) {- if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {- flush();- }- data_->textureSlots[data_->textureSlotIndex] = textureId;- texIndex = static_cast<f32>(data_->textureSlotIndex);- data_->textureSlotIndex++;- }+ f32 texIndex = data_->texSlots.findOrAllocate(textureId);+ if (texIndex < 0.0f) {+ flush();+ texIndex = data_->texSlots.findOrAllocate(textureId);}- glm::mat4 transform = glm::translate(glm::mat4(1.0f), position);- transform = glm::scale(transform, glm::vec3(size, 1.0f));-for (u32 i = 0; i < 4; ++i) {BatchVertex vertex;- vertex.position = glm::vec3(transform * QUAD_POSITIONS[i]);+ vertex.position = glm::vec3(+ position.x + QUAD_POSITIONS[i].x * size.x,+ position.y + QUAD_POSITIONS[i].y * size.y,+ position.z+ );vertex.color = color;vertex.texCoord = QUAD_TEX_COORDS[i] * uvScale + uvOffset;vertex.texIndex = texIndex;@@ -577,24 +558,10 @@ void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2flush();}- f32 texIndex = 0.0f;- if (textureId != 0) {- bool found = false;- for (u32 i = 0; i < data_->textureSlotIndex; ++i) {- if (data_->textureSlots[i] == textureId) {- texIndex = static_cast<f32>(i);- found = true;- break;- }- }- if (!found) {- if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {- flush();- }- data_->textureSlots[data_->textureSlotIndex] = textureId;- texIndex = static_cast<f32>(data_->textureSlotIndex);- data_->textureSlotIndex++;- }+ f32 texIndex = data_->texSlots.findOrAllocate(textureId);+ if (texIndex < 0.0f) {+ flush();+ texIndex = data_->texSlots.findOrAllocate(textureId);}glm::mat4 transform = glm::translate(glm::mat4(1.0f), glm::vec3(position, 0.0f));@@ -667,17 +634,12 @@ void BatchRenderer2D::drawNineSlice(const glm::vec2& position, const glm::vec2&};auto resolveTextureSlot = [this, textureId]() -> f32 {- if (textureId == 0) return 0.0f;- for (u32 i = 0; i < data_->textureSlotIndex; ++i) {- if (data_->textureSlots[i] == textureId) {- return static_cast<f32>(i);- }- }- if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {+ f32 idx = data_->texSlots.findOrAllocate(textureId);+ if (idx < 0.0f) {flush();+ idx = data_->texSlots.findOrAllocate(textureId);}- data_->textureSlots[data_->textureSlotIndex] = textureId;- return static_cast<f32>(data_->textureSlotIndex++);+ return idx;};f32 cachedTexIndex = resolveTextureSlot();diff --git a/src/esengine/renderer/Shader.cpp b/src/esengine/renderer/Shader.cppindex 8143f67cc..3e7747a57 100644--- a/src/esengine/renderer/Shader.cpp+++ b/src/esengine/renderer/Shader.cpp@@ -212,6 +212,34 @@ void Shader::setUniform(const std::string& name, const glm::mat4& value) const {glUniformMatrix4fv(getUniformLocation(name), 1, GL_FALSE, glm::value_ptr(value));}+void Shader::setUniform(i32 location, i32 value) const {+ if (location >= 0) glUniform1i(location, value);+}++void Shader::setUniform(i32 location, f32 value) const {+ if (location >= 0) glUniform1f(location, value);+}++void Shader::setUniform(i32 location, const glm::vec2& value) const {+ if (location >= 0) glUniform2f(location, value.x, value.y);+}++void Shader::setUniform(i32 location, const glm::vec3& value) const {+ if (location >= 0) glUniform3f(location, value.x, value.y, value.z);+}++void Shader::setUniform(i32 location, const glm::vec4& value) const {+ if (location >= 0) glUniform4f(location, value.x, value.y, value.z, value.w);+}++void Shader::setUniform(i32 location, const glm::mat3& value) const {+ if (location >= 0) glUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(value));+}++void Shader::setUniform(i32 location, const glm::mat4& value) const {+ if (location >= 0) glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(value));+}+i32 Shader::getAttribLocation(const std::string& name) const {return glGetAttribLocation(programId_, name.c_str());}diff --git a/src/esengine/renderer/Shader.hpp b/src/esengine/renderer/Shader.hppindex 5a474ae51..b4b5f80a0 100644--- a/src/esengine/renderer/Shader.hpp+++ b/src/esengine/renderer/Shader.hpp@@ -97,49 +97,21 @@ public:* @param value Integer value*/void setUniform(const std::string& name, i32 value) const;-- /**- * @brief Sets a float uniform- * @param name Uniform name in shader- * @param value Float value- */void setUniform(const std::string& name, f32 value) const;-- /**- * @brief Sets a vec2 uniform- * @param name Uniform name in shader- * @param value Vector value- */void setUniform(const std::string& name, const glm::vec2& value) const;-- /**- * @brief Sets a vec3 uniform- * @param name Uniform name in shader- * @param value Vector value- */void setUniform(const std::string& name, const glm::vec3& value) const;-- /**- * @brief Sets a vec4 uniform- * @param name Uniform name in shader- * @param value Vector value- */void setUniform(const std::string& name, const glm::vec4& value) const;-- /**- * @brief Sets a mat3 uniform- * @param name Uniform name in shader- * @param value Matrix value- */void setUniform(const std::string& name, const glm::mat3& value) const;-- /**- * @brief Sets a mat4 uniform- * @param name Uniform name in shader- * @param value Matrix value- */void setUniform(const std::string& name, const glm::mat4& value) const;+ void setUniform(i32 location, i32 value) const;+ void setUniform(i32 location, f32 value) const;+ void setUniform(i32 location, const glm::vec2& value) const;+ void setUniform(i32 location, const glm::vec3& value) const;+ void setUniform(i32 location, const glm::vec4& value) const;+ void setUniform(i32 location, const glm::mat3& value) const;+ void setUniform(i32 location, const glm::mat4& value) const;+// =========================================================================// Attributes// =========================================================================@@ -151,6 +123,8 @@ public:*/i32 getAttribLocation(const std::string& name) const;+ i32 getUniformLocation(const std::string& name) const;+// =========================================================================// State// =========================================================================@@ -176,14 +150,6 @@ private:*/bool compile(const std::string& vertexSrc, const std::string& fragmentSrc);- /**- * @brief Gets uniform location with caching- * @param name Uniform name- * @return Location, or -1 if not found- */- i32 getUniformLocation(const std::string& name) const;-- /** @brief OpenGL program handle */u32 programId_ = 0;/** @brief Cached uniform locations (mutable for const uniform setters) */diff --git a/src/esengine/renderer/TextureSlotAllocator.hpp b/src/esengine/renderer/TextureSlotAllocator.hppnew file mode 100644index 000000000..58bebe4cc--- /dev/null+++ b/src/esengine/renderer/TextureSlotAllocator.hpp@@ -0,0 +1,68 @@+#pragma once++#include "../core/Types.hpp"++#ifdef ES_PLATFORM_WEB+ #include <GLES3/gl3.h>+#else+ #ifdef _WIN32+ #include <windows.h>+ #endif+ #include <glad/glad.h>+#endif++#include <array>++namespace esengine {++template<u32 MaxSlots>+class TextureSlotAllocator {+public:+ void init(u32 whiteTextureId) {+ white_texture_id_ = whiteTextureId;+ reset();+ }++ void reset() {+ for (u32 i = 0; i < MaxSlots; ++i) {+ slots_[i] = white_texture_id_;+ }+ slot_count_ = 1;+ }++ f32 findOrAllocate(u32 textureId) {+ if (textureId == 0) {+ return 0.0f;+ }+ for (u32 i = 0; i < slot_count_; ++i) {+ if (slots_[i] == textureId) {+ return static_cast<f32>(i);+ }+ }+ if (slot_count_ >= MaxSlots) {+ return -1.0f;+ }+ slots_[slot_count_] = textureId;+ return static_cast<f32>(slot_count_++);+ }++ bool isFull() const {+ return slot_count_ >= MaxSlots;+ }++ void bindAll() const {+ for (u32 i = 0; i < MaxSlots; ++i) {+ glActiveTexture(GL_TEXTURE0 + i);+ glBindTexture(GL_TEXTURE_2D, slots_[i]);+ }+ }++ u32 slotCount() const { return slot_count_; }++private:+ std::array<u32, MaxSlots> slots_{};+ u32 slot_count_ = 1;+ u32 white_texture_id_ = 0;+};++} // namespace esengine