@esengine/ecs-framework 2.2.5 → 2.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +1 -1
- package/index.cjs.map +1 -1
- package/index.d.ts +23 -12
- package/index.es5.js +1 -1
- package/index.es5.js.map +1 -1
- package/index.mjs +1 -1
- package/index.mjs.map +1 -1
- package/index.umd.js +1 -1
- package/index.umd.js.map +1 -1
- package/package.json +1 -1
package/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function t(e,t,n,i,r,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(i,r)}function n(e){return function(){var n=this,i=arguments;return new Promise((function(r,s){var o=e.apply(n,i);function a(e){t(o,r,s,a,c,"next",e)}function c(e){t(o,r,s,a,c,"throw",e)}a(void 0)}))}}function i(e,t,n){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return n&&d(r,n.prototype),r}function r(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,p(i.key),i)}}function s(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function o(t,n){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(i)return(i=i.call(t)).next.bind(i);if(Array.isArray(t)||(i=function(t,n){if(t){if("string"==typeof t)return e(t,n);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?e(t,n):void 0}}(t))||n){i&&(t=i);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function a(){return a=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},a.apply(null,arguments)}function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function u(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,d(e,t)}function h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(h=function(){return!!e})()}function l(){
|
|
2
2
|
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
|
|
3
|
-
var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function s(n,i,r,s){var c=i&&i.prototype instanceof a?i:a,u=Object.create(c.prototype);return f(u,"_invoke",function(n,i,r){var s,a,c,u=0,h=r||[],l=!1,f={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,n){return s=t,a=0,c=e,f.n=n,o}};function d(n,i){for(a=n,c=i,t=0;!l&&u&&!r&&t<h.length;t++){var r,s=h[t],d=f.p,p=s[2];n>3?(r=p===i)&&(c=s[(a=s[4])?5:(a=3,3)],s[4]=s[5]=e):s[0]<=d&&((r=n<2&&d<s[1])?(a=0,f.v=i,f.n=s[1]):d<p&&(r=n<3||s[0]>i||i>p)&&(s[4]=n,s[5]=i,f.n=p,a=0))}if(r||n>1)return o;throw l=!0,i}return function(r,h,p){if(u>1)throw TypeError("Generator is already running");for(l&&1===h&&d(h,p),a=h,c=p;(t=a<2?e:c)||!l;){s||(a?a<3?(a>1&&(f.n=-1),d(a,c)):f.n=c:f.v=c);try{if(u=2,s){if(a||(r="next"),t=s[r]){if(!(t=t.call(s,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,a<2&&(a=0)}else 1===a&&(t=s.return)&&t.call(s),a<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),a=1);s=e}else if((t=(l=f.n<0)?c:n.call(i,f))!==o)break}catch(t){s=e,a=1,c=t}finally{u=1}}return{value:t,done:l}}}(n,r,s),!0),u}var o={};function a(){}function c(){}function u(){}t=Object.getPrototypeOf;var h=[][i]?t(t([][i]())):(f(t={},i,(function(){return this})),t),d=u.prototype=a.prototype=Object.create(h);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,f(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=u,f(d,"constructor",u),f(u,"constructor",c),c.displayName="GeneratorFunction",f(u,r,"GeneratorFunction"),f(d),f(d,r,"Generator"),f(d,i,(function(){return this})),f(d,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:s,m:p}})()}function f(e,t,n,i){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}f=function(e,t,n,i){function s(t,n){f(e,t,(function(e){return this._invoke(t,n,e)}))}t?r?r(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(s("next",0),s("throw",1),s("return",2))},f(e,t,n,i)}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function p(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function y(e){var t="function"==typeof Map?new Map:void 0;return y=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return i(e,arguments,c(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),d(n,e)},y(e)}function m(e,t,n,i){var r,s=arguments.length,o=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,n,o):r(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o}function g(e,t){return function(n,i){t(n,i,e)}}function v(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}"function"==typeof SuppressedError&&SuppressedError;var _=function(){function e(){}return e.update=function(e){this.unscaledDeltaTime=e,this.deltaTime=e*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++},e.sceneChanged=function(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0},e.checkEvery=function(e,t){return this.totalTime-t>=e},e}();_.deltaTime=0,_.unscaledDeltaTime=0,_.totalTime=0,_.unscaledTotalTime=0,_.timeScale=1,_.frameCount=0;var S,C=function(){function e(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}var t=e.prototype;return t.getContext=function(){return this.context},t.reset=function(){this._elapsedTime=0},t.stop=function(){this._isDone=!0},t.tick=function(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=_.deltaTime,this._isDone},t.initialize=function(e,t,n,i){this._timeInSeconds=e,this._repeats=t,this.context=n,this._onTime=i.bind(n)},t.unload=function(){this.context=null,this._onTime=null},s(e,[{key:"isDone",get:function(){return this._isDone}},{key:"elapsedTime",get:function(){return this._elapsedTime}}])}(),w=new WeakMap,E=new WeakMap,b=new WeakMap;function A(){return function(e){var t=w.get(e);return w.set(e,{injectable:!0,dependencies:[],properties:null==t?void 0:t.properties}),e}}function T(e){return void 0===e&&(e=0),function(t){var n=t.prototype;if(!n||"function"!=typeof n.update)throw new Error("@Updatable() decorator requires class "+t.name+" to implement IUpdatable interface with update() method. Please add 'implements IUpdatable' and define update(deltaTime?: number): void method.");return b.set(t,{updatable:!0,priority:e}),t}}function M(e){return function(t,n,i){var r=E.get(t);r||(r=new Map,E.set(t,r)),r.set(i,e)}}function x(e){var t,n=w.get(e);return null!==(t=null==n?void 0:n.injectable)&&void 0!==t&&t}function I(e,t){for(var n,r=(n=e,E.get(n)||new Map),s=[],o=e.length,a=0;a<o;a++){var c=r.get(a);if(c){if("string"==typeof c||"symbol"==typeof c)throw new Error("String and Symbol service identifiers are not yet supported in constructor injection. Please use class types for "+e.name+" parameter "+a);s.push(t.resolve(c))}else s.push(void 0)}return i(e,s)}function k(e,t){var n,i=e.constructor,r=(n=i,w.get(n));if(null!=r&&r.properties&&0!==r.properties.size)for(var s,a=o(r.properties);!(s=a()).done;){var c=s.value,u=c[0],h=c[1],l=t.resolve(h);null!==l&&(e[u]=l)}}function D(e){var t,n=b.get(e);return null!==(t=null==n?void 0:n.updatable)&&void 0!==t&&t}function R(e){return b.get(e)}exports.TimerManager=function(){function e(){this._timers=[]}var t=e.prototype;return t.update=function(){for(var e=this._timers.length-1;e>=0;e--)this._timers[e].tick()&&(this._timers[e].unload(),this._timers.splice(e,1))},t.schedule=function(e,t,n,i){var r=new C;return r.initialize(e,t,n,i),this._timers.push(r),r},t.dispose=function(){for(var e,t=o(this._timers);!(e=t()).done;){e.value.unload()}this._timers=[]},e}(),exports.TimerManager=m([T()],exports.TimerManager),exports.PerformanceWarningType=void 0,(S=exports.PerformanceWarningType||(exports.PerformanceWarningType={})).HIGH_EXECUTION_TIME="high_execution_time",S.HIGH_MEMORY_USAGE="high_memory_usage",S.HIGH_CPU_USAGE="high_cpu_usage",S.FREQUENT_GC="frequent_gc",S.LOW_FPS="low_fps",S.HIGH_ENTITY_COUNT="high_entity_count";var O=function(){function e(){this._systemData=new Map,this._systemStats=new Map,this._warnings=[],this._isEnabled=!1,this._maxRecentSamples=60,this._maxWarnings=100,this._thresholds={executionTime:{warning:16.67,critical:33.33},memoryUsage:{warning:100,critical:200},cpuUsage:{warning:70,critical:90},fps:{warning:45,critical:30},entityCount:{warning:1e3,critical:5e3}},this._fpsHistory=[],this._lastFrameTime=0,this._frameCount=0,this._fpsUpdateInterval=1e3,this._lastFpsUpdate=0,this._currentFps=60,this._memoryCheckInterval=5e3,this._lastMemoryCheck=0,this._memoryHistory=[],this._gcCount=0,this._lastGcCheck=0,this._gcCheckInterval=1e3}var t=e.prototype;return t.enable=function(){this._isEnabled=!0},t.disable=function(){this._isEnabled=!1},t.startMonitoring=function(e){return this._isEnabled?performance.now():0},t.endMonitoring=function(e,t,n){if(void 0===n&&(n=0),this._isEnabled&&0!==t){var i=performance.now(),r=i-t,s={name:e,executionTime:r,entityCount:n,averageTimePerEntity:n>0?r/n:0,lastUpdateTime:i};this._systemData.set(e,s),this.updateStats(e,r)}},t.updateStats=function(e,t){var n=this._systemStats.get(e);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(e,n)),n.totalTime+=t,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,t),n.maxTime=Math.max(n.maxTime,t),n.recentTimes.push(t),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)},t.calculateAdvancedStats=function(e){if(0!==e.recentTimes.length){var t=e.recentTimes.reduce((function(e,t){return e+t}),0)/e.recentTimes.length,n=e.recentTimes.reduce((function(e,n){return e+Math.pow(n-t,2)}),0)/e.recentTimes.length;e.standardDeviation=Math.sqrt(n);var i=[].concat(e.recentTimes).sort((function(e,t){return e-t})),r=i.length;e.percentile95=i[Math.floor(.95*r)]||0,e.percentile99=i[Math.floor(.99*r)]||0}},t.getSystemData=function(e){return this._systemData.get(e)},t.getSystemStats=function(e){return this._systemStats.get(e)},t.getAllSystemData=function(){return new Map(this._systemData)},t.getAllSystemStats=function(){return new Map(this._systemStats)},t.getPerformanceReport=function(){if(!this._isEnabled)return"Performance monitoring is disabled.";var e=[];e.push("=== ECS Performance Report ==="),e.push("");for(var t,n=o(Array.from(this._systemStats.entries()).sort((function(e,t){return t[1].averageTime-e[1].averageTime})));!(t=n()).done;){var i=t.value,r=i[0],s=i[1],a=this._systemData.get(r);e.push("System: "+r),e.push(" Current: "+(null==a?void 0:a.executionTime.toFixed(2))+"ms ("+(null==a?void 0:a.entityCount)+" entities)"),e.push(" Average: "+s.averageTime.toFixed(2)+"ms"),e.push(" Min/Max: "+s.minTime.toFixed(2)+"ms / "+s.maxTime.toFixed(2)+"ms"),e.push(" Total: "+s.totalTime.toFixed(2)+"ms ("+s.executionCount+" calls)"),null!=a&&a.averageTimePerEntity&&a.averageTimePerEntity>0&&e.push(" Per Entity: "+a.averageTimePerEntity.toFixed(4)+"ms"),e.push("")}var c=Array.from(this._systemData.values()).reduce((function(e,t){return e+t.executionTime}),0);return e.push("Total Frame Time: "+c.toFixed(2)+"ms"),e.push("Systems Count: "+this._systemData.size),e.join("\n")},t.reset=function(){this._systemData.clear(),this._systemStats.clear()},t.resetSystem=function(e){this._systemData.delete(e),this._systemStats.delete(e)},t.getPerformanceWarnings=function(e){void 0===e&&(e=16.67);for(var t,n=[],i=o(this._systemData.entries());!(t=i()).done;){var r=t.value,s=r[0],a=r[1];a.executionTime>e&&n.push(s+": "+a.executionTime.toFixed(2)+"ms (>"+e+"ms)")}return n},t.setMaxRecentSamples=function(e){this._maxRecentSamples=e;for(var t,n=o(this._systemStats.values());!(t=n()).done;)for(var i=t.value;i.recentTimes.length>e;)i.recentTimes.shift()},t.dispose=function(){this._systemData.clear(),this._systemStats.clear(),this._warnings=[],this._fpsHistory=[],this._memoryHistory=[],this._isEnabled=!1},s(e,[{key:"isEnabled",get:function(){return this._isEnabled}}])}(),z=function(){function e(e,t,n){void 0===t&&(t=100),void 0===n&&(n=1024),this._objects=[],this._createFn=e,this._maxSize=t,this._objectSize=n,this._stats={size:0,maxSize:t,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}e.getPool=function(t,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this._pools.get(t);return r||(r=new e((function(){return new t}),n,i),this._pools.set(t,r)),r};var t=e.prototype;return t.obtain=function(){if(this._stats.totalObtained++,this._objects.length>0){var e=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),e}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()},t.release=function(e){e&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(e.reset(),this._objects.push(e),this._stats.size++,this._updateMemoryUsage()))},t.getStats=function(){return a({},this._stats)},t.clear=function(){for(var e,t=o(this._objects);!(e=t()).done;){e.value.reset()}this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()},t.compact=function(e){for(var t=null!=e?e:Math.floor(this._objects.length/2);this._objects.length>t;){var n=this._objects.pop();n&&(n.reset(),this._stats.size--)}this._updateMemoryUsage()},t.prewarm=function(e){for(var t=Math.min(e,this._maxSize-this._objects.length),n=0;n<t;n++){var i=this._createFn();i.reset(),this._objects.push(i),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()},t.setMaxSize=function(e){this._maxSize=e,this._stats.maxSize=e,this._objects.length>e&&this.compact(e)},t.getAvailableCount=function(){return this._objects.length},t.isEmpty=function(){return 0===this._objects.length},t.isFull=function(){return this._objects.length>=this._maxSize},e.getAllPoolTypes=function(){return Array.from(this._pools.keys())},e.getAllPoolStats=function(){for(var e,t={},n=o(this._pools);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];t[r.name||r.toString()]=s.getStats()}return t},e.compactAllPools=function(){for(var e,t=o(this._pools.values());!(e=t()).done;){e.value.compact()}},e.clearAllPools=function(){for(var e,t=o(this._pools.values());!(e=t()).done;){e.value.clear()}this._pools.clear()},e.getGlobalStatsString=function(){var e=this.getAllPoolStats(),t=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(e).length)return t.push("No pools registered"),t.join("\n");for(var n=0,i=Object.entries(e);n<i.length;n++){var r=i[n],s=r[0],o=r[1];t.push(s+":"),t.push(" Size: "+o.size+"/"+o.maxSize),t.push(" Hit Rate: "+(100*o.hitRate).toFixed(1)+"%"),t.push(" Total Created: "+o.totalCreated),t.push(" Total Obtained: "+o.totalObtained),t.push(" Memory: "+(o.estimatedMemoryUsage/1024).toFixed(1)+" KB"),t.push("")}return t.join("\n")},t._updateHitRate=function(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{var e=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=e/this._stats.totalObtained}},t._updateMemoryUsage=function(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize},e}();z._pools=new Map;var B,P=function(){function e(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}var t=e.prototype;return t.registerPool=function(e,t){this.pools.set(e,t)},t.getPool=function(e){return this.pools.get(e)||null},t.update=function(){var e=Date.now();e-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=e)},t.createPool=function(e,t,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this.pools.get(e);return r||(r=new z(t,n,i),this.pools.set(e,r)),r},t.removePool=function(e){var t=this.pools.get(e);return!!t&&(t.clear(),this.pools.delete(e),!0)},t.getPoolNames=function(){return Array.from(this.pools.keys())},t.getPoolCount=function(){return this.pools.size},t.compactAllPools=function(){for(var e,t=o(this.pools.values());!(e=t()).done;){e.value.compact()}},t.clearAllPools=function(){for(var e,t=o(this.pools.values());!(e=t()).done;){e.value.clear()}},t.getAllStats=function(){for(var e,t=new Map,n=o(this.pools);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];t.set(r,s.getStats())}return t},t.getGlobalStats=function(){for(var e,t=0,n=0,i=0,r=0,s=0,a=0,c=o(this.pools.values());!(e=c()).done;){var u=e.value.getStats();t+=u.size,n+=u.maxSize,i+=u.totalCreated,r+=u.totalObtained,s+=u.totalReleased,a+=u.estimatedMemoryUsage}return{size:t,maxSize:n,totalCreated:i,totalObtained:r,totalReleased:s,hitRate:0===r?0:(r-i)/r,estimatedMemoryUsage:a}},t.getStatsString=function(){var e=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return e.push("No pools registered"),e.join("\n");var t=this.getGlobalStats();e.push("Total Pools: "+this.pools.size),e.push("Global Hit Rate: "+(100*t.hitRate).toFixed(1)+"%"),e.push("Global Memory Usage: "+(t.estimatedMemoryUsage/1024).toFixed(1)+" KB"),e.push("");for(var n,i=o(this.pools);!(n=i()).done;){var r=n.value,s=r[0],a=r[1].getStats();e.push(s+":"),e.push(" Size: "+a.size+"/"+a.maxSize),e.push(" Hit Rate: "+(100*a.hitRate).toFixed(1)+"%"),e.push(" Memory: "+(a.estimatedMemoryUsage/1024).toFixed(1)+" KB"),e.push("")}return e.join("\n")},t.setAutoCompactInterval=function(e){this.autoCompactInterval=e},t.prewarmAllPools=function(){for(var e,t=o(this.pools.values());!(e=t()).done;){var n=e.value,i=n.getStats(),r=Math.floor(.2*i.maxSize);n.prewarm(r)}},t.reset=function(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0},t.dispose=function(){this.reset()},e}(),L=Symbol("ComponentTypeName"),N=Symbol("SystemTypeName");function W(e){return e.__systemMetadata__}function U(e){var t=e[L];return t||(e.name||"UnknownComponent")}function F(e){var t=e[N];return t||(e.name||"UnknownSystem")}function H(e){return U(e.constructor)}function j(e){return F(e.constructor)}exports.LogLevel=void 0,(B=exports.LogLevel||(exports.LogLevel={}))[B.Debug=0]="Debug",B[B.Info=1]="Info",B[B.Warn=2]="Warn",B[B.Error=3]="Error",B[B.Fatal=4]="Fatal",B[B.None=5]="None";var q={BLACK:"[30m",RED:"[31m",GREEN:"[32m",YELLOW:"[33m",BLUE:"[34m",MAGENTA:"[35m",CYAN:"[36m",WHITE:"[37m",BRIGHT_BLACK:"[90m",BRIGHT_RED:"[91m",BRIGHT_GREEN:"[92m",BRIGHT_YELLOW:"[93m",BRIGHT_BLUE:"[94m",BRIGHT_MAGENTA:"[95m",BRIGHT_CYAN:"[96m",BRIGHT_WHITE:"[97m",RESET:"[0m",BOLD:"[1m",UNDERLINE:"[4m"},G=function(){function e(e){void 0===e&&(e={}),this._config=a({level:exports.LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window},e)}var t=e.prototype;return t.debug=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Debug,e].concat(n))},t.info=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Info,e].concat(n))},t.warn=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Warn,e].concat(n))},t.error=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Error,e].concat(n))},t.fatal=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Fatal,e].concat(n))},t.setLevel=function(e){this._config.level=e},t.setColors=function(e){0===Object.keys(e).length?delete this._config.colors:this._config.colors=a({},this._config.colors,e)},t.setPrefix=function(e){this._config.prefix=e},t.log=function(e,t){if(!(e<this._config.level)){var n=t;if(this._config.enableTimestamp)n="["+(new Date).toISOString()+"] "+n;if(this._config.prefix&&(n="["+this._config.prefix+"] "+n),n="["+exports.LogLevel[e].toUpperCase()+"] "+n,this._config.output)this._config.output(e,n);else{for(var i=arguments.length,r=new Array(i>2?i-2:0),s=2;s<i;s++)r[s-2]=arguments[s];this.outputToConsole.apply(this,[e,n].concat(r))}}},t.outputToConsole=function(e,t){for(var n=this._config.enableColors?this.getColors():null,i=arguments.length,r=new Array(i>2?i-2:0),s=2;s<i;s++)r[s-2]=arguments[s];switch(e){case exports.LogLevel.Debug:var o,a;if(n)(o=console).debug.apply(o,[""+n.debug+t+n.reset].concat(r));else(a=console).debug.apply(a,[t].concat(r));break;case exports.LogLevel.Info:var c,u;if(n)(c=console).info.apply(c,[""+n.info+t+n.reset].concat(r));else(u=console).info.apply(u,[t].concat(r));break;case exports.LogLevel.Warn:var h,l;if(n)(h=console).warn.apply(h,[""+n.warn+t+n.reset].concat(r));else(l=console).warn.apply(l,[t].concat(r));break;case exports.LogLevel.Error:var f,d;if(n)(f=console).error.apply(f,[""+n.error+t+n.reset].concat(r));else(d=console).error.apply(d,[t].concat(r));break;case exports.LogLevel.Fatal:var p,y;if(n)(p=console).error.apply(p,[""+n.fatal+t+n.reset].concat(r));else(y=console).error.apply(y,[t].concat(r))}},t.getColors=function(){return a({},{debug:q.BRIGHT_BLACK,info:q.GREEN,warn:q.YELLOW,error:q.RED,fatal:q.BRIGHT_RED,reset:q.RESET},this._config.colors)},e}(),Q=function(){function e(){this._loggers=new Map,this._defaultLevel=exports.LogLevel.Info,this._defaultLogger=new G({level:this._defaultLevel})}e.getInstance=function(){return e._instance||(e._instance=new e),e._instance};var t=e.prototype;return t.getLogger=function(e){if(!e)return this._defaultLogger;if(!this._loggers.has(e)){var t=new G({prefix:e,level:this._defaultLevel});this._loggers.set(e,t)}return this._loggers.get(e)},t.setLogger=function(e,t){this._loggers.set(e,t)},t.setGlobalLevel=function(e){this._defaultLevel=e,this._defaultLogger instanceof G&&this._defaultLogger.setLevel(e);for(var t,n=o(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof G&&i.setLevel(e)}},t.createChildLogger=function(e,t){var n=e+"."+t;return this.getLogger(n)},t.setGlobalColors=function(e){this._defaultLogger instanceof G&&this._defaultLogger.setColors(e);for(var t,n=o(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof G&&i.setColors(e)}},t.resetColors=function(){this._defaultLogger instanceof G&&this._defaultLogger.setColors({});for(var e,t=o(this._loggers.values());!(e=t()).done;){var n=e.value;n instanceof G&&n.setColors({})}},e}(),V=Q.getInstance().getLogger();function Y(e){return Q.getInstance().getLogger(e)}Y("ReferenceTracker");var K=function(){function e(e){this._target=e}return e.prototype.deref=function(){return this._target},e}(),J="undefined"!=typeof globalThis&&globalThis.WeakRef||"undefined"!=typeof global&&global.WeakRef||"undefined"!=typeof window&&window.WeakRef||K,$=new Map;function Z(e){var t=$.get(e);return(null==t?void 0:t.deref())||null}var X=function(){function e(){this._references=new Map,this._scene=null}var t=e.prototype;return t.registerReference=function(e,t,n){var i=e.id,r=this._references.get(i);r||(r=new Set,this._references.set(i,r)),this._findRecord(r,t,n)||r.add({component:new J(t),propertyKey:n})},t.unregisterReference=function(e,t,n){var i=e.id,r=this._references.get(i);if(r){var s=this._findRecord(r,t,n);s&&(r.delete(s),0===r.size&&this._references.delete(i))}},t.clearReferencesTo=function(e){var t=this._references.get(e);if(t){for(var n,i=[],r=o(t);!(n=r()).done;){var s=n.value;s.component.deref()&&i.push(s)}for(var a=0,c=i;a<c.length;a++){var u=c[a],h=u.component.deref();h&&(h[u.propertyKey]=null)}this._references.delete(e)}},t.clearComponentReferences=function(e){for(var t,n=o(this._references.entries());!(t=n()).done;){for(var i,r=t.value,s=r[0],a=r[1],c=[],u=o(a);!(i=u()).done;){var h=i.value,l=h.component.deref();l&&l!==e||c.push(h)}for(var f=0,d=c;f<d.length;f++){var p=d[f];a.delete(p)}0===a.size&&this._references.delete(s)}},t.getReferencesTo=function(e){var t=this._references.get(e);if(!t)return[];for(var n,i=[],r=o(t);!(n=r()).done;){var s=n.value;s.component.deref()&&i.push(s)}return i},t.cleanup=function(){for(var e,t=[],n=o(this._references.entries());!(e=n()).done;){for(var i,r=e.value,s=r[0],a=r[1],c=[],u=o(a);!(i=u()).done;){var h=i.value;h.component.deref()||c.push(h)}for(var l=0,f=c;l<f.length;l++){var d=f[l];a.delete(d)}0===a.size&&t.push(s)}for(var p=0,y=t;p<y.length;p++){var m=y[p];this._references.delete(m)}},t.setScene=function(e){this._scene=new J(e)},t.registerEntityScene=function(e,t){$.set(e,new J(t))},t.unregisterEntityScene=function(e){$.delete(e)},t.getDebugInfo=function(){for(var e,t={},n=o(this._references.entries());!(e=n()).done;){for(var i,r=e.value,s=r[0],a=[],c=o(r[1]);!(i=c()).done;){var u=i.value,h=u.component.deref();h&&a.push({componentId:h.id,propertyKey:u.propertyKey})}a.length>0&&(t["entity_"+s]=a)}return t},t._findRecord=function(e,t,n){for(var i,r=o(e);!(i=r()).done;){var s=i.value;if(s.component.deref()===t&&s.propertyKey===n)return s}},e}(),ee=Y("EntityRefDecorator"),te=Symbol("EntityRefMetadata"),ne=Symbol("EntityRefValues");function ie(e){var t=e[ne];return t||(t=new Map,e[ne]=t),t}function re(e){return e&&("function"==typeof e?e:e.constructor)[te]||null}var se=function(){function e(){}var t=e.prototype;return t.collectEntityData=function(e){if(!e)return this.getEmptyEntityDebugData();var t,n=e.entities;if(!n)return this.getEmptyEntityDebugData();try{t=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeData(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:[],entityDetailsMap:{}}},t.getRawEntityList=function(e){if(!e)return[];var t=e.entities;return null!=t&&t.buffer?t.buffer.map((function(e){var t,n;return{id:e.id,name:e.name||"Entity_"+e.id,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((function(e){return H(e)})),parentId:(null===(t=e.parent)||void 0===t?void 0:t.id)||null,childIds:(null===(n=e.children)||void 0===n?void 0:n.map((function(e){return e.id})))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}})):[]},t.getEntityDetails=function(e,t){try{var n,i,r;if(!t)return null;var s=t.entities;if(null==s||!s.buffer)return null;var o=s.buffer.find((function(t){return t.id===e}));if(!o)return null;var c=o.getDebugInfo?o.getDebugInfo():this.buildFallbackEntityInfo(o,t),u=this.extractComponentDetails(o.components),h=this.getSceneInfo(t);return a({},c,{scene:h.name,sceneName:h.name,sceneType:h.type,parentName:(null===(n=o.parent)||void 0===n?void 0:n.name)||null,components:u||[],componentCount:(null===(i=o.components)||void 0===i?void 0:i.length)||0,componentTypes:(null===(r=o.components)||void 0===r?void 0:r.map((function(e){return H(e)})))||[]})}catch(e){return{error:"获取实体详情失败: "+(e instanceof Error?e.message:String(e)),scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}},t.getSceneInfo=function(e){var t="当前场景",n="Scene";try{if(e.name&&"string"==typeof e.name&&e.name.trim())t=e.name.trim();else if(e.constructor&&e.constructor.name)t=e.constructor.name,n=e.constructor.name;else if(e._name&&"string"==typeof e._name&&e._name.trim())t=e._name.trim();else{var i,r=null===(i=Object.getPrototypeOf(e))||void 0===i||null===(i=i.constructor)||void 0===i?void 0:i.name;r&&"Object"!==r&&(t=r,n=r)}}catch(e){t="场景名获取失败"}return{name:t,type:n}},t.collectEntityDataWithMemory=function(e){if(!e)return this.getEmptyEntityDebugData();var t,n=e.entities;if(!n)return this.getEmptyEntityDebugData();try{t=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeDataWithMemory(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:this.buildEntityHierarchyTree(n),entityDetailsMap:this.buildEntityDetailsMap(n,e)}},t.collectArchetypeData=function(e){var t;if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(e.archetypeSystem);var n={entities:(null===(t=e.entities)||void 0===t?void 0:t.buffer)||[]};return{distribution:this.getArchetypeDistributionFast(n),topEntities:this.getTopEntitiesByComponentsFast(n)}},t.getArchetypeDistributionFast=function(e){var t=new Map;return e&&e.entities&&e.entities.forEach((function(e){var n,i=(null===(n=e.components)||void 0===n?void 0:n.map((function(e){return H(e)})))||[],r=i.length>0?i.sort().join(", "):"无组件",s=t.get(r);s?s.count++:t.set(r,{count:1,componentTypes:i})})),Array.from(t.entries()).map((function(e){return{signature:e[0],count:e[1].count,memory:0}})).sort((function(e,t){return t.count-e.count})).slice(0,20)},t.getTopEntitiesByComponentsFast=function(e){return e&&e.entities?e.entities.map((function(e){var t;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0}})).sort((function(e,t){return t.componentCount-e.componentCount})):[]},t.collectArchetypeDataWithMemory=function(e){var t;if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(e.archetypeSystem);var n={entities:(null===(t=e.entities)||void 0===t?void 0:t.buffer)||[]};return{distribution:this.getArchetypeDistributionWithMemory(n),topEntities:this.getTopEntitiesByComponentsWithMemory(n)}},t.extractArchetypeStatistics=function(e){var t=e.getAllArchetypes(),n=[],i=[];return t.forEach((function(e){var t,r,s=(null===(t=e.componentTypes)||void 0===t?void 0:t.map((function(e){return e.name})).join(","))||"Unknown",o=(null===(r=e.entities)||void 0===r?void 0:r.length)||0;n.push({signature:s,count:o,memory:0}),e.entities&&e.entities.forEach((function(e){var t;i.push({id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0})}))})),n.sort((function(e,t){return t.count-e.count})),i.sort((function(e,t){return t.componentCount-e.componentCount})),{distribution:n,topEntities:i}},t.extractArchetypeStatisticsWithMemory=function(e){var t=this,n=e.getAllArchetypes(),i=[],r=[];return n.forEach((function(e){var n,s,o=(null===(n=e.componentTypes)||void 0===n?void 0:n.map((function(e){return e.name})).join(","))||"Unknown",a=(null===(s=e.entities)||void 0===s?void 0:s.length)||0,c=0;if(e.entities&&e.entities.length>0){for(var u=Math.min(5,e.entities.length),h=0,l=0;l<u;l++)h+=t.estimateEntityMemoryUsage(e.entities[l]);c=h/u*a}i.push({signature:o,count:a,memory:c}),e.entities&&e.entities.forEach((function(e){var n;r.push({id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(n=e.components)||void 0===n?void 0:n.length)||0,memory:t.estimateEntityMemoryUsage(e)})}))})),i.sort((function(e,t){return t.count-e.count})),r.sort((function(e,t){return t.componentCount-e.componentCount})),{distribution:i,topEntities:r}},t.getArchetypeDistribution=function(e){var t=new Map;return e&&e.entities&&e.entities.forEach((function(e){var n,i=(null===(n=e.componentMask)||void 0===n?void 0:n.toString())||"0",r=t.get(i);t.set(i,(r||0)+1)})),Array.from(t.entries()).map((function(e){return{signature:e[0],count:e[1],memory:0}})).sort((function(e,t){return t.count-e.count}))},t.getArchetypeDistributionWithMemory=function(e){var t=this,n=new Map;return e&&e.entities&&e.entities.forEach((function(e){var i,r=(null===(i=e.components)||void 0===i?void 0:i.map((function(e){return H(e)})))||[],s=r.length>0?r.sort().join(", "):"无组件",o=n.get(s),a=t.estimateEntityMemoryUsage(e);(isNaN(a)||a<0)&&(a=0),o?(o.count++,o.memory+=a):n.set(s,{count:1,memory:a,componentTypes:r})})),Array.from(n.entries()).map((function(e){var t=e[0],n=e[1];return{signature:t,count:n.count,memory:isNaN(n.memory)?0:n.memory}})).sort((function(e,t){return t.count-e.count}))},t.getTopEntitiesByComponents=function(e){return e&&e.entities?e.entities.map((function(e){var t;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0}})).sort((function(e,t){return t.componentCount-e.componentCount})):[]},t.getTopEntitiesByComponentsWithMemory=function(e){var t=this;return e&&e.entities?e.entities.map((function(e){var n;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(n=e.components)||void 0===n?void 0:n.length)||0,memory:t.estimateEntityMemoryUsage(e)}})).sort((function(e,t){return t.componentCount-e.componentCount})):[]},t.getEmptyEntityDebugData=function(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}},t.calculateFallbackEntityStats=function(e){var t=e.buffer||[],n=t.filter((function(e){return e.enabled&&!e._isDestroyed}));return{totalEntities:t.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?t.reduce((function(e,t){var n;return e+((null===(n=t.components)||void 0===n?void 0:n.length)||0)}),0)/n.length:0}},t.estimateEntityMemoryUsage=function(e){var t=this;try{var n=0,i=this.calculateObjectSize(e,["components","children","parent"]);return!isNaN(i)&&i>0&&(n+=i),e.components&&Array.isArray(e.components)&&e.components.forEach((function(e){var i=t.calculateObjectSize(e,["entity"]);!isNaN(i)&&i>0&&(n+=i)})),isNaN(n)||n<0?0:n}catch(e){return 0}},t.calculateObjectSize=function(e,t){if(void 0===t&&(t=[]),!e||"object"!=typeof e)return 0;var n=new WeakSet,i=function(e,r){if(void 0===r&&(r=0),!e||"object"!=typeof e||r>=2)return 0;if(n.has(e))return 0;n.add(e);var s=32;try{for(var o=Object.keys(e),a=Math.min(o.length,20),c=0;c<a;c++){var u=o[c];if(!(t.includes(u)||"constructor"===u||"__proto__"===u||u.startsWith("_cc_")||u.startsWith("__"))){var h=e[u];s+=2*u.length,"string"==typeof h?s+=Math.min(2*h.length,200):"number"==typeof h?s+=8:"boolean"==typeof h?s+=4:Array.isArray(h)?s+=40+Math.min(8*h.length,160):"object"==typeof h&&null!==h&&(s+=i(h,r+1))}}}catch(e){return 64}return s};try{var r=i(e);return Math.max(r,32)}catch(e){return 64}},t.buildEntityHierarchyTree=function(e){var t=this;if(null==e||!e.buffer)return[];var n=[];return e.buffer.forEach((function(e){if(!e.parent){var i=t.buildEntityHierarchyNode(e);n.push(i)}})),n.sort((function(e,t){return e.name<t.name?-1:e.name>t.name?1:e.id-t.id})),n},t.buildEntityHierarchyNode=function(e){var t,n=this,i={id:e.id,name:e.name||"Entity_"+e.id,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((function(e){return H(e)})),parentId:(null===(t=e.parent)||void 0===t?void 0:t.id)||null,children:[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0};(e.children&&e.children.length>0&&(i.children=e.children.map((function(e){return n.buildEntityHierarchyNode(e)}))),"function"==typeof e.getDebugInfo)&&(i=a({},i,e.getDebugInfo()));return e.components&&e.components.length>0&&(i.componentDetails=this.extractComponentDetails(e.components)),i},t.buildEntityDetailsMap=function(e,t){var n=this;if(null==e||!e.buffer)return{};for(var i={},r=e.buffer,s=0;s<r.length;s+=100){r.slice(s,s+100).forEach((function(e){var r,s=e.getDebugInfo?e.getDebugInfo():n.buildFallbackEntityInfo(e,t),o=e.getComponentCacheStats?e.getComponentCacheStats():null,c=n.extractComponentDetails(e.components);i[e.id]=a({},s,{parentName:(null===(r=e.parent)||void 0===r?void 0:r.name)||null,components:c,componentTypes:s.componentTypes||c.map((function(e){return e.typeName})),cachePerformance:o?{hitRate:o.cacheStats.hitRate,size:o.cacheStats.size,maxSize:o.cacheStats.maxSize}:null})}))}return i},t.buildFallbackEntityInfo=function(e,t){var n,i,r,s=this.getSceneInfo(t);return{name:e.name||"Entity_"+e.id,id:e.id,enabled:!1!==e.enabled,active:!1!==e.active,activeInHierarchy:!1!==e.activeInHierarchy,destroyed:e.isDestroyed||!1,scene:s.name,sceneName:s.name,sceneType:s.type,componentCount:e.components.length,componentTypes:e.components.map((function(e){return H(e)})),componentMask:(null===(n=e.componentMask)||void 0===n?void 0:n.toString())||"0",parentId:(null===(i=e.parent)||void 0===i?void 0:i.id)||null,childCount:(null===(r=e.children)||void 0===r?void 0:r.length)||0,childIds:e.children.map((function(e){return e.id}))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}},t.extractComponentDetails=function(e){var t=this;return e.map((function(e){var n=H(e),i={};try{Object.keys(e).forEach((function(n){if(!n.startsWith("_")&&"entity"!==n&&"constructor"!==n){var r=e[n];null!=r&&(i[n]=t.formatPropertyValue(r))}})),0===Object.keys(i).length&&(i._info="该组件没有公开属性",i._componentId=H(e))}catch(t){i._error="属性提取失败",i._componentId=H(e)}return{typeName:n,properties:i}}))},t.getComponentProperties=function(e,t,n){var i=this;try{if(!n)return{};var r=n.entities;if(null==r||!r.buffer)return{};var s=r.buffer.find((function(t){return t.id===e}));if(!s||t>=s.components.length)return{};var o=s.components[t],a={};return Object.keys(o).forEach((function(e){if(!e.startsWith("_")&&"entity"!==e){var t=o[e];null!=t&&(a[e]=i.formatPropertyValue(t))}})),a}catch(e){return{_error:"属性提取失败"}}},t.formatPropertyValue=function(e,t){return void 0===t&&(t=0),null==e?e:"object"!=typeof e?"string"==typeof e&&e.length>200?"[长字符串: "+e.length+"字符] "+e.substring(0,100)+"...":e:0===t?this.formatObjectFirstLevel(e):this.createLazyLoadPlaceholder(e)},t.formatObjectFirstLevel=function(e){var t=this;try{if(Array.isArray(e)){if(0===e.length)return[];if(e.length>10){var n=e.slice(0,3).map((function(e){return t.formatPropertyValue(e,1)}));return{_isLazyArray:!0,_arrayLength:e.length,_sample:n,_summary:"数组["+e.length+"个元素]"}}return e.map((function(e){return t.formatPropertyValue(e,1)}))}var i=Object.keys(e);if(0===i.length)return{};for(var r={},s=0,o=0,a=i;o<a.length;o++){var c=a[o];if(s>=15){r._hasMoreProperties=!0,r._totalProperties=i.length,r._hiddenCount=i.length-s;break}if(!c.startsWith("_")&&!c.startsWith("$")&&"function"!=typeof e[c])try{var u=e[c];null!=u&&(r[c]=this.formatPropertyValue(u,1),s++)}catch(e){r[c]="[访问失败: "+(e instanceof Error?e.message:String(e))+"]",s++}}return r}catch(e){return"[对象解析失败: "+(e instanceof Error?e.message:String(e))+"]"}},t.createLazyLoadPlaceholder=function(e){try{var t,n=(null===(t=e.constructor)||void 0===t?void 0:t.name)||"Object";return{_isLazyObject:!0,_typeName:n,_summary:this.getObjectSummary(e,n),_objectId:this.generateObjectId(e)}}catch(e){return{_isLazyObject:!0,_typeName:"Unknown",_summary:"无法分析的对象: "+(e instanceof Error?e.message:String(e)),_objectId:Math.random().toString(36).substr(2,9)}}},t.getObjectSummary=function(e,t){try{if((t.toLowerCase().includes("vec")||t.toLowerCase().includes("vector"))&&void 0!==e.x&&void 0!==e.y){var n=void 0!==e.z?e.z:"";return t+"("+e.x+", "+e.y+(n?", "+n:"")+")"}if(t.toLowerCase().includes("color")&&void 0!==e.r&&void 0!==e.g&&void 0!==e.b){var i=void 0!==e.a?e.a:1;return t+"("+e.r+", "+e.g+", "+e.b+", "+i+")"}if(t.toLowerCase().includes("node"))return t+": "+(e.name||e._name||"未命名");if(t.toLowerCase().includes("component")){var r,s,o=(null===(r=e.node)||void 0===r?void 0:r.name)||(null===(s=e.node)||void 0===s?void 0:s._name)||"";return t+(o?" on "+o:"")}var a=Object.keys(e);return 0===a.length?t+" (空对象)":t+" ("+a.length+"个属性)"}catch(e){return t+" (无法分析)"}},t.generateObjectId=function(e){try{return void 0!==e.id?"obj_"+e.id:void 0!==e._id?"obj_"+e._id:void 0!==e.uuid?"obj_"+e.uuid:void 0!==e._uuid?"obj_"+e._uuid:"obj_"+Math.random().toString(36).substr(2,9)}catch(e){return"obj_"+Math.random().toString(36).substr(2,9)}},t.expandLazyObject=function(e,t,n,i){try{if(!i)return null;var r=i.entities;if(null==r||!r.buffer)return null;var s=r.buffer.find((function(t){return t.id===e}));if(!s)return null;if(t>=s.components.length)return null;var o=s.components[t],a=this.getObjectByPath(o,n);return a?this.formatObjectFirstLevel(a):null}catch(e){return{error:"展开失败: "+(e instanceof Error?e.message:String(e))}}},t.getObjectByPath=function(e,t){if(!t)return e;for(var n,i=e,r=o(t.split("."));!(n=r()).done;){var s=n.value;if(null==i)return null;if(s.includes("[")&&s.includes("]")){var a=s.substring(0,s.indexOf("[")),c=parseInt(s.substring(s.indexOf("[")+1,s.indexOf("]")));if(a&&(i=i[a]),!(Array.isArray(i)&&c>=0&&c<i.length))return null;i=i[c]}else i=i[s]}return i},e}(),oe=function(){function e(){}return e.prototype.collectSystemData=function(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};var n=t.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};var i=n.processors||[],r=new Map,s=new Map;if(e)try{r=e.getAllSystemStats(),s=e.getAllSystemData()}catch(e){}return{totalSystems:i.length,systemsInfo:i.map((function(e){var t,n=e.systemName||j(e),i=r.get(n),o=s.get(n);return{name:n,type:j(e),entityCount:(null===(t=e.entities)||void 0===t?void 0:t.length)||0,executionTime:(null==i?void 0:i.averageTime)||(null==o?void 0:o.executionTime)||0,minExecutionTime:(null==i?void 0:i.minTime)===Number.MAX_VALUE?0:(null==i?void 0:i.minTime)||0,maxExecutionTime:(null==i?void 0:i.maxTime)||0,executionTimeHistory:(null==i?void 0:i.recentTimes)||[],updateOrder:e.updateOrder||0,enabled:!1!==e.enabled,lastUpdateTime:(null==o?void 0:o.lastUpdateTime)||0}}))}},e}(),ae=function(){function e(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.lastGCCount=0,this.gcCollections=0,this.lastMemoryCheck=0}var t=e.prototype;return t.collectPerformanceData=function(e){var t=_.deltaTime,n=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),s=r.totalExecutionTime,o=n>0?s/n*100:0,a=0;performance.memory&&(a=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(s),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();var c=this.frameTimeHistory.filter((function(e){return e>=0}));return{frameTime:s,engineFrameTime:n,ecsPercentage:o,memoryUsage:a,fps:i,averageFrameTime:c.length>0?c.reduce((function(e,t){return e+t}),0)/c.length:s,minFrameTime:c.length>0?Math.min.apply(Math,c):s,maxFrameTime:c.length>0?Math.max.apply(Math,c):s,frameTimeHistory:[].concat(this.frameTimeHistory),systemPerformance:this.getSystemPerformance(e),systemBreakdown:r.systemBreakdown,memoryDetails:this.getMemoryDetails()}},t.getECSPerformanceData=function(e){if(!e)return{totalExecutionTime:0,systemBreakdown:[]};if(!e.enabled){try{e.enabled=!0}catch(e){}return{totalExecutionTime:0,systemBreakdown:[]}}try{var t=0,n=[],i=e.getAllSystemStats();if(0===i.size)return{totalExecutionTime:0,systemBreakdown:[]};for(var r,s=o(i.entries());!(r=s()).done;){var a=r.value,c=a[0],u=a[1],h=u.recentTimes&&u.recentTimes.length>0?u.recentTimes[u.recentTimes.length-1]:u.averageTime||0;t+=h,n.push({systemName:c,executionTime:h,percentage:0})}return n.forEach((function(e){e.percentage=t>0?e.executionTime/t*100:0})),n.sort((function(e,t){return t.executionTime-e.executionTime})),{totalExecutionTime:t,systemBreakdown:n}}catch(e){return{totalExecutionTime:0,systemBreakdown:[]}}},t.getSystemPerformance=function(e){if(!e)return[];try{var t=e.getAllSystemStats(),n=e.getAllSystemData();return Array.from(t.entries()).map((function(e){var t=e[0],i=e[1],r=n.get(t);return{systemName:t,averageTime:i.averageTime||0,maxTime:i.maxTime||0,minTime:i.minTime===Number.MAX_VALUE?0:i.minTime||0,samples:i.executionCount||0,percentage:0,entityCount:(null==r?void 0:r.entityCount)||0,lastExecutionTime:(null==r?void 0:r.executionTime)||0}}))}catch(e){return[]}},t.getMemoryDetails=function(){var e={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){var t=performance.memory;if(e.totalMemory=t.jsHeapSizeLimit||536870912,e.usedMemory=t.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,this.lastMemoryCheck>0)this.lastMemoryCheck-e.usedMemory>1048576&&this.gcCollections++;this.lastMemoryCheck=e.usedMemory}else e.totalMemory=536870912,e.freeMemory=536870912}catch(e){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return e},t.updateGCCount=function(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(e){return this.gcCollections}},e}(),ce=function(){function e(e,t,n,i,r){void 0===n&&(n=1e3),void 0===i&&(i=10),void 0===r&&(r=1.5),this.pool=[],this.stats={totalCreated:0,totalAcquired:0,totalReleased:0},this.createFn=e,this.resetFn=t,this.maxSize=n,this.minSize=Math.max(1,i),this.growthFactor=Math.max(1.1,r)}var t=e.prototype;return t.acquire=function(){return this.stats.totalAcquired++,this.pool.length>0?this.pool.pop():(this.stats.totalCreated++,this.createFn())},t.release=function(e){this.stats.totalReleased++,this.pool.length>=this.maxSize||(this.resetFn&&this.resetFn(e),this.pool.push(e))},t.prewarm=function(e){for(var t=Math.min(e,this.maxSize),n=this.pool.length;n<t;n++){var i=this.createFn();this.resetFn&&this.resetFn(i),this.pool.push(i),this.stats.totalCreated++}},t.shrink=function(){for(;this.pool.length>this.minSize;)this.pool.pop()},t.clear=function(){this.pool.length=0},t.getAvailableCount=function(){return this.pool.length},t.getMaxSize=function(){return this.maxSize},t.getStats=function(){var e=0===this.stats.totalAcquired?0:(this.stats.totalAcquired-this.stats.totalCreated)/this.stats.totalAcquired;return{totalCreated:this.stats.totalCreated,totalAcquired:this.stats.totalAcquired,totalReleased:this.stats.totalReleased,hitRate:e,currentSize:this.pool.length,maxSize:this.maxSize,minSize:this.minSize,utilizationRate:this.pool.length/this.maxSize}},e}(),ue=function(){function e(){this.pools=new Map,this.usageTracker=new Map,this.autoCleanupInterval=6e4,this.lastCleanupTime=0}e.getInstance=function(){return e.instance||(e.instance=new e),e.instance};var t=e.prototype;return t.registerPool=function(e,t,n,i,r){this.pools.set(e,new ce(t,n,i,r)),this.usageTracker.set(e,{createCount:0,releaseCount:0,lastAccessTime:Date.now()})},t.acquireComponent=function(e){var t=this.pools.get(e);return this.trackUsage(e,"create"),t?t.acquire():null},t.releaseComponent=function(e,t){var n=this.pools.get(e);this.trackUsage(e,"release"),n&&n.release(t)},t.trackUsage=function(e,t){var n=this.usageTracker.get(e);n||(n={createCount:0,releaseCount:0,lastAccessTime:Date.now()},this.usageTracker.set(e,n)),"create"===t?n.createCount++:n.releaseCount++,n.lastAccessTime=Date.now()},t.update=function(){var e=Date.now();if(!(e-this.lastCleanupTime<this.autoCleanupInterval)){for(var t,n=o(this.usageTracker.entries());!(t=n()).done;){var i=t.value,r=i[0];if(e-i[1].lastAccessTime>12e4){var s=this.pools.get(r);s&&s.shrink()}}this.lastCleanupTime=e}},t.getHotComponents=function(e){return void 0===e&&(e=100),Array.from(this.usageTracker.entries()).filter((function(t){return t[0],t[1].createCount>e})).map((function(e){return e[0]}))},t.prewarmAll=function(e){void 0===e&&(e=100);for(var t,n=o(this.pools.values());!(t=n()).done;){t.value.prewarm(e)}},t.clearAll=function(){for(var e,t=o(this.pools.values());!(e=t()).done;){e.value.clear()}},t.reset=function(){this.pools.clear(),this.usageTracker.clear()},t.getGlobalStats=function(){for(var e,t=[],n=o(this.pools.entries());!(e=n()).done;){var i=e.value,r=i[0],s=i[1];t.push({componentName:r,poolStats:s.getStats(),usage:this.usageTracker.get(r)})}return t},t.getPoolStats=function(){for(var e,t=new Map,n=o(this.pools);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];t.set(r,{available:s.getAvailableCount(),maxSize:s.getMaxSize()})}return t},t.getPoolUtilization=function(){for(var e,t=new Map,n=o(this.pools);!(e=n()).done;){var i=e.value,r=i[0],s=i[1],a=s.getAvailableCount(),c=s.getMaxSize(),u=c-a,h=c>0?u/c*100:0;t.set(r,{used:u,total:c,utilization:h})}return t},t.getComponentUtilization=function(e){var t=this.pools.get(e);if(!t)return 0;var n=t.getAvailableCount(),i=t.getMaxSize();return i>0?(i-n)/i*100:0},e}(),he=function(){function e(){}var t=e.prototype;return t.collectComponentData=function(e){var t=this;if(!e)return{componentTypes:0,componentInstances:0,componentStats:[]};var n=e.entities;if(null==n||!n.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};var i=new Map,r=0;n.buffer.forEach((function(e){e.components&&e.components.forEach((function(e){var t=H(e),n=i.get(t)||{count:0,entities:0};n.count++,r++,i.set(t,n)}))}));var s=new Map,a=new Map;try{for(var c,u=ue.getInstance(),h=u.getPoolStats(),l=u.getPoolUtilization(),f=o(h.entries());!(c=f()).done;){var d=c.value,p=d[0],y=d[1];a.set(p,y.maxSize)}for(var m,g=o(l.entries());!(m=g()).done;){var v=m.value,_=v[0],S=v[1];s.set(_,S.utilization)}}catch(e){}return{componentTypes:i.size,componentInstances:r,componentStats:Array.from(i.entries()).map((function(i){var r=i[0],o=i[1],c=a.get(r)||0,u=s.get(r)||0,h=t.getEstimatedComponentSize(r,e);return{typeName:r,instanceCount:o.count,memoryPerInstance:h,totalMemory:o.count*h,poolSize:c,poolUtilization:u,averagePerEntity:o.count/n.buffer.length}}))}},t.getEstimatedComponentSize=function(t,n){if(e.componentSizeCache.has(t))return e.componentSizeCache.get(t);if(!n)return 64;var i=n.entities;if(null==i||!i.buffer)return 64;var r=64;try{for(var s,a=o(i.buffer);!(s=a()).done;){var c=s.value;if(c.components){var u=c.components.find((function(e){return H(e)===t}));if(u){r=this.calculateQuickObjectSize(u);break}}}}catch(e){r=64}return e.componentSizeCache.set(t,r),r},t.calculateQuickObjectSize=function(e){if(!e||"object"!=typeof e)return 8;var t=32,n=new WeakSet,i=function(e,t){if(void 0===t&&(t=0),!e||"object"!=typeof e||n.has(e)||t>3)return 0;n.add(e);var r=0;try{for(var s=Object.keys(e),o=0;o<Math.min(s.length,20);o++){var a=s[o];if("entity"!==a&&"_entity"!==a&&"constructor"!==a){var c=e[a];r+=2*a.length,"string"==typeof c?r+=Math.min(2*c.length,200):"number"==typeof c?r+=8:"boolean"==typeof c?r+=4:"object"==typeof c&&null!==c&&(r+=i(c,t+1))}}}catch(e){return 32}return r};return t+=i(e),Math.max(t,32)},t.calculateDetailedComponentMemory=function(e,t){if(!t)return this.getEstimatedComponentSize(e,t);var n=t.entities;if(null==n||!n.buffer)return this.getEstimatedComponentSize(e,t);try{for(var i,r=o(n.buffer);!(i=r()).done;){var s=i.value;if(s.components){var a=s.components.find((function(t){return H(t)===e}));if(a)return this.estimateObjectSize(a)}}}catch(e){}return this.getEstimatedComponentSize(e,t)},t.estimateObjectSize=function(e,t,n){if(void 0===t&&(t=new WeakSet),void 0===n&&(n=0),null==e||n>10)return 0;if(t.has(e))return 0;var i=0;switch(typeof e){case"boolean":i=4;break;case"number":default:i=8;break;case"string":i=24+Math.min(2*e.length,1e3);break;case"object":if(t.add(e),Array.isArray(e)){i=40+8*e.length;for(var r=Math.min(e.length,50),s=0;s<r;s++)i+=this.estimateObjectSize(e[s],t,n+1)}else{i=32;try{for(var o=Object.getOwnPropertyNames(e),a=Math.min(o.length,30),c=0;c<a;c++){var u=o[c];if("constructor"!==u&&"__proto__"!==u&&"entity"!==u&&"_entity"!==u&&!u.startsWith("_cc_")&&!u.startsWith("__"))try{i+=16+2*u.length;var h=e[u];null!=h&&(i+=this.estimateObjectSize(h,t,n+1))}catch(e){continue}}}catch(e){i=128}}}return 8*Math.ceil(i/8)},e.clearCache=function(){e.componentSizeCache.clear()},e}();he.componentSizeCache=new Map;var le,fe=function(){function e(){this.sceneStartTime=Date.now()}var t=e.prototype;return t.collectSceneData=function(e){var t,n;if(!e)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneMemory:0,sceneUptime:0};var i=(Date.now()-this.sceneStartTime)/1e3,r=e.entities,s=e.entityProcessors;return{currentSceneName:e.name||"Unnamed Scene",isInitialized:e._didSceneBegin||!1,sceneRunTime:i,sceneEntityCount:(null==r||null===(t=r.buffer)||void 0===t?void 0:t.length)||0,sceneSystemCount:(null==s||null===(n=s.processors)||void 0===n?void 0:n.length)||0,sceneMemory:0,sceneUptime:i}},t.setSceneStartTime=function(e){this.sceneStartTime=e},e}(),de=function(){function e(e,t){void 0===t&&(t=!0),this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectInterval=2e3,this.url=e,this.autoReconnect=t}var t=e.prototype;return t.setMessageHandler=function(e){this.messageHandler=e},t.connect=function(){var e=this;return new Promise((function(t,n){try{e.ws=new WebSocket(e.url),e.ws.onopen=function(n){e.handleOpen(n),t()},e.ws.onclose=function(t){e.handleClose(t)},e.ws.onerror=function(t){e.handleError(t),n(t)},e.ws.onmessage=function(t){e.handleMessage(t)}}catch(t){e.handleConnectionFailure(t),n(t)}}))},t.disconnect=function(){this.ws&&(this.autoReconnect=!1,this.ws.close(),this.ws=void 0),this.isConnected=!1},t.send=function(e){if(this.isConnected&&this.ws)try{var t="string"==typeof e?e:JSON.stringify(e);this.ws.send(t)}catch(e){}},t.getConnectionStatus=function(){return this.isConnected},t.setMaxReconnectAttempts=function(e){this.maxReconnectAttempts=e},t.setReconnectInterval=function(e){this.reconnectInterval=e},t.scheduleReconnect=function(){var e=this;this.reconnectTimer&&clearTimeout(this.reconnectTimer);var t=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout((function(){e.connect().catch((function(t){e.reconnectAttempts<e.maxReconnectAttempts&&e.scheduleReconnect()}))}),t)},t.handleMessage=function(e){try{var t=JSON.parse(e.data);this.messageHandler&&this.messageHandler(t)}catch(e){}},t.handleOpen=function(e){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(e)},t.handleClose=function(e){this.isConnected=!1,this.onClose&&this.onClose(e),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()},t.handleError=function(e){this.onError&&this.onError(e)},t.handleConnectionFailure=function(e){this.onError&&this.onError(e)},e}();!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(le||(le={}));var pe=function(){function e(){}return e.create=function(t){if(t<0)throw new Error("Bit index "+t+" out of range [0, ∞)");var n={base:[0,0],segments:void 0};return e.setBit(n,t),n},e.fromNumber=function(e){return{base:[e>>>0,0],segments:void 0}},e.hasAny=function(e,t){var n=t.base,i=e.base,r=t.segments,s=e.segments,o=0!==(i[le.LOW]&n[le.LOW])||0!==(i[le.HIGH]&n[le.HIGH]);return!o&&r&&s?s.some((function(e,t){return 0!==(e[le.LOW]&r[t][le.LOW])||0!==(e[le.HIGH]&r[t][le.HIGH])})):o},e.hasAll=function(e,t){var n,i=e.base,r=t.base,s=e.segments,o=t.segments,a=(i[le.LOW]&r[le.LOW])===r[le.LOW]&&(i[le.HIGH]&r[le.HIGH])===r[le.HIGH];if(!a||!o)return a;var c=null!==(n=null==s?void 0:s.length)&&void 0!==n?n:0;if(s)for(var u=0;u<Math.min(c,o.length);u++)if((s[u][le.LOW]&o[u][le.LOW])!==o[u][le.LOW]||(s[u][le.HIGH]&o[u][le.HIGH])!==o[u][le.HIGH])return!1;for(var h=c;h<o.length;h++)if(0!==o[h][le.LOW]||0!==o[h][le.HIGH])return!1;return!0},e.hasNone=function(e,t){var n=e.base,i=t.base,r=e.segments,s=t.segments,o=0===(n[le.LOW]&i[le.LOW])&&0===(n[le.HIGH]&i[le.HIGH]);return r&&o&&s?r.every((function(e,t){return 0===(e[le.LOW]&s[t][le.LOW])&&0===(e[le.HIGH]&s[t][le.HIGH])})):o},e.isZero=function(e){var t=0===e.base[le.LOW]&&0===e.base[le.HIGH];return e.segments&&t?e.segments.every((function(e){return 0===e[le.LOW]&&0===e[le.HIGH]})):t},e.equals=function(e,t){var n,i,r=e.base[le.LOW]===t.base[le.LOW]&&e.base[le.HIGH]===t.base[le.HIGH];if(!r||!e.segments&&!t.segments)return r;for(var s=null!==(n=e.segments)&&void 0!==n?n:[],o=null!==(i=t.segments)&&void 0!==i?i:[],a=0;a<Math.max(s.length,o.length);a++){var c=s[a],u=o[a];if(c&&!u){if(0!==c[le.LOW]||0!==c[le.HIGH])return!1}else if(!c&&u){if(0!==u[le.LOW]||0!==u[le.HIGH])return!1}else if(c[le.LOW]!==u[le.LOW]||c[le.HIGH]!==u[le.HIGH])return!1}return!0},e.setBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var i=e.getSegmentByBitIndex(t,n),r=63&n;r<32?i[le.LOW]|=1<<r:i[le.HIGH]|=1<<r-32},e.getBit=function(t,n){if(n<0)return!1;var i=e.getSegmentByBitIndex(t,n,!1);if(!i)return!1;var r=63&n;return r<32?!!(i[le.LOW]&1<<r):!!(i[le.HIGH]&1<<r-32)},e.clearBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var i=e.getSegmentByBitIndex(t,n,!1);if(i){var r=63&n;r<32?i[le.LOW]&=~(1<<r):i[le.HIGH]&=~(1<<r-32)}},e.orInPlace=function(e,t){e.base[le.LOW]|=t.base[le.LOW],e.base[le.HIGH]|=t.base[le.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++)i[r][le.LOW]|=n[r][le.LOW],i[r][le.HIGH]|=n[r][le.HIGH]}},e.andInPlace=function(e,t){e.base[le.LOW]&=t.base[le.LOW],e.base[le.HIGH]&=t.base[le.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++)i[r][le.LOW]&=n[r][le.LOW],i[r][le.HIGH]&=n[r][le.HIGH]}},e.xorInPlace=function(e,t){e.base[le.LOW]^=t.base[le.LOW],e.base[le.HIGH]^=t.base[le.HIGH];var n=t.segments;if(n&&0!=n.length){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++)i[r][le.LOW]^=n[r][le.LOW],i[r][le.HIGH]^=n[r][le.HIGH]}},e.clear=function(e){e.base[le.LOW]=0,e.base[le.HIGH]=0;for(var t=0;t<(null!==(n=null===(i=e.segments)||void 0===i?void 0:i.length)&&void 0!==n?n:0);t++){var n,i,r=e.segments[t];r[le.LOW]=0,r[le.HIGH]=0}},e.copy=function(t,n){if(e.clear(n),n.base[le.LOW]=t.base[le.LOW],n.base[le.HIGH]=t.base[le.HIGH],t.segments&&0!=t.segments.length)if(n.segments){for(var i=t.segments.length-n.segments.length,r=0;r<i;r++)n.segments.push([0,0]);for(var s=0;s<length;s++){var o=n.segments[s],a=t.segments[s];o[le.LOW]=a[le.LOW],o[le.HIGH]=a[le.HIGH]}}else n.segments=t.segments.map((function(e){return[].concat(e)}))},e.clone=function(e){return{base:e.base.slice(),segments:e.segments?e.segments.map((function(e){return[].concat(e)})):void 0}},e.toString=function(e,t,n){var i,r;void 0===t&&(t=2),void 0===n&&(n=!1),2!=t&&16!=t&&(t=2);var s=null!==(i=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==i?i:0,o="";if(n){var a=0;a=2===t?66:19;for(var c=0;c<=s;c++){o+=(0===c?"0 (Base):":c+" ("+64*c+"):").toString().padEnd(a)}o+="\n"}for(var u=-1;u<s;u++){var h="",l=-1==u?e.base:e.segments[u],f=l[le.HIGH],d=l[le.LOW];if(2==t){h=f.toString(2).padStart(32,"0")+"_"+d.toString(2).padStart(32,"0")}else{var p=f?f.toString(16).toUpperCase():"";n&&(p=p.padStart(8,"0"));var y=d.toString(16).toUpperCase();p&&(y=y.padStart(8,"0")),h="0x"+p+y}o+=-1===u?h:" "+h}return o},e.popCount=function(e){for(var t=0,n=-1;n<(null!==(i=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==i?i:0);n++){for(var i,r,s=-1==n?e.base:e.segments[n],o=s[le.LOW],a=s[le.HIGH];o;)o&=o-1,t++;for(;a;)a&=a-1,t++}return t},e.getSegmentByBitIndex=function(e,t,n){if(void 0===n&&(n=!0),t<=63)return e.base;var i=e.segments;if(!i){if(!n)return null;i=e.segments=[]}var r=(t>>6)-1;if(i.length<=r){if(!n)return null;for(var s=r-i.length+1,o=0;o<s;o++)i.push([0,0])}return i[r]},e}();pe.ZERO={base:[0,0],segments:void 0};var ye=function(){function e(){}return e.inferOptimalType=function(e,t){void 0===t&&(t={});var n=typeof e;if("boolean"===n)return"uint8";if("number"!==n)return"float32";var i=t,r=i.minValue,s=i.maxValue,o=i.precision,a=i.signed;if(!0===o)return Math.abs(e)>34028235e31||void 0!==r&&Math.abs(r)>34028235e31||void 0!==s&&Math.abs(s)>34028235e31?"float64":"float32";if(!1===o||Number.isInteger(e)){var c=void 0!==r?r:e,u=void 0!==s?s:e;return!1!==a&&(c<0||e<0)?c>=-128&&u<=127?"int8":c>=-32768&&u<=32767?"int16":c>=-2147483648&&u<=2147483647?"int32":"float64":u<=255?"uint8":u<=65535?"uint16":u<=4294967295?"uint32":"float64"}return Number.isInteger(e)?e>=0&&e<=255?"uint8":e>=-128&&e<=127?"int8":e>=0&&e<=65535?"uint16":e>=-32768&&e<=32767?"int16":e>=0&&e<=4294967295?"uint32":e>=-2147483648&&e<=2147483647?"int32":"float64":"float32"},e.getTypedArrayConstructor=function(e){switch(e){case"float32":default:return Float32Array;case"float64":return Float64Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int8":return Int8Array;case"uint8":return Uint8Array;case"uint8clamped":return Uint8ClampedArray}},e}(),me=function(){function e(e){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=e,this.initializeFields(e)}var t=e.prototype;return t.initializeFields=function(t){var n=new t,i=t.__highPrecisionFields||new Set,r=t.__float64Fields||new Set,s=t.__float32Fields||new Set,o=t.__int32Fields||new Set,a=t.__uint32Fields||new Set,c=t.__int16Fields||new Set,u=t.__uint16Fields||new Set,h=t.__int8Fields||new Set,l=t.__uint8Fields||new Set,f=t.__uint8ClampedFields||new Set,d=t.__autoTypedFields||new Map,p=t.__serializeMapFields||new Set,y=t.__serializeSetFields||new Set,m=t.__serializeArrayFields||new Set;for(var g in n)if(n.hasOwnProperty(g)&&"id"!==g){var v=n[g],_=typeof v;if("number"===_)if(i.has(g));else if(d.has(g)){var S=d.get(g),C=ye.inferOptimalType(v,S),w=ye.getTypedArrayConstructor(C);this.fields.set(g,new w(this._capacity)),e._logger.info("字段 "+g+" 自动推断为 "+C+" 类型,值: "+v+", 选项:",S)}else r.has(g)?this.fields.set(g,new Float64Array(this._capacity)):o.has(g)?this.fields.set(g,new Int32Array(this._capacity)):a.has(g)?this.fields.set(g,new Uint32Array(this._capacity)):c.has(g)?this.fields.set(g,new Int16Array(this._capacity)):u.has(g)?this.fields.set(g,new Uint16Array(this._capacity)):h.has(g)?this.fields.set(g,new Int8Array(this._capacity)):l.has(g)?this.fields.set(g,new Uint8Array(this._capacity)):f.has(g)?this.fields.set(g,new Uint8ClampedArray(this._capacity)):(s.has(g),this.fields.set(g,new Float32Array(this._capacity)));else"boolean"===_?l.has(g)||!s.has(g)&&!r.has(g)?this.fields.set(g,new Uint8Array(this._capacity)):this.fields.set(g,new Float32Array(this._capacity)):"string"===_?this.stringFields.set(g,new Array(this._capacity)):"object"===_&&null!==v&&(p.has(g)||y.has(g)||m.has(g))&&this.serializedFields.set(g,new Array(this._capacity))}},t.addComponent=function(e,t){if(this.entityToIndex.has(e)){var n=this.entityToIndex.get(e);this.updateComponentAtIndex(n,t)}else{var i;this.freeIndices.length>0?i=this.freeIndices.pop():(i=this._size)>=this._capacity&&this.resize(2*this._capacity),this.entityToIndex.set(e,i),this.indexToEntity[i]=e,this.updateComponentAtIndex(i,t),this._size++}},t.updateComponentAtIndex=function(e,t){var n=this.indexToEntity[e],i=new Map,r=this.type.__highPrecisionFields||new Set,s=this.type.__serializeMapFields||new Set,o=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=this.type.__deepCopyFields||new Set;for(var u in t)if(t.hasOwnProperty(u)&&"id"!==u){var h=t[u],l=typeof h;if("number"===l)if(r.has(u)||!this.fields.has(u))i.set(u,h);else this.fields.get(u)[e]=h;else if("boolean"===l&&this.fields.has(u)){this.fields.get(u)[e]=h?1:0}else if(this.stringFields.has(u)){this.stringFields.get(u)[e]=String(h)}else if(this.serializedFields.has(u)){this.serializedFields.get(u)[e]=this.serializeValue(h,u,s,o,a)}else c.has(u)?i.set(u,this.deepClone(h)):i.set(u,h)}i.size>0&&this.complexFields.set(n,i)},t.serializeValue=function(t,n,i,r,s){try{return i.has(n)&&t instanceof Map?JSON.stringify(Array.from(t.entries())):r.has(n)&&t instanceof Set?JSON.stringify(Array.from(t)):(s.has(n)&&Array.isArray(t),JSON.stringify(t))}catch(t){return e._logger.warn("SoA序列化字段 "+n+" 失败:",t),"{}"}},t.deserializeValue=function(t,n,i,r,s){try{var o=JSON.parse(t);return i.has(n)?new Map(o):r.has(n)?new Set(o):(s.has(n),o)}catch(t){return e._logger.warn("SoA反序列化字段 "+n+" 失败:",t),null}},t.deepClone=function(e){var t=this;if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array)return e.map((function(e){return t.deepClone(e)}));if(e instanceof Map){for(var n,i=new Map,r=o(e.entries());!(n=r()).done;){var s=n.value,a=s[0],c=s[1];i.set(a,this.deepClone(c))}return i}if(e instanceof Set){for(var u,h=new Set,l=o(e.values());!(u=l()).done;){var f=u.value;h.add(this.deepClone(f))}return h}var d={};for(var p in e)e.hasOwnProperty(p)&&(d[p]=this.deepClone(e[p]));return d},t.getComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;for(var n,i=new this.type,r=this.type.__serializeMapFields||new Set,s=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=o(this.fields.entries());!(n=c()).done;){var u=n.value,h=u[0],l=u[1][t],f=this.getFieldType(h);i[h]="boolean"===f?1===l:l}for(var d,p=o(this.stringFields.entries());!(d=p()).done;){var y=d.value,m=y[0],g=y[1];i[m]=g[t]}for(var v,_=o(this.serializedFields.entries());!(v=_()).done;){var S=v.value,C=S[0],w=S[1][t];w&&(i[C]=this.deserializeValue(w,C,r,s,a))}var E=this.complexFields.get(e);if(E)for(var b,A=o(E.entries());!(b=A()).done;){var T=b.value,M=T[0],x=T[1];i[M]=x}return i},t.getFieldType=function(e){return typeof(new this.type)[e]},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.getComponent(e);return this.complexFields.delete(e),this.entityToIndex.delete(e),this.freeIndices.push(t),this._size--,n},t.resize=function(t){for(var n,i=o(this.fields.entries());!(n=i()).done;){var r=n.value,s=r[0],a=r[1],c=void 0;a instanceof Float32Array?c=new Float32Array(t):a instanceof Float64Array?c=new Float64Array(t):a instanceof Int32Array?c=new Int32Array(t):a instanceof Uint32Array?c=new Uint32Array(t):a instanceof Int16Array?c=new Int16Array(t):a instanceof Uint16Array?c=new Uint16Array(t):a instanceof Int8Array?c=new Int8Array(t):a instanceof Uint8Array?c=new Uint8Array(t):a instanceof Uint8ClampedArray?c=new Uint8ClampedArray(t):(c=new Float32Array(t),e._logger.warn("未知的TypedArray类型用于字段 "+s+",回退到Float32Array")),c.set(a),this.fields.set(s,c)}for(var u,h=o(this.stringFields.entries());!(u=h()).done;){for(var l=u.value,f=l[0],d=l[1],p=new Array(t),y=0;y<d.length;y++)p[y]=d[y];this.stringFields.set(f,p)}for(var m,g=o(this.serializedFields.entries());!(m=g()).done;){for(var v=m.value,_=v[0],S=v[1],C=new Array(t),w=0;w<S.length;w++)C[w]=S[w];this.serializedFields.set(_,C)}this._capacity=t},t.getActiveIndices=function(){return Array.from(this.entityToIndex.values())},t.getFieldArray=function(e){return this.fields.get(e)||null},t.getTypedFieldArray=function(e){return this.fields.get(String(e))||null},t.getEntityIndex=function(e){return this.entityToIndex.get(e)},t.getEntityIdByIndex=function(e){return this.indexToEntity[e]},t.size=function(){return this._size},t.clear=function(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(var e,t=o(this.fields.values());!(e=t()).done;){e.value.fill(0)}for(var n,i=o(this.stringFields.values());!(n=i()).done;)for(var r=n.value,s=0;s<r.length;s++)r[s]=void 0;for(var a,c=o(this.serializedFields.values());!(a=c()).done;)for(var u=a.value,h=0;h<u.length;h++)u[h]=void 0},t.compact=function(){if(0!==this.freeIndices.length){for(var e=Array.from(this.entityToIndex.entries()).sort((function(e,t){return e[1]-t[1]})),t=new Map,n=[],i=0;i<e.length;i++){var r=e[i],s=r[0],a=r[1];if(t.set(s,i),n[i]=s,i!==a){for(var c,u=o(this.fields.entries());!(c=u()).done;){var h=c.value[1];h[i]=h[a]}for(var l,f=o(this.stringFields.entries());!(l=f()).done;){var d=l.value[1];d[i]=d[a]}for(var p,y=o(this.serializedFields.entries());!(p=y()).done;){var m=p.value[1];m[i]=m[a]}}}this.entityToIndex=t,this.indexToEntity=n,this.freeIndices=[],this._size=e.length}},t.getStats=function(){for(var e,t=0,n=new Map,i=o(this.fields.entries());!(e=i()).done;){var r=e.value,s=r[0],a=r[1],c=void 0,u=void 0;a instanceof Float32Array?(c=4,u="float32"):a instanceof Float64Array?(c=8,u="float64"):a instanceof Int32Array?(c=4,u="int32"):a instanceof Uint32Array?(c=4,u="uint32"):a instanceof Int16Array?(c=2,u="int16"):a instanceof Uint16Array?(c=2,u="uint16"):a instanceof Int8Array?(c=1,u="int8"):a instanceof Uint8Array?(c=1,u="uint8"):a instanceof Uint8ClampedArray?(c=1,u="uint8clamped"):(c=4,u="unknown");var h=a.length*c;t+=h,n.set(s,{size:this._size,capacity:a.length,type:u,memory:h})}return{size:this._size,capacity:this._capacity,usedSlots:this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:t,fieldStats:n}},t.performVectorizedOperation=function(e){var t=this.getActiveIndices();e(this.fields,t)},e}();me._logger=Y("SoAStorage");var ge=function(){function e(){}return e.register=function(e){var t=U(e);if(this.componentTypes.has(e))return this.componentTypes.get(e);var n=this.nextBitIndex++;return this.componentTypes.set(e,n),this.bitIndexToType.set(n,e),this.componentNameToType.set(t,e),this.componentNameToId.set(t,n),n},e.getBitMask=function(e){var t=this.componentTypes.get(e);if(void 0===t){var n=U(e);throw new Error("Component type "+n+" is not registered")}return pe.create(t)},e.getBitIndex=function(e){var t=this.componentTypes.get(e);if(void 0===t){var n=U(e);throw new Error("Component type "+n+" is not registered")}return t},e.isRegistered=function(e){return this.componentTypes.has(e)},e.getTypeByBitIndex=function(e){return this.bitIndexToType.get(e)||null},e.getRegisteredCount=function(){return this.nextBitIndex},e.getComponentType=function(e){return this.componentNameToType.get(e)||null},e.getAllRegisteredTypes=function(){return new Map(this.componentTypes)},e.getAllComponentNames=function(){return new Map(this.componentNameToType)},e.getComponentId=function(e){return this.componentNameToId.get(e)},e.registerComponentByName=function(e){if(this.componentNameToId.has(e))return this.componentNameToId.get(e);var t=this.nextBitIndex++;return this.componentNameToId.set(e,t),t},e.createSingleComponentMask=function(e){var t="single:"+e;if(this.maskCache.has(t))return this.maskCache.get(t);var n=this.getComponentId(e);if(void 0===n)throw new Error("Component type "+e+" is not registered");var i=pe.create(n);return this.maskCache.set(t,i),i},e.createComponentMask=function(e){var t="multi:"+[].concat(e).sort().join(",");if(this.maskCache.has(t))return this.maskCache.get(t);for(var n,i=pe.clone(pe.ZERO),r=o(e);!(n=r()).done;){var s=n.value,a=this.getComponentId(s);if(void 0!==a){var c=pe.create(a);pe.orInPlace(i,c)}}return this.maskCache.set(t,i),i},e.clearMaskCache=function(){this.maskCache.clear()},e.reset=function(){this.componentTypes.clear(),this.bitIndexToType.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0},e}();ge._logger=Y("ComponentStorage"),ge.componentTypes=new Map,ge.bitIndexToType=new Map,ge.componentNameToType=new Map,ge.componentNameToId=new Map,ge.maskCache=new Map,ge.nextBitIndex=0;var ve=function(){function e(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e,ge.isRegistered(e)||ge.register(e)}var t=e.prototype;return t.addComponent=function(e,t){if(this.entityToIndex.has(e))throw new Error("Entity "+e+" already has component "+U(this.componentType));var n=this.dense.length;this.dense.push(t),this.entityIds.push(e),this.entityToIndex.set(e,n)},t.getComponent=function(e){var t=this.entityToIndex.get(e);return void 0!==t?this.dense[t]:null},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.dense[t],i=this.dense.length-1;if(t!==i){var r=this.dense[i],s=this.entityIds[i];this.dense[t]=r,this.entityIds[t]=s,this.entityToIndex.set(s,t)}return this.dense.pop(),this.entityIds.pop(),this.entityToIndex.delete(e),n},t.forEach=function(e){for(var t=0;t<this.dense.length;t++)e(this.dense[t],this.entityIds[t],t)},t.getDenseArray=function(){return{components:[].concat(this.dense),entityIds:[].concat(this.entityIds)}},t.clear=function(){this.dense.length=0,this.entityIds.length=0,this.entityToIndex.clear()},t.getStats=function(){return{totalSlots:this.dense.length,usedSlots:this.dense.length,freeSlots:0,fragmentation:0}},s(e,[{key:"size",get:function(){return this.dense.length}},{key:"type",get:function(){return this.componentType}}])}(),_e=function(){function e(){this.storages=new Map}var t=e.prototype;return t.isSoAStorage=function(e){return this.storages.get(e)instanceof me},t.getSoAStorage=function(e){var t=this.getStorage(e);return t instanceof me?t:null},t.getFieldArray=function(e,t){var n=this.getSoAStorage(e);return n?n.getFieldArray(t):null},t.getTypedFieldArray=function(e,t){var n=this.getSoAStorage(e);return n?n.getTypedFieldArray(t):null},t.getActiveIndices=function(e){var t=this.getSoAStorage(e);return t?t.getActiveIndices():[]},t.getEntityIndex=function(e,t){var n=this.getSoAStorage(e);return n?n.getEntityIndex(t):void 0},t.getEntityIdByIndex=function(e,t){var n=this.getSoAStorage(e);return n?n.getEntityIdByIndex(t):void 0},t.getStorage=function(t){var n=this.storages.get(t);n||(t.__enableSoA?(n=new me(t),e._logger.info("为 "+U(t)+" 启用SoA优化(适用于大规模批量操作)")):n=new ve(t),this.storages.set(t,n));return n},t.addComponent=function(e,t){var n=t.constructor;this.getStorage(n).addComponent(e,t)},t.getComponent=function(e,t){var n=this.storages.get(t);return n?n.getComponent(e):null},t.hasComponent=function(e,t){var n=this.storages.get(t);return!!n&&n.hasComponent(e)},t.removeComponent=function(e,t){var n=this.storages.get(t);return n?n.removeComponent(e):null},t.removeAllComponents=function(e){for(var t,n=o(this.storages.values());!(t=n()).done;){t.value.removeComponent(e)}},t.getComponentMask=function(e){for(var t,n=pe.clone(pe.ZERO),i=o(this.storages.entries());!(t=i()).done;){var r=t.value,s=r[0];if(r[1].hasComponent(e)){var a=ge.getBitMask(s);pe.orInPlace(n,a)}}return n},t.getAllStats=function(){for(var e,t=new Map,n=o(this.storages.entries());!(e=n()).done;){var i=e.value,r=i[0],s=i[1],a=U(r);t.set(a,s.getStats())}return t},t.clear=function(){for(var e,t=o(this.storages.values());!(e=t()).done;){e.value.clear()}this.storages.clear()},e}();_e._logger=Y("ComponentStorage");var Se=function(){function e(){}return e.prototype.compare=function(e,t){var n=e.updateOrder-t.updateOrder;return 0==n&&(n=e.id-t.id),n},e}(),Ce=function(){function e(e,t){this.scene=null,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=pe.clone(pe.ZERO),this._componentCache=null,this.name=e,this.id=t}e.notifyQuerySystems=function(e){e.scene&&e.scene.querySystem&&(e.scene.querySystem.updateEntity(e),e.scene.clearSystemEntityCaches())};var t=e.prototype;return t._rebuildComponentCache=function(){var e,t=[];if(null!==(e=this.scene)&&void 0!==e&&e.componentStorageManager){for(var n=this._componentMask,i=ge.getRegisteredCount(),r=0;r<i;r++)if(pe.getBit(n,r)){var s=ge.getTypeByBitIndex(r);if(s){var o=this.scene.componentStorageManager.getComponent(this.id,s);o&&t.push(o)}}this._componentCache=t}else this._componentCache=t},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var s=i(e,n);return this.addComponent(s)},t.addComponentInternal=function(e){var t=e.constructor;ge.isRegistered(t)||ge.register(t);var n=ge.getBitMask(t);return pe.orInPlace(this._componentMask,n),this._componentCache=null,e},t.addComponent=function(t){var n,i=t.constructor;if(!this.scene)throw new Error("Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()");if(!this.scene.componentStorageManager)throw new Error("Scene does not have componentStorageManager");if(this.hasComponent(i))throw new Error("Entity "+this.name+" already has component "+U(i));(this.addComponentInternal(t),this.scene.componentStorageManager.addComponent(this.id,t),t.entityId=this.id,this.scene.referenceTracker&&this.scene.referenceTracker.registerEntityScene(this.id,this.scene),t.onAddedToEntity(),e.eventBus)&&e.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(n=this.tag)||void 0===n?void 0:n.toString(),componentType:U(i),component:t});return e.notifyQuerySystems(this),t},t.getComponent=function(e){var t;return this.hasComponent(e)&&null!==(t=this.scene)&&void 0!==t&&t.componentStorageManager?this.scene.componentStorageManager.getComponent(this.id,e):null},t.hasComponent=function(e){if(!ge.isRegistered(e))return!1;var t=ge.getBitMask(e);return pe.hasAny(this._componentMask,t)},t.getOrCreateComponent=function(e){var t=this.getComponent(e);if(!t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];t=this.createComponent.apply(this,[e].concat(i))}return t},t.removeComponent=function(t){var n,i,r=t.constructor;if(ge.isRegistered(r)){var s,o=ge.getBitIndex(r);if(pe.clearBit(this._componentMask,o),this._componentCache=null,null!==(n=this.scene)&&void 0!==n&&n.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,r),null!==(i=this.scene)&&void 0!==i&&i.referenceTracker&&this.scene.referenceTracker.clearComponentReferences(t),t.onRemovedFromEntity&&t.onRemovedFromEntity(),t.entityId=null,e.eventBus)e.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(s=this.tag)||void 0===s?void 0:s.toString(),componentType:U(r),component:t});e.notifyQuerySystems(this)}},t.removeComponentByType=function(e){var t=this.getComponent(e);return t?(this.removeComponent(t),t):null},t.removeAllComponents=function(){var t=[].concat(this.components);pe.clear(this._componentMask),this._componentCache=null;for(var n,i=o(t);!(n=i()).done;){var r,s=n.value,a=s.constructor;null!==(r=this.scene)&&void 0!==r&&r.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,a),s.onRemovedFromEntity()}e.notifyQuerySystems(this)},t.addComponents=function(t){for(var n,i=[],r=o(t);!(n=r()).done;){var s=n.value;try{i.push(this.addComponent(s))}catch(t){e._logger.warn("添加组件失败 "+H(s)+":",t)}}return i},t.removeComponentsByTypes=function(e){for(var t,n=[],i=o(e);!(t=i()).done;){var r=t.value;n.push(this.removeComponentByType(r))}return n},t.getComponents=function(e){for(var t,n=[],i=o(this.components);!(t=i()).done;){var r=t.value;r instanceof e&&n.push(r)}return n},t.addChild=function(e){if(e===this)throw new Error("Entity cannot be its own child");return e._parent===this||(e._parent&&e._parent.removeChild(e),e._parent=this,this._children.push(e),!e.scene&&this.scene&&(e.scene=this.scene,this.scene.addEntity(e))),e},t.removeChild=function(e){var t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e._parent=null,!0)},t.removeAllChildren=function(){for(var e,t=o([].concat(this._children));!(e=t()).done;){var n=e.value;this.removeChild(n)}},t.findChild=function(e,t){void 0===t&&(t=!1);for(var n,i=o(this._children);!(n=i()).done;){var r=n.value;if(r.name===e)return r}if(t)for(var s,a=o(this._children);!(s=a()).done;){var c=s.value.findChild(e,!0);if(c)return c}return null},t.findChildrenByTag=function(e,t){void 0===t&&(t=!1);for(var n,i=[],r=o(this._children);!(n=r()).done;){var s=n.value;s.tag===e&&i.push(s)}if(t)for(var a,c=o(this._children);!(a=c()).done;){var u=a.value;i.push.apply(i,u.findChildrenByTag(e,!0))}return i},t.getRoot=function(){for(var e=this;e._parent;)e=e._parent;return e},t.isAncestorOf=function(e){for(var t=e._parent;t;){if(t===this)return!0;t=t._parent}return!1},t.isDescendantOf=function(e){return e.isAncestorOf(this)},t.getDepth=function(){for(var e=0,t=this._parent;t;)e++,t=t._parent;return e},t.forEachChild=function(e,t){void 0===t&&(t=!1),this._children.forEach((function(n,i){e(n,i),t&&n.forEachChild(e,!0)}))},t.onActiveChanged=function(){for(var e,t=o(this.components);!(e=t()).done;){var n=e.value;"onActiveChanged"in n&&"function"==typeof n.onActiveChanged&&n.onActiveChanged()}this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})},t.destroy=function(){if(!this._isDestroyed){this._isDestroyed=!0,this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id));for(var e,t=o([].concat(this._children));!(e=t()).done;){e.value.destroy()}this._parent&&this._parent.removeChild(this),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this))}},t.destroyAllChildren=function(){if(0!==this._children.length){var e=this.scene,t=[],n=function(e){for(var i,r=o(e._children);!(i=r()).done;){var s=i.value;t.push(s),n(s)}};n(this);for(var i=0,r=t;i<r.length;i++){r[i]._isDestroyed=!0}for(var s=0,a=t;s<a.length;s++){a[s].removeAllComponents()}if(e){for(var c,u=o(t);!(c=u()).done;){var h=c.value;e.entities.remove(h),e.querySystem.removeEntity(h)}e.clearSystemEntityCaches()}this._children.length=0}},t.compareTo=function(e){return Se.prototype.compare(this,e)},t.toString=function(){return"Entity["+this.name+":"+this.id+"]"},t.getDebugInfo=function(){var e;return{name:this.name,id:this.id,enabled:this._enabled,active:this._active,activeInHierarchy:this.activeInHierarchy,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map((function(e){return H(e)})),componentMask:pe.toString(this._componentMask,2),parentId:(null===(e=this._parent)||void 0===e?void 0:e.id)||null,childCount:this._children.length,childIds:this._children.map((function(e){return e.id})),depth:this.getDepth(),cacheBuilt:null!==this._componentCache}},s(e,[{key:"isDestroyed",get:function(){return this._isDestroyed}},{key:"components",get:function(){return null===this._componentCache&&this._rebuildComponentCache(),this._componentCache}},{key:"parent",get:function(){return this._parent}},{key:"children",get:function(){return[].concat(this._children)}},{key:"childCount",get:function(){return this._children.length}},{key:"active",get:function(){return this._active},set:function(e){this._active!==e&&(this._active=e,this.onActiveChanged())}},{key:"activeInHierarchy",get:function(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}},{key:"tag",get:function(){return this._tag},set:function(e){this._tag=e}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this._updateOrder=e}},{key:"componentMask",get:function(){return this._componentMask}}])}();Ce._logger=Y("Entity"),Ce.entityComparer=new Se,Ce.eventBus=null;var we=function(){function e(e,t){this.scene=e,this.storageManager=t;var n=e.identifierPool.checkOut();this.entity=new Ce("",n),this.entity.scene=this.scene}var t=e.prototype;return t.named=function(e){return this.entity.name=e,this},t.tagged=function(e){return this.entity.tag=e,this},t.with=function(e){return this.entity.addComponent(e),this},t.withComponents=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i];this.entity.addComponent(s)}return this},t.withIf=function(e,t){return e&&this.entity.addComponent(t),this},t.withFactory=function(e){var t=e();return this.entity.addComponent(t),this},t.configure=function(e,t){var n=this.entity.getComponent(e);return n&&t(n),this},t.enabled=function(e){return void 0===e&&(e=!0),this.entity.enabled=e,this},t.active=function(e){return void 0===e&&(e=!0),this.entity.active=e,this},t.withChild=function(e){var t=e.build();return this.entity.addChild(t),this},t.withChildren=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i].build();this.entity.addChild(s)}return this},t.withChildFactory=function(e){var t=e(this.entity).build();return this.entity.addChild(t),this},t.withChildIf=function(e,t){if(e){var n=t.build();this.entity.addChild(n)}return this},t.build=function(){return this.entity},t.spawn=function(){return this.scene.addEntity(this.entity),this.entity},t.clone=function(){var t=new e(this.scene,this.storageManager);return t.entity=this.entity,t},e}(),Ee=function(){function e(e){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._scene=e}var t=e.prototype;return t.add=function(e){this.addImmediate(e)},t.addImmediate=function(e){this._idToEntity.has(e.id)||(this.buffer.push(e),this._idToEntity.set(e.id,e),this.updateNameIndex(e,!0))},t.remove=function(e){this.removeImmediate(e)},t.removeImmediate=function(e){var t=this.buffer.indexOf(e);-1!==t&&(this.buffer.splice(t,1),this._idToEntity.delete(e.id),this.updateNameIndex(e,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(e.id))},t.removeAllEntities=function(){for(var e=[],t=this.buffer.length-1;t>=0;t--)e.push(this.buffer[t].id),this.buffer[t].destroy();if(this._scene&&this._scene.identifierPool)for(var n,i=o(e);!(n=i()).done;){var r=n.value;this._scene.identifierPool.checkIn(r)}this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0},t.updateLists=function(){if(this._entitiesToAdd.length>0){for(var e,t=o(this._entitiesToAdd);!(e=t()).done;){var n=e.value;this.addImmediate(n)}this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(var i,r=o(this._entitiesToRemove);!(i=r()).done;){var s=i.value;this.removeImmediate(s)}this._entitiesToRemove.length=0}},t.update=function(){this.updateLists()},t.findEntity=function(e){var t=this._nameToEntities.get(e);return t&&t.length>0?t[0]:null},t.findEntitiesByName=function(e){return this._nameToEntities.get(e)||[]},t.findEntityById=function(e){return this._idToEntity.get(e)||null},t.findEntitiesByTag=function(e){for(var t,n=[],i=o(this.buffer);!(t=i()).done;){var r=t.value;r.tag===e&&n.push(r)}return n},t.findEntitiesWithComponent=function(e){for(var t,n=[],i=o(this.buffer);!(t=i()).done;){var r=t.value;r.hasComponent(e)&&n.push(r)}return n},t.forEach=function(e){for(var t,n=o(this.buffer);!(t=n()).done;){e(t.value)}},t.forEachWhere=function(e,t){for(var n,i=o(this.buffer);!(n=i()).done;){var r=n.value;e(r)&&t(r)}},t.updateNameIndex=function(e,t){if(e.name)if(t){var n=this._nameToEntities.get(e.name);n||(n=[],this._nameToEntities.set(e.name,n)),n.push(e)}else{var i=this._nameToEntities.get(e.name);if(i){var r=i.indexOf(e);-1!==r&&(i.splice(r,1),0===i.length&&this._nameToEntities.delete(e.name))}}},t.getStats=function(){for(var e,t=0,n=o(this.buffer);!(e=n()).done;){var i=e.value;i.enabled&&!i.isDestroyed&&t++}return{totalEntities:this.buffer.length,activeEntities:t,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}},s(e,[{key:"count",get:function(){return this.buffer.length}}])}(),be=function(){function e(e,t){void 0===e&&(e=100),void 0===t&&(t=1024),this._nextAvailableIndex=0,this._freeIndices=[],this._generations=new Map,this._pendingRecycle=[],this._recycleDelay=100,this._stats={totalAllocated:0,totalRecycled:0,currentActive:0,memoryExpansions:0},this._recycleDelay=e,this._expansionBlockSize=t,this._preAllocateGenerations(0,this._expansionBlockSize)}var t=e.prototype;return t.checkOut=function(){var t;if(this._processDelayedRecycle(),this._freeIndices.length>0)t=this._freeIndices.pop();else{if(this._nextAvailableIndex>e.MAX_INDEX)throw new Error("实体索引已达到框架设计限制 ("+e.MAX_INDEX+")。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。");t=this._nextAvailableIndex++,this._ensureGenerationCapacity(t)}var n=this._generations.get(t)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(t,n)},t.checkIn=function(e){var t=this._unpackIndex(e),n=this._unpackGeneration(e);return!!this._isValidId(t,n)&&(!this._pendingRecycle.some((function(e){return e.index===t&&e.generation===n}))&&(this._pendingRecycle.push({index:t,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0))},t.isValid=function(e){var t=this._unpackIndex(e),n=this._unpackGeneration(e);return this._isValidId(t,n)},t.getStats=function(){for(var t,n=0,i=0,r=o(this._generations);!(t=r()).done;){var s=t.value,a=s[0],c=s[1];a<this._nextAvailableIndex&&(n+=c,i++)}var u=i>0?n/i:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:e.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*u)/100,generationStorageSize:this._generations.size}},t.forceProcessDelayedRecycle=function(){this._processDelayedRecycle(!0)},t._processDelayedRecycle=function(t){if(void 0===t&&(t=!1),0!==this._pendingRecycle.length){for(var n,i=Date.now(),r=[],s=[],a=o(this._pendingRecycle);!(n=a()).done;){var c=n.value;t||i-c.timestamp>=this._recycleDelay?r.push(c):s.push(c)}for(var u=0,h=r;u<h.length;u++){var l=h[u];if(this._isValidId(l.index,l.generation)){var f=l.generation+1;f>e.MAX_GENERATION&&(f=1),this._generations.set(l.index,f),this._freeIndices.push(l.index)}}this._pendingRecycle=s}},t._preAllocateGenerations=function(t,n){for(var i=0;i<n;i++){var r=t+i;r<=e.MAX_INDEX&&this._generations.set(r,1)}this._stats.memoryExpansions++},t._ensureGenerationCapacity=function(e){if(!this._generations.has(e)){var t=Math.floor(e/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(t,this._expansionBlockSize)}},t._calculateMemoryUsage=function(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length},t._packId=function(e,t){return t<<16|e},t._unpackIndex=function(e){return 65535&e},t._unpackGeneration=function(e){return e>>>16&65535},t._isValidId=function(e,t){if(e<0||e>=this._nextAvailableIndex)return!1;var n=this._generations.get(e);return void 0!==n&&n===t},e}();be.MAX_INDEX=65535,be.MAX_GENERATION=65535;var Ae=function(){function e(){this.condition={all:[],any:[],none:[]}}e.all=function(){var t=new e;return t.all.apply(t,arguments)},e.any=function(){var t=new e;return t.any.apply(t,arguments)},e.none=function(){var t=new e;return t.none.apply(t,arguments)},e.byTag=function(t){return(new e).withTag(t)},e.byName=function(t){return(new e).withName(t)},e.byComponent=function(t){return(new e).withComponent(t)},e.complex=function(){return new e},e.empty=function(){return new e};var t=e.prototype;return t.all=function(){var e;return(e=this.condition.all).push.apply(e,arguments),this},t.any=function(){var e;return(e=this.condition.any).push.apply(e,arguments),this},t.none=function(){var e;return(e=this.condition.none).push.apply(e,arguments),this},t.exclude=function(){return this.none.apply(this,arguments)},t.one=function(){return this.any.apply(this,arguments)},t.withTag=function(e){return this.condition.tag=e,this},t.withName=function(e){return this.condition.name=e,this},t.withComponent=function(e){return this.condition.component=e,this},t.withoutTag=function(){return delete this.condition.tag,this},t.withoutName=function(){return delete this.condition.name,this},t.withoutComponent=function(){return delete this.condition.component,this},t.getCondition=function(){return{all:[].concat(this.condition.all),any:[].concat(this.condition.any),none:[].concat(this.condition.none),tag:this.condition.tag,name:this.condition.name,component:this.condition.component}},t.isEmpty=function(){return 0===this.condition.all.length&&0===this.condition.any.length&&0===this.condition.none.length&&void 0===this.condition.tag&&void 0===this.condition.name&&void 0===this.condition.component},t.reset=function(){return this.condition.all.length=0,this.condition.any.length=0,this.condition.none.length=0,delete this.condition.tag,delete this.condition.name,delete this.condition.component,this},t.clone=function(){var t,n,i,r=new e;return(t=r.condition.all).push.apply(t,this.condition.all),(n=r.condition.any).push.apply(n,this.condition.any),(i=r.condition.none).push.apply(i,this.condition.none),void 0!==this.condition.tag&&(r.condition.tag=this.condition.tag),void 0!==this.condition.name&&(r.condition.name=this.condition.name),void 0!==this.condition.component&&(r.condition.component=this.condition.component),r},t.toString=function(){var e=[];return this.condition.all.length>0&&e.push("all("+this.condition.all.map((function(e){return U(e)})).join(", ")+")"),this.condition.any.length>0&&e.push("any("+this.condition.any.map((function(e){return U(e)})).join(", ")+")"),this.condition.none.length>0&&e.push("none("+this.condition.none.map((function(e){return U(e)})).join(", ")+")"),void 0!==this.condition.tag&&e.push("tag("+this.condition.tag+")"),void 0!==this.condition.name&&e.push("name("+this.condition.name+")"),void 0!==this.condition.component&&e.push("component("+U(this.condition.component)+")"),"Matcher["+e.join(" & ")+"]"},e}(),Te=function(){function e(e){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=j(this),this._initialized=!1,this._matcher=e||Ae.empty(),this._eventListeners=[],this._scene=null,this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.logger=Y(this.getLoggerName()),this._entityCache={frame:null,persistent:null,tracked:new Set,invalidate:function(){this.persistent=null},clearFrame:function(){this.frame=null},clearAll:function(){this.frame=null,this.persistent=null,this.tracked.clear()}}}var t=e.prototype;return t.setPerformanceMonitor=function(e){this._performanceMonitor=e},t.getPerformanceMonitor=function(){if(!this._performanceMonitor)throw new Error(this._systemName+": PerformanceMonitor未注入,请确保在Core.create()之后再添加System到Scene");return this._performanceMonitor},t.setUpdateOrder=function(e){this._updateOrder=e},t.initialize=function(){this._initialized||(this._initialized=!0,this.scene&&(this._entityCache.invalidate(),this.queryEntities()),this.onInitialize())},t.onInitialize=function(){},t.clearEntityCache=function(){this._entityCache.invalidate()},t.reset=function(){this.scene=null,this._initialized=!1,this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.destroy()},t.queryEntities=function(){var e;if(null===(e=this.scene)||void 0===e||!e.querySystem||!this._matcher)return[];var t=this._matcher.getCondition(),n=this.scene.querySystem,i=[];return i=this._matcher.isEmpty()?n.getAllEntities():this.isSingleCondition(t)?this.executeSingleConditionQuery(t,n):this.executeComplexQuery(t,n),this.updateEntityTracking(i),i},t.isSingleCondition=function(e){var t=(e.all.length>0?1:0)|(e.any.length>0?2:0)|(e.none.length>0?4:0)|(void 0!==e.tag?8:0)|(void 0!==e.name?16:0)|(void 0!==e.component?32:0);return 0!==t&&!(t&t-1)},t.executeSingleConditionQuery=function(e,t){return void 0!==e.tag?t.queryByTag(e.tag).entities:void 0!==e.name?t.queryByName(e.name).entities:void 0!==e.component?t.queryByComponent(e.component).entities:e.all.length>0&&0===e.any.length&&0===e.none.length?t.queryAll.apply(t,e.all).entities:0===e.all.length&&e.any.length>0&&0===e.none.length?t.queryAny.apply(t,e.any).entities:0===e.all.length&&0===e.any.length&&e.none.length>0?t.queryNone.apply(t,e.none).entities:[]},t.executeComplexQueryWithIdSets=function(e,t){var n=null;if(void 0!==e.tag){var i=t.queryByTag(e.tag);n=this.extractEntityIds(i.entities)}if(void 0!==e.name){var r=this.extractEntityIds(t.queryByName(e.name).entities);n=n?this.intersectIdSets(n,r):r}if(void 0!==e.component){var s=this.extractEntityIds(t.queryByComponent(e.component).entities);n=n?this.intersectIdSets(n,s):s}if(e.all.length>0){var o=this.extractEntityIds(t.queryAll.apply(t,e.all).entities);n=n?this.intersectIdSets(n,o):o}if(e.any.length>0){var a=this.extractEntityIds(t.queryAny.apply(t,e.any).entities);n=n?this.intersectIdSets(n,a):a}if(e.none.length>0){n||(n=this.extractEntityIds(t.getAllEntities()));var c=t.queryAny.apply(t,e.none),u=this.extractEntityIds(c.entities);n=this.differenceIdSets(n,u)}return n?this.idSetToEntityArray(n,t.getAllEntities()):[]},t.extractEntityIds=function(e){for(var t=e.length,n=new Set,i=0;i<t;i=i+1|0)n.add(0|e[i].id);return n},t.intersectIdSets=function(e,t){var n,i;e.size<=t.size?(n=e,i=t):(n=t,i=e);for(var r,s=new Set,a=o(n);!(r=a()).done;){var c=r.value;i.has(c)&&s.add(c)}return s},t.differenceIdSets=function(e,t){for(var n,i=new Set,r=o(e);!(n=r()).done;){var s=n.value;t.has(s)||i.add(s)}return i},t.getEntityIdMap=function(e){var t,n,i=null!==(t=null===(n=this.scene)||void 0===n||null===(n=n.querySystem)||void 0===n?void 0:n.version)&&void 0!==t?t:0;return null!==this._entityIdMap&&this._entityIdMapVersion===i?this._entityIdMap:this.rebuildEntityIdMap(e,i)},t.rebuildEntityIdMap=function(e,t){var n=this._entityIdMap;n?n.clear():n=new Map;for(var i=e.length,r=0;r<i;r=r+1|0){var s=e[r];n.set(0|s.id,s)}return this._entityIdMap=n,this._entityIdMapVersion=t,this._entityIdMapSize=i,n},t.idSetToEntityArray=function(e,t){for(var n,i=this.getEntityIdMap(t),r=e.size,s=new Array(r),a=0,c=o(e);!(n=c()).done;){var u=n.value,h=i.get(u);void 0!==h&&(s[a]=h,a=a+1|0)}return a<r&&(s.length=a),s},t.executeComplexQuery=function(e,t){return this.executeComplexQueryWithIdSets(e,t)},t.update=function(){if(this._enabled&&this.onCheckProcessing()){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName),n=0;try{this.onBegin(),this._entityCache.frame=this.queryEntities(),n=this._entityCache.frame.length,this.process(this._entityCache.frame)}finally{e.endMonitoring(this._systemName,t,n)}}},t.lateUpdate=function(){if(this._enabled&&this.onCheckProcessing()){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName+"_Late"),n=0;try{var i=this._entityCache.frame||[];n=i.length,this.lateProcess(i),this.onEnd()}finally{e.endMonitoring(this._systemName+"_Late",t,n),this._entityCache.clearFrame()}}},t.onBegin=function(){},t.process=function(e){},t.lateProcess=function(e){},t.onEnd=function(){},t.onCheckProcessing=function(){return!0},t.getPerformanceData=function(){return this.getPerformanceMonitor().getSystemData(this._systemName)},t.getPerformanceStats=function(){return this.getPerformanceMonitor().getSystemStats(this._systemName)},t.resetPerformanceData=function(){this.getPerformanceMonitor().resetSystem(this._systemName)},t.toString=function(){var e=this.entities.length,t=this.getPerformanceData(),n=t?" ("+t.executionTime.toFixed(2)+"ms)":"";return this._systemName+"["+e+" entities]"+n},t.updateEntityTracking=function(e){for(var t,n=new Set(e),i=!1,r=o(e);!(t=r()).done;){var s=t.value;this._entityCache.tracked.has(s)||(this._entityCache.tracked.add(s),this.onAdded(s),i=!0)}for(var a,c=o(this._entityCache.tracked);!(a=c()).done;){var u=a.value;n.has(u)||(this._entityCache.tracked.delete(u),this.onRemoved(u),i=!0)}i&&this._entityCache.invalidate()},t.onAdded=function(e){},t.onRemoved=function(e){},t.dispose=function(){this.cleanupManualEventListeners(),this._entityCache.clearAll(),this._entityIdMap=null,this._initialized=!1,this._scene=null,this.logger.debug("System "+this._systemName+" disposed")},t.addEventListener=function(e,t,n){var i;if(null!==(i=this.scene)&&void 0!==i&&i.eventSystem){var r=this.scene.eventSystem.on(e,t,n);r&&this._eventListeners.push({eventSystem:this.scene.eventSystem,eventType:e,handler:t,listenerRef:r})}else this.logger.warn(this.systemName+": 无法添加事件监听器,scene.eventSystem 不可用")},t.removeEventListener=function(e,t){var n=this._eventListeners.findIndex((function(n){return n.eventType===e&&n.handler===t}));if(n>=0){var i=this._eventListeners[n];i.eventSystem.off(e,i.listenerRef),this._eventListeners.splice(n,1)}},t.cleanupManualEventListeners=function(){for(var e,t=o(this._eventListeners);!(e=t()).done;){var n=e.value;try{n.eventSystem.off(n.eventType,n.listenerRef)}catch(e){this.logger.warn(this.systemName+': 移除事件监听器失败 "'+n.eventType+'"',e)}}this._eventListeners.length=0},t.destroy=function(){this.cleanupManualEventListeners(),this.onDestroy()},t.getLoggerName=function(){return"EntitySystem"},t.onDestroy=function(){},t.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" in "+this.systemName);return n},t.getComponents=function(e){for(var t=this,n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i.map((function(n){return t.requireComponent(e,n)}))},t.forEach=function(e,t){for(var n=0;n<e.length;n++)t(e[n],n)},t.filterEntities=function(e,t){return Array.from(e).filter(t)},t.mapEntities=function(e,t){return Array.from(e).map(t)},t.findEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return e[n]},t.someEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1},t.everyEntity=function(e,t){for(var n=0;n<e.length;n++)if(!t(e[n],n))return!1;return!0},s(e,[{key:"entities",get:function(){return null!==this._entityCache.frame?this._entityCache.frame:(null===this._entityCache.persistent&&(this._entityCache.persistent=this.queryEntities()),this._entityCache.persistent)}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this.setUpdateOrder(e)}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"systemName",get:function(){return this._systemName}},{key:"scene",get:function(){return this._scene},set:function(e){this._scene=e}},{key:"matcher",get:function(){return this._matcher}}])}(),Me=function(){function e(){this._processors=[],this._isDirty=!1}var t=e.prototype;return t.setDirty=function(){this._isDirty=!0},t.add=function(e){this._processors.push(e),this.setDirty()},t.remove=function(e){var t=this._processors.indexOf(e);-1!==t&&this._processors.splice(t,1)},t.getProcessor=function(e){for(var t,n=o(this._processors);!(t=n()).done;){var i=t.value;if(i instanceof e)return i}return null},t.begin=function(){this.sortProcessors()},t.end=function(){for(var t,n=o(this._processors);!(t=n()).done;){var i=t.value;try{i.reset()}catch(t){e._logger.error("Error in processor "+j(i)+":",t)}}this._isDirty=!1,this._processors.length=0},t.update=function(){this.sortProcessors();for(var t,n=o(this._processors);!(t=n()).done;){var i=t.value;try{i.update()}catch(t){e._logger.error("Error in processor "+j(i)+":",t)}}},t.lateUpdate=function(){for(var e,t=o(this._processors);!(e=t()).done;){e.value.lateUpdate()}},t.sortProcessors=function(){this._isDirty&&(this._processors.sort((function(e,t){return e.updateOrder-t.updateOrder})),this._isDirty=!1)},s(e,[{key:"processors",get:function(){return this._processors}},{key:"count",get:function(){return this._processors.length}}])}();Me._logger=Y("EntityProcessorList");var xe=function(){function e(e){if(e&&"object"==typeof e)this._value=pe.clone(e);else if("number"==typeof e)this._value=pe.fromNumber(e);else if("string"==typeof e){var t=parseInt(e,10);this._value=pe.fromNumber(t)}else this._value=pe.clone(pe.ZERO)}var t=e.prototype;return t.set=function(e){if(e<0)throw new Error("Bit index cannot be negative");pe.setBit(this._value,e)},t.clear=function(e){if(e<0)throw new Error("Bit index cannot be negative");pe.clearBit(this._value,e)},t.get=function(e){return pe.getBit(this._value,e)},t.containsAll=function(e){return pe.hasAll(this._value,e._value)},t.intersects=function(e){return pe.hasAny(this._value,e._value)},t.excludes=function(e){return pe.hasNone(this._value,e._value)},t.clearAll=function(){pe.clear(this._value)},t.isEmpty=function(){return pe.isZero(this._value)},t.cardinality=function(){return pe.popCount(this._value)},t.and=function(t){var n=new e;return pe.copy(this._value,n._value),pe.andInPlace(n._value,t._value),n},t.or=function(t){var n=new e;return pe.copy(this._value,n._value),pe.orInPlace(n._value,t._value),n},t.xor=function(t){var n=new e;return pe.copy(this._value,n._value),pe.xorInPlace(n._value,t._value),n},t.not=function(t){void 0===t&&(t=64),t>64&&(t=64);var n=new e;if(pe.copy(this._value,n._value),t<=32){var i=(1<<t)-1;n._value.base[le.LOW]=~n._value.base[le.LOW]&i,n._value.base[le.HIGH]=0}else if(n._value.base[le.LOW]=~n._value.base[le.LOW],t<64){var r=(1<<t-32)-1;n._value.base[le.HIGH]=~n._value.base[le.HIGH]&r}else n._value.base[le.HIGH]=~n._value.base[le.HIGH];return n},t.copyFrom=function(e){pe.copy(e._value,this._value)},t.clone=function(){return new e(this._value)},t.getValue=function(){return this._value},t.setValue=function(e){if("object"==typeof e)pe.copy(e,this._value);else if("number"==typeof e)this._value=pe.fromNumber(e);else{var t=parseInt(e,10);this._value=pe.fromNumber(t)}},t.toString=function(){for(var e=[],t=0;t<64;t++)this.get(t)&&e.push(t.toString());return"Bits["+e.join(", ")+"]"},t.toBinaryString=function(e){void 0===e&&(e=0),0==e&&(e=64+(this._value.segments?64*this._value.segments.length:0));for(var t="",n=e-1;n>=0;n--)t+=this.get(n)?"1":"0",n%8==0&&n>0&&(t+=" ");return t},t.toHexString=function(){return pe.toString(this._value,16)},e.fromBinaryString=function(t){var n=t.replace(/\s/g,""),i={base:void 0,segments:void 0};if(n.length<=32){var r=parseInt(n,2);i.base=[r>>>0,0]}else{var s=n.substring(n.length-32),o=n.substring(0,n.length-32),a=parseInt(s,2),c=parseInt(o,2);i.base=[a>>>0,c>>>0]}return new e(i)},e.fromHexString=function(t){var n=t.replace(/^0x/i,""),i={base:void 0,segments:void 0};if(n.length<=8){var r=parseInt(n,16);i.base=[r>>>0,0]}else{var s=n.substring(n.length-8),o=n.substring(0,n.length-8),a=parseInt(s,16),c=parseInt(o,16);i.base=[a>>>0,c>>>0]}return new e(i)},t.equals=function(e){return pe.equals(this._value,e._value)},t.getHighestBitIndex=function(){if(pe.isZero(this._value))return-1;if(0!==this._value.base[le.HIGH])for(var e=31;e>=0;e--)if(this._value.base[le.HIGH]&1<<e)return e+32;for(var t=31;t>=0;t--)if(this._value.base[le.LOW]&1<<t)return t;return-1},t.getLowestBitIndex=function(){if(pe.isZero(this._value))return-1;for(var e=0;e<32;e++)if(this._value.base[le.LOW]&1<<e)return e;for(var t=0;t<32;t++)if(this._value.base[le.HIGH]&1<<t)return t+32;return-1},e}(),Ie=function(){function e(){this._dense=[],this._sparse=new Map}var t=e.prototype;return t.add=function(e){if(this._sparse.has(e))return!1;var t=this._dense.length;return this._dense.push(e),this._sparse.set(e,t),!0},t.remove=function(e){var t=this._sparse.get(e);if(void 0===t)return!1;var n=this._dense.length-1;if(t!==n){var i=this._dense[n];this._dense[t]=i,this._sparse.set(i,t)}return this._dense.pop(),this._sparse.delete(e),!0},t.has=function(e){return this._sparse.has(e)},t.getIndex=function(e){return this._sparse.get(e)},t.getByIndex=function(e){return this._dense[e]},t.forEach=function(e){for(var t=0;t<this._dense.length;t++)e(this._dense[t],t)},t.map=function(e){for(var t=[],n=0;n<this._dense.length;n++)t.push(e(this._dense[n],n));return t},t.filter=function(e){for(var t=[],n=0;n<this._dense.length;n++)e(this._dense[n],n)&&t.push(this._dense[n]);return t},t.find=function(e){for(var t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return this._dense[t]},t.some=function(e){for(var t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return!0;return!1},t.every=function(e){for(var t=0;t<this._dense.length;t++)if(!e(this._dense[t],t))return!1;return!0},t.getDenseArray=function(){return[].concat(this._dense)},t.getDenseArrayUnsafe=function(){return this._dense},t.clear=function(){this._dense.length=0,this._sparse.clear()},t.toArray=function(){return[].concat(this._dense)},t.toSet=function(){return new Set(this._dense)},t.getMemoryStats=function(){var e=8*this._dense.length,t=16*this._sparse.size;return{denseArraySize:e,sparseMapSize:t,totalMemory:e+t}},t.validate=function(){if(this._dense.length!==this._sparse.size)return!1;for(var e=0;e<this._dense.length;e++){var t=this._dense[e];if(this._sparse.get(t)!==e)return!1}for(var n,i=o(this._sparse);!(n=i()).done;){var r=n.value,s=r[0],a=r[1];if(a>=this._dense.length||this._dense[a]!==s)return!1}return!0},s(e,[{key:"size",get:function(){return this._dense.length}},{key:"isEmpty",get:function(){return 0===this._dense.length}}])}(),ke=function(e){function t(){return e.call(this)||this}return u(t,e),t.prototype.reset=function(){this.clear()},t}(y(Set)),De=function(){function e(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new Ie}var t=e.prototype;return t.addEntity=function(e){this._entities.has(e)&&this.removeEntity(e);for(var t,n=pe.clone(pe.ZERO),i=new Set,r=o(e.components);!(t=r()).done;){var s=t.value.constructor;i.add(s),ge.isRegistered(s)||ge.register(s);var a=ge.getBitMask(s);pe.orInPlace(n,a)}this._entities.add(e);for(var c=this._entities.getIndex(e);this._componentMasks.length<=c;)this._componentMasks.push(pe.clone(pe.ZERO));this._componentMasks[c]=n,this.updateComponentMappings(e,i,!0)},t.removeEntity=function(e){var t=this._entities.getIndex(e);if(void 0!==t){var n=this.getEntityComponentTypes(e);this.updateComponentMappings(e,n,!1),this._entities.remove(e);var i=this._componentMasks.length-1;t!==i&&(this._componentMasks[t]=this._componentMasks[i]),this._componentMasks.pop()}},t.queryByComponent=function(e){var t=this._componentToEntities.get(e);return t?new Set(t):new Set},t.queryMultipleAnd=function(t){var n=this;if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);for(var i,r=pe.clone(pe.ZERO),s=o(t);!(i=s()).done;){var a=i.value;if(!ge.isRegistered(a))return new Set;var c=ge.getBitMask(a);pe.orInPlace(r,c)}var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var i=n._componentMasks[t];pe.hasAll(i,r)&&u.add(e)})),u},t.queryMultipleOr=function(t){var n=this;if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);for(var i,r=pe.clone(pe.ZERO),s=o(t);!(i=s()).done;){var a=i.value;if(ge.isRegistered(a)){var c=ge.getBitMask(a);pe.orInPlace(r,c)}}if(pe.equals(r,pe.ZERO))return new Set;var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var i=n._componentMasks[t];pe.hasAny(i,r)&&u.add(e)})),u},t.hasComponent=function(e,t){var n=this._entities.getIndex(e);if(void 0===n)return!1;if(!ge.isRegistered(t))return!1;var i=this._componentMasks[n],r=ge.getBitMask(t);return pe.hasAny(i,r)},t.getEntityMask=function(e){var t=this._entities.getIndex(e);if(void 0!==t)return this._componentMasks[t]},t.getAllEntities=function(){return this._entities.toArray()},t.forEach=function(e){var t=this;this._entities.forEach((function(n,i){e(n,t._componentMasks[i],i)}))},t.clear=function(){this._entities.clear(),this._componentMasks.length=0;for(var t,n=o(this._componentToEntities.values());!(t=n()).done;){var i=t.value;e._entitySetPool.release(i)}this._componentToEntities.clear()},t.getMemoryStats=function(){for(var e,t=this._entities.getMemoryStats(),n=16*this._componentMasks.length,i=16*this._componentToEntities.size,r=o(this._componentToEntities.values());!(e=r()).done;){i+=8*e.value.size}return{entitiesMemory:t.totalMemory,masksMemory:n,mappingsMemory:i,totalMemory:t.totalMemory+n+i}},t.validate=function(){if(!this._entities.validate())return!1;if(this._componentMasks.length!==this._entities.size)return!1;for(var e,t=new Set,n=o(this._componentToEntities.values());!(e=n()).done;)for(var i,r=o(e.value);!(i=r()).done;){var s=i.value;t.add(s)}for(var a,c=o(t);!(a=c()).done;){var u=a.value;if(!this._entities.has(u))return!1}return!0},t.getEntityComponentTypes=function(e){for(var t,n=new Set,i=o(e.components);!(t=i()).done;){var r=t.value;n.add(r.constructor)}return n},t.updateComponentMappings=function(t,n,i){for(var r,s=o(n);!(r=s()).done;){var a=r.value,c=this._componentToEntities.get(a);i?(c||(c=e._entitySetPool.obtain(),this._componentToEntities.set(a,c)),c.add(t)):c&&(c.delete(t),0===c.size&&(this._componentToEntities.delete(a),e._entitySetPool.release(c)))}},s(e,[{key:"size",get:function(){return this._entities.size}},{key:"isEmpty",get:function(){return this._entities.isEmpty}}])}();De._entitySetPool=z.getPool(ke,50,512);var Re,Oe=function(){function e(){this.buckets=new Map,this._size=0}var t=e.prototype;return t.murmur32=function(e,t){var n=t>>>0,i=function(e){e=(e=Math.imul(e,3432918353)>>>0)<<15|e>>>17,e=Math.imul(e,461845907)>>>0,n=(n^=e)<<13|n>>>19,n=Math.imul(n,5)+3864292196>>>0};if(i(e.base[0]>>>0),i(e.base[1]>>>0),e.segments)for(var r,s=o(e.segments);!(r=s()).done;){var a=r.value;i(a[0]>>>0),i(a[1]>>>0)}return n^=e.segments?8*e.segments.length:8,n^=n>>>16,n=Math.imul(n,2246822507)>>>0,n^=n>>>13,n=Math.imul(n,3266489909)>>>0,(n^=n>>>16)>>>0},t.getHashes=function(e){return[this.murmur32(e,2538058380),this.murmur32(e,305419896)]},t.set=function(e,t){var n=this.getHashes(e),i=n[0],r=n[1],s=this.buckets.get(i);s||(s=[],this.buckets.set(i,s));for(var o=0;o<s.length;o++)if(s[o][0]===r)return s[o][1]=t,this;return s.push([r,t]),this._size++,this},t.get=function(e){var t=this.getHashes(e),n=t[0],i=t[1],r=this.buckets.get(n);if(r)for(var s=0;s<r.length;s++)if(r[s][0]===i)return r[s][1]},t.has=function(e){return void 0!==this.get(e)},t.delete=function(e){var t=this.getHashes(e),n=t[0],i=t[1],r=this.buckets.get(n);if(!r)return!1;for(var s=0;s<r.length;s++)if(r[s][0]===i)return r.splice(s,1),this._size--,0===r.length&&this.buckets.delete(n),!0;return!1},t.clear=function(){this.buckets.clear(),this._size=0},t.entries=l().m((function e(){var t,n,i,r,s,a,c,u;return l().w((function(e){for(;;)switch(e.n){case 0:t=o(this.buckets);case 1:if((n=t()).done){e.n=5;break}(i=n.value)[0],r=i[1],s=o(r);case 2:if((a=s()).done){e.n=4;break}return(c=a.value)[0],u=c[1],e.n=3,[void 0,u];case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}}),e,this)})),t.values=l().m((function e(){var t,n,i,r,s,a,c;return l().w((function(e){for(;;)switch(e.n){case 0:t=o(this.buckets.values());case 1:if((n=t()).done){e.n=5;break}i=n.value,r=o(i);case 2:if((s=r()).done){e.n=4;break}return(a=s.value)[0],c=a[1],e.n=3,c;case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}}),e,this)})),s(e,[{key:"size",get:function(){return this._size}},{key:"innerBuckets",get:function(){return this.buckets}}])}(),ze=function(){function e(){this._archetypes=new Oe,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._entityComponentTypesCache=new Map,this._allArchetypes=[]}var t=e.prototype;return t.addEntity=function(e){var t=this.getEntityComponentTypes(e),n=this.generateArchetypeId(t),i=this._archetypes.get(n);i||(i=this.createArchetype(t)),i.entities.add(e),this._entityToArchetype.set(e,i)},t.removeEntity=function(e){var t=this._entityToArchetype.get(e);t&&(t.entities.delete(e),this._entityComponentTypesCache.delete(e),this._entityToArchetype.delete(e))},t.updateEntity=function(e){var t=this._entityToArchetype.get(e);this._entityComponentTypesCache.delete(e);var n=this.getEntityComponentTypes(e),i=this.generateArchetypeId(n);if(!t||t.id!==i){t&&t.entities.delete(e);var r=this._archetypes.get(i);r||(r=this.createArchetype(n)),r.entities.add(e),this._entityToArchetype.set(e,r)}},t.queryArchetypes=function(e,t){void 0===t&&(t="AND");var n=[],i=0;if("AND"===t){if(0===e.length){for(var r,s=o(this._allArchetypes);!(r=s()).done;){var a=r.value;n.push(a),i+=a.entities.size}return{archetypes:n,totalEntities:i}}if(1===e.length){var c=this._componentToArchetypes.get(e[0]);if(c)for(var u,h=o(c);!(u=h()).done;){var l=u.value;n.push(l),i+=l.entities.size}return{archetypes:n,totalEntities:i}}for(var f,d,p=1/0,y=o(e);!(d=y()).done;){var m=d.value,g=this._componentToArchetypes.get(m);if(!g||0===g.size)return{archetypes:[],totalEntities:0};g.size<p&&(p=g.size,f=g)}var v=this.generateArchetypeId(e);if(f)for(var _,S=o(f);!(_=S()).done;){var C=_.value;pe.hasAll(C.id,v)&&(n.push(C),i+=C.entities.size)}}else{for(var w,E=new Set,b=o(e);!(w=b()).done;){var A=w.value,T=this._componentToArchetypes.get(A);if(T)for(var M,x=o(T);!(M=x()).done;){var I=M.value;E.add(I)}}for(var k,D=o(E);!(k=D()).done;){var R=k.value;n.push(R),i+=R.entities.size}}return{archetypes:n,totalEntities:i}},t.getEntityArchetype=function(e){return this._entityToArchetype.get(e)},t.getAllArchetypes=function(){return this._allArchetypes.slice()},t.getEntitiesByComponent=function(e){var t=this._componentToArchetypes.get(e);if(!t||0===t.size)return[];for(var n,i=[],r=o(t);!(n=r()).done;)for(var s,a=o(n.value.entities);!(s=a()).done;){var c=s.value;i.push(c)}return i},t.clear=function(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._entityComponentTypesCache.clear(),this._allArchetypes=[]},t.updateAllArchetypeArrays=function(){this._allArchetypes=[];for(var e,t=o(this._archetypes.values());!(e=t()).done;){var n=e.value;this._allArchetypes.push(n)}},t.getEntityComponentTypes=function(e){var t=this._entityComponentTypesCache.get(e);return t||(t=e.components.map((function(e){return e.constructor})),this._entityComponentTypesCache.set(e,t)),t},t.generateArchetypeId=function(e){for(var t,n=pe.clone(pe.ZERO),i=o(e);!(t=i()).done;){var r=t.value;ge.isRegistered(r)||ge.register(r);var s=ge.getBitMask(r);pe.orInPlace(n,s)}return n},t.createArchetype=function(e){var t=this.generateArchetypeId(e),n={id:t,componentTypes:[].concat(e),entities:new Set};this._archetypes.set(t,n),this.updateAllArchetypeArrays();for(var i,r=o(e);!(i=r()).done;){var s=i.value,a=this._componentToArchetypes.get(s);a||(a=new Set,this._componentToArchetypes.set(s,a)),a.add(n)}return n},e}();!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(Re||(Re={}));var Be,Pe=Y("ReactiveQuery");exports.ReactiveQueryChangeType=void 0,(Be=exports.ReactiveQueryChangeType||(exports.ReactiveQueryChangeType={})).ADDED="added",Be.REMOVED="removed",Be.BATCH_UPDATE="batch_update";var Le,Ne,We=function(){function e(e,t){var n,i,r;void 0===t&&(t={}),this._entities=[],this._entityIdSet=new Set,this._listeners=[],this._active=!0,this._condition=e,this._config={enableBatchMode:null===(n=t.enableBatchMode)||void 0===n||n,batchDelay:null!==(i=t.batchDelay)&&void 0!==i?i:16,debug:null!==(r=t.debug)&&void 0!==r&&r},this._id=this.generateQueryId(),this._batchChanges={added:[],removed:[],timer:null},this._config.debug&&Pe.debug("创建ReactiveQuery: "+this._id)}var t=e.prototype;return t.generateQueryId=function(){return this._condition.type+":"+this._condition.componentTypes.map((function(e){return e.name})).sort().join(",")},t.subscribe=function(e){var t=this;if(!this._active)throw new Error("Cannot subscribe to disposed ReactiveQuery "+this._id);if("function"!=typeof e)throw new TypeError("Listener must be a function");return this._listeners.push(e),this._config.debug&&Pe.debug("订阅ReactiveQuery: "+this._id+", 监听器数量: "+this._listeners.length),function(){var n=t._listeners.indexOf(e);-1!==n&&t._listeners.splice(n,1)}},t.unsubscribeAll=function(){this._listeners.length=0},t.getEntities=function(){return this._entities},t.matches=function(e){var t=e.componentMask;switch(this._condition.type){case Re.ALL:return pe.hasAll(t,this._condition.mask);case Re.ANY:return pe.hasAny(t,this._condition.mask);case Re.NONE:return pe.hasNone(t,this._condition.mask);default:return!1}},t.notifyEntityAdded=function(e){this._active&&this.matches(e)&&(this._entityIdSet.has(e.id)||(this._entities.push(e),this._entityIdSet.add(e.id),this._config.enableBatchMode?this.addToBatch("added",e):this.notifyListeners({type:exports.ReactiveQueryChangeType.ADDED,entity:e}),this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 实体添加 "+e.name+"("+e.id+")")))},t.notifyEntityRemoved=function(e){if(this._active&&this._entityIdSet.has(e.id)){var t=this._entities.indexOf(e);-1!==t&&this._entities.splice(t,1),this._entityIdSet.delete(e.id),this._config.enableBatchMode?this.addToBatch("removed",e):this.notifyListeners({type:exports.ReactiveQueryChangeType.REMOVED,entity:e}),this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 实体移除 "+e.name+"("+e.id+")")}},t.notifyEntityChanged=function(e){if(this._active){var t=this._entityIdSet.has(e.id),n=this.matches(e);t&&!n?this.notifyEntityRemoved(e):!t&&n&&this.notifyEntityAdded(e)}},t.initializeWith=function(e){this._entities.length=0,this._entityIdSet.clear();for(var t,n=o(e);!(t=n()).done;){var i=t.value;this.matches(i)&&(this._entities.push(i),this._entityIdSet.add(i.id))}this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 初始化 "+this._entities.length+" 个实体")},t.addToBatch=function(e,t){var n=this;"added"===e?this._batchChanges.added.push(t):this._batchChanges.removed.push(t),null===this._batchChanges.timer&&(this._batchChanges.timer=setTimeout((function(){n.flushBatchChanges()}),this._config.batchDelay))},t.flushBatchChanges=function(){if(0!==this._batchChanges.added.length||0!==this._batchChanges.removed.length){var e=[].concat(this._batchChanges.added),t=[].concat(this._batchChanges.removed);this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._batchChanges.timer=null,this.notifyListeners({type:exports.ReactiveQueryChangeType.BATCH_UPDATE,added:e,removed:t,entities:this._entities}),this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 批量更新 +"+e.length+" -"+t.length)}else this._batchChanges.timer=null},t.notifyListeners=function(e){for(var t,n=o([].concat(this._listeners));!(t=n()).done;){var i=t.value;try{i(e)}catch(e){Pe.error("ReactiveQuery "+this._id+": 监听器执行出错",e)}}},t.pause=function(){this._active=!1,null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0},t.resume=function(){this._active=!0},t.dispose=function(){null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._active=!1,this.unsubscribeAll(),this._entities.length=0,this._entityIdSet.clear(),this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 已销毁")},s(e,[{key:"count",get:function(){return this._entities.length}},{key:"condition",get:function(){return this._condition}},{key:"id",get:function(){return this._id}},{key:"active",get:function(){return this._active}},{key:"listenerCount",get:function(){return this._listeners.length}}])}(),Ue=function(){function e(){this._logger=Y("QuerySystem"),this.entities=[],this._version=0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.componentMaskCache=new Map,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.resultArrayPool=[],this.poolMaxSize=50,this._reactiveQueries=new Map,this._reactiveQueriesByComponent=new Map,this.entityIndex={byTag:new Map,byName:new Map},this.archetypeSystem=new ze}var t=e.prototype;return t.acquireResultArray=function(){return this.resultArrayPool.length>0?this.resultArrayPool.pop():[]},t.releaseResultArray=function(e){this.resultArrayPool.length<this.poolMaxSize&&(e.length=0,this.resultArrayPool.push(e))},t.setEntities=function(e){this.entities=e,this.clearQueryCache(),this.clearReactiveQueries(),this.rebuildIndexes()},t.addEntity=function(e,t){void 0===t&&(t=!1),this.entities.includes(e)||(this.entities.push(e),this.addEntityToIndexes(e),this.archetypeSystem.addEntity(e),this.notifyReactiveQueriesEntityAdded(e),t||this.clearQueryCache(),this._version++)},t.addEntities=function(e){if(0!==e.length){for(var t,n=new Set(this.entities.map((function(e){return e.id}))),i=0,r=o(e);!(t=r()).done;){var s=t.value;n.has(s.id)||(this.entities.push(s),this.addEntityToIndexes(s),this.archetypeSystem.addEntity(s),n.add(s.id),i++)}i>0&&this.clearQueryCache()}},t.addEntitiesUnchecked=function(e){if(0!==e.length){for(var t,n=o(e);!(t=n()).done;){var i=t.value;this.entities.push(i)}for(var r,s=o(e);!(r=s()).done;){var a=r.value;this.addEntityToIndexes(a),this.archetypeSystem.addEntity(a)}this.clearQueryCache()}},t.removeEntity=function(e){var t=this.entities.indexOf(e);if(-1!==t){for(var n,i=[],r=o(e.components);!(n=r()).done;){var s=n.value;i.push(s.constructor)}this.entities.splice(t,1),this.removeEntityFromIndexes(e),this.archetypeSystem.removeEntity(e),i.length>0?this.notifyReactiveQueriesEntityRemoved(e,i):this.notifyReactiveQueriesEntityRemovedFallback(e),this.clearQueryCache(),this._version++}},t.updateEntity=function(e){this.entities.includes(e)?(this.removeEntityFromIndexes(e),this.archetypeSystem.updateEntity(e),this.addEntityToIndexes(e),this.notifyReactiveQueriesEntityChanged(e),this.clearQueryCache(),this._version++):this.addEntity(e)},t.addEntityToIndexes=function(e){var t=e.tag;void 0!==t&&(this.entityIndex.byTag.get(t)||this.createAndSetTagIndex(t)).add(e);var n=e.name;n&&(this.entityIndex.byName.get(n)||this.createAndSetNameIndex(n)).add(e)},t.createAndSetTagIndex=function(e){var t=new Set;return this.entityIndex.byTag.set(e,t),t},t.createAndSetNameIndex=function(e){var t=new Set;return this.entityIndex.byName.set(e,t),t},t.removeEntityFromIndexes=function(e){if(void 0!==e.tag){var t=this.entityIndex.byTag.get(e.tag);t&&(t.delete(e),0===t.size&&this.entityIndex.byTag.delete(e.tag))}if(e.name){var n=this.entityIndex.byName.get(e.name);n&&(n.delete(e),0===n.size&&this.entityIndex.byName.delete(e.name))}},t.rebuildIndexes=function(){this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear();for(var e,t=o(this.entities);!(e=t()).done;){var n=e.value;this.addEntityToIndexes(n),this.archetypeSystem.addEntity(n)}},t.queryAll=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(Re.ALL,n).getEntities();return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryMultipleComponents=function(e){for(var t,n=[],i=o(this.archetypeSystem.queryArchetypes(e,"AND").archetypes);!(t=i()).done;)for(var r,s=o(t.value.entities);!(r=s()).done;){var a=r.value;n.push(a)}return n},t.queryAny=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(Re.ANY,n).getEntities();return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryNone=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(Re.NONE,n).getEntities();return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryByTag=function(e){var t=performance.now();this.queryStats.totalQueries++;var n="tag:"+e,i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byTag.get(e)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByName=function(e){var t=performance.now();this.queryStats.totalQueries++;var n="name:"+e,i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byName.get(e)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByComponent=function(e){var t=performance.now();this.queryStats.totalQueries++;var n=this.generateCacheKey("component",[e]),i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var r=this.archetypeSystem.getEntitiesByComponent(e);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.getFromCache=function(e){var t=this.queryCache.get(e);return t?Date.now()-t.timestamp>this.cacheTimeout||t.version!==this._version?(this.queryCache.delete(e),null):(t.hitCount++,t.entities):null},t.addToCache=function(e,t){this.queryCache.size>=this.cacheMaxSize&&this.cleanupCache(),this.queryCache.set(e,{entities:t,timestamp:Date.now(),hitCount:0,version:this._version})},t.cleanupCache=function(){for(var e,t=Date.now(),n=o(this.queryCache.entries());!(e=n()).done;){var i=e.value,r=i[0];t-i[1].timestamp>this.cacheTimeout&&this.queryCache.delete(r)}if(this.queryCache.size>=this.cacheMaxSize){for(var s,a=1/0,c="",u=1/0,h=o(this.queryCache.entries());!(s=h()).done;){var l=s.value,f=l[0],d=l[1];(d.hitCount<a||d.hitCount===a&&d.timestamp<u)&&(a=d.hitCount,c=f,u=d.timestamp)}c&&this.queryCache.delete(c)}},t.clearQueryCache=function(){this.queryCache.clear(),this.componentMaskCache.clear()},t.clearReactiveQueries=function(){for(var e,t=o(this._reactiveQueries.values());!(e=t()).done;){e.value.dispose()}this._reactiveQueries.clear(),this._reactiveQueriesByComponent.clear()},t.generateCacheKey=function(e,t){return 1===t.length?e+":"+U(t[0]):e+":"+t.map((function(e){return U(e)})).sort().join(",")},t.clearCache=function(){this.clearQueryCache(),this.clearReactiveQueries()},t.createReactiveQuery=function(e,t){if(!e||0===e.length)throw new Error("组件类型列表不能为空");var n=this.createComponentMask(e),i={type:Re.ALL,componentTypes:e,mask:n},r=new We(i,t),s=this.executeTraditionalQuery(Re.ALL,e);r.initializeWith(s);var a=this.generateCacheKey("all",e);this._reactiveQueries.set(a,r);for(var c,u=o(e);!(c=u()).done;){var h=c.value,l=this._reactiveQueriesByComponent.get(h);l||(l=new Set,this._reactiveQueriesByComponent.set(h,l)),l.add(r)}return r},t.destroyReactiveQuery=function(e){if(e){var t=e.id;this._reactiveQueries.delete(t);for(var n,i=o(e.condition.componentTypes);!(n=i()).done;){var r=n.value,s=this._reactiveQueriesByComponent.get(r);s&&(s.delete(e),0===s.size&&this._reactiveQueriesByComponent.delete(r))}e.dispose()}},t.createComponentMask=function(e){var t=e.map((function(e){return U(e)})).sort().join(","),n=this.componentMaskCache.get(t);if(n)return n;for(var i,r=pe.clone(pe.ZERO),s=o(e);!(i=s()).done;){var a=i.value;ge.isRegistered(a)||ge.register(a);var c=ge.getBitMask(a);pe.orInPlace(r,c)}return this.componentMaskCache.set(t,r),r},t.getAllEntities=function(){return this.entities},t.getStats=function(){return{entityCount:this.entities.length,indexStats:{componentIndexSize:this.archetypeSystem.getAllArchetypes().length,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},queryStats:a({},this.queryStats,{cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}),optimizationStats:{archetypeSystem:this.archetypeSystem.getAllArchetypes().map((function(e){return{id:e.id,componentTypes:e.componentTypes.map((function(e){return U(e)})),entityCount:e.entities.size}}))},cacheStats:{size:this._reactiveQueries.size,hitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}},t.getEntityArchetype=function(e){return this.archetypeSystem.getEntityArchetype(e)},t.getOrCreateReactiveQuery=function(e,t){var n=this.generateCacheKey(e,t),i=this._reactiveQueries.get(n);if(!i){var r=this.createComponentMask(t);i=new We({type:e,componentTypes:t,mask:r},{enableBatchMode:!1,debug:!1});var s=this.executeTraditionalQuery(e,t);i.initializeWith(s),this._reactiveQueries.set(n,i);for(var a,c=o(t);!(a=c()).done;){var u=a.value,h=this._reactiveQueriesByComponent.get(u);h||(h=new Set,this._reactiveQueriesByComponent.set(u,h)),h.add(i)}this._logger.debug("创建内部响应式查询缓存: "+n)}return i},t.executeTraditionalQuery=function(e,t){switch(e){case Re.ALL:for(var n,i=[],r=o(this.archetypeSystem.queryArchetypes(t,"AND").archetypes);!(n=r()).done;)for(var s,a=o(n.value.entities);!(s=a()).done;){var c=s.value;i.push(c)}return i;case Re.ANY:for(var u,h=[],l=o(this.archetypeSystem.queryArchetypes(t,"OR").archetypes);!(u=l()).done;)for(var f,d=o(u.value.entities);!(f=d()).done;){var p=f.value;h.push(p)}return h;case Re.NONE:var y=this.createComponentMask(t);return this.entities.filter((function(e){return pe.hasNone(e.componentMask,y)}));default:return[]}},t.notifyReactiveQueriesEntityAdded=function(e){if(0!==this._reactiveQueries.size)for(var t,n=new Set,i=o(e.components);!(t=i()).done;){var r=t.value.constructor,s=this._reactiveQueriesByComponent.get(r);if(s)for(var a,c=o(s);!(a=c()).done;){var u=a.value;n.has(u)||(u.notifyEntityAdded(e),n.add(u))}}},t.notifyReactiveQueriesEntityRemoved=function(e,t){if(0!==this._reactiveQueries.size)for(var n,i=new Set,r=o(t);!(n=r()).done;){var s=n.value,a=this._reactiveQueriesByComponent.get(s);if(a)for(var c,u=o(a);!(c=u()).done;){var h=c.value;i.has(h)||(h.notifyEntityRemoved(e),i.add(h))}}},t.notifyReactiveQueriesEntityRemovedFallback=function(e){if(0!==this._reactiveQueries.size)for(var t,n=o(this._reactiveQueries.values());!(t=n()).done;){t.value.notifyEntityRemoved(e)}},t.notifyReactiveQueriesEntityChanged=function(e){if(0!==this._reactiveQueries.size){for(var t,n=new Set,i=o(e.components);!(t=i()).done;){var r=t.value.constructor,s=this._reactiveQueriesByComponent.get(r);if(s)for(var a,c=o(s);!(a=c()).done;){var u=a.value;n.has(u)||(u.notifyEntityChanged(e),n.add(u))}}for(var h,l=o(this._reactiveQueries.values());!(h=l()).done;){var f=h.value;n.has(f)||f.notifyEntityChanged(e)}}},s(e,[{key:"version",get:function(){return this._version}}])}(),Fe=function(){function e(e){this._logger=Y("QueryBuilder"),this.conditions=[],this.querySystem=e}var t=e.prototype;return t.withAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:Re.ALL,componentTypes:t,mask:this.createComponentMask(t)}),this},t.withAny=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:Re.ANY,componentTypes:t,mask:this.createComponentMask(t)}),this},t.without=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:Re.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this},t.execute=function(){var e,t,n,i=performance.now();if(1===this.conditions.length){var r=this.conditions[0];switch(r.type){case Re.ALL:return(e=this.querySystem).queryAll.apply(e,r.componentTypes);case Re.ANY:return(t=this.querySystem).queryAny.apply(t,r.componentTypes);case Re.NONE:return(n=this.querySystem).queryNone.apply(n,r.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-i,fromCache:!1}},t.createComponentMask=function(e){for(var t,n=pe.clone(pe.ZERO),i=o(e);!(t=i()).done;){var r=t.value;try{var s=ge.getBitMask(r);pe.orInPlace(n,s)}catch(e){this._logger.warn("组件类型 "+U(r)+" 未注册,跳过")}}return n},t.reset=function(){return this.conditions=[],this},e}(),He=function(){function e(){this.listeners=new Map,this.stats=new Map,this.batchQueue=new Map,this.batchTimers=new Map,this.batchConfigs=new Map,this.nextListenerId=0,this.isEnabled=!0,this.maxListeners=100}var t=e.prototype;return t.on=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,n)},t.once=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,a({},n,{once:!0}))},t.onAsync=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,a({},n,{async:!0}))},t.off=function(e,t){var n=this.listeners.get(e);if(!n)return!1;var i=n.findIndex((function(e){return e.id===t}));return-1!==i&&(n.splice(i,1),0===n.length&&(this.listeners.delete(e),this.stats.delete(e)),!0)},t.offAll=function(e){this.listeners.delete(e),this.stats.delete(e),this.clearBatch(e)},t.emit=function(){var e=n(l().m((function e(t,n){var i;return l().w((function(e){for(;;)switch(e.n){case 0:if(this.isEnabled){e.n=1;break}return e.a(2);case 1:if(null==(i=this.batchConfigs.get(t))||!i.enabled){e.n=2;break}return this.addToBatch(t,n),e.a(2);case 2:return e.n=3,this.executeEvent(t,n);case 3:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),t.emitSync=function(t,n){if(this.isEnabled){var i=this.listeners.get(t);if(i&&0!==i.length){for(var r,s=performance.now(),a=[],c=o(this.sortListenersByPriority(i));!(r=c()).done;){var u=r.value;if(!u.config.async)try{u.config.context?u.handler.call(u.config.context,n):u.handler(n),u.config.once&&a.push(u.id)}catch(n){e._logger.error("事件处理器执行错误 "+t+":",n)}}this.removeListeners(t,a),this.updateStats(t,performance.now()-s)}}},t.setBatchConfig=function(e,t){this.batchConfigs.set(e,t)},t.flushBatch=function(e){var t=this.batchQueue.get(e);if(t&&0!==t.length){var n=this.batchTimers.get(e);n&&(clearTimeout(n),this.batchTimers.delete(e)),this.processBatch(e,t),this.batchQueue.delete(e)}},t.getStats=function(e){return e?this.stats.get(e)||this.createEmptyStats(e):new Map(this.stats)},t.resetStats=function(e){e?this.stats.delete(e):this.stats.clear()},t.setEnabled=function(e){this.isEnabled=e},t.hasListeners=function(e){var t=this.listeners.get(e);return!!t&&t.length>0},t.getListenerCount=function(e){var t=this.listeners.get(e);return t?t.length:0},t.clear=function(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()},t.setMaxListeners=function(e){this.maxListeners=e},t.addListener=function(t,n,i){var r=this.listeners.get(t);if(r||(r=[],this.listeners.set(t,r)),r.length>=this.maxListeners)return e._logger.warn("事件类型 "+t+" 的监听器数量超过最大限制 ("+this.maxListeners+")"),"";var s="listener_"+this.nextListenerId++,o={handler:n,config:a({priority:0},i),id:s};return r.push(o),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),s},t.executeEvent=function(){var t=n(l().m((function t(i,r){var s,a,c,u,h,f,d,p,y,m;return l().w((function(t){for(;;)switch(t.n){case 0:if((s=this.listeners.get(i))&&0!==s.length){t.n=1;break}return t.a(2);case 1:for(a=performance.now(),c=[],u=this.sortListenersByPriority(s),h=u.filter((function(e){return!e.config.async})),f=u.filter((function(e){return e.config.async})),d=o(h);!(p=d()).done;){y=p.value;try{y.config.context?y.handler.call(y.config.context,r):y.handler(r),y.config.once&&c.push(y.id)}catch(t){e._logger.error("同步事件处理器执行错误 "+i+":",t)}}return m=f.map(function(){var t=n(l().m((function t(n){var s;return l().w((function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,!n.config.context){t.n=2;break}return t.n=1,n.handler.call(n.config.context,r);case 1:t.n=3;break;case 2:return t.n=3,n.handler(r);case 3:n.config.once&&c.push(n.id),t.n=5;break;case 4:t.p=4,s=t.v,e._logger.error("异步事件处理器执行错误 "+i+":",s);case 5:return t.a(2)}}),t,null,[[0,4]])})));return function(e){return t.apply(this,arguments)}}()),t.n=2,Promise.all(m);case 2:this.removeListeners(i,c),this.updateStats(i,performance.now()-a);case 3:return t.a(2)}}),t,this)})));return function(e,n){return t.apply(this,arguments)}}(),t.sortListenersByPriority=function(e){return e.slice().sort((function(e,t){return(t.config.priority||0)-(e.config.priority||0)}))},t.removeListeners=function(e,t){if(0!==t.length){var n=this.listeners.get(e);if(n){for(var i,r=function(){var e=i.value,t=n.findIndex((function(t){return t.id===e}));-1!==t&&n.splice(t,1)},s=o(t);!(i=s()).done;)r();0===n.length&&(this.listeners.delete(e),this.stats.delete(e))}}},t.addToBatch=function(e,t){var n=this,i=this.batchQueue.get(e);i||(i=[],this.batchQueue.set(e,i)),i.push(t);var r=this.batchConfigs.get(e);if(i.length>=r.batchSize)this.flushBatch(e);else if(!this.batchTimers.has(e)){var s=setTimeout((function(){n.flushBatch(e)}),r.delay);this.batchTimers.set(e,s)}},t.processBatch=function(){var e=n(l().m((function e(t,n){var i;return l().w((function(e){for(;;)switch(e.n){case 0:return i={type:t,events:n,count:n.length,timestamp:Date.now()},e.n=1,this.executeEvent(t+":batch",i);case 1:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),t.clearBatch=function(e){this.batchQueue.delete(e);var t=this.batchTimers.get(e);t&&(clearTimeout(t),this.batchTimers.delete(e))},t.clearAllBatches=function(){this.batchQueue.clear();for(var e,t=o(this.batchTimers.values());!(e=t()).done;){var n=e.value;clearTimeout(n)}this.batchTimers.clear(),this.batchConfigs.clear()},t.updateStats=function(e,t){var n=this.stats.get(e);n||(n=this.createEmptyStats(e),this.stats.set(e,n)),n.triggerCount++,n.totalExecutionTime+=t,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(e)},t.createEmptyStats=function(e){return{eventType:e,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}},e}();He._logger=Y("EventSystem"),exports.ECSEventType=void 0,(Le=exports.ECSEventType||(exports.ECSEventType={})).ENTITY_CREATED="entity:created",Le.ENTITY_DESTROYED="entity:destroyed",Le.ENTITY_ENABLED="entity:enabled",Le.ENTITY_DISABLED="entity:disabled",Le.ENTITY_TAG_ADDED="entity:tag:added",Le.ENTITY_TAG_REMOVED="entity:tag:removed",Le.ENTITY_NAME_CHANGED="entity:name:changed",Le.COMPONENT_ADDED="component:added",Le.COMPONENT_REMOVED="component:removed",Le.COMPONENT_MODIFIED="component:modified",Le.COMPONENT_ENABLED="component:enabled",Le.COMPONENT_DISABLED="component:disabled",Le.SYSTEM_ADDED="system:added",Le.SYSTEM_REMOVED="system:removed",Le.SYSTEM_ENABLED="system:enabled",Le.SYSTEM_DISABLED="system:disabled",Le.SYSTEM_PROCESSING_START="system:processing:start",Le.SYSTEM_PROCESSING_END="system:processing:end",Le.SYSTEM_ERROR="system:error",Le.SCENE_CREATED="scene:created",Le.SCENE_DESTROYED="scene:destroyed",Le.SCENE_ACTIVATED="scene:activated",Le.SCENE_DEACTIVATED="scene:deactivated",Le.SCENE_PAUSED="scene:paused",Le.SCENE_RESUMED="scene:resumed",Le.QUERY_EXECUTED="query:executed",Le.QUERY_CACHE_HIT="query:cache:hit",Le.QUERY_CACHE_MISS="query:cache:miss",Le.QUERY_OPTIMIZED="query:optimized",Le.PERFORMANCE_WARNING="performance:warning",Le.PERFORMANCE_CRITICAL="performance:critical",Le.MEMORY_USAGE_HIGH="memory:usage:high",Le.FRAME_RATE_DROP="frame:rate:drop",Le.INDEX_CREATED="index:created",Le.INDEX_UPDATED="index:updated",Le.INDEX_OPTIMIZED="index:optimized",Le.ARCHETYPE_CREATED="archetype:created",Le.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",Le.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",Le.DIRTY_MARK_ADDED="dirty:mark:added",Le.DIRTY_BATCH_PROCESSED="dirty:batch:processed",Le.ERROR_OCCURRED="error:occurred",Le.WARNING_ISSUED="warning:issued",Le.FRAMEWORK_INITIALIZED="framework:initialized",Le.FRAMEWORK_SHUTDOWN="framework:shutdown",Le.DEBUG_INFO="debug:info",Le.DEBUG_STATS_UPDATED="debug:stats:updated",exports.EventPriority=void 0,(Ne=exports.EventPriority||(exports.EventPriority={}))[Ne.LOWEST=0]="LOWEST",Ne[Ne.LOW=25]="LOW",Ne[Ne.NORMAL=50]="NORMAL",Ne[Ne.HIGH=75]="HIGH",Ne[Ne.HIGHEST=100]="HIGHEST",Ne[Ne.CRITICAL=200]="CRITICAL";var je={ENTITY:{CREATED:exports.ECSEventType.ENTITY_CREATED,DESTROYED:exports.ECSEventType.ENTITY_DESTROYED,ENABLED:exports.ECSEventType.ENTITY_ENABLED,DISABLED:exports.ECSEventType.ENTITY_DISABLED,TAG_ADDED:exports.ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:exports.ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:exports.ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:exports.ECSEventType.COMPONENT_ADDED,REMOVED:exports.ECSEventType.COMPONENT_REMOVED,MODIFIED:exports.ECSEventType.COMPONENT_MODIFIED,ENABLED:exports.ECSEventType.COMPONENT_ENABLED,DISABLED:exports.ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:exports.ECSEventType.SYSTEM_ADDED,REMOVED:exports.ECSEventType.SYSTEM_REMOVED,ENABLED:exports.ECSEventType.SYSTEM_ENABLED,DISABLED:exports.ECSEventType.SYSTEM_DISABLED,PROCESSING_START:exports.ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:exports.ECSEventType.SYSTEM_PROCESSING_END,ERROR:exports.ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:exports.ECSEventType.PERFORMANCE_WARNING,CRITICAL:exports.ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:exports.ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:exports.ECSEventType.FRAME_RATE_DROP}},qe=function(){function e(){}return e.isValid=function(e){return this.validTypes.has(e)},e.getAllValidTypes=function(){return Array.from(this.validTypes)},e.addCustomType=function(e){this.validTypes.add(e)},e.removeCustomType=function(e){this.validTypes.delete(e)},e}();qe.validTypes=new Set([].concat(Object.values(exports.ECSEventType),Object.values(je.ENTITY),Object.values(je.COMPONENT),Object.values(je.SYSTEM),Object.values(je.PERFORMANCE)));var Ge=function(){function e(e){void 0===e&&(e=!1),this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new He,this.isDebugMode=e}var t=e.prototype;return t.emit=function(t,n,i){void 0===i&&(i=!1),this.validateEventType(t);var r=i?this.enhanceEventData(t,n):n;this.isDebugMode&&e._logger.info("发射事件: "+t,r),this.eventSystem.emitSync(t,r)},t.emitAsync=function(){var t=n(l().m((function t(n,i,r){var s;return l().w((function(t){for(;;)switch(t.n){case 0:return void 0===r&&(r=!1),this.validateEventType(n),s=r?this.enhanceEventData(n,i):i,this.isDebugMode&&e._logger.info("发射异步事件: "+n,s),t.n=1,this.eventSystem.emit(n,s);case 1:return t.a(2)}}),t,this)})));return function(e,n,i){return t.apply(this,arguments)}}(),t.on=function(t,n,i){void 0===i&&(i={}),this.validateEventType(t);var r={once:i.once||!1,priority:i.priority||exports.EventPriority.NORMAL,async:i.async||!1,context:i.context};return this.isDebugMode&&e._logger.info("添加监听器: "+t,r),this.eventSystem.on(t,n,r)},t.once=function(e,t,n){return void 0===n&&(n={}),this.on(e,t,a({},n,{once:!0}))},t.onAsync=function(e,t,n){return void 0===n&&(n={}),this.on(e,t,a({},n,{async:!0}))},t.off=function(t,n){return this.isDebugMode&&e._logger.info("移除监听器: "+n+" 事件: "+t),this.eventSystem.off(t,n)},t.offAll=function(t){this.isDebugMode&&e._logger.info("移除所有监听器: "+t),this.eventSystem.offAll(t)},t.hasListeners=function(e){return this.eventSystem.hasListeners(e)},t.getStats=function(e){var t=this,n=this.eventSystem.getStats(e);if(n instanceof Map){var i=new Map;return n.forEach((function(e,n){i.set(n,t.convertEventStats(e))})),i}return this.convertEventStats(n)},t.clear=function(){this.isDebugMode&&e._logger.info("清空所有监听器"),this.eventSystem.clear()},t.setEnabled=function(e){this.eventSystem.setEnabled(e)},t.setDebugMode=function(e){this.isDebugMode=e},t.setMaxListeners=function(e){this.eventSystem.setMaxListeners(e)},t.getListenerCount=function(e){return this.eventSystem.getListenerCount(e)},t.setBatchConfig=function(e,t,n){this.eventSystem.setBatchConfig(e,{batchSize:t,delay:n,enabled:!0})},t.flushBatch=function(e){this.eventSystem.flushBatch(e)},t.resetStats=function(e){this.eventSystem.resetStats(e)},t.emitEntityCreated=function(e){this.emit(exports.ECSEventType.ENTITY_CREATED,e)},t.emitEntityDestroyed=function(e){this.emit(exports.ECSEventType.ENTITY_DESTROYED,e)},t.emitComponentAdded=function(e){this.emit(exports.ECSEventType.COMPONENT_ADDED,e)},t.emitComponentRemoved=function(e){this.emit(exports.ECSEventType.COMPONENT_REMOVED,e)},t.emitSystemAdded=function(e){this.emit(exports.ECSEventType.SYSTEM_ADDED,e)},t.emitSystemRemoved=function(e){this.emit(exports.ECSEventType.SYSTEM_REMOVED,e)},t.emitSceneChanged=function(e){this.emit(exports.ECSEventType.SCENE_ACTIVATED,e)},t.emitPerformanceWarning=function(e){this.emit(exports.ECSEventType.PERFORMANCE_WARNING,e)},t.onEntityCreated=function(e,t){return this.on(exports.ECSEventType.ENTITY_CREATED,e,t)},t.onComponentAdded=function(e,t){return this.on(exports.ECSEventType.COMPONENT_ADDED,e,t)},t.onSystemError=function(e,t){return this.on(exports.ECSEventType.SYSTEM_ERROR,e,t)},t.onPerformanceWarning=function(e,t){return this.on(exports.ECSEventType.PERFORMANCE_WARNING,e,t)},t.validateEventType=function(t){this.isDebugMode&&(qe.isValid(t)||(e._logger.warn("未知事件类型: "+t),qe.addCustomType(t)))},t.enhanceEventData=function(e,t){if(null==t)return{timestamp:Date.now(),eventId:e+"_"+ ++this.eventIdCounter,source:"EventBus"};var n=t;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=e+"_"+ ++this.eventIdCounter),n.source||(n.source="EventBus"),n},t.convertEventStats=function(e){return{eventType:e.eventType,listenerCount:e.listenerCount,triggerCount:e.triggerCount,totalExecutionTime:e.totalExecutionTime,averageExecutionTime:e.averageExecutionTime,lastTriggerTime:e.lastTriggerTime}},e}();Ge._logger=Y("EventBus");var Qe=function(){function e(){}return e.getInstance=function(e){return void 0===e&&(e=!1),this.instance||(this.instance=new Ge(e)),this.instance},e.reset=function(e){return void 0===e&&(e=!1),this.instance&&this.instance.clear(),this.instance=new Ge(e),this.instance},e}(),Ve=function(){function e(e,t){this._entities=e,this._componentTypes=t}var t=e.prototype;return t.forEach=function(e){this._entities.forEach(e)},t.map=function(e){return this._entities.map(e)},t.filter=function(t){return new e(this._entities.filter(t),this._componentTypes)},t.find=function(e){return this._entities.find(e)},t.some=function(e){return this._entities.some(e)},t.every=function(e){return this._entities.every(e)},t.get=function(e){return this._entities[e]},t.toArray=function(){return[].concat(this._entities)},t.getComponentTypes=function(){return this._componentTypes},t[Symbol.iterator]=function(){return this._entities[Symbol.iterator]()},s(e,[{key:"entities",get:function(){return this._entities}},{key:"length",get:function(){return this._entities.length}},{key:"first",get:function(){return this._entities[0]}},{key:"last",get:function(){return this._entities[this._entities.length-1]}},{key:"isEmpty",get:function(){return 0===this._entities.length}}])}(),Ye=function(){function e(e,t,n,i,r){this._all=e||[],this._any=t||[],this._none=n||[],this._tag=i,this._name=r}var t=e.prototype;return t.withAll=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e([].concat(this._all,n),this._any,this._none,this._tag,this._name)},t.withAny=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e(this._all,[].concat(this._any,n),this._none,this._tag,this._name)},t.withNone=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e(this._all,this._any,[].concat(this._none,n),this._tag,this._name)},t.withTag=function(t){return new e(this._all,this._any,this._none,t,this._name)},t.withName=function(t){return new e(this._all,this._any,this._none,this._tag,t)},t.buildMatcher=function(){var e,t,n,i=Ae.complex();this._all.length>0&&(i=(e=i).all.apply(e,this._all));this._any.length>0&&(i=(t=i).any.apply(t,this._any));this._none.length>0&&(i=(n=i).none.apply(n,this._none));return void 0!==this._tag&&(i=i.withTag(this._tag)),void 0!==this._name&&(i=i.withName(this._name)),i},t.getCondition=function(){return{all:[].concat(this._all),any:[].concat(this._any),none:[].concat(this._none),tag:this._tag,name:this._name}},t.getRequiredTypes=function(){return this._all},t.clone=function(){return new e([].concat(this._all),[].concat(this._any),[].concat(this._none),this._tag,this._name)},e}();var Ke=Symbol("SerializableMetadata"),Je=Symbol("SerializeField"),$e=Symbol("SerializeOptions");function Ze(e){return function(t,n){var i=t.constructor,r=i[Ke];r||(r={options:{version:1},fields:new Map,ignoredFields:new Set},i[Ke]=r),r.fields.set(n,e||{})}}function Xe(e){return e&&("function"==typeof e?e:e.constructor)[Ke]||null}var et=function(){function e(){}return e.serialize=function(e){var t=Xe(e);if(!t)return null;for(var n,i=e.constructor,r=t.options.typeId||U(i),s={},a=o(t.fields);!(n=a()).done;){var c=n.value,u=c[0],h=c[1],l="symbol"==typeof u?u.toString():u,f=e[u];if(!t.ignoredFields.has(u)){var d=h.serializer?h.serializer(f):this.serializeValue(f);s[h.alias||l]=d}}return{type:r,version:t.options.version,data:s}},e.deserialize=function(e,t){var n=t.get(e.type);if(!n)return console.warn("未找到组件类型: "+e.type),null;var i=Xe(n);if(!i)return console.warn("组件 "+e.type+" 不可序列化"),null;for(var r,s=new n,a=o(i.fields);!(r=a()).done;){var c=r.value,u=c[0],h=c[1],l="symbol"==typeof u?u.toString():u,f=h.alias||l,d=e.data[f];if(void 0!==d){var p=h.deserializer?h.deserializer(d):this.deserializeValue(d);s[u]=p}}return s},e.serializeComponents=function(e){for(var t,n=[],i=o(e);!(t=i()).done;){var r=t.value,s=this.serialize(r);s&&n.push(s)}return n},e.deserializeComponents=function(e,t){for(var n,i=[],r=o(e);!(n=r()).done;){var s=n.value,a=this.deserialize(s,t);a&&i.push(a)}return i},e.serializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(Array.isArray(e))return e.map((function(e){return t.serializeValue(e)}));if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if("object"===n){var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=this.serializeValue(e[r]));return i}},e.deserializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if("object"===n&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((function(e){return t.deserializeValue(e)}));if("object"===n){var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=this.deserializeValue(e[r]));return i}return e},e.validateVersion=function(e,t){return e.version===t},e.getSerializationInfo=function(e){var t=Xe(e);if(!t)return{type:"unknown",version:0,fields:[],ignoredFields:[],isSerializable:!1};var n="function"==typeof e?e:e.constructor;return{type:t.options.typeId||U(n),version:t.options.version,fields:Array.from(t.fields.keys()).map((function(e){return"symbol"==typeof e?e.toString():e})),ignoredFields:Array.from(t.ignoredFields).map((function(e){return"symbol"==typeof e?e.toString():e})),isSerializable:!0}},e}(),tt=function(){function e(){}return e.serialize=function(e,t){void 0===t&&(t=!0);var n=et.serializeComponents(Array.from(e.components)),i={id:e.id,name:e.name,tag:e.tag,active:e.active,enabled:e.enabled,updateOrder:e.updateOrder,components:n,children:[]};if(e.parent&&(i.parentId=e.parent.id),t)for(var r,s=o(e.children);!(r=s()).done;){var a=r.value;i.children.push(this.serialize(a,!0))}return i},e.deserialize=function(e,t,n,i,r){void 0===i&&(i=!1);var s=i?e.id:n(),a=new Ce(e.name,s);r&&(a.scene=r),a.tag=e.tag,a.active=e.active,a.enabled=e.enabled,a.updateOrder=e.updateOrder;for(var c,u=o(et.deserializeComponents(e.components,t));!(c=u()).done;){var h=c.value;a.addComponent(h)}for(var l,f=o(e.children);!(l=f()).done;){var d=l.value,p=this.deserialize(d,t,n,i,r);a.addChild(p)}return a},e.serializeEntities=function(e,t){void 0===t&&(t=!0);for(var n,i=[],r=o(e);!(n=r()).done;){var s=n.value;s.parent&&t||i.push(this.serialize(s,t))}return i},e.deserializeEntities=function(e,t,n,i,r){void 0===i&&(i=!1);for(var s,a=[],c=o(e);!(s=c()).done;){var u=s.value,h=this.deserialize(u,t,n,i,r);a.push(h)}return a},e.clone=function(e,t,n){var i=this.serialize(e,!0);return this.deserialize(i,t,n,!1)},e}();const nt=new TextEncoder;function it(e,t,n){e.length>50?function(e,t,n){nt.encodeInto(e,t.subarray(n))}(e,t,n):function(e,t,n){const i=e.length;let r=n,s=0;for(;s<i;){let n=e.charCodeAt(s++);if(4294967168&n){if(4294965248&n){if(n>=55296&&n<=56319&&s<i){const t=e.charCodeAt(s);56320==(64512&t)&&(++s,n=((1023&n)<<10)+(1023&t)+65536)}4294901760&n?(t[r++]=n>>18&7|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128):(t[r++]=n>>12&15|224,t[r++]=n>>6&63|128)}else t[r++]=n>>6&31|192;t[r++]=63&n|128}else t[r++]=n}}(e,t,n)}function rt(e,t,n){let i=t;const r=i+n,s=[];let o="";for(;i<r;){const t=e[i++];if(128&t)if(192==(224&t)){const n=63&e[i++];s.push((31&t)<<6|n)}else if(224==(240&t)){const n=63&e[i++],r=63&e[i++];s.push((31&t)<<12|n<<6|r)}else if(240==(248&t)){let n=(7&t)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++];n>65535&&(n-=65536,s.push(n>>>10&1023|55296),n=56320|1023&n),s.push(n)}else s.push(t);else s.push(t);s.length>=4096&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const st=new TextDecoder;function ot(e,t,n){return n>200?function(e,t,n){const i=e.subarray(t,t+n);return st.decode(i)}(e,t,n):rt(e,t,n)}class at{constructor(e,t){this.type=e,this.data=t}}class ct extends Error{constructor(e){super(e);const t=Object.create(ct.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ct.name})}}const ut=4294967295;function ht(e,t,n){const i=Math.floor(n/4294967296),r=n;e.setUint32(t,i),e.setUint32(t+4,r)}function lt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}const ft={type:-1,encode:function(e){if(e instanceof Date){return function({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=17179869183){if(0===t&&e<=4294967295){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}{const n=e/4294967296,i=4294967295&e,r=new Uint8Array(8),s=new DataView(r.buffer);return s.setUint32(0,t<<2|3&n),s.setUint32(4,i),r}}{const n=new Uint8Array(12),i=new DataView(n.buffer);return i.setUint32(0,t),ht(i,4,e),n}}(function(e){const t=e.getTime(),n=Math.floor(t/1e3),i=1e6*(t-1e3*n),r=Math.floor(i/1e9);return{sec:n+r,nsec:i-1e9*r}}(e))}return null},decode:function(e){const t=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const e=t.getUint32(0);return{sec:4294967296*(3&e)+t.getUint32(4),nsec:e>>>2}}case 12:return{sec:lt(t,4),nsec:t.getUint32(0)};default:throw new ct(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}};class dt{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ft)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{const i=-1-e;this.builtInEncoders[i]=t,this.builtInDecoders[i]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){const i=this.builtInEncoders[n];if(null!=i){const r=i(e,t);if(null!=r){return new at(-1-n,r)}}}for(let n=0;n<this.encoders.length;n++){const i=this.encoders[n];if(null!=i){const r=i(e,t);if(null!=r){return new at(n,r)}}}return e instanceof at?e:null}decode(e,t,n){const i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,n):new at(t,e)}}function pt(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):function(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}(e)?new Uint8Array(e):Uint8Array.from(e)}dt.defaultCodec=new dt;class yt{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??dt.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??100,this.initialBufferSize=e?.initialBufferSize??2048,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new yt({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered){return this.clone().encodeSharedRef(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered){return this.clone().encode(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.useBigInt64&&"bigint"==typeof e?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)}resizeBuffer(e){const t=new ArrayBuffer(e),n=new Uint8Array(t),i=new DataView(t);n.set(this.bytes),this.view=i,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(e){!1===e?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too long string: ${e} bytes in UTF-8`);this.writeU8(219),this.writeU32(e)}}encodeString(e){const t=function(e){const t=e.length;let n=0,i=0;for(;i<t;){let r=e.charCodeAt(i++);if(4294967168&r)if(4294965248&r){if(r>=55296&&r<=56319&&i<t){const t=e.charCodeAt(i);56320==(64512&t)&&(++i,r=((1023&r)<<10)+(1023&t)+65536)}n+=4294901760&r?4:3}else n+=2;else n++}return n}(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),it(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);this.encodeMap(e,t)}}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large binary: ${t}`);this.writeU8(198),this.writeU32(t)}const n=pt(e);this.writeU8a(n)}encodeArray(e,t){const n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error(`Too large array: ${n}`);this.writeU8(221),this.writeU32(n)}for(const n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let n=0;for(const i of t)void 0!==e[i]&&n++;return n}encodeMap(e,t){const n=Object.keys(e);this.sortKeys&&n.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else{if(!(i<4294967296))throw new Error(`Too large map object: ${i}`);this.writeU8(223),this.writeU32(i)}for(const i of n){const n=e[i];this.ignoreUndefined&&void 0===n||(this.encodeString(i),this.doEncode(n,t+1))}}encodeExtension(e){if("function"==typeof e.data){const t=e.data(this.pos+6),n=t.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);return this.writeU8(201),this.writeU32(n),this.writeI8(e.type),void this.writeU8a(t)}const t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),function(e,t,n){const i=n/4294967296,r=n;e.setUint32(t,i),e.setUint32(t+4,r)}(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ht(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function mt(e,t){return new yt(t).encodeSharedRef(e)}function gt(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const vt="array",_t="map_key",St="map_value",Ct=e=>{if("string"==typeof e||"number"==typeof e)return e;throw new ct("The type of key must be string or number but "+typeof e)};class wt{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=vt,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=_t,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===vt){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===_t||e.type===St){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Et=new DataView(new ArrayBuffer(0)),bt=new Uint8Array(Et.buffer);try{Et.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const At=new RangeError("Insufficient data"),Tt=new class{constructor(e=16,t=16){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){const i=this.caches[n-1];e:for(const r of i){const i=r.bytes;for(let r=0;r<n;r++)if(i[r]!==e[t+r])continue e;return r.str}return null}store(e,t){const n=this.caches[e.length-1],i={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)}decode(e,t,n){const i=this.find(e,t,n);if(null!=i)return this.hit++,i;this.miss++;const r=rt(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,r),r}};class Mt{constructor(e){this.totalPos=0,this.pos=0,this.view=Et,this.bytes=bt,this.headByte=-1,this.stack=new wt,this.entered=!1,this.extensionCodec=e?.extensionCodec??dt.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??ut,this.maxBinLength=e?.maxBinLength??ut,this.maxArrayLength=e?.maxArrayLength??ut,this.maxMapLength=e?.maxMapLength??ut,this.maxExtLength=e?.maxExtLength??ut,this.keyDecoder=void 0!==e?.keyDecoder?e.keyDecoder:Tt,this.mapKeyConverter=e?.mapKeyConverter??Ct}clone(){return new Mt({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){const t=pt(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(-1!==this.headByte||this.hasRemaining(1)){const t=this.bytes.subarray(this.pos),n=pt(e),i=new Uint8Array(t.length+n.length);i.set(t),i.set(n,t.length),this.setBuffer(i)}else this.setBuffer(e)}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered){return this.clone().decode(e)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){const t=this.clone();yield*t.decodeMulti(e)}else try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered){return this.clone().decodeAsync(e)}try{this.entered=!0;let t,n=!1;for await(const i of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(i);try{t=this.doDecodeSync(),n=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return t}const{headByte:i,pos:r,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${gt(i)} at ${s} (${r} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){const n=this.clone();yield*n.decodeMultiAsync(e,t)}else try{this.entered=!0;let n=t,i=-1;for await(const r of e){if(t&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(r),n&&(i=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),0!==--i;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const n=e-128;if(0!==n){this.pushMapState(n),this.complete();continue e}t={}}else if(e<160){const n=e-144;if(0!==n){this.pushArrayState(n),this.complete();continue e}t=[]}else{const n=e-160;t=this.decodeString(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===e){const e=this.lookU8();t=this.decodeString(e,1)}else if(218===e){const e=this.lookU16();t=this.decodeString(e,2)}else if(219===e){const e=this.lookU32();t=this.decodeString(e,4)}else if(220===e){const e=this.readU16();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(221===e){const e=this.readU32();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(222===e){const e=this.readU16();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(223===e){const e=this.readU32();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(196===e){const e=this.lookU8();t=this.decodeBinary(e,1)}else if(197===e){const e=this.lookU16();t=this.decodeBinary(e,2)}else if(198===e){const e=this.lookU32();t=this.decodeBinary(e,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){const e=this.lookU8();t=this.decodeExtension(e,1)}else if(200===e){const e=this.lookU16();t=this.decodeExtension(e,2)}else{if(201!==e)throw new ct(`Unrecognized type byte: ${gt(e)}`);{const e=this.lookU32();t=this.decodeExtension(e,4)}}this.complete();const n=this.stack;for(;n.length>0;){const e=n.top();if(e.type===vt){if(e.array[e.position]=t,e.position++,e.position!==e.size)continue e;t=e.array,n.release(e)}else{if(e.type===_t){if("__proto__"===t)throw new ct("The key __proto__ is not allowed");e.key=this.mapKeyConverter(t),e.type=St;continue e}if(e.map[e.key]=t,e.readCount++,e.readCount!==e.size){e.key=null,e.type=_t;continue e}t=e.map,n.release(e)}}return t}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new ct(`Unrecognized array type byte: ${gt(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new ct(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ct(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new ct(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw At;const n=this.pos+t;let i;return i=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,n,e):ot(this.bytes,n,e),this.pos+=t+e,i}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===_t}return!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new ct(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw At;const n=this.pos+t,i=this.bytes.subarray(n,n+e);return this.pos+=t+e,i}decodeExtension(e,t){if(e>this.maxExtLength)throw new ct(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=(t=this.view,n=this.pos,4294967296*t.getUint32(n)+t.getUint32(n+4));var t,n;return this.pos+=8,e}readI64(){const e=lt(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function xt(e,t){return new Mt(t).decode(e)}var It,kt=function(){function e(){}return e.serialize=function(e,t){var n=a({systems:!1,format:"json",pretty:!0,includeMetadata:!0},t),i=this.filterEntities(e,n),r=tt.serializeEntities(i,!0),s=this.buildComponentTypeRegistry(i),o=this.serializeSceneData(e.sceneData),c={name:e.name,version:this.SERIALIZATION_VERSION,entities:r,componentTypeRegistry:s};return o&&Object.keys(o).length>0&&(c.sceneData=o),n.includeMetadata&&(c.timestamp=Date.now(),c.metadata={entityCount:r.length,componentTypeCount:s.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(c,null,2):JSON.stringify(c):mt(c)},e.deserialize=function(e,t,n){var i,r=a({strategy:"replace",preserveIds:!1},n);try{i="string"==typeof t?JSON.parse(t):xt(t)}catch(e){throw new Error("Failed to parse save data: "+e)}r.migration&&i.version!==this.SERIALIZATION_VERSION&&(i=r.migration(i.version,this.SERIALIZATION_VERSION,i));var s=r.componentRegistry||this.getGlobalComponentRegistry();"replace"===r.strategy&&e.destroyAllEntities();for(var c,u=o(tt.deserializeEntities(i.entities,s,(function(){return e.identifierPool.checkOut()}),r.preserveIds||!1,e));!(c=u()).done;){var h=c.value;e.addEntity(h,!0),this.addChildrenRecursively(h,e)}e.querySystem.clearCache(),e.clearSystemEntityCaches(),i.sceneData&&this.deserializeSceneData(i.sceneData,e.sceneData)},e.addChildrenRecursively=function(e,t){for(var n,i=o(e.children);!(n=i()).done;){var r=n.value;t.addEntity(r,!0),this.addChildrenRecursively(r,t)}},e.serializeSceneData=function(e){for(var t,n={},i=o(e);!(t=i()).done;){var r=t.value,s=r[0],a=r[1];n[s]=this.serializeValue(a)}return n},e.deserializeSceneData=function(e,t){t.clear();for(var n=0,i=Object.entries(e);n<i.length;n++){var r=i[n],s=r[0],o=r[1];t.set(s,this.deserializeValue(o))}},e.serializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if(Array.isArray(e))return e.map((function(e){return t.serializeValue(e)}));if("object"===n){var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=this.serializeValue(e[r]));return i}},e.deserializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if("object"===n&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((function(e){return t.deserializeValue(e)}));if("object"===n){var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=this.deserializeValue(e[r]));return i}return e},e.filterEntities=function(e,t){var n=Array.from(e.entities.buffer);if(t.components&&t.components.length>0){var i=new Set(t.components);return n.filter((function(e){return Array.from(e.components).some((function(e){return i.has(e.constructor)}))}))}return n},e.buildComponentTypeRegistry=function(e){for(var t,n=new Map,i=o(e);!(t=i()).done;)for(var r,s=o(t.value.components);!(r=s()).done;){var a=r.value,c=U(a.constructor),u=Xe(a);u&&!n.has(c)&&n.set(c,u.options.version)}return Array.from(n.entries()).map((function(e){return{typeName:e[0],version:e[1]}}))},e.getGlobalComponentRegistry=function(){return ge.getAllComponentNames()},e.validate=function(e){var t=[];try{var n=JSON.parse(e);return n.version||t.push("Missing version field"),n.entities&&Array.isArray(n.entities)||t.push("Missing or invalid entities field"),n.componentTypeRegistry&&Array.isArray(n.componentTypeRegistry)||t.push("Missing or invalid componentTypeRegistry field"),{valid:0===t.length,version:n.version,errors:t.length>0?t:void 0}}catch(e){return{valid:!1,errors:["JSON parse error: "+e]}}},e.getInfo=function(e){try{var t,n=JSON.parse(e);return{name:n.name,version:n.version,timestamp:n.timestamp,entityCount:(null===(t=n.metadata)||void 0===t?void 0:t.entityCount)||n.entities.length,componentTypeCount:n.componentTypeRegistry.length}}catch(e){return null}},e}();kt.SERIALIZATION_VERSION=1,exports.ChangeOperation=void 0,(It=exports.ChangeOperation||(exports.ChangeOperation={})).EntityAdded="entity_added",It.EntityRemoved="entity_removed",It.EntityUpdated="entity_updated",It.ComponentAdded="component_added",It.ComponentRemoved="component_removed",It.ComponentUpdated="component_updated",It.SceneDataUpdated="scene_data_updated";var Dt=function(){function e(){}return e.createSnapshot=function(e,t){for(var n,i=a({deepComponentComparison:!0,trackSceneData:!0,compressSnapshot:!1},t),r={version:++this.snapshotVersion,entityIds:new Set,entities:new Map,components:new Map,sceneData:new Map},s=o(e.entities.buffer);!(n=s()).done;){var c,u=n.value;if(r.entityIds.add(u.id),r.entities.set(u.id,{name:u.name,tag:u.tag,active:u.active,enabled:u.enabled,updateOrder:u.updateOrder,parentId:null===(c=u.parent)||void 0===c?void 0:c.id}),i.deepComponentComparison){for(var h,l=new Map,f=o(u.components);!(h=f()).done;){var d=h.value,p=et.serialize(d);p&&l.set(p.type,JSON.stringify(p.data))}l.size>0&&r.components.set(u.id,l)}}if(i.trackSceneData)for(var y,m=o(e.sceneData);!(y=m()).done;){var g=y.value,v=g[0],_=g[1];r.sceneData.set(v,JSON.stringify(_))}return r},e.computeIncremental=function(e,t,n){for(var i,r=a({deepComponentComparison:!0,trackSceneData:!0},n),s={version:++this.snapshotVersion,timestamp:Date.now(),sceneName:e.name,baseVersion:t.version,entityChanges:[],componentChanges:[],sceneDataChanges:[]},c=new Set,u=o(e.entities.buffer);!(i=u()).done;){var h=i.value;if(c.add(h.id),t.entityIds.has(h.id)){var l,f,d=t.entities.get(h.id);if(d.name!==h.name||d.tag!==h.tag||d.active!==h.active||d.enabled!==h.enabled||d.updateOrder!==h.updateOrder||d.parentId!==(null===(l=h.parent)||void 0===l?void 0:l.id))s.entityChanges.push({operation:exports.ChangeOperation.EntityUpdated,entityId:h.id,entityData:{name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder,parentId:null===(f=h.parent)||void 0===f?void 0:f.id}});r.deepComponentComparison&&this.detectComponentChanges(h,t,s.componentChanges)}else{var p;s.entityChanges.push({operation:exports.ChangeOperation.EntityAdded,entityId:h.id,entityName:h.name,entityData:{id:h.id,name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder,parentId:null===(p=h.parent)||void 0===p?void 0:p.id,components:[],children:[]}});for(var y,m=o(h.components);!(y=m()).done;){var g=y.value,v=et.serialize(g);v&&s.componentChanges.push({operation:exports.ChangeOperation.ComponentAdded,entityId:h.id,componentType:v.type,componentData:v})}}}for(var _,S=o(t.entityIds);!(_=S()).done;){var C=_.value;c.has(C)||s.entityChanges.push({operation:exports.ChangeOperation.EntityRemoved,entityId:C})}return r.trackSceneData&&this.detectSceneDataChanges(e,t,s.sceneDataChanges),s},e.detectComponentChanges=function(e,t,n){for(var i,r=t.components.get(e.id),s=new Map,a=o(e.components);!(i=a()).done;){var c=i.value,u=et.serialize(c);u&&s.set(u.type,u)}for(var h,l=o(s);!(h=l()).done;){var f=h.value,d=f[0],p=f[1],y=JSON.stringify(p.data);r&&r.has(d)?r.get(d)!==y&&n.push({operation:exports.ChangeOperation.ComponentUpdated,entityId:e.id,componentType:d,componentData:p}):n.push({operation:exports.ChangeOperation.ComponentAdded,entityId:e.id,componentType:d,componentData:p})}if(r)for(var m,g=o(r.keys());!(m=g()).done;){var v=m.value;s.has(v)||n.push({operation:exports.ChangeOperation.ComponentRemoved,entityId:e.id,componentType:v})}},e.detectSceneDataChanges=function(e,t,n){for(var i,r=new Set,s=o(e.sceneData);!(i=s()).done;){var a=i.value,c=a[0],u=a[1];r.add(c);var h=JSON.stringify(u),l=t.sceneData.get(c);l&&l===h||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:c,value:u})}for(var f,d=o(t.sceneData.keys());!(f=d()).done;){var p=f.value;r.has(p)||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:p,value:void 0,deleted:!0})}},e.applyIncremental=function(e,t,n){for(var i,r=o(t.entityChanges);!(i=r()).done;){var s=i.value;switch(s.operation){case exports.ChangeOperation.EntityAdded:this.applyEntityAdded(e,s);break;case exports.ChangeOperation.EntityRemoved:this.applyEntityRemoved(e,s);break;case exports.ChangeOperation.EntityUpdated:this.applyEntityUpdated(e,s)}}for(var a,c=o(t.componentChanges);!(a=c()).done;){var u=a.value;switch(u.operation){case exports.ChangeOperation.ComponentAdded:this.applyComponentAdded(e,u,n);break;case exports.ChangeOperation.ComponentRemoved:this.applyComponentRemoved(e,u,n);break;case exports.ChangeOperation.ComponentUpdated:this.applyComponentUpdated(e,u,n)}}for(var h,l=o(t.sceneDataChanges);!(h=l()).done;){var f=h.value;f.deleted?e.sceneData.delete(f.key):e.sceneData.set(f.key,f.value)}},e.applyEntityAdded=function(e,t){var n,i;if(t.entityData){var r=new Ce(t.entityName||"Entity",t.entityId);r.tag=t.entityData.tag||0,r.active=null===(n=t.entityData.active)||void 0===n||n,r.enabled=null===(i=t.entityData.enabled)||void 0===i||i,r.updateOrder=t.entityData.updateOrder||0,e.addEntity(r)}},e.applyEntityRemoved=function(e,t){var n=e.entities.findEntityById(t.entityId);n&&n.destroy()},e.applyEntityUpdated=function(e,t){if(t.entityData){var n=e.entities.findEntityById(t.entityId);if(n)if(void 0!==t.entityData.name&&(n.name=t.entityData.name),void 0!==t.entityData.tag&&(n.tag=t.entityData.tag),void 0!==t.entityData.active&&(n.active=t.entityData.active),void 0!==t.entityData.enabled&&(n.enabled=t.entityData.enabled),void 0!==t.entityData.updateOrder&&(n.updateOrder=t.entityData.updateOrder),void 0!==t.entityData.parentId){var i=e.entities.findEntityById(t.entityData.parentId);i&&n.parent!==i&&(n.parent&&n.parent.removeChild(n),i.addChild(n))}else n.parent&&n.parent.removeChild(n)}},e.applyComponentAdded=function(e,t,n){if(t.componentData){var i=e.entities.findEntityById(t.entityId);if(i){var r=et.deserialize(t.componentData,n);r&&i.addComponent(r)}}},e.applyComponentRemoved=function(e,t,n){var i=e.entities.findEntityById(t.entityId);if(i){var r=n.get(t.componentType);r&&i.removeComponentByType(r)}},e.applyComponentUpdated=function(e,t,n){if(t.componentData){var i=e.entities.findEntityById(t.entityId);if(i){var r=n.get(t.componentType);if(r){i.removeComponentByType(r);var s=et.deserialize(t.componentData,n);s&&i.addComponent(s)}}}},e.serializeIncremental=function(e,t){var n=a({format:"json",pretty:!1},t);return"binary"===n.format?mt(e):n.pretty?JSON.stringify(e,null,2):JSON.stringify(e)},e.deserializeIncremental=function(e){return"string"==typeof e?JSON.parse(e):xt(e)},e.getIncrementalSize=function(e,t){void 0===t&&(t="json");var n=this.serializeIncremental(e,{format:t});return"string"==typeof n?"undefined"!=typeof Blob?new Blob([n]).size:"undefined"!=typeof Buffer?Buffer.byteLength(n,"utf8"):(new TextEncoder).encode(n).length:n.length},e.getIncrementalStats=function(e){return{totalChanges:e.entityChanges.length+e.componentChanges.length+e.sceneDataChanges.length,entityChanges:e.entityChanges.length,componentChanges:e.componentChanges.length,sceneDataChanges:e.sceneDataChanges.length,addedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityAdded})).length,removedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityRemoved})).length,updatedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityUpdated})).length,addedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentAdded})).length,removedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentRemoved})).length,updatedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentUpdated})).length}},e.resetVersion=function(){this.snapshotVersion=0},e}();Dt.snapshotVersion=0;var Rt,Ot=Y("ServiceContainer");exports.ServiceLifetime=void 0,(Rt=exports.ServiceLifetime||(exports.ServiceLifetime={})).Singleton="singleton",Rt.Transient="transient";var zt=function(){function e(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}var t=e.prototype;return t.registerSingleton=function(e,t){this._services.has(e)?Ot.warn("Service "+e.name+" is already registered"):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Singleton}),Ot.debug("Registered singleton service: "+e.name))},t.registerTransient=function(e,t){this._services.has(e)?Ot.warn("Service "+e.name+" is already registered"):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Transient}),Ot.debug("Registered transient service: "+e.name))},t.registerInstance=function(e,t){if(this._services.has(e))Ot.warn("Service "+e.name+" is already registered");else{if(this._services.set(e,{type:e,instance:t,lifetime:exports.ServiceLifetime.Singleton}),D(e)){var n,i=R(e),r=null!==(n=null==i?void 0:i.priority)&&void 0!==n?n:0;this._updatableServices.push({instance:t,priority:r}),this._updatableServices.sort((function(e,t){return e.priority-t.priority})),Ot.debug("Service "+e.name+" is updatable (priority: "+r+"), added to update list")}Ot.debug("Registered service instance: "+e.name)}},t.resolve=function(e){var t=this._services.get(e);if(!t)throw new Error("Service "+e.name+" is not registered");if(this._resolving.has(e)){var n=Array.from(this._resolving).map((function(e){return e.name})).join(" -> ");throw new Error("Circular dependency detected: "+n+" -> "+e.name)}if(t.lifetime===exports.ServiceLifetime.Singleton&&t.instance)return t.instance;this._resolving.add(e);try{var i;if(i=t.factory?t.factory(this):new t.type,t.lifetime===exports.ServiceLifetime.Singleton&&(t.instance=i,D(t.type))){var r,s=R(t.type),o=null!==(r=null==s?void 0:s.priority)&&void 0!==r?r:0;this._updatableServices.push({instance:i,priority:o}),this._updatableServices.sort((function(e,t){return e.priority-t.priority})),Ot.debug("Service "+e.name+" is updatable (priority: "+o+"), added to update list")}return i}finally{this._resolving.delete(e)}},t.tryResolve=function(e){try{return this.resolve(e)}catch(e){return null}},t.isRegistered=function(e){return this._services.has(e)},t.unregister=function(e){var t=this._services.get(e);if(!t)return!1;if(t.instance){var n=this._updatableServices.findIndex((function(e){return e.instance===t.instance}));-1!==n&&this._updatableServices.splice(n,1),t.instance.dispose()}return this._services.delete(e),Ot.debug("Unregistered service: "+e.name),!0},t.clear=function(){for(var e,t=o(this._services);!(e=t()).done;){var n=e.value[1];n.instance&&n.instance.dispose()}this._services.clear(),this._updatableServices=[],Ot.debug("Cleared all services")},t.getRegisteredServices=function(){return Array.from(this._services.keys())},t.updateAll=function(e){for(var t,n=o(this._updatableServices);!(t=n()).done;){t.value.instance.update(e)}},t.getUpdatableCount=function(){return this._updatableServices.length},t.getAll=function(){for(var e,t=[],n=o(this._services.values());!(e=n()).done;){var i=e.value;i.instance&&t.push(i.instance)}return t},e}(),Bt=function(){function e(e){var t=this;this.name="",this.sceneData=new Map,this._didSceneBegin=!1,this.entities=new Ee(this),this.identifierPool=new be,this.componentStorageManager=new _e,this.querySystem=new Ue,this.eventSystem=new He,this.referenceTracker=new X,this._services=new zt,this.logger=Y("Scene"),this._performanceMonitor=(null==e?void 0:e.performanceMonitor)||new O,null!=e&&e.name&&(this.name=e.name),Ce.eventBus||(Ce.eventBus=new Ge(!1)),Ce.eventBus&&Ce.eventBus.onComponentAdded((function(e){t.eventSystem.emitSync("component:added",e)}))}var t=e.prototype;return t.getSystem=function(e){return this._services.tryResolve(e)},t.initialize=function(){},t.onStart=function(){},t.unload=function(){},t.begin=function(){this._didSceneBegin=!0,this.onStart()},t.end=function(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this._services.clear(),this.unload()},t.update=function(){ue.getInstance().update(),this.entities.updateLists();for(var e,t=this.systems,n=o(t);!(e=n()).done;){var i=e.value;if(i.enabled)try{i.update()}catch(e){this.logger.error("Error in system "+i.constructor.name+".update():",e)}}for(var r,s=o(t);!(r=s()).done;){var a=r.value;if(a.enabled)try{a.lateUpdate()}catch(e){this.logger.error("Error in system "+a.constructor.name+".lateUpdate():",e)}}},t.createEntity=function(e){var t=new Ce(e,this.identifierPool.checkOut());return this.eventSystem.emitSync("entity:created",{entityName:e,entity:t,scene:this}),this.addEntity(t)},t.clearSystemEntityCaches=function(){for(var e,t=o(this.systems);!(e=t()).done;){e.value.clearEntityCache()}},t.addEntity=function(e,t){return void 0===t&&(t=!1),this.entities.add(e),e.scene=this,this.querySystem.addEntity(e,t),t||this.clearSystemEntityCaches(),this.eventSystem.emitSync("entity:added",{entity:e,scene:this}),e},t.createEntities=function(e,t){void 0===t&&(t="Entity");for(var n=[],i=0;i<e;i++){var r=new Ce(t+"_"+i,this.identifierPool.checkOut());r.scene=this,n.push(r)}for(var s=0,o=n;s<o.length;s++){var a=o[s];this.entities.add(a)}return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:e}),n},t.destroyEntities=function(e){if(0!==e.length){for(var t,n=o(e);!(t=n()).done;){t.value._isDestroyed=!0}for(var i,r=o(e);!(i=r()).done;){i.value.removeAllComponents()}for(var s,a=o(e);!(s=a()).done;){var c=s.value;this.entities.remove(c),this.querySystem.removeEntity(c)}this.querySystem.clearCache(),this.clearSystemEntityCaches()}},t.destroyAllEntities=function(){this.entities.removeAllEntities(),this.querySystem.setEntities([])},t.findEntity=function(e){return this.entities.findEntity(e)},t.findEntityById=function(e){return this.entities.findEntityById(e)},t.findEntitiesByTag=function(e){for(var t,n=[],i=o(this.entities.buffer);!(t=i()).done;){var r=t.value;r.tag===e&&n.push(r)}return n},t.getEntityByName=function(e){return this.findEntity(e)},t.getEntitiesByTag=function(e){return this.findEntitiesByTag(e)},t.queryAll=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments)},t.queryAny=function(){var e;return(e=this.querySystem).queryAny.apply(e,arguments)},t.queryNone=function(){var e;return(e=this.querySystem).queryNone.apply(e,arguments)},t.query=function(){return new Ye},t.addEntityProcessor=function(e){var t,n;if("function"==typeof e){if(n=e,this._services.isRegistered(n)){var i=this._services.resolve(n);return this.logger.debug("System "+n.name+" already registered, returning existing instance"),i}t=x(n)?I(n,this._services):new n}else if(n=(t=e).constructor,this._services.isRegistered(n)){var r=this._services.resolve(n);return r===t?(this.logger.debug("System "+n.name+" instance already registered, returning it"),t):(this.logger.warn("Attempting to register a different instance of "+n.name+", but type is already registered. Returning existing instance."),r)}t.scene=this,t.setPerformanceMonitor(this._performanceMonitor);var s=W(n);return void 0!==(null==s?void 0:s.updateOrder)&&t.setUpdateOrder(s.updateOrder),void 0!==(null==s?void 0:s.enabled)&&(t.enabled=s.enabled),this._services.registerInstance(n,t),k(t,this._services),t.initialize(),this.logger.debug("System "+n.name+" registered and initialized"),t},t.registerSystems=function(e){for(var t,n=[],i=o(e);!(t=i()).done;){var r=t.value,s=this.addEntityProcessor(r);n.push(s)}return n},t.addSystem=function(e){return this.addEntityProcessor(e)},t.removeEntityProcessor=function(e){var t=e.constructor;this._services.unregister(t),e.reset()},t.removeSystem=function(e){this.removeEntityProcessor(e)},t.getEntityProcessor=function(e){return this._services.tryResolve(e)},t.getStats=function(){return{entityCount:this.entities.count,processorCount:this.systems.length,componentStorageStats:this.componentStorageManager.getAllStats()}},t.getDebugInfo=function(){var e=this.systems;return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:e.length,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((function(e){return{name:e.name,id:e.id,componentCount:e.components.length,componentTypes:e.components.map((function(e){return H(e)}))}})),processors:e.map((function(e){var t;return{name:j(e),updateOrder:e.updateOrder,entityCount:(null===(t=e._entities)||void 0===t?void 0:t.length)||0}})),componentStats:this.componentStorageManager.getAllStats()}},t.serialize=function(e){return kt.serialize(this,e)},t.deserialize=function(e,t){kt.deserialize(this,e,t)},t.createIncrementalSnapshot=function(e){this._incrementalBaseSnapshot=Dt.createSnapshot(this,e)},t.serializeIncremental=function(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return Dt.computeIncremental(this,this._incrementalBaseSnapshot,e)},t.applyIncremental=function(e,t){var n="string"==typeof e||e instanceof Uint8Array?Dt.deserializeIncremental(e):e,i=t||ge.getAllComponentNames();Dt.applyIncremental(this,n,i)},t.updateIncrementalSnapshot=function(e){this.createIncrementalSnapshot(e)},t.clearIncrementalSnapshot=function(){this._incrementalBaseSnapshot=void 0},t.hasIncrementalSnapshot=function(){return void 0!==this._incrementalBaseSnapshot},s(e,[{key:"systems",get:function(){for(var e,t=[],n=o(this._services.getAll());!(e=n()).done;){var i=e.value;i instanceof Te&&t.push(i)}return t.sort((function(e,t){return e.updateOrder-t.updateOrder})),t}},{key:"services",get:function(){return this._services}}])}(),Pt=function(){function e(){this.scene=new Bt}var t=e.prototype;return t.named=function(e){return this.scene.name=e,this},t.withEntity=function(e){return this.scene.addEntity(e),this},t.withEntityBuilder=function(e){var t=e(new we(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(t),this},t.withEntities=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i];this.scene.addEntity(s)}return this},t.withSystem=function(e){return this.scene.addSystem(e),this},t.withSystems=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i];this.scene.addSystem(s)}return this},t.build=function(){return this.scene},e}(),Lt=function(){function e(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.component=i(e,n)}var t=e.prototype;return t.set=function(e,t){return this.component[e]=t,this},t.configure=function(e){return e(this.component),this},t.setIf=function(e,t,n){return e&&(this.component[t]=n),this},t.build=function(){return this.component},e}(),Nt=function(){function e(e){this.entities=e}var t=e.prototype;return t.addComponent=function(e){for(var t,n=o(this.entities);!(t=n()).done;){t.value.addComponent(e)}return this},t.removeComponent=function(e){for(var t,n=o(this.entities);!(t=n()).done;){t.value.removeComponentByType(e)}return this},t.setActive=function(e){for(var t,n=o(this.entities);!(t=n()).done;){t.value.active=e}return this},t.setTag=function(e){for(var t,n=o(this.entities);!(t=n()).done;){t.value.tag=e}return this},t.forEach=function(e){return this.entities.forEach(e),this},t.filter=function(t){return new e(this.entities.filter(t))},t.toArray=function(){return this.entities.slice()},t.count=function(){return this.entities.length},e}(),Wt=function(){function e(e,t,n){this.scene=e,this.querySystem=t,this.eventSystem=n}var t=e.prototype;return t.createEntity=function(){return new we(this.scene,this.scene.componentStorageManager)},t.createScene=function(){return new Pt},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return i(Lt,[e].concat(n))},t.query=function(){return new Fe(this.querySystem)},t.find=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments).entities},t.findFirst=function(){var e,t=(e=this.querySystem).queryAll.apply(e,arguments);return t.entities.length>0?t.entities[0]:null},t.findByName=function(e){return this.scene.findEntity(e)},t.findByTag=function(e){return this.scene.findEntitiesByTag(e)},t.emit=function(e,t){this.eventSystem.emitSync(e,t)},t.emitAsync=function(){var e=n(l().m((function e(t,n){return l().w((function(e){for(;;)switch(e.n){case 0:return e.n=1,this.eventSystem.emit(t,n);case 1:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),t.on=function(e,t){return this.eventSystem.on(e,t)},t.once=function(e,t){return this.eventSystem.once(e,t)},t.off=function(e,t){this.eventSystem.off(e,t)},t.batch=function(e){return new Nt(e)},t.getStats=function(){return{entityCount:this.scene.entities.count,systemCount:this.scene.systems.length,componentStats:this.scene.componentStorageManager.getAllStats(),queryStats:this.querySystem.getStats(),eventStats:this.eventSystem.getStats()}},e}();function Ut(e,t,n){return new Wt(e,t,n)}var Ft,Ht=Y("World"),jt=function(){function e(e){void 0===e&&(e={}),this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config=a({name:"World",debug:!1,maxScenes:10,autoCleanup:!0},e),this.name=this._config.name,this._createdAt=Date.now(),Ht.info("创建World: "+this.name)}var t=e.prototype;return t.createScene=function(e,t){if(this._scenes.has(e))throw new Error("Scene ID '"+e+"' 已存在于World '"+this.name+"' 中");if(this._scenes.size>=this._config.maxScenes)throw new Error("World '"+this.name+"' 已达到最大Scene数量限制: "+this._config.maxScenes);var n=t||new Bt;return"id"in n&&(n.id=e),"name"in n&&!n.name&&(n.name=e),this._scenes.set(e,n),n.initialize(),Ht.info("在World '"+this.name+"' 中创建Scene: "+e),n},t.removeScene=function(e){var t=this._scenes.get(e);return!!t&&(this._activeScenes.has(e)&&this.setSceneActive(e,!1),t.end(),this._scenes.delete(e),Ht.info("从World '"+this.name+"' 中移除Scene: "+e),!0)},t.getScene=function(e){return this._scenes.get(e)||null},t.getSceneIds=function(){return Array.from(this._scenes.keys())},t.getAllScenes=function(){return Array.from(this._scenes.values())},t.removeAllScenes=function(){for(var e=0,t=Array.from(this._scenes.keys());e<t.length;e++){var n=t[e];this.removeScene(n)}Ht.info("从World '"+this.name+"' 中移除所有Scene")},t.setSceneActive=function(e,t){var n=this._scenes.get(e);n?t?(this._activeScenes.add(e),n.begin&&n.begin(),Ht.debug("在World '"+this.name+"' 中激活Scene: "+e)):(this._activeScenes.delete(e),Ht.debug("在World '"+this.name+"' 中停用Scene: "+e)):Ht.warn("Scene '"+e+"' 不存在于World '"+this.name+"' 中")},t.isSceneActive=function(e){return this._activeScenes.has(e)},t.getActiveSceneCount=function(){return this._activeScenes.size},t.addGlobalSystem=function(e){return this._globalSystems.includes(e)||(this._globalSystems.push(e),e.initialize&&e.initialize(),Ht.debug("在World '"+this.name+"' 中添加全局System: "+e.name)),e},t.removeGlobalSystem=function(e){var t=this._globalSystems.indexOf(e);return-1!==t&&(this._globalSystems.splice(t,1),e.reset&&e.reset(),Ht.debug("从World '"+this.name+"' 中移除全局System: "+e.name),!0)},t.getGlobalSystem=function(e){for(var t,n=o(this._globalSystems);!(t=n()).done;){var i=t.value;if(i instanceof e)return i}return null},t.start=function(){if(!this._isActive){this._isActive=!0;for(var e,t=o(this._globalSystems);!(e=t()).done;){var n=e.value;n.initialize&&n.initialize()}Ht.info("启动World: "+this.name)}},t.stop=function(){if(this._isActive){for(var e,t=o(this._activeScenes);!(e=t()).done;){var n=e.value;this.setSceneActive(n,!1)}for(var i,r=o(this._globalSystems);!(i=r()).done;){var s=i.value;s.reset&&s.reset()}this._isActive=!1,Ht.info("停止World: "+this.name)}},t.updateGlobalSystems=function(){if(this._isActive)for(var e,t=o(this._globalSystems);!(e=t()).done;){var n=e.value;n.update&&n.update()}},t.updateScenes=function(){if(this._isActive){for(var e,t=o(this._activeScenes);!(e=t()).done;){var n=e.value,i=this._scenes.get(n);i&&i.update&&i.update()}this._config.autoCleanup&&this.shouldAutoCleanup()&&this.cleanup()}},t.destroy=function(){Ht.info("销毁World: "+this.name),this.stop();for(var e=0,t=Array.from(this._scenes.keys());e<t.length;e++){var n=t[e];this.removeScene(n)}for(var i,r=o(this._globalSystems);!(i=r()).done;){var s=i.value;s.destroy?s.destroy():s.reset&&s.reset()}this._globalSystems.length=0,this._scenes.clear(),this._activeScenes.clear()},t.getStatus=function(){var e=this;return{name:this.name,isActive:this._isActive,sceneCount:this._scenes.size,activeSceneCount:this._activeScenes.size,globalSystemCount:this._globalSystems.length,createdAt:this._createdAt,config:a({},this._config),scenes:Array.from(this._scenes.keys()).map((function(t){var n;return{id:t,isActive:e._activeScenes.has(t),name:(null===(n=e._scenes.get(t))||void 0===n?void 0:n.name)||t}}))}},t.getStats=function(){for(var e,t={totalEntities:0,totalSystems:this._globalSystems.length,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}},n=o(this._scenes.values());!(e=n()).done;){var i=e.value;i.entities&&(t.totalEntities+=i.entities.count),i.systems&&(t.totalSystems+=i.systems.length)}return t},t.shouldAutoCleanup=function(){for(var e,t=Date.now(),n=o(this._scenes);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];if(!this._activeScenes.has(r)&&s.entities&&0===s.entities.count&&t-this._createdAt>3e5)return!0}return!1},t.cleanup=function(){for(var e=Array.from(this._scenes.keys()),t=Date.now(),n=0,i=e;n<i.length;n++){var r=i[n],s=this._scenes.get(r);s&&!this._activeScenes.has(r)&&s.entities&&0===s.entities.count&&t-this._createdAt>3e5&&(this.removeScene(r),Ht.debug("自动清理空Scene: "+r+" from World "+this.name))}},s(e,[{key:"isActive",get:function(){return this._isActive}},{key:"sceneCount",get:function(){return this._scenes.size}},{key:"createdAt",get:function(){return this._createdAt}}])}(),qt=function(){function e(){this._nextScene=null,this._ecsAPI=null,this._logger=Y("SceneManager"),this._defaultWorld=new jt({name:"__default__"}),this._defaultWorld.start()}var t=e.prototype;return t.setSceneChangedCallback=function(e){this._onSceneChangedCallback=e},t.setScene=function(t){return this._defaultWorld.removeAllScenes(),this._defaultWorld.createScene(e.DEFAULT_SCENE_ID,t),this._defaultWorld.setSceneActive(e.DEFAULT_SCENE_ID,!0),t.querySystem&&t.eventSystem?this._ecsAPI=Ut(t,t.querySystem,t.eventSystem):this._ecsAPI=null,_.sceneChanged(),this._onSceneChangedCallback&&this._onSceneChangedCallback(),this._logger.info("Scene changed to: "+t.name),t},t.loadScene=function(e){this._nextScene=e,this._logger.info("Scheduled scene load: "+e.name)},t.update=function(){this._nextScene&&(this.setScene(this._nextScene),this._nextScene=null),this._defaultWorld.updateGlobalSystems(),this._defaultWorld.updateScenes()},t.destroy=function(){this._logger.info("SceneManager destroying"),this._defaultWorld.destroy(),this._nextScene=null,this._ecsAPI=null,this._logger.info("SceneManager destroyed")},t.dispose=function(){this.destroy()},s(e,[{key:"currentScene",get:function(){return this._defaultWorld.getScene(e.DEFAULT_SCENE_ID)}},{key:"api",get:function(){return this._ecsAPI}},{key:"hasScene",get:function(){return null!==this._defaultWorld.getScene(e.DEFAULT_SCENE_ID)}},{key:"hasPendingScene",get:function(){return null!==this._nextScene}}])}();qt.DEFAULT_SCENE_ID="__main__",exports.DebugConfigService=function(){function e(){this._config={enabled:!1,websocketUrl:"",debugFrameRate:30,autoReconnect:!0,channels:{entities:!0,systems:!0,performance:!0,components:!0,scenes:!0}}}var t=e.prototype;return t.setConfig=function(e){this._config=e},t.getConfig=function(){return this._config},t.isEnabled=function(){return this._config.enabled},t.dispose=function(){},e}(),exports.DebugConfigService=m([A(),v("design:paramtypes",[])],exports.DebugConfigService),exports.DebugManager=function(){function e(e,t,n){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.originalConsole={log:console.log.bind(console),debug:console.debug.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},this.config=n.getConfig(),this.sceneManager=e,this.performanceMonitor=t,this.entityCollector=new se,this.systemCollector=new oe,this.performanceCollector=new ae,this.componentCollector=new he,this.sceneCollector=new fe,this.webSocketManager=new de(this.config.websocketUrl,!1!==this.config.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));var i=this.config.debugFrameRate||30;this.sendInterval=1e3/i,this.interceptConsole(),this.start()}var t=e.prototype;return t.start=function(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())},t.stop=function(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())},t.interceptConsole=function(){var e=this;console.log=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("info",e.formatLogMessage(i)),(t=e.originalConsole).log.apply(t,i)},console.debug=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("debug",e.formatLogMessage(i)),(t=e.originalConsole).debug.apply(t,i)},console.info=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("info",e.formatLogMessage(i)),(t=e.originalConsole).info.apply(t,i)},console.warn=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("warn",e.formatLogMessage(i)),(t=e.originalConsole).warn.apply(t,i)},console.error=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("error",e.formatLogMessage(i)),(t=e.originalConsole).error.apply(t,i)}},t.formatLogMessage=function(e){var t=this;return e.map((function(e){if("string"==typeof e)return e;if(e instanceof Error)return e.name+": "+e.message;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{return t.safeStringify(e,6)}catch(t){return Object.prototype.toString.call(e)}return String(e)})).join(" ")},t.safeStringify=function(e,t){void 0===t&&(t=6);var n=new WeakSet,i=function(e,r){if(null===e)return null;if(void 0!==e){if("object"!=typeof e)return e;if(r>=t)return"[Max Depth Reached]";if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e)){var s=e.map((function(e){return i(e,r+1)}));return n.delete(e),s}var o={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&(o[a]=i(e[a],r+1));return n.delete(e),o}};return JSON.stringify(i(e,0))},t.sendLog=function(e,t){if(this.webSocketManager.getConnectionStatus())try{this.webSocketManager.send({type:"log",data:{level:e,message:t,timestamp:(new Date).toISOString()}})}catch(e){}},t.updateConfig=function(e){this.config=e;var t=e.debugFrameRate||30;this.sendInterval=1e3/t,this.webSocketManager&&e.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new de(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())},t.update=function(e){if(this.isRunning&&this.config.enabled){this.frameCounter++;var t=Date.now();t-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=t)}},t.onSceneChanged=function(){this.isRunning&&this.config.enabled&&this.sendDebugData()},t.handleMessage=function(e){try{switch(e.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":e.config&&this.updateConfig(a({},this.config,e.config));break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(e);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(e);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(e);break;case"get_entity_details":this.handleGetEntityDetailsRequest(e);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(t){e.requestId&&this.webSocketManager.send({type:"error_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleExpandLazyObjectRequest=function(e){try{var t=e.entityId,n=e.componentIndex,i=e.propertyPath,r=e.requestId;if(void 0===t||void 0===n||!i)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,error:"缺少必要参数"});var s=this.sceneManager.currentScene,o=this.entityCollector.expandLazyObject(t,n,i,s);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,data:o})}catch(t){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetComponentPropertiesRequest=function(e){try{var t=e.entityId,n=e.componentIndex,i=e.requestId;if(void 0===t||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:i,error:"缺少必要参数"});var r=this.sceneManager.currentScene,s=this.entityCollector.getComponentProperties(t,n,r);this.webSocketManager.send({type:"get_component_properties_response",requestId:i,data:s})}catch(t){this.webSocketManager.send({type:"get_component_properties_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetRawEntityListRequest=function(e){try{var t=e.requestId,n=this.sceneManager.currentScene,i=this.entityCollector.getRawEntityList(n);this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t,data:i})}catch(t){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetEntityDetailsRequest=function(e){try{var t=e.entityId,n=e.requestId;if(void 0===t)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});var i=this.sceneManager.currentScene,r=this.entityCollector.getEntityDetails(t,i);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:r})}catch(t){this.webSocketManager.send({type:"get_entity_details_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleMemorySnapshotRequest=function(){try{var e=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:e})}catch(e){this.webSocketManager.send({type:"memory_snapshot_error",error:e instanceof Error?e.message:"内存快照捕获失败"})}},t.captureMemorySnapshot=function(){var e=Date.now(),t=this.collectBaseMemoryInfo(),n=this.sceneManager.currentScene,i=this.entityCollector.collectEntityDataWithMemory(n),r=null!=n&&n.entities?this.collectComponentMemoryStats(n.entities):{totalMemory:0,componentTypes:0,totalInstances:0,breakdown:[]},s=this.collectSystemMemoryStats(),o=this.collectPoolMemoryStats(),a=this.collectPerformanceStats(),c=i.entitiesPerArchetype.reduce((function(e,t){return e+t.memory}),0);return{timestamp:e,version:"2.0",summary:{totalEntities:i.totalEntities,totalMemoryUsage:t.usedMemory,totalMemoryLimit:t.totalMemory,memoryUtilization:t.usedMemory/t.totalMemory*100,gcCollections:t.gcCollections,entityMemory:c,componentMemory:r.totalMemory,systemMemory:s.totalMemory,poolMemory:o.totalMemory},baseMemory:t,entities:{totalMemory:c,entityCount:i.totalEntities,archetypes:i.entitiesPerArchetype,largestEntities:i.topEntitiesByComponents},components:r,systems:s,pools:o,performance:a}},t.collectBaseMemoryInfo=function(){var e={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null,detailedMemory:void 0};try{var t=performance;if(t.memory){var n=t.memory;e.totalMemory=n.jsHeapSizeLimit||536870912,e.usedMemory=n.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,e.heapInfo={totalJSHeapSize:n.totalJSHeapSize||0,usedJSHeapSize:n.usedJSHeapSize||0,jsHeapSizeLimit:n.jsHeapSizeLimit||0}}else e.totalMemory=536870912,e.freeMemory=536870912;t.measureUserAgentSpecificMemory&&t.measureUserAgentSpecificMemory().then((function(t){e.detailedMemory=t})).catch((function(){}))}catch(e){}return e},t.collectComponentMemoryStats=function(e){for(var t,n=new Map,i=0,r=new Map,s=o(e.buffer);!(t=s()).done;){var a=t.value;if(a&&!a.destroyed&&a.components)for(var c,u=o(a.components);!(c=u()).done;){var h=H(c.value);r.set(h,(r.get(h)||0)+1)}}for(var l,f=o(r.entries());!(l=f()).done;){var d=l.value,p=d[0],y=d[1],m=this.componentCollector.calculateDetailedComponentMemory(p),g=m*y;i+=g;for(var v,_=[],S=0,C=o(e.buffer);!(v=C()).done;){var w=v.value;if(w&&!w.destroyed&&w.components){for(var E,b=o(w.components);!(E=b()).done;){if(H(E.value)===p&&(_.push({entityId:w.id,entityName:w.name||"Entity_"+w.id,memory:m}),++S>=100))break}if(S>=100)break}}n.set(p,{count:y,totalMemory:g,instances:_.slice(0,10)})}var A=Array.from(n.entries()).map((function(e){var t=e[0],n=e[1];return{typeName:t,instanceCount:n.count,totalMemory:n.totalMemory,averageMemory:n.totalMemory/n.count,percentage:i>0?n.totalMemory/i*100:0,largestInstances:n.instances.sort((function(e,t){return t.memory-e.memory})).slice(0,3)}})).sort((function(e,t){return t.totalMemory-e.totalMemory}));return{totalMemory:i,componentTypes:n.size,totalInstances:Array.from(n.values()).reduce((function(e,t){return e+t.count}),0),breakdown:A}},t.collectSystemMemoryStats=function(){var e=this.sceneManager.currentScene,t=0,n=[];try{var i=null==e?void 0:e.systems;if(i)for(var r,s=new Map,a=o(i);!(r=a()).done;){var c=r.value,u=j(c),h=void 0;s.has(u)?h=s.get(u):(h=this.calculateQuickSystemSize(c),s.set(u,h)),t+=h,n.push({name:u,memory:h,enabled:!1!==c.enabled,updateOrder:c.updateOrder||0})}}catch(e){}return{totalMemory:t,systemCount:n.length,breakdown:n.sort((function(e,t){return t.memory-e.memory}))}},t.calculateQuickSystemSize=function(e){if(!e||"object"!=typeof e)return 64;var t=128;try{for(var n=Object.keys(e),i=0;i<Math.min(n.length,15);i++){var r=n[i];if("entities"!==r&&"scene"!==r&&"constructor"!==r){var s=e[r];t+=2*r.length,"string"==typeof s?t+=Math.min(2*s.length,100):"number"==typeof s?t+=8:"boolean"==typeof s?t+=4:Array.isArray(s)?t+=40+Math.min(8*s.length,200):"object"==typeof s&&null!==s&&(t+=64)}}}catch(e){return 128}return Math.max(t,64)},t.collectPoolMemoryStats=function(){var e=0,t=[];try{for(var n,i=o(ue.getInstance().getPoolStats().entries());!(n=i()).done;){var r=n.value,s=r[0],a=r[1],c=32*a.maxSize;e+=c,t.push({typeName:s,maxSize:a.maxSize,currentSize:a.currentSize||0,estimatedMemory:c,utilization:a.currentSize?a.currentSize/a.maxSize*100:0})}}catch(e){}try{for(var u=z.getAllPoolStats(),h=0,l=Object.entries(u);h<l.length;h++){var f=l[h],d=f[0],p=f[1];e+=p.estimatedMemoryUsage,t.push({typeName:"Pool_"+d,maxSize:p.maxSize,currentSize:p.size,estimatedMemory:p.estimatedMemoryUsage,utilization:p.size/p.maxSize*100,hitRate:100*p.hitRate})}}catch(e){}return{totalMemory:e,poolCount:t.length,breakdown:t.sort((function(e,t){return t.estimatedMemory-e.estimatedMemory}))}},t.collectPerformanceStats=function(){try{var e;if(!this.performanceMonitor)return{enabled:!1};var t=this.performanceMonitor.getAllSystemStats(),n=this.performanceMonitor.getPerformanceWarnings();return{enabled:null!==(e=this.performanceMonitor.enabled)&&void 0!==e&&e,systemCount:t.size,warnings:n.slice(0,10),topSystems:Array.from(t.entries()).map((function(e){var t=e[0],n=e[1];return{name:t,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort((function(e,t){return t.averageTime-e.averageTime})).slice(0,5)}}catch(e){return{enabled:!1,error:e instanceof Error?e.message:String(e)}}},t.getDebugData=function(){var e=Date.now(),t=this.sceneManager.currentScene,n={timestamp:e,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:(null==t?void 0:t.name)||"Unknown"};return this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(t)),this.config.channels.systems&&(n.systems=this.systemCollector.collectSystemData(this.performanceMonitor,t)),this.config.channels.performance&&(n.performance=this.performanceCollector.collectPerformanceData(this.performanceMonitor)),this.config.channels.components&&(n.components=this.componentCollector.collectComponentData(t)),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData(t)),n},t.connectWebSocket=function(){var e=n(l().m((function e(){return l().w((function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.webSocketManager.connect();case 1:e.n=3;break;case 2:e.p=2,e.v;case 3:return e.a(2)}}),e,this,[[0,2]])})));return function(){return e.apply(this,arguments)}}(),t.sendDebugData=function(){if(this.webSocketManager.getConnectionStatus())try{var e={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(e)}catch(e){}},t.dispose=function(){this.stop(),console.log=this.originalConsole.log,console.debug=this.originalConsole.debug,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error},e}(),exports.DebugManager=m([A(),T(),g(0,M(qt)),g(1,M(O)),g(2,M(exports.DebugConfigService)),v("design:paramtypes",[qt,O,exports.DebugConfigService])],exports.DebugManager),exports.PluginState=void 0,(Ft=exports.PluginState||(exports.PluginState={})).NotInstalled="not_installed",Ft.Installed="installed",Ft.Failed="failed";var Gt=Y("PluginManager"),Qt=function(){function e(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}var t=e.prototype;return t.initialize=function(e,t){this._core=e,this._services=t,Gt.info("PluginManager initialized")},t.install=function(){var e=n(l().m((function e(t){var n,i;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(this._core&&this._services){e.n=1;break}throw new Error("PluginManager not initialized. Call initialize() first.");case 1:if(!this._plugins.has(t.name)){e.n=2;break}return Gt.warn("Plugin "+t.name+" is already installed"),e.a(2);case 2:return t.dependencies&&t.dependencies.length>0&&this._checkDependencies(t),n={name:t.name,version:t.version,state:exports.PluginState.NotInstalled,installedAt:Date.now()},this._metadata.set(t.name,n),e.p=3,Gt.info("Installing plugin: "+t.name+" v"+t.version),e.n=4,t.install(this._core,this._services);case 4:this._plugins.set(t.name,t),n.state=exports.PluginState.Installed,Gt.info("Plugin "+t.name+" installed successfully"),e.n=6;break;case 5:throw e.p=5,i=e.v,n.state=exports.PluginState.Failed,n.error=i instanceof Error?i.message:String(i),Gt.error("Failed to install plugin "+t.name+":",i),i;case 6:return e.a(2)}}),e,this,[[3,5]])})));return function(t){return e.apply(this,arguments)}}(),t.uninstall=function(){var e=n(l().m((function e(t){var n,i;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(n=this._plugins.get(t)){e.n=1;break}throw new Error("Plugin "+t+" is not installed");case 1:return this._checkDependents(t),e.p=2,Gt.info("Uninstalling plugin: "+t),e.n=3,n.uninstall();case 3:this._plugins.delete(t),this._metadata.delete(t),Gt.info("Plugin "+t+" uninstalled successfully"),e.n=5;break;case 4:throw e.p=4,i=e.v,Gt.error("Failed to uninstall plugin "+t+":",i),i;case 5:return e.a(2)}}),e,this,[[2,4]])})));return function(t){return e.apply(this,arguments)}}(),t.getPlugin=function(e){return this._plugins.get(e)},t.getMetadata=function(e){return this._metadata.get(e)},t.getAllPlugins=function(){return Array.from(this._plugins.values())},t.getAllMetadata=function(){return Array.from(this._metadata.values())},t.isInstalled=function(e){return this._plugins.has(e)},t._checkDependencies=function(e){if(e.dependencies){for(var t,n=[],i=o(e.dependencies);!(t=i()).done;){var r=t.value;this._plugins.has(r)||n.push(r)}if(n.length>0)throw new Error("Plugin "+e.name+" has unmet dependencies: "+n.join(", "))}},t._checkDependents=function(e){for(var t,n=[],i=o(this._plugins.values());!(t=i()).done;){var r=t.value;r.dependencies&&r.dependencies.includes(e)&&n.push(r.name)}if(n.length>0)throw new Error("Cannot uninstall plugin "+e+": it is required by "+n.join(", "))},t.dispose=function(){for(var e,t=o(Array.from(this._plugins.values()).reverse());!(e=t()).done;){var n=e.value;try{Gt.info("Disposing plugin: "+n.name),n.uninstall()}catch(e){Gt.error("Error disposing plugin "+n.name+":",e)}}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,Gt.info("PluginManager disposed")},e}(),Vt=Y("WorldManager"),Yt=function(){function e(e){void 0===e&&(e={}),this._worlds=new Map,this._activeWorlds=new Set,this._cleanupTimer=null,this._isRunning=!1,this._config=a({maxWorlds:50,autoCleanup:!0,cleanupInterval:3e4,debug:!1},e),this._isRunning=!0,Vt.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupInterval:this._config.cleanupInterval}),this.startCleanupTimer()}var t=e.prototype;return t.createWorld=function(e,t){if(!e||"string"!=typeof e||""===e.trim())throw new Error("World ID不能为空");if(this._worlds.has(e))throw new Error("World ID '"+e+"' 已存在");if(this._worlds.size>=this._config.maxWorlds)throw new Error("已达到最大World数量限制: "+this._config.maxWorlds);var n=a({name:e,debug:this._config.debug},t),i=new jt(n);return this._worlds.set(e,i),Vt.info("创建World: "+e,{config:n}),i},t.removeWorld=function(e){var t=this._worlds.get(e);return!!t&&(this._activeWorlds.has(e)&&this.setWorldActive(e,!1),t.destroy(),this._worlds.delete(e),Vt.info("移除World: "+e),!0)},t.getWorld=function(e){return this._worlds.get(e)||null},t.getWorldIds=function(){return Array.from(this._worlds.keys())},t.getAllWorlds=function(){return Array.from(this._worlds.values())},t.setWorldActive=function(e,t){var n=this._worlds.get(e);n?t?(this._activeWorlds.add(e),n.start(),Vt.debug("激活World: "+e)):(this._activeWorlds.delete(e),n.stop(),Vt.debug("停用World: "+e)):Vt.warn("World '"+e+"' 不存在")},t.isWorldActive=function(e){return this._activeWorlds.has(e)},t.updateAll=function(){if(this._isRunning)for(var e,t=o(this._activeWorlds);!(e=t()).done;){var n=e.value,i=this._worlds.get(n);i&&i.isActive&&(i.updateGlobalSystems(),i.updateScenes())}},t.getActiveWorlds=function(){for(var e,t=[],n=o(this._activeWorlds);!(e=n()).done;){var i=e.value,r=this._worlds.get(i);r&&t.push(r)}return t},t.startAll=function(){this._isRunning=!0;for(var e,t=o(this._worlds.keys());!(e=t()).done;){var n=e.value;this.setWorldActive(n,!0)}Vt.info("启动所有World")},t.stopAll=function(){this._isRunning=!1;for(var e,t=o(this._activeWorlds);!(e=t()).done;){var n=e.value;this.setWorldActive(n,!1)}Vt.info("停止所有World")},t.findWorlds=function(e){for(var t,n=[],i=o(this._worlds.values());!(t=i()).done;){var r=t.value;e(r)&&n.push(r)}return n},t.findWorldByName=function(e){for(var t,n=o(this._worlds.values());!(t=n()).done;){var i=t.value;if(i.name===e)return i}return null},t.getStats=function(){for(var e,t={totalWorlds:this._worlds.size,activeWorlds:this._activeWorlds.size,totalScenes:0,totalEntities:0,totalSystems:0,memoryUsage:0,isRunning:this._isRunning,config:a({},this._config),worlds:[]},n=o(this._worlds);!(e=n()).done;){var i=e.value,r=i[0],s=i[1],c=s.getStats();t.totalScenes+=c.totalSystems,t.totalEntities+=c.totalEntities,t.totalSystems+=c.totalSystems,t.worlds.push(a({id:r,name:s.name,isActive:this._activeWorlds.has(r),sceneCount:s.sceneCount},c))}return t},t.getDetailedStatus=function(){var e=this;return a({},this.getStats(),{worlds:Array.from(this._worlds.entries()).map((function(t){var n=t[0],i=t[1];return{id:n,isActive:e._activeWorlds.has(n),status:i.getStatus()}}))})},t.cleanup=function(){for(var e,t=[],n=o(this._worlds);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];this.shouldCleanupWorld(s)&&t.push(r)}for(var a=0,c=t;a<c.length;a++){var u=c[a];this.removeWorld(u)}return t.length>0&&Vt.debug("清理了 "+t.length+" 个World"),t.length},t.destroy=function(){Vt.info("正在销毁WorldManager..."),this.stopCleanupTimer(),this.stopAll();for(var e=0,t=Array.from(this._worlds.keys());e<t.length;e++){var n=t[e];this.removeWorld(n)}this._worlds.clear(),this._activeWorlds.clear(),this._isRunning=!1,Vt.info("WorldManager已销毁")},t.dispose=function(){this.destroy()},t.startCleanupTimer=function(){var e=this;this._config.autoCleanup&&!this._cleanupTimer&&(this._cleanupTimer=setInterval((function(){e.cleanup()}),this._config.cleanupInterval),Vt.debug("启动World清理定时器,间隔: "+this._config.cleanupInterval+"ms"))},t.stopCleanupTimer=function(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null,Vt.debug("停止World清理定时器"))},t.shouldCleanupWorld=function(e){return!e.isActive&&((0===e.sceneCount||!e.getAllScenes().some((function(e){return e.entities&&e.entities.count>0})))&&Date.now()-e.createdAt>6e5)},s(e,[{key:"worldCount",get:function(){return this._worlds.size}},{key:"activeWorldCount",get:function(){return this._activeWorlds.size}},{key:"isRunning",get:function(){return this._isRunning}},{key:"config",get:function(){return a({},this._config)}}])}(),Kt=function(){function e(t){var n,i,r,s=this;if(void 0===t&&(t={}),e._instance=this,this._config=a({debug:!0,enableEntitySystems:!0},t),this._serviceContainer=new zt,this._timerManager=new exports.TimerManager,this._serviceContainer.registerInstance(exports.TimerManager,this._timerManager),this._performanceMonitor=new O,this._serviceContainer.registerInstance(O,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new P,this._serviceContainer.registerInstance(P,this._poolManager),this._sceneManager=new qt,this._serviceContainer.registerInstance(qt,this._sceneManager),this._sceneManager.setSceneChangedCallback((function(){s._debugManager&&s._debugManager.onSceneChanged()})),this._worldManager=new Yt,this._serviceContainer.registerInstance(Yt,this._worldManager),this._pluginManager=new Qt,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(Qt,this._pluginManager),e.entitySystemsEnabled=null===(n=this._config.enableEntitySystems)||void 0===n||n,this.debug=null===(i=this._config.debug)||void 0===i||i,null!==(r=this._config.debugConfig)&&void 0!==r&&r.enabled){var o=new exports.DebugConfigService;o.setConfig(this._config.debugConfig),this._serviceContainer.registerInstance(exports.DebugConfigService,o),this._serviceContainer.registerSingleton(exports.DebugManager,(function(e){return I(exports.DebugManager,e)})),this._debugManager=this._serviceContainer.resolve(exports.DebugManager)}this.initialize()}e.create=function(t){if(void 0===t&&(t=!0),null==this._instance){var n="boolean"==typeof t?{debug:t,enableEntitySystems:!0}:t;this._instance=new e(n)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance},e.setScene=function(t){if(!this._instance)throw e._logger.warn("Core实例未创建,请先调用Core.create()"),new Error("Core实例未创建");return this._instance._sceneManager.setScene(t)},e.loadScene=function(t){this._instance?this._instance._sceneManager.loadScene(t):e._logger.warn("Core实例未创建,请先调用Core.create()")},e.update=function(t){this._instance?this._instance.updateInternal(t):e._logger.warn("Core实例未创建,请先调用Core.create()")},e.schedule=function(e,t,n,i){if(void 0===t&&(t=!1),!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");if(!i)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(e,t,n,i)},e.enableDebug=function(t){if(this._instance){if(this._instance._debugManager)this._instance._debugManager.updateConfig(t);else{var n=new exports.DebugConfigService;n.setConfig(t),this._instance._serviceContainer.registerInstance(exports.DebugConfigService,n),this._instance._serviceContainer.registerSingleton(exports.DebugManager,(function(e){return I(exports.DebugManager,e)})),this._instance._debugManager=this._instance._serviceContainer.resolve(exports.DebugManager)}this._instance._config.debugConfig=t}else e._logger.warn("Core实例未创建,请先调用Core.create()")},e.disableDebug=function(){this._instance&&(this._instance._debugManager&&(this._instance._debugManager.stop(),this._instance._debugManager=void 0),this._instance._config.debugConfig&&(this._instance._config.debugConfig.enabled=!1))},e.getDebugData=function(){var e;return null!==(e=this._instance)&&void 0!==e&&e._debugManager?this._instance._debugManager.getDebugData():null},e.installPlugin=function(){var e=n(l().m((function e(t){return l().w((function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.install(t);case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.uninstallPlugin=function(){var e=n(l().m((function e(t){return l().w((function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.uninstall(t);case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.getPlugin=function(e){if(this._instance)return this._instance._pluginManager.getPlugin(e)},e.isPluginInstalled=function(e){return!!this._instance&&this._instance._pluginManager.isInstalled(e)};var t=e.prototype;return t.initialize=function(){var t;e._logger.info("Core initialized",{debug:this.debug,entitySystemsEnabled:e.entitySystemsEnabled,debugEnabled:(null===(t=this._config.debugConfig)||void 0===t?void 0:t.enabled)||!1})},t.updateInternal=function(t){if(!e.paused){var n=this._performanceMonitor.startMonitoring("Core.update");_.update(t),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(_.deltaTime);var i=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(t),this._performanceMonitor.endMonitoring("Services.update",i,this._serviceContainer.getUpdatableCount()),this._poolManager.update(),this._sceneManager.update(),this._worldManager.updateAll(),this._performanceMonitor.endMonitoring("Core.update",n)}},e.destroy=function(){this._instance&&(this._instance._debugManager&&this._instance._debugManager.stop(),this._instance._serviceContainer.clear(),e._logger.info("Core destroyed"),this._instance=null)},s(e,null,[{key:"Instance",get:function(){return this._instance}},{key:"services",get:function(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}},{key:"worldManager",get:function(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._worldManager}},{key:"scene",get:function(){return this._instance?this._instance._sceneManager.currentScene:null}},{key:"ecsAPI",get:function(){return this._instance?this._instance._sceneManager.api:null}},{key:"isDebugEnabled",get:function(){var e;return(null===(e=this._instance)||void 0===e||null===(e=e._config.debugConfig)||void 0===e?void 0:e.enabled)||!1}}])}();Kt.paused=!1,Kt._instance=null,Kt._logger=Y("Core");var Jt=Y("DebugPlugin");exports.DebugPlugin=function(){function e(e){var t,n;this.name="@esengine/debug-plugin",this.version="1.0.0",this.worldManager=null,this.updateTimer=null,this.autoStart=null!==(t=null==e?void 0:e.autoStart)&&void 0!==t&&t,this.updateInterval=null!==(n=null==e?void 0:e.updateInterval)&&void 0!==n?n:1e3}var t=e.prototype;return t.install=function(){var e=n(l().m((function e(t,n){return l().w((function(e){for(;;)switch(e.n){case 0:this.worldManager=n.resolve(Yt),Jt.info("ECS Debug Plugin installed"),this.autoStart&&this.start();case 1:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),t.uninstall=function(){var e=n(l().m((function e(){return l().w((function(e){for(;;)switch(e.n){case 0:this.stop(),this.worldManager=null,Jt.info("ECS Debug Plugin uninstalled");case 1:return e.a(2)}}),e,this)})));return function(){return e.apply(this,arguments)}}(),t.dispose=function(){this.stop(),this.worldManager=null},t.start=function(){var e=this;this.updateTimer?Jt.warn("Debug monitoring already started"):(Jt.info("Starting debug monitoring"),this.updateTimer=setInterval((function(){e.logStats()}),this.updateInterval))},t.stop=function(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null,Jt.info("Debug monitoring stopped"))},t.getStats=function(){if(!this.worldManager)throw new Error("Plugin not installed");for(var e,t=[],n=0,i=0,r=o(this.worldManager.getAllWorlds());!(e=r()).done;)for(var s,a=o(e.value.getAllScenes());!(s=a()).done;){var c=s.value,u=this.getSceneInfo(c);t.push(u),n+=u.entityCount,i+=u.systems.length}return{scenes:t,totalEntities:n,totalSystems:i,timestamp:Date.now()}},t.getSceneInfo=function(e){var t=this,n=e.entities.buffer,i=e.systems;return{name:e.name,entityCount:n.length,systems:i.map((function(e){return t.getSystemInfo(e)})),entities:n.map((function(e){return t.getEntityInfo(e)}))}},t.getSystemInfo=function(e){var t=e.getPerformanceStats();return{name:e.constructor.name,enabled:e.enabled,updateOrder:e.updateOrder,entityCount:e.entities.length,performance:t?{avgExecutionTime:t.averageTime,maxExecutionTime:t.maxTime,totalCalls:t.executionCount}:void 0}},t.getEntityInfo=function(e){var t=this,n=e.components;return{id:e.id,name:e.name,enabled:e.enabled,tag:e.tag,componentCount:n.length,components:n.map((function(e){return t.getComponentInfo(e)}))}},t.getComponentInfo=function(e){for(var t=e.constructor.name,n={},i=0,r=Object.keys(e);i<r.length;i++){var s=r[i];if(!s.startsWith("_")){var o=e[s];"function"!=typeof o&&(n[s]=o)}}return{type:t,data:n}},t.queryEntities=function(e){if(!this.worldManager)throw new Error("Plugin not installed");for(var t,n=[],i=o(this.worldManager.getAllWorlds());!(t=i()).done;)for(var r,s=o(t.value.getAllScenes());!(r=s()).done;){var a=r.value;if(!e.sceneId||a.name===e.sceneId)for(var c,u=o(a.entities.buffer);!(c=u()).done;){var h=c.value;if((void 0===e.tag||h.tag===e.tag)&&(!e.name||h.name.includes(e.name))){if(e.hasComponent)if(!h.components.some((function(t){return t.constructor.name===e.hasComponent})))continue;n.push(this.getEntityInfo(h))}}}return n},t.logStats=function(){var e=this.getStats();Jt.info("=== ECS Debug Stats ==="),Jt.info("Total Entities: "+e.totalEntities),Jt.info("Total Systems: "+e.totalSystems),Jt.info("Scenes: "+e.scenes.length);for(var t,n=o(e.scenes);!(t=n()).done;){var i=t.value;Jt.info("\n[Scene: "+i.name+"]"),Jt.info(" Entities: "+i.entityCount),Jt.info(" Systems: "+i.systems.length);for(var r,s=o(i.systems);!(r=s()).done;){var a=r.value,c=a.performance?" | Avg: "+a.performance.avgExecutionTime.toFixed(2)+"ms, Max: "+a.performance.maxExecutionTime.toFixed(2)+"ms":"";Jt.info(" - "+a.name+" ("+(a.enabled?"enabled":"disabled")+") | Entities: "+a.entityCount+c)}}Jt.info("========================\n")},t.exportJSON=function(){var e=this.getStats();return JSON.stringify(e,null,2)},e}(),exports.DebugPlugin=m([A(),v("design:paramtypes",[Object])],exports.DebugPlugin);var $t=function(e,t){this.func=e,this.context=t},Zt=function(){function e(){this._messageTable=new Map}var t=e.prototype;return t.addObserver=function(e,t,n){var i=this._messageTable.get(e);i||(i=[],this._messageTable.set(e,i)),this.hasObserver(e,t)||i.push(new $t(t,n))},t.removeObserver=function(e,t){var n=this._messageTable.get(e);if(n){var i=n.findIndex((function(e){return e.func==t}));-1!=i&&n.splice(i,1)}},t.emit=function(e){var t=this._messageTable.get(e);if(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(var s,a=o(t);!(s=a()).done;){var c,u=s.value;(c=u.func).call.apply(c,[u.context].concat(i))}}},t.hasObserver=function(e,t){var n=this._messageTable.get(e);return!!n&&n.some((function(e){return e.func===t}))},t.removeAllObservers=function(e){void 0!==e?this._messageTable.delete(e):this._messageTable.clear()},t.dispose=function(){this._messageTable.clear()},t.getEventTypeCount=function(){return this._messageTable.size},t.getObserverCount=function(e){var t=this._messageTable.get(e);return t?t.length:0},e}(),Xt=function(){function e(){this._enabled=!1}var t=e.prototype;return t.setEnabled=function(e){this._enabled!=e&&(this._enabled=e,this._enabled?this.onEnabled():this.onDisabled())},t.onEnabled=function(){},t.onDisabled=function(){},t.update=function(){},s(e,[{key:"enabled",get:function(){return this._enabled},set:function(e){this.setEnabled(e)}}])}(),en=function(){function e(){this.entityId=null,this.id=e._idGenerator++}var t=e.prototype;return t.onAddedToEntity=function(){},t.onRemovedFromEntity=function(){},e}();en._idGenerator=0;var tn=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){this.processSystem()},t}(Te),nn=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){},t}(Te),rn=function(e){function t(t,n){var i;return(i=e.call(this,n)||this).acc=0,i.intervalRemainder=0,i.interval=t,i}u(t,e);var n=t.prototype;return n.onCheckProcessing=function(){return this.acc+=_.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)},n.getIntervalDelta=function(){return this.interval+this.intervalRemainder},t}(Te),sn=function(){function e(){this.adapter=null,this.logger=Y("PlatformManager")}e.getInstance=function(){return e.instance||(e.instance=new e),e.instance};var t=e.prototype;return t.getAdapter=function(){if(!this.adapter)throw new Error("平台适配器未注册,请调用 registerAdapter() 注册适配器");return this.adapter},t.registerAdapter=function(e){this.adapter=e,this.logger.info("平台适配器已注册: "+e.name,{name:e.name,version:e.version,supportsWorker:e.isWorkerSupported(),supportsSharedArrayBuffer:e.isSharedArrayBufferSupported(),hardwareConcurrency:e.getHardwareConcurrency()})},t.hasAdapter=function(){return null!==this.adapter},t.getAdapterInfo=function(){return this.adapter?{name:this.adapter.name,version:this.adapter.version,config:this.adapter.getPlatformConfig()}:null},t.supportsFeature=function(e){if(!this.adapter)return!1;var t=this.adapter.getPlatformConfig();switch(e){case"worker":return this.adapter.isWorkerSupported();case"shared-array-buffer":return this.adapter.isSharedArrayBufferSupported();case"transferable-objects":return t.supportsTransferableObjects;case"module-worker":return t.supportsModuleWorker;default:return!1}},t.getBasicWorkerConfig=function(){if(!this.adapter)return{platformSupportsWorker:!1,platformSupportsSharedArrayBuffer:!1,platformMaxWorkerCount:1,platformLimitations:{}};var e=this.adapter.getPlatformConfig();return{platformSupportsWorker:this.adapter.isWorkerSupported(),platformSupportsSharedArrayBuffer:this.adapter.isSharedArrayBufferSupported(),platformMaxWorkerCount:e.maxWorkerCount,platformLimitations:e.limitations||{}}},t.getFullPlatformConfig=function(){var e=n(l().m((function e(){return l().w((function(e){for(;;)switch(e.n){case 0:if(this.adapter){e.n=1;break}throw new Error("平台适配器未注册");case 1:if("function"!=typeof this.adapter.getPlatformConfigAsync){e.n=3;break}return e.n=2,this.adapter.getPlatformConfigAsync();case 2:return e.a(2,e.v);case 3:return e.a(2,this.adapter.getPlatformConfig())}}),e,this)})));return function(){return e.apply(this,arguments)}}(),e}(),on=function(e){function t(t,n){var i,r,s,o,a,c;void 0===n&&(n={}),(c=e.call(this,t)||this).workerPool=null,c.isProcessing=!1,c.sharedBuffer=null,c.sharedFloatArray=null,c.hasLoggedSyncMode=!1,c.platformAdapter=sn.getInstance().getAdapter();var u=null!==(i=n.workerCount)&&void 0!==i?i:c.getMaxSystemWorkerCount(),h=c.getMaxSystemWorkerCount(),l=Math.min(u,h);return u>h&&c.logger.warn("请求 "+u+" 个Worker,但系统最多支持 "+h+" 个。实际使用 "+l+" 个Worker。"),c.config={enableWorker:null===(r=n.enableWorker)||void 0===r||r,workerCount:l,systemConfig:n.systemConfig,entitiesPerWorker:n.entitiesPerWorker,useSharedArrayBuffer:null!==(s=n.useSharedArrayBuffer)&&void 0!==s?s:c.isSharedArrayBufferSupported(),entityDataSize:null!==(o=n.entityDataSize)&&void 0!==o?o:c.getDefaultEntityDataSize(),maxEntities:null!==(a=n.maxEntities)&&void 0!==a?a:1e4},c.config.enableWorker&&c.isWorkerSupported()&&(c.config.useSharedArrayBuffer&&c.initializeSharedArrayBuffer(),c.initializeWorkerPool()),c}u(t,e);var i=t.prototype;return i.isWorkerSupported=function(){return this.platformAdapter.isWorkerSupported()},i.isSharedArrayBufferSupported=function(){return this.platformAdapter.isSharedArrayBufferSupported()},i.getMaxSystemWorkerCount=function(){return this.platformAdapter.getPlatformConfig().maxWorkerCount},i.initializeSharedArrayBuffer=function(){try{if(!this.isSharedArrayBufferSupported())return this.logger.warn(this.systemName+": 平台不支持SharedArrayBuffer,降级到单Worker模式以保证数据处理完整性"),this.config.useSharedArrayBuffer=!1,void(this.config.workerCount=1);var e=this.config.maxEntities*this.config.entityDataSize*4;this.sharedBuffer=this.platformAdapter.createSharedArrayBuffer(e),this.sharedBuffer&&(this.sharedFloatArray=new Float32Array(this.sharedBuffer)),this.logger.info(this.systemName+": SharedArrayBuffer初始化成功 ("+e+" 字节)")}catch(e){this.logger.warn(this.systemName+": SharedArrayBuffer初始化失败,降级到单Worker模式以保证数据处理完整性",e),this.config.useSharedArrayBuffer=!1,this.sharedBuffer=null,this.sharedFloatArray=null,this.config.workerCount=1}},i.initializeWorkerPool=function(){try{for(var e=this.createWorkerScript(),t=[],n=(this.platformAdapter.getPlatformConfig().workerScriptPrefix||"")+e,i=0;i<this.config.workerCount;i++)try{var r=this.platformAdapter.createWorker(n,{name:"WorkerEntitySystem-"+i});t.push(r)}catch(e){throw this.logger.error("创建Worker "+i+" 失败:",e),e}this.workerPool=new an(t,this.sharedBuffer)}catch(e){this.logger.error(this.systemName+": Worker池初始化失败",e),this.config.enableWorker=!1}},i.createWorkerScript=function(){var e,t=this.workerProcess.toString().match(/\{([\s\S]*)\}/);if(!t)throw new Error("无法解析workerProcess方法");var n=t[1],i=this.config.entityDataSize,r=(null===(e=this.getSharedArrayBufferProcessFunction)||void 0===e?void 0:e.call(this))||null,s="";if(r){var o=r.toString().match(/\{([\s\S]*)\}/);o&&(s=o[1])}return"\n // Worker脚本 - 支持SharedArrayBuffer\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = "+i+";\n\n self.onmessage = function(e) {\n const { type, id, entities, deltaTime, systemConfig, startIndex, endIndex, sharedBuffer } = e.data;\n\n\n try {\n // 处理SharedArrayBuffer初始化\n if (type === 'init' && sharedBuffer) {\n sharedFloatArray = new Float32Array(sharedBuffer);\n self.postMessage({ type: 'init', success: true });\n return;\n }\n\n // 处理SharedArrayBuffer数据\n if (type === 'shared' && sharedFloatArray) {\n processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig);\n self.postMessage({ id, result: null }); // SharedArrayBuffer不需要返回数据\n return;\n }\n\n // 传统处理方式\n if (entities) {\n // 定义处理函数\n function workerProcess(entities, deltaTime, systemConfig) {\n "+n+"\n }\n\n // 执行处理\n const result = workerProcess(entities, deltaTime, systemConfig);\n\n // 处理Promise返回值\n if (result && typeof result.then === 'function') {\n result.then(finalResult => {\n self.postMessage({ id, result: finalResult });\n }).catch(error => {\n self.postMessage({ id, error: error.message });\n });\n } else {\n self.postMessage({ id, result });\n }\n }\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n };\n\n // SharedArrayBuffer处理函数 - 由子类定义\n function processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig) {\n if (!sharedFloatArray) return;\n\n "+(s?"\n // 用户定义的处理函数\n const userProcessFunction = function(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig) {\n "+s+"\n };\n userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig);\n ":"")+"\n }\n "},i.process=function(e){var t=this;if(!this.isProcessing){this.isProcessing=!0;try{this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?this.processWithSharedArrayBuffer(e).finally((function(){t.isProcessing=!1})):(this.config.useSharedArrayBuffer&&this.logger.info(this.systemName+": 本帧降级到传统Worker模式"),this.processWithWorker(e).finally((function(){t.isProcessing=!1}))):(this.hasLoggedSyncMode||(this.logger.info(this.systemName+": Worker不可用,使用同步处理"),this.hasLoggedSyncMode=!0),this.processSynchronously(e),this.isProcessing=!1)}catch(e){throw this.isProcessing=!1,this.logger.error(this.systemName+": 处理失败",e),e}}},i.processWithSharedArrayBuffer=function(){var e=n(l().m((function e(t){var n;return l().w((function(e){for(;;)switch(e.n){case 0:if(this.sharedFloatArray){e.n=1;break}throw new Error("SharedArrayBuffer not initialized");case 1:return this.writeEntitiesToSharedBuffer(t),n=this.createSharedArrayBufferTasks(t.length),e.n=2,Promise.all(n);case 2:this.readResultsFromSharedBuffer(t);case 3:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),i.processWithWorker=function(){var e=n(l().m((function e(t){var n,i,r,s,a,c,u,h,f,d,p,y,m,g,v=this;return l().w((function(e){for(;;)switch(e.n){case 0:for(n=[],i=0;i<t.length;i++)n[i]=this.extractEntityData(t[i]);return r=this.createBatches(n),s=_.deltaTime,a=r.map((function(e){return v.workerPool.execute({entities:e,deltaTime:s,systemConfig:v.config.systemConfig})})),e.n=1,Promise.all(a);case 1:for(c=e.v,u=0,h=o(c);!(f=h()).done;)for(d=f.value,p=o(d);!(y=p()).done;)m=y.value,u<t.length&&(g=t[u])&&m&&this.applyResult(g,m),u++;case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),i.processSynchronously=function(e){var t=this,n=e.map((function(e){return t.extractEntityData(e)})),i=_.deltaTime,r=this.workerProcess(n,i,this.config.systemConfig);r&&"function"==typeof r.then?r.then((function(n){e.forEach((function(e,i){t.applyResult(e,n[i])}))})):e.forEach((function(e,n){t.applyResult(e,r[n])}))},i.createBatches=function(e){var t=this.config.workerCount,n=[];if(this.config.entitiesPerWorker){for(var i=this.config.entitiesPerWorker,r=0;r<e.length;r+=i){var s=Math.min(r+i,e.length);n.push(e.slice(r,s))}n.length>t&&this.logger.warn(this.systemName+": 创建了 "+n.length+" 个批次,但只有 "+t+" 个Worker。某些Worker将依次处理多个批次。")}else for(var o=Math.ceil(e.length/t),a=0;a<t;a++){var c=a*o,u=Math.min(c+o,e.length);c<e.length&&n.push(e.slice(c,u))}return n},i.writeEntitiesToSharedBuffer=function(e){if(this.sharedFloatArray)for(var t=0;t<e.length&&t<this.config.maxEntities;t++){var n=e[t],i=this.extractEntityData(n),r=t*this.config.entityDataSize;this.writeEntityToBuffer(i,r)}},i.createSharedArrayBufferTasks=function(e){var t=[];if(this.config.entitiesPerWorker){var n=this.config.entitiesPerWorker,i=Math.ceil(e/n),r=this.config.workerCount;i>r&&this.logger.warn(this.systemName+": 需要 "+i+" 个任务处理 "+e+" 个实体(每任务 "+n+" 个),但只有 "+r+" 个Worker。某些Worker将依次处理多个任务。");for(var s=0;s<e;s+=n){var o=s,a=Math.min(s+n,e),c=this.workerPool.executeSharedBuffer({startIndex:o,endIndex:a,deltaTime:_.deltaTime,systemConfig:this.config.systemConfig});t.push(c)}}else for(var u=Math.ceil(e/this.config.workerCount),h=0;h<this.config.workerCount;h++){var l=h*u,f=Math.min(l+u,e);if(l<e){var d=this.workerPool.executeSharedBuffer({startIndex:l,endIndex:f,deltaTime:_.deltaTime,systemConfig:this.config.systemConfig});t.push(d)}}return t},i.readResultsFromSharedBuffer=function(e){if(this.sharedFloatArray)for(var t=0;t<e.length&&t<this.config.maxEntities;t++){var n=e[t],i=t*this.config.entityDataSize,r=this.readEntityFromBuffer(i);r&&this.applyResult(n,r)}},i.updateConfig=function(e){var t=a({},this.config);if(void 0!==e.workerCount){var n=this.getMaxSystemWorkerCount(),i=Math.min(e.workerCount,n);e.workerCount>n&&this.logger.warn("请求 "+e.workerCount+" 个Worker,但系统最多支持 "+n+" 个。实际使用 "+i+" 个Worker。"),e.workerCount=i}Object.assign(this.config,e),t.useSharedArrayBuffer===this.config.useSharedArrayBuffer?t.workerCount===this.config.workerCount?(!this.config.enableWorker&&this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&!this.workerPool&&this.isWorkerSupported()&&this.initializeWorkerPool()):this.reinitializeWorkerPool():this.reinitializeWorkerSystem()},i.reinitializeWorkerSystem=function(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.sharedBuffer=null,this.sharedFloatArray=null,this.config.useSharedArrayBuffer||(this.config.workerCount=1),this.config.enableWorker&&this.isWorkerSupported()&&(this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool())},i.reinitializeWorkerPool=function(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()},i.getWorkerInfo=function(){var e="sync";return this.config.enableWorker&&this.workerPool&&(e=this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?"shared-buffer":"worker"),{enabled:this.config.enableWorker,workerCount:this.config.workerCount,entitiesPerWorker:this.config.entitiesPerWorker,maxSystemWorkerCount:this.getMaxSystemWorkerCount(),isProcessing:this.isProcessing,sharedArrayBufferSupported:this.isSharedArrayBufferSupported(),sharedArrayBufferEnabled:this.config.useSharedArrayBuffer,currentMode:e}},i.onDestroy=function(){e.prototype.onDestroy.call(this),this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)},i.getLoggerName=function(){return"WorkerEntitySystem"},t}(Te),an=function(){function e(e,t){var n=this;void 0===t&&(t=null),this.workers=[],this.taskQueue=[],this.busyWorkers=new Set,this.taskCounter=0,this.sharedBuffer=null,this.logger=Y("PlatformWorkerPool"),this.sharedBuffer=t,this.workers=e;for(var i=function(i){var r=e[i];r.onMessage((function(e){return n.handleWorkerMessage(i,e.data)})),r.onError((function(e){return n.handleWorkerError(i,e)})),t&&r.postMessage({type:"init",sharedBuffer:t})},r=0;r<e.length;r++)i(r)}var t=e.prototype;return t.executeSharedBuffer=function(e){var t=this;return new Promise((function(n,i){var r={id:"shared-task-"+ ++t.taskCounter,data:a({},e,{type:"shared"}),resolve:function(){return n()},reject:i};t.taskQueue.push(r),t.processQueue()}))},t.execute=function(e){var t=this;return new Promise((function(n,i){var r={id:"task-"+ ++t.taskCounter,data:e,resolve:function(e){n(e)},reject:i};t.taskQueue.push(r),t.processQueue()}))},t.processQueue=function(){if(0!==this.taskQueue.length)for(var e=0;e<this.workers.length;e++)if(!this.busyWorkers.has(e)&&this.taskQueue.length>0){var t=this.taskQueue.shift();this.busyWorkers.add(e),this.workers[e].postMessage(a({id:t.id},t.data)),this.workers[e]._currentTask=t}},t.handleWorkerMessage=function(e,t){var n=this.workers[e],i=n._currentTask;i&&(this.busyWorkers.delete(e),n._currentTask=null,t.error?i.reject(new Error(t.error)):i.resolve(t.result),this.processQueue())},t.handleWorkerError=function(e,t){var n=this.workers[e],i=n._currentTask;i&&(this.busyWorkers.delete(e),n._currentTask=null,i.reject(new Error(t.message))),this.processQueue()},t.destroy=function(){for(var e,t=o(this.workers);!(e=t()).done;){e.value.terminate()}this.workers.length=0,this.taskQueue.length=0,this.busyWorkers.clear()},e}(),cn=function(){function e(){}return e.registerComponentMigration=function(e,t,n,i){this.componentMigrations.has(e)||this.componentMigrations.set(e,new Map),this.componentMigrations.get(e).set(t,i)},e.registerSceneMigration=function(e,t,n){this.sceneMigrations.set(e,n)},e.migrateComponent=function(e,t){var n=e.version;if(n===t)return e;var i=this.componentMigrations.get(e.type);if(!i)return console.warn("No migration path found for component "+e.type),e;for(var r=a({},e),s=n;s<t;){var o=i.get(s);if(!o){console.warn("Missing migration from version "+s+" to "+(s+1)+" for "+e.type);break}r.data=o(r.data,s,s+1),s++}return r.version=s,r},e.migrateScene=function(e,t){var n=e.version;if(n===t)return e;for(var i=a({},e),r=n;r<t;){var s=this.sceneMigrations.get(r);if(!s){console.warn("Missing scene migration from version "+r+" to "+(r+1));break}i=s(i,r,r+1),r++}return i.version=r,i=this.migrateSceneComponents(i)},e.migrateSceneComponents=function(e){var t=this,n=a({},e);return n.entities=e.entities.map((function(n){return a({},n,{components:n.components.map((function(n){var i=e.componentTypeRegistry.find((function(e){return e.typeName===n.type}));return i&&i.version!==n.version?t.migrateComponent(n,i.version):n})),children:t.migrateEntitiesComponents(n.children,e.componentTypeRegistry)})})),n},e.migrateEntitiesComponents=function(e,t){var n=this;return e.map((function(e){return a({},e,{components:e.components.map((function(e){var i=t.find((function(t){return t.typeName===e.type}));return i&&i.version!==e.version?n.migrateComponent(e,i.version):e})),children:n.migrateEntitiesComponents(e.children,t)})}))},e.clearMigrations=function(){this.componentMigrations.clear(),this.sceneMigrations.clear()},e.getComponentMigrationPath=function(e){var t=this.componentMigrations.get(e);return t?Array.from(t.keys()).sort((function(e,t){return e-t})):[]},e.getSceneMigrationPath=function(){return Array.from(this.sceneMigrations.keys()).sort((function(e,t){return e-t}))},e.canMigrateComponent=function(e,t,n){if(t===n)return!0;var i=this.componentMigrations.get(e);if(!i)return!1;for(var r=t;r<n;r++)if(!i.has(r))return!1;return!0},e.canMigrateScene=function(e,t){if(e===t)return!0;for(var n=e;n<t;n++)if(!this.sceneMigrations.has(n))return!1;return!0},e}();cn.componentMigrations=new Map,cn.sceneMigrations=new Map;var un=function(){function e(){this.fromVersion=1,this.toVersion=2}var t=e.prototype;return t.forComponent=function(e){return this.componentType=e,this},t.fromVersionToVersion=function(e,t){return this.fromVersion=e,this.toVersion=t,this},t.migrate=function(e){this.componentType?cn.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):cn.registerSceneMigration(this.fromVersion,this.toVersion,e)},e}();var hn=function(){function e(e){this._entity=e}var t=e.prototype;return t.with=function(e){return this._entity.addComponent(e),this},t.withConfigured=function(e,t){return this._entity.addComponent(e),t(e),this},t.withTag=function(e){return this._entity.tag=e,this},t.withName=function(e){return this._entity.name=e,this},t.withActive=function(e){return this._entity.active=e,this},t.withEnabled=function(e){return this._entity.enabled=e,this},t.withUpdateOrder=function(e){return this._entity.updateOrder=e,this},t.withChild=function(e){return this._entity.addChild(e),this},t.build=function(){return this._entity},s(e,[{key:"entity",get:function(){return this._entity}}])}();var ln=function(){function e(){}return e.getType=function(e){return e.constructor},e}(),fn=function(){function e(){}return e.toNumber=function(e){return null==e?0:Number(e)},e}();function dn(e){return"function"==typeof e&&e.prototype instanceof en}var pn=function(){function e(){}return e.detect=function(){var e,t=[],n="unknown",i=!1;return"undefined"!=typeof globalThis&&t.push("globalThis"),"undefined"!=typeof window&&t.push("window"),"undefined"!=typeof self&&t.push("self"),this.isNodeJS()?(n="nodejs",i=!0,e="NodeAdapter",t.push("nodejs","process","require")):this.isWeChatMiniGame()?(n="wechat-minigame",i=!0,e="WeChatMiniGameAdapter",t.push("wx","wechat-minigame")):this.isByteDanceMiniGame()?(n="bytedance-minigame",i=!0,e="ByteDanceMiniGameAdapter",t.push("tt","bytedance-minigame")):this.isAlipayMiniGame()?(n="alipay-minigame",i=!0,e="AlipayMiniGameAdapter",t.push("my","alipay-minigame")):this.isBaiduMiniGame()?(n="baidu-minigame",i=!0,e="BaiduMiniGameAdapter",t.push("swan","baidu-minigame")):this.isBrowser()&&(n="browser",i=!0,e="BrowserAdapter",t.push("browser")),"undefined"!=typeof Worker&&t.push("Worker"),"undefined"!=typeof SharedArrayBuffer&&t.push("SharedArrayBuffer"),"undefined"!=typeof navigator&&navigator.hardwareConcurrency&&t.push("hardwareConcurrency"),"undefined"!=typeof performance&&"function"==typeof performance.now&&t.push("performance.now"),"undefined"!=typeof Blob&&t.push("Blob"),"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL&&t.push("URL.createObjectURL"),{platform:n,confident:i,features:t,adapterClass:e}},e.isWeChatMiniGame=function(){if(void 0!==globalThis.wx){var e=globalThis.wx;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1},e.isByteDanceMiniGame=function(){if(void 0!==globalThis.tt){var e=globalThis.tt;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1},e.isNodeJS=function(){try{return!("undefined"==typeof process||!process.versions||!process.versions.node||"undefined"==typeof require||"undefined"==typeof module||"undefined"==typeof exports||"undefined"!=typeof window||"undefined"!=typeof document)}catch(e){return!1}},e.isAlipayMiniGame=function(){if(void 0!==globalThis.my){var e=globalThis.my;return!(!e.getSystemInfo||!e.createCanvas)}return!1},e.isBaiduMiniGame=function(){if(void 0!==globalThis.swan){var e=globalThis.swan;return!(!e.getSystemInfo||!e.createCanvas)}return!1},e.isBrowser=function(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location},e.getDetailedInfo=function(){var e={};return e.userAgent="undefined"!=typeof navigator?navigator.userAgent:"unknown",e.platform="undefined"!=typeof navigator?navigator.platform:"unknown",e.globalObjects={window:"undefined"!=typeof window,document:"undefined"!=typeof document,navigator:"undefined"!=typeof navigator,wx:void 0!==globalThis.wx,tt:void 0!==globalThis.tt,my:void 0!==globalThis.my,swan:void 0!==globalThis.swan},e.workerSupport={Worker:"undefined"!=typeof Worker,SharedWorker:"undefined"!=typeof SharedWorker,ServiceWorker:"undefined"!=typeof navigator&&"serviceWorker"in navigator,SharedArrayBuffer:"undefined"!=typeof SharedArrayBuffer,crossOriginIsolated:"undefined"!=typeof self&&self.crossOriginIsolated},e.performance={performanceNow:"undefined"!=typeof performance&&"function"==typeof performance.now,hardwareConcurrency:"undefined"!=typeof navigator?navigator.hardwareConcurrency:void 0},e.apiSupport={Blob:"undefined"!=typeof Blob,URL:"undefined"!=typeof URL,createObjectURL:"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL,ArrayBuffer:"undefined"!=typeof ArrayBuffer,TypedArrays:"undefined"!=typeof Float32Array},e},e}();exports.AutoTyped=function(e){return function(t,n){var i=String(n);t.constructor.__autoTypedFields||(t.constructor.__autoTypedFields=new Map),t.constructor.__autoTypedFields.set(i,e||{})}},exports.BitMask64Utils=pe,exports.Bits=xe,exports.COMPONENT_TYPE_NAME=L,exports.Colors=q,exports.Component=en,exports.ComponentDataCollector=he,exports.ComponentPool=ce,exports.ComponentPoolManager=ue,exports.ComponentRegistry=ge,exports.ComponentSerializer=et,exports.ComponentSparseSet=De,exports.ComponentStorage=ve,exports.ConsoleLogger=G,exports.Core=Kt,exports.DeepCopy=function(e,t){var n=String(t);e.constructor.__deepCopyFields||(e.constructor.__deepCopyFields=new Set),e.constructor.__deepCopyFields.add(n)},exports.ECSComponent=function(e){return function(t){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return t[L]=e,t}},exports.ECSFluentAPI=Wt,exports.ECSSystem=function(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return n[N]=e,t&&(n.__systemMetadata__=t),n}},exports.ENTITY_REF_METADATA=te,exports.EVENT_TYPES=je,exports.Emitter=Zt,exports.EnableSoA=function(e){return e.__enableSoA=!0,e},exports.Entity=Ce,exports.EntityDataCollector=se,exports.EntityList=Ee,exports.EntityProcessorList=Me,exports.EntityRef=function(){return function(e,t){var n=e.constructor,i=n[te];i||(i={properties:new Set},n[te]=i);var r="symbol"==typeof t?t.toString():t;i.properties.add(r),Object.defineProperty(e,t,{get:function(){return ie(this).get(r)||null},set:function(e){var t=ie(this),n=t.get(r)||null;if(n!==e){var i=null!==this.entityId?Z(this.entityId):null;if(i&&i.referenceTracker){var s=i.referenceTracker;if(n&&s.unregisterReference(n,this,r),e){var o;if(e.scene!==i)return void ee.error("Cannot reference Entity from different Scene. Entity: "+e.name+", Scene: "+((null===(o=e.scene)||void 0===o?void 0:o.name)||"null"));if(e.isDestroyed)return ee.warn("Cannot reference destroyed Entity: "+e.name),void t.set(r,null);s.registerReference(e,this,r)}t.set(r,e)}else t.set(r,e)}},enumerable:!0,configurable:!0})}},exports.EntitySerializer=tt,exports.EntitySystem=Te,exports.EventBus=Ge,exports.EventTypeValidator=qe,exports.Float32=function(e,t){var n=String(t);e.constructor.__float32Fields||(e.constructor.__float32Fields=new Set),e.constructor.__float32Fields.add(n)},exports.Float64=function(e,t){var n=String(t);e.constructor.__float64Fields||(e.constructor.__float64Fields=new Set),e.constructor.__float64Fields.add(n)},exports.FuncPack=$t,exports.GlobalEventBus=Qe,exports.GlobalManager=Xt,exports.HighPrecision=function(e,t){var n=String(t);e.constructor.__highPrecisionFields||(e.constructor.__highPrecisionFields=new Set),e.constructor.__highPrecisionFields.add(n)},exports.IdentifierPool=be,exports.IgnoreSerialization=function(){return function(e,t){var n=e.constructor,i=n[Ke];i||(i={options:{version:1},fields:new Map,ignoredFields:new Set},n[Ke]=i),i.ignoredFields.add(t)}},exports.IncrementalSerializer=Dt,exports.Inject=M,exports.Injectable=A,exports.Int16=function(e,t){var n=String(t);e.constructor.__int16Fields||(e.constructor.__int16Fields=new Set),e.constructor.__int16Fields.add(n)},exports.Int32=function(e,t){var n=String(t);e.constructor.__int32Fields||(e.constructor.__int32Fields=new Set),e.constructor.__int32Fields.add(n)},exports.Int8=function(e,t){var n=String(t);e.constructor.__int8Fields||(e.constructor.__int8Fields=new Set),e.constructor.__int8Fields.add(n)},exports.IntervalSystem=rn,exports.Logger=V,exports.LoggerManager=Q,exports.Matcher=Ae,exports.MigrationBuilder=un,exports.NumberExtension=fn,exports.PassiveSystem=nn,exports.PerformanceDataCollector=ae,exports.PerformanceMonitor=O,exports.PlatformDetector=pn,exports.PlatformManager=sn,exports.PluginManager=Qt,exports.Pool=z,exports.PoolManager=P,exports.ProcessingSystem=tn,exports.QuerySystem=Ue,exports.ReactiveQuery=We,exports.ReferenceTracker=X,exports.SERIALIZABLE_METADATA=Ke,exports.SERIALIZE_FIELD=Je,exports.SERIALIZE_OPTIONS=$e,exports.SYSTEM_TYPE_NAME=N,exports.Scene=Bt,exports.SceneDataCollector=fe,exports.SceneManager=qt,exports.SceneSerializer=kt,exports.Serializable=function(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");var n=t[Ke];return n?n.options=e:(n={options:e,fields:new Map,ignoredFields:new Set},t[Ke]=n),t}},exports.Serialize=Ze,exports.SerializeArray=function(e,t){var n=String(t);e.constructor.__serializeArrayFields||(e.constructor.__serializeArrayFields=new Set),e.constructor.__serializeArrayFields.add(n)},exports.SerializeAsMap=function(){return function(e,t){Ze({serializer:function(e){return e instanceof Map?Array.from(e.entries()):null},deserializer:function(e){return Array.isArray(e)?new Map(e):new Map}})(e,t)}},exports.SerializeAsSet=function(){return function(e,t){Ze({serializer:function(e){return e instanceof Set?Array.from(e):null},deserializer:function(e){return Array.isArray(e)?new Set(e):new Set}})(e,t)}},exports.SerializeMap=function(e,t){var n=String(t);e.constructor.__serializeMapFields||(e.constructor.__serializeMapFields=new Set),e.constructor.__serializeMapFields.add(n)},exports.SerializeSet=function(e,t){var n=String(t);e.constructor.__serializeSetFields||(e.constructor.__serializeSetFields=new Set),e.constructor.__serializeSetFields.add(n)},exports.ServiceContainer=zt,exports.SoAStorage=me,exports.SparseSet=Ie,exports.SystemDataCollector=oe,exports.Time=_,exports.Timer=C,exports.TypeInference=ye,exports.TypeSafeEventSystem=He,exports.TypeUtils=ln,exports.TypedEntityBuilder=hn,exports.TypedQueryBuilder=Ye,exports.TypedQueryResult=Ve,exports.Uint16=function(e,t){var n=String(t);e.constructor.__uint16Fields||(e.constructor.__uint16Fields=new Set),e.constructor.__uint16Fields.add(n)},exports.Uint32=function(e,t){var n=String(t);e.constructor.__uint32Fields||(e.constructor.__uint32Fields=new Set),e.constructor.__uint32Fields.add(n)},exports.Uint8=function(e,t){var n=String(t);e.constructor.__uint8Fields||(e.constructor.__uint8Fields=new Set),e.constructor.__uint8Fields.add(n)},exports.Uint8Clamped=function(e,t){var n=String(t);e.constructor.__uint8ClampedFields||(e.constructor.__uint8ClampedFields=new Set),e.constructor.__uint8ClampedFields.add(n)},exports.Updatable=T,exports.VersionMigrationManager=cn,exports.WebSocketManager=de,exports.WorkerEntitySystem=on,exports.World=jt,exports.WorldManager=Yt,exports.addAndConfigure=function(e,t,n){return e.addComponent(t),n(t),e},exports.buildEntity=function(e){return new hn(e)},exports.createECSAPI=Ut,exports.createInstance=I,exports.createLogger=Y,exports.createQuery=function(){return new Ye},exports.getBasicWorkerConfig=function(){return sn.getInstance().getBasicWorkerConfig()},exports.getComponentInstanceTypeName=H,exports.getComponentTypeName=U,exports.getComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.map((function(t){return e.getComponent(t)}))},exports.getCurrentAdapter=function(){return sn.getInstance().getAdapter()},exports.getEntityRefMetadata=re,exports.getFullPlatformConfig=function(){return sn.getInstance().getFullPlatformConfig()},exports.getOrAddComponent=function(e,t,n){var i=e.getComponent(t);return i||(i=n(),e.addComponent(i)),i},exports.getSceneByEntityId=Z,exports.getSerializationMetadata=Xe,exports.getSystemInstanceTypeName=j,exports.getSystemMetadata=W,exports.getSystemTypeName=F,exports.getUpdatableMetadata=R,exports.hasAdapter=function(){return sn.getInstance().hasAdapter()},exports.hasAnyComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.some((function(t){return e.hasComponent(t)}))},exports.hasComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.every((function(t){return e.hasComponent(t)}))},exports.hasEntityRef=function(e){return null!==re(e)},exports.isComponentArray=function(e){return e.every(dn)},exports.isComponentType=dn,exports.isSerializable=function(e){return null!==Xe(e)},exports.isUpdatable=D,exports.queryFor=function(e){return new Ye([e])},exports.queryForAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new Ye(t)},exports.registerInjectable=function(e,t,n){if(void 0===n&&(n=!0),!x(t))throw new Error(t.name+" is not marked as @Injectable(). Please add @Injectable() decorator to the class.");var i=function(e){return I(t,e)};n?e.registerSingleton(t,i):e.registerTransient(t,i)},exports.registerPlatformAdapter=function(e){return sn.getInstance().registerAdapter(e)},exports.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" (id: "+e.id+")");return n},exports.resetLoggerColors=function(){Q.getInstance().resetColors()},exports.setGlobalLogLevel=function(e){Q.getInstance().setGlobalLevel(e)},exports.setLoggerColors=function(e){Q.getInstance().setGlobalColors(e)},exports.supportsFeature=function(e){return sn.getInstance().supportsFeature(e)},exports.tryGetComponent=function(e,t){var n=e.getComponent(t);return null!==n?n:void 0},exports.updateComponent=function(e,t,n){var i=e.getComponent(t);return!!i&&(Object.assign(i,n),!0)};
|
|
3
|
+
var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function s(n,i,r,s){var c=i&&i.prototype instanceof a?i:a,u=Object.create(c.prototype);return f(u,"_invoke",function(n,i,r){var s,a,c,u=0,h=r||[],l=!1,f={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,n){return s=t,a=0,c=e,f.n=n,o}};function d(n,i){for(a=n,c=i,t=0;!l&&u&&!r&&t<h.length;t++){var r,s=h[t],d=f.p,p=s[2];n>3?(r=p===i)&&(c=s[(a=s[4])?5:(a=3,3)],s[4]=s[5]=e):s[0]<=d&&((r=n<2&&d<s[1])?(a=0,f.v=i,f.n=s[1]):d<p&&(r=n<3||s[0]>i||i>p)&&(s[4]=n,s[5]=i,f.n=p,a=0))}if(r||n>1)return o;throw l=!0,i}return function(r,h,p){if(u>1)throw TypeError("Generator is already running");for(l&&1===h&&d(h,p),a=h,c=p;(t=a<2?e:c)||!l;){s||(a?a<3?(a>1&&(f.n=-1),d(a,c)):f.n=c:f.v=c);try{if(u=2,s){if(a||(r="next"),t=s[r]){if(!(t=t.call(s,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,a<2&&(a=0)}else 1===a&&(t=s.return)&&t.call(s),a<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),a=1);s=e}else if((t=(l=f.n<0)?c:n.call(i,f))!==o)break}catch(t){s=e,a=1,c=t}finally{u=1}}return{value:t,done:l}}}(n,r,s),!0),u}var o={};function a(){}function c(){}function u(){}t=Object.getPrototypeOf;var h=[][i]?t(t([][i]())):(f(t={},i,(function(){return this})),t),d=u.prototype=a.prototype=Object.create(h);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,f(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=u,f(d,"constructor",u),f(u,"constructor",c),c.displayName="GeneratorFunction",f(u,r,"GeneratorFunction"),f(d),f(d,r,"Generator"),f(d,i,(function(){return this})),f(d,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:s,m:p}})()}function f(e,t,n,i){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}f=function(e,t,n,i){function s(t,n){f(e,t,(function(e){return this._invoke(t,n,e)}))}t?r?r(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(s("next",0),s("throw",1),s("return",2))},f(e,t,n,i)}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function p(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function y(e){var t="function"==typeof Map?new Map:void 0;return y=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return i(e,arguments,c(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),d(n,e)},y(e)}function m(e,t,n,i){var r,s=arguments.length,o=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,n,o):r(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o}function g(e,t){return function(n,i){t(n,i,e)}}function v(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}"function"==typeof SuppressedError&&SuppressedError;var _=function(){function e(){}return e.update=function(e){this.unscaledDeltaTime=e,this.deltaTime=e*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++},e.sceneChanged=function(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0},e.checkEvery=function(e,t){return this.totalTime-t>=e},e}();_.deltaTime=0,_.unscaledDeltaTime=0,_.totalTime=0,_.unscaledTotalTime=0,_.timeScale=1,_.frameCount=0;var S,C=function(){function e(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}var t=e.prototype;return t.getContext=function(){return this.context},t.reset=function(){this._elapsedTime=0},t.stop=function(){this._isDone=!0},t.tick=function(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=_.deltaTime,this._isDone},t.initialize=function(e,t,n,i){this._timeInSeconds=e,this._repeats=t,this.context=n,this._onTime=i.bind(n)},t.unload=function(){this.context=null,this._onTime=null},s(e,[{key:"isDone",get:function(){return this._isDone}},{key:"elapsedTime",get:function(){return this._elapsedTime}}])}(),w=new WeakMap,E=new WeakMap,b=new WeakMap;function A(){return function(e){var t=w.get(e);return w.set(e,{injectable:!0,dependencies:[],properties:null==t?void 0:t.properties}),e}}function T(e){return void 0===e&&(e=0),function(t){var n=t.prototype;if(!n||"function"!=typeof n.update)throw new Error("@Updatable() decorator requires class "+t.name+" to implement IUpdatable interface with update() method. Please add 'implements IUpdatable' and define update(deltaTime?: number): void method.");return b.set(t,{updatable:!0,priority:e}),t}}function M(e){return function(t,n,i){var r=E.get(t);r||(r=new Map,E.set(t,r)),r.set(i,e)}}function x(e){var t,n=w.get(e);return null!==(t=null==n?void 0:n.injectable)&&void 0!==t&&t}function I(e,t){for(var n,r=(n=e,E.get(n)||new Map),s=[],o=e.length,a=0;a<o;a++){var c=r.get(a);if(c){if("string"==typeof c||"symbol"==typeof c)throw new Error("String and Symbol service identifiers are not yet supported in constructor injection. Please use class types for "+e.name+" parameter "+a);s.push(t.resolve(c))}else s.push(void 0)}return i(e,s)}function k(e,t){var n,i=e.constructor,r=(n=i,w.get(n));if(null!=r&&r.properties&&0!==r.properties.size)for(var s,a=o(r.properties);!(s=a()).done;){var c=s.value,u=c[0],h=c[1],l=t.resolve(h);null!==l&&(e[u]=l)}}function D(e){var t,n=b.get(e);return null!==(t=null==n?void 0:n.updatable)&&void 0!==t&&t}function R(e){return b.get(e)}exports.TimerManager=function(){function e(){this._timers=[]}var t=e.prototype;return t.update=function(){for(var e=this._timers.length-1;e>=0;e--)this._timers[e].tick()&&(this._timers[e].unload(),this._timers.splice(e,1))},t.schedule=function(e,t,n,i){var r=new C;return r.initialize(e,t,n,i),this._timers.push(r),r},t.dispose=function(){for(var e,t=o(this._timers);!(e=t()).done;){e.value.unload()}this._timers=[]},e}(),exports.TimerManager=m([T()],exports.TimerManager),exports.PerformanceWarningType=void 0,(S=exports.PerformanceWarningType||(exports.PerformanceWarningType={})).HIGH_EXECUTION_TIME="high_execution_time",S.HIGH_MEMORY_USAGE="high_memory_usage",S.HIGH_CPU_USAGE="high_cpu_usage",S.FREQUENT_GC="frequent_gc",S.LOW_FPS="low_fps",S.HIGH_ENTITY_COUNT="high_entity_count";var O=function(){function e(){this._systemData=new Map,this._systemStats=new Map,this._warnings=[],this._isEnabled=!1,this._maxRecentSamples=60,this._maxWarnings=100,this._thresholds={executionTime:{warning:16.67,critical:33.33},memoryUsage:{warning:100,critical:200},cpuUsage:{warning:70,critical:90},fps:{warning:45,critical:30},entityCount:{warning:1e3,critical:5e3}},this._fpsHistory=[],this._lastFrameTime=0,this._frameCount=0,this._fpsUpdateInterval=1e3,this._lastFpsUpdate=0,this._currentFps=60,this._memoryCheckInterval=5e3,this._lastMemoryCheck=0,this._memoryHistory=[],this._gcCount=0,this._lastGcCheck=0,this._gcCheckInterval=1e3}var t=e.prototype;return t.enable=function(){this._isEnabled=!0},t.disable=function(){this._isEnabled=!1},t.startMonitoring=function(e){return this._isEnabled?performance.now():0},t.endMonitoring=function(e,t,n){if(void 0===n&&(n=0),this._isEnabled&&0!==t){var i=performance.now(),r=i-t,s={name:e,executionTime:r,entityCount:n,averageTimePerEntity:n>0?r/n:0,lastUpdateTime:i};this._systemData.set(e,s),this.updateStats(e,r)}},t.updateStats=function(e,t){var n=this._systemStats.get(e);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(e,n)),n.totalTime+=t,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,t),n.maxTime=Math.max(n.maxTime,t),n.recentTimes.push(t),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)},t.calculateAdvancedStats=function(e){if(0!==e.recentTimes.length){var t=e.recentTimes.reduce((function(e,t){return e+t}),0)/e.recentTimes.length,n=e.recentTimes.reduce((function(e,n){return e+Math.pow(n-t,2)}),0)/e.recentTimes.length;e.standardDeviation=Math.sqrt(n);var i=[].concat(e.recentTimes).sort((function(e,t){return e-t})),r=i.length;e.percentile95=i[Math.floor(.95*r)]||0,e.percentile99=i[Math.floor(.99*r)]||0}},t.getSystemData=function(e){return this._systemData.get(e)},t.getSystemStats=function(e){return this._systemStats.get(e)},t.getAllSystemData=function(){return new Map(this._systemData)},t.getAllSystemStats=function(){return new Map(this._systemStats)},t.getPerformanceReport=function(){if(!this._isEnabled)return"Performance monitoring is disabled.";var e=[];e.push("=== ECS Performance Report ==="),e.push("");for(var t,n=o(Array.from(this._systemStats.entries()).sort((function(e,t){return t[1].averageTime-e[1].averageTime})));!(t=n()).done;){var i=t.value,r=i[0],s=i[1],a=this._systemData.get(r);e.push("System: "+r),e.push(" Current: "+(null==a?void 0:a.executionTime.toFixed(2))+"ms ("+(null==a?void 0:a.entityCount)+" entities)"),e.push(" Average: "+s.averageTime.toFixed(2)+"ms"),e.push(" Min/Max: "+s.minTime.toFixed(2)+"ms / "+s.maxTime.toFixed(2)+"ms"),e.push(" Total: "+s.totalTime.toFixed(2)+"ms ("+s.executionCount+" calls)"),null!=a&&a.averageTimePerEntity&&a.averageTimePerEntity>0&&e.push(" Per Entity: "+a.averageTimePerEntity.toFixed(4)+"ms"),e.push("")}var c=Array.from(this._systemData.values()).reduce((function(e,t){return e+t.executionTime}),0);return e.push("Total Frame Time: "+c.toFixed(2)+"ms"),e.push("Systems Count: "+this._systemData.size),e.join("\n")},t.reset=function(){this._systemData.clear(),this._systemStats.clear()},t.resetSystem=function(e){this._systemData.delete(e),this._systemStats.delete(e)},t.getPerformanceWarnings=function(e){void 0===e&&(e=16.67);for(var t,n=[],i=o(this._systemData.entries());!(t=i()).done;){var r=t.value,s=r[0],a=r[1];a.executionTime>e&&n.push(s+": "+a.executionTime.toFixed(2)+"ms (>"+e+"ms)")}return n},t.setMaxRecentSamples=function(e){this._maxRecentSamples=e;for(var t,n=o(this._systemStats.values());!(t=n()).done;)for(var i=t.value;i.recentTimes.length>e;)i.recentTimes.shift()},t.dispose=function(){this._systemData.clear(),this._systemStats.clear(),this._warnings=[],this._fpsHistory=[],this._memoryHistory=[],this._isEnabled=!1},s(e,[{key:"isEnabled",get:function(){return this._isEnabled}}])}(),z=function(){function e(e,t,n){void 0===t&&(t=100),void 0===n&&(n=1024),this._objects=[],this._createFn=e,this._maxSize=t,this._objectSize=n,this._stats={size:0,maxSize:t,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}e.getPool=function(t,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this._pools.get(t);return r||(r=new e((function(){return new t}),n,i),this._pools.set(t,r)),r};var t=e.prototype;return t.obtain=function(){if(this._stats.totalObtained++,this._objects.length>0){var e=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),e}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()},t.release=function(e){e&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(e.reset(),this._objects.push(e),this._stats.size++,this._updateMemoryUsage()))},t.getStats=function(){return a({},this._stats)},t.clear=function(){for(var e,t=o(this._objects);!(e=t()).done;){e.value.reset()}this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()},t.compact=function(e){for(var t=null!=e?e:Math.floor(this._objects.length/2);this._objects.length>t;){var n=this._objects.pop();n&&(n.reset(),this._stats.size--)}this._updateMemoryUsage()},t.prewarm=function(e){for(var t=Math.min(e,this._maxSize-this._objects.length),n=0;n<t;n++){var i=this._createFn();i.reset(),this._objects.push(i),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()},t.setMaxSize=function(e){this._maxSize=e,this._stats.maxSize=e,this._objects.length>e&&this.compact(e)},t.getAvailableCount=function(){return this._objects.length},t.isEmpty=function(){return 0===this._objects.length},t.isFull=function(){return this._objects.length>=this._maxSize},e.getAllPoolTypes=function(){return Array.from(this._pools.keys())},e.getAllPoolStats=function(){for(var e,t={},n=o(this._pools);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];t[r.name||r.toString()]=s.getStats()}return t},e.compactAllPools=function(){for(var e,t=o(this._pools.values());!(e=t()).done;){e.value.compact()}},e.clearAllPools=function(){for(var e,t=o(this._pools.values());!(e=t()).done;){e.value.clear()}this._pools.clear()},e.getGlobalStatsString=function(){var e=this.getAllPoolStats(),t=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(e).length)return t.push("No pools registered"),t.join("\n");for(var n=0,i=Object.entries(e);n<i.length;n++){var r=i[n],s=r[0],o=r[1];t.push(s+":"),t.push(" Size: "+o.size+"/"+o.maxSize),t.push(" Hit Rate: "+(100*o.hitRate).toFixed(1)+"%"),t.push(" Total Created: "+o.totalCreated),t.push(" Total Obtained: "+o.totalObtained),t.push(" Memory: "+(o.estimatedMemoryUsage/1024).toFixed(1)+" KB"),t.push("")}return t.join("\n")},t._updateHitRate=function(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{var e=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=e/this._stats.totalObtained}},t._updateMemoryUsage=function(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize},e}();z._pools=new Map;var B,P=function(){function e(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}var t=e.prototype;return t.registerPool=function(e,t){this.pools.set(e,t)},t.getPool=function(e){return this.pools.get(e)||null},t.update=function(){var e=Date.now();e-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=e)},t.createPool=function(e,t,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this.pools.get(e);return r||(r=new z(t,n,i),this.pools.set(e,r)),r},t.removePool=function(e){var t=this.pools.get(e);return!!t&&(t.clear(),this.pools.delete(e),!0)},t.getPoolNames=function(){return Array.from(this.pools.keys())},t.getPoolCount=function(){return this.pools.size},t.compactAllPools=function(){for(var e,t=o(this.pools.values());!(e=t()).done;){e.value.compact()}},t.clearAllPools=function(){for(var e,t=o(this.pools.values());!(e=t()).done;){e.value.clear()}},t.getAllStats=function(){for(var e,t=new Map,n=o(this.pools);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];t.set(r,s.getStats())}return t},t.getGlobalStats=function(){for(var e,t=0,n=0,i=0,r=0,s=0,a=0,c=o(this.pools.values());!(e=c()).done;){var u=e.value.getStats();t+=u.size,n+=u.maxSize,i+=u.totalCreated,r+=u.totalObtained,s+=u.totalReleased,a+=u.estimatedMemoryUsage}return{size:t,maxSize:n,totalCreated:i,totalObtained:r,totalReleased:s,hitRate:0===r?0:(r-i)/r,estimatedMemoryUsage:a}},t.getStatsString=function(){var e=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return e.push("No pools registered"),e.join("\n");var t=this.getGlobalStats();e.push("Total Pools: "+this.pools.size),e.push("Global Hit Rate: "+(100*t.hitRate).toFixed(1)+"%"),e.push("Global Memory Usage: "+(t.estimatedMemoryUsage/1024).toFixed(1)+" KB"),e.push("");for(var n,i=o(this.pools);!(n=i()).done;){var r=n.value,s=r[0],a=r[1].getStats();e.push(s+":"),e.push(" Size: "+a.size+"/"+a.maxSize),e.push(" Hit Rate: "+(100*a.hitRate).toFixed(1)+"%"),e.push(" Memory: "+(a.estimatedMemoryUsage/1024).toFixed(1)+" KB"),e.push("")}return e.join("\n")},t.setAutoCompactInterval=function(e){this.autoCompactInterval=e},t.prewarmAllPools=function(){for(var e,t=o(this.pools.values());!(e=t()).done;){var n=e.value,i=n.getStats(),r=Math.floor(.2*i.maxSize);n.prewarm(r)}},t.reset=function(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0},t.dispose=function(){this.reset()},e}(),L=Symbol("ComponentTypeName"),N=Symbol("SystemTypeName");function W(e){return e.__systemMetadata__}function U(e){var t=e[L];return t||(e.name||"UnknownComponent")}function F(e){var t=e[N];return t||(e.name||"UnknownSystem")}function H(e){return U(e.constructor)}function j(e){return F(e.constructor)}exports.LogLevel=void 0,(B=exports.LogLevel||(exports.LogLevel={}))[B.Debug=0]="Debug",B[B.Info=1]="Info",B[B.Warn=2]="Warn",B[B.Error=3]="Error",B[B.Fatal=4]="Fatal",B[B.None=5]="None";var q={BLACK:"[30m",RED:"[31m",GREEN:"[32m",YELLOW:"[33m",BLUE:"[34m",MAGENTA:"[35m",CYAN:"[36m",WHITE:"[37m",BRIGHT_BLACK:"[90m",BRIGHT_RED:"[91m",BRIGHT_GREEN:"[92m",BRIGHT_YELLOW:"[93m",BRIGHT_BLUE:"[94m",BRIGHT_MAGENTA:"[95m",BRIGHT_CYAN:"[96m",BRIGHT_WHITE:"[97m",RESET:"[0m",BOLD:"[1m",UNDERLINE:"[4m"},G=function(){function e(e){void 0===e&&(e={}),this._config=a({level:exports.LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window},e)}var t=e.prototype;return t.debug=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Debug,e].concat(n))},t.info=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Info,e].concat(n))},t.warn=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Warn,e].concat(n))},t.error=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Error,e].concat(n))},t.fatal=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.log.apply(this,[exports.LogLevel.Fatal,e].concat(n))},t.setLevel=function(e){this._config.level=e},t.setColors=function(e){0===Object.keys(e).length?delete this._config.colors:this._config.colors=a({},this._config.colors,e)},t.setPrefix=function(e){this._config.prefix=e},t.log=function(e,t){if(!(e<this._config.level)){var n=t;if(this._config.enableTimestamp)n="["+(new Date).toISOString()+"] "+n;if(this._config.prefix&&(n="["+this._config.prefix+"] "+n),n="["+exports.LogLevel[e].toUpperCase()+"] "+n,this._config.output)this._config.output(e,n);else{for(var i=arguments.length,r=new Array(i>2?i-2:0),s=2;s<i;s++)r[s-2]=arguments[s];this.outputToConsole.apply(this,[e,n].concat(r))}}},t.outputToConsole=function(e,t){for(var n=this._config.enableColors?this.getColors():null,i=arguments.length,r=new Array(i>2?i-2:0),s=2;s<i;s++)r[s-2]=arguments[s];switch(e){case exports.LogLevel.Debug:var o,a;if(n)(o=console).debug.apply(o,[""+n.debug+t+n.reset].concat(r));else(a=console).debug.apply(a,[t].concat(r));break;case exports.LogLevel.Info:var c,u;if(n)(c=console).info.apply(c,[""+n.info+t+n.reset].concat(r));else(u=console).info.apply(u,[t].concat(r));break;case exports.LogLevel.Warn:var h,l;if(n)(h=console).warn.apply(h,[""+n.warn+t+n.reset].concat(r));else(l=console).warn.apply(l,[t].concat(r));break;case exports.LogLevel.Error:var f,d;if(n)(f=console).error.apply(f,[""+n.error+t+n.reset].concat(r));else(d=console).error.apply(d,[t].concat(r));break;case exports.LogLevel.Fatal:var p,y;if(n)(p=console).error.apply(p,[""+n.fatal+t+n.reset].concat(r));else(y=console).error.apply(y,[t].concat(r))}},t.getColors=function(){return a({},{debug:q.BRIGHT_BLACK,info:q.GREEN,warn:q.YELLOW,error:q.RED,fatal:q.BRIGHT_RED,reset:q.RESET},this._config.colors)},e}(),Q=function(){function e(){this._loggers=new Map,this._defaultLevel=exports.LogLevel.Info,this._defaultLogger=new G({level:this._defaultLevel})}e.getInstance=function(){return e._instance||(e._instance=new e),e._instance};var t=e.prototype;return t.getLogger=function(e){if(!e)return this._defaultLogger;if(!this._loggers.has(e)){var t=new G({prefix:e,level:this._defaultLevel});this._loggers.set(e,t)}return this._loggers.get(e)},t.setLogger=function(e,t){this._loggers.set(e,t)},t.setGlobalLevel=function(e){this._defaultLevel=e,this._defaultLogger instanceof G&&this._defaultLogger.setLevel(e);for(var t,n=o(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof G&&i.setLevel(e)}},t.createChildLogger=function(e,t){var n=e+"."+t;return this.getLogger(n)},t.setGlobalColors=function(e){this._defaultLogger instanceof G&&this._defaultLogger.setColors(e);for(var t,n=o(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof G&&i.setColors(e)}},t.resetColors=function(){this._defaultLogger instanceof G&&this._defaultLogger.setColors({});for(var e,t=o(this._loggers.values());!(e=t()).done;){var n=e.value;n instanceof G&&n.setColors({})}},e}(),V=Q.getInstance().getLogger();function Y(e){return Q.getInstance().getLogger(e)}Y("ReferenceTracker");var K=function(){function e(e){this._target=e}return e.prototype.deref=function(){return this._target},e}(),J="undefined"!=typeof globalThis&&globalThis.WeakRef||"undefined"!=typeof global&&global.WeakRef||"undefined"!=typeof window&&window.WeakRef||K,$=new Map;function Z(e){var t=$.get(e);return(null==t?void 0:t.deref())||null}var X=function(){function e(){this._references=new Map,this._scene=null}var t=e.prototype;return t.registerReference=function(e,t,n){var i=e.id,r=this._references.get(i);r||(r=new Set,this._references.set(i,r)),this._findRecord(r,t,n)||r.add({component:new J(t),propertyKey:n})},t.unregisterReference=function(e,t,n){var i=e.id,r=this._references.get(i);if(r){var s=this._findRecord(r,t,n);s&&(r.delete(s),0===r.size&&this._references.delete(i))}},t.clearReferencesTo=function(e){var t=this._references.get(e);if(t){for(var n,i=[],r=o(t);!(n=r()).done;){var s=n.value;s.component.deref()&&i.push(s)}for(var a=0,c=i;a<c.length;a++){var u=c[a],h=u.component.deref();h&&(h[u.propertyKey]=null)}this._references.delete(e)}},t.clearComponentReferences=function(e){for(var t,n=o(this._references.entries());!(t=n()).done;){for(var i,r=t.value,s=r[0],a=r[1],c=[],u=o(a);!(i=u()).done;){var h=i.value,l=h.component.deref();l&&l!==e||c.push(h)}for(var f=0,d=c;f<d.length;f++){var p=d[f];a.delete(p)}0===a.size&&this._references.delete(s)}},t.getReferencesTo=function(e){var t=this._references.get(e);if(!t)return[];for(var n,i=[],r=o(t);!(n=r()).done;){var s=n.value;s.component.deref()&&i.push(s)}return i},t.cleanup=function(){for(var e,t=[],n=o(this._references.entries());!(e=n()).done;){for(var i,r=e.value,s=r[0],a=r[1],c=[],u=o(a);!(i=u()).done;){var h=i.value;h.component.deref()||c.push(h)}for(var l=0,f=c;l<f.length;l++){var d=f[l];a.delete(d)}0===a.size&&t.push(s)}for(var p=0,y=t;p<y.length;p++){var m=y[p];this._references.delete(m)}},t.setScene=function(e){this._scene=new J(e)},t.registerEntityScene=function(e,t){$.set(e,new J(t))},t.unregisterEntityScene=function(e){$.delete(e)},t.getDebugInfo=function(){for(var e,t={},n=o(this._references.entries());!(e=n()).done;){for(var i,r=e.value,s=r[0],a=[],c=o(r[1]);!(i=c()).done;){var u=i.value,h=u.component.deref();h&&a.push({componentId:h.id,propertyKey:u.propertyKey})}a.length>0&&(t["entity_"+s]=a)}return t},t._findRecord=function(e,t,n){for(var i,r=o(e);!(i=r()).done;){var s=i.value;if(s.component.deref()===t&&s.propertyKey===n)return s}},e}(),ee=Y("EntityRefDecorator"),te=Symbol("EntityRefMetadata"),ne=Symbol("EntityRefValues");function ie(e){var t=e[ne];return t||(t=new Map,e[ne]=t),t}function re(e){return e&&("function"==typeof e?e:e.constructor)[te]||null}var se=function(){function e(){}var t=e.prototype;return t.collectEntityData=function(e){if(!e)return this.getEmptyEntityDebugData();var t,n=e.entities;if(!n)return this.getEmptyEntityDebugData();try{t=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeData(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:[],entityDetailsMap:{}}},t.getRawEntityList=function(e){if(!e)return[];var t=e.entities;return null!=t&&t.buffer?t.buffer.map((function(e){var t,n;return{id:e.id,name:e.name||"Entity_"+e.id,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((function(e){return H(e)})),parentId:(null===(t=e.parent)||void 0===t?void 0:t.id)||null,childIds:(null===(n=e.children)||void 0===n?void 0:n.map((function(e){return e.id})))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}})):[]},t.getEntityDetails=function(e,t){try{var n,i,r;if(!t)return null;var s=t.entities;if(null==s||!s.buffer)return null;var o=s.buffer.find((function(t){return t.id===e}));if(!o)return null;var c=o.getDebugInfo?o.getDebugInfo():this.buildFallbackEntityInfo(o,t),u=this.extractComponentDetails(o.components),h=this.getSceneInfo(t);return a({},c,{scene:h.name,sceneName:h.name,sceneType:h.type,parentName:(null===(n=o.parent)||void 0===n?void 0:n.name)||null,components:u||[],componentCount:(null===(i=o.components)||void 0===i?void 0:i.length)||0,componentTypes:(null===(r=o.components)||void 0===r?void 0:r.map((function(e){return H(e)})))||[]})}catch(e){return{error:"获取实体详情失败: "+(e instanceof Error?e.message:String(e)),scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}},t.getSceneInfo=function(e){var t="当前场景",n="Scene";try{if(e.name&&"string"==typeof e.name&&e.name.trim())t=e.name.trim();else if(e.constructor&&e.constructor.name)t=e.constructor.name,n=e.constructor.name;else if(e._name&&"string"==typeof e._name&&e._name.trim())t=e._name.trim();else{var i,r=null===(i=Object.getPrototypeOf(e))||void 0===i||null===(i=i.constructor)||void 0===i?void 0:i.name;r&&"Object"!==r&&(t=r,n=r)}}catch(e){t="场景名获取失败"}return{name:t,type:n}},t.collectEntityDataWithMemory=function(e){if(!e)return this.getEmptyEntityDebugData();var t,n=e.entities;if(!n)return this.getEmptyEntityDebugData();try{t=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(e){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeDataWithMemory(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:this.buildEntityHierarchyTree(n),entityDetailsMap:this.buildEntityDetailsMap(n,e)}},t.collectArchetypeData=function(e){var t;if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(e.archetypeSystem);var n={entities:(null===(t=e.entities)||void 0===t?void 0:t.buffer)||[]};return{distribution:this.getArchetypeDistributionFast(n),topEntities:this.getTopEntitiesByComponentsFast(n)}},t.getArchetypeDistributionFast=function(e){var t=new Map;return e&&e.entities&&e.entities.forEach((function(e){var n,i=(null===(n=e.components)||void 0===n?void 0:n.map((function(e){return H(e)})))||[],r=i.length>0?i.sort().join(", "):"无组件",s=t.get(r);s?s.count++:t.set(r,{count:1,componentTypes:i})})),Array.from(t.entries()).map((function(e){return{signature:e[0],count:e[1].count,memory:0}})).sort((function(e,t){return t.count-e.count})).slice(0,20)},t.getTopEntitiesByComponentsFast=function(e){return e&&e.entities?e.entities.map((function(e){var t;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0}})).sort((function(e,t){return t.componentCount-e.componentCount})):[]},t.collectArchetypeDataWithMemory=function(e){var t;if(e&&e.archetypeSystem&&"function"==typeof e.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(e.archetypeSystem);var n={entities:(null===(t=e.entities)||void 0===t?void 0:t.buffer)||[]};return{distribution:this.getArchetypeDistributionWithMemory(n),topEntities:this.getTopEntitiesByComponentsWithMemory(n)}},t.extractArchetypeStatistics=function(e){var t=e.getAllArchetypes(),n=[],i=[];return t.forEach((function(e){var t,r,s=(null===(t=e.componentTypes)||void 0===t?void 0:t.map((function(e){return e.name})).join(","))||"Unknown",o=(null===(r=e.entities)||void 0===r?void 0:r.length)||0;n.push({signature:s,count:o,memory:0}),e.entities&&e.entities.forEach((function(e){var t;i.push({id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0})}))})),n.sort((function(e,t){return t.count-e.count})),i.sort((function(e,t){return t.componentCount-e.componentCount})),{distribution:n,topEntities:i}},t.extractArchetypeStatisticsWithMemory=function(e){var t=this,n=e.getAllArchetypes(),i=[],r=[];return n.forEach((function(e){var n,s,o=(null===(n=e.componentTypes)||void 0===n?void 0:n.map((function(e){return e.name})).join(","))||"Unknown",a=(null===(s=e.entities)||void 0===s?void 0:s.length)||0,c=0;if(e.entities&&e.entities.length>0){for(var u=Math.min(5,e.entities.length),h=0,l=0;l<u;l++)h+=t.estimateEntityMemoryUsage(e.entities[l]);c=h/u*a}i.push({signature:o,count:a,memory:c}),e.entities&&e.entities.forEach((function(e){var n;r.push({id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(n=e.components)||void 0===n?void 0:n.length)||0,memory:t.estimateEntityMemoryUsage(e)})}))})),i.sort((function(e,t){return t.count-e.count})),r.sort((function(e,t){return t.componentCount-e.componentCount})),{distribution:i,topEntities:r}},t.getArchetypeDistribution=function(e){var t=new Map;return e&&e.entities&&e.entities.forEach((function(e){var n,i=(null===(n=e.componentMask)||void 0===n?void 0:n.toString())||"0",r=t.get(i);t.set(i,(r||0)+1)})),Array.from(t.entries()).map((function(e){return{signature:e[0],count:e[1],memory:0}})).sort((function(e,t){return t.count-e.count}))},t.getArchetypeDistributionWithMemory=function(e){var t=this,n=new Map;return e&&e.entities&&e.entities.forEach((function(e){var i,r=(null===(i=e.components)||void 0===i?void 0:i.map((function(e){return H(e)})))||[],s=r.length>0?r.sort().join(", "):"无组件",o=n.get(s),a=t.estimateEntityMemoryUsage(e);(isNaN(a)||a<0)&&(a=0),o?(o.count++,o.memory+=a):n.set(s,{count:1,memory:a,componentTypes:r})})),Array.from(n.entries()).map((function(e){var t=e[0],n=e[1];return{signature:t,count:n.count,memory:isNaN(n.memory)?0:n.memory}})).sort((function(e,t){return t.count-e.count}))},t.getTopEntitiesByComponents=function(e){return e&&e.entities?e.entities.map((function(e){var t;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(t=e.components)||void 0===t?void 0:t.length)||0,memory:0}})).sort((function(e,t){return t.componentCount-e.componentCount})):[]},t.getTopEntitiesByComponentsWithMemory=function(e){var t=this;return e&&e.entities?e.entities.map((function(e){var n;return{id:e.id.toString(),name:e.name||"Entity_"+e.id,componentCount:(null===(n=e.components)||void 0===n?void 0:n.length)||0,memory:t.estimateEntityMemoryUsage(e)}})).sort((function(e,t){return t.componentCount-e.componentCount})):[]},t.getEmptyEntityDebugData=function(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}},t.calculateFallbackEntityStats=function(e){var t=e.buffer||[],n=t.filter((function(e){return e.enabled&&!e._isDestroyed}));return{totalEntities:t.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?t.reduce((function(e,t){var n;return e+((null===(n=t.components)||void 0===n?void 0:n.length)||0)}),0)/n.length:0}},t.estimateEntityMemoryUsage=function(e){var t=this;try{var n=0,i=this.calculateObjectSize(e,["components","children","parent"]);return!isNaN(i)&&i>0&&(n+=i),e.components&&Array.isArray(e.components)&&e.components.forEach((function(e){var i=t.calculateObjectSize(e,["entity"]);!isNaN(i)&&i>0&&(n+=i)})),isNaN(n)||n<0?0:n}catch(e){return 0}},t.calculateObjectSize=function(e,t){if(void 0===t&&(t=[]),!e||"object"!=typeof e)return 0;var n=new WeakSet,i=function(e,r){if(void 0===r&&(r=0),!e||"object"!=typeof e||r>=2)return 0;if(n.has(e))return 0;n.add(e);var s=32;try{for(var o=Object.keys(e),a=Math.min(o.length,20),c=0;c<a;c++){var u=o[c];if(!(t.includes(u)||"constructor"===u||"__proto__"===u||u.startsWith("_cc_")||u.startsWith("__"))){var h=e[u];s+=2*u.length,"string"==typeof h?s+=Math.min(2*h.length,200):"number"==typeof h?s+=8:"boolean"==typeof h?s+=4:Array.isArray(h)?s+=40+Math.min(8*h.length,160):"object"==typeof h&&null!==h&&(s+=i(h,r+1))}}}catch(e){return 64}return s};try{var r=i(e);return Math.max(r,32)}catch(e){return 64}},t.buildEntityHierarchyTree=function(e){var t=this;if(null==e||!e.buffer)return[];var n=[];return e.buffer.forEach((function(e){if(!e.parent){var i=t.buildEntityHierarchyNode(e);n.push(i)}})),n.sort((function(e,t){return e.name<t.name?-1:e.name>t.name?1:e.id-t.id})),n},t.buildEntityHierarchyNode=function(e){var t,n=this,i={id:e.id,name:e.name||"Entity_"+e.id,active:!1!==e.active,enabled:!1!==e.enabled,activeInHierarchy:!1!==e.activeInHierarchy,componentCount:e.components.length,componentTypes:e.components.map((function(e){return H(e)})),parentId:(null===(t=e.parent)||void 0===t?void 0:t.id)||null,children:[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0};(e.children&&e.children.length>0&&(i.children=e.children.map((function(e){return n.buildEntityHierarchyNode(e)}))),"function"==typeof e.getDebugInfo)&&(i=a({},i,e.getDebugInfo()));return e.components&&e.components.length>0&&(i.componentDetails=this.extractComponentDetails(e.components)),i},t.buildEntityDetailsMap=function(e,t){var n=this;if(null==e||!e.buffer)return{};for(var i={},r=e.buffer,s=0;s<r.length;s+=100){r.slice(s,s+100).forEach((function(e){var r,s=e.getDebugInfo?e.getDebugInfo():n.buildFallbackEntityInfo(e,t),o=e.getComponentCacheStats?e.getComponentCacheStats():null,c=n.extractComponentDetails(e.components);i[e.id]=a({},s,{parentName:(null===(r=e.parent)||void 0===r?void 0:r.name)||null,components:c,componentTypes:s.componentTypes||c.map((function(e){return e.typeName})),cachePerformance:o?{hitRate:o.cacheStats.hitRate,size:o.cacheStats.size,maxSize:o.cacheStats.maxSize}:null})}))}return i},t.buildFallbackEntityInfo=function(e,t){var n,i,r,s=this.getSceneInfo(t);return{name:e.name||"Entity_"+e.id,id:e.id,enabled:!1!==e.enabled,active:!1!==e.active,activeInHierarchy:!1!==e.activeInHierarchy,destroyed:e.isDestroyed||!1,scene:s.name,sceneName:s.name,sceneType:s.type,componentCount:e.components.length,componentTypes:e.components.map((function(e){return H(e)})),componentMask:(null===(n=e.componentMask)||void 0===n?void 0:n.toString())||"0",parentId:(null===(i=e.parent)||void 0===i?void 0:i.id)||null,childCount:(null===(r=e.children)||void 0===r?void 0:r.length)||0,childIds:e.children.map((function(e){return e.id}))||[],depth:e.getDepth?e.getDepth():0,tag:e.tag||0,updateOrder:e.updateOrder||0}},t.extractComponentDetails=function(e){var t=this;return e.map((function(e){var n=H(e),i={};try{Object.keys(e).forEach((function(n){if(!n.startsWith("_")&&"entity"!==n&&"constructor"!==n){var r=e[n];null!=r&&(i[n]=t.formatPropertyValue(r))}})),0===Object.keys(i).length&&(i._info="该组件没有公开属性",i._componentId=H(e))}catch(t){i._error="属性提取失败",i._componentId=H(e)}return{typeName:n,properties:i}}))},t.getComponentProperties=function(e,t,n){var i=this;try{if(!n)return{};var r=n.entities;if(null==r||!r.buffer)return{};var s=r.buffer.find((function(t){return t.id===e}));if(!s||t>=s.components.length)return{};var o=s.components[t],a={};return Object.keys(o).forEach((function(e){if(!e.startsWith("_")&&"entity"!==e){var t=o[e];null!=t&&(a[e]=i.formatPropertyValue(t))}})),a}catch(e){return{_error:"属性提取失败"}}},t.formatPropertyValue=function(e,t){return void 0===t&&(t=0),null==e?e:"object"!=typeof e?"string"==typeof e&&e.length>200?"[长字符串: "+e.length+"字符] "+e.substring(0,100)+"...":e:0===t?this.formatObjectFirstLevel(e):this.createLazyLoadPlaceholder(e)},t.formatObjectFirstLevel=function(e){var t=this;try{if(Array.isArray(e)){if(0===e.length)return[];if(e.length>10){var n=e.slice(0,3).map((function(e){return t.formatPropertyValue(e,1)}));return{_isLazyArray:!0,_arrayLength:e.length,_sample:n,_summary:"数组["+e.length+"个元素]"}}return e.map((function(e){return t.formatPropertyValue(e,1)}))}var i=Object.keys(e);if(0===i.length)return{};for(var r={},s=0,o=0,a=i;o<a.length;o++){var c=a[o];if(s>=15){r._hasMoreProperties=!0,r._totalProperties=i.length,r._hiddenCount=i.length-s;break}if(!c.startsWith("_")&&!c.startsWith("$")&&"function"!=typeof e[c])try{var u=e[c];null!=u&&(r[c]=this.formatPropertyValue(u,1),s++)}catch(e){r[c]="[访问失败: "+(e instanceof Error?e.message:String(e))+"]",s++}}return r}catch(e){return"[对象解析失败: "+(e instanceof Error?e.message:String(e))+"]"}},t.createLazyLoadPlaceholder=function(e){try{var t,n=(null===(t=e.constructor)||void 0===t?void 0:t.name)||"Object";return{_isLazyObject:!0,_typeName:n,_summary:this.getObjectSummary(e,n),_objectId:this.generateObjectId(e)}}catch(e){return{_isLazyObject:!0,_typeName:"Unknown",_summary:"无法分析的对象: "+(e instanceof Error?e.message:String(e)),_objectId:Math.random().toString(36).substr(2,9)}}},t.getObjectSummary=function(e,t){try{if((t.toLowerCase().includes("vec")||t.toLowerCase().includes("vector"))&&void 0!==e.x&&void 0!==e.y){var n=void 0!==e.z?e.z:"";return t+"("+e.x+", "+e.y+(n?", "+n:"")+")"}if(t.toLowerCase().includes("color")&&void 0!==e.r&&void 0!==e.g&&void 0!==e.b){var i=void 0!==e.a?e.a:1;return t+"("+e.r+", "+e.g+", "+e.b+", "+i+")"}if(t.toLowerCase().includes("node"))return t+": "+(e.name||e._name||"未命名");if(t.toLowerCase().includes("component")){var r,s,o=(null===(r=e.node)||void 0===r?void 0:r.name)||(null===(s=e.node)||void 0===s?void 0:s._name)||"";return t+(o?" on "+o:"")}var a=Object.keys(e);return 0===a.length?t+" (空对象)":t+" ("+a.length+"个属性)"}catch(e){return t+" (无法分析)"}},t.generateObjectId=function(e){try{return void 0!==e.id?"obj_"+e.id:void 0!==e._id?"obj_"+e._id:void 0!==e.uuid?"obj_"+e.uuid:void 0!==e._uuid?"obj_"+e._uuid:"obj_"+Math.random().toString(36).substr(2,9)}catch(e){return"obj_"+Math.random().toString(36).substr(2,9)}},t.expandLazyObject=function(e,t,n,i){try{if(!i)return null;var r=i.entities;if(null==r||!r.buffer)return null;var s=r.buffer.find((function(t){return t.id===e}));if(!s)return null;if(t>=s.components.length)return null;var o=s.components[t],a=this.getObjectByPath(o,n);return a?this.formatObjectFirstLevel(a):null}catch(e){return{error:"展开失败: "+(e instanceof Error?e.message:String(e))}}},t.getObjectByPath=function(e,t){if(!t)return e;for(var n,i=e,r=o(t.split("."));!(n=r()).done;){var s=n.value;if(null==i)return null;if(s.includes("[")&&s.includes("]")){var a=s.substring(0,s.indexOf("[")),c=parseInt(s.substring(s.indexOf("[")+1,s.indexOf("]")));if(a&&(i=i[a]),!(Array.isArray(i)&&c>=0&&c<i.length))return null;i=i[c]}else i=i[s]}return i},e}(),oe=function(){function e(){}return e.prototype.collectSystemData=function(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};var n=t.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};var i=n.processors||[],r=new Map,s=new Map;if(e)try{r=e.getAllSystemStats(),s=e.getAllSystemData()}catch(e){}return{totalSystems:i.length,systemsInfo:i.map((function(e){var t,n=e.systemName||j(e),i=r.get(n),o=s.get(n);return{name:n,type:j(e),entityCount:(null===(t=e.entities)||void 0===t?void 0:t.length)||0,executionTime:(null==i?void 0:i.averageTime)||(null==o?void 0:o.executionTime)||0,minExecutionTime:(null==i?void 0:i.minTime)===Number.MAX_VALUE?0:(null==i?void 0:i.minTime)||0,maxExecutionTime:(null==i?void 0:i.maxTime)||0,executionTimeHistory:(null==i?void 0:i.recentTimes)||[],updateOrder:e.updateOrder||0,enabled:!1!==e.enabled,lastUpdateTime:(null==o?void 0:o.lastUpdateTime)||0}}))}},e}(),ae=function(){function e(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.lastGCCount=0,this.gcCollections=0,this.lastMemoryCheck=0}var t=e.prototype;return t.collectPerformanceData=function(e){var t=_.deltaTime,n=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),s=r.totalExecutionTime,o=n>0?s/n*100:0,a=0;performance.memory&&(a=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(s),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();var c=this.frameTimeHistory.filter((function(e){return e>=0}));return{frameTime:s,engineFrameTime:n,ecsPercentage:o,memoryUsage:a,fps:i,averageFrameTime:c.length>0?c.reduce((function(e,t){return e+t}),0)/c.length:s,minFrameTime:c.length>0?Math.min.apply(Math,c):s,maxFrameTime:c.length>0?Math.max.apply(Math,c):s,frameTimeHistory:[].concat(this.frameTimeHistory),systemPerformance:this.getSystemPerformance(e),systemBreakdown:r.systemBreakdown,memoryDetails:this.getMemoryDetails()}},t.getECSPerformanceData=function(e){if(!e)return{totalExecutionTime:0,systemBreakdown:[]};if(!e.enabled){try{e.enabled=!0}catch(e){}return{totalExecutionTime:0,systemBreakdown:[]}}try{var t=0,n=[],i=e.getAllSystemStats();if(0===i.size)return{totalExecutionTime:0,systemBreakdown:[]};for(var r,s=o(i.entries());!(r=s()).done;){var a=r.value,c=a[0],u=a[1],h=u.recentTimes&&u.recentTimes.length>0?u.recentTimes[u.recentTimes.length-1]:u.averageTime||0;t+=h,n.push({systemName:c,executionTime:h,percentage:0})}return n.forEach((function(e){e.percentage=t>0?e.executionTime/t*100:0})),n.sort((function(e,t){return t.executionTime-e.executionTime})),{totalExecutionTime:t,systemBreakdown:n}}catch(e){return{totalExecutionTime:0,systemBreakdown:[]}}},t.getSystemPerformance=function(e){if(!e)return[];try{var t=e.getAllSystemStats(),n=e.getAllSystemData();return Array.from(t.entries()).map((function(e){var t=e[0],i=e[1],r=n.get(t);return{systemName:t,averageTime:i.averageTime||0,maxTime:i.maxTime||0,minTime:i.minTime===Number.MAX_VALUE?0:i.minTime||0,samples:i.executionCount||0,percentage:0,entityCount:(null==r?void 0:r.entityCount)||0,lastExecutionTime:(null==r?void 0:r.executionTime)||0}}))}catch(e){return[]}},t.getMemoryDetails=function(){var e={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){var t=performance.memory;if(e.totalMemory=t.jsHeapSizeLimit||536870912,e.usedMemory=t.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,this.lastMemoryCheck>0)this.lastMemoryCheck-e.usedMemory>1048576&&this.gcCollections++;this.lastMemoryCheck=e.usedMemory}else e.totalMemory=536870912,e.freeMemory=536870912}catch(e){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return e},t.updateGCCount=function(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(e){return this.gcCollections}},e}(),ce=function(){function e(e,t,n,i,r){void 0===n&&(n=1e3),void 0===i&&(i=10),void 0===r&&(r=1.5),this.pool=[],this.stats={totalCreated:0,totalAcquired:0,totalReleased:0},this.createFn=e,this.resetFn=t,this.maxSize=n,this.minSize=Math.max(1,i),this.growthFactor=Math.max(1.1,r)}var t=e.prototype;return t.acquire=function(){return this.stats.totalAcquired++,this.pool.length>0?this.pool.pop():(this.stats.totalCreated++,this.createFn())},t.release=function(e){this.stats.totalReleased++,this.pool.length>=this.maxSize||(this.resetFn&&this.resetFn(e),this.pool.push(e))},t.prewarm=function(e){for(var t=Math.min(e,this.maxSize),n=this.pool.length;n<t;n++){var i=this.createFn();this.resetFn&&this.resetFn(i),this.pool.push(i),this.stats.totalCreated++}},t.shrink=function(){for(;this.pool.length>this.minSize;)this.pool.pop()},t.clear=function(){this.pool.length=0},t.getAvailableCount=function(){return this.pool.length},t.getMaxSize=function(){return this.maxSize},t.getStats=function(){var e=0===this.stats.totalAcquired?0:(this.stats.totalAcquired-this.stats.totalCreated)/this.stats.totalAcquired;return{totalCreated:this.stats.totalCreated,totalAcquired:this.stats.totalAcquired,totalReleased:this.stats.totalReleased,hitRate:e,currentSize:this.pool.length,maxSize:this.maxSize,minSize:this.minSize,utilizationRate:this.pool.length/this.maxSize}},e}(),ue=function(){function e(){this.pools=new Map,this.usageTracker=new Map,this.autoCleanupInterval=6e4,this.lastCleanupTime=0}e.getInstance=function(){return e.instance||(e.instance=new e),e.instance};var t=e.prototype;return t.registerPool=function(e,t,n,i,r){this.pools.set(e,new ce(t,n,i,r)),this.usageTracker.set(e,{createCount:0,releaseCount:0,lastAccessTime:Date.now()})},t.acquireComponent=function(e){var t=this.pools.get(e);return this.trackUsage(e,"create"),t?t.acquire():null},t.releaseComponent=function(e,t){var n=this.pools.get(e);this.trackUsage(e,"release"),n&&n.release(t)},t.trackUsage=function(e,t){var n=this.usageTracker.get(e);n||(n={createCount:0,releaseCount:0,lastAccessTime:Date.now()},this.usageTracker.set(e,n)),"create"===t?n.createCount++:n.releaseCount++,n.lastAccessTime=Date.now()},t.update=function(){var e=Date.now();if(!(e-this.lastCleanupTime<this.autoCleanupInterval)){for(var t,n=o(this.usageTracker.entries());!(t=n()).done;){var i=t.value,r=i[0];if(e-i[1].lastAccessTime>12e4){var s=this.pools.get(r);s&&s.shrink()}}this.lastCleanupTime=e}},t.getHotComponents=function(e){return void 0===e&&(e=100),Array.from(this.usageTracker.entries()).filter((function(t){return t[0],t[1].createCount>e})).map((function(e){return e[0]}))},t.prewarmAll=function(e){void 0===e&&(e=100);for(var t,n=o(this.pools.values());!(t=n()).done;){t.value.prewarm(e)}},t.clearAll=function(){for(var e,t=o(this.pools.values());!(e=t()).done;){e.value.clear()}},t.reset=function(){this.pools.clear(),this.usageTracker.clear()},t.getGlobalStats=function(){for(var e,t=[],n=o(this.pools.entries());!(e=n()).done;){var i=e.value,r=i[0],s=i[1];t.push({componentName:r,poolStats:s.getStats(),usage:this.usageTracker.get(r)})}return t},t.getPoolStats=function(){for(var e,t=new Map,n=o(this.pools);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];t.set(r,{available:s.getAvailableCount(),maxSize:s.getMaxSize()})}return t},t.getPoolUtilization=function(){for(var e,t=new Map,n=o(this.pools);!(e=n()).done;){var i=e.value,r=i[0],s=i[1],a=s.getAvailableCount(),c=s.getMaxSize(),u=c-a,h=c>0?u/c*100:0;t.set(r,{used:u,total:c,utilization:h})}return t},t.getComponentUtilization=function(e){var t=this.pools.get(e);if(!t)return 0;var n=t.getAvailableCount(),i=t.getMaxSize();return i>0?(i-n)/i*100:0},e}(),he=function(){function e(){}var t=e.prototype;return t.collectComponentData=function(e){var t=this;if(!e)return{componentTypes:0,componentInstances:0,componentStats:[]};var n=e.entities;if(null==n||!n.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};var i=new Map,r=0;n.buffer.forEach((function(e){e.components&&e.components.forEach((function(e){var t=H(e),n=i.get(t)||{count:0,entities:0};n.count++,r++,i.set(t,n)}))}));var s=new Map,a=new Map;try{for(var c,u=ue.getInstance(),h=u.getPoolStats(),l=u.getPoolUtilization(),f=o(h.entries());!(c=f()).done;){var d=c.value,p=d[0],y=d[1];a.set(p,y.maxSize)}for(var m,g=o(l.entries());!(m=g()).done;){var v=m.value,_=v[0],S=v[1];s.set(_,S.utilization)}}catch(e){}return{componentTypes:i.size,componentInstances:r,componentStats:Array.from(i.entries()).map((function(i){var r=i[0],o=i[1],c=a.get(r)||0,u=s.get(r)||0,h=t.getEstimatedComponentSize(r,e);return{typeName:r,instanceCount:o.count,memoryPerInstance:h,totalMemory:o.count*h,poolSize:c,poolUtilization:u,averagePerEntity:o.count/n.buffer.length}}))}},t.getEstimatedComponentSize=function(t,n){if(e.componentSizeCache.has(t))return e.componentSizeCache.get(t);if(!n)return 64;var i=n.entities;if(null==i||!i.buffer)return 64;var r=64;try{for(var s,a=o(i.buffer);!(s=a()).done;){var c=s.value;if(c.components){var u=c.components.find((function(e){return H(e)===t}));if(u){r=this.calculateQuickObjectSize(u);break}}}}catch(e){r=64}return e.componentSizeCache.set(t,r),r},t.calculateQuickObjectSize=function(e){if(!e||"object"!=typeof e)return 8;var t=32,n=new WeakSet,i=function(e,t){if(void 0===t&&(t=0),!e||"object"!=typeof e||n.has(e)||t>3)return 0;n.add(e);var r=0;try{for(var s=Object.keys(e),o=0;o<Math.min(s.length,20);o++){var a=s[o];if("entity"!==a&&"_entity"!==a&&"constructor"!==a){var c=e[a];r+=2*a.length,"string"==typeof c?r+=Math.min(2*c.length,200):"number"==typeof c?r+=8:"boolean"==typeof c?r+=4:"object"==typeof c&&null!==c&&(r+=i(c,t+1))}}}catch(e){return 32}return r};return t+=i(e),Math.max(t,32)},t.calculateDetailedComponentMemory=function(e,t){if(!t)return this.getEstimatedComponentSize(e,t);var n=t.entities;if(null==n||!n.buffer)return this.getEstimatedComponentSize(e,t);try{for(var i,r=o(n.buffer);!(i=r()).done;){var s=i.value;if(s.components){var a=s.components.find((function(t){return H(t)===e}));if(a)return this.estimateObjectSize(a)}}}catch(e){}return this.getEstimatedComponentSize(e,t)},t.estimateObjectSize=function(e,t,n){if(void 0===t&&(t=new WeakSet),void 0===n&&(n=0),null==e||n>10)return 0;if(t.has(e))return 0;var i=0;switch(typeof e){case"boolean":i=4;break;case"number":default:i=8;break;case"string":i=24+Math.min(2*e.length,1e3);break;case"object":if(t.add(e),Array.isArray(e)){i=40+8*e.length;for(var r=Math.min(e.length,50),s=0;s<r;s++)i+=this.estimateObjectSize(e[s],t,n+1)}else{i=32;try{for(var o=Object.getOwnPropertyNames(e),a=Math.min(o.length,30),c=0;c<a;c++){var u=o[c];if("constructor"!==u&&"__proto__"!==u&&"entity"!==u&&"_entity"!==u&&!u.startsWith("_cc_")&&!u.startsWith("__"))try{i+=16+2*u.length;var h=e[u];null!=h&&(i+=this.estimateObjectSize(h,t,n+1))}catch(e){continue}}}catch(e){i=128}}}return 8*Math.ceil(i/8)},e.clearCache=function(){e.componentSizeCache.clear()},e}();he.componentSizeCache=new Map;var le,fe=function(){function e(){this.sceneStartTime=Date.now()}var t=e.prototype;return t.collectSceneData=function(e){var t,n;if(!e)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneMemory:0,sceneUptime:0};var i=(Date.now()-this.sceneStartTime)/1e3,r=e.entities,s=e.entityProcessors;return{currentSceneName:e.name||"Unnamed Scene",isInitialized:e._didSceneBegin||!1,sceneRunTime:i,sceneEntityCount:(null==r||null===(t=r.buffer)||void 0===t?void 0:t.length)||0,sceneSystemCount:(null==s||null===(n=s.processors)||void 0===n?void 0:n.length)||0,sceneMemory:0,sceneUptime:i}},t.setSceneStartTime=function(e){this.sceneStartTime=e},e}(),de=function(){function e(e,t){void 0===t&&(t=!0),this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectInterval=2e3,this.url=e,this.autoReconnect=t}var t=e.prototype;return t.setMessageHandler=function(e){this.messageHandler=e},t.connect=function(){var e=this;return new Promise((function(t,n){try{e.ws=new WebSocket(e.url),e.ws.onopen=function(n){e.handleOpen(n),t()},e.ws.onclose=function(t){e.handleClose(t)},e.ws.onerror=function(t){e.handleError(t),n(t)},e.ws.onmessage=function(t){e.handleMessage(t)}}catch(t){e.handleConnectionFailure(t),n(t)}}))},t.disconnect=function(){this.ws&&(this.autoReconnect=!1,this.ws.close(),this.ws=void 0),this.isConnected=!1},t.send=function(e){if(this.isConnected&&this.ws)try{var t="string"==typeof e?e:JSON.stringify(e);this.ws.send(t)}catch(e){}},t.getConnectionStatus=function(){return this.isConnected},t.setMaxReconnectAttempts=function(e){this.maxReconnectAttempts=e},t.setReconnectInterval=function(e){this.reconnectInterval=e},t.scheduleReconnect=function(){var e=this;this.reconnectTimer&&clearTimeout(this.reconnectTimer);var t=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout((function(){e.connect().catch((function(t){e.reconnectAttempts<e.maxReconnectAttempts&&e.scheduleReconnect()}))}),t)},t.handleMessage=function(e){try{var t=JSON.parse(e.data);this.messageHandler&&this.messageHandler(t)}catch(e){}},t.handleOpen=function(e){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(e)},t.handleClose=function(e){this.isConnected=!1,this.onClose&&this.onClose(e),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()},t.handleError=function(e){this.onError&&this.onError(e)},t.handleConnectionFailure=function(e){this.onError&&this.onError(e)},e}();!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(le||(le={}));var pe=function(){function e(){}return e.create=function(t){if(t<0)throw new Error("Bit index "+t+" out of range [0, ∞)");var n={base:[0,0],segments:void 0};return e.setBit(n,t),n},e.fromNumber=function(e){return{base:[e>>>0,0],segments:void 0}},e.hasAny=function(e,t){var n=t.base,i=e.base,r=t.segments,s=e.segments,o=0!==(i[le.LOW]&n[le.LOW])||0!==(i[le.HIGH]&n[le.HIGH]);return!o&&r&&s?s.some((function(e,t){return 0!==(e[le.LOW]&r[t][le.LOW])||0!==(e[le.HIGH]&r[t][le.HIGH])})):o},e.hasAll=function(e,t){var n,i=e.base,r=t.base,s=e.segments,o=t.segments,a=(i[le.LOW]&r[le.LOW])===r[le.LOW]&&(i[le.HIGH]&r[le.HIGH])===r[le.HIGH];if(!a||!o)return a;var c=null!==(n=null==s?void 0:s.length)&&void 0!==n?n:0;if(s)for(var u=0;u<Math.min(c,o.length);u++)if((s[u][le.LOW]&o[u][le.LOW])!==o[u][le.LOW]||(s[u][le.HIGH]&o[u][le.HIGH])!==o[u][le.HIGH])return!1;for(var h=c;h<o.length;h++)if(0!==o[h][le.LOW]||0!==o[h][le.HIGH])return!1;return!0},e.hasNone=function(e,t){var n=e.base,i=t.base,r=e.segments,s=t.segments,o=0===(n[le.LOW]&i[le.LOW])&&0===(n[le.HIGH]&i[le.HIGH]);return r&&o&&s?r.every((function(e,t){return 0===(e[le.LOW]&s[t][le.LOW])&&0===(e[le.HIGH]&s[t][le.HIGH])})):o},e.isZero=function(e){var t=0===e.base[le.LOW]&&0===e.base[le.HIGH];return e.segments&&t?e.segments.every((function(e){return 0===e[le.LOW]&&0===e[le.HIGH]})):t},e.equals=function(e,t){var n,i,r=e.base[le.LOW]===t.base[le.LOW]&&e.base[le.HIGH]===t.base[le.HIGH];if(!r||!e.segments&&!t.segments)return r;for(var s=null!==(n=e.segments)&&void 0!==n?n:[],o=null!==(i=t.segments)&&void 0!==i?i:[],a=0;a<Math.max(s.length,o.length);a++){var c=s[a],u=o[a];if(c&&!u){if(0!==c[le.LOW]||0!==c[le.HIGH])return!1}else if(!c&&u){if(0!==u[le.LOW]||0!==u[le.HIGH])return!1}else if(c[le.LOW]!==u[le.LOW]||c[le.HIGH]!==u[le.HIGH])return!1}return!0},e.setBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var i=e.getSegmentByBitIndex(t,n),r=63&n;r<32?i[le.LOW]|=1<<r:i[le.HIGH]|=1<<r-32},e.getBit=function(t,n){if(n<0)return!1;var i=e.getSegmentByBitIndex(t,n,!1);if(!i)return!1;var r=63&n;return r<32?!!(i[le.LOW]&1<<r):!!(i[le.HIGH]&1<<r-32)},e.clearBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var i=e.getSegmentByBitIndex(t,n,!1);if(i){var r=63&n;r<32?i[le.LOW]&=~(1<<r):i[le.HIGH]&=~(1<<r-32)}},e.orInPlace=function(e,t){e.base[le.LOW]|=t.base[le.LOW],e.base[le.HIGH]|=t.base[le.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++)i[r][le.LOW]|=n[r][le.LOW],i[r][le.HIGH]|=n[r][le.HIGH]}},e.andInPlace=function(e,t){e.base[le.LOW]&=t.base[le.LOW],e.base[le.HIGH]&=t.base[le.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++)i[r][le.LOW]&=n[r][le.LOW],i[r][le.HIGH]&=n[r][le.HIGH]}},e.xorInPlace=function(e,t){e.base[le.LOW]^=t.base[le.LOW],e.base[le.HIGH]^=t.base[le.HIGH];var n=t.segments;if(n&&0!=n.length){e.segments||(e.segments=[]);for(var i=e.segments;i.length<n.length;)i.push([0,0]);for(var r=0;r<n.length;r++)i[r][le.LOW]^=n[r][le.LOW],i[r][le.HIGH]^=n[r][le.HIGH]}},e.clear=function(e){e.base[le.LOW]=0,e.base[le.HIGH]=0;for(var t=0;t<(null!==(n=null===(i=e.segments)||void 0===i?void 0:i.length)&&void 0!==n?n:0);t++){var n,i,r=e.segments[t];r[le.LOW]=0,r[le.HIGH]=0}},e.copy=function(t,n){if(e.clear(n),n.base[le.LOW]=t.base[le.LOW],n.base[le.HIGH]=t.base[le.HIGH],t.segments&&0!=t.segments.length)if(n.segments){for(var i=t.segments.length-n.segments.length,r=0;r<i;r++)n.segments.push([0,0]);for(var s=0;s<length;s++){var o=n.segments[s],a=t.segments[s];o[le.LOW]=a[le.LOW],o[le.HIGH]=a[le.HIGH]}}else n.segments=t.segments.map((function(e){return[].concat(e)}))},e.clone=function(e){return{base:e.base.slice(),segments:e.segments?e.segments.map((function(e){return[].concat(e)})):void 0}},e.toString=function(e,t,n){var i,r;void 0===t&&(t=2),void 0===n&&(n=!1),2!=t&&16!=t&&(t=2);var s=null!==(i=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==i?i:0,o="";if(n){var a=0;a=2===t?66:19;for(var c=0;c<=s;c++){o+=(0===c?"0 (Base):":c+" ("+64*c+"):").toString().padEnd(a)}o+="\n"}for(var u=-1;u<s;u++){var h="",l=-1==u?e.base:e.segments[u],f=l[le.HIGH],d=l[le.LOW];if(2==t){h=f.toString(2).padStart(32,"0")+"_"+d.toString(2).padStart(32,"0")}else{var p=f?f.toString(16).toUpperCase():"";n&&(p=p.padStart(8,"0"));var y=d.toString(16).toUpperCase();p&&(y=y.padStart(8,"0")),h="0x"+p+y}o+=-1===u?h:" "+h}return o},e.popCount=function(e){for(var t=0,n=-1;n<(null!==(i=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==i?i:0);n++){for(var i,r,s=-1==n?e.base:e.segments[n],o=s[le.LOW],a=s[le.HIGH];o;)o&=o-1,t++;for(;a;)a&=a-1,t++}return t},e.getSegmentByBitIndex=function(e,t,n){if(void 0===n&&(n=!0),t<=63)return e.base;var i=e.segments;if(!i){if(!n)return null;i=e.segments=[]}var r=(t>>6)-1;if(i.length<=r){if(!n)return null;for(var s=r-i.length+1,o=0;o<s;o++)i.push([0,0])}return i[r]},e}();pe.ZERO={base:[0,0],segments:void 0};var ye=function(){function e(){}return e.inferOptimalType=function(e,t){void 0===t&&(t={});var n=typeof e;if("boolean"===n)return"uint8";if("number"!==n)return"float32";var i=t,r=i.minValue,s=i.maxValue,o=i.precision,a=i.signed;if(!0===o)return Math.abs(e)>34028235e31||void 0!==r&&Math.abs(r)>34028235e31||void 0!==s&&Math.abs(s)>34028235e31?"float64":"float32";if(!1===o||Number.isInteger(e)){var c=void 0!==r?r:e,u=void 0!==s?s:e;return!1!==a&&(c<0||e<0)?c>=-128&&u<=127?"int8":c>=-32768&&u<=32767?"int16":c>=-2147483648&&u<=2147483647?"int32":"float64":u<=255?"uint8":u<=65535?"uint16":u<=4294967295?"uint32":"float64"}return Number.isInteger(e)?e>=0&&e<=255?"uint8":e>=-128&&e<=127?"int8":e>=0&&e<=65535?"uint16":e>=-32768&&e<=32767?"int16":e>=0&&e<=4294967295?"uint32":e>=-2147483648&&e<=2147483647?"int32":"float64":"float32"},e.getTypedArrayConstructor=function(e){switch(e){case"float32":default:return Float32Array;case"float64":return Float64Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int8":return Int8Array;case"uint8":return Uint8Array;case"uint8clamped":return Uint8ClampedArray}},e}(),me=function(){function e(e){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=e,this.initializeFields(e)}var t=e.prototype;return t.initializeFields=function(t){var n=new t,i=t.__highPrecisionFields||new Set,r=t.__float64Fields||new Set,s=t.__float32Fields||new Set,o=t.__int32Fields||new Set,a=t.__uint32Fields||new Set,c=t.__int16Fields||new Set,u=t.__uint16Fields||new Set,h=t.__int8Fields||new Set,l=t.__uint8Fields||new Set,f=t.__uint8ClampedFields||new Set,d=t.__autoTypedFields||new Map,p=t.__serializeMapFields||new Set,y=t.__serializeSetFields||new Set,m=t.__serializeArrayFields||new Set;for(var g in n)if(n.hasOwnProperty(g)&&"id"!==g){var v=n[g],_=typeof v;if("number"===_)if(i.has(g));else if(d.has(g)){var S=d.get(g),C=ye.inferOptimalType(v,S),w=ye.getTypedArrayConstructor(C);this.fields.set(g,new w(this._capacity)),e._logger.info("字段 "+g+" 自动推断为 "+C+" 类型,值: "+v+", 选项:",S)}else r.has(g)?this.fields.set(g,new Float64Array(this._capacity)):o.has(g)?this.fields.set(g,new Int32Array(this._capacity)):a.has(g)?this.fields.set(g,new Uint32Array(this._capacity)):c.has(g)?this.fields.set(g,new Int16Array(this._capacity)):u.has(g)?this.fields.set(g,new Uint16Array(this._capacity)):h.has(g)?this.fields.set(g,new Int8Array(this._capacity)):l.has(g)?this.fields.set(g,new Uint8Array(this._capacity)):f.has(g)?this.fields.set(g,new Uint8ClampedArray(this._capacity)):(s.has(g),this.fields.set(g,new Float32Array(this._capacity)));else"boolean"===_?l.has(g)||!s.has(g)&&!r.has(g)?this.fields.set(g,new Uint8Array(this._capacity)):this.fields.set(g,new Float32Array(this._capacity)):"string"===_?this.stringFields.set(g,new Array(this._capacity)):"object"===_&&null!==v&&(p.has(g)||y.has(g)||m.has(g))&&this.serializedFields.set(g,new Array(this._capacity))}},t.addComponent=function(e,t){if(this.entityToIndex.has(e)){var n=this.entityToIndex.get(e);this.updateComponentAtIndex(n,t)}else{var i;this.freeIndices.length>0?i=this.freeIndices.pop():(i=this._size)>=this._capacity&&this.resize(2*this._capacity),this.entityToIndex.set(e,i),this.indexToEntity[i]=e,this.updateComponentAtIndex(i,t),this._size++}},t.updateComponentAtIndex=function(e,t){var n=this.indexToEntity[e],i=new Map,r=this.type.__highPrecisionFields||new Set,s=this.type.__serializeMapFields||new Set,o=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=this.type.__deepCopyFields||new Set;for(var u in t)if(t.hasOwnProperty(u)&&"id"!==u){var h=t[u],l=typeof h;if("number"===l)if(r.has(u)||!this.fields.has(u))i.set(u,h);else this.fields.get(u)[e]=h;else if("boolean"===l&&this.fields.has(u)){this.fields.get(u)[e]=h?1:0}else if(this.stringFields.has(u)){this.stringFields.get(u)[e]=String(h)}else if(this.serializedFields.has(u)){this.serializedFields.get(u)[e]=this.serializeValue(h,u,s,o,a)}else c.has(u)?i.set(u,this.deepClone(h)):i.set(u,h)}i.size>0&&this.complexFields.set(n,i)},t.serializeValue=function(t,n,i,r,s){try{return i.has(n)&&t instanceof Map?JSON.stringify(Array.from(t.entries())):r.has(n)&&t instanceof Set?JSON.stringify(Array.from(t)):(s.has(n)&&Array.isArray(t),JSON.stringify(t))}catch(t){return e._logger.warn("SoA序列化字段 "+n+" 失败:",t),"{}"}},t.deserializeValue=function(t,n,i,r,s){try{var o=JSON.parse(t);return i.has(n)?new Map(o):r.has(n)?new Set(o):(s.has(n),o)}catch(t){return e._logger.warn("SoA反序列化字段 "+n+" 失败:",t),null}},t.deepClone=function(e){var t=this;if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array)return e.map((function(e){return t.deepClone(e)}));if(e instanceof Map){for(var n,i=new Map,r=o(e.entries());!(n=r()).done;){var s=n.value,a=s[0],c=s[1];i.set(a,this.deepClone(c))}return i}if(e instanceof Set){for(var u,h=new Set,l=o(e.values());!(u=l()).done;){var f=u.value;h.add(this.deepClone(f))}return h}var d={};for(var p in e)e.hasOwnProperty(p)&&(d[p]=this.deepClone(e[p]));return d},t.getComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;for(var n,i=new this.type,r=this.type.__serializeMapFields||new Set,s=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=o(this.fields.entries());!(n=c()).done;){var u=n.value,h=u[0],l=u[1][t],f=this.getFieldType(h);i[h]="boolean"===f?1===l:l}for(var d,p=o(this.stringFields.entries());!(d=p()).done;){var y=d.value,m=y[0],g=y[1];i[m]=g[t]}for(var v,_=o(this.serializedFields.entries());!(v=_()).done;){var S=v.value,C=S[0],w=S[1][t];w&&(i[C]=this.deserializeValue(w,C,r,s,a))}var E=this.complexFields.get(e);if(E)for(var b,A=o(E.entries());!(b=A()).done;){var T=b.value,M=T[0],x=T[1];i[M]=x}return i},t.getFieldType=function(e){return typeof(new this.type)[e]},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.getComponent(e);return this.complexFields.delete(e),this.entityToIndex.delete(e),this.freeIndices.push(t),this._size--,n},t.resize=function(t){for(var n,i=o(this.fields.entries());!(n=i()).done;){var r=n.value,s=r[0],a=r[1],c=void 0;a instanceof Float32Array?c=new Float32Array(t):a instanceof Float64Array?c=new Float64Array(t):a instanceof Int32Array?c=new Int32Array(t):a instanceof Uint32Array?c=new Uint32Array(t):a instanceof Int16Array?c=new Int16Array(t):a instanceof Uint16Array?c=new Uint16Array(t):a instanceof Int8Array?c=new Int8Array(t):a instanceof Uint8Array?c=new Uint8Array(t):a instanceof Uint8ClampedArray?c=new Uint8ClampedArray(t):(c=new Float32Array(t),e._logger.warn("未知的TypedArray类型用于字段 "+s+",回退到Float32Array")),c.set(a),this.fields.set(s,c)}for(var u,h=o(this.stringFields.entries());!(u=h()).done;){for(var l=u.value,f=l[0],d=l[1],p=new Array(t),y=0;y<d.length;y++)p[y]=d[y];this.stringFields.set(f,p)}for(var m,g=o(this.serializedFields.entries());!(m=g()).done;){for(var v=m.value,_=v[0],S=v[1],C=new Array(t),w=0;w<S.length;w++)C[w]=S[w];this.serializedFields.set(_,C)}this._capacity=t},t.getActiveIndices=function(){return Array.from(this.entityToIndex.values())},t.getFieldArray=function(e){return this.fields.get(e)||null},t.getTypedFieldArray=function(e){return this.fields.get(String(e))||null},t.getEntityIndex=function(e){return this.entityToIndex.get(e)},t.getEntityIdByIndex=function(e){return this.indexToEntity[e]},t.size=function(){return this._size},t.clear=function(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(var e,t=o(this.fields.values());!(e=t()).done;){e.value.fill(0)}for(var n,i=o(this.stringFields.values());!(n=i()).done;)for(var r=n.value,s=0;s<r.length;s++)r[s]=void 0;for(var a,c=o(this.serializedFields.values());!(a=c()).done;)for(var u=a.value,h=0;h<u.length;h++)u[h]=void 0},t.compact=function(){if(0!==this.freeIndices.length){for(var e=Array.from(this.entityToIndex.entries()).sort((function(e,t){return e[1]-t[1]})),t=new Map,n=[],i=0;i<e.length;i++){var r=e[i],s=r[0],a=r[1];if(t.set(s,i),n[i]=s,i!==a){for(var c,u=o(this.fields.entries());!(c=u()).done;){var h=c.value[1];h[i]=h[a]}for(var l,f=o(this.stringFields.entries());!(l=f()).done;){var d=l.value[1];d[i]=d[a]}for(var p,y=o(this.serializedFields.entries());!(p=y()).done;){var m=p.value[1];m[i]=m[a]}}}this.entityToIndex=t,this.indexToEntity=n,this.freeIndices=[],this._size=e.length}},t.getStats=function(){for(var e,t=0,n=new Map,i=o(this.fields.entries());!(e=i()).done;){var r=e.value,s=r[0],a=r[1],c=void 0,u=void 0;a instanceof Float32Array?(c=4,u="float32"):a instanceof Float64Array?(c=8,u="float64"):a instanceof Int32Array?(c=4,u="int32"):a instanceof Uint32Array?(c=4,u="uint32"):a instanceof Int16Array?(c=2,u="int16"):a instanceof Uint16Array?(c=2,u="uint16"):a instanceof Int8Array?(c=1,u="int8"):a instanceof Uint8Array?(c=1,u="uint8"):a instanceof Uint8ClampedArray?(c=1,u="uint8clamped"):(c=4,u="unknown");var h=a.length*c;t+=h,n.set(s,{size:this._size,capacity:a.length,type:u,memory:h})}return{size:this._size,capacity:this._capacity,usedSlots:this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:t,fieldStats:n}},t.performVectorizedOperation=function(e){var t=this.getActiveIndices();e(this.fields,t)},e}();me._logger=Y("SoAStorage");var ge=function(){function e(){}return e.register=function(e){var t=U(e);if(this.componentTypes.has(e))return this.componentTypes.get(e);var n=this.nextBitIndex++;return this.componentTypes.set(e,n),this.bitIndexToType.set(n,e),this.componentNameToType.set(t,e),this.componentNameToId.set(t,n),n},e.getBitMask=function(e){var t=this.componentTypes.get(e);if(void 0===t){var n=U(e);throw new Error("Component type "+n+" is not registered")}return pe.create(t)},e.getBitIndex=function(e){var t=this.componentTypes.get(e);if(void 0===t){var n=U(e);throw new Error("Component type "+n+" is not registered")}return t},e.isRegistered=function(e){return this.componentTypes.has(e)},e.getTypeByBitIndex=function(e){return this.bitIndexToType.get(e)||null},e.getRegisteredCount=function(){return this.nextBitIndex},e.getComponentType=function(e){return this.componentNameToType.get(e)||null},e.getAllRegisteredTypes=function(){return new Map(this.componentTypes)},e.getAllComponentNames=function(){return new Map(this.componentNameToType)},e.getComponentId=function(e){return this.componentNameToId.get(e)},e.registerComponentByName=function(e){if(this.componentNameToId.has(e))return this.componentNameToId.get(e);var t=this.nextBitIndex++;return this.componentNameToId.set(e,t),t},e.createSingleComponentMask=function(e){var t="single:"+e;if(this.maskCache.has(t))return this.maskCache.get(t);var n=this.getComponentId(e);if(void 0===n)throw new Error("Component type "+e+" is not registered");var i=pe.create(n);return this.maskCache.set(t,i),i},e.createComponentMask=function(e){var t="multi:"+[].concat(e).sort().join(",");if(this.maskCache.has(t))return this.maskCache.get(t);for(var n,i=pe.clone(pe.ZERO),r=o(e);!(n=r()).done;){var s=n.value,a=this.getComponentId(s);if(void 0!==a){var c=pe.create(a);pe.orInPlace(i,c)}}return this.maskCache.set(t,i),i},e.clearMaskCache=function(){this.maskCache.clear()},e.reset=function(){this.componentTypes.clear(),this.bitIndexToType.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0},e}();ge._logger=Y("ComponentStorage"),ge.componentTypes=new Map,ge.bitIndexToType=new Map,ge.componentNameToType=new Map,ge.componentNameToId=new Map,ge.maskCache=new Map,ge.nextBitIndex=0;var ve=function(){function e(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e,ge.isRegistered(e)||ge.register(e)}var t=e.prototype;return t.addComponent=function(e,t){if(this.entityToIndex.has(e))throw new Error("Entity "+e+" already has component "+U(this.componentType));var n=this.dense.length;this.dense.push(t),this.entityIds.push(e),this.entityToIndex.set(e,n)},t.getComponent=function(e){var t=this.entityToIndex.get(e);return void 0!==t?this.dense[t]:null},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.dense[t],i=this.dense.length-1;if(t!==i){var r=this.dense[i],s=this.entityIds[i];this.dense[t]=r,this.entityIds[t]=s,this.entityToIndex.set(s,t)}return this.dense.pop(),this.entityIds.pop(),this.entityToIndex.delete(e),n},t.forEach=function(e){for(var t=0;t<this.dense.length;t++)e(this.dense[t],this.entityIds[t],t)},t.getDenseArray=function(){return{components:[].concat(this.dense),entityIds:[].concat(this.entityIds)}},t.clear=function(){this.dense.length=0,this.entityIds.length=0,this.entityToIndex.clear()},t.getStats=function(){return{totalSlots:this.dense.length,usedSlots:this.dense.length,freeSlots:0,fragmentation:0}},s(e,[{key:"size",get:function(){return this.dense.length}},{key:"type",get:function(){return this.componentType}}])}(),_e=function(){function e(){this.storages=new Map}var t=e.prototype;return t.isSoAStorage=function(e){return this.storages.get(e)instanceof me},t.getSoAStorage=function(e){var t=this.getStorage(e);return t instanceof me?t:null},t.getFieldArray=function(e,t){var n=this.getSoAStorage(e);return n?n.getFieldArray(t):null},t.getTypedFieldArray=function(e,t){var n=this.getSoAStorage(e);return n?n.getTypedFieldArray(t):null},t.getActiveIndices=function(e){var t=this.getSoAStorage(e);return t?t.getActiveIndices():[]},t.getEntityIndex=function(e,t){var n=this.getSoAStorage(e);return n?n.getEntityIndex(t):void 0},t.getEntityIdByIndex=function(e,t){var n=this.getSoAStorage(e);return n?n.getEntityIdByIndex(t):void 0},t.getStorage=function(t){var n=this.storages.get(t);n||(t.__enableSoA?(n=new me(t),e._logger.info("为 "+U(t)+" 启用SoA优化(适用于大规模批量操作)")):n=new ve(t),this.storages.set(t,n));return n},t.addComponent=function(e,t){var n=t.constructor;this.getStorage(n).addComponent(e,t)},t.getComponent=function(e,t){var n=this.storages.get(t);return n?n.getComponent(e):null},t.hasComponent=function(e,t){var n=this.storages.get(t);return!!n&&n.hasComponent(e)},t.removeComponent=function(e,t){var n=this.storages.get(t);return n?n.removeComponent(e):null},t.removeAllComponents=function(e){for(var t,n=o(this.storages.values());!(t=n()).done;){t.value.removeComponent(e)}},t.getComponentMask=function(e){for(var t,n=pe.clone(pe.ZERO),i=o(this.storages.entries());!(t=i()).done;){var r=t.value,s=r[0];if(r[1].hasComponent(e)){var a=ge.getBitMask(s);pe.orInPlace(n,a)}}return n},t.getAllStats=function(){for(var e,t=new Map,n=o(this.storages.entries());!(e=n()).done;){var i=e.value,r=i[0],s=i[1],a=U(r);t.set(a,s.getStats())}return t},t.clear=function(){for(var e,t=o(this.storages.values());!(e=t()).done;){e.value.clear()}this.storages.clear()},e}();_e._logger=Y("ComponentStorage");var Se=function(){function e(){}return e.prototype.compare=function(e,t){var n=e.updateOrder-t.updateOrder;return 0==n&&(n=e.id-t.id),n},e}(),Ce=function(){function e(e,t){this.scene=null,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=pe.clone(pe.ZERO),this._componentCache=null,this.name=e,this.id=t}e.notifyQuerySystems=function(e){e.scene&&e.scene.querySystem&&(e.scene.querySystem.updateEntity(e),e.scene.clearSystemEntityCaches())};var t=e.prototype;return t._rebuildComponentCache=function(){var e,t=[];if(null!==(e=this.scene)&&void 0!==e&&e.componentStorageManager){for(var n=this._componentMask,i=ge.getRegisteredCount(),r=0;r<i;r++)if(pe.getBit(n,r)){var s=ge.getTypeByBitIndex(r);if(s){var o=this.scene.componentStorageManager.getComponent(this.id,s);o&&t.push(o)}}this._componentCache=t}else this._componentCache=t},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var s=i(e,n);return this.addComponent(s)},t.addComponentInternal=function(e){var t=e.constructor;ge.isRegistered(t)||ge.register(t);var n=ge.getBitMask(t);return pe.orInPlace(this._componentMask,n),this._componentCache=null,e},t.addComponent=function(t){var n,i=t.constructor;if(!this.scene)throw new Error("Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()");if(!this.scene.componentStorageManager)throw new Error("Scene does not have componentStorageManager");if(this.hasComponent(i))throw new Error("Entity "+this.name+" already has component "+U(i));(this.addComponentInternal(t),this.scene.componentStorageManager.addComponent(this.id,t),t.entityId=this.id,this.scene.referenceTracker&&this.scene.referenceTracker.registerEntityScene(this.id,this.scene),t.onAddedToEntity(),e.eventBus)&&e.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(n=this.tag)||void 0===n?void 0:n.toString(),componentType:U(i),component:t});return e.notifyQuerySystems(this),t},t.getComponent=function(e){var t;return this.hasComponent(e)&&null!==(t=this.scene)&&void 0!==t&&t.componentStorageManager?this.scene.componentStorageManager.getComponent(this.id,e):null},t.hasComponent=function(e){if(!ge.isRegistered(e))return!1;var t=ge.getBitMask(e);return pe.hasAny(this._componentMask,t)},t.getOrCreateComponent=function(e){var t=this.getComponent(e);if(!t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];t=this.createComponent.apply(this,[e].concat(i))}return t},t.removeComponent=function(t){var n,i,r=t.constructor;if(ge.isRegistered(r)){var s,o=ge.getBitIndex(r);if(pe.clearBit(this._componentMask,o),this._componentCache=null,null!==(n=this.scene)&&void 0!==n&&n.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,r),null!==(i=this.scene)&&void 0!==i&&i.referenceTracker&&this.scene.referenceTracker.clearComponentReferences(t),t.onRemovedFromEntity&&t.onRemovedFromEntity(),t.entityId=null,e.eventBus)e.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(s=this.tag)||void 0===s?void 0:s.toString(),componentType:U(r),component:t});e.notifyQuerySystems(this)}},t.removeComponentByType=function(e){var t=this.getComponent(e);return t?(this.removeComponent(t),t):null},t.removeAllComponents=function(){var t=[].concat(this.components);pe.clear(this._componentMask),this._componentCache=null;for(var n,i=o(t);!(n=i()).done;){var r,s=n.value,a=s.constructor;null!==(r=this.scene)&&void 0!==r&&r.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,a),s.onRemovedFromEntity()}e.notifyQuerySystems(this)},t.addComponents=function(t){for(var n,i=[],r=o(t);!(n=r()).done;){var s=n.value;try{i.push(this.addComponent(s))}catch(t){e._logger.warn("添加组件失败 "+H(s)+":",t)}}return i},t.removeComponentsByTypes=function(e){for(var t,n=[],i=o(e);!(t=i()).done;){var r=t.value;n.push(this.removeComponentByType(r))}return n},t.getComponents=function(e){for(var t,n=[],i=o(this.components);!(t=i()).done;){var r=t.value;r instanceof e&&n.push(r)}return n},t.addChild=function(e){if(e===this)throw new Error("Entity cannot be its own child");return e._parent===this||(e._parent&&e._parent.removeChild(e),e._parent=this,this._children.push(e),!e.scene&&this.scene&&(e.scene=this.scene,this.scene.addEntity(e))),e},t.removeChild=function(e){var t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e._parent=null,!0)},t.removeAllChildren=function(){for(var e,t=o([].concat(this._children));!(e=t()).done;){var n=e.value;this.removeChild(n)}},t.findChild=function(e,t){void 0===t&&(t=!1);for(var n,i=o(this._children);!(n=i()).done;){var r=n.value;if(r.name===e)return r}if(t)for(var s,a=o(this._children);!(s=a()).done;){var c=s.value.findChild(e,!0);if(c)return c}return null},t.findChildrenByTag=function(e,t){void 0===t&&(t=!1);for(var n,i=[],r=o(this._children);!(n=r()).done;){var s=n.value;s.tag===e&&i.push(s)}if(t)for(var a,c=o(this._children);!(a=c()).done;){var u=a.value;i.push.apply(i,u.findChildrenByTag(e,!0))}return i},t.getRoot=function(){for(var e=this;e._parent;)e=e._parent;return e},t.isAncestorOf=function(e){for(var t=e._parent;t;){if(t===this)return!0;t=t._parent}return!1},t.isDescendantOf=function(e){return e.isAncestorOf(this)},t.getDepth=function(){for(var e=0,t=this._parent;t;)e++,t=t._parent;return e},t.forEachChild=function(e,t){void 0===t&&(t=!1),this._children.forEach((function(n,i){e(n,i),t&&n.forEachChild(e,!0)}))},t.onActiveChanged=function(){for(var e,t=o(this.components);!(e=t()).done;){var n=e.value;"onActiveChanged"in n&&"function"==typeof n.onActiveChanged&&n.onActiveChanged()}this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})},t.destroy=function(){if(!this._isDestroyed){this._isDestroyed=!0,this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id));for(var e,t=o([].concat(this._children));!(e=t()).done;){e.value.destroy()}this._parent&&this._parent.removeChild(this),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this))}},t.destroyAllChildren=function(){if(0!==this._children.length){var e=this.scene,t=[],n=function(e){for(var i,r=o(e._children);!(i=r()).done;){var s=i.value;t.push(s),n(s)}};n(this);for(var i=0,r=t;i<r.length;i++){r[i]._isDestroyed=!0}for(var s=0,a=t;s<a.length;s++){a[s].removeAllComponents()}if(e){for(var c,u=o(t);!(c=u()).done;){var h=c.value;e.entities.remove(h),e.querySystem.removeEntity(h)}e.clearSystemEntityCaches()}this._children.length=0}},t.compareTo=function(e){return Se.prototype.compare(this,e)},t.toString=function(){return"Entity["+this.name+":"+this.id+"]"},t.getDebugInfo=function(){var e;return{name:this.name,id:this.id,enabled:this._enabled,active:this._active,activeInHierarchy:this.activeInHierarchy,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map((function(e){return H(e)})),componentMask:pe.toString(this._componentMask,2),parentId:(null===(e=this._parent)||void 0===e?void 0:e.id)||null,childCount:this._children.length,childIds:this._children.map((function(e){return e.id})),depth:this.getDepth(),cacheBuilt:null!==this._componentCache}},s(e,[{key:"isDestroyed",get:function(){return this._isDestroyed}},{key:"components",get:function(){return null===this._componentCache&&this._rebuildComponentCache(),this._componentCache}},{key:"parent",get:function(){return this._parent}},{key:"children",get:function(){return[].concat(this._children)}},{key:"childCount",get:function(){return this._children.length}},{key:"active",get:function(){return this._active},set:function(e){this._active!==e&&(this._active=e,this.onActiveChanged())}},{key:"activeInHierarchy",get:function(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}},{key:"tag",get:function(){return this._tag},set:function(e){this._tag=e}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this._updateOrder=e}},{key:"componentMask",get:function(){return this._componentMask}}])}();Ce._logger=Y("Entity"),Ce.entityComparer=new Se,Ce.eventBus=null;var we=function(){function e(e,t){this.scene=e,this.storageManager=t;var n=e.identifierPool.checkOut();this.entity=new Ce("",n),this.entity.scene=this.scene}var t=e.prototype;return t.named=function(e){return this.entity.name=e,this},t.tagged=function(e){return this.entity.tag=e,this},t.with=function(e){return this.entity.addComponent(e),this},t.withComponents=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i];this.entity.addComponent(s)}return this},t.withIf=function(e,t){return e&&this.entity.addComponent(t),this},t.withFactory=function(e){var t=e();return this.entity.addComponent(t),this},t.configure=function(e,t){var n=this.entity.getComponent(e);return n&&t(n),this},t.enabled=function(e){return void 0===e&&(e=!0),this.entity.enabled=e,this},t.active=function(e){return void 0===e&&(e=!0),this.entity.active=e,this},t.withChild=function(e){var t=e.build();return this.entity.addChild(t),this},t.withChildren=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i].build();this.entity.addChild(s)}return this},t.withChildFactory=function(e){var t=e(this.entity).build();return this.entity.addChild(t),this},t.withChildIf=function(e,t){if(e){var n=t.build();this.entity.addChild(n)}return this},t.build=function(){return this.entity},t.spawn=function(){return this.scene.addEntity(this.entity),this.entity},t.clone=function(){var t=new e(this.scene,this.storageManager);return t.entity=this.entity,t},e}(),Ee=function(){function e(e){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._scene=e}var t=e.prototype;return t.add=function(e){this.addImmediate(e)},t.addImmediate=function(e){this._idToEntity.has(e.id)||(this.buffer.push(e),this._idToEntity.set(e.id,e),this.updateNameIndex(e,!0))},t.remove=function(e){this.removeImmediate(e)},t.removeImmediate=function(e){var t=this.buffer.indexOf(e);-1!==t&&(this.buffer.splice(t,1),this._idToEntity.delete(e.id),this.updateNameIndex(e,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(e.id))},t.removeAllEntities=function(){for(var e=[],t=this.buffer.length-1;t>=0;t--)e.push(this.buffer[t].id),this.buffer[t].destroy();if(this._scene&&this._scene.identifierPool)for(var n,i=o(e);!(n=i()).done;){var r=n.value;this._scene.identifierPool.checkIn(r)}this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0},t.updateLists=function(){if(this._entitiesToAdd.length>0){for(var e,t=o(this._entitiesToAdd);!(e=t()).done;){var n=e.value;this.addImmediate(n)}this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(var i,r=o(this._entitiesToRemove);!(i=r()).done;){var s=i.value;this.removeImmediate(s)}this._entitiesToRemove.length=0}},t.update=function(){this.updateLists()},t.findEntity=function(e){var t=this._nameToEntities.get(e);return t&&t.length>0?t[0]:null},t.findEntitiesByName=function(e){return this._nameToEntities.get(e)||[]},t.findEntityById=function(e){return this._idToEntity.get(e)||null},t.findEntitiesByTag=function(e){for(var t,n=[],i=o(this.buffer);!(t=i()).done;){var r=t.value;r.tag===e&&n.push(r)}return n},t.findEntitiesWithComponent=function(e){for(var t,n=[],i=o(this.buffer);!(t=i()).done;){var r=t.value;r.hasComponent(e)&&n.push(r)}return n},t.forEach=function(e){for(var t,n=o(this.buffer);!(t=n()).done;){e(t.value)}},t.forEachWhere=function(e,t){for(var n,i=o(this.buffer);!(n=i()).done;){var r=n.value;e(r)&&t(r)}},t.updateNameIndex=function(e,t){if(e.name)if(t){var n=this._nameToEntities.get(e.name);n||(n=[],this._nameToEntities.set(e.name,n)),n.push(e)}else{var i=this._nameToEntities.get(e.name);if(i){var r=i.indexOf(e);-1!==r&&(i.splice(r,1),0===i.length&&this._nameToEntities.delete(e.name))}}},t.getStats=function(){for(var e,t=0,n=o(this.buffer);!(e=n()).done;){var i=e.value;i.enabled&&!i.isDestroyed&&t++}return{totalEntities:this.buffer.length,activeEntities:t,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}},s(e,[{key:"count",get:function(){return this.buffer.length}}])}(),be=function(){function e(e,t){void 0===e&&(e=100),void 0===t&&(t=1024),this._nextAvailableIndex=0,this._freeIndices=[],this._generations=new Map,this._pendingRecycle=[],this._recycleDelay=100,this._stats={totalAllocated:0,totalRecycled:0,currentActive:0,memoryExpansions:0},this._recycleDelay=e,this._expansionBlockSize=t,this._preAllocateGenerations(0,this._expansionBlockSize)}var t=e.prototype;return t.checkOut=function(){var t;if(this._processDelayedRecycle(),this._freeIndices.length>0)t=this._freeIndices.pop();else{if(this._nextAvailableIndex>e.MAX_INDEX)throw new Error("实体索引已达到框架设计限制 ("+e.MAX_INDEX+")。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。");t=this._nextAvailableIndex++,this._ensureGenerationCapacity(t)}var n=this._generations.get(t)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(t,n)},t.checkIn=function(e){var t=this._unpackIndex(e),n=this._unpackGeneration(e);return!!this._isValidId(t,n)&&(!this._pendingRecycle.some((function(e){return e.index===t&&e.generation===n}))&&(this._pendingRecycle.push({index:t,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0))},t.isValid=function(e){var t=this._unpackIndex(e),n=this._unpackGeneration(e);return this._isValidId(t,n)},t.getStats=function(){for(var t,n=0,i=0,r=o(this._generations);!(t=r()).done;){var s=t.value,a=s[0],c=s[1];a<this._nextAvailableIndex&&(n+=c,i++)}var u=i>0?n/i:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:e.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*u)/100,generationStorageSize:this._generations.size}},t.forceProcessDelayedRecycle=function(){this._processDelayedRecycle(!0)},t._processDelayedRecycle=function(t){if(void 0===t&&(t=!1),0!==this._pendingRecycle.length){for(var n,i=Date.now(),r=[],s=[],a=o(this._pendingRecycle);!(n=a()).done;){var c=n.value;t||i-c.timestamp>=this._recycleDelay?r.push(c):s.push(c)}for(var u=0,h=r;u<h.length;u++){var l=h[u];if(this._isValidId(l.index,l.generation)){var f=l.generation+1;f>e.MAX_GENERATION&&(f=1),this._generations.set(l.index,f),this._freeIndices.push(l.index)}}this._pendingRecycle=s}},t._preAllocateGenerations=function(t,n){for(var i=0;i<n;i++){var r=t+i;r<=e.MAX_INDEX&&this._generations.set(r,1)}this._stats.memoryExpansions++},t._ensureGenerationCapacity=function(e){if(!this._generations.has(e)){var t=Math.floor(e/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(t,this._expansionBlockSize)}},t._calculateMemoryUsage=function(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length},t._packId=function(e,t){return t<<16|e},t._unpackIndex=function(e){return 65535&e},t._unpackGeneration=function(e){return e>>>16&65535},t._isValidId=function(e,t){if(e<0||e>=this._nextAvailableIndex)return!1;var n=this._generations.get(e);return void 0!==n&&n===t},e}();be.MAX_INDEX=65535,be.MAX_GENERATION=65535;var Ae=function(){function e(){this.condition={all:[],any:[],none:[]}}e.all=function(){var t=new e;return t.all.apply(t,arguments)},e.any=function(){var t=new e;return t.any.apply(t,arguments)},e.none=function(){var t=new e;return t.none.apply(t,arguments)},e.byTag=function(t){return(new e).withTag(t)},e.byName=function(t){return(new e).withName(t)},e.byComponent=function(t){return(new e).withComponent(t)},e.complex=function(){return new e},e.empty=function(){return new e};var t=e.prototype;return t.all=function(){var e;return(e=this.condition.all).push.apply(e,arguments),this},t.any=function(){var e;return(e=this.condition.any).push.apply(e,arguments),this},t.none=function(){var e;return(e=this.condition.none).push.apply(e,arguments),this},t.exclude=function(){return this.none.apply(this,arguments)},t.one=function(){return this.any.apply(this,arguments)},t.withTag=function(e){return this.condition.tag=e,this},t.withName=function(e){return this.condition.name=e,this},t.withComponent=function(e){return this.condition.component=e,this},t.withoutTag=function(){return delete this.condition.tag,this},t.withoutName=function(){return delete this.condition.name,this},t.withoutComponent=function(){return delete this.condition.component,this},t.getCondition=function(){return{all:[].concat(this.condition.all),any:[].concat(this.condition.any),none:[].concat(this.condition.none),tag:this.condition.tag,name:this.condition.name,component:this.condition.component}},t.isEmpty=function(){return 0===this.condition.all.length&&0===this.condition.any.length&&0===this.condition.none.length&&void 0===this.condition.tag&&void 0===this.condition.name&&void 0===this.condition.component},t.reset=function(){return this.condition.all.length=0,this.condition.any.length=0,this.condition.none.length=0,delete this.condition.tag,delete this.condition.name,delete this.condition.component,this},t.clone=function(){var t,n,i,r=new e;return(t=r.condition.all).push.apply(t,this.condition.all),(n=r.condition.any).push.apply(n,this.condition.any),(i=r.condition.none).push.apply(i,this.condition.none),void 0!==this.condition.tag&&(r.condition.tag=this.condition.tag),void 0!==this.condition.name&&(r.condition.name=this.condition.name),void 0!==this.condition.component&&(r.condition.component=this.condition.component),r},t.toString=function(){var e=[];return this.condition.all.length>0&&e.push("all("+this.condition.all.map((function(e){return U(e)})).join(", ")+")"),this.condition.any.length>0&&e.push("any("+this.condition.any.map((function(e){return U(e)})).join(", ")+")"),this.condition.none.length>0&&e.push("none("+this.condition.none.map((function(e){return U(e)})).join(", ")+")"),void 0!==this.condition.tag&&e.push("tag("+this.condition.tag+")"),void 0!==this.condition.name&&e.push("name("+this.condition.name+")"),void 0!==this.condition.component&&e.push("component("+U(this.condition.component)+")"),"Matcher["+e.join(" & ")+"]"},e}(),Te=function(){function e(e){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=j(this),this._initialized=!1,this._matcher=e||Ae.empty(),this._eventListeners=[],this._scene=null,this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.logger=Y(this.getLoggerName()),this._entityCache={frame:null,persistent:null,tracked:new Set,invalidate:function(){this.persistent=null},clearFrame:function(){this.frame=null},clearAll:function(){this.frame=null,this.persistent=null,this.tracked.clear()}}}var t=e.prototype;return t.setPerformanceMonitor=function(e){this._performanceMonitor=e},t.getPerformanceMonitor=function(){if(!this._performanceMonitor)throw new Error(this._systemName+": PerformanceMonitor未注入,请确保在Core.create()之后再添加System到Scene");return this._performanceMonitor},t.setUpdateOrder=function(e){this._updateOrder=e},t.initialize=function(){this._initialized||(this._initialized=!0,this.scene&&(this._entityCache.invalidate(),this.queryEntities()),this.onInitialize())},t.onInitialize=function(){},t.clearEntityCache=function(){this._entityCache.invalidate()},t.reset=function(){this.scene=null,this._initialized=!1,this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.destroy()},t.queryEntities=function(){var e;if(null===(e=this.scene)||void 0===e||!e.querySystem||!this._matcher)return[];var t=this._matcher.getCondition(),n=this.scene.querySystem,i=[];return i=this._matcher.isEmpty()?n.getAllEntities():this.isSingleCondition(t)?this.executeSingleConditionQuery(t,n):this.executeComplexQuery(t,n),this.updateEntityTracking(i),i},t.isSingleCondition=function(e){var t=(e.all.length>0?1:0)|(e.any.length>0?2:0)|(e.none.length>0?4:0)|(void 0!==e.tag?8:0)|(void 0!==e.name?16:0)|(void 0!==e.component?32:0);return 0!==t&&!(t&t-1)},t.executeSingleConditionQuery=function(e,t){return void 0!==e.tag?t.queryByTag(e.tag).entities:void 0!==e.name?t.queryByName(e.name).entities:void 0!==e.component?t.queryByComponent(e.component).entities:e.all.length>0&&0===e.any.length&&0===e.none.length?t.queryAll.apply(t,e.all).entities:0===e.all.length&&e.any.length>0&&0===e.none.length?t.queryAny.apply(t,e.any).entities:0===e.all.length&&0===e.any.length&&e.none.length>0?t.queryNone.apply(t,e.none).entities:[]},t.executeComplexQueryWithIdSets=function(e,t){var n=null;if(void 0!==e.tag){var i=t.queryByTag(e.tag);n=this.extractEntityIds(i.entities)}if(void 0!==e.name){var r=this.extractEntityIds(t.queryByName(e.name).entities);n=n?this.intersectIdSets(n,r):r}if(void 0!==e.component){var s=this.extractEntityIds(t.queryByComponent(e.component).entities);n=n?this.intersectIdSets(n,s):s}if(e.all.length>0){var o=this.extractEntityIds(t.queryAll.apply(t,e.all).entities);n=n?this.intersectIdSets(n,o):o}if(e.any.length>0){var a=this.extractEntityIds(t.queryAny.apply(t,e.any).entities);n=n?this.intersectIdSets(n,a):a}if(e.none.length>0){n||(n=this.extractEntityIds(t.getAllEntities()));var c=t.queryAny.apply(t,e.none),u=this.extractEntityIds(c.entities);n=this.differenceIdSets(n,u)}return n?this.idSetToEntityArray(n,t.getAllEntities()):[]},t.extractEntityIds=function(e){for(var t=e.length,n=new Set,i=0;i<t;i=i+1|0)n.add(0|e[i].id);return n},t.intersectIdSets=function(e,t){var n,i;e.size<=t.size?(n=e,i=t):(n=t,i=e);for(var r,s=new Set,a=o(n);!(r=a()).done;){var c=r.value;i.has(c)&&s.add(c)}return s},t.differenceIdSets=function(e,t){for(var n,i=new Set,r=o(e);!(n=r()).done;){var s=n.value;t.has(s)||i.add(s)}return i},t.getEntityIdMap=function(e){var t,n,i=null!==(t=null===(n=this.scene)||void 0===n||null===(n=n.querySystem)||void 0===n?void 0:n.version)&&void 0!==t?t:0;return null!==this._entityIdMap&&this._entityIdMapVersion===i?this._entityIdMap:this.rebuildEntityIdMap(e,i)},t.rebuildEntityIdMap=function(e,t){var n=this._entityIdMap;n?n.clear():n=new Map;for(var i=e.length,r=0;r<i;r=r+1|0){var s=e[r];n.set(0|s.id,s)}return this._entityIdMap=n,this._entityIdMapVersion=t,this._entityIdMapSize=i,n},t.idSetToEntityArray=function(e,t){for(var n,i=this.getEntityIdMap(t),r=e.size,s=new Array(r),a=0,c=o(e);!(n=c()).done;){var u=n.value,h=i.get(u);void 0!==h&&(s[a]=h,a=a+1|0)}return a<r&&(s.length=a),s},t.executeComplexQuery=function(e,t){return this.executeComplexQueryWithIdSets(e,t)},t.update=function(){if(this._enabled&&this.onCheckProcessing()){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName),n=0;try{this.onBegin(),this._entityCache.frame=this.queryEntities(),n=this._entityCache.frame.length,this.process(this._entityCache.frame)}finally{e.endMonitoring(this._systemName,t,n)}}},t.lateUpdate=function(){if(this._enabled&&this.onCheckProcessing()){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName+"_Late"),n=0;try{var i=this._entityCache.frame||[];n=i.length,this.lateProcess(i),this.onEnd()}finally{e.endMonitoring(this._systemName+"_Late",t,n),this._entityCache.clearFrame()}}},t.onBegin=function(){},t.process=function(e){},t.lateProcess=function(e){},t.onEnd=function(){},t.onCheckProcessing=function(){return!0},t.getPerformanceData=function(){return this.getPerformanceMonitor().getSystemData(this._systemName)},t.getPerformanceStats=function(){return this.getPerformanceMonitor().getSystemStats(this._systemName)},t.resetPerformanceData=function(){this.getPerformanceMonitor().resetSystem(this._systemName)},t.toString=function(){var e=this.entities.length,t=this.getPerformanceData(),n=t?" ("+t.executionTime.toFixed(2)+"ms)":"";return this._systemName+"["+e+" entities]"+n},t.updateEntityTracking=function(e){for(var t,n=new Set(e),i=!1,r=o(e);!(t=r()).done;){var s=t.value;this._entityCache.tracked.has(s)||(this._entityCache.tracked.add(s),this.onAdded(s),i=!0)}for(var a,c=o(this._entityCache.tracked);!(a=c()).done;){var u=a.value;n.has(u)||(this._entityCache.tracked.delete(u),this.onRemoved(u),i=!0)}i&&this._entityCache.invalidate()},t.onAdded=function(e){},t.onRemoved=function(e){},t.dispose=function(){this.cleanupManualEventListeners(),this._entityCache.clearAll(),this._entityIdMap=null,this._initialized=!1,this._scene=null,this.logger.debug("System "+this._systemName+" disposed")},t.addEventListener=function(e,t,n){var i;if(null!==(i=this.scene)&&void 0!==i&&i.eventSystem){var r=this.scene.eventSystem.on(e,t,n);r&&this._eventListeners.push({eventSystem:this.scene.eventSystem,eventType:e,handler:t,listenerRef:r})}else this.logger.warn(this.systemName+": 无法添加事件监听器,scene.eventSystem 不可用")},t.removeEventListener=function(e,t){var n=this._eventListeners.findIndex((function(n){return n.eventType===e&&n.handler===t}));if(n>=0){var i=this._eventListeners[n];i.eventSystem.off(e,i.listenerRef),this._eventListeners.splice(n,1)}},t.cleanupManualEventListeners=function(){for(var e,t=o(this._eventListeners);!(e=t()).done;){var n=e.value;try{n.eventSystem.off(n.eventType,n.listenerRef)}catch(e){this.logger.warn(this.systemName+': 移除事件监听器失败 "'+n.eventType+'"',e)}}this._eventListeners.length=0},t.destroy=function(){this.cleanupManualEventListeners(),this.onDestroy()},t.getLoggerName=function(){return"EntitySystem"},t.onDestroy=function(){},t.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" in "+this.systemName);return n},t.getComponents=function(e){for(var t=this,n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i.map((function(n){return t.requireComponent(e,n)}))},t.forEach=function(e,t){for(var n=0;n<e.length;n++)t(e[n],n)},t.filterEntities=function(e,t){return Array.from(e).filter(t)},t.mapEntities=function(e,t){return Array.from(e).map(t)},t.findEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return e[n]},t.someEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1},t.everyEntity=function(e,t){for(var n=0;n<e.length;n++)if(!t(e[n],n))return!1;return!0},s(e,[{key:"entities",get:function(){return null!==this._entityCache.frame?this._entityCache.frame:(null===this._entityCache.persistent&&(this._entityCache.persistent=this.queryEntities()),this._entityCache.persistent)}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this.setUpdateOrder(e)}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"systemName",get:function(){return this._systemName}},{key:"scene",get:function(){return this._scene},set:function(e){this._scene=e}},{key:"matcher",get:function(){return this._matcher}}])}(),Me=function(){function e(){this._processors=[],this._isDirty=!1}var t=e.prototype;return t.setDirty=function(){this._isDirty=!0},t.add=function(e){this._processors.push(e),this.setDirty()},t.remove=function(e){var t=this._processors.indexOf(e);-1!==t&&this._processors.splice(t,1)},t.getProcessor=function(e){for(var t,n=o(this._processors);!(t=n()).done;){var i=t.value;if(i instanceof e)return i}return null},t.begin=function(){this.sortProcessors()},t.end=function(){for(var t,n=o(this._processors);!(t=n()).done;){var i=t.value;try{i.reset()}catch(t){e._logger.error("Error in processor "+j(i)+":",t)}}this._isDirty=!1,this._processors.length=0},t.update=function(){this.sortProcessors();for(var t,n=o(this._processors);!(t=n()).done;){var i=t.value;try{i.update()}catch(t){e._logger.error("Error in processor "+j(i)+":",t)}}},t.lateUpdate=function(){for(var e,t=o(this._processors);!(e=t()).done;){e.value.lateUpdate()}},t.sortProcessors=function(){this._isDirty&&(this._processors.sort((function(e,t){return e.updateOrder-t.updateOrder})),this._isDirty=!1)},s(e,[{key:"processors",get:function(){return this._processors}},{key:"count",get:function(){return this._processors.length}}])}();Me._logger=Y("EntityProcessorList");var xe=function(){function e(e){if(e&&"object"==typeof e)this._value=pe.clone(e);else if("number"==typeof e)this._value=pe.fromNumber(e);else if("string"==typeof e){var t=parseInt(e,10);this._value=pe.fromNumber(t)}else this._value=pe.clone(pe.ZERO)}var t=e.prototype;return t.set=function(e){if(e<0)throw new Error("Bit index cannot be negative");pe.setBit(this._value,e)},t.clear=function(e){if(e<0)throw new Error("Bit index cannot be negative");pe.clearBit(this._value,e)},t.get=function(e){return pe.getBit(this._value,e)},t.containsAll=function(e){return pe.hasAll(this._value,e._value)},t.intersects=function(e){return pe.hasAny(this._value,e._value)},t.excludes=function(e){return pe.hasNone(this._value,e._value)},t.clearAll=function(){pe.clear(this._value)},t.isEmpty=function(){return pe.isZero(this._value)},t.cardinality=function(){return pe.popCount(this._value)},t.and=function(t){var n=new e;return pe.copy(this._value,n._value),pe.andInPlace(n._value,t._value),n},t.or=function(t){var n=new e;return pe.copy(this._value,n._value),pe.orInPlace(n._value,t._value),n},t.xor=function(t){var n=new e;return pe.copy(this._value,n._value),pe.xorInPlace(n._value,t._value),n},t.not=function(t){void 0===t&&(t=64),t>64&&(t=64);var n=new e;if(pe.copy(this._value,n._value),t<=32){var i=(1<<t)-1;n._value.base[le.LOW]=~n._value.base[le.LOW]&i,n._value.base[le.HIGH]=0}else if(n._value.base[le.LOW]=~n._value.base[le.LOW],t<64){var r=(1<<t-32)-1;n._value.base[le.HIGH]=~n._value.base[le.HIGH]&r}else n._value.base[le.HIGH]=~n._value.base[le.HIGH];return n},t.copyFrom=function(e){pe.copy(e._value,this._value)},t.clone=function(){return new e(this._value)},t.getValue=function(){return this._value},t.setValue=function(e){if("object"==typeof e)pe.copy(e,this._value);else if("number"==typeof e)this._value=pe.fromNumber(e);else{var t=parseInt(e,10);this._value=pe.fromNumber(t)}},t.toString=function(){for(var e=[],t=0;t<64;t++)this.get(t)&&e.push(t.toString());return"Bits["+e.join(", ")+"]"},t.toBinaryString=function(e){void 0===e&&(e=0),0==e&&(e=64+(this._value.segments?64*this._value.segments.length:0));for(var t="",n=e-1;n>=0;n--)t+=this.get(n)?"1":"0",n%8==0&&n>0&&(t+=" ");return t},t.toHexString=function(){return pe.toString(this._value,16)},e.fromBinaryString=function(t){var n=t.replace(/\s/g,""),i={base:void 0,segments:void 0};if(n.length<=32){var r=parseInt(n,2);i.base=[r>>>0,0]}else{var s=n.substring(n.length-32),o=n.substring(0,n.length-32),a=parseInt(s,2),c=parseInt(o,2);i.base=[a>>>0,c>>>0]}return new e(i)},e.fromHexString=function(t){var n=t.replace(/^0x/i,""),i={base:void 0,segments:void 0};if(n.length<=8){var r=parseInt(n,16);i.base=[r>>>0,0]}else{var s=n.substring(n.length-8),o=n.substring(0,n.length-8),a=parseInt(s,16),c=parseInt(o,16);i.base=[a>>>0,c>>>0]}return new e(i)},t.equals=function(e){return pe.equals(this._value,e._value)},t.getHighestBitIndex=function(){if(pe.isZero(this._value))return-1;if(0!==this._value.base[le.HIGH])for(var e=31;e>=0;e--)if(this._value.base[le.HIGH]&1<<e)return e+32;for(var t=31;t>=0;t--)if(this._value.base[le.LOW]&1<<t)return t;return-1},t.getLowestBitIndex=function(){if(pe.isZero(this._value))return-1;for(var e=0;e<32;e++)if(this._value.base[le.LOW]&1<<e)return e;for(var t=0;t<32;t++)if(this._value.base[le.HIGH]&1<<t)return t+32;return-1},e}(),Ie=function(){function e(){this._dense=[],this._sparse=new Map}var t=e.prototype;return t.add=function(e){if(this._sparse.has(e))return!1;var t=this._dense.length;return this._dense.push(e),this._sparse.set(e,t),!0},t.remove=function(e){var t=this._sparse.get(e);if(void 0===t)return!1;var n=this._dense.length-1;if(t!==n){var i=this._dense[n];this._dense[t]=i,this._sparse.set(i,t)}return this._dense.pop(),this._sparse.delete(e),!0},t.has=function(e){return this._sparse.has(e)},t.getIndex=function(e){return this._sparse.get(e)},t.getByIndex=function(e){return this._dense[e]},t.forEach=function(e){for(var t=0;t<this._dense.length;t++)e(this._dense[t],t)},t.map=function(e){for(var t=[],n=0;n<this._dense.length;n++)t.push(e(this._dense[n],n));return t},t.filter=function(e){for(var t=[],n=0;n<this._dense.length;n++)e(this._dense[n],n)&&t.push(this._dense[n]);return t},t.find=function(e){for(var t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return this._dense[t]},t.some=function(e){for(var t=0;t<this._dense.length;t++)if(e(this._dense[t],t))return!0;return!1},t.every=function(e){for(var t=0;t<this._dense.length;t++)if(!e(this._dense[t],t))return!1;return!0},t.getDenseArray=function(){return[].concat(this._dense)},t.getDenseArrayUnsafe=function(){return this._dense},t.clear=function(){this._dense.length=0,this._sparse.clear()},t.toArray=function(){return[].concat(this._dense)},t.toSet=function(){return new Set(this._dense)},t.getMemoryStats=function(){var e=8*this._dense.length,t=16*this._sparse.size;return{denseArraySize:e,sparseMapSize:t,totalMemory:e+t}},t.validate=function(){if(this._dense.length!==this._sparse.size)return!1;for(var e=0;e<this._dense.length;e++){var t=this._dense[e];if(this._sparse.get(t)!==e)return!1}for(var n,i=o(this._sparse);!(n=i()).done;){var r=n.value,s=r[0],a=r[1];if(a>=this._dense.length||this._dense[a]!==s)return!1}return!0},s(e,[{key:"size",get:function(){return this._dense.length}},{key:"isEmpty",get:function(){return 0===this._dense.length}}])}(),ke=function(e){function t(){return e.call(this)||this}return u(t,e),t.prototype.reset=function(){this.clear()},t}(y(Set)),De=function(){function e(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new Ie}var t=e.prototype;return t.addEntity=function(e){this._entities.has(e)&&this.removeEntity(e);for(var t,n=pe.clone(pe.ZERO),i=new Set,r=o(e.components);!(t=r()).done;){var s=t.value.constructor;i.add(s),ge.isRegistered(s)||ge.register(s);var a=ge.getBitMask(s);pe.orInPlace(n,a)}this._entities.add(e);for(var c=this._entities.getIndex(e);this._componentMasks.length<=c;)this._componentMasks.push(pe.clone(pe.ZERO));this._componentMasks[c]=n,this.updateComponentMappings(e,i,!0)},t.removeEntity=function(e){var t=this._entities.getIndex(e);if(void 0!==t){var n=this.getEntityComponentTypes(e);this.updateComponentMappings(e,n,!1),this._entities.remove(e);var i=this._componentMasks.length-1;t!==i&&(this._componentMasks[t]=this._componentMasks[i]),this._componentMasks.pop()}},t.queryByComponent=function(e){var t=this._componentToEntities.get(e);return t?new Set(t):new Set},t.queryMultipleAnd=function(t){var n=this;if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);for(var i,r=pe.clone(pe.ZERO),s=o(t);!(i=s()).done;){var a=i.value;if(!ge.isRegistered(a))return new Set;var c=ge.getBitMask(a);pe.orInPlace(r,c)}var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var i=n._componentMasks[t];pe.hasAll(i,r)&&u.add(e)})),u},t.queryMultipleOr=function(t){var n=this;if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);for(var i,r=pe.clone(pe.ZERO),s=o(t);!(i=s()).done;){var a=i.value;if(ge.isRegistered(a)){var c=ge.getBitMask(a);pe.orInPlace(r,c)}}if(pe.equals(r,pe.ZERO))return new Set;var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var i=n._componentMasks[t];pe.hasAny(i,r)&&u.add(e)})),u},t.hasComponent=function(e,t){var n=this._entities.getIndex(e);if(void 0===n)return!1;if(!ge.isRegistered(t))return!1;var i=this._componentMasks[n],r=ge.getBitMask(t);return pe.hasAny(i,r)},t.getEntityMask=function(e){var t=this._entities.getIndex(e);if(void 0!==t)return this._componentMasks[t]},t.getAllEntities=function(){return this._entities.toArray()},t.forEach=function(e){var t=this;this._entities.forEach((function(n,i){e(n,t._componentMasks[i],i)}))},t.clear=function(){this._entities.clear(),this._componentMasks.length=0;for(var t,n=o(this._componentToEntities.values());!(t=n()).done;){var i=t.value;e._entitySetPool.release(i)}this._componentToEntities.clear()},t.getMemoryStats=function(){for(var e,t=this._entities.getMemoryStats(),n=16*this._componentMasks.length,i=16*this._componentToEntities.size,r=o(this._componentToEntities.values());!(e=r()).done;){i+=8*e.value.size}return{entitiesMemory:t.totalMemory,masksMemory:n,mappingsMemory:i,totalMemory:t.totalMemory+n+i}},t.validate=function(){if(!this._entities.validate())return!1;if(this._componentMasks.length!==this._entities.size)return!1;for(var e,t=new Set,n=o(this._componentToEntities.values());!(e=n()).done;)for(var i,r=o(e.value);!(i=r()).done;){var s=i.value;t.add(s)}for(var a,c=o(t);!(a=c()).done;){var u=a.value;if(!this._entities.has(u))return!1}return!0},t.getEntityComponentTypes=function(e){for(var t,n=new Set,i=o(e.components);!(t=i()).done;){var r=t.value;n.add(r.constructor)}return n},t.updateComponentMappings=function(t,n,i){for(var r,s=o(n);!(r=s()).done;){var a=r.value,c=this._componentToEntities.get(a);i?(c||(c=e._entitySetPool.obtain(),this._componentToEntities.set(a,c)),c.add(t)):c&&(c.delete(t),0===c.size&&(this._componentToEntities.delete(a),e._entitySetPool.release(c)))}},s(e,[{key:"size",get:function(){return this._entities.size}},{key:"isEmpty",get:function(){return this._entities.isEmpty}}])}();De._entitySetPool=z.getPool(ke,50,512);var Re,Oe=function(){function e(){this.buckets=new Map,this._size=0}var t=e.prototype;return t.murmur32=function(e,t){var n=t>>>0,i=function(e){e=(e=Math.imul(e,3432918353)>>>0)<<15|e>>>17,e=Math.imul(e,461845907)>>>0,n=(n^=e)<<13|n>>>19,n=Math.imul(n,5)+3864292196>>>0};if(i(e.base[0]>>>0),i(e.base[1]>>>0),e.segments)for(var r,s=o(e.segments);!(r=s()).done;){var a=r.value;i(a[0]>>>0),i(a[1]>>>0)}return n^=e.segments?8*e.segments.length:8,n^=n>>>16,n=Math.imul(n,2246822507)>>>0,n^=n>>>13,n=Math.imul(n,3266489909)>>>0,(n^=n>>>16)>>>0},t.getHashes=function(e){return[this.murmur32(e,2538058380),this.murmur32(e,305419896)]},t.set=function(e,t){var n=this.getHashes(e),i=n[0],r=n[1],s=this.buckets.get(i);s||(s=[],this.buckets.set(i,s));for(var o=0;o<s.length;o++)if(s[o][0]===r)return s[o][1]=t,this;return s.push([r,t]),this._size++,this},t.get=function(e){var t=this.getHashes(e),n=t[0],i=t[1],r=this.buckets.get(n);if(r)for(var s=0;s<r.length;s++)if(r[s][0]===i)return r[s][1]},t.has=function(e){return void 0!==this.get(e)},t.delete=function(e){var t=this.getHashes(e),n=t[0],i=t[1],r=this.buckets.get(n);if(!r)return!1;for(var s=0;s<r.length;s++)if(r[s][0]===i)return r.splice(s,1),this._size--,0===r.length&&this.buckets.delete(n),!0;return!1},t.clear=function(){this.buckets.clear(),this._size=0},t.entries=l().m((function e(){var t,n,i,r,s,a,c,u;return l().w((function(e){for(;;)switch(e.n){case 0:t=o(this.buckets);case 1:if((n=t()).done){e.n=5;break}(i=n.value)[0],r=i[1],s=o(r);case 2:if((a=s()).done){e.n=4;break}return(c=a.value)[0],u=c[1],e.n=3,[void 0,u];case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}}),e,this)})),t.values=l().m((function e(){var t,n,i,r,s,a,c;return l().w((function(e){for(;;)switch(e.n){case 0:t=o(this.buckets.values());case 1:if((n=t()).done){e.n=5;break}i=n.value,r=o(i);case 2:if((s=r()).done){e.n=4;break}return(a=s.value)[0],c=a[1],e.n=3,c;case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}}),e,this)})),s(e,[{key:"size",get:function(){return this._size}},{key:"innerBuckets",get:function(){return this.buckets}}])}(),ze=function(){function e(){this._archetypes=new Oe,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._entityComponentTypesCache=new Map,this._allArchetypes=[]}var t=e.prototype;return t.addEntity=function(e){var t=this.getEntityComponentTypes(e),n=this.generateArchetypeId(t),i=this._archetypes.get(n);i||(i=this.createArchetype(t)),i.entities.add(e),this._entityToArchetype.set(e,i)},t.removeEntity=function(e){var t=this._entityToArchetype.get(e);t&&(t.entities.delete(e),this._entityComponentTypesCache.delete(e),this._entityToArchetype.delete(e))},t.updateEntity=function(e){var t=this._entityToArchetype.get(e);this._entityComponentTypesCache.delete(e);var n=this.getEntityComponentTypes(e),i=this.generateArchetypeId(n);if(!t||t.id!==i){t&&t.entities.delete(e);var r=this._archetypes.get(i);r||(r=this.createArchetype(n)),r.entities.add(e),this._entityToArchetype.set(e,r)}},t.queryArchetypes=function(e,t){void 0===t&&(t="AND");var n=[],i=0;if("AND"===t){if(0===e.length){for(var r,s=o(this._allArchetypes);!(r=s()).done;){var a=r.value;n.push(a),i+=a.entities.size}return{archetypes:n,totalEntities:i}}if(1===e.length){var c=this._componentToArchetypes.get(e[0]);if(c)for(var u,h=o(c);!(u=h()).done;){var l=u.value;n.push(l),i+=l.entities.size}return{archetypes:n,totalEntities:i}}for(var f,d,p=1/0,y=o(e);!(d=y()).done;){var m=d.value,g=this._componentToArchetypes.get(m);if(!g||0===g.size)return{archetypes:[],totalEntities:0};g.size<p&&(p=g.size,f=g)}var v=this.generateArchetypeId(e);if(f)for(var _,S=o(f);!(_=S()).done;){var C=_.value;pe.hasAll(C.id,v)&&(n.push(C),i+=C.entities.size)}}else{for(var w,E=new Set,b=o(e);!(w=b()).done;){var A=w.value,T=this._componentToArchetypes.get(A);if(T)for(var M,x=o(T);!(M=x()).done;){var I=M.value;E.add(I)}}for(var k,D=o(E);!(k=D()).done;){var R=k.value;n.push(R),i+=R.entities.size}}return{archetypes:n,totalEntities:i}},t.getEntityArchetype=function(e){return this._entityToArchetype.get(e)},t.getAllArchetypes=function(){return this._allArchetypes.slice()},t.getEntitiesByComponent=function(e){var t=this._componentToArchetypes.get(e);if(!t||0===t.size)return[];for(var n,i=[],r=o(t);!(n=r()).done;)for(var s,a=o(n.value.entities);!(s=a()).done;){var c=s.value;i.push(c)}return i},t.clear=function(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._entityComponentTypesCache.clear(),this._allArchetypes=[]},t.updateAllArchetypeArrays=function(){this._allArchetypes=[];for(var e,t=o(this._archetypes.values());!(e=t()).done;){var n=e.value;this._allArchetypes.push(n)}},t.getEntityComponentTypes=function(e){var t=this._entityComponentTypesCache.get(e);return t||(t=e.components.map((function(e){return e.constructor})),this._entityComponentTypesCache.set(e,t)),t},t.generateArchetypeId=function(e){for(var t,n=pe.clone(pe.ZERO),i=o(e);!(t=i()).done;){var r=t.value;ge.isRegistered(r)||ge.register(r);var s=ge.getBitMask(r);pe.orInPlace(n,s)}return n},t.createArchetype=function(e){var t=this.generateArchetypeId(e),n={id:t,componentTypes:[].concat(e),entities:new Set};this._archetypes.set(t,n),this.updateAllArchetypeArrays();for(var i,r=o(e);!(i=r()).done;){var s=i.value,a=this._componentToArchetypes.get(s);a||(a=new Set,this._componentToArchetypes.set(s,a)),a.add(n)}return n},e}();!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(Re||(Re={}));var Be,Pe=Y("ReactiveQuery");exports.ReactiveQueryChangeType=void 0,(Be=exports.ReactiveQueryChangeType||(exports.ReactiveQueryChangeType={})).ADDED="added",Be.REMOVED="removed",Be.BATCH_UPDATE="batch_update";var Le,Ne,We=function(){function e(e,t){var n,i,r;void 0===t&&(t={}),this._entities=[],this._entityIdSet=new Set,this._listeners=[],this._active=!0,this._condition=e,this._config={enableBatchMode:null===(n=t.enableBatchMode)||void 0===n||n,batchDelay:null!==(i=t.batchDelay)&&void 0!==i?i:16,debug:null!==(r=t.debug)&&void 0!==r&&r},this._id=this.generateQueryId(),this._batchChanges={added:[],removed:[],timer:null},this._config.debug&&Pe.debug("创建ReactiveQuery: "+this._id)}var t=e.prototype;return t.generateQueryId=function(){return this._condition.type+":"+this._condition.componentTypes.map((function(e){return e.name})).sort().join(",")},t.subscribe=function(e){var t=this;if(!this._active)throw new Error("Cannot subscribe to disposed ReactiveQuery "+this._id);if("function"!=typeof e)throw new TypeError("Listener must be a function");return this._listeners.push(e),this._config.debug&&Pe.debug("订阅ReactiveQuery: "+this._id+", 监听器数量: "+this._listeners.length),function(){var n=t._listeners.indexOf(e);-1!==n&&t._listeners.splice(n,1)}},t.unsubscribeAll=function(){this._listeners.length=0},t.getEntities=function(){return this._entities},t.matches=function(e){var t=e.componentMask;switch(this._condition.type){case Re.ALL:return pe.hasAll(t,this._condition.mask);case Re.ANY:return pe.hasAny(t,this._condition.mask);case Re.NONE:return pe.hasNone(t,this._condition.mask);default:return!1}},t.notifyEntityAdded=function(e){this._active&&this.matches(e)&&(this._entityIdSet.has(e.id)||(this._entities.push(e),this._entityIdSet.add(e.id),this._config.enableBatchMode?this.addToBatch("added",e):this.notifyListeners({type:exports.ReactiveQueryChangeType.ADDED,entity:e}),this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 实体添加 "+e.name+"("+e.id+")")))},t.notifyEntityRemoved=function(e){if(this._active&&this._entityIdSet.has(e.id)){var t=this._entities.indexOf(e);-1!==t&&this._entities.splice(t,1),this._entityIdSet.delete(e.id),this._config.enableBatchMode?this.addToBatch("removed",e):this.notifyListeners({type:exports.ReactiveQueryChangeType.REMOVED,entity:e}),this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 实体移除 "+e.name+"("+e.id+")")}},t.notifyEntityChanged=function(e){if(this._active){var t=this._entityIdSet.has(e.id),n=this.matches(e);t&&!n?this.notifyEntityRemoved(e):!t&&n&&this.notifyEntityAdded(e)}},t.initializeWith=function(e){this._entities.length=0,this._entityIdSet.clear();for(var t,n=o(e);!(t=n()).done;){var i=t.value;this.matches(i)&&(this._entities.push(i),this._entityIdSet.add(i.id))}this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 初始化 "+this._entities.length+" 个实体")},t.addToBatch=function(e,t){var n=this;"added"===e?this._batchChanges.added.push(t):this._batchChanges.removed.push(t),null===this._batchChanges.timer&&(this._batchChanges.timer=setTimeout((function(){n.flushBatchChanges()}),this._config.batchDelay))},t.flushBatchChanges=function(){if(0!==this._batchChanges.added.length||0!==this._batchChanges.removed.length){var e=[].concat(this._batchChanges.added),t=[].concat(this._batchChanges.removed);this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._batchChanges.timer=null,this.notifyListeners({type:exports.ReactiveQueryChangeType.BATCH_UPDATE,added:e,removed:t,entities:this._entities}),this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 批量更新 +"+e.length+" -"+t.length)}else this._batchChanges.timer=null},t.notifyListeners=function(e){for(var t,n=o([].concat(this._listeners));!(t=n()).done;){var i=t.value;try{i(e)}catch(e){Pe.error("ReactiveQuery "+this._id+": 监听器执行出错",e)}}},t.pause=function(){this._active=!1,null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0},t.resume=function(){this._active=!0},t.dispose=function(){null!==this._batchChanges.timer&&(clearTimeout(this._batchChanges.timer),this._batchChanges.timer=null),this._batchChanges.added.length=0,this._batchChanges.removed.length=0,this._active=!1,this.unsubscribeAll(),this._entities.length=0,this._entityIdSet.clear(),this._config.debug&&Pe.debug("ReactiveQuery "+this._id+": 已销毁")},s(e,[{key:"count",get:function(){return this._entities.length}},{key:"condition",get:function(){return this._condition}},{key:"id",get:function(){return this._id}},{key:"active",get:function(){return this._active}},{key:"listenerCount",get:function(){return this._listeners.length}}])}(),Ue=function(){function e(){this._logger=Y("QuerySystem"),this.entities=[],this._version=0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.componentMaskCache=new Map,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.resultArrayPool=[],this.poolMaxSize=50,this._reactiveQueries=new Map,this._reactiveQueriesByComponent=new Map,this.entityIndex={byTag:new Map,byName:new Map},this.archetypeSystem=new ze}var t=e.prototype;return t.acquireResultArray=function(){return this.resultArrayPool.length>0?this.resultArrayPool.pop():[]},t.releaseResultArray=function(e){this.resultArrayPool.length<this.poolMaxSize&&(e.length=0,this.resultArrayPool.push(e))},t.setEntities=function(e){this.entities=e,this.clearQueryCache(),this.clearReactiveQueries(),this.rebuildIndexes()},t.addEntity=function(e,t){void 0===t&&(t=!1),this.entities.includes(e)||(this.entities.push(e),this.addEntityToIndexes(e),this.archetypeSystem.addEntity(e),this.notifyReactiveQueriesEntityAdded(e),t||this.clearQueryCache(),this._version++)},t.addEntities=function(e){if(0!==e.length){for(var t,n=new Set(this.entities.map((function(e){return e.id}))),i=0,r=o(e);!(t=r()).done;){var s=t.value;n.has(s.id)||(this.entities.push(s),this.addEntityToIndexes(s),this.archetypeSystem.addEntity(s),n.add(s.id),i++)}i>0&&this.clearQueryCache()}},t.addEntitiesUnchecked=function(e){if(0!==e.length){for(var t,n=o(e);!(t=n()).done;){var i=t.value;this.entities.push(i)}for(var r,s=o(e);!(r=s()).done;){var a=r.value;this.addEntityToIndexes(a),this.archetypeSystem.addEntity(a)}this.clearQueryCache()}},t.removeEntity=function(e){var t=this.entities.indexOf(e);if(-1!==t){for(var n,i=[],r=o(e.components);!(n=r()).done;){var s=n.value;i.push(s.constructor)}this.entities.splice(t,1),this.removeEntityFromIndexes(e),this.archetypeSystem.removeEntity(e),i.length>0?this.notifyReactiveQueriesEntityRemoved(e,i):this.notifyReactiveQueriesEntityRemovedFallback(e),this.clearQueryCache(),this._version++}},t.updateEntity=function(e){this.entities.includes(e)?(this.removeEntityFromIndexes(e),this.archetypeSystem.updateEntity(e),this.addEntityToIndexes(e),this.notifyReactiveQueriesEntityChanged(e),this.clearQueryCache(),this._version++):this.addEntity(e)},t.addEntityToIndexes=function(e){var t=e.tag;void 0!==t&&(this.entityIndex.byTag.get(t)||this.createAndSetTagIndex(t)).add(e);var n=e.name;n&&(this.entityIndex.byName.get(n)||this.createAndSetNameIndex(n)).add(e)},t.createAndSetTagIndex=function(e){var t=new Set;return this.entityIndex.byTag.set(e,t),t},t.createAndSetNameIndex=function(e){var t=new Set;return this.entityIndex.byName.set(e,t),t},t.removeEntityFromIndexes=function(e){if(void 0!==e.tag){var t=this.entityIndex.byTag.get(e.tag);t&&(t.delete(e),0===t.size&&this.entityIndex.byTag.delete(e.tag))}if(e.name){var n=this.entityIndex.byName.get(e.name);n&&(n.delete(e),0===n.size&&this.entityIndex.byName.delete(e.name))}},t.rebuildIndexes=function(){this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear();for(var e,t=o(this.entities);!(e=t()).done;){var n=e.value;this.addEntityToIndexes(n),this.archetypeSystem.addEntity(n)}},t.queryAll=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(Re.ALL,n).getEntities();return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryMultipleComponents=function(e){for(var t,n=[],i=o(this.archetypeSystem.queryArchetypes(e,"AND").archetypes);!(t=i()).done;)for(var r,s=o(t.value.entities);!(r=s()).done;){var a=r.value;n.push(a)}return n},t.queryAny=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(Re.ANY,n).getEntities();return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryNone=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];var r=this.getOrCreateReactiveQuery(Re.NONE,n).getEntities();return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!0}},t.queryByTag=function(e){var t=performance.now();this.queryStats.totalQueries++;var n="tag:"+e,i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byTag.get(e)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByName=function(e){var t=performance.now();this.queryStats.totalQueries++;var n="name:"+e,i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byName.get(e)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByComponent=function(e){var t=performance.now();this.queryStats.totalQueries++;var n=this.generateCacheKey("component",[e]),i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var r=this.archetypeSystem.getEntitiesByComponent(e);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!1}},t.getFromCache=function(e){var t=this.queryCache.get(e);return t?Date.now()-t.timestamp>this.cacheTimeout||t.version!==this._version?(this.queryCache.delete(e),null):(t.hitCount++,t.entities):null},t.addToCache=function(e,t){this.queryCache.size>=this.cacheMaxSize&&this.cleanupCache(),this.queryCache.set(e,{entities:t,timestamp:Date.now(),hitCount:0,version:this._version})},t.cleanupCache=function(){for(var e,t=Date.now(),n=o(this.queryCache.entries());!(e=n()).done;){var i=e.value,r=i[0];t-i[1].timestamp>this.cacheTimeout&&this.queryCache.delete(r)}if(this.queryCache.size>=this.cacheMaxSize){for(var s,a=1/0,c="",u=1/0,h=o(this.queryCache.entries());!(s=h()).done;){var l=s.value,f=l[0],d=l[1];(d.hitCount<a||d.hitCount===a&&d.timestamp<u)&&(a=d.hitCount,c=f,u=d.timestamp)}c&&this.queryCache.delete(c)}},t.clearQueryCache=function(){this.queryCache.clear(),this.componentMaskCache.clear()},t.clearReactiveQueries=function(){for(var e,t=o(this._reactiveQueries.values());!(e=t()).done;){e.value.dispose()}this._reactiveQueries.clear(),this._reactiveQueriesByComponent.clear()},t.generateCacheKey=function(e,t){return 1===t.length?e+":"+U(t[0]):e+":"+t.map((function(e){return U(e)})).sort().join(",")},t.clearCache=function(){this.clearQueryCache(),this.clearReactiveQueries()},t.createReactiveQuery=function(e,t){if(!e||0===e.length)throw new Error("组件类型列表不能为空");var n=this.createComponentMask(e),i={type:Re.ALL,componentTypes:e,mask:n},r=new We(i,t),s=this.executeTraditionalQuery(Re.ALL,e);r.initializeWith(s);var a=this.generateCacheKey("all",e);this._reactiveQueries.set(a,r);for(var c,u=o(e);!(c=u()).done;){var h=c.value,l=this._reactiveQueriesByComponent.get(h);l||(l=new Set,this._reactiveQueriesByComponent.set(h,l)),l.add(r)}return r},t.destroyReactiveQuery=function(e){if(e){var t=e.id;this._reactiveQueries.delete(t);for(var n,i=o(e.condition.componentTypes);!(n=i()).done;){var r=n.value,s=this._reactiveQueriesByComponent.get(r);s&&(s.delete(e),0===s.size&&this._reactiveQueriesByComponent.delete(r))}e.dispose()}},t.createComponentMask=function(e){var t=e.map((function(e){return U(e)})).sort().join(","),n=this.componentMaskCache.get(t);if(n)return n;for(var i,r=pe.clone(pe.ZERO),s=o(e);!(i=s()).done;){var a=i.value;ge.isRegistered(a)||ge.register(a);var c=ge.getBitMask(a);pe.orInPlace(r,c)}return this.componentMaskCache.set(t,r),r},t.getAllEntities=function(){return this.entities},t.getStats=function(){return{entityCount:this.entities.length,indexStats:{componentIndexSize:this.archetypeSystem.getAllArchetypes().length,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},queryStats:a({},this.queryStats,{cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}),optimizationStats:{archetypeSystem:this.archetypeSystem.getAllArchetypes().map((function(e){return{id:e.id,componentTypes:e.componentTypes.map((function(e){return U(e)})),entityCount:e.entities.size}}))},cacheStats:{size:this._reactiveQueries.size,hitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}},t.getEntityArchetype=function(e){return this.archetypeSystem.getEntityArchetype(e)},t.getOrCreateReactiveQuery=function(e,t){var n=this.generateCacheKey(e,t),i=this._reactiveQueries.get(n);if(!i){var r=this.createComponentMask(t);i=new We({type:e,componentTypes:t,mask:r},{enableBatchMode:!1,debug:!1});var s=this.executeTraditionalQuery(e,t);i.initializeWith(s),this._reactiveQueries.set(n,i);for(var a,c=o(t);!(a=c()).done;){var u=a.value,h=this._reactiveQueriesByComponent.get(u);h||(h=new Set,this._reactiveQueriesByComponent.set(u,h)),h.add(i)}this._logger.debug("创建内部响应式查询缓存: "+n)}return i},t.executeTraditionalQuery=function(e,t){switch(e){case Re.ALL:for(var n,i=[],r=o(this.archetypeSystem.queryArchetypes(t,"AND").archetypes);!(n=r()).done;)for(var s,a=o(n.value.entities);!(s=a()).done;){var c=s.value;i.push(c)}return i;case Re.ANY:for(var u,h=[],l=o(this.archetypeSystem.queryArchetypes(t,"OR").archetypes);!(u=l()).done;)for(var f,d=o(u.value.entities);!(f=d()).done;){var p=f.value;h.push(p)}return h;case Re.NONE:var y=this.createComponentMask(t);return this.entities.filter((function(e){return pe.hasNone(e.componentMask,y)}));default:return[]}},t.notifyReactiveQueriesEntityAdded=function(e){if(0!==this._reactiveQueries.size)for(var t,n=new Set,i=o(e.components);!(t=i()).done;){var r=t.value.constructor,s=this._reactiveQueriesByComponent.get(r);if(s)for(var a,c=o(s);!(a=c()).done;){var u=a.value;n.has(u)||(u.notifyEntityAdded(e),n.add(u))}}},t.notifyReactiveQueriesEntityRemoved=function(e,t){if(0!==this._reactiveQueries.size)for(var n,i=new Set,r=o(t);!(n=r()).done;){var s=n.value,a=this._reactiveQueriesByComponent.get(s);if(a)for(var c,u=o(a);!(c=u()).done;){var h=c.value;i.has(h)||(h.notifyEntityRemoved(e),i.add(h))}}},t.notifyReactiveQueriesEntityRemovedFallback=function(e){if(0!==this._reactiveQueries.size)for(var t,n=o(this._reactiveQueries.values());!(t=n()).done;){t.value.notifyEntityRemoved(e)}},t.notifyReactiveQueriesEntityChanged=function(e){if(0!==this._reactiveQueries.size){for(var t,n=new Set,i=o(e.components);!(t=i()).done;){var r=t.value.constructor,s=this._reactiveQueriesByComponent.get(r);if(s)for(var a,c=o(s);!(a=c()).done;){var u=a.value;n.has(u)||(u.notifyEntityChanged(e),n.add(u))}}for(var h,l=o(this._reactiveQueries.values());!(h=l()).done;){var f=h.value;n.has(f)||f.notifyEntityChanged(e)}}},s(e,[{key:"version",get:function(){return this._version}}])}(),Fe=function(){function e(e){this._logger=Y("QueryBuilder"),this.conditions=[],this.querySystem=e}var t=e.prototype;return t.withAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:Re.ALL,componentTypes:t,mask:this.createComponentMask(t)}),this},t.withAny=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:Re.ANY,componentTypes:t,mask:this.createComponentMask(t)}),this},t.without=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.conditions.push({type:Re.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this},t.execute=function(){var e,t,n,i=performance.now();if(1===this.conditions.length){var r=this.conditions[0];switch(r.type){case Re.ALL:return(e=this.querySystem).queryAll.apply(e,r.componentTypes);case Re.ANY:return(t=this.querySystem).queryAny.apply(t,r.componentTypes);case Re.NONE:return(n=this.querySystem).queryNone.apply(n,r.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-i,fromCache:!1}},t.createComponentMask=function(e){for(var t,n=pe.clone(pe.ZERO),i=o(e);!(t=i()).done;){var r=t.value;try{var s=ge.getBitMask(r);pe.orInPlace(n,s)}catch(e){this._logger.warn("组件类型 "+U(r)+" 未注册,跳过")}}return n},t.reset=function(){return this.conditions=[],this},e}(),He=function(){function e(){this.listeners=new Map,this.stats=new Map,this.batchQueue=new Map,this.batchTimers=new Map,this.batchConfigs=new Map,this.nextListenerId=0,this.isEnabled=!0,this.maxListeners=100}var t=e.prototype;return t.on=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,n)},t.once=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,a({},n,{once:!0}))},t.onAsync=function(e,t,n){return void 0===n&&(n={}),this.addListener(e,t,a({},n,{async:!0}))},t.off=function(e,t){var n=this.listeners.get(e);if(!n)return!1;var i=n.findIndex((function(e){return e.id===t}));return-1!==i&&(n.splice(i,1),0===n.length&&(this.listeners.delete(e),this.stats.delete(e)),!0)},t.offAll=function(e){this.listeners.delete(e),this.stats.delete(e),this.clearBatch(e)},t.emit=function(){var e=n(l().m((function e(t,n){var i;return l().w((function(e){for(;;)switch(e.n){case 0:if(this.isEnabled){e.n=1;break}return e.a(2);case 1:if(null==(i=this.batchConfigs.get(t))||!i.enabled){e.n=2;break}return this.addToBatch(t,n),e.a(2);case 2:return e.n=3,this.executeEvent(t,n);case 3:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),t.emitSync=function(t,n){if(this.isEnabled){var i=this.listeners.get(t);if(i&&0!==i.length){for(var r,s=performance.now(),a=[],c=o(this.sortListenersByPriority(i));!(r=c()).done;){var u=r.value;if(!u.config.async)try{u.config.context?u.handler.call(u.config.context,n):u.handler(n),u.config.once&&a.push(u.id)}catch(n){e._logger.error("事件处理器执行错误 "+t+":",n)}}this.removeListeners(t,a),this.updateStats(t,performance.now()-s)}}},t.setBatchConfig=function(e,t){this.batchConfigs.set(e,t)},t.flushBatch=function(e){var t=this.batchQueue.get(e);if(t&&0!==t.length){var n=this.batchTimers.get(e);n&&(clearTimeout(n),this.batchTimers.delete(e)),this.processBatch(e,t),this.batchQueue.delete(e)}},t.getStats=function(e){return e?this.stats.get(e)||this.createEmptyStats(e):new Map(this.stats)},t.resetStats=function(e){e?this.stats.delete(e):this.stats.clear()},t.setEnabled=function(e){this.isEnabled=e},t.hasListeners=function(e){var t=this.listeners.get(e);return!!t&&t.length>0},t.getListenerCount=function(e){var t=this.listeners.get(e);return t?t.length:0},t.clear=function(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()},t.setMaxListeners=function(e){this.maxListeners=e},t.addListener=function(t,n,i){var r=this.listeners.get(t);if(r||(r=[],this.listeners.set(t,r)),r.length>=this.maxListeners)return e._logger.warn("事件类型 "+t+" 的监听器数量超过最大限制 ("+this.maxListeners+")"),"";var s="listener_"+this.nextListenerId++,o={handler:n,config:a({priority:0},i),id:s};return r.push(o),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),s},t.executeEvent=function(){var t=n(l().m((function t(i,r){var s,a,c,u,h,f,d,p,y,m;return l().w((function(t){for(;;)switch(t.n){case 0:if((s=this.listeners.get(i))&&0!==s.length){t.n=1;break}return t.a(2);case 1:for(a=performance.now(),c=[],u=this.sortListenersByPriority(s),h=u.filter((function(e){return!e.config.async})),f=u.filter((function(e){return e.config.async})),d=o(h);!(p=d()).done;){y=p.value;try{y.config.context?y.handler.call(y.config.context,r):y.handler(r),y.config.once&&c.push(y.id)}catch(t){e._logger.error("同步事件处理器执行错误 "+i+":",t)}}return m=f.map(function(){var t=n(l().m((function t(n){var s;return l().w((function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,!n.config.context){t.n=2;break}return t.n=1,n.handler.call(n.config.context,r);case 1:t.n=3;break;case 2:return t.n=3,n.handler(r);case 3:n.config.once&&c.push(n.id),t.n=5;break;case 4:t.p=4,s=t.v,e._logger.error("异步事件处理器执行错误 "+i+":",s);case 5:return t.a(2)}}),t,null,[[0,4]])})));return function(e){return t.apply(this,arguments)}}()),t.n=2,Promise.all(m);case 2:this.removeListeners(i,c),this.updateStats(i,performance.now()-a);case 3:return t.a(2)}}),t,this)})));return function(e,n){return t.apply(this,arguments)}}(),t.sortListenersByPriority=function(e){return e.slice().sort((function(e,t){return(t.config.priority||0)-(e.config.priority||0)}))},t.removeListeners=function(e,t){if(0!==t.length){var n=this.listeners.get(e);if(n){for(var i,r=function(){var e=i.value,t=n.findIndex((function(t){return t.id===e}));-1!==t&&n.splice(t,1)},s=o(t);!(i=s()).done;)r();0===n.length&&(this.listeners.delete(e),this.stats.delete(e))}}},t.addToBatch=function(e,t){var n=this,i=this.batchQueue.get(e);i||(i=[],this.batchQueue.set(e,i)),i.push(t);var r=this.batchConfigs.get(e);if(i.length>=r.batchSize)this.flushBatch(e);else if(!this.batchTimers.has(e)){var s=setTimeout((function(){n.flushBatch(e)}),r.delay);this.batchTimers.set(e,s)}},t.processBatch=function(){var e=n(l().m((function e(t,n){var i;return l().w((function(e){for(;;)switch(e.n){case 0:return i={type:t,events:n,count:n.length,timestamp:Date.now()},e.n=1,this.executeEvent(t+":batch",i);case 1:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),t.clearBatch=function(e){this.batchQueue.delete(e);var t=this.batchTimers.get(e);t&&(clearTimeout(t),this.batchTimers.delete(e))},t.clearAllBatches=function(){this.batchQueue.clear();for(var e,t=o(this.batchTimers.values());!(e=t()).done;){var n=e.value;clearTimeout(n)}this.batchTimers.clear(),this.batchConfigs.clear()},t.updateStats=function(e,t){var n=this.stats.get(e);n||(n=this.createEmptyStats(e),this.stats.set(e,n)),n.triggerCount++,n.totalExecutionTime+=t,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(e)},t.createEmptyStats=function(e){return{eventType:e,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}},e}();He._logger=Y("EventSystem"),exports.ECSEventType=void 0,(Le=exports.ECSEventType||(exports.ECSEventType={})).ENTITY_CREATED="entity:created",Le.ENTITY_DESTROYED="entity:destroyed",Le.ENTITY_ENABLED="entity:enabled",Le.ENTITY_DISABLED="entity:disabled",Le.ENTITY_TAG_ADDED="entity:tag:added",Le.ENTITY_TAG_REMOVED="entity:tag:removed",Le.ENTITY_NAME_CHANGED="entity:name:changed",Le.COMPONENT_ADDED="component:added",Le.COMPONENT_REMOVED="component:removed",Le.COMPONENT_MODIFIED="component:modified",Le.COMPONENT_ENABLED="component:enabled",Le.COMPONENT_DISABLED="component:disabled",Le.SYSTEM_ADDED="system:added",Le.SYSTEM_REMOVED="system:removed",Le.SYSTEM_ENABLED="system:enabled",Le.SYSTEM_DISABLED="system:disabled",Le.SYSTEM_PROCESSING_START="system:processing:start",Le.SYSTEM_PROCESSING_END="system:processing:end",Le.SYSTEM_ERROR="system:error",Le.SCENE_CREATED="scene:created",Le.SCENE_DESTROYED="scene:destroyed",Le.SCENE_ACTIVATED="scene:activated",Le.SCENE_DEACTIVATED="scene:deactivated",Le.SCENE_PAUSED="scene:paused",Le.SCENE_RESUMED="scene:resumed",Le.QUERY_EXECUTED="query:executed",Le.QUERY_CACHE_HIT="query:cache:hit",Le.QUERY_CACHE_MISS="query:cache:miss",Le.QUERY_OPTIMIZED="query:optimized",Le.PERFORMANCE_WARNING="performance:warning",Le.PERFORMANCE_CRITICAL="performance:critical",Le.MEMORY_USAGE_HIGH="memory:usage:high",Le.FRAME_RATE_DROP="frame:rate:drop",Le.INDEX_CREATED="index:created",Le.INDEX_UPDATED="index:updated",Le.INDEX_OPTIMIZED="index:optimized",Le.ARCHETYPE_CREATED="archetype:created",Le.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",Le.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",Le.DIRTY_MARK_ADDED="dirty:mark:added",Le.DIRTY_BATCH_PROCESSED="dirty:batch:processed",Le.ERROR_OCCURRED="error:occurred",Le.WARNING_ISSUED="warning:issued",Le.FRAMEWORK_INITIALIZED="framework:initialized",Le.FRAMEWORK_SHUTDOWN="framework:shutdown",Le.DEBUG_INFO="debug:info",Le.DEBUG_STATS_UPDATED="debug:stats:updated",exports.EventPriority=void 0,(Ne=exports.EventPriority||(exports.EventPriority={}))[Ne.LOWEST=0]="LOWEST",Ne[Ne.LOW=25]="LOW",Ne[Ne.NORMAL=50]="NORMAL",Ne[Ne.HIGH=75]="HIGH",Ne[Ne.HIGHEST=100]="HIGHEST",Ne[Ne.CRITICAL=200]="CRITICAL";var je={ENTITY:{CREATED:exports.ECSEventType.ENTITY_CREATED,DESTROYED:exports.ECSEventType.ENTITY_DESTROYED,ENABLED:exports.ECSEventType.ENTITY_ENABLED,DISABLED:exports.ECSEventType.ENTITY_DISABLED,TAG_ADDED:exports.ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:exports.ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:exports.ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:exports.ECSEventType.COMPONENT_ADDED,REMOVED:exports.ECSEventType.COMPONENT_REMOVED,MODIFIED:exports.ECSEventType.COMPONENT_MODIFIED,ENABLED:exports.ECSEventType.COMPONENT_ENABLED,DISABLED:exports.ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:exports.ECSEventType.SYSTEM_ADDED,REMOVED:exports.ECSEventType.SYSTEM_REMOVED,ENABLED:exports.ECSEventType.SYSTEM_ENABLED,DISABLED:exports.ECSEventType.SYSTEM_DISABLED,PROCESSING_START:exports.ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:exports.ECSEventType.SYSTEM_PROCESSING_END,ERROR:exports.ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:exports.ECSEventType.PERFORMANCE_WARNING,CRITICAL:exports.ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:exports.ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:exports.ECSEventType.FRAME_RATE_DROP}},qe=function(){function e(){}return e.isValid=function(e){return this.validTypes.has(e)},e.getAllValidTypes=function(){return Array.from(this.validTypes)},e.addCustomType=function(e){this.validTypes.add(e)},e.removeCustomType=function(e){this.validTypes.delete(e)},e}();qe.validTypes=new Set([].concat(Object.values(exports.ECSEventType),Object.values(je.ENTITY),Object.values(je.COMPONENT),Object.values(je.SYSTEM),Object.values(je.PERFORMANCE)));var Ge=function(){function e(e){void 0===e&&(e=!1),this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new He,this.isDebugMode=e}var t=e.prototype;return t.emit=function(t,n,i){void 0===i&&(i=!1),this.validateEventType(t);var r=i?this.enhanceEventData(t,n):n;this.isDebugMode&&e._logger.info("发射事件: "+t,r),this.eventSystem.emitSync(t,r)},t.emitAsync=function(){var t=n(l().m((function t(n,i,r){var s;return l().w((function(t){for(;;)switch(t.n){case 0:return void 0===r&&(r=!1),this.validateEventType(n),s=r?this.enhanceEventData(n,i):i,this.isDebugMode&&e._logger.info("发射异步事件: "+n,s),t.n=1,this.eventSystem.emit(n,s);case 1:return t.a(2)}}),t,this)})));return function(e,n,i){return t.apply(this,arguments)}}(),t.on=function(t,n,i){void 0===i&&(i={}),this.validateEventType(t);var r={once:i.once||!1,priority:i.priority||exports.EventPriority.NORMAL,async:i.async||!1,context:i.context};return this.isDebugMode&&e._logger.info("添加监听器: "+t,r),this.eventSystem.on(t,n,r)},t.once=function(e,t,n){return void 0===n&&(n={}),this.on(e,t,a({},n,{once:!0}))},t.onAsync=function(e,t,n){return void 0===n&&(n={}),this.on(e,t,a({},n,{async:!0}))},t.off=function(t,n){return this.isDebugMode&&e._logger.info("移除监听器: "+n+" 事件: "+t),this.eventSystem.off(t,n)},t.offAll=function(t){this.isDebugMode&&e._logger.info("移除所有监听器: "+t),this.eventSystem.offAll(t)},t.hasListeners=function(e){return this.eventSystem.hasListeners(e)},t.getStats=function(e){var t=this,n=this.eventSystem.getStats(e);if(n instanceof Map){var i=new Map;return n.forEach((function(e,n){i.set(n,t.convertEventStats(e))})),i}return this.convertEventStats(n)},t.clear=function(){this.isDebugMode&&e._logger.info("清空所有监听器"),this.eventSystem.clear()},t.setEnabled=function(e){this.eventSystem.setEnabled(e)},t.setDebugMode=function(e){this.isDebugMode=e},t.setMaxListeners=function(e){this.eventSystem.setMaxListeners(e)},t.getListenerCount=function(e){return this.eventSystem.getListenerCount(e)},t.setBatchConfig=function(e,t,n){this.eventSystem.setBatchConfig(e,{batchSize:t,delay:n,enabled:!0})},t.flushBatch=function(e){this.eventSystem.flushBatch(e)},t.resetStats=function(e){this.eventSystem.resetStats(e)},t.emitEntityCreated=function(e){this.emit(exports.ECSEventType.ENTITY_CREATED,e)},t.emitEntityDestroyed=function(e){this.emit(exports.ECSEventType.ENTITY_DESTROYED,e)},t.emitComponentAdded=function(e){this.emit(exports.ECSEventType.COMPONENT_ADDED,e)},t.emitComponentRemoved=function(e){this.emit(exports.ECSEventType.COMPONENT_REMOVED,e)},t.emitSystemAdded=function(e){this.emit(exports.ECSEventType.SYSTEM_ADDED,e)},t.emitSystemRemoved=function(e){this.emit(exports.ECSEventType.SYSTEM_REMOVED,e)},t.emitSceneChanged=function(e){this.emit(exports.ECSEventType.SCENE_ACTIVATED,e)},t.emitPerformanceWarning=function(e){this.emit(exports.ECSEventType.PERFORMANCE_WARNING,e)},t.onEntityCreated=function(e,t){return this.on(exports.ECSEventType.ENTITY_CREATED,e,t)},t.onComponentAdded=function(e,t){return this.on(exports.ECSEventType.COMPONENT_ADDED,e,t)},t.onSystemError=function(e,t){return this.on(exports.ECSEventType.SYSTEM_ERROR,e,t)},t.onPerformanceWarning=function(e,t){return this.on(exports.ECSEventType.PERFORMANCE_WARNING,e,t)},t.validateEventType=function(t){this.isDebugMode&&(qe.isValid(t)||(e._logger.warn("未知事件类型: "+t),qe.addCustomType(t)))},t.enhanceEventData=function(e,t){if(null==t)return{timestamp:Date.now(),eventId:e+"_"+ ++this.eventIdCounter,source:"EventBus"};var n=t;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=e+"_"+ ++this.eventIdCounter),n.source||(n.source="EventBus"),n},t.convertEventStats=function(e){return{eventType:e.eventType,listenerCount:e.listenerCount,triggerCount:e.triggerCount,totalExecutionTime:e.totalExecutionTime,averageExecutionTime:e.averageExecutionTime,lastTriggerTime:e.lastTriggerTime}},e}();Ge._logger=Y("EventBus");var Qe=function(){function e(){}return e.getInstance=function(e){return void 0===e&&(e=!1),this.instance||(this.instance=new Ge(e)),this.instance},e.reset=function(e){return void 0===e&&(e=!1),this.instance&&this.instance.clear(),this.instance=new Ge(e),this.instance},e}(),Ve=function(){function e(e,t){this._entities=e,this._componentTypes=t}var t=e.prototype;return t.forEach=function(e){this._entities.forEach(e)},t.map=function(e){return this._entities.map(e)},t.filter=function(t){return new e(this._entities.filter(t),this._componentTypes)},t.find=function(e){return this._entities.find(e)},t.some=function(e){return this._entities.some(e)},t.every=function(e){return this._entities.every(e)},t.get=function(e){return this._entities[e]},t.toArray=function(){return[].concat(this._entities)},t.getComponentTypes=function(){return this._componentTypes},t[Symbol.iterator]=function(){return this._entities[Symbol.iterator]()},s(e,[{key:"entities",get:function(){return this._entities}},{key:"length",get:function(){return this._entities.length}},{key:"first",get:function(){return this._entities[0]}},{key:"last",get:function(){return this._entities[this._entities.length-1]}},{key:"isEmpty",get:function(){return 0===this._entities.length}}])}(),Ye=function(){function e(e,t,n,i,r){this._all=e||[],this._any=t||[],this._none=n||[],this._tag=i,this._name=r}var t=e.prototype;return t.withAll=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e([].concat(this._all,n),this._any,this._none,this._tag,this._name)},t.withAny=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e(this._all,[].concat(this._any,n),this._none,this._tag,this._name)},t.withNone=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return new e(this._all,this._any,[].concat(this._none,n),this._tag,this._name)},t.withTag=function(t){return new e(this._all,this._any,this._none,t,this._name)},t.withName=function(t){return new e(this._all,this._any,this._none,this._tag,t)},t.buildMatcher=function(){var e,t,n,i=Ae.complex();this._all.length>0&&(i=(e=i).all.apply(e,this._all));this._any.length>0&&(i=(t=i).any.apply(t,this._any));this._none.length>0&&(i=(n=i).none.apply(n,this._none));return void 0!==this._tag&&(i=i.withTag(this._tag)),void 0!==this._name&&(i=i.withName(this._name)),i},t.getCondition=function(){return{all:[].concat(this._all),any:[].concat(this._any),none:[].concat(this._none),tag:this._tag,name:this._name}},t.getRequiredTypes=function(){return this._all},t.clone=function(){return new e([].concat(this._all),[].concat(this._any),[].concat(this._none),this._tag,this._name)},e}();var Ke=Symbol("SerializableMetadata"),Je=Symbol("SerializeField"),$e=Symbol("SerializeOptions");function Ze(e){return function(t,n){var i=t.constructor,r=i[Ke];r||(r={options:{version:1},fields:new Map,ignoredFields:new Set},i[Ke]=r),r.fields.set(n,e||{})}}function Xe(e){return e&&("function"==typeof e?e:e.constructor)[Ke]||null}var et=function(){function e(){}return e.serialize=function(e){var t=Xe(e);if(!t)return null;for(var n,i=e.constructor,r=t.options.typeId||U(i),s={},a=o(t.fields);!(n=a()).done;){var c=n.value,u=c[0],h=c[1],l="symbol"==typeof u?u.toString():u,f=e[u];if(!t.ignoredFields.has(u)){var d=h.serializer?h.serializer(f):this.serializeValue(f);s[h.alias||l]=d}}return{type:r,version:t.options.version,data:s}},e.deserialize=function(e,t){var n=t.get(e.type);if(!n)return console.warn("未找到组件类型: "+e.type),null;var i=Xe(n);if(!i)return console.warn("组件 "+e.type+" 不可序列化"),null;for(var r,s=new n,a=o(i.fields);!(r=a()).done;){var c=r.value,u=c[0],h=c[1],l="symbol"==typeof u?u.toString():u,f=h.alias||l,d=e.data[f];if(void 0!==d){var p=h.deserializer?h.deserializer(d):this.deserializeValue(d);s[u]=p}}return s},e.serializeComponents=function(e){for(var t,n=[],i=o(e);!(t=i()).done;){var r=t.value,s=this.serialize(r);s&&n.push(s)}return n},e.deserializeComponents=function(e,t){for(var n,i=[],r=o(e);!(n=r()).done;){var s=n.value,a=this.deserialize(s,t);a&&i.push(a)}return i},e.serializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(Array.isArray(e))return e.map((function(e){return t.serializeValue(e)}));if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if("object"===n){var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=this.serializeValue(e[r]));return i}},e.deserializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if("object"===n&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((function(e){return t.deserializeValue(e)}));if("object"===n){var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=this.deserializeValue(e[r]));return i}return e},e.validateVersion=function(e,t){return e.version===t},e.getSerializationInfo=function(e){var t=Xe(e);if(!t)return{type:"unknown",version:0,fields:[],ignoredFields:[],isSerializable:!1};var n="function"==typeof e?e:e.constructor;return{type:t.options.typeId||U(n),version:t.options.version,fields:Array.from(t.fields.keys()).map((function(e){return"symbol"==typeof e?e.toString():e})),ignoredFields:Array.from(t.ignoredFields).map((function(e){return"symbol"==typeof e?e.toString():e})),isSerializable:!0}},e}(),tt=function(){function e(){}return e.serialize=function(e,t){void 0===t&&(t=!0);var n=et.serializeComponents(Array.from(e.components)),i={id:e.id,name:e.name,tag:e.tag,active:e.active,enabled:e.enabled,updateOrder:e.updateOrder,components:n,children:[]};if(e.parent&&(i.parentId=e.parent.id),t)for(var r,s=o(e.children);!(r=s()).done;){var a=r.value;i.children.push(this.serialize(a,!0))}return i},e.deserialize=function(e,t,n,i,r){void 0===i&&(i=!1);var s=i?e.id:n(),a=new Ce(e.name,s);r&&(a.scene=r),a.tag=e.tag,a.active=e.active,a.enabled=e.enabled,a.updateOrder=e.updateOrder;for(var c,u=o(et.deserializeComponents(e.components,t));!(c=u()).done;){var h=c.value;a.addComponent(h)}for(var l,f=o(e.children);!(l=f()).done;){var d=l.value,p=this.deserialize(d,t,n,i,r);a.addChild(p)}return a},e.serializeEntities=function(e,t){void 0===t&&(t=!0);for(var n,i=[],r=o(e);!(n=r()).done;){var s=n.value;s.parent&&t||i.push(this.serialize(s,t))}return i},e.deserializeEntities=function(e,t,n,i,r){void 0===i&&(i=!1);for(var s,a=[],c=o(e);!(s=c()).done;){var u=s.value,h=this.deserialize(u,t,n,i,r);a.push(h)}return a},e.clone=function(e,t,n){var i=this.serialize(e,!0);return this.deserialize(i,t,n,!1)},e}();const nt=new TextEncoder;function it(e,t,n){e.length>50?function(e,t,n){nt.encodeInto(e,t.subarray(n))}(e,t,n):function(e,t,n){const i=e.length;let r=n,s=0;for(;s<i;){let n=e.charCodeAt(s++);if(4294967168&n){if(4294965248&n){if(n>=55296&&n<=56319&&s<i){const t=e.charCodeAt(s);56320==(64512&t)&&(++s,n=((1023&n)<<10)+(1023&t)+65536)}4294901760&n?(t[r++]=n>>18&7|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128):(t[r++]=n>>12&15|224,t[r++]=n>>6&63|128)}else t[r++]=n>>6&31|192;t[r++]=63&n|128}else t[r++]=n}}(e,t,n)}function rt(e,t,n){let i=t;const r=i+n,s=[];let o="";for(;i<r;){const t=e[i++];if(128&t)if(192==(224&t)){const n=63&e[i++];s.push((31&t)<<6|n)}else if(224==(240&t)){const n=63&e[i++],r=63&e[i++];s.push((31&t)<<12|n<<6|r)}else if(240==(248&t)){let n=(7&t)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++];n>65535&&(n-=65536,s.push(n>>>10&1023|55296),n=56320|1023&n),s.push(n)}else s.push(t);else s.push(t);s.length>=4096&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const st=new TextDecoder;function ot(e,t,n){return n>200?function(e,t,n){const i=e.subarray(t,t+n);return st.decode(i)}(e,t,n):rt(e,t,n)}class at{constructor(e,t){this.type=e,this.data=t}}class ct extends Error{constructor(e){super(e);const t=Object.create(ct.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ct.name})}}const ut=4294967295;function ht(e,t,n){const i=Math.floor(n/4294967296),r=n;e.setUint32(t,i),e.setUint32(t+4,r)}function lt(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}const ft={type:-1,encode:function(e){if(e instanceof Date){return function({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=17179869183){if(0===t&&e<=4294967295){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}{const n=e/4294967296,i=4294967295&e,r=new Uint8Array(8),s=new DataView(r.buffer);return s.setUint32(0,t<<2|3&n),s.setUint32(4,i),r}}{const n=new Uint8Array(12),i=new DataView(n.buffer);return i.setUint32(0,t),ht(i,4,e),n}}(function(e){const t=e.getTime(),n=Math.floor(t/1e3),i=1e6*(t-1e3*n),r=Math.floor(i/1e9);return{sec:n+r,nsec:i-1e9*r}}(e))}return null},decode:function(e){const t=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const e=t.getUint32(0);return{sec:4294967296*(3&e)+t.getUint32(4),nsec:e>>>2}}case 12:return{sec:lt(t,4),nsec:t.getUint32(0)};default:throw new ct(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}};class dt{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ft)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{const i=-1-e;this.builtInEncoders[i]=t,this.builtInDecoders[i]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){const i=this.builtInEncoders[n];if(null!=i){const r=i(e,t);if(null!=r){return new at(-1-n,r)}}}for(let n=0;n<this.encoders.length;n++){const i=this.encoders[n];if(null!=i){const r=i(e,t);if(null!=r){return new at(n,r)}}}return e instanceof at?e:null}decode(e,t,n){const i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,n):new at(t,e)}}function pt(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):function(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}(e)?new Uint8Array(e):Uint8Array.from(e)}dt.defaultCodec=new dt;class yt{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??dt.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??100,this.initialBufferSize=e?.initialBufferSize??2048,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new yt({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered){return this.clone().encodeSharedRef(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered){return this.clone().encode(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.useBigInt64&&"bigint"==typeof e?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)}resizeBuffer(e){const t=new ArrayBuffer(e),n=new Uint8Array(t),i=new DataView(t);n.set(this.bytes),this.view=i,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(e){!1===e?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too long string: ${e} bytes in UTF-8`);this.writeU8(219),this.writeU32(e)}}encodeString(e){const t=function(e){const t=e.length;let n=0,i=0;for(;i<t;){let r=e.charCodeAt(i++);if(4294967168&r)if(4294965248&r){if(r>=55296&&r<=56319&&i<t){const t=e.charCodeAt(i);56320==(64512&t)&&(++i,r=((1023&r)<<10)+(1023&t)+65536)}n+=4294901760&r?4:3}else n+=2;else n++}return n}(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),it(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);this.encodeMap(e,t)}}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large binary: ${t}`);this.writeU8(198),this.writeU32(t)}const n=pt(e);this.writeU8a(n)}encodeArray(e,t){const n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error(`Too large array: ${n}`);this.writeU8(221),this.writeU32(n)}for(const n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let n=0;for(const i of t)void 0!==e[i]&&n++;return n}encodeMap(e,t){const n=Object.keys(e);this.sortKeys&&n.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else{if(!(i<4294967296))throw new Error(`Too large map object: ${i}`);this.writeU8(223),this.writeU32(i)}for(const i of n){const n=e[i];this.ignoreUndefined&&void 0===n||(this.encodeString(i),this.doEncode(n,t+1))}}encodeExtension(e){if("function"==typeof e.data){const t=e.data(this.pos+6),n=t.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);return this.writeU8(201),this.writeU32(n),this.writeI8(e.type),void this.writeU8a(t)}const t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),function(e,t,n){const i=n/4294967296,r=n;e.setUint32(t,i),e.setUint32(t+4,r)}(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ht(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function mt(e,t){return new yt(t).encodeSharedRef(e)}function gt(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const vt="array",_t="map_key",St="map_value",Ct=e=>{if("string"==typeof e||"number"==typeof e)return e;throw new ct("The type of key must be string or number but "+typeof e)};class wt{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=vt,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=_t,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===vt){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===_t||e.type===St){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Et=new DataView(new ArrayBuffer(0)),bt=new Uint8Array(Et.buffer);try{Et.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const At=new RangeError("Insufficient data"),Tt=new class{constructor(e=16,t=16){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){const i=this.caches[n-1];e:for(const r of i){const i=r.bytes;for(let r=0;r<n;r++)if(i[r]!==e[t+r])continue e;return r.str}return null}store(e,t){const n=this.caches[e.length-1],i={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)}decode(e,t,n){const i=this.find(e,t,n);if(null!=i)return this.hit++,i;this.miss++;const r=rt(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,r),r}};class Mt{constructor(e){this.totalPos=0,this.pos=0,this.view=Et,this.bytes=bt,this.headByte=-1,this.stack=new wt,this.entered=!1,this.extensionCodec=e?.extensionCodec??dt.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??ut,this.maxBinLength=e?.maxBinLength??ut,this.maxArrayLength=e?.maxArrayLength??ut,this.maxMapLength=e?.maxMapLength??ut,this.maxExtLength=e?.maxExtLength??ut,this.keyDecoder=void 0!==e?.keyDecoder?e.keyDecoder:Tt,this.mapKeyConverter=e?.mapKeyConverter??Ct}clone(){return new Mt({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){const t=pt(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(-1!==this.headByte||this.hasRemaining(1)){const t=this.bytes.subarray(this.pos),n=pt(e),i=new Uint8Array(t.length+n.length);i.set(t),i.set(n,t.length),this.setBuffer(i)}else this.setBuffer(e)}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered){return this.clone().decode(e)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){const t=this.clone();yield*t.decodeMulti(e)}else try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered){return this.clone().decodeAsync(e)}try{this.entered=!0;let t,n=!1;for await(const i of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(i);try{t=this.doDecodeSync(),n=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return t}const{headByte:i,pos:r,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${gt(i)} at ${s} (${r} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){const n=this.clone();yield*n.decodeMultiAsync(e,t)}else try{this.entered=!0;let n=t,i=-1;for await(const r of e){if(t&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(r),n&&(i=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),0!==--i;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const n=e-128;if(0!==n){this.pushMapState(n),this.complete();continue e}t={}}else if(e<160){const n=e-144;if(0!==n){this.pushArrayState(n),this.complete();continue e}t=[]}else{const n=e-160;t=this.decodeString(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===e){const e=this.lookU8();t=this.decodeString(e,1)}else if(218===e){const e=this.lookU16();t=this.decodeString(e,2)}else if(219===e){const e=this.lookU32();t=this.decodeString(e,4)}else if(220===e){const e=this.readU16();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(221===e){const e=this.readU32();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(222===e){const e=this.readU16();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(223===e){const e=this.readU32();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(196===e){const e=this.lookU8();t=this.decodeBinary(e,1)}else if(197===e){const e=this.lookU16();t=this.decodeBinary(e,2)}else if(198===e){const e=this.lookU32();t=this.decodeBinary(e,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){const e=this.lookU8();t=this.decodeExtension(e,1)}else if(200===e){const e=this.lookU16();t=this.decodeExtension(e,2)}else{if(201!==e)throw new ct(`Unrecognized type byte: ${gt(e)}`);{const e=this.lookU32();t=this.decodeExtension(e,4)}}this.complete();const n=this.stack;for(;n.length>0;){const e=n.top();if(e.type===vt){if(e.array[e.position]=t,e.position++,e.position!==e.size)continue e;t=e.array,n.release(e)}else{if(e.type===_t){if("__proto__"===t)throw new ct("The key __proto__ is not allowed");e.key=this.mapKeyConverter(t),e.type=St;continue e}if(e.map[e.key]=t,e.readCount++,e.readCount!==e.size){e.key=null,e.type=_t;continue e}t=e.map,n.release(e)}}return t}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new ct(`Unrecognized array type byte: ${gt(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new ct(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ct(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new ct(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw At;const n=this.pos+t;let i;return i=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,n,e):ot(this.bytes,n,e),this.pos+=t+e,i}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===_t}return!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new ct(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw At;const n=this.pos+t,i=this.bytes.subarray(n,n+e);return this.pos+=t+e,i}decodeExtension(e,t){if(e>this.maxExtLength)throw new ct(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=(t=this.view,n=this.pos,4294967296*t.getUint32(n)+t.getUint32(n+4));var t,n;return this.pos+=8,e}readI64(){const e=lt(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function xt(e,t){return new Mt(t).decode(e)}var It,kt=function(){function e(){}return e.serialize=function(e,t){var n=a({systems:!1,format:"json",pretty:!0,includeMetadata:!0},t),i=this.filterEntities(e,n),r=tt.serializeEntities(i,!0),s=this.buildComponentTypeRegistry(i),o=this.serializeSceneData(e.sceneData),c={name:e.name,version:this.SERIALIZATION_VERSION,entities:r,componentTypeRegistry:s};return o&&Object.keys(o).length>0&&(c.sceneData=o),n.includeMetadata&&(c.timestamp=Date.now(),c.metadata={entityCount:r.length,componentTypeCount:s.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(c,null,2):JSON.stringify(c):mt(c)},e.deserialize=function(e,t,n){var i,r=a({strategy:"replace",preserveIds:!1},n);try{i="string"==typeof t?JSON.parse(t):xt(t)}catch(e){throw new Error("Failed to parse save data: "+e)}r.migration&&i.version!==this.SERIALIZATION_VERSION&&(i=r.migration(i.version,this.SERIALIZATION_VERSION,i));var s=r.componentRegistry||this.getGlobalComponentRegistry();"replace"===r.strategy&&e.destroyAllEntities();for(var c,u=o(tt.deserializeEntities(i.entities,s,(function(){return e.identifierPool.checkOut()}),r.preserveIds||!1,e));!(c=u()).done;){var h=c.value;e.addEntity(h,!0),this.addChildrenRecursively(h,e)}e.querySystem.clearCache(),e.clearSystemEntityCaches(),i.sceneData&&this.deserializeSceneData(i.sceneData,e.sceneData)},e.addChildrenRecursively=function(e,t){for(var n,i=o(e.children);!(n=i()).done;){var r=n.value;t.addEntity(r,!0),this.addChildrenRecursively(r,t)}},e.serializeSceneData=function(e){for(var t,n={},i=o(e);!(t=i()).done;){var r=t.value,s=r[0],a=r[1];n[s]=this.serializeValue(a)}return n},e.deserializeSceneData=function(e,t){t.clear();for(var n=0,i=Object.entries(e);n<i.length;n++){var r=i[n],s=r[0],o=r[1];t.set(s,this.deserializeValue(o))}},e.serializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if(Array.isArray(e))return e.map((function(e){return t.serializeValue(e)}));if("object"===n){var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=this.serializeValue(e[r]));return i}},e.deserializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if("object"===n&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((function(e){return t.deserializeValue(e)}));if("object"===n){var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=this.deserializeValue(e[r]));return i}return e},e.filterEntities=function(e,t){var n=Array.from(e.entities.buffer);if(t.components&&t.components.length>0){var i=new Set(t.components);return n.filter((function(e){return Array.from(e.components).some((function(e){return i.has(e.constructor)}))}))}return n},e.buildComponentTypeRegistry=function(e){for(var t,n=new Map,i=o(e);!(t=i()).done;)for(var r,s=o(t.value.components);!(r=s()).done;){var a=r.value,c=U(a.constructor),u=Xe(a);u&&!n.has(c)&&n.set(c,u.options.version)}return Array.from(n.entries()).map((function(e){return{typeName:e[0],version:e[1]}}))},e.getGlobalComponentRegistry=function(){return ge.getAllComponentNames()},e.validate=function(e){var t=[];try{var n=JSON.parse(e);return n.version||t.push("Missing version field"),n.entities&&Array.isArray(n.entities)||t.push("Missing or invalid entities field"),n.componentTypeRegistry&&Array.isArray(n.componentTypeRegistry)||t.push("Missing or invalid componentTypeRegistry field"),{valid:0===t.length,version:n.version,errors:t.length>0?t:void 0}}catch(e){return{valid:!1,errors:["JSON parse error: "+e]}}},e.getInfo=function(e){try{var t,n=JSON.parse(e);return{name:n.name,version:n.version,timestamp:n.timestamp,entityCount:(null===(t=n.metadata)||void 0===t?void 0:t.entityCount)||n.entities.length,componentTypeCount:n.componentTypeRegistry.length}}catch(e){return null}},e}();kt.SERIALIZATION_VERSION=1,exports.ChangeOperation=void 0,(It=exports.ChangeOperation||(exports.ChangeOperation={})).EntityAdded="entity_added",It.EntityRemoved="entity_removed",It.EntityUpdated="entity_updated",It.ComponentAdded="component_added",It.ComponentRemoved="component_removed",It.ComponentUpdated="component_updated",It.SceneDataUpdated="scene_data_updated";var Dt=function(){function e(){}return e.createSnapshot=function(e,t){for(var n,i=a({deepComponentComparison:!0,trackSceneData:!0,compressSnapshot:!1},t),r={version:++this.snapshotVersion,entityIds:new Set,entities:new Map,components:new Map,sceneData:new Map},s=o(e.entities.buffer);!(n=s()).done;){var c,u=n.value;if(r.entityIds.add(u.id),r.entities.set(u.id,{name:u.name,tag:u.tag,active:u.active,enabled:u.enabled,updateOrder:u.updateOrder,parentId:null===(c=u.parent)||void 0===c?void 0:c.id}),i.deepComponentComparison){for(var h,l=new Map,f=o(u.components);!(h=f()).done;){var d=h.value,p=et.serialize(d);p&&l.set(p.type,JSON.stringify(p.data))}l.size>0&&r.components.set(u.id,l)}}if(i.trackSceneData)for(var y,m=o(e.sceneData);!(y=m()).done;){var g=y.value,v=g[0],_=g[1];r.sceneData.set(v,JSON.stringify(_))}return r},e.computeIncremental=function(e,t,n){for(var i,r=a({deepComponentComparison:!0,trackSceneData:!0},n),s={version:++this.snapshotVersion,timestamp:Date.now(),sceneName:e.name,baseVersion:t.version,entityChanges:[],componentChanges:[],sceneDataChanges:[]},c=new Set,u=o(e.entities.buffer);!(i=u()).done;){var h=i.value;if(c.add(h.id),t.entityIds.has(h.id)){var l,f,d=t.entities.get(h.id);if(d.name!==h.name||d.tag!==h.tag||d.active!==h.active||d.enabled!==h.enabled||d.updateOrder!==h.updateOrder||d.parentId!==(null===(l=h.parent)||void 0===l?void 0:l.id))s.entityChanges.push({operation:exports.ChangeOperation.EntityUpdated,entityId:h.id,entityData:{name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder,parentId:null===(f=h.parent)||void 0===f?void 0:f.id}});r.deepComponentComparison&&this.detectComponentChanges(h,t,s.componentChanges)}else{var p;s.entityChanges.push({operation:exports.ChangeOperation.EntityAdded,entityId:h.id,entityName:h.name,entityData:{id:h.id,name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder,parentId:null===(p=h.parent)||void 0===p?void 0:p.id,components:[],children:[]}});for(var y,m=o(h.components);!(y=m()).done;){var g=y.value,v=et.serialize(g);v&&s.componentChanges.push({operation:exports.ChangeOperation.ComponentAdded,entityId:h.id,componentType:v.type,componentData:v})}}}for(var _,S=o(t.entityIds);!(_=S()).done;){var C=_.value;c.has(C)||s.entityChanges.push({operation:exports.ChangeOperation.EntityRemoved,entityId:C})}return r.trackSceneData&&this.detectSceneDataChanges(e,t,s.sceneDataChanges),s},e.detectComponentChanges=function(e,t,n){for(var i,r=t.components.get(e.id),s=new Map,a=o(e.components);!(i=a()).done;){var c=i.value,u=et.serialize(c);u&&s.set(u.type,u)}for(var h,l=o(s);!(h=l()).done;){var f=h.value,d=f[0],p=f[1],y=JSON.stringify(p.data);r&&r.has(d)?r.get(d)!==y&&n.push({operation:exports.ChangeOperation.ComponentUpdated,entityId:e.id,componentType:d,componentData:p}):n.push({operation:exports.ChangeOperation.ComponentAdded,entityId:e.id,componentType:d,componentData:p})}if(r)for(var m,g=o(r.keys());!(m=g()).done;){var v=m.value;s.has(v)||n.push({operation:exports.ChangeOperation.ComponentRemoved,entityId:e.id,componentType:v})}},e.detectSceneDataChanges=function(e,t,n){for(var i,r=new Set,s=o(e.sceneData);!(i=s()).done;){var a=i.value,c=a[0],u=a[1];r.add(c);var h=JSON.stringify(u),l=t.sceneData.get(c);l&&l===h||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:c,value:u})}for(var f,d=o(t.sceneData.keys());!(f=d()).done;){var p=f.value;r.has(p)||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:p,value:void 0,deleted:!0})}},e.applyIncremental=function(e,t,n){for(var i,r=o(t.entityChanges);!(i=r()).done;){var s=i.value;switch(s.operation){case exports.ChangeOperation.EntityAdded:this.applyEntityAdded(e,s);break;case exports.ChangeOperation.EntityRemoved:this.applyEntityRemoved(e,s);break;case exports.ChangeOperation.EntityUpdated:this.applyEntityUpdated(e,s)}}for(var a,c=o(t.componentChanges);!(a=c()).done;){var u=a.value;switch(u.operation){case exports.ChangeOperation.ComponentAdded:this.applyComponentAdded(e,u,n);break;case exports.ChangeOperation.ComponentRemoved:this.applyComponentRemoved(e,u,n);break;case exports.ChangeOperation.ComponentUpdated:this.applyComponentUpdated(e,u,n)}}for(var h,l=o(t.sceneDataChanges);!(h=l()).done;){var f=h.value;f.deleted?e.sceneData.delete(f.key):e.sceneData.set(f.key,f.value)}},e.applyEntityAdded=function(e,t){var n,i;if(t.entityData){var r=new Ce(t.entityName||"Entity",t.entityId);r.tag=t.entityData.tag||0,r.active=null===(n=t.entityData.active)||void 0===n||n,r.enabled=null===(i=t.entityData.enabled)||void 0===i||i,r.updateOrder=t.entityData.updateOrder||0,e.addEntity(r)}},e.applyEntityRemoved=function(e,t){var n=e.entities.findEntityById(t.entityId);n&&n.destroy()},e.applyEntityUpdated=function(e,t){if(t.entityData){var n=e.entities.findEntityById(t.entityId);if(n)if(void 0!==t.entityData.name&&(n.name=t.entityData.name),void 0!==t.entityData.tag&&(n.tag=t.entityData.tag),void 0!==t.entityData.active&&(n.active=t.entityData.active),void 0!==t.entityData.enabled&&(n.enabled=t.entityData.enabled),void 0!==t.entityData.updateOrder&&(n.updateOrder=t.entityData.updateOrder),void 0!==t.entityData.parentId){var i=e.entities.findEntityById(t.entityData.parentId);i&&n.parent!==i&&(n.parent&&n.parent.removeChild(n),i.addChild(n))}else n.parent&&n.parent.removeChild(n)}},e.applyComponentAdded=function(e,t,n){if(t.componentData){var i=e.entities.findEntityById(t.entityId);if(i){var r=et.deserialize(t.componentData,n);r&&i.addComponent(r)}}},e.applyComponentRemoved=function(e,t,n){var i=e.entities.findEntityById(t.entityId);if(i){var r=n.get(t.componentType);r&&i.removeComponentByType(r)}},e.applyComponentUpdated=function(e,t,n){if(t.componentData){var i=e.entities.findEntityById(t.entityId);if(i){var r=n.get(t.componentType);if(r){i.removeComponentByType(r);var s=et.deserialize(t.componentData,n);s&&i.addComponent(s)}}}},e.serializeIncremental=function(e,t){var n=a({format:"json",pretty:!1},t);return"binary"===n.format?mt(e):n.pretty?JSON.stringify(e,null,2):JSON.stringify(e)},e.deserializeIncremental=function(e){return"string"==typeof e?JSON.parse(e):xt(e)},e.getIncrementalSize=function(e,t){void 0===t&&(t="json");var n=this.serializeIncremental(e,{format:t});return"string"==typeof n?"undefined"!=typeof Blob?new Blob([n]).size:"undefined"!=typeof Buffer?Buffer.byteLength(n,"utf8"):(new TextEncoder).encode(n).length:n.length},e.getIncrementalStats=function(e){return{totalChanges:e.entityChanges.length+e.componentChanges.length+e.sceneDataChanges.length,entityChanges:e.entityChanges.length,componentChanges:e.componentChanges.length,sceneDataChanges:e.sceneDataChanges.length,addedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityAdded})).length,removedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityRemoved})).length,updatedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityUpdated})).length,addedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentAdded})).length,removedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentRemoved})).length,updatedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentUpdated})).length}},e.resetVersion=function(){this.snapshotVersion=0},e}();Dt.snapshotVersion=0;var Rt,Ot=Y("ServiceContainer");exports.ServiceLifetime=void 0,(Rt=exports.ServiceLifetime||(exports.ServiceLifetime={})).Singleton="singleton",Rt.Transient="transient";var zt=function(){function e(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}var t=e.prototype;return t.registerSingleton=function(e,t){this._services.has(e)?Ot.warn("Service "+e.name+" is already registered"):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Singleton}),Ot.debug("Registered singleton service: "+e.name))},t.registerTransient=function(e,t){this._services.has(e)?Ot.warn("Service "+e.name+" is already registered"):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Transient}),Ot.debug("Registered transient service: "+e.name))},t.registerInstance=function(e,t){if(this._services.has(e))Ot.warn("Service "+e.name+" is already registered");else{if(this._services.set(e,{type:e,instance:t,lifetime:exports.ServiceLifetime.Singleton}),D(e)){var n,i=R(e),r=null!==(n=null==i?void 0:i.priority)&&void 0!==n?n:0;this._updatableServices.push({instance:t,priority:r}),this._updatableServices.sort((function(e,t){return e.priority-t.priority})),Ot.debug("Service "+e.name+" is updatable (priority: "+r+"), added to update list")}Ot.debug("Registered service instance: "+e.name)}},t.resolve=function(e){var t=this._services.get(e);if(!t)throw new Error("Service "+e.name+" is not registered");if(this._resolving.has(e)){var n=Array.from(this._resolving).map((function(e){return e.name})).join(" -> ");throw new Error("Circular dependency detected: "+n+" -> "+e.name)}if(t.lifetime===exports.ServiceLifetime.Singleton&&t.instance)return t.instance;this._resolving.add(e);try{var i;if(i=t.factory?t.factory(this):new t.type,t.lifetime===exports.ServiceLifetime.Singleton&&(t.instance=i,D(t.type))){var r,s=R(t.type),o=null!==(r=null==s?void 0:s.priority)&&void 0!==r?r:0;this._updatableServices.push({instance:i,priority:o}),this._updatableServices.sort((function(e,t){return e.priority-t.priority})),Ot.debug("Service "+e.name+" is updatable (priority: "+o+"), added to update list")}return i}finally{this._resolving.delete(e)}},t.tryResolve=function(e){try{return this.resolve(e)}catch(e){return null}},t.isRegistered=function(e){return this._services.has(e)},t.unregister=function(e){var t=this._services.get(e);if(!t)return!1;if(t.instance){var n=this._updatableServices.findIndex((function(e){return e.instance===t.instance}));-1!==n&&this._updatableServices.splice(n,1),t.instance.dispose()}return this._services.delete(e),Ot.debug("Unregistered service: "+e.name),!0},t.clear=function(){for(var e,t=o(this._services);!(e=t()).done;){var n=e.value[1];n.instance&&n.instance.dispose()}this._services.clear(),this._updatableServices=[],Ot.debug("Cleared all services")},t.getRegisteredServices=function(){return Array.from(this._services.keys())},t.updateAll=function(e){for(var t,n=o(this._updatableServices);!(t=n()).done;){t.value.instance.update(e)}},t.getUpdatableCount=function(){return this._updatableServices.length},t.getAll=function(){for(var e,t=[],n=o(this._services.values());!(e=n()).done;){var i=e.value;i.instance&&t.push(i.instance)}return t},e}(),Bt=function(){function e(e){var t=this;this.name="",this.sceneData=new Map,this._performanceMonitor=null,this._didSceneBegin=!1,this.entities=new Ee(this),this.identifierPool=new be,this.componentStorageManager=new _e,this.querySystem=new Ue,this.eventSystem=new He,this.referenceTracker=new X,this._services=new zt,this.logger=Y("Scene"),null!=e&&e.name&&(this.name=e.name),Ce.eventBus||(Ce.eventBus=new Ge(!1)),Ce.eventBus&&Ce.eventBus.onComponentAdded((function(e){t.eventSystem.emitSync("component:added",e)}))}var t=e.prototype;return t.getSystem=function(e){return this._services.tryResolve(e)},t.initialize=function(){},t.onStart=function(){},t.unload=function(){},t.begin=function(){this._didSceneBegin=!0,this.onStart()},t.end=function(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this._services.clear(),this.unload()},t.update=function(){ue.getInstance().update(),this.entities.updateLists();for(var e,t=this.systems,n=o(t);!(e=n()).done;){var i=e.value;if(i.enabled)try{i.update()}catch(e){this.logger.error("Error in system "+i.constructor.name+".update():",e)}}for(var r,s=o(t);!(r=s()).done;){var a=r.value;if(a.enabled)try{a.lateUpdate()}catch(e){this.logger.error("Error in system "+a.constructor.name+".lateUpdate():",e)}}},t.createEntity=function(e){var t=new Ce(e,this.identifierPool.checkOut());return this.eventSystem.emitSync("entity:created",{entityName:e,entity:t,scene:this}),this.addEntity(t)},t.clearSystemEntityCaches=function(){for(var e,t=o(this.systems);!(e=t()).done;){e.value.clearEntityCache()}},t.addEntity=function(e,t){return void 0===t&&(t=!1),this.entities.add(e),e.scene=this,this.querySystem.addEntity(e,t),t||this.clearSystemEntityCaches(),this.eventSystem.emitSync("entity:added",{entity:e,scene:this}),e},t.createEntities=function(e,t){void 0===t&&(t="Entity");for(var n=[],i=0;i<e;i++){var r=new Ce(t+"_"+i,this.identifierPool.checkOut());r.scene=this,n.push(r)}for(var s=0,o=n;s<o.length;s++){var a=o[s];this.entities.add(a)}return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:e}),n},t.destroyEntities=function(e){if(0!==e.length){for(var t,n=o(e);!(t=n()).done;){t.value._isDestroyed=!0}for(var i,r=o(e);!(i=r()).done;){i.value.removeAllComponents()}for(var s,a=o(e);!(s=a()).done;){var c=s.value;this.entities.remove(c),this.querySystem.removeEntity(c)}this.querySystem.clearCache(),this.clearSystemEntityCaches()}},t.destroyAllEntities=function(){this.entities.removeAllEntities(),this.querySystem.setEntities([])},t.findEntity=function(e){return this.entities.findEntity(e)},t.findEntityById=function(e){return this.entities.findEntityById(e)},t.findEntitiesByTag=function(e){for(var t,n=[],i=o(this.entities.buffer);!(t=i()).done;){var r=t.value;r.tag===e&&n.push(r)}return n},t.getEntityByName=function(e){return this.findEntity(e)},t.getEntitiesByTag=function(e){return this.findEntitiesByTag(e)},t.queryAll=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments)},t.queryAny=function(){var e;return(e=this.querySystem).queryAny.apply(e,arguments)},t.queryNone=function(){var e;return(e=this.querySystem).queryNone.apply(e,arguments)},t.query=function(){return new Ye},t.addEntityProcessor=function(e){var t,n;if("function"==typeof e){if(n=e,this._services.isRegistered(n)){var i=this._services.resolve(n);return this.logger.debug("System "+n.name+" already registered, returning existing instance"),i}t=x(n)?I(n,this._services):new n}else if(n=(t=e).constructor,this._services.isRegistered(n)){var r=this._services.resolve(n);return r===t?(this.logger.debug("System "+n.name+" instance already registered, returning it"),t):(this.logger.warn("Attempting to register a different instance of "+n.name+", but type is already registered. Returning existing instance."),r)}t.scene=this,t.setPerformanceMonitor(this.performanceMonitor);var s=W(n);return void 0!==(null==s?void 0:s.updateOrder)&&t.setUpdateOrder(s.updateOrder),void 0!==(null==s?void 0:s.enabled)&&(t.enabled=s.enabled),this._services.registerInstance(n,t),k(t,this._services),t.initialize(),this.logger.debug("System "+n.name+" registered and initialized"),t},t.registerSystems=function(e){for(var t,n=[],i=o(e);!(t=i()).done;){var r=t.value,s=this.addEntityProcessor(r);n.push(s)}return n},t.addSystem=function(e){return this.addEntityProcessor(e)},t.removeEntityProcessor=function(e){var t=e.constructor;this._services.unregister(t),e.reset()},t.removeSystem=function(e){this.removeEntityProcessor(e)},t.getEntityProcessor=function(e){return this._services.tryResolve(e)},t.getStats=function(){return{entityCount:this.entities.count,processorCount:this.systems.length,componentStorageStats:this.componentStorageManager.getAllStats()}},t.getDebugInfo=function(){var e=this.systems;return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:e.length,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((function(e){return{name:e.name,id:e.id,componentCount:e.components.length,componentTypes:e.components.map((function(e){return H(e)}))}})),processors:e.map((function(e){var t;return{name:j(e),updateOrder:e.updateOrder,entityCount:(null===(t=e._entities)||void 0===t?void 0:t.length)||0}})),componentStats:this.componentStorageManager.getAllStats()}},t.serialize=function(e){return kt.serialize(this,e)},t.deserialize=function(e,t){kt.deserialize(this,e,t)},t.createIncrementalSnapshot=function(e){this._incrementalBaseSnapshot=Dt.createSnapshot(this,e)},t.serializeIncremental=function(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return Dt.computeIncremental(this,this._incrementalBaseSnapshot,e)},t.applyIncremental=function(e,t){var n="string"==typeof e||e instanceof Uint8Array?Dt.deserializeIncremental(e):e,i=t||ge.getAllComponentNames();Dt.applyIncremental(this,n,i)},t.updateIncrementalSnapshot=function(e){this.createIncrementalSnapshot(e)},t.clearIncrementalSnapshot=function(){this._incrementalBaseSnapshot=void 0},t.hasIncrementalSnapshot=function(){return void 0!==this._incrementalBaseSnapshot},s(e,[{key:"systems",get:function(){for(var e,t=[],n=o(this._services.getAll());!(e=n()).done;){var i=e.value;i instanceof Te&&t.push(i)}return t.sort((function(e,t){return e.updateOrder-t.updateOrder})),t}},{key:"services",get:function(){return this._services}},{key:"performanceMonitor",get:function(){var e;this._performanceMonitor||(this._performanceMonitor=null!==(e=this._services.tryResolve(O))&&void 0!==e?e:new O);return this._performanceMonitor}}])}(),Pt=function(){function e(){this.scene=new Bt}var t=e.prototype;return t.named=function(e){return this.scene.name=e,this},t.withEntity=function(e){return this.scene.addEntity(e),this},t.withEntityBuilder=function(e){var t=e(new we(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(t),this},t.withEntities=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i];this.scene.addEntity(s)}return this},t.withSystem=function(e){return this.scene.addSystem(e),this},t.withSystems=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i];this.scene.addSystem(s)}return this},t.build=function(){return this.scene},e}(),Lt=function(){function e(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.component=i(e,n)}var t=e.prototype;return t.set=function(e,t){return this.component[e]=t,this},t.configure=function(e){return e(this.component),this},t.setIf=function(e,t,n){return e&&(this.component[t]=n),this},t.build=function(){return this.component},e}(),Nt=function(){function e(e){this.entities=e}var t=e.prototype;return t.addComponent=function(e){for(var t,n=o(this.entities);!(t=n()).done;){t.value.addComponent(e)}return this},t.removeComponent=function(e){for(var t,n=o(this.entities);!(t=n()).done;){t.value.removeComponentByType(e)}return this},t.setActive=function(e){for(var t,n=o(this.entities);!(t=n()).done;){t.value.active=e}return this},t.setTag=function(e){for(var t,n=o(this.entities);!(t=n()).done;){t.value.tag=e}return this},t.forEach=function(e){return this.entities.forEach(e),this},t.filter=function(t){return new e(this.entities.filter(t))},t.toArray=function(){return this.entities.slice()},t.count=function(){return this.entities.length},e}(),Wt=function(){function e(e,t,n){this.scene=e,this.querySystem=t,this.eventSystem=n}var t=e.prototype;return t.createEntity=function(){return new we(this.scene,this.scene.componentStorageManager)},t.createScene=function(){return new Pt},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return i(Lt,[e].concat(n))},t.query=function(){return new Fe(this.querySystem)},t.find=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments).entities},t.findFirst=function(){var e,t=(e=this.querySystem).queryAll.apply(e,arguments);return t.entities.length>0?t.entities[0]:null},t.findByName=function(e){return this.scene.findEntity(e)},t.findByTag=function(e){return this.scene.findEntitiesByTag(e)},t.emit=function(e,t){this.eventSystem.emitSync(e,t)},t.emitAsync=function(){var e=n(l().m((function e(t,n){return l().w((function(e){for(;;)switch(e.n){case 0:return e.n=1,this.eventSystem.emit(t,n);case 1:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),t.on=function(e,t){return this.eventSystem.on(e,t)},t.once=function(e,t){return this.eventSystem.once(e,t)},t.off=function(e,t){this.eventSystem.off(e,t)},t.batch=function(e){return new Nt(e)},t.getStats=function(){return{entityCount:this.scene.entities.count,systemCount:this.scene.systems.length,componentStats:this.scene.componentStorageManager.getAllStats(),queryStats:this.querySystem.getStats(),eventStats:this.eventSystem.getStats()}},e}();function Ut(e,t,n){return new Wt(e,t,n)}var Ft,Ht=Y("World"),jt=function(){function e(e){void 0===e&&(e={}),this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config=a({name:"World",debug:!1,maxScenes:10,autoCleanup:!0},e),this.name=this._config.name,this._createdAt=Date.now(),Ht.info("创建World: "+this.name)}var t=e.prototype;return t.createScene=function(e,t){if(this._scenes.has(e))throw new Error("Scene ID '"+e+"' 已存在于World '"+this.name+"' 中");if(this._scenes.size>=this._config.maxScenes)throw new Error("World '"+this.name+"' 已达到最大Scene数量限制: "+this._config.maxScenes);var n=t||new Bt;return"id"in n&&(n.id=e),"name"in n&&!n.name&&(n.name=e),this._scenes.set(e,n),n.initialize(),Ht.info("在World '"+this.name+"' 中创建Scene: "+e),n},t.removeScene=function(e){var t=this._scenes.get(e);return!!t&&(this._activeScenes.has(e)&&this.setSceneActive(e,!1),t.end(),this._scenes.delete(e),Ht.info("从World '"+this.name+"' 中移除Scene: "+e),!0)},t.getScene=function(e){return this._scenes.get(e)||null},t.getSceneIds=function(){return Array.from(this._scenes.keys())},t.getAllScenes=function(){return Array.from(this._scenes.values())},t.removeAllScenes=function(){for(var e=0,t=Array.from(this._scenes.keys());e<t.length;e++){var n=t[e];this.removeScene(n)}Ht.info("从World '"+this.name+"' 中移除所有Scene")},t.setSceneActive=function(e,t){var n=this._scenes.get(e);n?t?(this._activeScenes.add(e),n.begin&&n.begin(),Ht.debug("在World '"+this.name+"' 中激活Scene: "+e)):(this._activeScenes.delete(e),Ht.debug("在World '"+this.name+"' 中停用Scene: "+e)):Ht.warn("Scene '"+e+"' 不存在于World '"+this.name+"' 中")},t.isSceneActive=function(e){return this._activeScenes.has(e)},t.getActiveSceneCount=function(){return this._activeScenes.size},t.addGlobalSystem=function(e){return this._globalSystems.includes(e)||(this._globalSystems.push(e),e.initialize&&e.initialize(),Ht.debug("在World '"+this.name+"' 中添加全局System: "+e.name)),e},t.removeGlobalSystem=function(e){var t=this._globalSystems.indexOf(e);return-1!==t&&(this._globalSystems.splice(t,1),e.reset&&e.reset(),Ht.debug("从World '"+this.name+"' 中移除全局System: "+e.name),!0)},t.getGlobalSystem=function(e){for(var t,n=o(this._globalSystems);!(t=n()).done;){var i=t.value;if(i instanceof e)return i}return null},t.start=function(){if(!this._isActive){this._isActive=!0;for(var e,t=o(this._globalSystems);!(e=t()).done;){var n=e.value;n.initialize&&n.initialize()}Ht.info("启动World: "+this.name)}},t.stop=function(){if(this._isActive){for(var e,t=o(this._activeScenes);!(e=t()).done;){var n=e.value;this.setSceneActive(n,!1)}for(var i,r=o(this._globalSystems);!(i=r()).done;){var s=i.value;s.reset&&s.reset()}this._isActive=!1,Ht.info("停止World: "+this.name)}},t.updateGlobalSystems=function(){if(this._isActive)for(var e,t=o(this._globalSystems);!(e=t()).done;){var n=e.value;n.update&&n.update()}},t.updateScenes=function(){if(this._isActive){for(var e,t=o(this._activeScenes);!(e=t()).done;){var n=e.value,i=this._scenes.get(n);i&&i.update&&i.update()}this._config.autoCleanup&&this.shouldAutoCleanup()&&this.cleanup()}},t.destroy=function(){Ht.info("销毁World: "+this.name),this.stop();for(var e=0,t=Array.from(this._scenes.keys());e<t.length;e++){var n=t[e];this.removeScene(n)}for(var i,r=o(this._globalSystems);!(i=r()).done;){var s=i.value;s.destroy?s.destroy():s.reset&&s.reset()}this._globalSystems.length=0,this._scenes.clear(),this._activeScenes.clear()},t.getStatus=function(){var e=this;return{name:this.name,isActive:this._isActive,sceneCount:this._scenes.size,activeSceneCount:this._activeScenes.size,globalSystemCount:this._globalSystems.length,createdAt:this._createdAt,config:a({},this._config),scenes:Array.from(this._scenes.keys()).map((function(t){var n;return{id:t,isActive:e._activeScenes.has(t),name:(null===(n=e._scenes.get(t))||void 0===n?void 0:n.name)||t}}))}},t.getStats=function(){for(var e,t={totalEntities:0,totalSystems:this._globalSystems.length,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}},n=o(this._scenes.values());!(e=n()).done;){var i=e.value;i.entities&&(t.totalEntities+=i.entities.count),i.systems&&(t.totalSystems+=i.systems.length)}return t},t.shouldAutoCleanup=function(){for(var e,t=Date.now(),n=o(this._scenes);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];if(!this._activeScenes.has(r)&&s.entities&&0===s.entities.count&&t-this._createdAt>3e5)return!0}return!1},t.cleanup=function(){for(var e=Array.from(this._scenes.keys()),t=Date.now(),n=0,i=e;n<i.length;n++){var r=i[n],s=this._scenes.get(r);s&&!this._activeScenes.has(r)&&s.entities&&0===s.entities.count&&t-this._createdAt>3e5&&(this.removeScene(r),Ht.debug("自动清理空Scene: "+r+" from World "+this.name))}},s(e,[{key:"isActive",get:function(){return this._isActive}},{key:"sceneCount",get:function(){return this._scenes.size}},{key:"createdAt",get:function(){return this._createdAt}}])}(),qt=function(){function e(e){this._nextScene=null,this._ecsAPI=null,this._logger=Y("SceneManager"),this._performanceMonitor=null,this._defaultWorld=new jt({name:"__default__"}),this._defaultWorld.start(),this._performanceMonitor=e||null}var t=e.prototype;return t.setSceneChangedCallback=function(e){this._onSceneChangedCallback=e},t.setScene=function(t){return this._defaultWorld.removeAllScenes(),this._performanceMonitor&&t.services.registerInstance(O,this._performanceMonitor),this._defaultWorld.createScene(e.DEFAULT_SCENE_ID,t),this._defaultWorld.setSceneActive(e.DEFAULT_SCENE_ID,!0),t.querySystem&&t.eventSystem?this._ecsAPI=Ut(t,t.querySystem,t.eventSystem):this._ecsAPI=null,_.sceneChanged(),this._onSceneChangedCallback&&this._onSceneChangedCallback(),this._logger.info("Scene changed to: "+t.name),t},t.loadScene=function(e){this._nextScene=e,this._logger.info("Scheduled scene load: "+e.name)},t.update=function(){this._nextScene&&(this.setScene(this._nextScene),this._nextScene=null),this._defaultWorld.updateGlobalSystems(),this._defaultWorld.updateScenes()},t.destroy=function(){this._logger.info("SceneManager destroying"),this._defaultWorld.destroy(),this._nextScene=null,this._ecsAPI=null,this._logger.info("SceneManager destroyed")},t.dispose=function(){this.destroy()},s(e,[{key:"currentScene",get:function(){return this._defaultWorld.getScene(e.DEFAULT_SCENE_ID)}},{key:"api",get:function(){return this._ecsAPI}},{key:"hasScene",get:function(){return null!==this._defaultWorld.getScene(e.DEFAULT_SCENE_ID)}},{key:"hasPendingScene",get:function(){return null!==this._nextScene}}])}();qt.DEFAULT_SCENE_ID="__main__",exports.DebugConfigService=function(){function e(){this._config={enabled:!1,websocketUrl:"",debugFrameRate:30,autoReconnect:!0,channels:{entities:!0,systems:!0,performance:!0,components:!0,scenes:!0}}}var t=e.prototype;return t.setConfig=function(e){this._config=e},t.getConfig=function(){return this._config},t.isEnabled=function(){return this._config.enabled},t.dispose=function(){},e}(),exports.DebugConfigService=m([A(),v("design:paramtypes",[])],exports.DebugConfigService),exports.DebugManager=function(){function e(e,t,n){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.originalConsole={log:console.log.bind(console),debug:console.debug.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},this.config=n.getConfig(),this.sceneManager=e,this.performanceMonitor=t,this.entityCollector=new se,this.systemCollector=new oe,this.performanceCollector=new ae,this.componentCollector=new he,this.sceneCollector=new fe,this.webSocketManager=new de(this.config.websocketUrl,!1!==this.config.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));var i=this.config.debugFrameRate||30;this.sendInterval=1e3/i,this.interceptConsole(),this.start()}var t=e.prototype;return t.start=function(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())},t.stop=function(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())},t.interceptConsole=function(){var e=this;console.log=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("info",e.formatLogMessage(i)),(t=e.originalConsole).log.apply(t,i)},console.debug=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("debug",e.formatLogMessage(i)),(t=e.originalConsole).debug.apply(t,i)},console.info=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("info",e.formatLogMessage(i)),(t=e.originalConsole).info.apply(t,i)},console.warn=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("warn",e.formatLogMessage(i)),(t=e.originalConsole).warn.apply(t,i)},console.error=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];e.sendLog("error",e.formatLogMessage(i)),(t=e.originalConsole).error.apply(t,i)}},t.formatLogMessage=function(e){var t=this;return e.map((function(e){if("string"==typeof e)return e;if(e instanceof Error)return e.name+": "+e.message;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{return t.safeStringify(e,6)}catch(t){return Object.prototype.toString.call(e)}return String(e)})).join(" ")},t.safeStringify=function(e,t){void 0===t&&(t=6);var n=new WeakSet,i=function(e,r){if(null===e)return null;if(void 0!==e){if("object"!=typeof e)return e;if(r>=t)return"[Max Depth Reached]";if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e)){var s=e.map((function(e){return i(e,r+1)}));return n.delete(e),s}var o={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&(o[a]=i(e[a],r+1));return n.delete(e),o}};return JSON.stringify(i(e,0))},t.sendLog=function(e,t){if(this.webSocketManager.getConnectionStatus())try{this.webSocketManager.send({type:"log",data:{level:e,message:t,timestamp:(new Date).toISOString()}})}catch(e){}},t.updateConfig=function(e){this.config=e;var t=e.debugFrameRate||30;this.sendInterval=1e3/t,this.webSocketManager&&e.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new de(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())},t.update=function(e){if(this.isRunning&&this.config.enabled){this.frameCounter++;var t=Date.now();t-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=t)}},t.onSceneChanged=function(){this.isRunning&&this.config.enabled&&this.sendDebugData()},t.handleMessage=function(e){try{switch(e.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":e.config&&this.updateConfig(a({},this.config,e.config));break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(e);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(e);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(e);break;case"get_entity_details":this.handleGetEntityDetailsRequest(e);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(t){e.requestId&&this.webSocketManager.send({type:"error_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleExpandLazyObjectRequest=function(e){try{var t=e.entityId,n=e.componentIndex,i=e.propertyPath,r=e.requestId;if(void 0===t||void 0===n||!i)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,error:"缺少必要参数"});var s=this.sceneManager.currentScene,o=this.entityCollector.expandLazyObject(t,n,i,s);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,data:o})}catch(t){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetComponentPropertiesRequest=function(e){try{var t=e.entityId,n=e.componentIndex,i=e.requestId;if(void 0===t||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:i,error:"缺少必要参数"});var r=this.sceneManager.currentScene,s=this.entityCollector.getComponentProperties(t,n,r);this.webSocketManager.send({type:"get_component_properties_response",requestId:i,data:s})}catch(t){this.webSocketManager.send({type:"get_component_properties_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetRawEntityListRequest=function(e){try{var t=e.requestId,n=this.sceneManager.currentScene,i=this.entityCollector.getRawEntityList(n);this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t,data:i})}catch(t){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleGetEntityDetailsRequest=function(e){try{var t=e.entityId,n=e.requestId;if(void 0===t)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});var i=this.sceneManager.currentScene,r=this.entityCollector.getEntityDetails(t,i);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:r})}catch(t){this.webSocketManager.send({type:"get_entity_details_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleMemorySnapshotRequest=function(){try{var e=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:e})}catch(e){this.webSocketManager.send({type:"memory_snapshot_error",error:e instanceof Error?e.message:"内存快照捕获失败"})}},t.captureMemorySnapshot=function(){var e=Date.now(),t=this.collectBaseMemoryInfo(),n=this.sceneManager.currentScene,i=this.entityCollector.collectEntityDataWithMemory(n),r=null!=n&&n.entities?this.collectComponentMemoryStats(n.entities):{totalMemory:0,componentTypes:0,totalInstances:0,breakdown:[]},s=this.collectSystemMemoryStats(),o=this.collectPoolMemoryStats(),a=this.collectPerformanceStats(),c=i.entitiesPerArchetype.reduce((function(e,t){return e+t.memory}),0);return{timestamp:e,version:"2.0",summary:{totalEntities:i.totalEntities,totalMemoryUsage:t.usedMemory,totalMemoryLimit:t.totalMemory,memoryUtilization:t.usedMemory/t.totalMemory*100,gcCollections:t.gcCollections,entityMemory:c,componentMemory:r.totalMemory,systemMemory:s.totalMemory,poolMemory:o.totalMemory},baseMemory:t,entities:{totalMemory:c,entityCount:i.totalEntities,archetypes:i.entitiesPerArchetype,largestEntities:i.topEntitiesByComponents},components:r,systems:s,pools:o,performance:a}},t.collectBaseMemoryInfo=function(){var e={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null,detailedMemory:void 0};try{var t=performance;if(t.memory){var n=t.memory;e.totalMemory=n.jsHeapSizeLimit||536870912,e.usedMemory=n.usedJSHeapSize||0,e.freeMemory=e.totalMemory-e.usedMemory,e.heapInfo={totalJSHeapSize:n.totalJSHeapSize||0,usedJSHeapSize:n.usedJSHeapSize||0,jsHeapSizeLimit:n.jsHeapSizeLimit||0}}else e.totalMemory=536870912,e.freeMemory=536870912;t.measureUserAgentSpecificMemory&&t.measureUserAgentSpecificMemory().then((function(t){e.detailedMemory=t})).catch((function(){}))}catch(e){}return e},t.collectComponentMemoryStats=function(e){for(var t,n=new Map,i=0,r=new Map,s=o(e.buffer);!(t=s()).done;){var a=t.value;if(a&&!a.destroyed&&a.components)for(var c,u=o(a.components);!(c=u()).done;){var h=H(c.value);r.set(h,(r.get(h)||0)+1)}}for(var l,f=o(r.entries());!(l=f()).done;){var d=l.value,p=d[0],y=d[1],m=this.componentCollector.calculateDetailedComponentMemory(p),g=m*y;i+=g;for(var v,_=[],S=0,C=o(e.buffer);!(v=C()).done;){var w=v.value;if(w&&!w.destroyed&&w.components){for(var E,b=o(w.components);!(E=b()).done;){if(H(E.value)===p&&(_.push({entityId:w.id,entityName:w.name||"Entity_"+w.id,memory:m}),++S>=100))break}if(S>=100)break}}n.set(p,{count:y,totalMemory:g,instances:_.slice(0,10)})}var A=Array.from(n.entries()).map((function(e){var t=e[0],n=e[1];return{typeName:t,instanceCount:n.count,totalMemory:n.totalMemory,averageMemory:n.totalMemory/n.count,percentage:i>0?n.totalMemory/i*100:0,largestInstances:n.instances.sort((function(e,t){return t.memory-e.memory})).slice(0,3)}})).sort((function(e,t){return t.totalMemory-e.totalMemory}));return{totalMemory:i,componentTypes:n.size,totalInstances:Array.from(n.values()).reduce((function(e,t){return e+t.count}),0),breakdown:A}},t.collectSystemMemoryStats=function(){var e=this.sceneManager.currentScene,t=0,n=[];try{var i=null==e?void 0:e.systems;if(i)for(var r,s=new Map,a=o(i);!(r=a()).done;){var c=r.value,u=j(c),h=void 0;s.has(u)?h=s.get(u):(h=this.calculateQuickSystemSize(c),s.set(u,h)),t+=h,n.push({name:u,memory:h,enabled:!1!==c.enabled,updateOrder:c.updateOrder||0})}}catch(e){}return{totalMemory:t,systemCount:n.length,breakdown:n.sort((function(e,t){return t.memory-e.memory}))}},t.calculateQuickSystemSize=function(e){if(!e||"object"!=typeof e)return 64;var t=128;try{for(var n=Object.keys(e),i=0;i<Math.min(n.length,15);i++){var r=n[i];if("entities"!==r&&"scene"!==r&&"constructor"!==r){var s=e[r];t+=2*r.length,"string"==typeof s?t+=Math.min(2*s.length,100):"number"==typeof s?t+=8:"boolean"==typeof s?t+=4:Array.isArray(s)?t+=40+Math.min(8*s.length,200):"object"==typeof s&&null!==s&&(t+=64)}}}catch(e){return 128}return Math.max(t,64)},t.collectPoolMemoryStats=function(){var e=0,t=[];try{for(var n,i=o(ue.getInstance().getPoolStats().entries());!(n=i()).done;){var r=n.value,s=r[0],a=r[1],c=32*a.maxSize;e+=c,t.push({typeName:s,maxSize:a.maxSize,currentSize:a.currentSize||0,estimatedMemory:c,utilization:a.currentSize?a.currentSize/a.maxSize*100:0})}}catch(e){}try{for(var u=z.getAllPoolStats(),h=0,l=Object.entries(u);h<l.length;h++){var f=l[h],d=f[0],p=f[1];e+=p.estimatedMemoryUsage,t.push({typeName:"Pool_"+d,maxSize:p.maxSize,currentSize:p.size,estimatedMemory:p.estimatedMemoryUsage,utilization:p.size/p.maxSize*100,hitRate:100*p.hitRate})}}catch(e){}return{totalMemory:e,poolCount:t.length,breakdown:t.sort((function(e,t){return t.estimatedMemory-e.estimatedMemory}))}},t.collectPerformanceStats=function(){try{var e;if(!this.performanceMonitor)return{enabled:!1};var t=this.performanceMonitor.getAllSystemStats(),n=this.performanceMonitor.getPerformanceWarnings();return{enabled:null!==(e=this.performanceMonitor.enabled)&&void 0!==e&&e,systemCount:t.size,warnings:n.slice(0,10),topSystems:Array.from(t.entries()).map((function(e){var t=e[0],n=e[1];return{name:t,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort((function(e,t){return t.averageTime-e.averageTime})).slice(0,5)}}catch(e){return{enabled:!1,error:e instanceof Error?e.message:String(e)}}},t.getDebugData=function(){var e=Date.now(),t=this.sceneManager.currentScene,n={timestamp:e,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:(null==t?void 0:t.name)||"Unknown"};return this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(t)),this.config.channels.systems&&(n.systems=this.systemCollector.collectSystemData(this.performanceMonitor,t)),this.config.channels.performance&&(n.performance=this.performanceCollector.collectPerformanceData(this.performanceMonitor)),this.config.channels.components&&(n.components=this.componentCollector.collectComponentData(t)),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData(t)),n},t.connectWebSocket=function(){var e=n(l().m((function e(){return l().w((function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.webSocketManager.connect();case 1:e.n=3;break;case 2:e.p=2,e.v;case 3:return e.a(2)}}),e,this,[[0,2]])})));return function(){return e.apply(this,arguments)}}(),t.sendDebugData=function(){if(this.webSocketManager.getConnectionStatus())try{var e={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(e)}catch(e){}},t.dispose=function(){this.stop(),console.log=this.originalConsole.log,console.debug=this.originalConsole.debug,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error},e}(),exports.DebugManager=m([A(),T(),g(0,M(qt)),g(1,M(O)),g(2,M(exports.DebugConfigService)),v("design:paramtypes",[qt,O,exports.DebugConfigService])],exports.DebugManager),exports.PluginState=void 0,(Ft=exports.PluginState||(exports.PluginState={})).NotInstalled="not_installed",Ft.Installed="installed",Ft.Failed="failed";var Gt=Y("PluginManager"),Qt=function(){function e(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}var t=e.prototype;return t.initialize=function(e,t){this._core=e,this._services=t,Gt.info("PluginManager initialized")},t.install=function(){var e=n(l().m((function e(t){var n,i;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(this._core&&this._services){e.n=1;break}throw new Error("PluginManager not initialized. Call initialize() first.");case 1:if(!this._plugins.has(t.name)){e.n=2;break}return Gt.warn("Plugin "+t.name+" is already installed"),e.a(2);case 2:return t.dependencies&&t.dependencies.length>0&&this._checkDependencies(t),n={name:t.name,version:t.version,state:exports.PluginState.NotInstalled,installedAt:Date.now()},this._metadata.set(t.name,n),e.p=3,Gt.info("Installing plugin: "+t.name+" v"+t.version),e.n=4,t.install(this._core,this._services);case 4:this._plugins.set(t.name,t),n.state=exports.PluginState.Installed,Gt.info("Plugin "+t.name+" installed successfully"),e.n=6;break;case 5:throw e.p=5,i=e.v,n.state=exports.PluginState.Failed,n.error=i instanceof Error?i.message:String(i),Gt.error("Failed to install plugin "+t.name+":",i),i;case 6:return e.a(2)}}),e,this,[[3,5]])})));return function(t){return e.apply(this,arguments)}}(),t.uninstall=function(){var e=n(l().m((function e(t){var n,i;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(n=this._plugins.get(t)){e.n=1;break}throw new Error("Plugin "+t+" is not installed");case 1:return this._checkDependents(t),e.p=2,Gt.info("Uninstalling plugin: "+t),e.n=3,n.uninstall();case 3:this._plugins.delete(t),this._metadata.delete(t),Gt.info("Plugin "+t+" uninstalled successfully"),e.n=5;break;case 4:throw e.p=4,i=e.v,Gt.error("Failed to uninstall plugin "+t+":",i),i;case 5:return e.a(2)}}),e,this,[[2,4]])})));return function(t){return e.apply(this,arguments)}}(),t.getPlugin=function(e){return this._plugins.get(e)},t.getMetadata=function(e){return this._metadata.get(e)},t.getAllPlugins=function(){return Array.from(this._plugins.values())},t.getAllMetadata=function(){return Array.from(this._metadata.values())},t.isInstalled=function(e){return this._plugins.has(e)},t._checkDependencies=function(e){if(e.dependencies){for(var t,n=[],i=o(e.dependencies);!(t=i()).done;){var r=t.value;this._plugins.has(r)||n.push(r)}if(n.length>0)throw new Error("Plugin "+e.name+" has unmet dependencies: "+n.join(", "))}},t._checkDependents=function(e){for(var t,n=[],i=o(this._plugins.values());!(t=i()).done;){var r=t.value;r.dependencies&&r.dependencies.includes(e)&&n.push(r.name)}if(n.length>0)throw new Error("Cannot uninstall plugin "+e+": it is required by "+n.join(", "))},t.dispose=function(){for(var e,t=o(Array.from(this._plugins.values()).reverse());!(e=t()).done;){var n=e.value;try{Gt.info("Disposing plugin: "+n.name),n.uninstall()}catch(e){Gt.error("Error disposing plugin "+n.name+":",e)}}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,Gt.info("PluginManager disposed")},e}(),Vt=Y("WorldManager"),Yt=function(){function e(e){void 0===e&&(e={}),this._worlds=new Map,this._activeWorlds=new Set,this._cleanupTimer=null,this._isRunning=!1,this._config=a({maxWorlds:50,autoCleanup:!0,cleanupInterval:3e4,debug:!1},e),this._isRunning=!0,Vt.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupInterval:this._config.cleanupInterval}),this.startCleanupTimer()}var t=e.prototype;return t.createWorld=function(e,t){if(!e||"string"!=typeof e||""===e.trim())throw new Error("World ID不能为空");if(this._worlds.has(e))throw new Error("World ID '"+e+"' 已存在");if(this._worlds.size>=this._config.maxWorlds)throw new Error("已达到最大World数量限制: "+this._config.maxWorlds);var n=a({name:e,debug:this._config.debug},t),i=new jt(n);return this._worlds.set(e,i),Vt.info("创建World: "+e,{config:n}),i},t.removeWorld=function(e){var t=this._worlds.get(e);return!!t&&(this._activeWorlds.has(e)&&this.setWorldActive(e,!1),t.destroy(),this._worlds.delete(e),Vt.info("移除World: "+e),!0)},t.getWorld=function(e){return this._worlds.get(e)||null},t.getWorldIds=function(){return Array.from(this._worlds.keys())},t.getAllWorlds=function(){return Array.from(this._worlds.values())},t.setWorldActive=function(e,t){var n=this._worlds.get(e);n?t?(this._activeWorlds.add(e),n.start(),Vt.debug("激活World: "+e)):(this._activeWorlds.delete(e),n.stop(),Vt.debug("停用World: "+e)):Vt.warn("World '"+e+"' 不存在")},t.isWorldActive=function(e){return this._activeWorlds.has(e)},t.updateAll=function(){if(this._isRunning)for(var e,t=o(this._activeWorlds);!(e=t()).done;){var n=e.value,i=this._worlds.get(n);i&&i.isActive&&(i.updateGlobalSystems(),i.updateScenes())}},t.getActiveWorlds=function(){for(var e,t=[],n=o(this._activeWorlds);!(e=n()).done;){var i=e.value,r=this._worlds.get(i);r&&t.push(r)}return t},t.startAll=function(){this._isRunning=!0;for(var e,t=o(this._worlds.keys());!(e=t()).done;){var n=e.value;this.setWorldActive(n,!0)}Vt.info("启动所有World")},t.stopAll=function(){this._isRunning=!1;for(var e,t=o(this._activeWorlds);!(e=t()).done;){var n=e.value;this.setWorldActive(n,!1)}Vt.info("停止所有World")},t.findWorlds=function(e){for(var t,n=[],i=o(this._worlds.values());!(t=i()).done;){var r=t.value;e(r)&&n.push(r)}return n},t.findWorldByName=function(e){for(var t,n=o(this._worlds.values());!(t=n()).done;){var i=t.value;if(i.name===e)return i}return null},t.getStats=function(){for(var e,t={totalWorlds:this._worlds.size,activeWorlds:this._activeWorlds.size,totalScenes:0,totalEntities:0,totalSystems:0,memoryUsage:0,isRunning:this._isRunning,config:a({},this._config),worlds:[]},n=o(this._worlds);!(e=n()).done;){var i=e.value,r=i[0],s=i[1],c=s.getStats();t.totalScenes+=c.totalSystems,t.totalEntities+=c.totalEntities,t.totalSystems+=c.totalSystems,t.worlds.push(a({id:r,name:s.name,isActive:this._activeWorlds.has(r),sceneCount:s.sceneCount},c))}return t},t.getDetailedStatus=function(){var e=this;return a({},this.getStats(),{worlds:Array.from(this._worlds.entries()).map((function(t){var n=t[0],i=t[1];return{id:n,isActive:e._activeWorlds.has(n),status:i.getStatus()}}))})},t.cleanup=function(){for(var e,t=[],n=o(this._worlds);!(e=n()).done;){var i=e.value,r=i[0],s=i[1];this.shouldCleanupWorld(s)&&t.push(r)}for(var a=0,c=t;a<c.length;a++){var u=c[a];this.removeWorld(u)}return t.length>0&&Vt.debug("清理了 "+t.length+" 个World"),t.length},t.destroy=function(){Vt.info("正在销毁WorldManager..."),this.stopCleanupTimer(),this.stopAll();for(var e=0,t=Array.from(this._worlds.keys());e<t.length;e++){var n=t[e];this.removeWorld(n)}this._worlds.clear(),this._activeWorlds.clear(),this._isRunning=!1,Vt.info("WorldManager已销毁")},t.dispose=function(){this.destroy()},t.startCleanupTimer=function(){var e=this;this._config.autoCleanup&&!this._cleanupTimer&&(this._cleanupTimer=setInterval((function(){e.cleanup()}),this._config.cleanupInterval),Vt.debug("启动World清理定时器,间隔: "+this._config.cleanupInterval+"ms"))},t.stopCleanupTimer=function(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null,Vt.debug("停止World清理定时器"))},t.shouldCleanupWorld=function(e){return!e.isActive&&((0===e.sceneCount||!e.getAllScenes().some((function(e){return e.entities&&e.entities.count>0})))&&Date.now()-e.createdAt>6e5)},s(e,[{key:"worldCount",get:function(){return this._worlds.size}},{key:"activeWorldCount",get:function(){return this._activeWorlds.size}},{key:"isRunning",get:function(){return this._isRunning}},{key:"config",get:function(){return a({},this._config)}}])}(),Kt=function(){function e(t){var n,i,r,s=this;if(void 0===t&&(t={}),e._instance=this,this._config=a({debug:!0,enableEntitySystems:!0},t),this._serviceContainer=new zt,this._timerManager=new exports.TimerManager,this._serviceContainer.registerInstance(exports.TimerManager,this._timerManager),this._performanceMonitor=new O,this._serviceContainer.registerInstance(O,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new P,this._serviceContainer.registerInstance(P,this._poolManager),this._sceneManager=new qt(this._performanceMonitor),this._serviceContainer.registerInstance(qt,this._sceneManager),this._sceneManager.setSceneChangedCallback((function(){s._debugManager&&s._debugManager.onSceneChanged()})),this._worldManager=new Yt(this._config.worldManagerConfig),this._serviceContainer.registerInstance(Yt,this._worldManager),this._pluginManager=new Qt,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(Qt,this._pluginManager),e.entitySystemsEnabled=null===(n=this._config.enableEntitySystems)||void 0===n||n,this.debug=null===(i=this._config.debug)||void 0===i||i,null!==(r=this._config.debugConfig)&&void 0!==r&&r.enabled){var o=new exports.DebugConfigService;o.setConfig(this._config.debugConfig),this._serviceContainer.registerInstance(exports.DebugConfigService,o),this._serviceContainer.registerSingleton(exports.DebugManager,(function(e){return I(exports.DebugManager,e)})),this._debugManager=this._serviceContainer.resolve(exports.DebugManager)}this.initialize()}e.create=function(t){if(void 0===t&&(t=!0),null==this._instance){var n="boolean"==typeof t?{debug:t,enableEntitySystems:!0}:t;this._instance=new e(n)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance},e.setScene=function(t){if(!this._instance)throw e._logger.warn("Core实例未创建,请先调用Core.create()"),new Error("Core实例未创建");return this._instance._sceneManager.setScene(t)},e.loadScene=function(t){this._instance?this._instance._sceneManager.loadScene(t):e._logger.warn("Core实例未创建,请先调用Core.create()")},e.update=function(t){this._instance?this._instance.updateInternal(t):e._logger.warn("Core实例未创建,请先调用Core.create()")},e.schedule=function(e,t,n,i){if(void 0===t&&(t=!1),!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");if(!i)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(e,t,n,i)},e.enableDebug=function(t){if(this._instance){if(this._instance._debugManager)this._instance._debugManager.updateConfig(t);else{var n=new exports.DebugConfigService;n.setConfig(t),this._instance._serviceContainer.registerInstance(exports.DebugConfigService,n),this._instance._serviceContainer.registerSingleton(exports.DebugManager,(function(e){return I(exports.DebugManager,e)})),this._instance._debugManager=this._instance._serviceContainer.resolve(exports.DebugManager)}this._instance._config.debugConfig=t}else e._logger.warn("Core实例未创建,请先调用Core.create()")},e.disableDebug=function(){this._instance&&(this._instance._debugManager&&(this._instance._debugManager.stop(),this._instance._debugManager=void 0),this._instance._config.debugConfig&&(this._instance._config.debugConfig.enabled=!1))},e.getDebugData=function(){var e;return null!==(e=this._instance)&&void 0!==e&&e._debugManager?this._instance._debugManager.getDebugData():null},e.installPlugin=function(){var e=n(l().m((function e(t){return l().w((function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.install(t);case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.uninstallPlugin=function(){var e=n(l().m((function e(t){return l().w((function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.uninstall(t);case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.getPlugin=function(e){if(this._instance)return this._instance._pluginManager.getPlugin(e)},e.isPluginInstalled=function(e){return!!this._instance&&this._instance._pluginManager.isInstalled(e)};var t=e.prototype;return t.initialize=function(){var t;e._logger.info("Core initialized",{debug:this.debug,entitySystemsEnabled:e.entitySystemsEnabled,debugEnabled:(null===(t=this._config.debugConfig)||void 0===t?void 0:t.enabled)||!1})},t.updateInternal=function(t){if(!e.paused){var n=this._performanceMonitor.startMonitoring("Core.update");_.update(t),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(_.deltaTime);var i=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(t),this._performanceMonitor.endMonitoring("Services.update",i,this._serviceContainer.getUpdatableCount()),this._poolManager.update(),this._sceneManager.update(),this._worldManager.updateAll(),this._performanceMonitor.endMonitoring("Core.update",n)}},e.destroy=function(){this._instance&&(this._instance._debugManager&&this._instance._debugManager.stop(),this._instance._serviceContainer.clear(),e._logger.info("Core destroyed"),this._instance=null)},s(e,null,[{key:"Instance",get:function(){return this._instance}},{key:"services",get:function(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}},{key:"worldManager",get:function(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._worldManager}},{key:"scene",get:function(){return this._instance?this._instance._sceneManager.currentScene:null}},{key:"ecsAPI",get:function(){return this._instance?this._instance._sceneManager.api:null}},{key:"isDebugEnabled",get:function(){var e;return(null===(e=this._instance)||void 0===e||null===(e=e._config.debugConfig)||void 0===e?void 0:e.enabled)||!1}}])}();Kt.paused=!1,Kt._instance=null,Kt._logger=Y("Core");var Jt=Y("DebugPlugin");exports.DebugPlugin=function(){function e(e){var t,n;this.name="@esengine/debug-plugin",this.version="1.0.0",this.worldManager=null,this.updateTimer=null,this.autoStart=null!==(t=null==e?void 0:e.autoStart)&&void 0!==t&&t,this.updateInterval=null!==(n=null==e?void 0:e.updateInterval)&&void 0!==n?n:1e3}var t=e.prototype;return t.install=function(){var e=n(l().m((function e(t,n){return l().w((function(e){for(;;)switch(e.n){case 0:this.worldManager=n.resolve(Yt),Jt.info("ECS Debug Plugin installed"),this.autoStart&&this.start();case 1:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),t.uninstall=function(){var e=n(l().m((function e(){return l().w((function(e){for(;;)switch(e.n){case 0:this.stop(),this.worldManager=null,Jt.info("ECS Debug Plugin uninstalled");case 1:return e.a(2)}}),e,this)})));return function(){return e.apply(this,arguments)}}(),t.dispose=function(){this.stop(),this.worldManager=null},t.start=function(){var e=this;this.updateTimer?Jt.warn("Debug monitoring already started"):(Jt.info("Starting debug monitoring"),this.updateTimer=setInterval((function(){e.logStats()}),this.updateInterval))},t.stop=function(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null,Jt.info("Debug monitoring stopped"))},t.getStats=function(){if(!this.worldManager)throw new Error("Plugin not installed");for(var e,t=[],n=0,i=0,r=o(this.worldManager.getAllWorlds());!(e=r()).done;)for(var s,a=o(e.value.getAllScenes());!(s=a()).done;){var c=s.value,u=this.getSceneInfo(c);t.push(u),n+=u.entityCount,i+=u.systems.length}return{scenes:t,totalEntities:n,totalSystems:i,timestamp:Date.now()}},t.getSceneInfo=function(e){var t=this,n=e.entities.buffer,i=e.systems;return{name:e.name,entityCount:n.length,systems:i.map((function(e){return t.getSystemInfo(e)})),entities:n.map((function(e){return t.getEntityInfo(e)}))}},t.getSystemInfo=function(e){var t=e.getPerformanceStats();return{name:e.constructor.name,enabled:e.enabled,updateOrder:e.updateOrder,entityCount:e.entities.length,performance:t?{avgExecutionTime:t.averageTime,maxExecutionTime:t.maxTime,totalCalls:t.executionCount}:void 0}},t.getEntityInfo=function(e){var t=this,n=e.components;return{id:e.id,name:e.name,enabled:e.enabled,tag:e.tag,componentCount:n.length,components:n.map((function(e){return t.getComponentInfo(e)}))}},t.getComponentInfo=function(e){for(var t=e.constructor.name,n={},i=0,r=Object.keys(e);i<r.length;i++){var s=r[i];if(!s.startsWith("_")){var o=e[s];"function"!=typeof o&&(n[s]=o)}}return{type:t,data:n}},t.queryEntities=function(e){if(!this.worldManager)throw new Error("Plugin not installed");for(var t,n=[],i=o(this.worldManager.getAllWorlds());!(t=i()).done;)for(var r,s=o(t.value.getAllScenes());!(r=s()).done;){var a=r.value;if(!e.sceneId||a.name===e.sceneId)for(var c,u=o(a.entities.buffer);!(c=u()).done;){var h=c.value;if((void 0===e.tag||h.tag===e.tag)&&(!e.name||h.name.includes(e.name))){if(e.hasComponent)if(!h.components.some((function(t){return t.constructor.name===e.hasComponent})))continue;n.push(this.getEntityInfo(h))}}}return n},t.logStats=function(){var e=this.getStats();Jt.info("=== ECS Debug Stats ==="),Jt.info("Total Entities: "+e.totalEntities),Jt.info("Total Systems: "+e.totalSystems),Jt.info("Scenes: "+e.scenes.length);for(var t,n=o(e.scenes);!(t=n()).done;){var i=t.value;Jt.info("\n[Scene: "+i.name+"]"),Jt.info(" Entities: "+i.entityCount),Jt.info(" Systems: "+i.systems.length);for(var r,s=o(i.systems);!(r=s()).done;){var a=r.value,c=a.performance?" | Avg: "+a.performance.avgExecutionTime.toFixed(2)+"ms, Max: "+a.performance.maxExecutionTime.toFixed(2)+"ms":"";Jt.info(" - "+a.name+" ("+(a.enabled?"enabled":"disabled")+") | Entities: "+a.entityCount+c)}}Jt.info("========================\n")},t.exportJSON=function(){var e=this.getStats();return JSON.stringify(e,null,2)},e}(),exports.DebugPlugin=m([A(),v("design:paramtypes",[Object])],exports.DebugPlugin);var $t=function(e,t){this.func=e,this.context=t},Zt=function(){function e(){this._messageTable=new Map}var t=e.prototype;return t.addObserver=function(e,t,n){var i=this._messageTable.get(e);i||(i=[],this._messageTable.set(e,i)),this.hasObserver(e,t)||i.push(new $t(t,n))},t.removeObserver=function(e,t){var n=this._messageTable.get(e);if(n){var i=n.findIndex((function(e){return e.func==t}));-1!=i&&n.splice(i,1)}},t.emit=function(e){var t=this._messageTable.get(e);if(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(var s,a=o(t);!(s=a()).done;){var c,u=s.value;(c=u.func).call.apply(c,[u.context].concat(i))}}},t.hasObserver=function(e,t){var n=this._messageTable.get(e);return!!n&&n.some((function(e){return e.func===t}))},t.removeAllObservers=function(e){void 0!==e?this._messageTable.delete(e):this._messageTable.clear()},t.dispose=function(){this._messageTable.clear()},t.getEventTypeCount=function(){return this._messageTable.size},t.getObserverCount=function(e){var t=this._messageTable.get(e);return t?t.length:0},e}(),Xt=function(){function e(){this._enabled=!1}var t=e.prototype;return t.setEnabled=function(e){this._enabled!=e&&(this._enabled=e,this._enabled?this.onEnabled():this.onDisabled())},t.onEnabled=function(){},t.onDisabled=function(){},t.update=function(){},s(e,[{key:"enabled",get:function(){return this._enabled},set:function(e){this.setEnabled(e)}}])}(),en=function(){function e(){this.entityId=null,this.id=e._idGenerator++}var t=e.prototype;return t.onAddedToEntity=function(){},t.onRemovedFromEntity=function(){},e}();en._idGenerator=0;var tn=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){this.processSystem()},t}(Te),nn=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){},t}(Te),rn=function(e){function t(t,n){var i;return(i=e.call(this,n)||this).acc=0,i.intervalRemainder=0,i.interval=t,i}u(t,e);var n=t.prototype;return n.onCheckProcessing=function(){return this.acc+=_.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)},n.getIntervalDelta=function(){return this.interval+this.intervalRemainder},t}(Te),sn=function(){function e(){this.adapter=null,this.logger=Y("PlatformManager")}e.getInstance=function(){return e.instance||(e.instance=new e),e.instance};var t=e.prototype;return t.getAdapter=function(){if(!this.adapter)throw new Error("平台适配器未注册,请调用 registerAdapter() 注册适配器");return this.adapter},t.registerAdapter=function(e){this.adapter=e,this.logger.info("平台适配器已注册: "+e.name,{name:e.name,version:e.version,supportsWorker:e.isWorkerSupported(),supportsSharedArrayBuffer:e.isSharedArrayBufferSupported(),hardwareConcurrency:e.getHardwareConcurrency()})},t.hasAdapter=function(){return null!==this.adapter},t.getAdapterInfo=function(){return this.adapter?{name:this.adapter.name,version:this.adapter.version,config:this.adapter.getPlatformConfig()}:null},t.supportsFeature=function(e){if(!this.adapter)return!1;var t=this.adapter.getPlatformConfig();switch(e){case"worker":return this.adapter.isWorkerSupported();case"shared-array-buffer":return this.adapter.isSharedArrayBufferSupported();case"transferable-objects":return t.supportsTransferableObjects;case"module-worker":return t.supportsModuleWorker;default:return!1}},t.getBasicWorkerConfig=function(){if(!this.adapter)return{platformSupportsWorker:!1,platformSupportsSharedArrayBuffer:!1,platformMaxWorkerCount:1,platformLimitations:{}};var e=this.adapter.getPlatformConfig();return{platformSupportsWorker:this.adapter.isWorkerSupported(),platformSupportsSharedArrayBuffer:this.adapter.isSharedArrayBufferSupported(),platformMaxWorkerCount:e.maxWorkerCount,platformLimitations:e.limitations||{}}},t.getFullPlatformConfig=function(){var e=n(l().m((function e(){return l().w((function(e){for(;;)switch(e.n){case 0:if(this.adapter){e.n=1;break}throw new Error("平台适配器未注册");case 1:if("function"!=typeof this.adapter.getPlatformConfigAsync){e.n=3;break}return e.n=2,this.adapter.getPlatformConfigAsync();case 2:return e.a(2,e.v);case 3:return e.a(2,this.adapter.getPlatformConfig())}}),e,this)})));return function(){return e.apply(this,arguments)}}(),e}(),on=function(e){function t(t,n){var i,r,s,o,a,c;void 0===n&&(n={}),(c=e.call(this,t)||this).workerPool=null,c.isProcessing=!1,c.sharedBuffer=null,c.sharedFloatArray=null,c.hasLoggedSyncMode=!1,c.platformAdapter=sn.getInstance().getAdapter();var u=null!==(i=n.workerCount)&&void 0!==i?i:c.getMaxSystemWorkerCount(),h=c.getMaxSystemWorkerCount(),l=Math.min(u,h);return u>h&&c.logger.warn("请求 "+u+" 个Worker,但系统最多支持 "+h+" 个。实际使用 "+l+" 个Worker。"),c.config={enableWorker:null===(r=n.enableWorker)||void 0===r||r,workerCount:l,systemConfig:n.systemConfig,entitiesPerWorker:n.entitiesPerWorker,useSharedArrayBuffer:null!==(s=n.useSharedArrayBuffer)&&void 0!==s?s:c.isSharedArrayBufferSupported(),entityDataSize:null!==(o=n.entityDataSize)&&void 0!==o?o:c.getDefaultEntityDataSize(),maxEntities:null!==(a=n.maxEntities)&&void 0!==a?a:1e4},c.config.enableWorker&&c.isWorkerSupported()&&(c.config.useSharedArrayBuffer&&c.initializeSharedArrayBuffer(),c.initializeWorkerPool()),c}u(t,e);var i=t.prototype;return i.isWorkerSupported=function(){return this.platformAdapter.isWorkerSupported()},i.isSharedArrayBufferSupported=function(){return this.platformAdapter.isSharedArrayBufferSupported()},i.getMaxSystemWorkerCount=function(){return this.platformAdapter.getPlatformConfig().maxWorkerCount},i.initializeSharedArrayBuffer=function(){try{if(!this.isSharedArrayBufferSupported())return this.logger.warn(this.systemName+": 平台不支持SharedArrayBuffer,降级到单Worker模式以保证数据处理完整性"),this.config.useSharedArrayBuffer=!1,void(this.config.workerCount=1);var e=this.config.maxEntities*this.config.entityDataSize*4;this.sharedBuffer=this.platformAdapter.createSharedArrayBuffer(e),this.sharedBuffer&&(this.sharedFloatArray=new Float32Array(this.sharedBuffer)),this.logger.info(this.systemName+": SharedArrayBuffer初始化成功 ("+e+" 字节)")}catch(e){this.logger.warn(this.systemName+": SharedArrayBuffer初始化失败,降级到单Worker模式以保证数据处理完整性",e),this.config.useSharedArrayBuffer=!1,this.sharedBuffer=null,this.sharedFloatArray=null,this.config.workerCount=1}},i.initializeWorkerPool=function(){try{for(var e=this.createWorkerScript(),t=[],n=(this.platformAdapter.getPlatformConfig().workerScriptPrefix||"")+e,i=0;i<this.config.workerCount;i++)try{var r=this.platformAdapter.createWorker(n,{name:"WorkerEntitySystem-"+i});t.push(r)}catch(e){throw this.logger.error("创建Worker "+i+" 失败:",e),e}this.workerPool=new an(t,this.sharedBuffer)}catch(e){this.logger.error(this.systemName+": Worker池初始化失败",e),this.config.enableWorker=!1}},i.createWorkerScript=function(){var e,t=this.workerProcess.toString().match(/\{([\s\S]*)\}/);if(!t)throw new Error("无法解析workerProcess方法");var n=t[1],i=this.config.entityDataSize,r=(null===(e=this.getSharedArrayBufferProcessFunction)||void 0===e?void 0:e.call(this))||null,s="";if(r){var o=r.toString().match(/\{([\s\S]*)\}/);o&&(s=o[1])}return"\n // Worker脚本 - 支持SharedArrayBuffer\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = "+i+";\n\n self.onmessage = function(e) {\n const { type, id, entities, deltaTime, systemConfig, startIndex, endIndex, sharedBuffer } = e.data;\n\n\n try {\n // 处理SharedArrayBuffer初始化\n if (type === 'init' && sharedBuffer) {\n sharedFloatArray = new Float32Array(sharedBuffer);\n self.postMessage({ type: 'init', success: true });\n return;\n }\n\n // 处理SharedArrayBuffer数据\n if (type === 'shared' && sharedFloatArray) {\n processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig);\n self.postMessage({ id, result: null }); // SharedArrayBuffer不需要返回数据\n return;\n }\n\n // 传统处理方式\n if (entities) {\n // 定义处理函数\n function workerProcess(entities, deltaTime, systemConfig) {\n "+n+"\n }\n\n // 执行处理\n const result = workerProcess(entities, deltaTime, systemConfig);\n\n // 处理Promise返回值\n if (result && typeof result.then === 'function') {\n result.then(finalResult => {\n self.postMessage({ id, result: finalResult });\n }).catch(error => {\n self.postMessage({ id, error: error.message });\n });\n } else {\n self.postMessage({ id, result });\n }\n }\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n };\n\n // SharedArrayBuffer处理函数 - 由子类定义\n function processSharedArrayBuffer(startIndex, endIndex, deltaTime, systemConfig) {\n if (!sharedFloatArray) return;\n\n "+(s?"\n // 用户定义的处理函数\n const userProcessFunction = function(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig) {\n "+s+"\n };\n userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig);\n ":"")+"\n }\n "},i.process=function(e){var t=this;if(!this.isProcessing){this.isProcessing=!0;try{this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?this.processWithSharedArrayBuffer(e).finally((function(){t.isProcessing=!1})):(this.config.useSharedArrayBuffer&&this.logger.info(this.systemName+": 本帧降级到传统Worker模式"),this.processWithWorker(e).finally((function(){t.isProcessing=!1}))):(this.hasLoggedSyncMode||(this.logger.info(this.systemName+": Worker不可用,使用同步处理"),this.hasLoggedSyncMode=!0),this.processSynchronously(e),this.isProcessing=!1)}catch(e){throw this.isProcessing=!1,this.logger.error(this.systemName+": 处理失败",e),e}}},i.processWithSharedArrayBuffer=function(){var e=n(l().m((function e(t){var n;return l().w((function(e){for(;;)switch(e.n){case 0:if(this.sharedFloatArray){e.n=1;break}throw new Error("SharedArrayBuffer not initialized");case 1:return this.writeEntitiesToSharedBuffer(t),n=this.createSharedArrayBufferTasks(t.length),e.n=2,Promise.all(n);case 2:this.readResultsFromSharedBuffer(t);case 3:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),i.processWithWorker=function(){var e=n(l().m((function e(t){var n,i,r,s,a,c,u,h,f,d,p,y,m,g,v=this;return l().w((function(e){for(;;)switch(e.n){case 0:for(n=[],i=0;i<t.length;i++)n[i]=this.extractEntityData(t[i]);return r=this.createBatches(n),s=_.deltaTime,a=r.map((function(e){return v.workerPool.execute({entities:e,deltaTime:s,systemConfig:v.config.systemConfig})})),e.n=1,Promise.all(a);case 1:for(c=e.v,u=0,h=o(c);!(f=h()).done;)for(d=f.value,p=o(d);!(y=p()).done;)m=y.value,u<t.length&&(g=t[u])&&m&&this.applyResult(g,m),u++;case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),i.processSynchronously=function(e){var t=this,n=e.map((function(e){return t.extractEntityData(e)})),i=_.deltaTime,r=this.workerProcess(n,i,this.config.systemConfig);r&&"function"==typeof r.then?r.then((function(n){e.forEach((function(e,i){t.applyResult(e,n[i])}))})):e.forEach((function(e,n){t.applyResult(e,r[n])}))},i.createBatches=function(e){var t=this.config.workerCount,n=[];if(this.config.entitiesPerWorker){for(var i=this.config.entitiesPerWorker,r=0;r<e.length;r+=i){var s=Math.min(r+i,e.length);n.push(e.slice(r,s))}n.length>t&&this.logger.warn(this.systemName+": 创建了 "+n.length+" 个批次,但只有 "+t+" 个Worker。某些Worker将依次处理多个批次。")}else for(var o=Math.ceil(e.length/t),a=0;a<t;a++){var c=a*o,u=Math.min(c+o,e.length);c<e.length&&n.push(e.slice(c,u))}return n},i.writeEntitiesToSharedBuffer=function(e){if(this.sharedFloatArray)for(var t=0;t<e.length&&t<this.config.maxEntities;t++){var n=e[t],i=this.extractEntityData(n),r=t*this.config.entityDataSize;this.writeEntityToBuffer(i,r)}},i.createSharedArrayBufferTasks=function(e){var t=[];if(this.config.entitiesPerWorker){var n=this.config.entitiesPerWorker,i=Math.ceil(e/n),r=this.config.workerCount;i>r&&this.logger.warn(this.systemName+": 需要 "+i+" 个任务处理 "+e+" 个实体(每任务 "+n+" 个),但只有 "+r+" 个Worker。某些Worker将依次处理多个任务。");for(var s=0;s<e;s+=n){var o=s,a=Math.min(s+n,e),c=this.workerPool.executeSharedBuffer({startIndex:o,endIndex:a,deltaTime:_.deltaTime,systemConfig:this.config.systemConfig});t.push(c)}}else for(var u=Math.ceil(e/this.config.workerCount),h=0;h<this.config.workerCount;h++){var l=h*u,f=Math.min(l+u,e);if(l<e){var d=this.workerPool.executeSharedBuffer({startIndex:l,endIndex:f,deltaTime:_.deltaTime,systemConfig:this.config.systemConfig});t.push(d)}}return t},i.readResultsFromSharedBuffer=function(e){if(this.sharedFloatArray)for(var t=0;t<e.length&&t<this.config.maxEntities;t++){var n=e[t],i=t*this.config.entityDataSize,r=this.readEntityFromBuffer(i);r&&this.applyResult(n,r)}},i.updateConfig=function(e){var t=a({},this.config);if(void 0!==e.workerCount){var n=this.getMaxSystemWorkerCount(),i=Math.min(e.workerCount,n);e.workerCount>n&&this.logger.warn("请求 "+e.workerCount+" 个Worker,但系统最多支持 "+n+" 个。实际使用 "+i+" 个Worker。"),e.workerCount=i}Object.assign(this.config,e),t.useSharedArrayBuffer===this.config.useSharedArrayBuffer?t.workerCount===this.config.workerCount?(!this.config.enableWorker&&this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&!this.workerPool&&this.isWorkerSupported()&&this.initializeWorkerPool()):this.reinitializeWorkerPool():this.reinitializeWorkerSystem()},i.reinitializeWorkerSystem=function(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.sharedBuffer=null,this.sharedFloatArray=null,this.config.useSharedArrayBuffer||(this.config.workerCount=1),this.config.enableWorker&&this.isWorkerSupported()&&(this.config.useSharedArrayBuffer&&this.initializeSharedArrayBuffer(),this.initializeWorkerPool())},i.reinitializeWorkerPool=function(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()},i.getWorkerInfo=function(){var e="sync";return this.config.enableWorker&&this.workerPool&&(e=this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?"shared-buffer":"worker"),{enabled:this.config.enableWorker,workerCount:this.config.workerCount,entitiesPerWorker:this.config.entitiesPerWorker,maxSystemWorkerCount:this.getMaxSystemWorkerCount(),isProcessing:this.isProcessing,sharedArrayBufferSupported:this.isSharedArrayBufferSupported(),sharedArrayBufferEnabled:this.config.useSharedArrayBuffer,currentMode:e}},i.onDestroy=function(){e.prototype.onDestroy.call(this),this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)},i.getLoggerName=function(){return"WorkerEntitySystem"},t}(Te),an=function(){function e(e,t){var n=this;void 0===t&&(t=null),this.workers=[],this.taskQueue=[],this.busyWorkers=new Set,this.taskCounter=0,this.sharedBuffer=null,this.logger=Y("PlatformWorkerPool"),this.sharedBuffer=t,this.workers=e;for(var i=function(i){var r=e[i];r.onMessage((function(e){return n.handleWorkerMessage(i,e.data)})),r.onError((function(e){return n.handleWorkerError(i,e)})),t&&r.postMessage({type:"init",sharedBuffer:t})},r=0;r<e.length;r++)i(r)}var t=e.prototype;return t.executeSharedBuffer=function(e){var t=this;return new Promise((function(n,i){var r={id:"shared-task-"+ ++t.taskCounter,data:a({},e,{type:"shared"}),resolve:function(){return n()},reject:i};t.taskQueue.push(r),t.processQueue()}))},t.execute=function(e){var t=this;return new Promise((function(n,i){var r={id:"task-"+ ++t.taskCounter,data:e,resolve:function(e){n(e)},reject:i};t.taskQueue.push(r),t.processQueue()}))},t.processQueue=function(){if(0!==this.taskQueue.length)for(var e=0;e<this.workers.length;e++)if(!this.busyWorkers.has(e)&&this.taskQueue.length>0){var t=this.taskQueue.shift();this.busyWorkers.add(e),this.workers[e].postMessage(a({id:t.id},t.data)),this.workers[e]._currentTask=t}},t.handleWorkerMessage=function(e,t){var n=this.workers[e],i=n._currentTask;i&&(this.busyWorkers.delete(e),n._currentTask=null,t.error?i.reject(new Error(t.error)):i.resolve(t.result),this.processQueue())},t.handleWorkerError=function(e,t){var n=this.workers[e],i=n._currentTask;i&&(this.busyWorkers.delete(e),n._currentTask=null,i.reject(new Error(t.message))),this.processQueue()},t.destroy=function(){for(var e,t=o(this.workers);!(e=t()).done;){e.value.terminate()}this.workers.length=0,this.taskQueue.length=0,this.busyWorkers.clear()},e}(),cn=function(){function e(){}return e.registerComponentMigration=function(e,t,n,i){this.componentMigrations.has(e)||this.componentMigrations.set(e,new Map),this.componentMigrations.get(e).set(t,i)},e.registerSceneMigration=function(e,t,n){this.sceneMigrations.set(e,n)},e.migrateComponent=function(e,t){var n=e.version;if(n===t)return e;var i=this.componentMigrations.get(e.type);if(!i)return console.warn("No migration path found for component "+e.type),e;for(var r=a({},e),s=n;s<t;){var o=i.get(s);if(!o){console.warn("Missing migration from version "+s+" to "+(s+1)+" for "+e.type);break}r.data=o(r.data,s,s+1),s++}return r.version=s,r},e.migrateScene=function(e,t){var n=e.version;if(n===t)return e;for(var i=a({},e),r=n;r<t;){var s=this.sceneMigrations.get(r);if(!s){console.warn("Missing scene migration from version "+r+" to "+(r+1));break}i=s(i,r,r+1),r++}return i.version=r,i=this.migrateSceneComponents(i)},e.migrateSceneComponents=function(e){var t=this,n=a({},e);return n.entities=e.entities.map((function(n){return a({},n,{components:n.components.map((function(n){var i=e.componentTypeRegistry.find((function(e){return e.typeName===n.type}));return i&&i.version!==n.version?t.migrateComponent(n,i.version):n})),children:t.migrateEntitiesComponents(n.children,e.componentTypeRegistry)})})),n},e.migrateEntitiesComponents=function(e,t){var n=this;return e.map((function(e){return a({},e,{components:e.components.map((function(e){var i=t.find((function(t){return t.typeName===e.type}));return i&&i.version!==e.version?n.migrateComponent(e,i.version):e})),children:n.migrateEntitiesComponents(e.children,t)})}))},e.clearMigrations=function(){this.componentMigrations.clear(),this.sceneMigrations.clear()},e.getComponentMigrationPath=function(e){var t=this.componentMigrations.get(e);return t?Array.from(t.keys()).sort((function(e,t){return e-t})):[]},e.getSceneMigrationPath=function(){return Array.from(this.sceneMigrations.keys()).sort((function(e,t){return e-t}))},e.canMigrateComponent=function(e,t,n){if(t===n)return!0;var i=this.componentMigrations.get(e);if(!i)return!1;for(var r=t;r<n;r++)if(!i.has(r))return!1;return!0},e.canMigrateScene=function(e,t){if(e===t)return!0;for(var n=e;n<t;n++)if(!this.sceneMigrations.has(n))return!1;return!0},e}();cn.componentMigrations=new Map,cn.sceneMigrations=new Map;var un=function(){function e(){this.fromVersion=1,this.toVersion=2}var t=e.prototype;return t.forComponent=function(e){return this.componentType=e,this},t.fromVersionToVersion=function(e,t){return this.fromVersion=e,this.toVersion=t,this},t.migrate=function(e){this.componentType?cn.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):cn.registerSceneMigration(this.fromVersion,this.toVersion,e)},e}();var hn=function(){function e(e){this._entity=e}var t=e.prototype;return t.with=function(e){return this._entity.addComponent(e),this},t.withConfigured=function(e,t){return this._entity.addComponent(e),t(e),this},t.withTag=function(e){return this._entity.tag=e,this},t.withName=function(e){return this._entity.name=e,this},t.withActive=function(e){return this._entity.active=e,this},t.withEnabled=function(e){return this._entity.enabled=e,this},t.withUpdateOrder=function(e){return this._entity.updateOrder=e,this},t.withChild=function(e){return this._entity.addChild(e),this},t.build=function(){return this._entity},s(e,[{key:"entity",get:function(){return this._entity}}])}();var ln=function(){function e(){}return e.getType=function(e){return e.constructor},e}(),fn=function(){function e(){}return e.toNumber=function(e){return null==e?0:Number(e)},e}();function dn(e){return"function"==typeof e&&e.prototype instanceof en}var pn=function(){function e(){}return e.detect=function(){var e,t=[],n="unknown",i=!1;return"undefined"!=typeof globalThis&&t.push("globalThis"),"undefined"!=typeof window&&t.push("window"),"undefined"!=typeof self&&t.push("self"),this.isNodeJS()?(n="nodejs",i=!0,e="NodeAdapter",t.push("nodejs","process","require")):this.isWeChatMiniGame()?(n="wechat-minigame",i=!0,e="WeChatMiniGameAdapter",t.push("wx","wechat-minigame")):this.isByteDanceMiniGame()?(n="bytedance-minigame",i=!0,e="ByteDanceMiniGameAdapter",t.push("tt","bytedance-minigame")):this.isAlipayMiniGame()?(n="alipay-minigame",i=!0,e="AlipayMiniGameAdapter",t.push("my","alipay-minigame")):this.isBaiduMiniGame()?(n="baidu-minigame",i=!0,e="BaiduMiniGameAdapter",t.push("swan","baidu-minigame")):this.isBrowser()&&(n="browser",i=!0,e="BrowserAdapter",t.push("browser")),"undefined"!=typeof Worker&&t.push("Worker"),"undefined"!=typeof SharedArrayBuffer&&t.push("SharedArrayBuffer"),"undefined"!=typeof navigator&&navigator.hardwareConcurrency&&t.push("hardwareConcurrency"),"undefined"!=typeof performance&&"function"==typeof performance.now&&t.push("performance.now"),"undefined"!=typeof Blob&&t.push("Blob"),"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL&&t.push("URL.createObjectURL"),{platform:n,confident:i,features:t,adapterClass:e}},e.isWeChatMiniGame=function(){if(void 0!==globalThis.wx){var e=globalThis.wx;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1},e.isByteDanceMiniGame=function(){if(void 0!==globalThis.tt){var e=globalThis.tt;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1},e.isNodeJS=function(){try{return!("undefined"==typeof process||!process.versions||!process.versions.node||"undefined"==typeof require||"undefined"==typeof module||"undefined"==typeof exports||"undefined"!=typeof window||"undefined"!=typeof document)}catch(e){return!1}},e.isAlipayMiniGame=function(){if(void 0!==globalThis.my){var e=globalThis.my;return!(!e.getSystemInfo||!e.createCanvas)}return!1},e.isBaiduMiniGame=function(){if(void 0!==globalThis.swan){var e=globalThis.swan;return!(!e.getSystemInfo||!e.createCanvas)}return!1},e.isBrowser=function(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location},e.getDetailedInfo=function(){var e={};return e.userAgent="undefined"!=typeof navigator?navigator.userAgent:"unknown",e.platform="undefined"!=typeof navigator?navigator.platform:"unknown",e.globalObjects={window:"undefined"!=typeof window,document:"undefined"!=typeof document,navigator:"undefined"!=typeof navigator,wx:void 0!==globalThis.wx,tt:void 0!==globalThis.tt,my:void 0!==globalThis.my,swan:void 0!==globalThis.swan},e.workerSupport={Worker:"undefined"!=typeof Worker,SharedWorker:"undefined"!=typeof SharedWorker,ServiceWorker:"undefined"!=typeof navigator&&"serviceWorker"in navigator,SharedArrayBuffer:"undefined"!=typeof SharedArrayBuffer,crossOriginIsolated:"undefined"!=typeof self&&self.crossOriginIsolated},e.performance={performanceNow:"undefined"!=typeof performance&&"function"==typeof performance.now,hardwareConcurrency:"undefined"!=typeof navigator?navigator.hardwareConcurrency:void 0},e.apiSupport={Blob:"undefined"!=typeof Blob,URL:"undefined"!=typeof URL,createObjectURL:"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL,ArrayBuffer:"undefined"!=typeof ArrayBuffer,TypedArrays:"undefined"!=typeof Float32Array},e},e}();exports.AutoTyped=function(e){return function(t,n){var i=String(n);t.constructor.__autoTypedFields||(t.constructor.__autoTypedFields=new Map),t.constructor.__autoTypedFields.set(i,e||{})}},exports.BitMask64Utils=pe,exports.Bits=xe,exports.COMPONENT_TYPE_NAME=L,exports.Colors=q,exports.Component=en,exports.ComponentDataCollector=he,exports.ComponentPool=ce,exports.ComponentPoolManager=ue,exports.ComponentRegistry=ge,exports.ComponentSerializer=et,exports.ComponentSparseSet=De,exports.ComponentStorage=ve,exports.ConsoleLogger=G,exports.Core=Kt,exports.DeepCopy=function(e,t){var n=String(t);e.constructor.__deepCopyFields||(e.constructor.__deepCopyFields=new Set),e.constructor.__deepCopyFields.add(n)},exports.ECSComponent=function(e){return function(t){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return t[L]=e,t}},exports.ECSFluentAPI=Wt,exports.ECSSystem=function(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return n[N]=e,t&&(n.__systemMetadata__=t),n}},exports.ENTITY_REF_METADATA=te,exports.EVENT_TYPES=je,exports.Emitter=Zt,exports.EnableSoA=function(e){return e.__enableSoA=!0,e},exports.Entity=Ce,exports.EntityDataCollector=se,exports.EntityList=Ee,exports.EntityProcessorList=Me,exports.EntityRef=function(){return function(e,t){var n=e.constructor,i=n[te];i||(i={properties:new Set},n[te]=i);var r="symbol"==typeof t?t.toString():t;i.properties.add(r),Object.defineProperty(e,t,{get:function(){return ie(this).get(r)||null},set:function(e){var t=ie(this),n=t.get(r)||null;if(n!==e){var i=null!==this.entityId?Z(this.entityId):null;if(i&&i.referenceTracker){var s=i.referenceTracker;if(n&&s.unregisterReference(n,this,r),e){var o;if(e.scene!==i)return void ee.error("Cannot reference Entity from different Scene. Entity: "+e.name+", Scene: "+((null===(o=e.scene)||void 0===o?void 0:o.name)||"null"));if(e.isDestroyed)return ee.warn("Cannot reference destroyed Entity: "+e.name),void t.set(r,null);s.registerReference(e,this,r)}t.set(r,e)}else t.set(r,e)}},enumerable:!0,configurable:!0})}},exports.EntitySerializer=tt,exports.EntitySystem=Te,exports.EventBus=Ge,exports.EventTypeValidator=qe,exports.Float32=function(e,t){var n=String(t);e.constructor.__float32Fields||(e.constructor.__float32Fields=new Set),e.constructor.__float32Fields.add(n)},exports.Float64=function(e,t){var n=String(t);e.constructor.__float64Fields||(e.constructor.__float64Fields=new Set),e.constructor.__float64Fields.add(n)},exports.FuncPack=$t,exports.GlobalEventBus=Qe,exports.GlobalManager=Xt,exports.HighPrecision=function(e,t){var n=String(t);e.constructor.__highPrecisionFields||(e.constructor.__highPrecisionFields=new Set),e.constructor.__highPrecisionFields.add(n)},exports.IdentifierPool=be,exports.IgnoreSerialization=function(){return function(e,t){var n=e.constructor,i=n[Ke];i||(i={options:{version:1},fields:new Map,ignoredFields:new Set},n[Ke]=i),i.ignoredFields.add(t)}},exports.IncrementalSerializer=Dt,exports.Inject=M,exports.Injectable=A,exports.Int16=function(e,t){var n=String(t);e.constructor.__int16Fields||(e.constructor.__int16Fields=new Set),e.constructor.__int16Fields.add(n)},exports.Int32=function(e,t){var n=String(t);e.constructor.__int32Fields||(e.constructor.__int32Fields=new Set),e.constructor.__int32Fields.add(n)},exports.Int8=function(e,t){var n=String(t);e.constructor.__int8Fields||(e.constructor.__int8Fields=new Set),e.constructor.__int8Fields.add(n)},exports.IntervalSystem=rn,exports.Logger=V,exports.LoggerManager=Q,exports.Matcher=Ae,exports.MigrationBuilder=un,exports.NumberExtension=fn,exports.PassiveSystem=nn,exports.PerformanceDataCollector=ae,exports.PerformanceMonitor=O,exports.PlatformDetector=pn,exports.PlatformManager=sn,exports.PluginManager=Qt,exports.Pool=z,exports.PoolManager=P,exports.ProcessingSystem=tn,exports.QuerySystem=Ue,exports.ReactiveQuery=We,exports.ReferenceTracker=X,exports.SERIALIZABLE_METADATA=Ke,exports.SERIALIZE_FIELD=Je,exports.SERIALIZE_OPTIONS=$e,exports.SYSTEM_TYPE_NAME=N,exports.Scene=Bt,exports.SceneDataCollector=fe,exports.SceneManager=qt,exports.SceneSerializer=kt,exports.Serializable=function(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");var n=t[Ke];return n?n.options=e:(n={options:e,fields:new Map,ignoredFields:new Set},t[Ke]=n),t}},exports.Serialize=Ze,exports.SerializeArray=function(e,t){var n=String(t);e.constructor.__serializeArrayFields||(e.constructor.__serializeArrayFields=new Set),e.constructor.__serializeArrayFields.add(n)},exports.SerializeAsMap=function(){return function(e,t){Ze({serializer:function(e){return e instanceof Map?Array.from(e.entries()):null},deserializer:function(e){return Array.isArray(e)?new Map(e):new Map}})(e,t)}},exports.SerializeAsSet=function(){return function(e,t){Ze({serializer:function(e){return e instanceof Set?Array.from(e):null},deserializer:function(e){return Array.isArray(e)?new Set(e):new Set}})(e,t)}},exports.SerializeMap=function(e,t){var n=String(t);e.constructor.__serializeMapFields||(e.constructor.__serializeMapFields=new Set),e.constructor.__serializeMapFields.add(n)},exports.SerializeSet=function(e,t){var n=String(t);e.constructor.__serializeSetFields||(e.constructor.__serializeSetFields=new Set),e.constructor.__serializeSetFields.add(n)},exports.ServiceContainer=zt,exports.SoAStorage=me,exports.SparseSet=Ie,exports.SystemDataCollector=oe,exports.Time=_,exports.Timer=C,exports.TypeInference=ye,exports.TypeSafeEventSystem=He,exports.TypeUtils=ln,exports.TypedEntityBuilder=hn,exports.TypedQueryBuilder=Ye,exports.TypedQueryResult=Ve,exports.Uint16=function(e,t){var n=String(t);e.constructor.__uint16Fields||(e.constructor.__uint16Fields=new Set),e.constructor.__uint16Fields.add(n)},exports.Uint32=function(e,t){var n=String(t);e.constructor.__uint32Fields||(e.constructor.__uint32Fields=new Set),e.constructor.__uint32Fields.add(n)},exports.Uint8=function(e,t){var n=String(t);e.constructor.__uint8Fields||(e.constructor.__uint8Fields=new Set),e.constructor.__uint8Fields.add(n)},exports.Uint8Clamped=function(e,t){var n=String(t);e.constructor.__uint8ClampedFields||(e.constructor.__uint8ClampedFields=new Set),e.constructor.__uint8ClampedFields.add(n)},exports.Updatable=T,exports.VersionMigrationManager=cn,exports.WebSocketManager=de,exports.WorkerEntitySystem=on,exports.World=jt,exports.WorldManager=Yt,exports.addAndConfigure=function(e,t,n){return e.addComponent(t),n(t),e},exports.buildEntity=function(e){return new hn(e)},exports.createECSAPI=Ut,exports.createInstance=I,exports.createLogger=Y,exports.createQuery=function(){return new Ye},exports.getBasicWorkerConfig=function(){return sn.getInstance().getBasicWorkerConfig()},exports.getComponentInstanceTypeName=H,exports.getComponentTypeName=U,exports.getComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.map((function(t){return e.getComponent(t)}))},exports.getCurrentAdapter=function(){return sn.getInstance().getAdapter()},exports.getEntityRefMetadata=re,exports.getFullPlatformConfig=function(){return sn.getInstance().getFullPlatformConfig()},exports.getOrAddComponent=function(e,t,n){var i=e.getComponent(t);return i||(i=n(),e.addComponent(i)),i},exports.getSceneByEntityId=Z,exports.getSerializationMetadata=Xe,exports.getSystemInstanceTypeName=j,exports.getSystemMetadata=W,exports.getSystemTypeName=F,exports.getUpdatableMetadata=R,exports.hasAdapter=function(){return sn.getInstance().hasAdapter()},exports.hasAnyComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.some((function(t){return e.hasComponent(t)}))},exports.hasComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.every((function(t){return e.hasComponent(t)}))},exports.hasEntityRef=function(e){return null!==re(e)},exports.isComponentArray=function(e){return e.every(dn)},exports.isComponentType=dn,exports.isSerializable=function(e){return null!==Xe(e)},exports.isUpdatable=D,exports.queryFor=function(e){return new Ye([e])},exports.queryForAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new Ye(t)},exports.registerInjectable=function(e,t,n){if(void 0===n&&(n=!0),!x(t))throw new Error(t.name+" is not marked as @Injectable(). Please add @Injectable() decorator to the class.");var i=function(e){return I(t,e)};n?e.registerSingleton(t,i):e.registerTransient(t,i)},exports.registerPlatformAdapter=function(e){return sn.getInstance().registerAdapter(e)},exports.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" (id: "+e.id+")");return n},exports.resetLoggerColors=function(){Q.getInstance().resetColors()},exports.setGlobalLogLevel=function(e){Q.getInstance().setGlobalLevel(e)},exports.setLoggerColors=function(e){Q.getInstance().setGlobalColors(e)},exports.supportsFeature=function(e){return sn.getInstance().supportsFeature(e)},exports.tryGetComponent=function(e,t){var n=e.getComponent(t);return null!==n?n:void 0},exports.updateComponent=function(e,t,n){var i=e.getComponent(t);return!!i&&(Object.assign(i,n),!0)};
|
|
4
4
|
//# sourceMappingURL=index.cjs.map
|