@esengine/ecs-framework 2.1.48 → 2.1.50

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,i=Array(e);n<e;n++)i[n]=t[n];return i}function e(t,e,n,i,r,s,o){try{var a=t[s](o),c=a.value}catch(t){return void n(t)}a.done?e(c):Promise.resolve(c).then(i,r)}function n(t){return function(){var n=this,i=arguments;return new Promise((function(r,s){var o=t.apply(n,i);function a(t){e(o,r,s,a,c,"next",t)}function c(t){e(o,r,s,a,c,"throw",t)}a(void 0)}))}}function i(t,e,n){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,e);var r=new(t.bind.apply(t,i));return n&&f(r,n.prototype),r}function r(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,m(i.key),i)}}function s(t,e,n){return e&&r(t.prototype,e),n&&r(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function o(e,n){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=function(e,n){if(e){if("string"==typeof e)return t(e,n);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(e,n):void 0}}(e))||n){i&&(e=i);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[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(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},a.apply(null,arguments)}function c(t){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},c(t)}function u(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,f(t,e)}function h(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(h=function(){return!!t})()}function l(){
1
+ 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,o,s){try{var a=e[o](s),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,o){var s=e.apply(n,i);function a(e){t(s,r,o,a,c,"next",e)}function c(e){t(s,r,o,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&&f(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 o(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(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,f(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 t,e,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 d(u,"_invoke",function(n,i,r){var s,a,c,u=0,h=r||[],l=!1,d={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return s=e,a=0,c=t,d.n=n,o}};function f(n,i){for(a=n,c=i,e=0;!l&&u&&!r&&e<h.length;e++){var r,s=h[e],f=d.p,m=s[2];n>3?(r=m===i)&&(c=s[(a=s[4])?5:(a=3,3)],s[4]=s[5]=t):s[0]<=f&&((r=n<2&&f<s[1])?(a=0,d.v=i,d.n=s[1]):f<m&&(r=n<3||s[0]>i||i>m)&&(s[4]=n,s[5]=i,d.n=m,a=0))}if(r||n>1)return o;throw l=!0,i}return function(r,h,m){if(u>1)throw TypeError("Generator is already running");for(l&&1===h&&f(h,m),a=h,c=m;(e=a<2?t:c)||!l;){s||(a?a<3?(a>1&&(d.n=-1),f(a,c)):d.n=c:d.v=c);try{if(u=2,s){if(a||(r="next"),e=s[r]){if(!(e=e.call(s,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,a<2&&(a=0)}else 1===a&&(e=s.return)&&e.call(s),a<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),a=1);s=t}else if((e=(l=d.n<0)?c:n.call(i,d))!==o)break}catch(e){s=t,a=1,c=e}finally{u=1}}return{value:e,done:l}}}(n,r,s),!0),u}var o={};function a(){}function c(){}function u(){}e=Object.getPrototypeOf;var h=[][i]?e(e([][i]())):(d(e={},i,(function(){return this})),e),f=u.prototype=a.prototype=Object.create(h);function m(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,u):(t.__proto__=u,d(t,r,"GeneratorFunction")),t.prototype=Object.create(f),t}return c.prototype=u,d(f,"constructor",u),d(u,"constructor",c),c.displayName="GeneratorFunction",d(u,r,"GeneratorFunction"),d(f),d(f,r,"Generator"),d(f,i,(function(){return this})),d(f,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:s,m:m}})()}function d(t,e,n,i){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}d=function(t,e,n,i){function s(e,n){d(t,e,(function(t){return this._invoke(e,n,t)}))}e?r?r(t,e,{value:n,enumerable:!i,configurable:!i,writable:!i}):t[e]=n:(s("next",0),s("throw",1),s("return",2))},d(t,e,n,i)}function f(t,e){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},f(t,e)}function m(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var i=n.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}function p(t){var e="function"==typeof Map?new Map:void 0;return p=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(e){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,n)}function n(){return i(t,arguments,c(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),f(n,t)},p(t)}var y=function(){function t(){this._enabled=!1}var e=t.prototype;return e.setEnabled=function(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())},e.onEnabled=function(){},e.onDisabled=function(){},e.update=function(){},s(t,[{key:"enabled",get:function(){return this._enabled},set:function(t){this.setEnabled(t)}}])}(),g=function(){function t(){}return t.update=function(t){this.unscaledDeltaTime=t,this.deltaTime=t*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++},t.sceneChanged=function(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0},t.checkEvery=function(t,e){return this.totalTime-e>=t},t}();g.deltaTime=0,g.unscaledDeltaTime=0,g.totalTime=0,g.unscaledTotalTime=0,g.timeScale=1,g.frameCount=0;var v,_=function(){function t(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}var e=t.prototype;return e.getContext=function(){return this.context},e.reset=function(){this._elapsedTime=0},e.stop=function(){this._isDone=!0},e.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+=g.deltaTime,this._isDone},e.initialize=function(t,e,n,i){this._timeInSeconds=t,this._repeats=e,this.context=n,this._onTime=i.bind(n)},e.unload=function(){this.context=null,this._onTime=null},s(t,[{key:"isDone",get:function(){return this._isDone}},{key:"elapsedTime",get:function(){return this._elapsedTime}}])}(),S=function(t){function e(){var e;return(e=t.apply(this,arguments)||this)._timers=[],e}u(e,t);var n=e.prototype;return n.update=function(){for(var t=this._timers.length-1;t>=0;t--)this._timers[t].tick()&&(this._timers[t].unload(),this._timers.splice(t,1))},n.schedule=function(t,e,n,i){var r=new _;return r.initialize(t,e,n,i),this._timers.push(r),r},e}(y);!function(t){t.HIGH_EXECUTION_TIME="high_execution_time",t.HIGH_MEMORY_USAGE="high_memory_usage",t.HIGH_CPU_USAGE="high_cpu_usage",t.FREQUENT_GC="frequent_gc",t.LOW_FPS="low_fps",t.HIGH_ENTITY_COUNT="high_entity_count"}(v||(v={}));var E=function(){function t(){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 e=t.prototype;return e.enable=function(){this._isEnabled=!0},e.disable=function(){this._isEnabled=!1},e.startMonitoring=function(t){return this._isEnabled?performance.now():0},e.endMonitoring=function(t,e,n){if(void 0===n&&(n=0),this._isEnabled&&0!==e){var i=performance.now(),r=i-e,s={name:t,executionTime:r,entityCount:n,averageTimePerEntity:n>0?r/n:0,lastUpdateTime:i};this._systemData.set(t,s),this.updateStats(t,r)}},e.updateStats=function(t,e){var n=this._systemStats.get(t);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(t,n)),n.totalTime+=e,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,e),n.maxTime=Math.max(n.maxTime,e),n.recentTimes.push(e),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)},e.calculateAdvancedStats=function(t){if(0!==t.recentTimes.length){var e=t.recentTimes.reduce((function(t,e){return t+e}),0)/t.recentTimes.length,n=t.recentTimes.reduce((function(t,n){return t+Math.pow(n-e,2)}),0)/t.recentTimes.length;t.standardDeviation=Math.sqrt(n);var i=[].concat(t.recentTimes).sort((function(t,e){return t-e})),r=i.length;t.percentile95=i[Math.floor(.95*r)]||0,t.percentile99=i[Math.floor(.99*r)]||0}},e.getSystemData=function(t){return this._systemData.get(t)},e.getSystemStats=function(t){return this._systemStats.get(t)},e.getAllSystemData=function(){return new Map(this._systemData)},e.getAllSystemStats=function(){return new Map(this._systemStats)},e.getPerformanceReport=function(){if(!this._isEnabled)return"Performance monitoring is disabled.";var t=[];t.push("=== ECS Performance Report ==="),t.push("");for(var e,n=o(Array.from(this._systemStats.entries()).sort((function(t,e){return e[1].averageTime-t[1].averageTime})));!(e=n()).done;){var i=e.value,r=i[0],s=i[1],a=this._systemData.get(r);t.push("System: "+r),t.push(" Current: "+(null==a?void 0:a.executionTime.toFixed(2))+"ms ("+(null==a?void 0:a.entityCount)+" entities)"),t.push(" Average: "+s.averageTime.toFixed(2)+"ms"),t.push(" Min/Max: "+s.minTime.toFixed(2)+"ms / "+s.maxTime.toFixed(2)+"ms"),t.push(" Total: "+s.totalTime.toFixed(2)+"ms ("+s.executionCount+" calls)"),null!=a&&a.averageTimePerEntity&&a.averageTimePerEntity>0&&t.push(" Per Entity: "+a.averageTimePerEntity.toFixed(4)+"ms"),t.push("")}var c=Array.from(this._systemData.values()).reduce((function(t,e){return t+e.executionTime}),0);return t.push("Total Frame Time: "+c.toFixed(2)+"ms"),t.push("Systems Count: "+this._systemData.size),t.join("\n")},e.reset=function(){this._systemData.clear(),this._systemStats.clear()},e.resetSystem=function(t){this._systemData.delete(t),this._systemStats.delete(t)},e.getPerformanceWarnings=function(t){void 0===t&&(t=16.67);for(var e,n=[],i=o(this._systemData.entries());!(e=i()).done;){var r=e.value,s=r[0],a=r[1];a.executionTime>t&&n.push(s+": "+a.executionTime.toFixed(2)+"ms (>"+t+"ms)")}return n},e.setMaxRecentSamples=function(t){this._maxRecentSamples=t;for(var e,n=o(this._systemStats.values());!(e=n()).done;)for(var i=e.value;i.recentTimes.length>t;)i.recentTimes.shift()},s(t,[{key:"isEnabled",get:function(){return this._isEnabled}}],[{key:"instance",get:function(){return t._instance||(t._instance=new t),t._instance}}])}(),T=function(){function t(t,e,n){void 0===e&&(e=100),void 0===n&&(n=1024),this._objects=[],this._createFn=t,this._maxSize=e,this._objectSize=n,this._stats={size:0,maxSize:e,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}t.getPool=function(e,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this._pools.get(e);return r||(r=new t((function(){return new e}),n,i),this._pools.set(e,r)),r};var e=t.prototype;return e.obtain=function(){if(this._stats.totalObtained++,this._objects.length>0){var t=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),t}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()},e.release=function(t){t&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(t.reset(),this._objects.push(t),this._stats.size++,this._updateMemoryUsage()))},e.getStats=function(){return a({},this._stats)},e.clear=function(){for(var t,e=o(this._objects);!(t=e()).done;){t.value.reset()}this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()},e.compact=function(t){for(var e=null!=t?t:Math.floor(this._objects.length/2);this._objects.length>e;){var n=this._objects.pop();n&&(n.reset(),this._stats.size--)}this._updateMemoryUsage()},e.prewarm=function(t){for(var e=Math.min(t,this._maxSize-this._objects.length),n=0;n<e;n++){var i=this._createFn();i.reset(),this._objects.push(i),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()},e.setMaxSize=function(t){this._maxSize=t,this._stats.maxSize=t,this._objects.length>t&&this.compact(t)},e.getAvailableCount=function(){return this._objects.length},e.isEmpty=function(){return 0===this._objects.length},e.isFull=function(){return this._objects.length>=this._maxSize},t.getAllPoolTypes=function(){return Array.from(this._pools.keys())},t.getAllPoolStats=function(){for(var t,e={},n=o(this._pools);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];e[r.name||r.toString()]=s.getStats()}return e},t.compactAllPools=function(){for(var t,e=o(this._pools.values());!(t=e()).done;){t.value.compact()}},t.clearAllPools=function(){for(var t,e=o(this._pools.values());!(t=e()).done;){t.value.clear()}this._pools.clear()},t.getGlobalStatsString=function(){var t=this.getAllPoolStats(),e=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(t).length)return e.push("No pools registered"),e.join("\n");for(var n=0,i=Object.entries(t);n<i.length;n++){var r=i[n],s=r[0],o=r[1];e.push(s+":"),e.push(" Size: "+o.size+"/"+o.maxSize),e.push(" Hit Rate: "+(100*o.hitRate).toFixed(1)+"%"),e.push(" Total Created: "+o.totalCreated),e.push(" Total Obtained: "+o.totalObtained),e.push(" Memory: "+(o.estimatedMemoryUsage/1024).toFixed(1)+" KB"),e.push("")}return e.join("\n")},e._updateHitRate=function(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{var t=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=t/this._stats.totalObtained}},e._updateMemoryUsage=function(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize},t}();T._pools=new Map;var C,b=function(){function t(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}t.getInstance=function(){return t.instance||(t.instance=new t),t.instance};var e=t.prototype;return e.registerPool=function(t,e){this.pools.set(t,e)},e.getPool=function(t){return this.pools.get(t)||null},e.update=function(){var t=Date.now();t-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=t)},e.createPool=function(t,e,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this.pools.get(t);return r||(r=new T(e,n,i),this.pools.set(t,r)),r},e.removePool=function(t){var e=this.pools.get(t);return!!e&&(e.clear(),this.pools.delete(t),!0)},e.getPoolNames=function(){return Array.from(this.pools.keys())},e.getPoolCount=function(){return this.pools.size},e.compactAllPools=function(){for(var t,e=o(this.pools.values());!(t=e()).done;){t.value.compact()}},e.clearAllPools=function(){for(var t,e=o(this.pools.values());!(t=e()).done;){t.value.clear()}},e.getAllStats=function(){for(var t,e=new Map,n=o(this.pools);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];e.set(r,s.getStats())}return e},e.getGlobalStats=function(){for(var t,e=0,n=0,i=0,r=0,s=0,a=0,c=o(this.pools.values());!(t=c()).done;){var u=t.value.getStats();e+=u.size,n+=u.maxSize,i+=u.totalCreated,r+=u.totalObtained,s+=u.totalReleased,a+=u.estimatedMemoryUsage}return{size:e,maxSize:n,totalCreated:i,totalObtained:r,totalReleased:s,hitRate:0===r?0:(r-i)/r,estimatedMemoryUsage:a}},e.getStatsString=function(){var t=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return t.push("No pools registered"),t.join("\n");var e=this.getGlobalStats();t.push("Total Pools: "+this.pools.size),t.push("Global Hit Rate: "+(100*e.hitRate).toFixed(1)+"%"),t.push("Global Memory Usage: "+(e.estimatedMemoryUsage/1024).toFixed(1)+" KB"),t.push("");for(var n,i=o(this.pools);!(n=i()).done;){var r=n.value,s=r[0],a=r[1].getStats();t.push(s+":"),t.push(" Size: "+a.size+"/"+a.maxSize),t.push(" Hit Rate: "+(100*a.hitRate).toFixed(1)+"%"),t.push(" Memory: "+(a.estimatedMemoryUsage/1024).toFixed(1)+" KB"),t.push("")}return t.join("\n")},e.setAutoCompactInterval=function(t){this.autoCompactInterval=t},e.prewarmAllPools=function(){for(var t,e=o(this.pools.values());!(t=e()).done;){var n=t.value,i=n.getStats(),r=Math.floor(.2*i.maxSize);n.prewarm(r)}},e.reset=function(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0},t}(),M=function(){function t(){}return t.create=function(t){if(t<0||t>=64)throw new Error("Bit index "+t+" out of range [0, 63]");return t<32?{lo:1<<t,hi:0}:{lo:0,hi:1<<t-32}},t.fromNumber=function(t){return{lo:t>>>0,hi:0}},t.hasAny=function(t,e){return 0!==(t.lo&e.lo)||0!==(t.hi&e.hi)},t.hasAll=function(t,e){return(t.lo&e.lo)===e.lo&&(t.hi&e.hi)===e.hi},t.hasNone=function(t,e){return 0===(t.lo&e.lo)&&0===(t.hi&e.hi)},t.isZero=function(t){return 0===t.lo&&0===t.hi},t.equals=function(t,e){return t.lo===e.lo&&t.hi===e.hi},t.setBit=function(t,e){if(e<0||e>=64)throw new Error("Bit index "+e+" out of range [0, 63]");e<32?t.lo|=1<<e:t.hi|=1<<e-32},t.clearBit=function(t,e){if(e<0||e>=64)throw new Error("Bit index "+e+" out of range [0, 63]");e<32?t.lo&=~(1<<e):t.hi&=~(1<<e-32)},t.orInPlace=function(t,e){t.lo|=e.lo,t.hi|=e.hi},t.andInPlace=function(t,e){t.lo&=e.lo,t.hi&=e.hi},t.xorInPlace=function(t,e){t.lo^=e.lo,t.hi^=e.hi},t.clear=function(t){t.lo=0,t.hi=0},t.copy=function(t,e){e.lo=t.lo,e.hi=t.hi},t.clone=function(t){return{lo:t.lo,hi:t.hi}},t.toString=function(t,e){if(void 0===e&&(e=2),2===e)return 0===t.hi?t.lo.toString(2):t.hi.toString(2)+t.lo.toString(2).padStart(32,"0");if(16===e)return 0===t.hi?"0x"+t.lo.toString(16).toUpperCase():"0x"+t.hi.toString(16).toUpperCase()+t.lo.toString(16).toUpperCase().padStart(8,"0");throw new Error("Only radix 2 and 16 are supported")},t.popCount=function(t){for(var e=0,n=t.lo,i=t.hi;n;)n&=n-1,e++;for(;i;)i&=i-1,e++;return e},t}();M.ZERO={lo:0,hi:0},function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error",t[t.Fatal=4]="Fatal",t[t.None=5]="None"}(C||(C={}));var w={BLACK:"",RED:"",GREEN:"",YELLOW:"",BLUE:"",MAGENTA:"",CYAN:"",WHITE:"",BRIGHT_BLACK:"",BRIGHT_RED:"",BRIGHT_GREEN:"",BRIGHT_YELLOW:"",BRIGHT_BLUE:"",BRIGHT_MAGENTA:"",BRIGHT_CYAN:"",BRIGHT_WHITE:"",RESET:"",BOLD:"",UNDERLINE:""},I=function(){function t(t){void 0===t&&(t={}),this._config=a({level:C.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window},t)}var e=t.prototype;return e.debug=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Debug,t].concat(n))},e.info=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Info,t].concat(n))},e.warn=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Warn,t].concat(n))},e.error=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Error,t].concat(n))},e.fatal=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Fatal,t].concat(n))},e.setLevel=function(t){this._config.level=t},e.setColors=function(t){0===Object.keys(t).length?delete this._config.colors:this._config.colors=a({},this._config.colors,t)},e.setPrefix=function(t){this._config.prefix=t},e.log=function(t,e){if(!(t<this._config.level)){var n=e;if(this._config.enableTimestamp)n="["+(new Date).toISOString()+"] "+n;if(this._config.prefix&&(n="["+this._config.prefix+"] "+n),n="["+C[t].toUpperCase()+"] "+n,this._config.output)this._config.output(t,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,[t,n].concat(r))}}},e.outputToConsole=function(t,e){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(t){case C.Debug:var o,a;if(n)(o=console).debug.apply(o,[""+n.debug+e+n.reset].concat(r));else(a=console).debug.apply(a,[e].concat(r));break;case C.Info:var c,u;if(n)(c=console).info.apply(c,[""+n.info+e+n.reset].concat(r));else(u=console).info.apply(u,[e].concat(r));break;case C.Warn:var h,l;if(n)(h=console).warn.apply(h,[""+n.warn+e+n.reset].concat(r));else(l=console).warn.apply(l,[e].concat(r));break;case C.Error:var d,f;if(n)(d=console).error.apply(d,[""+n.error+e+n.reset].concat(r));else(f=console).error.apply(f,[e].concat(r));break;case C.Fatal:var m,p;if(n)(m=console).error.apply(m,[""+n.fatal+e+n.reset].concat(r));else(p=console).error.apply(p,[e].concat(r))}},e.getColors=function(){return a({},{debug:w.BRIGHT_BLACK,info:w.GREEN,warn:w.YELLOW,error:w.RED,fatal:w.BRIGHT_RED,reset:w.RESET},this._config.colors)},t}(),A=function(){function t(){this._loggers=new Map,this._defaultLevel=C.Info,this._defaultLogger=new I({level:this._defaultLevel})}t.getInstance=function(){return t._instance||(t._instance=new t),t._instance};var e=t.prototype;return e.getLogger=function(t){if(!t)return this._defaultLogger;if(!this._loggers.has(t)){var e=new I({prefix:t,level:this._defaultLevel});this._loggers.set(t,e)}return this._loggers.get(t)},e.setLogger=function(t,e){this._loggers.set(t,e)},e.setGlobalLevel=function(t){this._defaultLevel=t,this._defaultLogger instanceof I&&this._defaultLogger.setLevel(t);for(var e,n=o(this._loggers.values());!(e=n()).done;){var i=e.value;i instanceof I&&i.setLevel(t)}},e.createChildLogger=function(t,e){var n=t+"."+e;return this.getLogger(n)},e.setGlobalColors=function(t){this._defaultLogger instanceof I&&this._defaultLogger.setColors(t);for(var e,n=o(this._loggers.values());!(e=n()).done;){var i=e.value;i instanceof I&&i.setColors(t)}},e.resetColors=function(){this._defaultLogger instanceof I&&this._defaultLogger.setColors({});for(var t,e=o(this._loggers.values());!(t=e()).done;){var n=t.value;n instanceof I&&n.setColors({})}},t}(),x=A.getInstance().getLogger();function D(t){return A.getInstance().getLogger(t)}function O(t){A.getInstance().setGlobalColors(t)}function k(){A.getInstance().resetColors()}function N(t){A.getInstance().setGlobalLevel(t)}function R(t){return t.__enableSoA=!0,t}function P(t,e){var n=String(e);t.constructor.__highPrecisionFields||(t.constructor.__highPrecisionFields=new Set),t.constructor.__highPrecisionFields.add(n)}function z(t,e){var n=String(e);t.constructor.__float64Fields||(t.constructor.__float64Fields=new Set),t.constructor.__float64Fields.add(n)}function B(t,e){var n=String(e);t.constructor.__float32Fields||(t.constructor.__float32Fields=new Set),t.constructor.__float32Fields.add(n)}function F(t,e){var n=String(e);t.constructor.__int32Fields||(t.constructor.__int32Fields=new Set),t.constructor.__int32Fields.add(n)}function L(t,e){var n=String(e);t.constructor.__serializeMapFields||(t.constructor.__serializeMapFields=new Set),t.constructor.__serializeMapFields.add(n)}var q=function(){function t(t){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=t,this.initializeFields(t)}var e=t.prototype;return e.initializeFields=function(t){var e=new t,n=t.__highPrecisionFields||new Set,i=t.__float64Fields||new Set,r=t.__float32Fields||new Set,s=t.__int32Fields||new Set,o=t.__serializeMapFields||new Set,a=t.__serializeSetFields||new Set,c=t.__serializeArrayFields||new Set;for(var u in e)if(e.hasOwnProperty(u)&&"id"!==u){var h=e[u],l=typeof h;"number"===l?n.has(u)||(i.has(u)?this.fields.set(u,new Float64Array(this._capacity)):s.has(u)?this.fields.set(u,new Int32Array(this._capacity)):(r.has(u),this.fields.set(u,new Float32Array(this._capacity)))):"boolean"===l?this.fields.set(u,new Float32Array(this._capacity)):"string"===l?this.stringFields.set(u,new Array(this._capacity)):"object"===l&&null!==h&&(o.has(u)||a.has(u)||c.has(u))&&this.serializedFields.set(u,new Array(this._capacity))}},e.addComponent=function(t,e){if(this.entityToIndex.has(t)){var n=this.entityToIndex.get(t);this.updateComponentAtIndex(n,e)}else{var i;this.freeIndices.length>0?i=this.freeIndices.pop():(i=this._size)>=this._capacity&&this.resize(2*this._capacity),this.entityToIndex.set(t,i),this.indexToEntity[i]=t,this.updateComponentAtIndex(i,e),this._size++}},e.updateComponentAtIndex=function(t,e){var n=this.indexToEntity[t],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 e)if(e.hasOwnProperty(u)&&"id"!==u){var h=e[u],l=typeof h;if("number"===l)if(r.has(u)||!this.fields.has(u))i.set(u,h);else this.fields.get(u)[t]=h;else if("boolean"===l&&this.fields.has(u)){this.fields.get(u)[t]=h?1:0}else if(this.stringFields.has(u)){this.stringFields.get(u)[t]=String(h)}else if(this.serializedFields.has(u)){this.serializedFields.get(u)[t]=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)},e.serializeValue=function(e,n,i,r,s){try{return i.has(n)&&e instanceof Map?JSON.stringify(Array.from(e.entries())):r.has(n)&&e instanceof Set?JSON.stringify(Array.from(e)):(s.has(n)&&Array.isArray(e),JSON.stringify(e))}catch(e){return t._logger.warn("SoA序列化字段 "+n+" 失败:",e),"{}"}},e.deserializeValue=function(e,n,i,r,s){try{var o=JSON.parse(e);return i.has(n)?new Map(o):r.has(n)?new Set(o):(s.has(n),o)}catch(e){return t._logger.warn("SoA反序列化字段 "+n+" 失败:",e),null}},e.deepClone=function(t){var e=this;if(null===t||"object"!=typeof t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array)return t.map((function(t){return e.deepClone(t)}));if(t instanceof Map){for(var n,i=new Map,r=o(t.entries());!(n=r()).done;){var s=n.value,a=s[0],c=s[1];i.set(a,this.deepClone(c))}return i}if(t instanceof Set){for(var u,h=new Set,l=o(t.values());!(u=l()).done;){var d=u.value;h.add(this.deepClone(d))}return h}var f={};for(var m in t)t.hasOwnProperty(m)&&(f[m]=this.deepClone(t[m]));return f},e.getComponent=function(t){var e=this.entityToIndex.get(t);if(void 0===e)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][e],d=this.getFieldType(h);i[h]="boolean"===d?1===l:l}for(var f,m=o(this.stringFields.entries());!(f=m()).done;){var p=f.value,y=p[0],g=p[1];i[y]=g[e]}for(var v,_=o(this.serializedFields.entries());!(v=_()).done;){var S=v.value,E=S[0],T=S[1][e];T&&(i[E]=this.deserializeValue(T,E,r,s,a))}var C=this.complexFields.get(t);if(C)for(var b,M=o(C.entries());!(b=M()).done;){var w=b.value,I=w[0],A=w[1];i[I]=A}return i},e.getFieldType=function(t){return typeof(new this.type)[t]},e.hasComponent=function(t){return this.entityToIndex.has(t)},e.removeComponent=function(t){var e=this.entityToIndex.get(t);if(void 0===e)return null;var n=this.getComponent(t);return this.complexFields.delete(t),this.entityToIndex.delete(t),this.freeIndices.push(e),this._size--,n},e.resize=function(t){for(var e,n=o(this.fields.entries());!(e=n()).done;){var i=e.value,r=i[0],s=i[1],a=void 0;(a=s instanceof Float32Array?new Float32Array(t):s instanceof Float64Array?new Float64Array(t):new Int32Array(t)).set(s),this.fields.set(r,a)}for(var c,u=o(this.stringFields.entries());!(c=u()).done;){for(var h=c.value,l=h[0],d=h[1],f=new Array(t),m=0;m<d.length;m++)f[m]=d[m];this.stringFields.set(l,f)}for(var p,y=o(this.serializedFields.entries());!(p=y()).done;){for(var g=p.value,v=g[0],_=g[1],S=new Array(t),E=0;E<_.length;E++)S[E]=_[E];this.serializedFields.set(v,S)}this._capacity=t},e.getActiveIndices=function(){return Array.from(this.entityToIndex.values())},e.getFieldArray=function(t){return this.fields.get(t)||null},e.getTypedFieldArray=function(t){return this.fields.get(String(t))||null},e.getEntityIndex=function(t){return this.entityToIndex.get(t)},e.getEntityIdByIndex=function(t){return this.indexToEntity[t]},e.size=function(){return this._size},e.clear=function(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(var t,e=o(this.fields.values());!(t=e()).done;){t.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},e.compact=function(){if(0!==this.freeIndices.length){for(var t=Array.from(this.entityToIndex.entries()).sort((function(t,e){return t[1]-e[1]})),e=new Map,n=[],i=0;i<t.length;i++){var r=t[i],s=r[0],a=r[1];if(e.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,d=o(this.stringFields.entries());!(l=d()).done;){var f=l.value[1];f[i]=f[a]}for(var m,p=o(this.serializedFields.entries());!(m=p()).done;){var y=m.value[1];y[i]=y[a]}}}this.entityToIndex=e,this.indexToEntity=n,this.freeIndices=[],this._size=t.length}},e.getStats=function(){for(var t,e=0,n=new Map,i=o(this.fields.entries());!(t=i()).done;){var r=t.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"):(c=4,u="int32");var h=a.length*c;e+=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:e,fieldStats:n}},e.performVectorizedOperation=function(t){var e=this.getActiveIndices();t(this.fields,e)},t}();q._logger=D("SoAStorage");var W=Symbol("ComponentTypeName"),U=Symbol("SystemTypeName");function j(t){return function(e){if(!t||"string"!=typeof t)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return e[W]=t,e}}function H(t){return function(e){if(!t||"string"!=typeof t)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return e[U]=t,e}}function G(t){var e=t[W];return e||(t.name||"UnknownComponent")}function Y(t){var e=t[U];return e||(t.name||"UnknownSystem")}function Q(t){return G(t.constructor)}function V(t){return Y(t.constructor)}var X=function(){function t(){}return t.register=function(t){var e=G(t);if(this.componentTypes.has(t))return this.componentTypes.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error("Maximum number of component types ("+this.maxComponents+") exceeded");var n=this.nextBitIndex++;return this.componentTypes.set(t,n),this.componentNameToType.set(e,t),this.componentNameToId.set(e,n),n},t.getBitMask=function(t){var e=this.componentTypes.get(t);if(void 0===e){var n=G(t);throw new Error("Component type "+n+" is not registered")}return M.create(e)},t.getBitIndex=function(t){var e=this.componentTypes.get(t);if(void 0===e){var n=G(t);throw new Error("Component type "+n+" is not registered")}return e},t.isRegistered=function(t){return this.componentTypes.has(t)},t.getComponentType=function(t){return this.componentNameToType.get(t)||null},t.getAllRegisteredTypes=function(){return new Map(this.componentTypes)},t.getAllComponentNames=function(){return new Map(this.componentNameToType)},t.getComponentId=function(t){return this.componentNameToId.get(t)},t.registerComponentByName=function(t){if(this.componentNameToId.has(t))return this.componentNameToId.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error("Maximum number of component types ("+this.maxComponents+") exceeded");var e=this.nextBitIndex++;return this.componentNameToId.set(t,e),e},t.createSingleComponentMask=function(t){var e="single:"+t;if(this.maskCache.has(e))return this.maskCache.get(e);var n=this.getComponentId(t);if(void 0===n)throw new Error("Component type "+t+" is not registered");var i=M.create(n);return this.maskCache.set(e,i),i},t.createComponentMask=function(t){var e="multi:"+[].concat(t).sort().join(",");if(this.maskCache.has(e))return this.maskCache.get(e);for(var n,i=M.clone(M.ZERO),r=o(t);!(n=r()).done;){var s=n.value,a=this.getComponentId(s);if(void 0!==a){var c=M.create(a);M.orInPlace(i,c)}}return this.maskCache.set(e,i),i},t.clearMaskCache=function(){this.maskCache.clear()},t.reset=function(){this.componentTypes.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0},t}();X._logger=D("ComponentStorage"),X.componentTypes=new Map,X.componentNameToType=new Map,X.componentNameToId=new Map,X.maskCache=new Map,X.nextBitIndex=0,X.maxComponents=64;var Z=function(){function t(t){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=t,X.isRegistered(t)||X.register(t)}var e=t.prototype;return e.addComponent=function(t,e){if(this.entityToIndex.has(t))throw new Error("Entity "+t+" already has component "+G(this.componentType));var n=this.dense.length;this.dense.push(e),this.entityIds.push(t),this.entityToIndex.set(t,n)},e.getComponent=function(t){var e=this.entityToIndex.get(t);return void 0!==e?this.dense[e]:null},e.hasComponent=function(t){return this.entityToIndex.has(t)},e.removeComponent=function(t){var e=this.entityToIndex.get(t);if(void 0===e)return null;var n=this.dense[e],i=this.dense.length-1;if(e!==i){var r=this.dense[i],s=this.entityIds[i];this.dense[e]=r,this.entityIds[e]=s,this.entityToIndex.set(s,e)}return this.dense.pop(),this.entityIds.pop(),this.entityToIndex.delete(t),n},e.forEach=function(t){for(var e=0;e<this.dense.length;e++)t(this.dense[e],this.entityIds[e],e)},e.getDenseArray=function(){return{components:[].concat(this.dense),entityIds:[].concat(this.entityIds)}},e.clear=function(){this.dense.length=0,this.entityIds.length=0,this.entityToIndex.clear()},e.getStats=function(){return{totalSlots:this.dense.length,usedSlots:this.dense.length,freeSlots:0,fragmentation:0}},s(t,[{key:"size",get:function(){return this.dense.length}},{key:"type",get:function(){return this.componentType}}])}(),J=function(){function t(){this.storages=new Map}var e=t.prototype;return e.isSoAStorage=function(t){return this.storages.get(t)instanceof q},e.getSoAStorage=function(t){var e=this.getStorage(t);return e instanceof q?e:null},e.getFieldArray=function(t,e){var n=this.getSoAStorage(t);return n?n.getFieldArray(e):null},e.getTypedFieldArray=function(t,e){var n=this.getSoAStorage(t);return n?n.getTypedFieldArray(e):null},e.getActiveIndices=function(t){var e=this.getSoAStorage(t);return e?e.getActiveIndices():[]},e.getEntityIndex=function(t,e){var n=this.getSoAStorage(t);return n?n.getEntityIndex(e):void 0},e.getEntityIdByIndex=function(t,e){var n=this.getSoAStorage(t);return n?n.getEntityIdByIndex(e):void 0},e.getStorage=function(e){var n=this.storages.get(e);n||(e.__enableSoA?(n=new q(e),t._logger.info("为 "+G(e)+" 启用SoA优化(适用于大规模批量操作)")):n=new Z(e),this.storages.set(e,n));return n},e.addComponent=function(t,e){var n=e.constructor;this.getStorage(n).addComponent(t,e)},e.getComponent=function(t,e){var n=this.storages.get(e);return n?n.getComponent(t):null},e.hasComponent=function(t,e){var n=this.storages.get(e);return!!n&&n.hasComponent(t)},e.removeComponent=function(t,e){var n=this.storages.get(e);return n?n.removeComponent(t):null},e.removeAllComponents=function(t){for(var e,n=o(this.storages.values());!(e=n()).done;){e.value.removeComponent(t)}},e.getComponentMask=function(t){for(var e,n=M.clone(M.ZERO),i=o(this.storages.entries());!(e=i()).done;){var r=e.value,s=r[0];if(r[1].hasComponent(t)){var a=X.getBitMask(s);M.orInPlace(n,a)}}return n},e.getAllStats=function(){for(var t,e=new Map,n=o(this.storages.entries());!(t=n()).done;){var i=t.value,r=i[0],s=i[1],a=G(r);e.set(a,s.getStats())}return e},e.clear=function(){for(var t,e=o(this.storages.values());!(t=e()).done;){t.value.clear()}this.storages.clear()},t}();J._logger=D("ComponentStorage");var K=function(){function t(){}return t.prototype.compare=function(t,e){var n=t.updateOrder-e.updateOrder;return 0==n&&(n=t.id-e.id),n},t}(),$=function(){function t(t,e){this.components=[],this.scene=null,this.updateInterval=1,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=M.clone(M.ZERO),this._componentsByTypeId=[],this._componentDenseIndexByTypeId=[],this.name=t,this.id=e}var e=t.prototype;return e.createComponent=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];var s=i(t,n);return this.addComponent(s)},e.addComponentInternal=function(t){var e=t.constructor;X.isRegistered(e)||X.register(e);var n=X.getBitIndex(e);t.entity=this,this._componentsByTypeId[n]=t;var i=this.components.length;this._componentDenseIndexByTypeId[n]=i,this.components.push(t);var r=X.getBitMask(e);return M.orInPlace(this._componentMask,r),t},e.addComponent=function(e){var n,i=e.constructor;if(this.hasComponent(i))throw new Error("Entity "+this.name+" already has component "+G(i));(this.addComponentInternal(e),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.addComponent(this.id,e),e.onAddedToEntity(),t.eventBus)&&t.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:G(i),component:e});return this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this)),e},e.getComponent=function(t){if(!X.isRegistered(t))return null;var e=X.getBitMask(t);if(M.hasNone(this._componentMask,e))return null;var n=X.getBitIndex(t),i=this._componentsByTypeId[n];if(i&&i.constructor===t)return i;if(this.scene&&this.scene.componentStorageManager){var r=this.scene.componentStorageManager.getComponent(this.id,t);if(r){if(this._componentsByTypeId[n]=r,!this.components.includes(r)){var s=this.components.length;this._componentDenseIndexByTypeId[n]=s,this.components.push(r)}return r}}for(var o=0;o<this.components.length;o++){var a=this.components[o];if(a instanceof t)return this._componentsByTypeId[n]=a,this._componentDenseIndexByTypeId[n]=o,a}return null},e.hasComponent=function(t){if(!X.isRegistered(t))return!1;var e=X.getBitMask(t);return M.hasAny(this._componentMask,e)},e.getOrCreateComponent=function(t){var e=this.getComponent(t);if(!e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];e=this.createComponent.apply(this,[t].concat(i))}return e},e.removeComponent=function(e){var n=e.constructor;if(X.isRegistered(n)){var i=X.getBitIndex(n);this._componentsByTypeId[i]=void 0,M.clearBit(this._componentMask,i);var r,s=this._componentDenseIndexByTypeId[i];if(void 0!==s&&s<this.components.length){var o=this.components.length-1;if(s!==o){var a=this.components[o];this.components[s]=a;var c=a.constructor,u=X.getBitIndex(c);this._componentDenseIndexByTypeId[u]=s}this.components.pop()}if(this._componentDenseIndexByTypeId[i]=-1,this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,n),e.onRemovedFromEntity&&e.onRemovedFromEntity(),t.eventBus)t.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(r=this.tag)||void 0===r?void 0:r.toString(),componentType:G(n),component:e});e.entity=null,this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this))}},e.removeComponentByType=function(t){var e=this.getComponent(t);return e?(this.removeComponent(e),e):null},e.removeAllComponents=function(){var t=[].concat(this.components);this._componentsByTypeId.length=0,this._componentDenseIndexByTypeId.length=0,M.clear(this._componentMask);for(var e,n=o(t);!(e=n()).done;){var i=e.value,r=i.constructor;this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,r),i.onRemovedFromEntity(),i.entity=null}this.components.length=0},e.addComponents=function(e){for(var n,i=[],r=o(e);!(n=r()).done;){var s=n.value;try{i.push(this.addComponent(s))}catch(e){t._logger.warn("添加组件失败 "+Q(s)+":",e)}}return i},e.removeComponentsByTypes=function(t){for(var e,n=[],i=o(t);!(e=i()).done;){var r=e.value;n.push(this.removeComponentByType(r))}return n},e.getComponents=function(t){for(var e,n=[],i=o(this.components);!(e=i()).done;){var r=e.value;r instanceof t&&n.push(r)}return n},e.addChild=function(t){if(t===this)throw new Error("Entity cannot be its own child");return t._parent===this||(t._parent&&t._parent.removeChild(t),t._parent=this,this._children.push(t),!t.scene&&this.scene&&(t.scene=this.scene,this.scene.addEntity(t))),t},e.removeChild=function(t){var e=this._children.indexOf(t);return-1!==e&&(this._children.splice(e,1),t._parent=null,!0)},e.removeAllChildren=function(){for(var t,e=o([].concat(this._children));!(t=e()).done;){var n=t.value;this.removeChild(n)}},e.findChild=function(t,e){void 0===e&&(e=!1);for(var n,i=o(this._children);!(n=i()).done;){var r=n.value;if(r.name===t)return r}if(e)for(var s,a=o(this._children);!(s=a()).done;){var c=s.value.findChild(t,!0);if(c)return c}return null},e.findChildrenByTag=function(t,e){void 0===e&&(e=!1);for(var n,i=[],r=o(this._children);!(n=r()).done;){var s=n.value;s.tag===t&&i.push(s)}if(e)for(var a,c=o(this._children);!(a=c()).done;){var u=a.value;i.push.apply(i,u.findChildrenByTag(t,!0))}return i},e.getRoot=function(){for(var t=this;t._parent;)t=t._parent;return t},e.isAncestorOf=function(t){for(var e=t._parent;e;){if(e===this)return!0;e=e._parent}return!1},e.isDescendantOf=function(t){return t.isAncestorOf(this)},e.getDepth=function(){for(var t=0,e=this._parent;e;)t++,e=e._parent;return t},e.forEachChild=function(t,e){void 0===e&&(e=!1),this._children.forEach((function(n,i){t(n,i),e&&n.forEachChild(t,!0)}))},e.onActiveChanged=function(){for(var t,e=o(this.components);!(t=e()).done;){var n=t.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})},e.update=function(){if(this.activeInHierarchy&&!this._isDestroyed){for(var t,e=o(this.components);!(t=e()).done;){var n=t.value;n.enabled&&n.update()}for(var i,r=o(this._children);!(i=r()).done;){i.value.update()}}},e.destroy=function(){if(!this._isDestroyed){this._isDestroyed=!0;for(var t,e=o([].concat(this._children));!(t=e()).done;){t.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))}},e.compareTo=function(t){return K.prototype.compare(this,t)},e.toString=function(){return"Entity["+this.name+":"+this.id+"]"},e.getDebugInfo=function(){var t;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(t){return Q(t)})),componentMask:M.toString(this._componentMask,2),parentId:(null===(t=this._parent)||void 0===t?void 0:t.id)||null,childCount:this._children.length,childIds:this._children.map((function(t){return t.id})),depth:this.getDepth(),indexMappingSize:this._componentsByTypeId.filter((function(t){return void 0!==t})).length,denseIndexMappingSize:this._componentDenseIndexByTypeId.filter((function(t){return-1!==t&&void 0!==t})).length}},s(t,[{key:"isDestroyed",get:function(){return this._isDestroyed}},{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(t){this._active!==t&&(this._active=t,this.onActiveChanged())}},{key:"activeInHierarchy",get:function(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}},{key:"tag",get:function(){return this._tag},set:function(t){this._tag=t}},{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled=t}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(t){this._updateOrder=t}},{key:"componentMask",get:function(){return this._componentMask}}])}();$._logger=D("Entity"),$.entityComparer=new K,$.eventBus=null;var tt=function(){function t(t,e){this.scene=t,this.storageManager=e,this.entity=new $("",t.identifierPool.checkOut())}var e=t.prototype;return e.named=function(t){return this.entity.name=t,this},e.tagged=function(t){return this.entity.tag=t,this},e.with=function(t){return this.entity.addComponent(t),this},e.withComponents=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var i=0,r=e;i<r.length;i++){var s=r[i];this.entity.addComponent(s)}return this},e.withIf=function(t,e){return t&&this.entity.addComponent(e),this},e.withFactory=function(t){var e=t();return this.entity.addComponent(e),this},e.configure=function(t,e){var n=this.entity.getComponent(t);return n&&e(n),this},e.enabled=function(t){return void 0===t&&(t=!0),this.entity.enabled=t,this},e.active=function(t){return void 0===t&&(t=!0),this.entity.active=t,this},e.withChild=function(t){var e=t.build();return this.entity.addChild(e),this},e.withChildren=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var i=0,r=e;i<r.length;i++){var s=r[i].build();this.entity.addChild(s)}return this},e.withChildFactory=function(t){var e=t(this.entity).build();return this.entity.addChild(e),this},e.withChildIf=function(t,e){if(t){var n=e.build();this.entity.addChild(n)}return this},e.build=function(){return this.entity},e.spawn=function(){return this.scene.addEntity(this.entity),this.entity},e.clone=function(){var e=new t(this.scene,this.storageManager);return e.entity=this.entity,e},t}(),et=function(){function t(t){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._isUpdating=!1,this._scene=t}var e=t.prototype;return e.add=function(t){this._isUpdating?this._entitiesToAdd.push(t):this.addImmediate(t)},e.addImmediate=function(t){this._idToEntity.has(t.id)||(this.buffer.push(t),this._idToEntity.set(t.id,t),this.updateNameIndex(t,!0))},e.remove=function(t){this._isUpdating?this._entitiesToRemove.push(t):this.removeImmediate(t)},e.removeImmediate=function(t){var e=this.buffer.indexOf(t);-1!==e&&(this.buffer.splice(e,1),this._idToEntity.delete(t.id),this.updateNameIndex(t,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(t.id))},e.removeAllEntities=function(){for(var t=[],e=this.buffer.length-1;e>=0;e--)t.push(this.buffer[e].id),this.buffer[e].destroy();if(this._scene&&this._scene.identifierPool)for(var n,i=o(t);!(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},e.updateLists=function(){if(this._entitiesToAdd.length>0){for(var t,e=o(this._entitiesToAdd);!(t=e()).done;){var n=t.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}},e.update=function(){this._isUpdating=!0;try{for(var t=0;t<this.buffer.length;t++){var e=this.buffer[t];e.enabled&&!e.isDestroyed&&e.update()}}finally{this._isUpdating=!1}this.updateLists()},e.findEntity=function(t){var e=this._nameToEntities.get(t);return e&&e.length>0?e[0]:null},e.findEntitiesByName=function(t){return this._nameToEntities.get(t)||[]},e.findEntityById=function(t){return this._idToEntity.get(t)||null},e.findEntitiesByTag=function(t){for(var e,n=[],i=o(this.buffer);!(e=i()).done;){var r=e.value;r.tag===t&&n.push(r)}return n},e.findEntitiesWithComponent=function(t){for(var e,n=[],i=o(this.buffer);!(e=i()).done;){var r=e.value;r.hasComponent(t)&&n.push(r)}return n},e.forEach=function(t){for(var e,n=o(this.buffer);!(e=n()).done;){t(e.value)}},e.forEachWhere=function(t,e){for(var n,i=o(this.buffer);!(n=i()).done;){var r=n.value;t(r)&&e(r)}},e.updateNameIndex=function(t,e){if(t.name)if(e){var n=this._nameToEntities.get(t.name);n||(n=[],this._nameToEntities.set(t.name,n)),n.push(t)}else{var i=this._nameToEntities.get(t.name);if(i){var r=i.indexOf(t);-1!==r&&(i.splice(r,1),0===i.length&&this._nameToEntities.delete(t.name))}}},e.getStats=function(){for(var t,e=0,n=o(this.buffer);!(t=n()).done;){var i=t.value;i.enabled&&!i.isDestroyed&&e++}return{totalEntities:this.buffer.length,activeEntities:e,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}},s(t,[{key:"count",get:function(){return this.buffer.length}}])}(),nt=function(){function t(){this._processors=[],this._isDirty=!1}var e=t.prototype;return e.setDirty=function(){this._isDirty=!0},e.add=function(t){this._processors.push(t),this.setDirty()},e.remove=function(t){var e=this._processors.indexOf(t);-1!==e&&this._processors.splice(e,1)},e.getProcessor=function(t){for(var e,n=o(this._processors);!(e=n()).done;){var i=e.value;if(i instanceof t)return i}return null},e.begin=function(){this.sortProcessors()},e.end=function(){},e.update=function(){this.sortProcessors();for(var e,n=o(this._processors);!(e=n()).done;){var i=e.value;try{i.update()}catch(e){t._logger.error("Error in processor "+V(i)+":",e)}}},e.lateUpdate=function(){for(var t,e=o(this._processors);!(t=e()).done;){t.value.lateUpdate()}},e.sortProcessors=function(){this._isDirty&&(this._processors.sort((function(t,e){return t.updateOrder-e.updateOrder})),this._isDirty=!1)},s(t,[{key:"processors",get:function(){return this._processors}},{key:"count",get:function(){return this._processors.length}}])}();nt._logger=D("EntityProcessorList");var it=function(){function t(t,e){void 0===t&&(t=100),void 0===e&&(e=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=t,this._expansionBlockSize=e,this._preAllocateGenerations(0,this._expansionBlockSize)}var e=t.prototype;return e.checkOut=function(){var e;if(this._processDelayedRecycle(),this._freeIndices.length>0)e=this._freeIndices.pop();else{if(this._nextAvailableIndex>t.MAX_INDEX)throw new Error("实体索引已达到框架设计限制 ("+t.MAX_INDEX+")。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。");e=this._nextAvailableIndex++,this._ensureGenerationCapacity(e)}var n=this._generations.get(e)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(e,n)},e.checkIn=function(t){var e=this._unpackIndex(t),n=this._unpackGeneration(t);return!!this._isValidId(e,n)&&(!this._pendingRecycle.some((function(t){return t.index===e&&t.generation===n}))&&(this._pendingRecycle.push({index:e,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0))},e.isValid=function(t){var e=this._unpackIndex(t),n=this._unpackGeneration(t);return this._isValidId(e,n)},e.getStats=function(){for(var e,n=0,i=0,r=o(this._generations);!(e=r()).done;){var s=e.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:t.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*u)/100,generationStorageSize:this._generations.size}},e.forceProcessDelayedRecycle=function(){this._processDelayedRecycle(!0)},e._processDelayedRecycle=function(e){if(void 0===e&&(e=!1),0!==this._pendingRecycle.length){for(var n,i=Date.now(),r=[],s=[],a=o(this._pendingRecycle);!(n=a()).done;){var c=n.value;e||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 d=l.generation+1;d>t.MAX_GENERATION&&(d=1),this._generations.set(l.index,d),this._freeIndices.push(l.index)}}this._pendingRecycle=s}},e._preAllocateGenerations=function(e,n){for(var i=0;i<n;i++){var r=e+i;r<=t.MAX_INDEX&&this._generations.set(r,1)}this._stats.memoryExpansions++},e._ensureGenerationCapacity=function(t){if(!this._generations.has(t)){var e=Math.floor(t/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(e,this._expansionBlockSize)}},e._calculateMemoryUsage=function(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length},e._packId=function(t,e){return e<<16|t},e._unpackIndex=function(t){return 65535&t},e._unpackGeneration=function(t){return t>>>16&65535},e._isValidId=function(t,e){if(t<0||t>=this._nextAvailableIndex)return!1;var n=this._generations.get(t);return void 0!==n&&n===e},t}();it.MAX_INDEX=65535,it.MAX_GENERATION=65535;var rt=function(){function t(t,e,n){void 0===n&&(n=1e3),this.pool=[],this.createFn=t,this.resetFn=e,this.maxSize=n}var e=t.prototype;return e.acquire=function(){return this.pool.length>0?this.pool.pop():this.createFn()},e.release=function(t){this.pool.length<this.maxSize&&(this.resetFn&&this.resetFn(t),this.pool.push(t))},e.prewarm=function(t){for(var e=0;e<t&&this.pool.length<this.maxSize;e++)this.pool.push(this.createFn())},e.clear=function(){this.pool.length=0},e.getAvailableCount=function(){return this.pool.length},e.getMaxSize=function(){return this.maxSize},t}(),st=function(){function t(){this.pools=new Map}t.getInstance=function(){return t.instance||(t.instance=new t),t.instance};var e=t.prototype;return e.registerPool=function(t,e,n,i){this.pools.set(t,new rt(e,n,i))},e.acquireComponent=function(t){var e=this.pools.get(t);return e?e.acquire():null},e.releaseComponent=function(t,e){var n=this.pools.get(t);n&&n.release(e)},e.prewarmAll=function(t){void 0===t&&(t=100);for(var e,n=o(this.pools.values());!(e=n()).done;){e.value.prewarm(t)}},e.clearAll=function(){for(var t,e=o(this.pools.values());!(t=e()).done;){t.value.clear()}},e.reset=function(){this.pools.clear()},e.getPoolStats=function(){for(var t,e=new Map,n=o(this.pools);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];e.set(r,{available:s.getAvailableCount(),maxSize:s.getMaxSize()})}return e},e.getPoolUtilization=function(){for(var t,e=new Map,n=o(this.pools);!(t=n()).done;){var i=t.value,r=i[0],s=i[1],a=s.getAvailableCount(),c=s.getMaxSize(),u=c-a,h=c>0?u/c*100:0;e.set(r,{used:u,total:c,utilization:h})}return e},e.getComponentUtilization=function(t){var e=this.pools.get(t);if(!e)return 0;var n=e.getAvailableCount(),i=e.getMaxSize();return i>0?(i-n)/i*100:0},t}(),ot=function(){function t(){this._dense=[],this._sparse=new Map}var e=t.prototype;return e.add=function(t){if(this._sparse.has(t))return!1;var e=this._dense.length;return this._dense.push(t),this._sparse.set(t,e),!0},e.remove=function(t){var e=this._sparse.get(t);if(void 0===e)return!1;var n=this._dense.length-1;if(e!==n){var i=this._dense[n];this._dense[e]=i,this._sparse.set(i,e)}return this._dense.pop(),this._sparse.delete(t),!0},e.has=function(t){return this._sparse.has(t)},e.getIndex=function(t){return this._sparse.get(t)},e.getByIndex=function(t){return this._dense[t]},e.forEach=function(t){for(var e=0;e<this._dense.length;e++)t(this._dense[e],e)},e.map=function(t){for(var e=[],n=0;n<this._dense.length;n++)e.push(t(this._dense[n],n));return e},e.filter=function(t){for(var e=[],n=0;n<this._dense.length;n++)t(this._dense[n],n)&&e.push(this._dense[n]);return e},e.find=function(t){for(var e=0;e<this._dense.length;e++)if(t(this._dense[e],e))return this._dense[e]},e.some=function(t){for(var e=0;e<this._dense.length;e++)if(t(this._dense[e],e))return!0;return!1},e.every=function(t){for(var e=0;e<this._dense.length;e++)if(!t(this._dense[e],e))return!1;return!0},e.getDenseArray=function(){return[].concat(this._dense)},e.getDenseArrayUnsafe=function(){return this._dense},e.clear=function(){this._dense.length=0,this._sparse.clear()},e.toArray=function(){return[].concat(this._dense)},e.toSet=function(){return new Set(this._dense)},e.getMemoryStats=function(){var t=8*this._dense.length,e=16*this._sparse.size;return{denseArraySize:t,sparseMapSize:e,totalMemory:t+e}},e.validate=function(){if(this._dense.length!==this._sparse.size)return!1;for(var t=0;t<this._dense.length;t++){var e=this._dense[t];if(this._sparse.get(e)!==t)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(t,[{key:"size",get:function(){return this._dense.length}},{key:"isEmpty",get:function(){return 0===this._dense.length}}])}(),at=function(t){function e(){return t.call(this)||this}return u(e,t),e.prototype.reset=function(){this.clear()},e}(p(Set)),ct=function(){function t(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new ot}var e=t.prototype;return e.addEntity=function(t){this._entities.has(t)&&this.removeEntity(t);for(var e,n=M.clone(M.ZERO),i=new Set,r=o(t.components);!(e=r()).done;){var s=e.value.constructor;i.add(s),X.isRegistered(s)||X.register(s);var a=X.getBitMask(s);M.orInPlace(n,a)}this._entities.add(t);for(var c=this._entities.getIndex(t);this._componentMasks.length<=c;)this._componentMasks.push(M.clone(M.ZERO));this._componentMasks[c]=n,this.updateComponentMappings(t,i,!0)},e.removeEntity=function(t){var e=this._entities.getIndex(t);if(void 0!==e){var n=this.getEntityComponentTypes(t);this.updateComponentMappings(t,n,!1),this._entities.remove(t);var i=this._componentMasks.length-1;e!==i&&(this._componentMasks[e]=this._componentMasks[i]),this._componentMasks.pop()}},e.queryByComponent=function(t){var e=this._componentToEntities.get(t);return e?new Set(e):new Set},e.queryMultipleAnd=function(e){var n=this;if(0===e.length)return new Set;if(1===e.length)return this.queryByComponent(e[0]);for(var i,r=M.clone(M.ZERO),s=o(e);!(i=s()).done;){var a=i.value;if(!X.isRegistered(a))return new Set;var c=X.getBitMask(a);M.orInPlace(r,c)}var u=t._entitySetPool.obtain();return this._entities.forEach((function(t,e){var i=n._componentMasks[e];M.hasAll(i,r)&&u.add(t)})),u},e.queryMultipleOr=function(e){var n=this;if(0===e.length)return new Set;if(1===e.length)return this.queryByComponent(e[0]);for(var i,r=M.clone(M.ZERO),s=o(e);!(i=s()).done;){var a=i.value;if(X.isRegistered(a)){var c=X.getBitMask(a);M.orInPlace(r,c)}}if(M.equals(r,M.ZERO))return new Set;var u=t._entitySetPool.obtain();return this._entities.forEach((function(t,e){var i=n._componentMasks[e];M.hasAny(i,r)&&u.add(t)})),u},e.hasComponent=function(t,e){var n=this._entities.getIndex(t);if(void 0===n)return!1;if(!X.isRegistered(e))return!1;var i=this._componentMasks[n],r=X.getBitMask(e);return M.hasAny(i,r)},e.getEntityMask=function(t){var e=this._entities.getIndex(t);if(void 0!==e)return this._componentMasks[e]},e.getAllEntities=function(){return this._entities.toArray()},e.forEach=function(t){var e=this;this._entities.forEach((function(n,i){t(n,e._componentMasks[i],i)}))},e.clear=function(){this._entities.clear(),this._componentMasks.length=0;for(var e,n=o(this._componentToEntities.values());!(e=n()).done;){var i=e.value;t._entitySetPool.release(i)}this._componentToEntities.clear()},e.getMemoryStats=function(){for(var t,e=this._entities.getMemoryStats(),n=16*this._componentMasks.length,i=16*this._componentToEntities.size,r=o(this._componentToEntities.values());!(t=r()).done;){i+=8*t.value.size}return{entitiesMemory:e.totalMemory,masksMemory:n,mappingsMemory:i,totalMemory:e.totalMemory+n+i}},e.validate=function(){if(!this._entities.validate())return!1;if(this._componentMasks.length!==this._entities.size)return!1;for(var t,e=new Set,n=o(this._componentToEntities.values());!(t=n()).done;)for(var i,r=o(t.value);!(i=r()).done;){var s=i.value;e.add(s)}for(var a,c=o(e);!(a=c()).done;){var u=a.value;if(!this._entities.has(u))return!1}return!0},e.getEntityComponentTypes=function(t){for(var e,n=new Set,i=o(t.components);!(e=i()).done;){var r=e.value;n.add(r.constructor)}return n},e.updateComponentMappings=function(e,n,i){for(var r,s=o(n);!(r=s()).done;){var a=r.value,c=this._componentToEntities.get(a);i?(c||(c=t._entitySetPool.obtain(),this._componentToEntities.set(a,c)),c.add(e)):c&&(c.delete(e),0===c.size&&(this._componentToEntities.delete(a),t._entitySetPool.release(c)))}},s(t,[{key:"size",get:function(){return this._entities.size}},{key:"isEmpty",get:function(){return this._entities.isEmpty}}])}();ct._entitySetPool=T.getPool(at,50,512);var ut,ht=function(){function t(){this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now(),this._sparseSet=new ct}var e=t.prototype;return e.addEntity=function(t){this._sparseSet.addEntity(t),this._lastUpdated=Date.now()},e.removeEntity=function(t){this._sparseSet.removeEntity(t),this._lastUpdated=Date.now()},e.query=function(t){var e=performance.now(),n=this._sparseSet.queryByComponent(t);return this._queryCount++,this._totalQueryTime+=performance.now()-e,n},e.queryMultiple=function(t,e){var n,i=performance.now();return n=0===t.length?new Set:1===t.length?this.query(t[0]):"AND"===e?this._sparseSet.queryMultipleAnd(t):this._sparseSet.queryMultipleOr(t),this._queryCount++,this._totalQueryTime+=performance.now()-i,n},e.clear=function(){this._sparseSet.clear(),this._lastUpdated=Date.now()},e.getStats=function(){var t=this._sparseSet.getMemoryStats();return{size:this._sparseSet.size,memoryUsage:t.totalMemory,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}},t}(),lt=function(){function t(){this._index=new ht}var e=t.prototype;return e.addEntity=function(t){this._index.addEntity(t)},e.removeEntity=function(t){this._index.removeEntity(t)},e.query=function(t){return this._index.query(t)},e.queryMultiple=function(t,e){return this._index.queryMultiple(t,e)},e.getStats=function(){return this._index.getStats()},e.clear=function(){this._index.clear()},t}(),dt=function(){function t(){this._archetypes=new Map,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._queryCache=new Map,this._cacheTimeout=5e3,this._maxCacheSize=100}var e=t.prototype;return e.addEntity=function(t){var e=this.getEntityComponentTypes(t),n=this.generateArchetypeId(e),i=this._archetypes.get(n);i||(i=this.createArchetype(e)),i.entities.push(t),i.updatedAt=Date.now(),this._entityToArchetype.set(t,i),this.updateComponentIndexes(i,e,!0),this.invalidateQueryCache()},e.removeEntity=function(t){var e=this._entityToArchetype.get(t);if(e){var n=e.entities.indexOf(t);-1!==n&&(e.entities.splice(n,1),e.updatedAt=Date.now()),this._entityToArchetype.delete(t),this.invalidateQueryCache()}},e.queryArchetypes=function(t,e){void 0===e&&(e="AND");var n=performance.now(),i=e+":"+t.map((function(t){return G(t)})).sort().join(","),r=this._queryCache.get(i);if(r&&Date.now()-r.timestamp<this._cacheTimeout)return a({},r.result,{executionTime:performance.now()-n,fromCache:!0});var s=[],c=0;if("AND"===e)for(var u,h=o(this._archetypes.values());!(u=h()).done;){var l=u.value;this.archetypeContainsAllComponents(l,t)&&(s.push(l),c+=l.entities.length)}else{for(var d,f=new Set,m=o(t);!(d=m()).done;){var p=d.value,y=this._componentToArchetypes.get(p);if(y)for(var g,v=o(y);!(g=v()).done;){var _=g.value;f.add(_)}}for(var S,E=o(f);!(S=E()).done;){var T=S.value;s.push(T),c+=T.entities.length}}var C={archetypes:s,totalEntities:c,executionTime:performance.now()-n,fromCache:!1};return this._queryCache.set(i,{result:C,timestamp:Date.now()}),C},e.getEntityArchetype=function(t){return this._entityToArchetype.get(t)},e.getAllArchetypes=function(){return Array.from(this._archetypes.values())},e.clear=function(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._queryCache.clear()},e.getEntityComponentTypes=function(t){return t.components.map((function(t){return t.constructor}))},e.generateArchetypeId=function(t){return t.map((function(t){return G(t)})).sort().join("|")},e.createArchetype=function(t){var e=this.generateArchetypeId(t),n={id:e,componentTypes:[].concat(t),entities:[],createdAt:Date.now(),updatedAt:Date.now()};return this._archetypes.set(e,n),n},e.archetypeContainsAllComponents=function(t,e){for(var n,i=o(e);!(n=i()).done;){var r=n.value;if(!t.componentTypes.includes(r))return!1}return!0},e.updateComponentIndexes=function(t,e,n){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)),n?a.add(t):(a.delete(t),0===a.size&&this._componentToArchetypes.delete(s))}},e.invalidateQueryCache=function(){this._queryCache.clear()},t}();!function(t){t[t.COMPONENT_MODIFIED=1]="COMPONENT_MODIFIED",t[t.COMPONENT_ADDED=2]="COMPONENT_ADDED",t[t.COMPONENT_REMOVED=4]="COMPONENT_REMOVED",t[t.TRANSFORM_CHANGED=8]="TRANSFORM_CHANGED",t[t.STATE_CHANGED=16]="STATE_CHANGED",t[t.CUSTOM_1=256]="CUSTOM_1",t[t.CUSTOM_2=512]="CUSTOM_2",t[t.CUSTOM_3=1024]="CUSTOM_3",t[t.ALL=4294967295]="ALL"}(ut||(ut={}));var ft,mt=function(){function t(){this._dirtyEntities=new Map,this._listeners=[],this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0},this._currentFrame=0,this._batchSize=100,this._maxProcessingTime=16,this._processingQueue=[],this._isProcessing=!1}var e=t.prototype;return e.markDirty=function(t,e,n){void 0===n&&(n=[]),this._stats.totalMarkings++;var i=this._dirtyEntities.get(t);i||(i={entity:t,flags:0,modifiedComponents:new Set,timestamp:performance.now(),frameNumber:this._currentFrame},this._dirtyEntities.set(t,i)),i.flags|=e,i.timestamp=performance.now(),i.frameNumber=this._currentFrame;for(var r,s=o(n);!(r=s()).done;){var a=r.value;i.modifiedComponents.add(a)}this.notifyListeners(i,e)},e.isDirty=function(t,e){void 0===e&&(e=ut.ALL);var n=this._dirtyEntities.get(t);return!!n&&0!==(n.flags&e)},e.clearDirty=function(t,e){void 0===e&&(e=ut.ALL);var n=this._dirtyEntities.get(t);n&&(e===ut.ALL?this._dirtyEntities.delete(t):(n.flags&=~e,0===n.flags&&this._dirtyEntities.delete(t)),this._stats.totalCleanups++)},e.getDirtyEntities=function(t){void 0===t&&(t=ut.ALL);for(var e,n=[],i=o(this._dirtyEntities.values());!(e=i()).done;){var r=e.value;0!==(r.flags&t)&&n.push(r)}return n},e.processDirtyEntities=function(){if(!this._isProcessing){this._isProcessing=!0;var t,e=performance.now();if(0===this._processingQueue.length)(t=this._processingQueue).push.apply(t,this._dirtyEntities.values());for(var n=0;this._processingQueue.length>0&&n<this._batchSize;){if(performance.now()-e>this._maxProcessingTime)break;var i=this._processingQueue.shift();this.processEntity(i),n++}0===this._processingQueue.length&&(this._isProcessing=!1,this.onFrameEnd())}},e.addListener=function(t){this._listeners.push(t),this._listeners.sort((function(t,e){return(t.priority||100)-(e.priority||100)}))},e.removeListener=function(t){var e=this._listeners.findIndex((function(e){return e.callback===t}));-1!==e&&this._listeners.splice(e,1)},e.beginFrame=function(){this._currentFrame++},e.endFrame=function(){this._isProcessing||this.processDirtyEntities()},e.getStats=function(){return{dirtyEntityCount:this._dirtyEntities.size,totalMarkings:this._stats.totalMarkings,totalCleanups:this._stats.totalCleanups,listenerCount:this._listeners.length,avgDirtyPerFrame:this._stats.frameCount>0?this._stats.totalDirtyPerFrame/this._stats.frameCount:0,estimatedMemoryUsage:this.estimateMemoryUsage()}},e.clear=function(){this._dirtyEntities.clear(),this._processingQueue.length=0,this._isProcessing=!1,this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0}},e.configureBatchProcessing=function(t,e){this._batchSize=t,this._maxProcessingTime=e},e.processEntity=function(e){for(var n,i=o(this._listeners);!(n=i()).done;){var r=n.value;if(0!==(e.flags&r.flags))try{r.callback(e)}catch(e){t._logger.error("脏数据监听器错误:",e)}}this.clearDirty(e.entity)},e.notifyListeners=function(e,n){for(var i,r=o(this._listeners);!(i=r()).done;){var s=i.value;if(0!==(n&s.flags))try{s.callback(e)}catch(e){t._logger.error("脏数据监听器通知错误:",e)}}},e.onFrameEnd=function(){this._stats.frameCount++,this._stats.totalDirtyPerFrame+=this._dirtyEntities.size},e.estimateMemoryUsage=function(){var t=0;return t+=100*this._dirtyEntities.size,t+=50*this._listeners.length,t+=8*this._processingQueue.length},t}();mt._logger=D("DirtyTrackingSystem"),function(t){t.ALL="all",t.ANY="any",t.NONE="none"}(ft||(ft={}));var pt,yt,gt=function(){function t(){this._logger=D("QuerySystem"),this.entities=[],this.indexDirty=!0,this._version=0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.entityIndex={byMask:new Map,byComponentType:new Map,byTag:new Map,byName:new Map},this.componentPoolManager=st.getInstance(),this.componentIndexManager=new lt,this.archetypeSystem=new dt,this.dirtyTrackingSystem=new mt}var e=t.prototype;return e.setEntities=function(t){this.entities=t,this.clearQueryCache(),this.rebuildIndexes()},e.addEntity=function(t,e){void 0===e&&(e=!1),this.entities.includes(t)||(this.entities.push(t),this.addEntityToIndexes(t),this.componentIndexManager.addEntity(t),this.archetypeSystem.addEntity(t),this.dirtyTrackingSystem.markDirty(t,ut.COMPONENT_ADDED),e||this.clearQueryCache(),this._version++)},e.addEntities=function(t){if(0!==t.length){for(var e,n=new Set(this.entities.map((function(t){return t.id}))),i=0,r=o(t);!(e=r()).done;){var s=e.value;n.has(s.id)||(this.entities.push(s),this.addEntityToIndexes(s),n.add(s.id),i++)}i>0&&this.clearQueryCache()}},e.addEntitiesUnchecked=function(t){if(0!==t.length){for(var e,n=o(t);!(e=n()).done;){var i=e.value;this.entities.push(i)}for(var r,s=o(t);!(r=s()).done;){var a=r.value;this.addEntityToIndexes(a)}this.clearQueryCache()}},e.removeEntity=function(t){var e=this.entities.indexOf(t);-1!==e&&(this.entities.splice(e,1),this.removeEntityFromIndexes(t),this.componentIndexManager.removeEntity(t),this.archetypeSystem.removeEntity(t),this.dirtyTrackingSystem.markDirty(t,ut.COMPONENT_REMOVED),this.clearQueryCache(),this._version++)},e.addEntityToIndexes=function(t){var e=t.componentMask.toString(),n=this.entityIndex.byMask.get(e);n||(n=new Set,this.entityIndex.byMask.set(e,n)),n.add(t);for(var i=t.components,r=0;r<i.length;r++){var s=i[r].constructor,o=this.entityIndex.byComponentType.get(s);o||(o=new Set,this.entityIndex.byComponentType.set(s,o)),o.add(t)}var a=t.tag;if(void 0!==a){var c=this.entityIndex.byTag.get(a);c||(c=new Set,this.entityIndex.byTag.set(a,c)),c.add(t)}var u=t.name;if(u){var h=this.entityIndex.byName.get(u);h||(h=new Set,this.entityIndex.byName.set(u,h)),h.add(t)}},e.removeEntityFromIndexes=function(t){var e=t.componentMask.toString(),n=this.entityIndex.byMask.get(e);n&&(n.delete(t),0===n.size&&this.entityIndex.byMask.delete(e));for(var i,r=o(t.components);!(i=r()).done;){var s=i.value.constructor,a=this.entityIndex.byComponentType.get(s);a&&(a.delete(t),0===a.size&&this.entityIndex.byComponentType.delete(s))}if(void 0!==t.tag){var c=this.entityIndex.byTag.get(t.tag);c&&(c.delete(t),0===c.size&&this.entityIndex.byTag.delete(t.tag))}if(t.name){var u=this.entityIndex.byName.get(t.name);u&&(u.delete(t),0===u.size&&this.entityIndex.byName.delete(t.name))}},e.rebuildIndexes=function(){this.entityIndex.byMask.clear(),this.entityIndex.byComponentType.clear(),this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear(),this.componentIndexManager.clear();for(var t,e=o(this.entities);!(t=e()).done;){var n=t.value;this.addEntityToIndexes(n),this.componentIndexManager.addEntity(n),this.archetypeSystem.addEntity(n)}this.indexDirty=!1},e.queryAll=function(){var t=performance.now();this.queryStats.totalQueries++;for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];var r="all:"+n.map((function(t){return G(t)})).sort().join(","),s=this.getFromCache(r);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};var a=[],c=this.archetypeSystem.queryArchetypes(n,"AND");if(c.archetypes.length>0){this.queryStats.archetypeHits++;for(var u,h=o(c.archetypes);!(u=h()).done;){var l,d=u.value;(l=a).push.apply(l,d.entities)}}else try{if(1===n.length){this.queryStats.indexHits++;var f=this.componentIndexManager.query(n[0]);a=Array.from(f)}else{var m=this.componentIndexManager.queryMultiple(n,"AND");a=Array.from(m)}}catch(t){a=[]}return this.addToCache(r,a),{entities:a,count:a.length,executionTime:performance.now()-t,fromCache:!1}},e.queryMultipleComponents=function(t){for(var e,n=null,i=1/0,r=o(t);!(e=r()).done;){var s=e.value,a=this.entityIndex.byComponentType.get(s);if(!a||0===a.size)return[];a.size<i&&(i=a.size,n=a)}if(!n)return[];for(var c,u=this.createComponentMask(t),h=[],l=o(n);!(c=l()).done;){var d=c.value;M.hasAll(d.componentMask,u)&&h.push(d)}return h},e.queryAny=function(){var t=performance.now();this.queryStats.totalQueries++;for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];var r="any:"+n.map((function(t){return G(t)})).sort().join(","),s=this.getFromCache(r);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};var a,c=this.archetypeSystem.queryArchetypes(n,"OR");if(c.archetypes.length>0){this.queryStats.archetypeHits++,a=[];for(var u,h=o(c.archetypes);!(u=h()).done;){var l,d=u.value;(l=a).push.apply(l,d.entities)}}else{var f=this.componentIndexManager.queryMultiple(n,"OR");a=Array.from(f)}return this.addToCache(r,a),{entities:a,count:a.length,executionTime:performance.now()-t,fromCache:!1}},e.queryNone=function(){var t=performance.now();this.queryStats.totalQueries++;for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];var r="none:"+n.map((function(t){return G(t)})).sort().join(","),s=this.getFromCache(r);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};var o=this.createComponentMask(n),a=this.entities.filter((function(t){return M.hasNone(t.componentMask,o)}));return this.addToCache(r,a),{entities:a,count:a.length,executionTime:performance.now()-t,fromCache:!1}},e.queryByTag=function(t){var e=performance.now();this.queryStats.totalQueries++;var n="tag:"+t,i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byTag.get(t)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!1}},e.queryByName=function(t){var e=performance.now();this.queryStats.totalQueries++;var n="name:"+t,i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byName.get(t)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!1}},e.queryByComponent=function(t){var e=performance.now();this.queryStats.totalQueries++;var n="component:"+G(t),i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byComponentType.get(t)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!1}},e.getFromCache=function(t){var e=this.queryCache.get(t);return e?Date.now()-e.timestamp>this.cacheTimeout?(this.queryCache.delete(t),null):(e.hitCount++,e.entities):null},e.addToCache=function(t,e){this.queryCache.size>=this.cacheMaxSize&&this.cleanupCache(),this.queryCache.set(t,{entities:[].concat(e),timestamp:Date.now(),hitCount:0})},e.cleanupCache=function(){for(var t,e=Date.now(),n=o(this.queryCache.entries());!(t=n()).done;){var i=t.value,r=i[0];e-i[1].timestamp>this.cacheTimeout&&this.queryCache.delete(r)}if(this.queryCache.size>=this.cacheMaxSize){var s=Array.from(this.queryCache.entries());s.sort((function(t,e){return t[1].hitCount-e[1].hitCount}));for(var a=Math.floor(.2*this.cacheMaxSize),c=0;c<a&&c<s.length;c++)this.queryCache.delete(s[c][0])}},e.clearQueryCache=function(){this.queryCache.clear()},e.clearCache=function(){this.clearQueryCache()},e.batchUpdateComponents=function(t){for(var e,n=this,i=[],r=function(){var t=e.value,r=n.entities.find((function(e){return e.id===t.entityId}));r&&(n.removeEntityFromIndexes(r),i.push(r))},s=o(t);!(e=s()).done;)r();for(var a=0,c=i;a<c.length;a++){var u=c[a];this.addEntityToIndexes(u)}for(var h=0,l=i;h<l.length;h++){var d=l[h];this.dirtyTrackingSystem.markDirty(d,ut.COMPONENT_MODIFIED,[])}this.clearQueryCache()},e.createComponentMask=function(t){for(var e,n=M.clone(M.ZERO),i=!1,r=o(t);!(e=r()).done;){var s=e.value;try{var a=X.getBitMask(s);M.orInPlace(n,a),i=!0}catch(t){this._logger.warn("组件类型 "+G(s)+" 未注册,跳过")}}return i?n:{lo:4294967295,hi:4294967295}},e.getAllEntities=function(){return[].concat(this.entities)},e.getStats=function(){return{entityCount:this.entities.length,indexStats:{maskIndexSize:this.entityIndex.byMask.size,componentIndexSize:this.entityIndex.byComponentType.size,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:{componentIndex:this.componentIndexManager.getStats(),archetypeSystem:this.archetypeSystem.getAllArchetypes().map((function(t){return{id:t.id,componentTypes:t.componentTypes.map((function(t){return G(t)})),entityCount:t.entities.length}})),dirtyTracking:this.dirtyTrackingSystem.getStats()},cacheStats:{size:this.queryCache.size,hitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}},e.configureDirtyTracking=function(t,e){this.dirtyTrackingSystem.configureBatchProcessing(t,e)},e.optimizePerformance=function(){this.dirtyTrackingSystem.processDirtyEntities(),this.cleanupCache(),this.componentIndexManager.getStats()},e.beginFrame=function(){this.dirtyTrackingSystem.beginFrame()},e.endFrame=function(){this.dirtyTrackingSystem.endFrame()},e.markEntityDirty=function(t,e){this.queryStats.dirtyChecks++,this.dirtyTrackingSystem.markDirty(t,ut.COMPONENT_MODIFIED,e),this.clearQueryCache()},e.getEntityArchetype=function(t){return this.archetypeSystem.getEntityArchetype(t)},s(t,[{key:"version",get:function(){return this._version}}])}(),vt=function(){function t(t){this._logger=D("QueryBuilder"),this.conditions=[],this.querySystem=t}var e=t.prototype;return e.withAll=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return this.conditions.push({type:ft.ALL,componentTypes:e,mask:this.createComponentMask(e)}),this},e.withAny=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return this.conditions.push({type:ft.ANY,componentTypes:e,mask:this.createComponentMask(e)}),this},e.without=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return this.conditions.push({type:ft.NONE,componentTypes:e,mask:this.createComponentMask(e)}),this},e.execute=function(){var t,e,n,i=performance.now();if(1===this.conditions.length){var r=this.conditions[0];switch(r.type){case ft.ALL:return(t=this.querySystem).queryAll.apply(t,r.componentTypes);case ft.ANY:return(e=this.querySystem).queryAny.apply(e,r.componentTypes);case ft.NONE:return(n=this.querySystem).queryNone.apply(n,r.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-i,fromCache:!1}},e.createComponentMask=function(t){for(var e,n=M.clone(M.ZERO),i=o(t);!(e=i()).done;){var r=e.value;try{var s=X.getBitMask(r);M.orInPlace(n,s)}catch(t){this._logger.warn("组件类型 "+G(r)+" 未注册,跳过")}}return n},e.reset=function(){return this.conditions=[],this},t}(),_t=function(){function t(){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 e=t.prototype;return e.on=function(t,e,n){return void 0===n&&(n={}),this.addListener(t,e,n)},e.once=function(t,e,n){return void 0===n&&(n={}),this.addListener(t,e,a({},n,{once:!0}))},e.onAsync=function(t,e,n){return void 0===n&&(n={}),this.addListener(t,e,a({},n,{async:!0}))},e.off=function(t,e){var n=this.listeners.get(t);if(!n)return!1;var i=n.findIndex((function(t){return t.id===e}));return-1!==i&&(n.splice(i,1),0===n.length&&(this.listeners.delete(t),this.stats.delete(t)),!0)},e.offAll=function(t){this.listeners.delete(t),this.stats.delete(t),this.clearBatch(t)},e.emit=function(){var t=n(l().m((function t(e,n){var i;return l().w((function(t){for(;;)switch(t.n){case 0:if(this.isEnabled){t.n=1;break}return t.a(2);case 1:if(null==(i=this.batchConfigs.get(e))||!i.enabled){t.n=2;break}return this.addToBatch(e,n),t.a(2);case 2:return t.n=3,this.executeEvent(e,n);case 3:return t.a(2)}}),t,this)})));return function(e,n){return t.apply(this,arguments)}}(),e.emitSync=function(e,n){if(this.isEnabled){var i=this.listeners.get(e);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){t._logger.error("事件处理器执行错误 "+e+":",n)}}this.removeListeners(e,a),this.updateStats(e,performance.now()-s)}}},e.setBatchConfig=function(t,e){this.batchConfigs.set(t,e)},e.flushBatch=function(t){var e=this.batchQueue.get(t);if(e&&0!==e.length){var n=this.batchTimers.get(t);n&&(clearTimeout(n),this.batchTimers.delete(t)),this.processBatch(t,e),this.batchQueue.delete(t)}},e.getStats=function(t){return t?this.stats.get(t)||this.createEmptyStats(t):new Map(this.stats)},e.resetStats=function(t){t?this.stats.delete(t):this.stats.clear()},e.setEnabled=function(t){this.isEnabled=t},e.hasListeners=function(t){var e=this.listeners.get(t);return!!e&&e.length>0},e.getListenerCount=function(t){var e=this.listeners.get(t);return e?e.length:0},e.clear=function(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()},e.setMaxListeners=function(t){this.maxListeners=t},e.addListener=function(e,n,i){var r=this.listeners.get(e);if(r||(r=[],this.listeners.set(e,r)),r.length>=this.maxListeners)return t._logger.warn("事件类型 "+e+" 的监听器数量超过最大限制 ("+this.maxListeners+")"),"";var s="listener_"+this.nextListenerId++,o={handler:n,config:a({priority:0},i),id:s};return r.push(o),this.stats.has(e)||this.stats.set(e,this.createEmptyStats(e)),s},e.executeEvent=function(){var e=n(l().m((function e(i,r){var s,a,c,u,h,d,f,m,p,y;return l().w((function(e){for(;;)switch(e.n){case 0:if((s=this.listeners.get(i))&&0!==s.length){e.n=1;break}return e.a(2);case 1:for(a=performance.now(),c=[],u=this.sortListenersByPriority(s),h=u.filter((function(t){return!t.config.async})),d=u.filter((function(t){return t.config.async})),f=o(h);!(m=f()).done;){p=m.value;try{p.config.context?p.handler.call(p.config.context,r):p.handler(r),p.config.once&&c.push(p.id)}catch(e){t._logger.error("同步事件处理器执行错误 "+i+":",e)}}return y=d.map(function(){var e=n(l().m((function e(n){var s;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(e.p=0,!n.config.context){e.n=2;break}return e.n=1,n.handler.call(n.config.context,r);case 1:e.n=3;break;case 2:return e.n=3,n.handler(r);case 3:n.config.once&&c.push(n.id),e.n=5;break;case 4:e.p=4,s=e.v,t._logger.error("异步事件处理器执行错误 "+i+":",s);case 5:return e.a(2)}}),e,null,[[0,4]])})));return function(t){return e.apply(this,arguments)}}()),e.n=2,Promise.all(y);case 2:this.removeListeners(i,c),this.updateStats(i,performance.now()-a);case 3:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),e.sortListenersByPriority=function(t){return t.slice().sort((function(t,e){return(e.config.priority||0)-(t.config.priority||0)}))},e.removeListeners=function(t,e){if(0!==e.length){var n=this.listeners.get(t);if(n){for(var i,r=function(){var t=i.value,e=n.findIndex((function(e){return e.id===t}));-1!==e&&n.splice(e,1)},s=o(e);!(i=s()).done;)r();0===n.length&&(this.listeners.delete(t),this.stats.delete(t))}}},e.addToBatch=function(t,e){var n=this,i=this.batchQueue.get(t);i||(i=[],this.batchQueue.set(t,i)),i.push(e);var r=this.batchConfigs.get(t);if(i.length>=r.batchSize)this.flushBatch(t);else if(!this.batchTimers.has(t)){var s=setTimeout((function(){n.flushBatch(t)}),r.delay);this.batchTimers.set(t,s)}},e.processBatch=function(){var t=n(l().m((function t(e,n){var i;return l().w((function(t){for(;;)switch(t.n){case 0:return i={type:e,events:n,count:n.length,timestamp:Date.now()},t.n=1,this.executeEvent(e+":batch",i);case 1:return t.a(2)}}),t,this)})));return function(e,n){return t.apply(this,arguments)}}(),e.clearBatch=function(t){this.batchQueue.delete(t);var e=this.batchTimers.get(t);e&&(clearTimeout(e),this.batchTimers.delete(t))},e.clearAllBatches=function(){this.batchQueue.clear();for(var t,e=o(this.batchTimers.values());!(t=e()).done;){var n=t.value;clearTimeout(n)}this.batchTimers.clear(),this.batchConfigs.clear()},e.updateStats=function(t,e){var n=this.stats.get(t);n||(n=this.createEmptyStats(t),this.stats.set(t,n)),n.triggerCount++,n.totalExecutionTime+=e,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(t)},e.createEmptyStats=function(t){return{eventType:t,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}},t}();_t._logger=D("EventSystem"),function(t){t.ENTITY_CREATED="entity:created",t.ENTITY_DESTROYED="entity:destroyed",t.ENTITY_ENABLED="entity:enabled",t.ENTITY_DISABLED="entity:disabled",t.ENTITY_TAG_ADDED="entity:tag:added",t.ENTITY_TAG_REMOVED="entity:tag:removed",t.ENTITY_NAME_CHANGED="entity:name:changed",t.COMPONENT_ADDED="component:added",t.COMPONENT_REMOVED="component:removed",t.COMPONENT_MODIFIED="component:modified",t.COMPONENT_ENABLED="component:enabled",t.COMPONENT_DISABLED="component:disabled",t.SYSTEM_ADDED="system:added",t.SYSTEM_REMOVED="system:removed",t.SYSTEM_ENABLED="system:enabled",t.SYSTEM_DISABLED="system:disabled",t.SYSTEM_PROCESSING_START="system:processing:start",t.SYSTEM_PROCESSING_END="system:processing:end",t.SYSTEM_ERROR="system:error",t.SCENE_CREATED="scene:created",t.SCENE_DESTROYED="scene:destroyed",t.SCENE_ACTIVATED="scene:activated",t.SCENE_DEACTIVATED="scene:deactivated",t.SCENE_PAUSED="scene:paused",t.SCENE_RESUMED="scene:resumed",t.QUERY_EXECUTED="query:executed",t.QUERY_CACHE_HIT="query:cache:hit",t.QUERY_CACHE_MISS="query:cache:miss",t.QUERY_OPTIMIZED="query:optimized",t.PERFORMANCE_WARNING="performance:warning",t.PERFORMANCE_CRITICAL="performance:critical",t.MEMORY_USAGE_HIGH="memory:usage:high",t.FRAME_RATE_DROP="frame:rate:drop",t.INDEX_CREATED="index:created",t.INDEX_UPDATED="index:updated",t.INDEX_OPTIMIZED="index:optimized",t.ARCHETYPE_CREATED="archetype:created",t.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",t.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",t.DIRTY_MARK_ADDED="dirty:mark:added",t.DIRTY_BATCH_PROCESSED="dirty:batch:processed",t.ERROR_OCCURRED="error:occurred",t.WARNING_ISSUED="warning:issued",t.FRAMEWORK_INITIALIZED="framework:initialized",t.FRAMEWORK_SHUTDOWN="framework:shutdown",t.DEBUG_INFO="debug:info",t.DEBUG_STATS_UPDATED="debug:stats:updated"}(pt||(pt={})),function(t){t[t.LOWEST=0]="LOWEST",t[t.LOW=25]="LOW",t[t.NORMAL=50]="NORMAL",t[t.HIGH=75]="HIGH",t[t.HIGHEST=100]="HIGHEST",t[t.CRITICAL=200]="CRITICAL"}(yt||(yt={}));var St={ENTITY:{CREATED:pt.ENTITY_CREATED,DESTROYED:pt.ENTITY_DESTROYED,ENABLED:pt.ENTITY_ENABLED,DISABLED:pt.ENTITY_DISABLED,TAG_ADDED:pt.ENTITY_TAG_ADDED,TAG_REMOVED:pt.ENTITY_TAG_REMOVED,NAME_CHANGED:pt.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:pt.COMPONENT_ADDED,REMOVED:pt.COMPONENT_REMOVED,MODIFIED:pt.COMPONENT_MODIFIED,ENABLED:pt.COMPONENT_ENABLED,DISABLED:pt.COMPONENT_DISABLED},SYSTEM:{ADDED:pt.SYSTEM_ADDED,REMOVED:pt.SYSTEM_REMOVED,ENABLED:pt.SYSTEM_ENABLED,DISABLED:pt.SYSTEM_DISABLED,PROCESSING_START:pt.SYSTEM_PROCESSING_START,PROCESSING_END:pt.SYSTEM_PROCESSING_END,ERROR:pt.SYSTEM_ERROR},PERFORMANCE:{WARNING:pt.PERFORMANCE_WARNING,CRITICAL:pt.PERFORMANCE_CRITICAL,MEMORY_HIGH:pt.MEMORY_USAGE_HIGH,FRAME_DROP:pt.FRAME_RATE_DROP}},Et=function(){function t(){}return t.isValid=function(t){return this.validTypes.has(t)},t.getAllValidTypes=function(){return Array.from(this.validTypes)},t.addCustomType=function(t){this.validTypes.add(t)},t.removeCustomType=function(t){this.validTypes.delete(t)},t}();Et.validTypes=new Set([].concat(Object.values(pt),Object.values(St.ENTITY),Object.values(St.COMPONENT),Object.values(St.SYSTEM),Object.values(St.PERFORMANCE)));var Tt=function(){function t(t){void 0===t&&(t=!1),this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new _t,this.isDebugMode=t}var e=t.prototype;return e.emit=function(e,n){this.validateEventType(e);var i=this.enhanceEventData(e,n);this.isDebugMode&&t._logger.info("发射事件: "+e,i),this.eventSystem.emitSync(e,i)},e.emitAsync=function(){var e=n(l().m((function e(n,i){var r;return l().w((function(e){for(;;)switch(e.n){case 0:return this.validateEventType(n),r=this.enhanceEventData(n,i),this.isDebugMode&&t._logger.info("发射异步事件: "+n,r),e.n=1,this.eventSystem.emit(n,r);case 1:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),e.on=function(e,n,i){void 0===i&&(i={}),this.validateEventType(e);var r={once:i.once||!1,priority:i.priority||yt.NORMAL,async:i.async||!1,context:i.context};return this.isDebugMode&&t._logger.info("添加监听器: "+e,r),this.eventSystem.on(e,n,r)},e.once=function(t,e,n){return void 0===n&&(n={}),this.on(t,e,a({},n,{once:!0}))},e.onAsync=function(t,e,n){return void 0===n&&(n={}),this.on(t,e,a({},n,{async:!0}))},e.off=function(e,n){return this.isDebugMode&&t._logger.info("移除监听器: "+n+" 事件: "+e),this.eventSystem.off(e,n)},e.offAll=function(e){this.isDebugMode&&t._logger.info("移除所有监听器: "+e),this.eventSystem.offAll(e)},e.hasListeners=function(t){return this.eventSystem.hasListeners(t)},e.getStats=function(t){var e=this,n=this.eventSystem.getStats(t);if(n instanceof Map){var i=new Map;return n.forEach((function(t,n){i.set(n,e.convertEventStats(t))})),i}return this.convertEventStats(n)},e.clear=function(){this.isDebugMode&&t._logger.info("清空所有监听器"),this.eventSystem.clear()},e.setEnabled=function(t){this.eventSystem.setEnabled(t)},e.setDebugMode=function(t){this.isDebugMode=t},e.setMaxListeners=function(t){this.eventSystem.setMaxListeners(t)},e.getListenerCount=function(t){return this.eventSystem.getListenerCount(t)},e.setBatchConfig=function(t,e,n){this.eventSystem.setBatchConfig(t,{batchSize:e,delay:n,enabled:!0})},e.flushBatch=function(t){this.eventSystem.flushBatch(t)},e.resetStats=function(t){this.eventSystem.resetStats(t)},e.emitEntityCreated=function(t){this.emit(pt.ENTITY_CREATED,t)},e.emitEntityDestroyed=function(t){this.emit(pt.ENTITY_DESTROYED,t)},e.emitComponentAdded=function(t){this.emit(pt.COMPONENT_ADDED,t)},e.emitComponentRemoved=function(t){this.emit(pt.COMPONENT_REMOVED,t)},e.emitSystemAdded=function(t){this.emit(pt.SYSTEM_ADDED,t)},e.emitSystemRemoved=function(t){this.emit(pt.SYSTEM_REMOVED,t)},e.emitSceneChanged=function(t){this.emit(pt.SCENE_ACTIVATED,t)},e.emitPerformanceWarning=function(t){this.emit(pt.PERFORMANCE_WARNING,t)},e.onEntityCreated=function(t,e){return this.on(pt.ENTITY_CREATED,t,e)},e.onComponentAdded=function(t,e){return this.on(pt.COMPONENT_ADDED,t,e)},e.onSystemError=function(t,e){return this.on(pt.SYSTEM_ERROR,t,e)},e.onPerformanceWarning=function(t,e){return this.on(pt.PERFORMANCE_WARNING,t,e)},e.validateEventType=function(e){Et.isValid(e)||(this.isDebugMode&&t._logger.warn("未知事件类型: "+e),this.isDebugMode&&Et.addCustomType(e))},e.enhanceEventData=function(t,e){if(null==e)return{timestamp:Date.now(),eventId:t+"_"+ ++this.eventIdCounter,source:"EventBus"};var n=e;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=t+"_"+ ++this.eventIdCounter),n.source||(n.source="EventBus"),n},e.convertEventStats=function(t){return{eventType:t.eventType,listenerCount:t.listenerCount,triggerCount:t.triggerCount,totalExecutionTime:t.totalExecutionTime,averageExecutionTime:t.averageExecutionTime,lastTriggerTime:t.lastTriggerTime}},t}();Tt._logger=D("EventBus");var Ct=function(){function t(){}return t.getInstance=function(t){return void 0===t&&(t=!1),this.instance||(this.instance=new Tt(t)),this.instance},t.reset=function(t){return void 0===t&&(t=!1),this.instance&&this.instance.clear(),this.instance=new Tt(t),this.instance},t}();function bt(t,e){return void 0===e&&(e={}),function(n,i,r){var s=r.value,o=n.constructor.prototype.initEventListeners||function(){};return n.constructor.prototype.initEventListeners=function(){o.call(this),Ct.getInstance().on(t,s.bind(this),e)},r}}function Mt(t,e){return void 0===e&&(e={}),function(n,i,r){var s=r.value,o=n.constructor.prototype.initEventListeners||function(){};return n.constructor.prototype.initEventListeners=function(){o.call(this),Ct.getInstance().onAsync(t,s.bind(this),e)},r}}var wt=function(){function t(t){var e=this;this.name="",this._didSceneBegin=!1,this.entities=new et(this),this.entityProcessors=new nt,this.identifierPool=new it,this.componentStorageManager=new J,this.querySystem=new gt,this.eventSystem=new _t,null!=t&&t.name&&(this.name=t.name),$.eventBus||($.eventBus=new Tt(!1)),$.eventBus&&$.eventBus.onComponentAdded((function(t){e.eventSystem.emitSync("component:added",t)}))}var e=t.prototype;return e.initialize=function(){},e.onStart=function(){},e.unload=function(){},e.begin=function(){null!=this.entityProcessors&&this.entityProcessors.begin(),this._didSceneBegin=!0,this.onStart()},e.end=function(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this.entityProcessors&&this.entityProcessors.end(),this.unload()},e.update=function(){this.entities.updateLists(),null!=this.entityProcessors&&this.entityProcessors.update(),this.entities.update(),null!=this.entityProcessors&&this.entityProcessors.lateUpdate()},e.createEntity=function(t){var e=new $(t,this.identifierPool.checkOut());return this.eventSystem.emitSync("entity:created",{entityName:t,entity:e,scene:this}),this.addEntity(e)},e.addEntity=function(t,e){return void 0===e&&(e=!1),this.entities.add(t),t.scene=this,this.querySystem.addEntity(t,e),this.eventSystem.emitSync("entity:added",{entity:t,scene:this}),t},e.createEntities=function(t,e){void 0===e&&(e="Entity");for(var n=[],i=0;i<t;i++){var r=new $(e+"_"+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:t}),n},e.destroyAllEntities=function(){this.entities.removeAllEntities(),this.querySystem.setEntities([])},e.findEntity=function(t){return this.entities.findEntity(t)},e.findEntityById=function(t){return this.entities.findEntityById(t)},e.findEntitiesByTag=function(t){for(var e,n=[],i=o(this.entities.buffer);!(e=i()).done;){var r=e.value;r.tag===t&&n.push(r)}return n},e.getEntityByName=function(t){return this.findEntity(t)},e.getEntitiesByTag=function(t){return this.findEntitiesByTag(t)},e.addEntityProcessor=function(t){return this.entityProcessors.processors.includes(t)||(t.scene=this,this.entityProcessors.add(t),t.initialize(),t.setUpdateOrder(this.entityProcessors.count-1)),t},e.addSystem=function(t){return this.addEntityProcessor(t)},e.removeEntityProcessor=function(t){this.entityProcessors.remove(t),t.reset(),t.scene=null},e.getEntityProcessor=function(t){return this.entityProcessors.getProcessor(t)},e.getStats=function(){return{entityCount:this.entities.count,processorCount:this.entityProcessors.count,componentStorageStats:this.componentStorageManager.getAllStats()}},e.getDebugInfo=function(){return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:this.entityProcessors.count,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((function(t){return{name:t.name,id:t.id,componentCount:t.components.length,componentTypes:t.components.map((function(t){return Q(t)}))}})),processors:this.entityProcessors.processors.map((function(t){var e;return{name:V(t),updateOrder:t.updateOrder,entityCount:(null===(e=t._entities)||void 0===e?void 0:e.length)||0}})),componentStats:this.componentStorageManager.getAllStats()}},s(t,[{key:"systems",get:function(){return this.entityProcessors.processors}}])}(),It=function(){function t(){this.scene=new wt}var e=t.prototype;return e.named=function(t){return this.scene.name=t,this},e.withEntity=function(t){return this.scene.addEntity(t),this},e.withEntityBuilder=function(t){var e=t(new tt(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(e),this},e.withEntities=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var i=0,r=e;i<r.length;i++){var s=r[i];this.scene.addEntity(s)}return this},e.withSystem=function(t){return this.scene.addSystem(t),this},e.withSystems=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var i=0,r=e;i<r.length;i++){var s=r[i];this.scene.addSystem(s)}return this},e.build=function(){return this.scene},t}(),At=function(){function t(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];this.component=i(t,n)}var e=t.prototype;return e.set=function(t,e){return this.component[t]=e,this},e.configure=function(t){return t(this.component),this},e.setIf=function(t,e,n){return t&&(this.component[e]=n),this},e.build=function(){return this.component},t}(),xt=function(){function t(t){this.entities=t}var e=t.prototype;return e.addComponent=function(t){for(var e,n=o(this.entities);!(e=n()).done;){e.value.addComponent(t)}return this},e.removeComponent=function(t){for(var e,n=o(this.entities);!(e=n()).done;){e.value.removeComponentByType(t)}return this},e.setActive=function(t){for(var e,n=o(this.entities);!(e=n()).done;){e.value.active=t}return this},e.setTag=function(t){for(var e,n=o(this.entities);!(e=n()).done;){e.value.tag=t}return this},e.forEach=function(t){return this.entities.forEach(t),this},e.filter=function(e){return new t(this.entities.filter(e))},e.toArray=function(){return this.entities.slice()},e.count=function(){return this.entities.length},t}(),Dt=function(){function t(t,e,n){this.scene=t,this.querySystem=e,this.eventSystem=n}var e=t.prototype;return e.createEntity=function(){return new tt(this.scene,this.scene.componentStorageManager)},e.createScene=function(){return new It},e.createComponent=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return i(At,[t].concat(n))},e.query=function(){return new vt(this.querySystem)},e.find=function(){var t;return(t=this.querySystem).queryAll.apply(t,arguments).entities},e.findFirst=function(){var t,e=(t=this.querySystem).queryAll.apply(t,arguments);return e.entities.length>0?e.entities[0]:null},e.findByName=function(t){return this.scene.findEntity(t)},e.findByTag=function(t){return this.scene.findEntitiesByTag(t)},e.emit=function(t,e){this.eventSystem.emitSync(t,e)},e.emitAsync=function(){var t=n(l().m((function t(e,n){return l().w((function(t){for(;;)switch(t.n){case 0:return t.n=1,this.eventSystem.emit(e,n);case 1:return t.a(2)}}),t,this)})));return function(e,n){return t.apply(this,arguments)}}(),e.on=function(t,e){return this.eventSystem.on(t,e)},e.once=function(t,e){return this.eventSystem.once(t,e)},e.off=function(t,e){this.eventSystem.off(t,e)},e.batch=function(t){return new xt(t)},e.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()}},t}();function Ot(t,e,n){return new Dt(t,e,n)}var kt=D("World"),Nt=function(){function t(t){void 0===t&&(t={}),this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config=a({name:"World",debug:!1,maxScenes:10,autoCleanup:!0},t),this.name=this._config.name,this._createdAt=Date.now(),kt.info("创建World: "+this.name)}var e=t.prototype;return e.createScene=function(t,e){if(this._scenes.has(t))throw new Error("Scene ID '"+t+"' 已存在于World '"+this.name+"' 中");if(this._scenes.size>=this._config.maxScenes)throw new Error("World '"+this.name+"' 已达到最大Scene数量限制: "+this._config.maxScenes);var n=e||new wt;return"id"in n&&(n.id=t),"name"in n&&!n.name&&(n.name=t),this._scenes.set(t,n),n.initialize(),kt.info("在World '"+this.name+"' 中创建Scene: "+t),n},e.removeScene=function(t){var e=this._scenes.get(t);return!!e&&(this._activeScenes.has(t)&&this.setSceneActive(t,!1),e.end(),this._scenes.delete(t),kt.info("从World '"+this.name+"' 中移除Scene: "+t),!0)},e.getScene=function(t){return this._scenes.get(t)||null},e.getSceneIds=function(){return Array.from(this._scenes.keys())},e.getAllScenes=function(){return Array.from(this._scenes.values())},e.setSceneActive=function(t,e){var n=this._scenes.get(t);n?e?(this._activeScenes.add(t),n.begin&&n.begin(),kt.debug("在World '"+this.name+"' 中激活Scene: "+t)):(this._activeScenes.delete(t),kt.debug("在World '"+this.name+"' 中停用Scene: "+t)):kt.warn("Scene '"+t+"' 不存在于World '"+this.name+"' 中")},e.isSceneActive=function(t){return this._activeScenes.has(t)},e.getActiveSceneCount=function(){return this._activeScenes.size},e.addGlobalSystem=function(t){return this._globalSystems.includes(t)||(this._globalSystems.push(t),t.initialize&&t.initialize(),kt.debug("在World '"+this.name+"' 中添加全局System: "+t.name)),t},e.removeGlobalSystem=function(t){var e=this._globalSystems.indexOf(t);return-1!==e&&(this._globalSystems.splice(e,1),t.reset&&t.reset(),kt.debug("从World '"+this.name+"' 中移除全局System: "+t.name),!0)},e.getGlobalSystem=function(t){for(var e,n=o(this._globalSystems);!(e=n()).done;){var i=e.value;if(i instanceof t)return i}return null},e.start=function(){if(!this._isActive){this._isActive=!0;for(var t,e=o(this._globalSystems);!(t=e()).done;){var n=t.value;n.initialize&&n.initialize()}kt.info("启动World: "+this.name)}},e.stop=function(){if(this._isActive){for(var t,e=o(this._activeScenes);!(t=e()).done;){var n=t.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,kt.info("停止World: "+this.name)}},e.updateGlobalSystems=function(){if(this._isActive)for(var t,e=o(this._globalSystems);!(t=e()).done;){var n=t.value;n.update&&n.update()}},e.updateScenes=function(){if(this._isActive){for(var t,e=o(this._activeScenes);!(t=e()).done;){var n=t.value,i=this._scenes.get(n);i&&i.update&&i.update()}this._config.autoCleanup&&this.shouldAutoCleanup()&&this.cleanup()}},e.destroy=function(){kt.info("销毁World: "+this.name),this.stop();for(var t=0,e=Array.from(this._scenes.keys());t<e.length;t++){var n=e[t];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()},e.getStatus=function(){var t=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(e){var n;return{id:e,isActive:t._activeScenes.has(e),name:(null===(n=t._scenes.get(e))||void 0===n?void 0:n.name)||e}}))}},e.getStats=function(){for(var t,e={totalEntities:0,totalSystems:this._globalSystems.length,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}},n=o(this._scenes.values());!(t=n()).done;){var i=t.value;i.entities&&(e.totalEntities+=i.entities.count),i.systems&&(e.totalSystems+=i.systems.length)}return e},e.shouldAutoCleanup=function(){for(var t,e=Date.now(),n=o(this._scenes);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];if(!this._activeScenes.has(r)&&s.entities&&0===s.entities.count&&e-this._createdAt>3e5)return!0}return!1},e.cleanup=function(){for(var t=Array.from(this._scenes.keys()),e=Date.now(),n=0,i=t;n<i.length;n++){var r=i[n],s=this._scenes.get(r);s&&!this._activeScenes.has(r)&&s.entities&&0===s.entities.count&&e-this._createdAt>3e5&&(this.removeScene(r),kt.debug("自动清理空Scene: "+r+" from World "+this.name))}},s(t,[{key:"isActive",get:function(){return this._isActive}},{key:"sceneCount",get:function(){return this._scenes.size}},{key:"createdAt",get:function(){return this._createdAt}}])}(),Rt=D("WorldManager"),Pt=function(){function t(t){void 0===t&&(t={}),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},t),Rt.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupInterval:this._config.cleanupInterval}),this.startCleanupTimer()}t.getInstance=function(e){return this._instance||(this._instance=new t(e)),this._instance},t.reset=function(){this._instance&&(this._instance.destroy(),this._instance=null)};var e=t.prototype;return e.createWorld=function(t,e){if(!t||"string"!=typeof t||""===t.trim())throw new Error("World ID不能为空");if(this._worlds.has(t))throw new Error("World ID '"+t+"' 已存在");if(this._worlds.size>=this._config.maxWorlds)throw new Error("已达到最大World数量限制: "+this._config.maxWorlds);var n=a({name:t,debug:this._config.debug},e),i=new Nt(n);return this._worlds.set(t,i),Rt.info("创建World: "+t,{config:n}),i},e.removeWorld=function(t){var e=this._worlds.get(t);return!!e&&(this._activeWorlds.has(t)&&this.setWorldActive(t,!1),e.destroy(),this._worlds.delete(t),Rt.info("移除World: "+t),!0)},e.getWorld=function(t){return this._worlds.get(t)||null},e.getWorldIds=function(){return Array.from(this._worlds.keys())},e.getAllWorlds=function(){return Array.from(this._worlds.values())},e.setWorldActive=function(t,e){var n=this._worlds.get(t);n?e?(this._activeWorlds.add(t),n.start(),Rt.debug("激活World: "+t)):(this._activeWorlds.delete(t),n.stop(),Rt.debug("停用World: "+t)):Rt.warn("World '"+t+"' 不存在")},e.isWorldActive=function(t){return this._activeWorlds.has(t)},e.getActiveWorlds=function(){for(var t,e=[],n=o(this._activeWorlds);!(t=n()).done;){var i=t.value,r=this._worlds.get(i);r&&e.push(r)}return e},e.startAll=function(){this._isRunning=!0;for(var t,e=o(this._worlds.keys());!(t=e()).done;){var n=t.value;this.setWorldActive(n,!0)}Rt.info("启动所有World")},e.stopAll=function(){this._isRunning=!1;for(var t,e=o(this._activeWorlds);!(t=e()).done;){var n=t.value;this.setWorldActive(n,!1)}Rt.info("停止所有World")},e.findWorlds=function(t){for(var e,n=[],i=o(this._worlds.values());!(e=i()).done;){var r=e.value;t(r)&&n.push(r)}return n},e.findWorldByName=function(t){for(var e,n=o(this._worlds.values());!(e=n()).done;){var i=e.value;if(i.name===t)return i}return null},e.getStats=function(){for(var t,e={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);!(t=n()).done;){var i=t.value,r=i[0],s=i[1],c=s.getStats();e.totalScenes+=c.totalSystems,e.totalEntities+=c.totalEntities,e.totalSystems+=c.totalSystems,e.worlds.push(a({id:r,name:s.name,isActive:this._activeWorlds.has(r),sceneCount:s.sceneCount},c))}return e},e.getDetailedStatus=function(){var t=this;return a({},this.getStats(),{worlds:Array.from(this._worlds.entries()).map((function(e){var n=e[0],i=e[1];return{id:n,isActive:t._activeWorlds.has(n),status:i.getStatus()}}))})},e.cleanup=function(){for(var t,e=[],n=o(this._worlds);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];this.shouldCleanupWorld(s)&&e.push(r)}for(var a=0,c=e;a<c.length;a++){var u=c[a];this.removeWorld(u)}return e.length>0&&Rt.debug("清理了 "+e.length+" 个World"),e.length},e.destroy=function(){Rt.info("正在销毁WorldManager..."),this.stopCleanupTimer(),this.stopAll();for(var t=0,e=Array.from(this._worlds.keys());t<e.length;t++){var n=e[t];this.removeWorld(n)}this._worlds.clear(),this._activeWorlds.clear(),this._isRunning=!1,Rt.info("WorldManager已销毁")},e.startCleanupTimer=function(){var t=this;this._config.autoCleanup&&!this._cleanupTimer&&(this._cleanupTimer=setInterval((function(){t.cleanup()}),this._config.cleanupInterval),Rt.debug("启动World清理定时器,间隔: "+this._config.cleanupInterval+"ms"))},e.stopCleanupTimer=function(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null,Rt.debug("停止World清理定时器"))},e.shouldCleanupWorld=function(t){return!t.isActive&&((0===t.sceneCount||!t.getAllScenes().some((function(t){return t.entities&&t.entities.count>0})))&&Date.now()-t.createdAt>6e5)},s(t,[{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)}}])}();Pt._instance=null;var zt=function(){function t(t){if(t&&"object"==typeof t)this._value=M.clone(t);else if("number"==typeof t)this._value=M.fromNumber(t);else if("string"==typeof t){var e=parseInt(t,10);this._value=M.fromNumber(e)}else this._value=M.clone(M.ZERO)}var e=t.prototype;return e.set=function(t){if(t<0)throw new Error("Bit index cannot be negative");if(t>=64)throw new Error("Bit index exceeds 64-bit limit. ECS framework supports max 64 component types.");M.setBit(this._value,t)},e.clear=function(t){if(t<0)throw new Error("Bit index cannot be negative");t>=64||M.clearBit(this._value,t)},e.get=function(t){if(t<0||t>=64)return!1;var e=M.create(t);return M.hasAny(this._value,e)},e.containsAll=function(t){return M.hasAll(this._value,t._value)},e.intersects=function(t){return M.hasAny(this._value,t._value)},e.excludes=function(t){return M.hasNone(this._value,t._value)},e.clearAll=function(){M.clear(this._value)},e.isEmpty=function(){return M.isZero(this._value)},e.cardinality=function(){return M.popCount(this._value)},e.and=function(e){var n=new t;return M.copy(this._value,n._value),M.andInPlace(n._value,e._value),n},e.or=function(e){var n=new t;return M.copy(this._value,n._value),M.orInPlace(n._value,e._value),n},e.xor=function(e){var n=new t;return M.copy(this._value,n._value),M.xorInPlace(n._value,e._value),n},e.not=function(e){void 0===e&&(e=64),e>64&&(e=64);var n=new t;if(M.copy(this._value,n._value),e<=32){var i=(1<<e)-1;n._value.lo=~n._value.lo&i,n._value.hi=0}else if(n._value.lo=~n._value.lo,e<64){var r=(1<<e-32)-1;n._value.hi=~n._value.hi&r}else n._value.hi=~n._value.hi;return n},e.copyFrom=function(t){M.copy(t._value,this._value)},e.clone=function(){return new t(this._value)},e.getValue=function(){return this._value},e.setValue=function(t){if("object"==typeof t)M.copy(t,this._value);else if("number"==typeof t)this._value=M.fromNumber(t);else{var e=parseInt(t,10);this._value=M.fromNumber(e)}},e.toString=function(){for(var t=[],e=0;e<64;e++)this.get(e)&&t.push(e.toString());return"Bits["+t.join(", ")+"]"},e.toBinaryString=function(t){void 0===t&&(t=64),t>64&&(t=64);for(var e="",n=t-1;n>=0;n--)e+=this.get(n)?"1":"0",n%8==0&&n>0&&(e+=" ");return e},e.toHexString=function(){return M.toString(this._value,16)},t.fromBinaryString=function(e){var n,i=e.replace(/\s/g,"");if(i.length<=32){n={lo:parseInt(i,2)>>>0,hi:0}}else{var r=i.substring(i.length-32),s=i.substring(0,i.length-32);n={lo:parseInt(r,2)>>>0,hi:parseInt(s,2)>>>0}}return new t(n)},t.fromHexString=function(e){var n,i=e.replace(/^0x/i,"");if(i.length<=8){n={lo:parseInt(i,16)>>>0,hi:0}}else{var r=i.substring(i.length-8),s=i.substring(0,i.length-8);n={lo:parseInt(r,16)>>>0,hi:parseInt(s,16)>>>0}}return new t(n)},e.equals=function(t){return M.equals(this._value,t._value)},e.getHighestBitIndex=function(){if(M.isZero(this._value))return-1;if(0!==this._value.hi)for(var t=31;t>=0;t--)if(this._value.hi&1<<t)return t+32;for(var e=31;e>=0;e--)if(this._value.lo&1<<e)return e;return-1},e.getLowestBitIndex=function(){if(M.isZero(this._value))return-1;for(var t=0;t<32;t++)if(this._value.lo&1<<t)return t;for(var e=0;e<32;e++)if(this._value.hi&1<<e)return e+32;return-1},t}(),Bt=function(){function t(){this._componentTypes=new Map,this._typeNames=new Map,this._nextTypeId=0}var e=t.prototype;return e.getTypeId=function(t){var e=this._componentTypes.get(t);return void 0===e&&(e=this._nextTypeId++,this._componentTypes.set(t,e),this._typeNames.set(e,G(t))),e},e.getTypeName=function(t){return this._typeNames.get(t)||"Unknown"},e.createBits=function(){for(var t=new zt,e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];for(var r=0,s=n;r<s.length;r++){var o=s[r],a=this.getTypeId(o);t.set(a)}return t},e.getEntityBits=function(t){for(var e,n=new zt,i=o(t);!(e=i()).done;){var r=e.value,s=this.getTypeId(r.constructor);n.set(s)}return n},e.reset=function(){this._componentTypes.clear(),this._typeNames.clear(),this._nextTypeId=0},s(t,[{key:"registeredTypeCount",get:function(){return this._componentTypes.size}}],[{key:"instance",get:function(){return t._instance||(t._instance=new t),t._instance}}])}(),Ft=function(){function t(){}var e=t.prototype;return e.collectEntityData=function(t){if(!t)return this.getEmptyEntityDebugData();var e,n=t.entities;if(!n)return this.getEmptyEntityDebugData();try{e=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeData(t);return{totalEntities:e.totalEntities,activeEntities:e.activeEntities,pendingAdd:e.pendingAdd||0,pendingRemove:e.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:[],entityDetailsMap:{}}},e.getRawEntityList=function(t){if(!t)return[];var e=t.entities;return null!=e&&e.buffer?e.buffer.map((function(t){var e,n;return{id:t.id,name:t.name||"Entity_"+t.id,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:!1!==t.activeInHierarchy,componentCount:t.components.length,componentTypes:t.components.map((function(t){return Q(t)})),parentId:(null===(e=t.parent)||void 0===e?void 0:e.id)||null,childIds:(null===(n=t.children)||void 0===n?void 0:n.map((function(t){return t.id})))||[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0}})):[]},e.getEntityDetails=function(t,e){try{var n,i,r;if(!e)return null;var s=e.entities;if(null==s||!s.buffer)return null;var o=s.buffer.find((function(e){return e.id===t}));if(!o)return null;var c=o.getDebugInfo?o.getDebugInfo():this.buildFallbackEntityInfo(o,e),u=this.extractComponentDetails(o.components),h=this.getSceneInfo(e);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(t){return Q(t)})))||[]})}catch(t){return{error:"获取实体详情失败: "+(t instanceof Error?t.message:String(t)),scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}},e.getSceneInfo=function(t){var e="当前场景",n="Scene";try{if(t.name&&"string"==typeof t.name&&t.name.trim())e=t.name.trim();else if(t.constructor&&t.constructor.name)e=t.constructor.name,n=t.constructor.name;else if(t._name&&"string"==typeof t._name&&t._name.trim())e=t._name.trim();else{var i,r=null===(i=Object.getPrototypeOf(t))||void 0===i||null===(i=i.constructor)||void 0===i?void 0:i.name;r&&"Object"!==r&&(e=r,n=r)}}catch(t){e="场景名获取失败"}return{name:e,type:n}},e.collectEntityDataWithMemory=function(t){if(!t)return this.getEmptyEntityDebugData();var e,n=t.entities;if(!n)return this.getEmptyEntityDebugData();try{e=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeDataWithMemory(t);return{totalEntities:e.totalEntities,activeEntities:e.activeEntities,pendingAdd:e.pendingAdd||0,pendingRemove:e.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:this.buildEntityHierarchyTree(n),entityDetailsMap:this.buildEntityDetailsMap(n,t)}},e.collectArchetypeData=function(t){var e;if(t&&t.archetypeSystem&&"function"==typeof t.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(t.archetypeSystem);var n={entities:(null===(e=t.entities)||void 0===e?void 0:e.buffer)||[]};return{distribution:this.getArchetypeDistributionFast(n),topEntities:this.getTopEntitiesByComponentsFast(n)}},e.getArchetypeDistributionFast=function(t){var e=new Map;return t&&t.entities&&t.entities.forEach((function(t){var n,i=(null===(n=t.components)||void 0===n?void 0:n.map((function(t){return Q(t)})))||[],r=i.length>0?i.sort().join(", "):"无组件",s=e.get(r);s?s.count++:e.set(r,{count:1,componentTypes:i})})),Array.from(e.entries()).map((function(t){return{signature:t[0],count:t[1].count,memory:0}})).sort((function(t,e){return e.count-t.count})).slice(0,20)},e.getTopEntitiesByComponentsFast=function(t){return t&&t.entities?t.entities.map((function(t){var e;return{id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(e=t.components)||void 0===e?void 0:e.length)||0,memory:0}})).sort((function(t,e){return e.componentCount-t.componentCount})).slice(0,10):[]},e.collectArchetypeDataWithMemory=function(t){var e;if(t&&t.archetypeSystem&&"function"==typeof t.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(t.archetypeSystem);var n={entities:(null===(e=t.entities)||void 0===e?void 0:e.buffer)||[]};return{distribution:this.getArchetypeDistributionWithMemory(n),topEntities:this.getTopEntitiesByComponentsWithMemory(n)}},e.extractArchetypeStatistics=function(t){var e=t.getAllArchetypes(),n=[],i=[];return e.forEach((function(t){var e,r,s=(null===(e=t.componentTypes)||void 0===e?void 0:e.map((function(t){return t.name})).join(","))||"Unknown",o=(null===(r=t.entities)||void 0===r?void 0:r.length)||0;n.push({signature:s,count:o,memory:0}),t.entities&&t.entities.slice(0,5).forEach((function(t){var e;i.push({id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(e=t.components)||void 0===e?void 0:e.length)||0,memory:0})}))})),n.sort((function(t,e){return e.count-t.count})),i.sort((function(t,e){return e.componentCount-t.componentCount})),{distribution:n,topEntities:i}},e.extractArchetypeStatisticsWithMemory=function(t){var e=this,n=t.getAllArchetypes(),i=[],r=[];return n.forEach((function(t){var n,s,o=(null===(n=t.componentTypes)||void 0===n?void 0:n.map((function(t){return t.name})).join(","))||"Unknown",a=(null===(s=t.entities)||void 0===s?void 0:s.length)||0,c=0;if(t.entities&&t.entities.length>0){for(var u=Math.min(5,t.entities.length),h=0,l=0;l<u;l++)h+=e.estimateEntityMemoryUsage(t.entities[l]);c=h/u*a}i.push({signature:o,count:a,memory:c}),t.entities&&t.entities.slice(0,5).forEach((function(t){var n;r.push({id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(n=t.components)||void 0===n?void 0:n.length)||0,memory:e.estimateEntityMemoryUsage(t)})}))})),i.sort((function(t,e){return e.count-t.count})),r.sort((function(t,e){return e.componentCount-t.componentCount})),{distribution:i,topEntities:r}},e.getArchetypeDistribution=function(t){var e=new Map;return t&&t.entities&&t.entities.forEach((function(t){var n,i=(null===(n=t.componentMask)||void 0===n?void 0:n.toString())||"0",r=e.get(i);e.set(i,(r||0)+1)})),Array.from(e.entries()).map((function(t){return{signature:t[0],count:t[1],memory:0}})).sort((function(t,e){return e.count-t.count}))},e.getArchetypeDistributionWithMemory=function(t){var e=this,n=new Map;return t&&t.entities&&t.entities.forEach((function(t){var i,r=(null===(i=t.components)||void 0===i?void 0:i.map((function(t){return Q(t)})))||[],s=r.length>0?r.sort().join(", "):"无组件",o=n.get(s),a=e.estimateEntityMemoryUsage(t);(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(t){var e=t[0],n=t[1];return{signature:e,count:n.count,memory:isNaN(n.memory)?0:n.memory}})).sort((function(t,e){return e.count-t.count}))},e.getTopEntitiesByComponents=function(t){return t&&t.entities?t.entities.map((function(t){var e;return{id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(e=t.components)||void 0===e?void 0:e.length)||0,memory:0}})).sort((function(t,e){return e.componentCount-t.componentCount})):[]},e.getTopEntitiesByComponentsWithMemory=function(t){var e=this;return t&&t.entities?t.entities.map((function(t){var n;return{id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(n=t.components)||void 0===n?void 0:n.length)||0,memory:e.estimateEntityMemoryUsage(t)}})).sort((function(t,e){return e.componentCount-t.componentCount})):[]},e.getEmptyEntityDebugData=function(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}},e.calculateFallbackEntityStats=function(t){var e=t.buffer||[],n=e.filter((function(t){return t.enabled&&!t._isDestroyed}));return{totalEntities:e.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?e.reduce((function(t,e){var n;return t+((null===(n=e.components)||void 0===n?void 0:n.length)||0)}),0)/n.length:0}},e.estimateEntityMemoryUsage=function(t){var e=this;try{var n=0,i=this.calculateObjectSize(t,["components","children","parent"]);return!isNaN(i)&&i>0&&(n+=i),t.components&&Array.isArray(t.components)&&t.components.forEach((function(t){var i=e.calculateObjectSize(t,["entity"]);!isNaN(i)&&i>0&&(n+=i)})),isNaN(n)||n<0?0:n}catch(t){return 0}},e.calculateObjectSize=function(t,e){if(void 0===e&&(e=[]),!t||"object"!=typeof t)return 0;var n=new WeakSet,i=function(t,r){if(void 0===r&&(r=0),!t||"object"!=typeof t||r>=2)return 0;if(n.has(t))return 0;n.add(t);var s=32;try{for(var o=Object.keys(t),a=Math.min(o.length,20),c=0;c<a;c++){var u=o[c];if(!(e.includes(u)||"constructor"===u||"__proto__"===u||u.startsWith("_cc_")||u.startsWith("__"))){var h=t[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(t){return 64}return s};try{var r=i(t);return Math.max(r,32)}catch(t){return 64}},e.buildEntityHierarchyTree=function(t){var e=this;if(null==t||!t.buffer)return[];var n=[];return t.buffer.forEach((function(t){if(!t.parent){var i=e.buildEntityHierarchyNode(t);n.push(i)}})),n.sort((function(t,e){return t.name<e.name?-1:t.name>e.name?1:t.id-e.id})),n},e.buildEntityHierarchyNode=function(t){var e,n=this,i={id:t.id,name:t.name||"Entity_"+t.id,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:!1!==t.activeInHierarchy,componentCount:t.components.length,componentTypes:t.components.map((function(t){return Q(t)})),parentId:(null===(e=t.parent)||void 0===e?void 0:e.id)||null,children:[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0};(t.children&&t.children.length>0&&(i.children=t.children.map((function(t){return n.buildEntityHierarchyNode(t)}))),"function"==typeof t.getDebugInfo)&&(i=a({},i,t.getDebugInfo()));return t.components&&t.components.length>0&&(i.componentDetails=this.extractComponentDetails(t.components)),i},e.buildEntityDetailsMap=function(t,e){var n=this;if(null==t||!t.buffer)return{};for(var i={},r=t.buffer,s=0;s<r.length;s+=100){r.slice(s,s+100).forEach((function(t){var r,s=t.getDebugInfo?t.getDebugInfo():n.buildFallbackEntityInfo(t,e),o=t.getComponentCacheStats?t.getComponentCacheStats():null,c=n.extractComponentDetails(t.components);i[t.id]=a({},s,{parentName:(null===(r=t.parent)||void 0===r?void 0:r.name)||null,components:c,componentTypes:s.componentTypes||c.map((function(t){return t.typeName})),cachePerformance:o?{hitRate:o.cacheStats.hitRate,size:o.cacheStats.size,maxSize:o.cacheStats.maxSize}:null})}))}return i},e.buildFallbackEntityInfo=function(t,e){var n,i,r,s=this.getSceneInfo(e);return{name:t.name||"Entity_"+t.id,id:t.id,enabled:!1!==t.enabled,active:!1!==t.active,activeInHierarchy:!1!==t.activeInHierarchy,destroyed:t.isDestroyed||!1,scene:s.name,sceneName:s.name,sceneType:s.type,componentCount:t.components.length,componentTypes:t.components.map((function(t){return Q(t)})),componentMask:(null===(n=t.componentMask)||void 0===n?void 0:n.toString())||"0",parentId:(null===(i=t.parent)||void 0===i?void 0:i.id)||null,childCount:(null===(r=t.children)||void 0===r?void 0:r.length)||0,childIds:t.children.map((function(t){return t.id}))||[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0}},e.extractComponentDetails=function(t){var e=this;return t.map((function(t){var n=Q(t);if(!n||"Object"===n||"Function"===n)try{var i=Bt.instance,r=t.constructor,s=i.getTypeId(r);n=i.getTypeName(s)}catch(t){n="UnknownComponent"}var o={};try{Object.keys(t).forEach((function(n){if(!n.startsWith("_")&&"entity"!==n&&"constructor"!==n){var i=t[n];null!=i&&(o[n]=e.formatPropertyValue(i))}})),0===Object.keys(o).length&&(o._info="该组件没有公开属性",o._componentId=Q(t))}catch(e){o._error="属性提取失败",o._componentId=Q(t)}return{typeName:n,properties:o}}))},e.getComponentProperties=function(t,e,n){var i=this;try{if(!n)return{};var r=n.entities;if(null==r||!r.buffer)return{};var s=r.buffer.find((function(e){return e.id===t}));if(!s||e>=s.components.length)return{};var o=s.components[e],a={};return Object.keys(o).forEach((function(t){if(!t.startsWith("_")&&"entity"!==t){var e=o[t];null!=e&&(a[t]=i.formatPropertyValue(e))}})),a}catch(t){return{_error:"属性提取失败"}}},e.formatPropertyValue=function(t,e){return void 0===e&&(e=0),null==t?t:"object"!=typeof t?"string"==typeof t&&t.length>200?"[长字符串: "+t.length+"字符] "+t.substring(0,100)+"...":t:0===e?this.formatObjectFirstLevel(t):this.createLazyLoadPlaceholder(t)},e.formatObjectFirstLevel=function(t){var e=this;try{if(Array.isArray(t)){if(0===t.length)return[];if(t.length>10){var n=t.slice(0,3).map((function(t){return e.formatPropertyValue(t,1)}));return{_isLazyArray:!0,_arrayLength:t.length,_sample:n,_summary:"数组["+t.length+"个元素]"}}return t.map((function(t){return e.formatPropertyValue(t,1)}))}var i=Object.keys(t);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 t[c])try{var u=t[c];null!=u&&(r[c]=this.formatPropertyValue(u,1),s++)}catch(t){r[c]="[访问失败: "+(t instanceof Error?t.message:String(t))+"]",s++}}return r}catch(t){return"[对象解析失败: "+(t instanceof Error?t.message:String(t))+"]"}},e.createLazyLoadPlaceholder=function(t){try{var e,n=(null===(e=t.constructor)||void 0===e?void 0:e.name)||"Object";return{_isLazyObject:!0,_typeName:n,_summary:this.getObjectSummary(t,n),_objectId:this.generateObjectId(t)}}catch(t){return{_isLazyObject:!0,_typeName:"Unknown",_summary:"无法分析的对象: "+(t instanceof Error?t.message:String(t)),_objectId:Math.random().toString(36).substr(2,9)}}},e.getObjectSummary=function(t,e){try{if((e.toLowerCase().includes("vec")||e.toLowerCase().includes("vector"))&&void 0!==t.x&&void 0!==t.y){var n=void 0!==t.z?t.z:"";return e+"("+t.x+", "+t.y+(n?", "+n:"")+")"}if(e.toLowerCase().includes("color")&&void 0!==t.r&&void 0!==t.g&&void 0!==t.b){var i=void 0!==t.a?t.a:1;return e+"("+t.r+", "+t.g+", "+t.b+", "+i+")"}if(e.toLowerCase().includes("node"))return e+": "+(t.name||t._name||"未命名");if(e.toLowerCase().includes("component")){var r,s,o=(null===(r=t.node)||void 0===r?void 0:r.name)||(null===(s=t.node)||void 0===s?void 0:s._name)||"";return e+(o?" on "+o:"")}var a=Object.keys(t);return 0===a.length?e+" (空对象)":e+" ("+a.length+"个属性)"}catch(t){return e+" (无法分析)"}},e.generateObjectId=function(t){try{return void 0!==t.id?"obj_"+t.id:void 0!==t._id?"obj_"+t._id:void 0!==t.uuid?"obj_"+t.uuid:void 0!==t._uuid?"obj_"+t._uuid:"obj_"+Math.random().toString(36).substr(2,9)}catch(t){return"obj_"+Math.random().toString(36).substr(2,9)}},e.expandLazyObject=function(t,e,n,i){try{if(!i)return null;var r=i.entities;if(null==r||!r.buffer)return null;var s=r.buffer.find((function(e){return e.id===t}));if(!s)return null;if(e>=s.components.length)return null;var o=s.components[e],a=this.getObjectByPath(o,n);return a?this.formatObjectFirstLevel(a):null}catch(t){return{error:"展开失败: "+(t instanceof Error?t.message:String(t))}}},e.getObjectByPath=function(t,e){if(!e)return t;for(var n,i=t,r=o(e.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},t}(),Lt=function(){function t(){}return t.prototype.collectSystemData=function(t,e){if(!e)return{totalSystems:0,systemsInfo:[]};var n=e.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};var i=n.processors||[],r=new Map,s=new Map;if(t)try{r=t.getAllSystemStats(),s=t.getAllSystemData()}catch(t){}return{totalSystems:i.length,systemsInfo:i.map((function(t){var e,n=t.systemName||V(t),i=r.get(n),o=s.get(n);return{name:n,type:V(t),entityCount:(null===(e=t.entities)||void 0===e?void 0:e.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:t.updateOrder||0,enabled:!1!==t.enabled,lastUpdateTime:(null==o?void 0:o.lastUpdateTime)||0}}))}},t}(),qt=function(){function t(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.lastGCCount=0,this.gcCollections=0,this.lastMemoryCheck=0}var e=t.prototype;return e.collectPerformanceData=function(t){var e=g.deltaTime,n=1e3*e,i=e>0?Math.round(1/e):0,r=this.getECSPerformanceData(t),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(t){return t>=0}));return{frameTime:s,engineFrameTime:n,ecsPercentage:o,memoryUsage:a,fps:i,averageFrameTime:c.length>0?c.reduce((function(t,e){return t+e}),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(t),systemBreakdown:r.systemBreakdown,memoryDetails:this.getMemoryDetails()}},e.getECSPerformanceData=function(t){if(!t)return{totalExecutionTime:0,systemBreakdown:[]};if(!t.enabled){try{t.enabled=!0}catch(t){}return{totalExecutionTime:0,systemBreakdown:[]}}try{var e=0,n=[],i=t.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;e+=h,n.push({systemName:c,executionTime:h,percentage:0})}return n.forEach((function(t){t.percentage=e>0?t.executionTime/e*100:0})),n.sort((function(t,e){return e.executionTime-t.executionTime})),{totalExecutionTime:e,systemBreakdown:n}}catch(t){return{totalExecutionTime:0,systemBreakdown:[]}}},e.getSystemPerformance=function(t){if(!t)return[];try{var e=t.getAllSystemStats(),n=t.getAllSystemData();return Array.from(e.entries()).map((function(t){var e=t[0],i=t[1],r=n.get(e);return{systemName:e,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(t){return[]}},e.getMemoryDetails=function(){var t={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){var e=performance.memory;if(t.totalMemory=e.jsHeapSizeLimit||536870912,t.usedMemory=e.usedJSHeapSize||0,t.freeMemory=t.totalMemory-t.usedMemory,this.lastMemoryCheck>0)this.lastMemoryCheck-t.usedMemory>1048576&&this.gcCollections++;this.lastMemoryCheck=t.usedMemory}else t.totalMemory=536870912,t.freeMemory=536870912}catch(t){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return t},e.updateGCCount=function(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(t){return this.gcCollections}},t}(),Wt=function(){function t(){}var e=t.prototype;return e.collectComponentData=function(t){var e=this;if(!t)return{componentTypes:0,componentInstances:0,componentStats:[]};var n=t.entities;if(null==n||!n.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};var i=new Map,r=0;n.buffer.forEach((function(t){t.components&&t.components.forEach((function(t){var e=Q(t),n=i.get(e)||{count:0,entities:0};n.count++,r++,i.set(e,n)}))}));var s=new Map,a=new Map;try{for(var c,u=st.getInstance(),h=u.getPoolStats(),l=u.getPoolUtilization(),d=o(h.entries());!(c=d()).done;){var f=c.value,m=f[0],p=f[1];a.set(m,p.maxSize)}for(var y,g=o(l.entries());!(y=g()).done;){var v=y.value,_=v[0],S=v[1];s.set(_,S.utilization)}}catch(t){}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=e.getEstimatedComponentSize(r,t);return{typeName:r,instanceCount:o.count,memoryPerInstance:h,totalMemory:o.count*h,poolSize:c,poolUtilization:u,averagePerEntity:o.count/n.buffer.length}}))}},e.getEstimatedComponentSize=function(e,n){if(t.componentSizeCache.has(e))return t.componentSizeCache.get(e);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(t){return Q(t)===e}));if(u){r=this.calculateQuickObjectSize(u);break}}}}catch(t){r=64}return t.componentSizeCache.set(e,r),r},e.calculateQuickObjectSize=function(t){if(!t||"object"!=typeof t)return 8;var e=32,n=new WeakSet,i=function(t,e){if(void 0===e&&(e=0),!t||"object"!=typeof t||n.has(t)||e>3)return 0;n.add(t);var r=0;try{for(var s=Object.keys(t),o=0;o<Math.min(s.length,20);o++){var a=s[o];if("entity"!==a&&"_entity"!==a&&"constructor"!==a){var c=t[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,e+1))}}}catch(t){return 32}return r};return e+=i(t),Math.max(e,32)},e.calculateDetailedComponentMemory=function(t,e){if(!e)return this.getEstimatedComponentSize(t,e);var n=e.entities;if(null==n||!n.buffer)return this.getEstimatedComponentSize(t,e);try{for(var i,r=o(n.buffer);!(i=r()).done;){var s=i.value;if(s.components){var a=s.components.find((function(e){return Q(e)===t}));if(a)return this.estimateObjectSize(a)}}}catch(t){}return this.getEstimatedComponentSize(t,e)},e.estimateObjectSize=function(t,e,n){if(void 0===e&&(e=new WeakSet),void 0===n&&(n=0),null==t||n>10)return 0;if(e.has(t))return 0;var i=0;switch(typeof t){case"boolean":i=4;break;case"number":default:i=8;break;case"string":i=24+Math.min(2*t.length,1e3);break;case"object":if(e.add(t),Array.isArray(t)){i=40+8*t.length;for(var r=Math.min(t.length,50),s=0;s<r;s++)i+=this.estimateObjectSize(t[s],e,n+1)}else{i=32;try{for(var o=Object.getOwnPropertyNames(t),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=t[u];null!=h&&(i+=this.estimateObjectSize(h,e,n+1))}catch(t){continue}}}catch(t){i=128}}}return 8*Math.ceil(i/8)},t.clearCache=function(){t.componentSizeCache.clear()},t}();Wt.componentSizeCache=new Map;var Ut=function(){function t(){this.sceneStartTime=Date.now()}var e=t.prototype;return e.collectSceneData=function(t){var e,n;if(!t)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneMemory:0,sceneUptime:0};var i=(Date.now()-this.sceneStartTime)/1e3,r=t.entities,s=t.entityProcessors;return{currentSceneName:t.name||"Unnamed Scene",isInitialized:t._didSceneBegin||!1,sceneRunTime:i,sceneEntityCount:(null==r||null===(e=r.buffer)||void 0===e?void 0:e.length)||0,sceneSystemCount:(null==s||null===(n=s.processors)||void 0===n?void 0:n.length)||0,sceneMemory:0,sceneUptime:i}},e.setSceneStartTime=function(t){this.sceneStartTime=t},t}(),jt=function(){function t(t,e){void 0===e&&(e=!0),this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectInterval=2e3,this.url=t,this.autoReconnect=e}var e=t.prototype;return e.setMessageHandler=function(t){this.messageHandler=t},e.connect=function(){var t=this;return new Promise((function(e,n){try{t.ws=new WebSocket(t.url),t.ws.onopen=function(n){t.handleOpen(n),e()},t.ws.onclose=function(e){t.handleClose(e)},t.ws.onerror=function(e){t.handleError(e),n(e)},t.ws.onmessage=function(e){t.handleMessage(e)}}catch(e){t.handleConnectionFailure(e),n(e)}}))},e.disconnect=function(){this.ws&&(this.autoReconnect=!1,this.ws.close(),this.ws=void 0),this.isConnected=!1},e.send=function(t){if(this.isConnected&&this.ws)try{var e="string"==typeof t?t:JSON.stringify(t);this.ws.send(e)}catch(t){}},e.getConnectionStatus=function(){return this.isConnected},e.setMaxReconnectAttempts=function(t){this.maxReconnectAttempts=t},e.setReconnectInterval=function(t){this.reconnectInterval=t},e.scheduleReconnect=function(){var t=this;this.reconnectTimer&&clearTimeout(this.reconnectTimer);var e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout((function(){t.connect().catch((function(e){t.reconnectAttempts<t.maxReconnectAttempts&&t.scheduleReconnect()}))}),e)},e.handleMessage=function(t){try{var e=JSON.parse(t.data);this.messageHandler&&this.messageHandler(e)}catch(t){}},e.handleOpen=function(t){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(t)},e.handleClose=function(t){this.isConnected=!1,this.onClose&&this.onClose(t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()},e.handleError=function(t){this.onError&&this.onError(t)},e.handleConnectionFailure=function(t){this.onError&&this.onError(t)},t}(),Ht=function(){function t(t,e){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.config=e,this.sceneProvider=function(){return t.scene||t.constructor.scene},this.performanceMonitorProvider=function(){return t._performanceMonitor},this.entityCollector=new Ft,this.systemCollector=new Lt,this.performanceCollector=new qt,this.componentCollector=new Wt,this.sceneCollector=new Ut,this.webSocketManager=new jt(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));var n=e.debugFrameRate||30;this.sendInterval=1e3/n,this.start()}var e=t.prototype;return e.start=function(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())},e.stop=function(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())},e.updateConfig=function(t){this.config=t;var e=t.debugFrameRate||30;this.sendInterval=1e3/e,this.webSocketManager&&t.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new jt(t.websocketUrl,!1!==t.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())},e.onFrameUpdate=function(t){if(this.isRunning&&this.config.enabled){this.frameCounter++;var e=Date.now();e-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=e)}},e.onSceneChanged=function(){this.isRunning&&this.config.enabled&&this.sendDebugData()},e.handleMessage=function(t){try{switch(t.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":t.config&&this.updateConfig(a({},this.config,t.config));break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(t);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(t);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(t);break;case"get_entity_details":this.handleGetEntityDetailsRequest(t);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(e){t.requestId&&this.webSocketManager.send({type:"error_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleExpandLazyObjectRequest=function(t){try{var e=t.entityId,n=t.componentIndex,i=t.propertyPath,r=t.requestId;if(void 0===e||void 0===n||!i)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,error:"缺少必要参数"});var s=this.entityCollector.expandLazyObject(e,n,i);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,data:s})}catch(e){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleGetComponentPropertiesRequest=function(t){try{var e=t.entityId,n=t.componentIndex,i=t.requestId;if(void 0===e||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:i,error:"缺少必要参数"});var r=this.entityCollector.getComponentProperties(e,n);this.webSocketManager.send({type:"get_component_properties_response",requestId:i,data:r})}catch(e){this.webSocketManager.send({type:"get_component_properties_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleGetRawEntityListRequest=function(t){try{var e=t.requestId,n=this.entityCollector.getRawEntityList();this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e,data:n})}catch(e){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleGetEntityDetailsRequest=function(t){try{var e=t.entityId,n=t.requestId;if(void 0===e)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});var i=this.entityCollector.getEntityDetails(e);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:i})}catch(e){this.webSocketManager.send({type:"get_entity_details_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleMemorySnapshotRequest=function(){try{var t=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:t})}catch(t){this.webSocketManager.send({type:"memory_snapshot_error",error:t instanceof Error?t.message:"内存快照捕获失败"})}},e.captureMemorySnapshot=function(){var t=Date.now(),e=this.collectBaseMemoryInfo(),n=this.sceneProvider(),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(t,e){return t+e.memory}),0);return{timestamp:t,version:"2.0",summary:{totalEntities:i.totalEntities,totalMemoryUsage:e.usedMemory,totalMemoryLimit:e.totalMemory,memoryUtilization:e.usedMemory/e.totalMemory*100,gcCollections:e.gcCollections,entityMemory:c,componentMemory:r.totalMemory,systemMemory:s.totalMemory,poolMemory:o.totalMemory},baseMemory:e,entities:{totalMemory:c,entityCount:i.totalEntities,archetypes:i.entitiesPerArchetype,largestEntities:i.topEntitiesByComponents},components:r,systems:s,pools:o,performance:a}},e.collectBaseMemoryInfo=function(){var t={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null,detailedMemory:void 0};try{var e=performance;if(e.memory){var n=e.memory;t.totalMemory=n.jsHeapSizeLimit||536870912,t.usedMemory=n.usedJSHeapSize||0,t.freeMemory=t.totalMemory-t.usedMemory,t.heapInfo={totalJSHeapSize:n.totalJSHeapSize||0,usedJSHeapSize:n.usedJSHeapSize||0,jsHeapSizeLimit:n.jsHeapSizeLimit||0}}else t.totalMemory=536870912,t.freeMemory=536870912;e.measureUserAgentSpecificMemory&&e.measureUserAgentSpecificMemory().then((function(e){t.detailedMemory=e})).catch((function(){}))}catch(t){}return t},e.collectComponentMemoryStats=function(t){for(var e,n=new Map,i=0,r=new Map,s=o(t.buffer);!(e=s()).done;){var a=e.value;if(a&&!a.destroyed&&a.components)for(var c,u=o(a.components);!(c=u()).done;){var h=Q(c.value);r.set(h,(r.get(h)||0)+1)}}for(var l,d=o(r.entries());!(l=d()).done;){var f=l.value,m=f[0],p=f[1],y=this.componentCollector.calculateDetailedComponentMemory(m),g=y*p;i+=g;for(var v,_=[],S=0,E=o(t.buffer);!(v=E()).done;){var T=v.value;if(T&&!T.destroyed&&T.components){for(var C,b=o(T.components);!(C=b()).done;){if(Q(C.value)===m&&(_.push({entityId:T.id,entityName:T.name||"Entity_"+T.id,memory:y}),++S>=100))break}if(S>=100)break}}n.set(m,{count:p,totalMemory:g,instances:_.slice(0,10)})}var M=Array.from(n.entries()).map((function(t){var e=t[0],n=t[1];return{typeName:e,instanceCount:n.count,totalMemory:n.totalMemory,averageMemory:n.totalMemory/n.count,percentage:i>0?n.totalMemory/i*100:0,largestInstances:n.instances.sort((function(t,e){return e.memory-t.memory})).slice(0,3)}})).sort((function(t,e){return e.totalMemory-t.totalMemory}));return{totalMemory:i,componentTypes:n.size,totalInstances:Array.from(n.values()).reduce((function(t,e){return t+e.count}),0),breakdown:M}},e.collectSystemMemoryStats=function(){var t=this.sceneProvider(),e=0,n=[];try{var i=null==t?void 0:t.entityProcessors;if(i&&i.processors)for(var r,s=new Map,a=o(i.processors);!(r=a()).done;){var c=r.value,u=V(c),h=void 0;s.has(u)?h=s.get(u):(h=this.calculateQuickSystemSize(c),s.set(u,h)),e+=h,n.push({name:u,memory:h,enabled:!1!==c.enabled,updateOrder:c.updateOrder||0})}}catch(t){}return{totalMemory:e,systemCount:n.length,breakdown:n.sort((function(t,e){return e.memory-t.memory}))}},e.calculateQuickSystemSize=function(t){if(!t||"object"!=typeof t)return 64;var e=128;try{for(var n=Object.keys(t),i=0;i<Math.min(n.length,15);i++){var r=n[i];if("entities"!==r&&"scene"!==r&&"constructor"!==r){var s=t[r];e+=2*r.length,"string"==typeof s?e+=Math.min(2*s.length,100):"number"==typeof s?e+=8:"boolean"==typeof s?e+=4:Array.isArray(s)?e+=40+Math.min(8*s.length,200):"object"==typeof s&&null!==s&&(e+=64)}}}catch(t){return 128}return Math.max(e,64)},e.collectPoolMemoryStats=function(){var t=0,e=[];try{for(var n,i=o(st.getInstance().getPoolStats().entries());!(n=i()).done;){var r=n.value,s=r[0],a=r[1],c=32*a.maxSize;t+=c,e.push({typeName:s,maxSize:a.maxSize,currentSize:a.currentSize||0,estimatedMemory:c,utilization:a.currentSize?a.currentSize/a.maxSize*100:0})}}catch(t){}try{for(var u=T.getAllPoolStats(),h=0,l=Object.entries(u);h<l.length;h++){var d=l[h],f=d[0],m=d[1];t+=m.estimatedMemoryUsage,e.push({typeName:"Pool_"+f,maxSize:m.maxSize,currentSize:m.size,estimatedMemory:m.estimatedMemoryUsage,utilization:m.size/m.maxSize*100,hitRate:100*m.hitRate})}}catch(t){}return{totalMemory:t,poolCount:e.length,breakdown:e.sort((function(t,e){return e.estimatedMemory-t.estimatedMemory}))}},e.collectPerformanceStats=function(){try{var t,e=this.performanceMonitorProvider();if(!e)return{enabled:!1};var n=e.getAllSystemStats(),i=e.getPerformanceWarnings();return{enabled:null!==(t=e.enabled)&&void 0!==t&&t,systemCount:n.size,warnings:i.slice(0,10),topSystems:Array.from(n.entries()).map((function(t){var e=t[0],n=t[1];return{name:e,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort((function(t,e){return e.averageTime-t.averageTime})).slice(0,5)}}catch(t){return{enabled:!1,error:t instanceof Error?t.message:String(t)}}},e.getDebugData=function(){var t=Date.now(),e=this.sceneProvider(),n={timestamp:t,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:(null==e?void 0:e.name)||"Unknown"};if(this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(e)),this.config.channels.systems){var i=this.performanceMonitorProvider();n.systems=this.systemCollector.collectSystemData(i,e)}if(this.config.channels.performance){var r=this.performanceMonitorProvider();n.performance=this.performanceCollector.collectPerformanceData(r)}return this.config.channels.components&&(n.components=this.componentCollector.collectComponentData(e)),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData(e)),n},e.connectWebSocket=function(){var t=n(l().m((function t(){return l().w((function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,t.n=1,this.webSocketManager.connect();case 1:t.n=3;break;case 2:t.p=2;case 3:return t.a(2)}}),t,this,[[0,2]])})));return function(){return t.apply(this,arguments)}}(),e.sendDebugData=function(){if(this.webSocketManager.getConnectionStatus())try{var t={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(t)}catch(t){}},t}(),Gt=function(){function t(e){var n,i,r;void 0===e&&(e={}),this._globalManagers=[],t._instance=this,this._config=a({debug:!0,enableEntitySystems:!0},e),this._timerManager=new S,t.registerGlobalManager(this._timerManager),this._performanceMonitor=E.instance,this._config.debug&&this._performanceMonitor.enable(),this._poolManager=b.getInstance(),t.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&&(this._debugManager=new Ht(this,this._config.debugConfig)),this.initialize()}t.getScene=function(){if(!this._instance)return null;this._instance.ensureDefaultWorld();var t=this._instance._worldManager.getWorld(this.DEFAULT_WORLD_ID);return(null==t?void 0:t.getScene(this.DEFAULT_SCENE_ID))||null},t.setScene=function(t){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");this._instance.ensureDefaultWorld();var e=this._instance._worldManager.getWorld(this.DEFAULT_WORLD_ID);return e.getScene(this.DEFAULT_SCENE_ID)&&e.removeScene(this.DEFAULT_SCENE_ID),e.createScene(this.DEFAULT_SCENE_ID,t),e.setSceneActive(this.DEFAULT_SCENE_ID,!0),this._instance.onSceneChanged(),t},t.create=function(e){if(void 0===e&&(e=!0),null==this._instance){var n="boolean"==typeof e?{debug:e,enableEntitySystems:!0}:e;this._instance=new t(n)}return this._instance},t.update=function(e){this._instance?this._instance.updateInternal(e):t._logger.warn("Core实例未创建,请先调用Core.create()")},t.registerGlobalManager=function(t){this._instance._globalManagers.push(t),t.enabled=!0},t.unregisterGlobalManager=function(t){this._instance._globalManagers.splice(this._instance._globalManagers.indexOf(t),1),t.enabled=!1},t.getGlobalManager=function(t){for(var e,n=o(this._instance._globalManagers);!(e=n()).done;){var i=e.value;if(i instanceof t)return i}return null},t.schedule=function(t,e,n,i){if(void 0===e&&(e=!1),!i)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(t,e,n,i)},t.enableDebug=function(e){this._instance?(this._instance._debugManager?this._instance._debugManager.updateConfig(e):this._instance._debugManager=new Ht(this._instance,e),this._instance._config.debugConfig=e):t._logger.warn("Core实例未创建,请先调用Core.create()")},t.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))},t.getDebugData=function(){var t;return null!==(t=this._instance)&&void 0!==t&&t._debugManager?this._instance._debugManager.getDebugData():null},t.getWorldManager=function(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._worldManager||(this._instance._worldManager=Pt.getInstance({maxWorlds:50,autoCleanup:!0,cleanupInterval:6e4,debug:this._instance._config.debug})),this._instance._worldManager},t.enableWorldManager=function(){return this.getWorldManager()};var e=t.prototype;return e.ensureDefaultWorld=function(){this._worldManager||(this._worldManager=Pt.getInstance({maxWorlds:1,autoCleanup:!1,cleanupInterval:0,debug:this._config.debug})),this._worldManager.getWorld(t.DEFAULT_WORLD_ID)||(this._worldManager.createWorld(t.DEFAULT_WORLD_ID,{name:"DefaultWorld",maxScenes:1,autoCleanup:!1}),this._worldManager.setWorldActive(t.DEFAULT_WORLD_ID,!0))},e.onSceneChanged=function(){var e=this;g.sceneChanged();var n=t.getScene();n&&n.querySystem&&n.eventSystem&&(this._ecsAPI=Ot(n,n.querySystem,n.eventSystem)),this._debugManager&&queueMicrotask((function(){var t;null===(t=e._debugManager)||void 0===t||t.onSceneChanged()}))},e.initialize=function(){},e.updateInternal=function(e){if(!t.paused){var n=this._performanceMonitor.startMonitoring("Core.update");g.update(e),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(g.deltaTime);for(var i,r=this._performanceMonitor.startMonitoring("GlobalManagers.update"),s=o(this._globalManagers);!(i=s()).done;){var a=i.value;a.enabled&&a.update()}if(this._performanceMonitor.endMonitoring("GlobalManagers.update",r,this._globalManagers.length),this._poolManager.update(),this._worldManager){for(var c,u=this._performanceMonitor.startMonitoring("Worlds.update"),h=0,l=o(this._worldManager.getActiveWorlds());!(c=l()).done;){var d=c.value;d.updateGlobalSystems(),d.updateScenes(),h+=d.getStats().totalEntities}this._performanceMonitor.endMonitoring("Worlds.update",u,h)}this._debugManager&&this._debugManager.onFrameUpdate(e),this._performanceMonitor.endMonitoring("Core.update",n)}},s(t,null,[{key:"Instance",get:function(){return this._instance}},{key:"scene",get:function(){return this.getScene()}},{key:"ecsAPI",get:function(){var t;return(null===(t=this._instance)||void 0===t?void 0:t._ecsAPI)||null}},{key:"isDebugEnabled",get:function(){var t;return(null===(t=this._instance)||void 0===t||null===(t=t._config.debugConfig)||void 0===t?void 0:t.enabled)||!1}}])}();Gt.paused=!1,Gt.DEFAULT_WORLD_ID="__default__",Gt.DEFAULT_SCENE_ID="__main__",Gt._logger=D("Core");var Yt=function(t,e){this.func=t,this.context=e},Qt=function(){function t(){this._messageTable=new Map}var e=t.prototype;return e.addObserver=function(t,e,n){var i=this._messageTable.get(t);i||(i=[],this._messageTable.set(t,i)),this.hasObserver(t,e)||i.push(new Yt(e,n))},e.removeObserver=function(t,e){var n=this._messageTable.get(t);if(n){var i=n.findIndex((function(t){return t.func==e}));-1!=i&&n.splice(i,1)}},e.emit=function(t){var e=this._messageTable.get(t);if(e){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(e);!(s=a()).done;){var c,u=s.value;(c=u.func).call.apply(c,[u.context].concat(i))}}},e.hasObserver=function(t,e){var n=this._messageTable.get(t);return!!n&&n.some((function(t){return t.func===e}))},e.removeAllObservers=function(t){void 0!==t?this._messageTable.delete(t):this._messageTable.clear()},e.dispose=function(){this._messageTable.clear()},e.getEventTypeCount=function(){return this._messageTable.size},e.getObserverCount=function(t){var e=this._messageTable.get(t);return e?e.length:0},t}(),Vt=function(){function t(){this._enabled=!0,this._updateOrder=0,this.id=t._idGenerator++}var e=t.prototype;return e.onAddedToEntity=function(){},e.onRemovedFromEntity=function(){},e.onEnabled=function(){},e.onDisabled=function(){},e.update=function(){},s(t,[{key:"enabled",get:function(){return this.entity?this.entity.enabled&&this._enabled:this._enabled},set:function(t){this._enabled!==t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(t){this._updateOrder=t}}])}();Vt._idGenerator=0;var Xt=function(){function t(){this.condition={all:[],any:[],none:[]}}t.all=function(){var e=new t;return e.all.apply(e,arguments)},t.any=function(){var e=new t;return e.any.apply(e,arguments)},t.none=function(){var e=new t;return e.none.apply(e,arguments)},t.byTag=function(e){return(new t).withTag(e)},t.byName=function(e){return(new t).withName(e)},t.byComponent=function(e){return(new t).withComponent(e)},t.complex=function(){return new t},t.empty=function(){return new t};var e=t.prototype;return e.all=function(){var t;return(t=this.condition.all).push.apply(t,arguments),this},e.any=function(){var t;return(t=this.condition.any).push.apply(t,arguments),this},e.none=function(){var t;return(t=this.condition.none).push.apply(t,arguments),this},e.exclude=function(){return this.none.apply(this,arguments)},e.one=function(){return this.any.apply(this,arguments)},e.withTag=function(t){return this.condition.tag=t,this},e.withName=function(t){return this.condition.name=t,this},e.withComponent=function(t){return this.condition.component=t,this},e.withoutTag=function(){return delete this.condition.tag,this},e.withoutName=function(){return delete this.condition.name,this},e.withoutComponent=function(){return delete this.condition.component,this},e.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}},e.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},e.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},e.clone=function(){var e,n,i,r=new t;return(e=r.condition.all).push.apply(e,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},e.toString=function(){var t=[];return this.condition.all.length>0&&t.push("all("+this.condition.all.map((function(t){return G(t)})).join(", ")+")"),this.condition.any.length>0&&t.push("any("+this.condition.any.map((function(t){return G(t)})).join(", ")+")"),this.condition.none.length>0&&t.push("none("+this.condition.none.map((function(t){return G(t)})).join(", ")+")"),void 0!==this.condition.tag&&t.push("tag("+this.condition.tag+")"),void 0!==this.condition.name&&t.push("name("+this.condition.name+")"),void 0!==this.condition.component&&t.push("component("+G(this.condition.component)+")"),"Matcher["+t.join(" & ")+"]"},t}(),Zt=function(){function t(t){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=E.instance,this._initialized=!1,this._trackedEntities=new Set,this._eventListeners=[],this._scene=null,this._matcher=t||Xt.empty(),this._systemName=V(this)}var e=t.prototype;return e.setUpdateOrder=function(t){this._updateOrder=t,this.scene&&this.scene.entityProcessors&&this.scene.entityProcessors.setDirty()},e.initialize=function(){this._initialized||(this._initialized=!0,this.scene&&this.queryEntities(),this.onInitialize())},e.onInitialize=function(){},e.reset=function(){this._initialized=!1,this._trackedEntities.clear(),this.cleanupEventListeners(),this.onDestroy()},e.queryEntities=function(){var t;if(null===(t=this.scene)||void 0===t||!t.querySystem||!this._matcher)return[];var e=this._matcher.getCondition(),n=this.scene.querySystem,i=[];return i=this._matcher.isEmpty()?n.getAllEntities():this.isSingleCondition(e)?this.executeSingleConditionQuery(e,n):this.executeComplexQuery(e,n),this.updateEntityTracking(i),i},e.isSingleCondition=function(t){return 1===(t.all.length>0?1:0)+(t.any.length>0?1:0)+(t.none.length>0?1:0)+(void 0!==t.tag?1:0)+(void 0!==t.name?1:0)+(void 0!==t.component?1:0)},e.executeSingleConditionQuery=function(t,e){return void 0!==t.tag?e.queryByTag(t.tag).entities:void 0!==t.name?e.queryByName(t.name).entities:void 0!==t.component?e.queryByComponent(t.component).entities:t.all.length>0&&0===t.any.length&&0===t.none.length?e.queryAll.apply(e,t.all).entities:0===t.all.length&&t.any.length>0&&0===t.none.length?e.queryAny.apply(e,t.any).entities:0===t.all.length&&0===t.any.length&&t.none.length>0?e.queryNone.apply(e,t.none).entities:[]},e.executeComplexQueryWithIdSets=function(t,e){var n=null;if(void 0!==t.tag){var i=e.queryByTag(t.tag);n=this.extractEntityIds(i.entities)}if(void 0!==t.name){var r=this.extractEntityIds(e.queryByName(t.name).entities);n=n?this.intersectIdSets(n,r):r}if(void 0!==t.component){var s=this.extractEntityIds(e.queryByComponent(t.component).entities);n=n?this.intersectIdSets(n,s):s}if(t.all.length>0){var o=this.extractEntityIds(e.queryAll.apply(e,t.all).entities);n=n?this.intersectIdSets(n,o):o}if(t.any.length>0){var a=this.extractEntityIds(e.queryAny.apply(e,t.any).entities);n=n?this.intersectIdSets(n,a):a}if(t.none.length>0){n||(n=this.extractEntityIds(e.getAllEntities()));var c=e.queryAny.apply(e,t.none),u=this.extractEntityIds(c.entities);n=this.differenceIdSets(n,u)}return n?this.idSetToEntityArray(n,e.getAllEntities()):[]},e.extractEntityIds=function(t){for(var e=new Set,n=0;n<t.length;n++)e.add(t[n].id);return e},e.intersectIdSets=function(t,e){for(var n,i=t.size<=e.size?[t,e]:[e,t],r=i[0],s=i[1],a=new Set,c=o(r);!(n=c()).done;){var u=n.value;s.has(u)&&a.add(u)}return a},e.differenceIdSets=function(t,e){for(var n,i=new Set,r=o(t);!(n=r()).done;){var s=n.value;e.has(s)||i.add(s)}return i},e.idSetToEntityArray=function(t,e){for(var n,i=new Map,r=o(e);!(n=r()).done;){var s=n.value;i.set(s.id,s)}for(var a,c=[],u=o(t);!(a=u()).done;){var h=a.value,l=i.get(h);l&&c.push(l)}return c},e.executeComplexQuery=function(t,e){return this.executeComplexQueryWithIdSets(t,e)},e.update=function(){if(this._enabled&&this.onCheckProcessing()){var t=this._performanceMonitor.startMonitoring(this._systemName),e=0;try{this.onBegin();var n=this.queryEntities();e=n.length,this.process(n)}finally{this._performanceMonitor.endMonitoring(this._systemName,t,e)}}},e.lateUpdate=function(){if(this._enabled&&this.onCheckProcessing()){var t=this._performanceMonitor.startMonitoring(this._systemName+"_Late"),e=0;try{var n=this.queryEntities();e=n.length,this.lateProcess(n),this.onEnd()}finally{this._performanceMonitor.endMonitoring(this._systemName+"_Late",t,e)}}},e.onBegin=function(){},e.process=function(t){},e.lateProcess=function(t){},e.onEnd=function(){},e.onCheckProcessing=function(){return!0},e.getPerformanceData=function(){return this._performanceMonitor.getSystemData(this._systemName)},e.getPerformanceStats=function(){return this._performanceMonitor.getSystemStats(this._systemName)},e.resetPerformanceData=function(){this._performanceMonitor.resetSystem(this._systemName)},e.toString=function(){var t=this.entities.length,e=this.getPerformanceData(),n=e?" ("+e.executionTime.toFixed(2)+"ms)":"";return this._systemName+"["+t+" entities]"+n},e.updateEntityTracking=function(t){for(var e,n=new Set(t),i=o(t);!(e=i()).done;){var r=e.value;this._trackedEntities.has(r)||(this._trackedEntities.add(r),this.onAdded(r))}for(var s,a=o(this._trackedEntities);!(s=a()).done;){var c=s.value;n.has(c)||(this._trackedEntities.delete(c),this.onRemoved(c))}},e.onAdded=function(t){},e.onRemoved=function(t){},e.addEventListener=function(t,e,n){var i;if(null!==(i=this.scene)&&void 0!==i&&i.eventSystem){var r=this.scene.eventSystem.on(t,e,n);r&&this._eventListeners.push({eventSystem:this.scene.eventSystem,eventType:t,handler:e,listenerRef:r})}else console.warn("["+this.systemName+"] Cannot add event listener: scene.eventSystem not available")},e.removeEventListener=function(t,e){var n=this._eventListeners.findIndex((function(n){return n.eventType===t&&n.handler===e}));if(n>=0){var i=this._eventListeners[n];i.eventSystem.off(t,i.listenerRef),this._eventListeners.splice(n,1)}},e.cleanupEventListeners=function(){for(var t,e=o(this._eventListeners);!(t=e()).done;){var n=t.value;try{n.eventSystem.off(n.eventType,n.listenerRef)}catch(t){console.warn("["+this.systemName+'] Failed to remove event listener for "'+n.eventType+'":',t)}}this._eventListeners.length=0},e.onDestroy=function(){},s(t,[{key:"entities",get:function(){return this.queryEntities()}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)}},{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled=t}},{key:"systemName",get:function(){return this._systemName}},{key:"scene",get:function(){return this._scene},set:function(t){this._scene=t}},{key:"matcher",get:function(){return this._matcher}}])}(),Jt=function(t){function e(e){return t.call(this,e)||this}return u(e,t),e.prototype.process=function(t){this.processSystem()},e}(Zt),Kt=function(t){function e(e){return t.call(this,e)||this}return u(e,t),e.prototype.process=function(t){},e}(Zt),$t=function(t){function e(e,n){var i;return(i=t.call(this,n)||this).acc=0,i.intervalRemainder=0,i.interval=e,i}u(e,t);var n=e.prototype;return n.onCheckProcessing=function(){return this.acc+=g.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)},n.getIntervalDelta=function(){return this.interval+this.intervalRemainder},e}(Zt),te=function(){function t(t){this.entityManager=t,this._allComponents=[],this._anyComponents=[],this._withoutComponents=[],this._withTags=[],this._withoutTags=[],this._activeOnly=!1,this._enabledOnly=!1,this._customPredicates=[]}var e=t.prototype;return e.withAll=function(){var t;return(t=this._allComponents).push.apply(t,arguments),this},e.withAny=function(){var t;return(t=this._anyComponents).push.apply(t,arguments),this},e.without=function(){var t;return(t=this._withoutComponents).push.apply(t,arguments),this},e.withTag=function(t){return this._withTags.push(t),this},e.withoutTag=function(t){return this._withoutTags.push(t),this},e.active=function(){return this._activeOnly=!0,this},e.enabled=function(){return this._enabledOnly=!0,this},e.where=function(t){return this._customPredicates.push(t),this},e.execute=function(){var t=this,e=[];if(this._allComponents.length>0){var n=this.entityManager.queryWithComponentIndex(this._allComponents,"AND");e=Array.from(n)}else if(this._anyComponents.length>0){var i=this.entityManager.queryWithComponentIndex(this._anyComponents,"OR");e=Array.from(i)}else e=this.entityManager.getAllEntities();return e.filter((function(e){return t.matchesEntity(e)}))},e.first=function(){var t=this;return this.entityManager.getAllEntities().find((function(e){return t.matchesEntity(e)}))||null},e.count=function(){var t=this;return this.entityManager.getAllEntities().filter((function(e){return t.matchesEntity(e)})).length},e.forEach=function(t){var e=this;this.entityManager.getAllEntities().forEach((function(n){e.matchesEntity(n)&&t(n)}))},e.matchesEntity=function(t){if(this._activeOnly&&!t.active)return!1;if(this._enabledOnly&&!t.enabled)return!1;if(this._allComponents.length>0)for(var e,n=o(this._allComponents);!(e=n()).done;){var i=e.value;if(!t.hasComponent(i))return!1}if(this._anyComponents.length>0){for(var r,s=!1,a=o(this._anyComponents);!(r=a()).done;){var c=r.value;if(t.hasComponent(c)){s=!0;break}}if(!s)return!1}if(this._withoutComponents.length>0)for(var u,h=o(this._withoutComponents);!(u=h()).done;){var l=u.value;if(t.hasComponent(l))return!1}if(this._withTags.length>0&&!this._withTags.includes(t.tag))return!1;if(this._withoutTags.length>0&&this._withoutTags.includes(t.tag))return!1;if(this._customPredicates.length>0)for(var d,f=o(this._customPredicates);!(d=f()).done;){if(!(0,d.value)(t))return!1}return!0},t}(),ee=function(){function t(){var t=this;this._entities=new Map,this._entitiesByName=new Map,this._entitiesByTag=new Map,this._destroyedEntities=new Set,this._identifierPool=new it,this._componentIndexManager=new lt,this._archetypeSystem=new dt,this._dirtyTrackingSystem=new mt,this._eventBus=new Tt(!1),$.eventBus=this._eventBus,this._eventBus.on("component:added",(function(e){var n=t._entities.get(e.entityId);n&&(t._componentIndexManager.addEntity(n),t._archetypeSystem.addEntity(n))})),this._eventBus.on("component:removed",(function(e){var n=t._entities.get(e.entityId);n&&(t._componentIndexManager.removeEntity(n),t._archetypeSystem.removeEntity(n))}))}var e=t.prototype;return e.createEntity=function(t){var e,n=this._identifierPool.checkOut();t||(t="Entity_"+n);var i=new $(t,n);return this._entities.set(n,i),this.updateNameIndex(i,!0),this.updateTagIndex(i,!0),i.components.length>0&&(this._componentIndexManager.addEntity(i),this._archetypeSystem.addEntity(i),this._dirtyTrackingSystem.markDirty(i,ut.COMPONENT_ADDED)),this._eventBus.emitEntityCreated({timestamp:Date.now(),source:"EntityManager",entityId:i.id,entityName:i.name,entityTag:null===(e=i.tag)||void 0===e?void 0:e.toString()}),i},e.createEntitiesBatch=function(t,e,n){if(void 0===e&&(e="Entity"),void 0===n&&(n=!1),t<=0)return[];for(var i=[],r=0;r<t;r++){var s=this._identifierPool.checkOut(),a=new $(e+"_"+s,s);i.push(a),this._entities.set(s,a)}for(var c=0,u=i;c<u.length;c++){var h=u[c];this.updateNameIndex(h,!0),this.updateTagIndex(h,!0),h.components.length>0&&(this._componentIndexManager.addEntity(h),this._archetypeSystem.addEntity(h),this._dirtyTrackingSystem.markDirty(h,ut.COMPONENT_ADDED))}if(!n)for(var l,d=Date.now(),f=o(i);!(l=f()).done;){var m,p=l.value;this._eventBus.emitEntityCreated({timestamp:d,source:"EntityManager",entityId:p.id,entityName:p.name,entityTag:null===(m=p.tag)||void 0===m?void 0:m.toString()})}return i},e.destroyEntity=function(t){var e,n=null;return!!(n="string"==typeof t?this.getEntityByName(t):"number"==typeof t?this._entities.get(t)||null:this._entities.get(t.id)||null)&&(this._destroyedEntities.add(n.id),this.updateNameIndex(n,!1),this.updateTagIndex(n,!1),this._componentIndexManager.removeEntity(n),this._archetypeSystem.removeEntity(n),this._dirtyTrackingSystem.markDirty(n,ut.COMPONENT_REMOVED),this._eventBus.emitEntityDestroyed({timestamp:Date.now(),source:"EntityManager",entityId:n.id,entityName:n.name,entityTag:null===(e=n.tag)||void 0===e?void 0:e.toString()}),n.destroy(),this._entities.delete(n.id),this._identifierPool.checkIn(n.id),!0)},e.getAllEntities=function(){return Array.from(this._entities.values())},e.getEntity=function(t){var e="string"==typeof t?parseInt(t):t;return this._entities.get(e)||null},e.getEntityByName=function(t){var e=this._entitiesByName.get(t);return e&&e.length>0?e[0]:null},e.getEntitiesByTag=function(t){return Array.from(this._entities.values()).filter((function(e){return e.tag===t}))},e.getEntitiesWithComponent=function(t){var e=this._componentIndexManager.query(t);return Array.from(e)},e.query=function(){return new te(this)},e.queryWithComponentIndex=function(t,e){return this._componentIndexManager.queryMultiple(t,e)},e.markEntityDirty=function(t,e){this._dirtyTrackingSystem.markDirty(t,ut.COMPONENT_MODIFIED,e)},e.getOptimizationStats=function(){return{componentIndex:this._componentIndexManager.getStats(),archetypeSystem:this._archetypeSystem.getAllArchetypes().map((function(t){return{id:t.id,componentTypes:t.componentTypes.map((function(t){return t.name})),entityCount:t.entities.length}})),dirtyTracking:this._dirtyTrackingSystem.getStats()}},e.updateNameIndex=function(t,e){if(t.name)if(e){var n=this._entitiesByName.get(t.name);n||(n=[],this._entitiesByName.set(t.name,n)),n.push(t)}else{var i=this._entitiesByName.get(t.name);if(i){var r=i.indexOf(t);-1!==r&&(i.splice(r,1),0===i.length&&this._entitiesByName.delete(t.name))}}},e.updateTagIndex=function(t,e){if(e){var n=this._entitiesByTag.get(t.tag);n||(n=[],this._entitiesByTag.set(t.tag,n)),n.push(t)}else{var i=this._entitiesByTag.get(t.tag);if(i){var r=i.indexOf(t);-1!==r&&(i.splice(r,1),0===i.length&&this._entitiesByTag.delete(t.tag))}}},s(t,[{key:"entityCount",get:function(){return this._entities.size}},{key:"activeEntityCount",get:function(){for(var t,e=0,n=o(this._entities.values());!(t=n()).done;){var i=t.value;i.active&&!i.isDestroyed&&e++}return e}},{key:"eventBus",get:function(){return this._eventBus}}])}(),ne=function(){function t(){}return t.getType=function(t){return t.constructor},t}(),ie=function(){function t(){}return t.toNumber=function(t){return null==t?0:Number(t)},t}();export{dt as ArchetypeSystem,Mt as AsyncEventHandler,M as BitMask64Utils,zt as Bits,W as COMPONENT_TYPE_NAME,w as Colors,Vt as Component,Wt as ComponentDataCollector,ht as ComponentIndex,lt as ComponentIndexManager,rt as ComponentPool,st as ComponentPoolManager,X as ComponentRegistry,ct as ComponentSparseSet,Z as ComponentStorage,Bt as ComponentTypeManager,I as ConsoleLogger,Gt as Core,Ht as DebugManager,ut as DirtyFlag,mt as DirtyTrackingSystem,j as ECSComponent,pt as ECSEventType,Dt as ECSFluentAPI,H as ECSSystem,St as EVENT_TYPES,Qt as Emitter,R as EnableSoA,$ as Entity,Ft as EntityDataCollector,et as EntityList,ee as EntityManager,nt as EntityProcessorList,te as EntityQueryBuilder,Zt as EntitySystem,Tt as EventBus,bt as EventHandler,yt as EventPriority,Et as EventTypeValidator,B as Float32,z as Float64,Yt as FuncPack,Ct as GlobalEventBus,y as GlobalManager,P as HighPrecision,it as IdentifierPool,F as Int32,$t as IntervalSystem,C as LogLevel,x as Logger,A as LoggerManager,Xt as Matcher,ie as NumberExtension,Kt as PassiveSystem,qt as PerformanceDataCollector,E as PerformanceMonitor,v as PerformanceWarningType,T as Pool,b as PoolManager,Jt as ProcessingSystem,gt as QuerySystem,U as SYSTEM_TYPE_NAME,wt as Scene,Ut as SceneDataCollector,L as SerializeMap,q as SoAStorage,ot as SparseSet,Lt as SystemDataCollector,g as Time,_ as Timer,S as TimerManager,_t as TypeSafeEventSystem,ne as TypeUtils,jt as WebSocketManager,Nt as World,Pt as WorldManager,Ot as createECSAPI,D as createLogger,Q as getComponentInstanceTypeName,G as getComponentTypeName,V as getSystemInstanceTypeName,Y as getSystemTypeName,k as resetLoggerColors,N as setGlobalLogLevel,O as setLoggerColors};
3
+ var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function o(n,i,r,o){var c=i&&i.prototype instanceof a?i:a,u=Object.create(c.prototype);return d(u,"_invoke",function(n,i,r){var o,a,c,u=0,h=r||[],l=!1,d={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return o=t,a=0,c=e,d.n=n,s}};function f(n,i){for(a=n,c=i,t=0;!l&&u&&!r&&t<h.length;t++){var r,o=h[t],f=d.p,p=o[2];n>3?(r=p===i)&&(c=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=e):o[0]<=f&&((r=n<2&&f<o[1])?(a=0,d.v=i,d.n=o[1]):f<p&&(r=n<3||o[0]>i||i>p)&&(o[4]=n,o[5]=i,d.n=p,a=0))}if(r||n>1)return s;throw l=!0,i}return function(r,h,p){if(u>1)throw TypeError("Generator is already running");for(l&&1===h&&f(h,p),a=h,c=p;(t=a<2?e:c)||!l;){o||(a?a<3?(a>1&&(d.n=-1),f(a,c)):d.n=c:d.v=c);try{if(u=2,o){if(a||(r="next"),t=o[r]){if(!(t=t.call(o,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=o.return)&&t.call(o),a<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),a=1);o=e}else if((t=(l=d.n<0)?c:n.call(i,d))!==s)break}catch(t){o=e,a=1,c=t}finally{u=1}}return{value:t,done:l}}}(n,r,o),!0),u}var s={};function a(){}function c(){}function u(){}t=Object.getPrototypeOf;var h=[][i]?t(t([][i]())):(d(t={},i,(function(){return this})),t),f=u.prototype=a.prototype=Object.create(h);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,d(e,r,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=u,d(f,"constructor",u),d(u,"constructor",c),c.displayName="GeneratorFunction",d(u,r,"GeneratorFunction"),d(f),d(f,r,"Generator"),d(f,i,(function(){return this})),d(f,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:o,m:p}})()}function d(e,t,n,i){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}d=function(e,t,n,i){function o(t,n){d(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:(o("next",0),o("throw",1),o("return",2))},d(e,t,n,i)}function f(e,t){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},f(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 m(e){var t="function"==typeof Map?new Map:void 0;return m=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}}),f(n,e)},m(e)}var y=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(){},o(e,[{key:"enabled",get:function(){return this._enabled},set:function(e){this.setEnabled(e)}}])}(),g=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}();g.deltaTime=0,g.unscaledDeltaTime=0,g.totalTime=0,g.unscaledTotalTime=0,g.timeScale=1,g.frameCount=0;var v,_=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+=g.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},o(e,[{key:"isDone",get:function(){return this._isDone}},{key:"elapsedTime",get:function(){return this._elapsedTime}}])}(),S=function(e){function t(){var t;return(t=e.apply(this,arguments)||this)._timers=[],t}u(t,e);var n=t.prototype;return n.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))},n.schedule=function(e,t,n,i){var r=new _;return r.initialize(e,t,n,i),this._timers.push(r),r},t}(y);!function(e){e.HIGH_EXECUTION_TIME="high_execution_time",e.HIGH_MEMORY_USAGE="high_memory_usage",e.HIGH_CPU_USAGE="high_cpu_usage",e.FREQUENT_GC="frequent_gc",e.LOW_FPS="low_fps",e.HIGH_ENTITY_COUNT="high_entity_count"}(v||(v={}));var E=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,o={name:e,executionTime:r,entityCount:n,averageTimePerEntity:n>0?r/n:0,lastUpdateTime:i};this._systemData.set(e,o),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=s(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],o=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: "+o.averageTime.toFixed(2)+"ms"),e.push(" Min/Max: "+o.minTime.toFixed(2)+"ms / "+o.maxTime.toFixed(2)+"ms"),e.push(" Total: "+o.totalTime.toFixed(2)+"ms ("+o.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=s(this._systemData.entries());!(t=i()).done;){var r=t.value,o=r[0],a=r[1];a.executionTime>e&&n.push(o+": "+a.executionTime.toFixed(2)+"ms (>"+e+"ms)")}return n},t.setMaxRecentSamples=function(e){this._maxRecentSamples=e;for(var t,n=s(this._systemStats.values());!(t=n()).done;)for(var i=t.value;i.recentTimes.length>e;)i.recentTimes.shift()},o(e,[{key:"isEnabled",get:function(){return this._isEnabled}}],[{key:"instance",get:function(){return e._instance||(e._instance=new e),e._instance}}])}(),C=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=s(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=s(this._pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t[r.name||r.toString()]=o.getStats()}return t},e.compactAllPools=function(){for(var e,t=s(this._pools.values());!(e=t()).done;){e.value.compact()}},e.clearAllPools=function(){for(var e,t=s(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],o=r[0],s=r[1];t.push(o+":"),t.push(" Size: "+s.size+"/"+s.maxSize),t.push(" Hit Rate: "+(100*s.hitRate).toFixed(1)+"%"),t.push(" Total Created: "+s.totalCreated),t.push(" Total Obtained: "+s.totalObtained),t.push(" Memory: "+(s.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}();C._pools=new Map;var b,T=function(){function e(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}e.getInstance=function(){return e.instance||(e.instance=new e),e.instance};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 C(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=s(this.pools.values());!(e=t()).done;){e.value.compact()}},t.clearAllPools=function(){for(var e,t=s(this.pools.values());!(e=t()).done;){e.value.clear()}},t.getAllStats=function(){for(var e,t=new Map,n=s(this.pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.set(r,o.getStats())}return t},t.getGlobalStats=function(){for(var e,t=0,n=0,i=0,r=0,o=0,a=0,c=s(this.pools.values());!(e=c()).done;){var u=e.value.getStats();t+=u.size,n+=u.maxSize,i+=u.totalCreated,r+=u.totalObtained,o+=u.totalReleased,a+=u.estimatedMemoryUsage}return{size:t,maxSize:n,totalCreated:i,totalObtained:r,totalReleased:o,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=s(this.pools);!(n=i()).done;){var r=n.value,o=r[0],a=r[1].getStats();e.push(o+":"),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=s(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},e}(),w=function(){function e(){}return e.create=function(e){if(e<0||e>=64)throw new Error("Bit index "+e+" out of range [0, 63]");return e<32?{lo:1<<e,hi:0}:{lo:0,hi:1<<e-32}},e.fromNumber=function(e){return{lo:e>>>0,hi:0}},e.hasAny=function(e,t){return 0!==(e.lo&t.lo)||0!==(e.hi&t.hi)},e.hasAll=function(e,t){return(e.lo&t.lo)===t.lo&&(e.hi&t.hi)===t.hi},e.hasNone=function(e,t){return 0===(e.lo&t.lo)&&0===(e.hi&t.hi)},e.isZero=function(e){return 0===e.lo&&0===e.hi},e.equals=function(e,t){return e.lo===t.lo&&e.hi===t.hi},e.setBit=function(e,t){if(t<0||t>=64)throw new Error("Bit index "+t+" out of range [0, 63]");t<32?e.lo|=1<<t:e.hi|=1<<t-32},e.clearBit=function(e,t){if(t<0||t>=64)throw new Error("Bit index "+t+" out of range [0, 63]");t<32?e.lo&=~(1<<t):e.hi&=~(1<<t-32)},e.orInPlace=function(e,t){e.lo|=t.lo,e.hi|=t.hi},e.andInPlace=function(e,t){e.lo&=t.lo,e.hi&=t.hi},e.xorInPlace=function(e,t){e.lo^=t.lo,e.hi^=t.hi},e.clear=function(e){e.lo=0,e.hi=0},e.copy=function(e,t){t.lo=e.lo,t.hi=e.hi},e.clone=function(e){return{lo:e.lo,hi:e.hi}},e.toString=function(e,t){if(void 0===t&&(t=2),2===t)return 0===e.hi?e.lo.toString(2):e.hi.toString(2)+e.lo.toString(2).padStart(32,"0");if(16===t)return 0===e.hi?"0x"+e.lo.toString(16).toUpperCase():"0x"+e.hi.toString(16).toUpperCase()+e.lo.toString(16).toUpperCase().padStart(8,"0");throw new Error("Only radix 2 and 16 are supported")},e.popCount=function(e){for(var t=0,n=e.lo,i=e.hi;n;)n&=n-1,t++;for(;i;)i&=i-1,t++;return t},e}();w.ZERO={lo:0,hi:0},function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error",e[e.Fatal=4]="Fatal",e[e.None=5]="None"}(b||(b={}));var M={BLACK:"",RED:"",GREEN:"",YELLOW:"",BLUE:"",MAGENTA:"",CYAN:"",WHITE:"",BRIGHT_BLACK:"",BRIGHT_RED:"",BRIGHT_GREEN:"",BRIGHT_YELLOW:"",BRIGHT_BLUE:"",BRIGHT_MAGENTA:"",BRIGHT_CYAN:"",BRIGHT_WHITE:"",RESET:"",BOLD:"",UNDERLINE:""},A=function(){function e(e){void 0===e&&(e={}),this._config=a({level:b.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,[b.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,[b.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,[b.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,[b.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,[b.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="["+b[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),o=2;o<i;o++)r[o-2]=arguments[o];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),o=2;o<i;o++)r[o-2]=arguments[o];switch(e){case b.Debug:var s,a;if(n)(s=console).debug.apply(s,[""+n.debug+t+n.reset].concat(r));else(a=console).debug.apply(a,[t].concat(r));break;case b.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 b.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 b.Error:var d,f;if(n)(d=console).error.apply(d,[""+n.error+t+n.reset].concat(r));else(f=console).error.apply(f,[t].concat(r));break;case b.Fatal:var p,m;if(n)(p=console).error.apply(p,[""+n.fatal+t+n.reset].concat(r));else(m=console).error.apply(m,[t].concat(r))}},t.getColors=function(){return a({},{debug:M.BRIGHT_BLACK,info:M.GREEN,warn:M.YELLOW,error:M.RED,fatal:M.BRIGHT_RED,reset:M.RESET},this._config.colors)},e}(),I=function(){function e(){this._loggers=new Map,this._defaultLevel=b.Info,this._defaultLogger=new A({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 A({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 A&&this._defaultLogger.setLevel(e);for(var t,n=s(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof A&&i.setLevel(e)}},t.createChildLogger=function(e,t){var n=e+"."+t;return this.getLogger(n)},t.setGlobalColors=function(e){this._defaultLogger instanceof A&&this._defaultLogger.setColors(e);for(var t,n=s(this._loggers.values());!(t=n()).done;){var i=t.value;i instanceof A&&i.setColors(e)}},t.resetColors=function(){this._defaultLogger instanceof A&&this._defaultLogger.setColors({});for(var e,t=s(this._loggers.values());!(e=t()).done;){var n=e.value;n instanceof A&&n.setColors({})}},e}(),x=I.getInstance().getLogger();function k(e){return I.getInstance().getLogger(e)}function D(e){I.getInstance().setGlobalColors(e)}function P(){I.getInstance().resetColors()}function R(e){I.getInstance().setGlobalLevel(e)}function B(e){return e.__enableSoA=!0,e}function N(e,t){var n=String(t);e.constructor.__highPrecisionFields||(e.constructor.__highPrecisionFields=new Set),e.constructor.__highPrecisionFields.add(n)}function O(e,t){var n=String(t);e.constructor.__float64Fields||(e.constructor.__float64Fields=new Set),e.constructor.__float64Fields.add(n)}function z(e,t){var n=String(t);e.constructor.__float32Fields||(e.constructor.__float32Fields=new Set),e.constructor.__float32Fields.add(n)}function W(e,t){var n=String(t);e.constructor.__int32Fields||(e.constructor.__int32Fields=new Set),e.constructor.__int32Fields.add(n)}function F(e,t){var n=String(t);e.constructor.__serializeMapFields||(e.constructor.__serializeMapFields=new Set),e.constructor.__serializeMapFields.add(n)}var L=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(e){var t=new e,n=e.__highPrecisionFields||new Set,i=e.__float64Fields||new Set,r=e.__float32Fields||new Set,o=e.__int32Fields||new Set,s=e.__serializeMapFields||new Set,a=e.__serializeSetFields||new Set,c=e.__serializeArrayFields||new Set;for(var u in t)if(t.hasOwnProperty(u)&&"id"!==u){var h=t[u],l=typeof h;"number"===l?n.has(u)||(i.has(u)?this.fields.set(u,new Float64Array(this._capacity)):o.has(u)?this.fields.set(u,new Int32Array(this._capacity)):(r.has(u),this.fields.set(u,new Float32Array(this._capacity)))):"boolean"===l?this.fields.set(u,new Float32Array(this._capacity)):"string"===l?this.stringFields.set(u,new Array(this._capacity)):"object"===l&&null!==h&&(s.has(u)||a.has(u)||c.has(u))&&this.serializedFields.set(u,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,o=this.type.__serializeMapFields||new Set,s=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,o,s,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,o){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)):(o.has(n)&&Array.isArray(t),JSON.stringify(t))}catch(t){return e._logger.warn("SoA序列化字段 "+n+" 失败:",t),"{}"}},t.deserializeValue=function(t,n,i,r,o){try{var s=JSON.parse(t);return i.has(n)?new Map(s):r.has(n)?new Set(s):(o.has(n),s)}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=s(e.entries());!(n=r()).done;){var o=n.value,a=o[0],c=o[1];i.set(a,this.deepClone(c))}return i}if(e instanceof Set){for(var u,h=new Set,l=s(e.values());!(u=l()).done;){var d=u.value;h.add(this.deepClone(d))}return h}var f={};for(var p in e)e.hasOwnProperty(p)&&(f[p]=this.deepClone(e[p]));return f},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,o=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=s(this.fields.entries());!(n=c()).done;){var u=n.value,h=u[0],l=u[1][t],d=this.getFieldType(h);i[h]="boolean"===d?1===l:l}for(var f,p=s(this.stringFields.entries());!(f=p()).done;){var m=f.value,y=m[0],g=m[1];i[y]=g[t]}for(var v,_=s(this.serializedFields.entries());!(v=_()).done;){var S=v.value,E=S[0],C=S[1][t];C&&(i[E]=this.deserializeValue(C,E,r,o,a))}var b=this.complexFields.get(e);if(b)for(var T,w=s(b.entries());!(T=w()).done;){var M=T.value,A=M[0],I=M[1];i[A]=I}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(e){for(var t,n=s(this.fields.entries());!(t=n()).done;){var i=t.value,r=i[0],o=i[1],a=void 0;(a=o instanceof Float32Array?new Float32Array(e):o instanceof Float64Array?new Float64Array(e):new Int32Array(e)).set(o),this.fields.set(r,a)}for(var c,u=s(this.stringFields.entries());!(c=u()).done;){for(var h=c.value,l=h[0],d=h[1],f=new Array(e),p=0;p<d.length;p++)f[p]=d[p];this.stringFields.set(l,f)}for(var m,y=s(this.serializedFields.entries());!(m=y()).done;){for(var g=m.value,v=g[0],_=g[1],S=new Array(e),E=0;E<_.length;E++)S[E]=_[E];this.serializedFields.set(v,S)}this._capacity=e},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=s(this.fields.values());!(e=t()).done;){e.value.fill(0)}for(var n,i=s(this.stringFields.values());!(n=i()).done;)for(var r=n.value,o=0;o<r.length;o++)r[o]=void 0;for(var a,c=s(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],o=r[0],a=r[1];if(t.set(o,i),n[i]=o,i!==a){for(var c,u=s(this.fields.entries());!(c=u()).done;){var h=c.value[1];h[i]=h[a]}for(var l,d=s(this.stringFields.entries());!(l=d()).done;){var f=l.value[1];f[i]=f[a]}for(var p,m=s(this.serializedFields.entries());!(p=m()).done;){var y=p.value[1];y[i]=y[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=s(this.fields.entries());!(e=i()).done;){var r=e.value,o=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"):(c=4,u="int32");var h=a.length*c;t+=h,n.set(o,{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}();L._logger=k("SoAStorage");var q=Symbol("ComponentTypeName"),j=Symbol("SystemTypeName");function U(e){return function(t){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return t[q]=e,t}}function H(e){return function(t){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return t[j]=e,t}}function G(e){var t=e[q];return t||(e.name||"UnknownComponent")}function Y(e){var t=e[j];return t||(e.name||"UnknownSystem")}function Q(e){return G(e.constructor)}function V(e){return Y(e.constructor)}var X=function(){function e(){}return e.register=function(e){var t=G(e);if(this.componentTypes.has(e))return this.componentTypes.get(e);if(this.nextBitIndex>=this.maxComponents)throw new Error("Maximum number of component types ("+this.maxComponents+") exceeded");var n=this.nextBitIndex++;return this.componentTypes.set(e,n),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=G(e);throw new Error("Component type "+n+" is not registered")}return w.create(t)},e.getBitIndex=function(e){var t=this.componentTypes.get(e);if(void 0===t){var n=G(e);throw new Error("Component type "+n+" is not registered")}return t},e.isRegistered=function(e){return this.componentTypes.has(e)},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);if(this.nextBitIndex>=this.maxComponents)throw new Error("Maximum number of component types ("+this.maxComponents+") exceeded");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=w.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=w.clone(w.ZERO),r=s(e);!(n=r()).done;){var o=n.value,a=this.getComponentId(o);if(void 0!==a){var c=w.create(a);w.orInPlace(i,c)}}return this.maskCache.set(t,i),i},e.clearMaskCache=function(){this.maskCache.clear()},e.reset=function(){this.componentTypes.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0},e}();X._logger=k("ComponentStorage"),X.componentTypes=new Map,X.componentNameToType=new Map,X.componentNameToId=new Map,X.maskCache=new Map,X.nextBitIndex=0,X.maxComponents=64;var Z=function(){function e(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e,X.isRegistered(e)||X.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 "+G(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],o=this.entityIds[i];this.dense[t]=r,this.entityIds[t]=o,this.entityToIndex.set(o,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}},o(e,[{key:"size",get:function(){return this.dense.length}},{key:"type",get:function(){return this.componentType}}])}(),J=function(){function e(){this.storages=new Map}var t=e.prototype;return t.isSoAStorage=function(e){return this.storages.get(e)instanceof L},t.getSoAStorage=function(e){var t=this.getStorage(e);return t instanceof L?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 L(t),e._logger.info("为 "+G(t)+" 启用SoA优化(适用于大规模批量操作)")):n=new Z(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=s(this.storages.values());!(t=n()).done;){t.value.removeComponent(e)}},t.getComponentMask=function(e){for(var t,n=w.clone(w.ZERO),i=s(this.storages.entries());!(t=i()).done;){var r=t.value,o=r[0];if(r[1].hasComponent(e)){var a=X.getBitMask(o);w.orInPlace(n,a)}}return n},t.getAllStats=function(){for(var e,t=new Map,n=s(this.storages.entries());!(e=n()).done;){var i=e.value,r=i[0],o=i[1],a=G(r);t.set(a,o.getStats())}return t},t.clear=function(){for(var e,t=s(this.storages.values());!(e=t()).done;){e.value.clear()}this.storages.clear()},e}();J._logger=k("ComponentStorage");var K=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}(),$=function(){function e(e,t){this.components=[],this.scene=null,this.updateInterval=1,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=w.clone(w.ZERO),this._componentsByTypeId=[],this._componentDenseIndexByTypeId=[],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.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 o=i(e,n);return this.addComponent(o)},t.addComponentInternal=function(e){var t=e.constructor;X.isRegistered(t)||X.register(t);var n=X.getBitIndex(t);e.entity=this,this._componentsByTypeId[n]=e;var i=this.components.length;this._componentDenseIndexByTypeId[n]=i,this.components.push(e);var r=X.getBitMask(t);return w.orInPlace(this._componentMask,r),e},t.addComponent=function(t){var n,i=t.constructor;if(this.hasComponent(i))throw new Error("Entity "+this.name+" already has component "+G(i));(this.addComponentInternal(t),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.addComponent(this.id,t),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:G(i),component:t});return e.notifyQuerySystems(this),t},t.getComponent=function(e){if(!X.isRegistered(e))return null;var t=X.getBitMask(e);if(w.hasNone(this._componentMask,t))return null;var n=X.getBitIndex(e),i=this._componentsByTypeId[n];if(i&&i.constructor===e)return i;if(this.scene&&this.scene.componentStorageManager){var r=this.scene.componentStorageManager.getComponent(this.id,e);if(r){if(this._componentsByTypeId[n]=r,!this.components.includes(r)){var o=this.components.length;this._componentDenseIndexByTypeId[n]=o,this.components.push(r)}return r}}for(var s=0;s<this.components.length;s++){var a=this.components[s];if(a instanceof e)return this._componentsByTypeId[n]=a,this._componentDenseIndexByTypeId[n]=s,a}return null},t.hasComponent=function(e){if(!X.isRegistered(e))return!1;var t=X.getBitMask(e);return w.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=t.constructor;if(X.isRegistered(n)){var i=X.getBitIndex(n);this._componentsByTypeId[i]=void 0,w.clearBit(this._componentMask,i);var r,o=this._componentDenseIndexByTypeId[i];if(void 0!==o&&o<this.components.length){var s=this.components.length-1;if(o!==s){var a=this.components[s];this.components[o]=a;var c=a.constructor,u=X.getBitIndex(c);this._componentDenseIndexByTypeId[u]=o}this.components.pop()}if(this._componentDenseIndexByTypeId[i]=-1,this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,n),t.onRemovedFromEntity&&t.onRemovedFromEntity(),e.eventBus)e.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(r=this.tag)||void 0===r?void 0:r.toString(),componentType:G(n),component:t});t.entity=null,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);this._componentsByTypeId.length=0,this._componentDenseIndexByTypeId.length=0,w.clear(this._componentMask);for(var n,i=s(t);!(n=i()).done;){var r=n.value,o=r.constructor;this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,o),r.onRemovedFromEntity(),r.entity=null}this.components.length=0,e.notifyQuerySystems(this)},t.addComponents=function(t){for(var n,i=[],r=s(t);!(n=r()).done;){var o=n.value;try{i.push(this.addComponent(o))}catch(t){e._logger.warn("添加组件失败 "+Q(o)+":",t)}}return i},t.removeComponentsByTypes=function(e){for(var t,n=[],i=s(e);!(t=i()).done;){var r=t.value;n.push(this.removeComponentByType(r))}return n},t.getComponents=function(e){for(var t,n=[],i=s(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=s([].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=s(this._children);!(n=i()).done;){var r=n.value;if(r.name===e)return r}if(t)for(var o,a=s(this._children);!(o=a()).done;){var c=o.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=s(this._children);!(n=r()).done;){var o=n.value;o.tag===e&&i.push(o)}if(t)for(var a,c=s(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=s(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.update=function(){if(this.activeInHierarchy&&!this._isDestroyed){for(var e,t=s(this.components);!(e=t()).done;){var n=e.value;n.enabled&&n.update()}for(var i,r=s(this._children);!(i=r()).done;){i.value.update()}}},t.destroy=function(){if(!this._isDestroyed){this._isDestroyed=!0;for(var e,t=s([].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.compareTo=function(e){return K.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 Q(e)})),componentMask:w.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(),indexMappingSize:this._componentsByTypeId.filter((function(e){return void 0!==e})).length,denseIndexMappingSize:this._componentDenseIndexByTypeId.filter((function(e){return-1!==e&&void 0!==e})).length}},o(e,[{key:"isDestroyed",get:function(){return this._isDestroyed}},{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}}])}();$._logger=k("Entity"),$.entityComparer=new K,$.eventBus=null;var ee=function(){function e(e,t){this.scene=e,this.storageManager=t,this.entity=new $("",e.identifierPool.checkOut())}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 o=r[i];this.entity.addComponent(o)}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 o=r[i].build();this.entity.addChild(o)}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}(),te=function(){function e(e){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._isUpdating=!1,this._enableEntityDirectUpdate=!1,this._scene=e}var t=e.prototype;return t.setEnableEntityDirectUpdate=function(e){this._enableEntityDirectUpdate=e},t.add=function(e){this._isUpdating?this._entitiesToAdd.push(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._isUpdating?this._entitiesToRemove.push(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=s(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=s(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=s(this._entitiesToRemove);!(i=r()).done;){var o=i.value;this.removeImmediate(o)}this._entitiesToRemove.length=0}},t.update=function(){this._isUpdating=!0;try{if(this._enableEntityDirectUpdate)for(var e=0;e<this.buffer.length;e++){var t=this.buffer[e];t.enabled&&!t.isDestroyed&&t.update()}}finally{this._isUpdating=!1}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=s(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=s(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=s(this.buffer);!(t=n()).done;){e(t.value)}},t.forEachWhere=function(e,t){for(var n,i=s(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=s(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}},o(e,[{key:"count",get:function(){return this.buffer.length}}])}(),ne=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=s(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=s(this._processors);!(t=n()).done;){var i=t.value;try{i.reset()}catch(t){e._logger.error("Error in processor "+V(i)+":",t)}}this._isDirty=!1,this._processors.length=0},t.update=function(){this.sortProcessors();for(var t,n=s(this._processors);!(t=n()).done;){var i=t.value;try{i.update()}catch(t){e._logger.error("Error in processor "+V(i)+":",t)}}},t.lateUpdate=function(){for(var e,t=s(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)},o(e,[{key:"processors",get:function(){return this._processors}},{key:"count",get:function(){return this._processors.length}}])}();ne._logger=k("EntityProcessorList");var ie=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=s(this._generations);!(t=r()).done;){var o=t.value,a=o[0],c=o[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=[],o=[],a=s(this._pendingRecycle);!(n=a()).done;){var c=n.value;t||i-c.timestamp>=this._recycleDelay?r.push(c):o.push(c)}for(var u=0,h=r;u<h.length;u++){var l=h[u];if(this._isValidId(l.index,l.generation)){var d=l.generation+1;d>e.MAX_GENERATION&&(d=1),this._generations.set(l.index,d),this._freeIndices.push(l.index)}}this._pendingRecycle=o}},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}();ie.MAX_INDEX=65535,ie.MAX_GENERATION=65535;var re=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=s(this._sparse);!(n=i()).done;){var r=n.value,o=r[0],a=r[1];if(a>=this._dense.length||this._dense[a]!==o)return!1}return!0},o(e,[{key:"size",get:function(){return this._dense.length}},{key:"isEmpty",get:function(){return 0===this._dense.length}}])}(),oe=function(e){function t(){return e.call(this)||this}return u(t,e),t.prototype.reset=function(){this.clear()},t}(m(Set)),se=function(){function e(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new re}var t=e.prototype;return t.addEntity=function(e){this._entities.has(e)&&this.removeEntity(e);for(var t,n=w.clone(w.ZERO),i=new Set,r=s(e.components);!(t=r()).done;){var o=t.value.constructor;i.add(o),X.isRegistered(o)||X.register(o);var a=X.getBitMask(o);w.orInPlace(n,a)}this._entities.add(e);for(var c=this._entities.getIndex(e);this._componentMasks.length<=c;)this._componentMasks.push(w.clone(w.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=w.clone(w.ZERO),o=s(t);!(i=o()).done;){var a=i.value;if(!X.isRegistered(a))return new Set;var c=X.getBitMask(a);w.orInPlace(r,c)}var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var i=n._componentMasks[t];w.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=w.clone(w.ZERO),o=s(t);!(i=o()).done;){var a=i.value;if(X.isRegistered(a)){var c=X.getBitMask(a);w.orInPlace(r,c)}}if(w.equals(r,w.ZERO))return new Set;var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var i=n._componentMasks[t];w.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(!X.isRegistered(t))return!1;var i=this._componentMasks[n],r=X.getBitMask(t);return w.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=s(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=s(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=s(this._componentToEntities.values());!(e=n()).done;)for(var i,r=s(e.value);!(i=r()).done;){var o=i.value;t.add(o)}for(var a,c=s(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=s(e.components);!(t=i()).done;){var r=t.value;n.add(r.constructor)}return n},t.updateComponentMappings=function(t,n,i){for(var r,o=s(n);!(r=o()).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)))}},o(e,[{key:"size",get:function(){return this._entities.size}},{key:"isEmpty",get:function(){return this._entities.isEmpty}}])}();se._entitySetPool=C.getPool(oe,50,512);var ae,ce=function(){function e(){this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now(),this._sparseSet=new se}var t=e.prototype;return t.addEntity=function(e){this._sparseSet.addEntity(e),this._lastUpdated=Date.now()},t.removeEntity=function(e){this._sparseSet.removeEntity(e),this._lastUpdated=Date.now()},t.query=function(e){var t=performance.now(),n=this._sparseSet.queryByComponent(e);return this._queryCount++,this._totalQueryTime+=performance.now()-t,n},t.queryMultiple=function(e,t){var n,i=performance.now();return n=0===e.length?new Set:1===e.length?this.query(e[0]):"AND"===t?this._sparseSet.queryMultipleAnd(e):this._sparseSet.queryMultipleOr(e),this._queryCount++,this._totalQueryTime+=performance.now()-i,n},t.clear=function(){this._sparseSet.clear(),this._lastUpdated=Date.now()},t.getStats=function(){var e=this._sparseSet.getMemoryStats();return{size:this._sparseSet.size,memoryUsage:e.totalMemory,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}},e}(),ue=function(){function e(){this._index=new ce}var t=e.prototype;return t.addEntity=function(e){this._index.addEntity(e)},t.removeEntity=function(e){this._index.removeEntity(e)},t.query=function(e){return this._index.query(e)},t.queryMultiple=function(e,t){return this._index.queryMultiple(e,t)},t.getStats=function(){return this._index.getStats()},t.clear=function(){this._index.clear()},e}(),he=function(){function e(){this._archetypes=new Map,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._entityComponentTypesCache=new Map,this._archetypeIdCache=new Map}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),this.updateComponentIndexes(i,t,!0)},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){var r=new Set;t&&(t.entities.delete(e),t.componentTypes.forEach((function(e){return r.add(e)})));var o=this._archetypes.get(i);o||(o=this.createArchetype(n)),o.entities.add(e),this._entityToArchetype.set(e,o),n.forEach((function(e){return r.add(e)})),t&&this.updateComponentIndexes(t,t.componentTypes,!1),this.updateComponentIndexes(o,n,!0)}},t.queryArchetypes=function(e,t){void 0===t&&(t="AND");var n=[],i=0;if("AND"===t)for(var r,o=s(this._archetypes.values());!(r=o()).done;){var a=r.value;this.archetypeContainsAllComponents(a,e)&&(n.push(a),i+=a.entities.size)}else{for(var c,u=new Set,h=s(e);!(c=h()).done;){var l=c.value,d=this._componentToArchetypes.get(l);if(d)for(var f,p=s(d);!(f=p()).done;){var m=f.value;u.add(m)}}for(var y,g=s(u);!(y=g()).done;){var v=y.value;n.push(v),i+=v.entities.size}}return{archetypes:n,totalEntities:i}},t.getEntityArchetype=function(e){return this._entityToArchetype.get(e)},t.getAllArchetypes=function(){return Array.from(this._archetypes.values())},t.clear=function(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._entityComponentTypesCache.clear(),this._archetypeIdCache.clear()},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){var t=e.map((function(e){return G(e)})).sort().join("|"),n=this._archetypeIdCache.get(t);return n||(n=t,this._archetypeIdCache.set(t,n)),n},t.createArchetype=function(e){var t=this.generateArchetypeId(e),n={id:t,componentTypes:[].concat(e),entities:new Set};return this._archetypes.set(t,n),n},t.archetypeContainsAllComponents=function(e,t){for(var n,i=s(t);!(n=i()).done;){var r=n.value;if(!e.componentTypes.includes(r))return!1}return!0},t.updateComponentIndexes=function(e,t,n){for(var i,r=s(t);!(i=r()).done;){var o=i.value,a=this._componentToArchetypes.get(o);a||(a=new Set,this._componentToArchetypes.set(o,a)),n?a.add(e):(a.delete(e),0===a.size&&this._componentToArchetypes.delete(o))}},e}();!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(ae||(ae={}));var le,de,fe=function(){function e(){this._logger=k("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.entityIndex={byMask:new Map,byComponentType:new Map,byTag:new Map,byName:new Map},this.componentIndexManager=new ue,this.archetypeSystem=new he}var t=e.prototype;return t.setEntities=function(e){this.entities=e,this.clearQueryCache(),this.rebuildIndexes()},t.addEntity=function(e,t){void 0===t&&(t=!1),this.entities.includes(e)||(this.entities.push(e),this.addEntityToIndexes(e),this.componentIndexManager.addEntity(e),this.archetypeSystem.addEntity(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=s(e);!(t=r()).done;){var o=t.value;n.has(o.id)||(this.entities.push(o),this.addEntityToIndexes(o),this.componentIndexManager.addEntity(o),this.archetypeSystem.addEntity(o),n.add(o.id),i++)}i>0&&this.clearQueryCache()}},t.addEntitiesUnchecked=function(e){if(0!==e.length){for(var t,n=s(e);!(t=n()).done;){var i=t.value;this.entities.push(i)}for(var r,o=s(e);!(r=o()).done;){var a=r.value;this.addEntityToIndexes(a),this.componentIndexManager.addEntity(a),this.archetypeSystem.addEntity(a)}this.clearQueryCache()}},t.removeEntity=function(e){var t=this.entities.indexOf(e);-1!==t&&(this.entities.splice(t,1),this.removeEntityFromIndexes(e),this.componentIndexManager.removeEntity(e),this.archetypeSystem.removeEntity(e),this.clearQueryCache(),this._version++)},t.updateEntity=function(e){this.entities.includes(e)?(this.removeEntityFromIndexes(e),this.archetypeSystem.updateEntity(e),this.componentIndexManager.removeEntity(e),this.componentIndexManager.addEntity(e),this.addEntityToIndexes(e),this.clearQueryCache(),this._version++):this.addEntity(e)},t.addEntityToIndexes=function(e){var t=e.componentMask.toString();(this.entityIndex.byMask.get(t)||this.createAndSetMaskIndex(t)).add(e);for(var n=e.components,i=0;i<n.length;i++){var r=n[i].constructor;(this.entityIndex.byComponentType.get(r)||this.createAndSetComponentIndex(r)).add(e)}var o=e.tag;void 0!==o&&(this.entityIndex.byTag.get(o)||this.createAndSetTagIndex(o)).add(e);var s=e.name;s&&(this.entityIndex.byName.get(s)||this.createAndSetNameIndex(s)).add(e)},t.createAndSetMaskIndex=function(e){var t=new Set;return this.entityIndex.byMask.set(e,t),t},t.createAndSetComponentIndex=function(e){var t=new Set;return this.entityIndex.byComponentType.set(e,t),t},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){var t=e.componentMask.toString(),n=this.entityIndex.byMask.get(t);n&&(n.delete(e),0===n.size&&this.entityIndex.byMask.delete(t));for(var i,r=s(e.components);!(i=r()).done;){var o=i.value.constructor,a=this.entityIndex.byComponentType.get(o);a&&(a.delete(e),0===a.size&&this.entityIndex.byComponentType.delete(o))}if(void 0!==e.tag){var c=this.entityIndex.byTag.get(e.tag);c&&(c.delete(e),0===c.size&&this.entityIndex.byTag.delete(e.tag))}if(e.name){var u=this.entityIndex.byName.get(e.name);u&&(u.delete(e),0===u.size&&this.entityIndex.byName.delete(e.name))}},t.rebuildIndexes=function(){this.entityIndex.byMask.clear(),this.entityIndex.byComponentType.clear(),this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear(),this.componentIndexManager.clear();for(var e,t=s(this.entities);!(e=t()).done;){var n=e.value;this.addEntityToIndexes(n),this.componentIndexManager.addEntity(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.generateCacheKey("all",n),o=this.getFromCache(r);if(o)return this.queryStats.cacheHits++,{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!0};var a=[],c=this.archetypeSystem.queryArchetypes(n,"AND");if(c.archetypes.length>0){this.queryStats.archetypeHits++;for(var u,h=s(c.archetypes);!(u=h()).done;){var l,d=u.value;(l=a).push.apply(l,d.entities)}}else try{if(1===n.length){this.queryStats.indexHits++;var f=this.componentIndexManager.query(n[0]);a=Array.from(f)}else{var p=this.componentIndexManager.queryMultiple(n,"AND");a=Array.from(p)}}catch(e){a=[]}return this.addToCache(r,a),{entities:a,count:a.length,executionTime:performance.now()-e,fromCache:!1}},t.queryMultipleComponents=function(e){for(var t,n=null,i=1/0,r=s(e);!(t=r()).done;){var o=t.value,a=this.entityIndex.byComponentType.get(o);if(!a||0===a.size)return[];a.size<i&&(i=a.size,n=a)}if(!n)return[];for(var c,u=this.createComponentMask(e),h=[],l=s(n);!(c=l()).done;){var d=c.value;w.hasAll(d.componentMask,u)&&h.push(d)}return h},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.generateCacheKey("any",n),o=this.getFromCache(r);if(o)return this.queryStats.cacheHits++,{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!0};var a,c=this.archetypeSystem.queryArchetypes(n,"OR");if(c.archetypes.length>0){this.queryStats.archetypeHits++,a=[];for(var u,h=s(c.archetypes);!(u=h()).done;){var l,d=u.value;(l=a).push.apply(l,d.entities)}}else{var f=this.componentIndexManager.queryMultiple(n,"OR");a=Array.from(f)}return this.addToCache(r,a),{entities:a,count:a.length,executionTime:performance.now()-e,fromCache:!1}},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.generateCacheKey("none",n),o=this.getFromCache(r);if(o)return this.queryStats.cacheHits++,{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!0};var s=this.createComponentMask(n),a=this.entities.filter((function(e){return w.hasNone(e.componentMask,s)}));return this.addToCache(r,a),{entities:a,count:a.length,executionTime:performance.now()-e,fromCache:!1}},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=Array.from(this.entityIndex.byComponentType.get(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=s(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 o,a=1/0,c="",u=1/0,h=s(this.queryCache.entries());!(o=h()).done;){var l=o.value,d=l[0],f=l[1];(f.hitCount<a||f.hitCount===a&&f.timestamp<u)&&(a=f.hitCount,c=d,u=f.timestamp)}c&&this.queryCache.delete(c)}},t.clearQueryCache=function(){this.queryCache.clear(),this.componentMaskCache.clear()},t.generateCacheKey=function(e,t){return 1===t.length?e+":"+G(t[0]):e+":"+t.map((function(e){return G(e)})).sort().join(",")},t.clearCache=function(){this.clearQueryCache()},t.createComponentMask=function(e){var t=e.map((function(e){return G(e)})).sort().join(","),n=this.componentMaskCache.get(t);if(n)return n;for(var i,r=w.clone(w.ZERO),o=!1,a=s(e);!(i=a()).done;){var c=i.value;try{var u=X.getBitMask(c);w.orInPlace(r,u),o=!0}catch(e){this._logger.warn("组件类型 "+G(c)+" 未注册,跳过")}}return o||(r={lo:4294967295,hi:4294967295}),this.componentMaskCache.set(t,r),r},t.getAllEntities=function(){return this.entities},t.getStats=function(){return{entityCount:this.entities.length,indexStats:{maskIndexSize:this.entityIndex.byMask.size,componentIndexSize:this.entityIndex.byComponentType.size,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:{componentIndex:this.componentIndexManager.getStats(),archetypeSystem:this.archetypeSystem.getAllArchetypes().map((function(e){return{id:e.id,componentTypes:e.componentTypes.map((function(e){return G(e)})),entityCount:e.entities.size}}))},cacheStats:{size:this.queryCache.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)},o(e,[{key:"version",get:function(){return this._version}}])}(),pe=function(){function e(e){this._logger=k("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:ae.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:ae.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:ae.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 ae.ALL:return(e=this.querySystem).queryAll.apply(e,r.componentTypes);case ae.ANY:return(t=this.querySystem).queryAny.apply(t,r.componentTypes);case ae.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=w.clone(w.ZERO),i=s(e);!(t=i()).done;){var r=t.value;try{var o=X.getBitMask(r);w.orInPlace(n,o)}catch(e){this._logger.warn("组件类型 "+G(r)+" 未注册,跳过")}}return n},t.reset=function(){return this.conditions=[],this},e}(),me=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,o=performance.now(),a=[],c=s(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()-o)}}},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 o="listener_"+this.nextListenerId++,s={handler:n,config:a({priority:0},i),id:o};return r.push(s),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),o},t.executeEvent=function(){var t=n(l().m((function t(i,r){var o,a,c,u,h,d,f,p,m,y;return l().w((function(t){for(;;)switch(t.n){case 0:if((o=this.listeners.get(i))&&0!==o.length){t.n=1;break}return t.a(2);case 1:for(a=performance.now(),c=[],u=this.sortListenersByPriority(o),h=u.filter((function(e){return!e.config.async})),d=u.filter((function(e){return e.config.async})),f=s(h);!(p=f()).done;){m=p.value;try{m.config.context?m.handler.call(m.config.context,r):m.handler(r),m.config.once&&c.push(m.id)}catch(t){e._logger.error("同步事件处理器执行错误 "+i+":",t)}}return y=d.map(function(){var t=n(l().m((function t(n){var o;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,o=t.v,e._logger.error("异步事件处理器执行错误 "+i+":",o);case 5:return t.a(2)}}),t,null,[[0,4]])})));return function(e){return t.apply(this,arguments)}}()),t.n=2,Promise.all(y);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)},o=s(t);!(i=o()).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 o=setTimeout((function(){n.flushBatch(e)}),r.delay);this.batchTimers.set(e,o)}},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=s(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}();me._logger=k("EventSystem"),function(e){e.ENTITY_CREATED="entity:created",e.ENTITY_DESTROYED="entity:destroyed",e.ENTITY_ENABLED="entity:enabled",e.ENTITY_DISABLED="entity:disabled",e.ENTITY_TAG_ADDED="entity:tag:added",e.ENTITY_TAG_REMOVED="entity:tag:removed",e.ENTITY_NAME_CHANGED="entity:name:changed",e.COMPONENT_ADDED="component:added",e.COMPONENT_REMOVED="component:removed",e.COMPONENT_MODIFIED="component:modified",e.COMPONENT_ENABLED="component:enabled",e.COMPONENT_DISABLED="component:disabled",e.SYSTEM_ADDED="system:added",e.SYSTEM_REMOVED="system:removed",e.SYSTEM_ENABLED="system:enabled",e.SYSTEM_DISABLED="system:disabled",e.SYSTEM_PROCESSING_START="system:processing:start",e.SYSTEM_PROCESSING_END="system:processing:end",e.SYSTEM_ERROR="system:error",e.SCENE_CREATED="scene:created",e.SCENE_DESTROYED="scene:destroyed",e.SCENE_ACTIVATED="scene:activated",e.SCENE_DEACTIVATED="scene:deactivated",e.SCENE_PAUSED="scene:paused",e.SCENE_RESUMED="scene:resumed",e.QUERY_EXECUTED="query:executed",e.QUERY_CACHE_HIT="query:cache:hit",e.QUERY_CACHE_MISS="query:cache:miss",e.QUERY_OPTIMIZED="query:optimized",e.PERFORMANCE_WARNING="performance:warning",e.PERFORMANCE_CRITICAL="performance:critical",e.MEMORY_USAGE_HIGH="memory:usage:high",e.FRAME_RATE_DROP="frame:rate:drop",e.INDEX_CREATED="index:created",e.INDEX_UPDATED="index:updated",e.INDEX_OPTIMIZED="index:optimized",e.ARCHETYPE_CREATED="archetype:created",e.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",e.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",e.DIRTY_MARK_ADDED="dirty:mark:added",e.DIRTY_BATCH_PROCESSED="dirty:batch:processed",e.ERROR_OCCURRED="error:occurred",e.WARNING_ISSUED="warning:issued",e.FRAMEWORK_INITIALIZED="framework:initialized",e.FRAMEWORK_SHUTDOWN="framework:shutdown",e.DEBUG_INFO="debug:info",e.DEBUG_STATS_UPDATED="debug:stats:updated"}(le||(le={})),function(e){e[e.LOWEST=0]="LOWEST",e[e.LOW=25]="LOW",e[e.NORMAL=50]="NORMAL",e[e.HIGH=75]="HIGH",e[e.HIGHEST=100]="HIGHEST",e[e.CRITICAL=200]="CRITICAL"}(de||(de={}));var ye={ENTITY:{CREATED:le.ENTITY_CREATED,DESTROYED:le.ENTITY_DESTROYED,ENABLED:le.ENTITY_ENABLED,DISABLED:le.ENTITY_DISABLED,TAG_ADDED:le.ENTITY_TAG_ADDED,TAG_REMOVED:le.ENTITY_TAG_REMOVED,NAME_CHANGED:le.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:le.COMPONENT_ADDED,REMOVED:le.COMPONENT_REMOVED,MODIFIED:le.COMPONENT_MODIFIED,ENABLED:le.COMPONENT_ENABLED,DISABLED:le.COMPONENT_DISABLED},SYSTEM:{ADDED:le.SYSTEM_ADDED,REMOVED:le.SYSTEM_REMOVED,ENABLED:le.SYSTEM_ENABLED,DISABLED:le.SYSTEM_DISABLED,PROCESSING_START:le.SYSTEM_PROCESSING_START,PROCESSING_END:le.SYSTEM_PROCESSING_END,ERROR:le.SYSTEM_ERROR},PERFORMANCE:{WARNING:le.PERFORMANCE_WARNING,CRITICAL:le.PERFORMANCE_CRITICAL,MEMORY_HIGH:le.MEMORY_USAGE_HIGH,FRAME_DROP:le.FRAME_RATE_DROP}},ge=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}();ge.validTypes=new Set([].concat(Object.values(le),Object.values(ye.ENTITY),Object.values(ye.COMPONENT),Object.values(ye.SYSTEM),Object.values(ye.PERFORMANCE)));var ve=function(){function e(e){void 0===e&&(e=!1),this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new me,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 o;return l().w((function(t){for(;;)switch(t.n){case 0:return void 0===r&&(r=!1),this.validateEventType(n),o=r?this.enhanceEventData(n,i):i,this.isDebugMode&&e._logger.info("发射异步事件: "+n,o),t.n=1,this.eventSystem.emit(n,o);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||de.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(le.ENTITY_CREATED,e)},t.emitEntityDestroyed=function(e){this.emit(le.ENTITY_DESTROYED,e)},t.emitComponentAdded=function(e){this.emit(le.COMPONENT_ADDED,e)},t.emitComponentRemoved=function(e){this.emit(le.COMPONENT_REMOVED,e)},t.emitSystemAdded=function(e){this.emit(le.SYSTEM_ADDED,e)},t.emitSystemRemoved=function(e){this.emit(le.SYSTEM_REMOVED,e)},t.emitSceneChanged=function(e){this.emit(le.SCENE_ACTIVATED,e)},t.emitPerformanceWarning=function(e){this.emit(le.PERFORMANCE_WARNING,e)},t.onEntityCreated=function(e,t){return this.on(le.ENTITY_CREATED,e,t)},t.onComponentAdded=function(e,t){return this.on(le.COMPONENT_ADDED,e,t)},t.onSystemError=function(e,t){return this.on(le.SYSTEM_ERROR,e,t)},t.onPerformanceWarning=function(e,t){return this.on(le.PERFORMANCE_WARNING,e,t)},t.validateEventType=function(t){this.isDebugMode&&(ge.isValid(t)||(e._logger.warn("未知事件类型: "+t),ge.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}();ve._logger=k("EventBus");var _e=function(){function e(){}return e.getInstance=function(e){return void 0===e&&(e=!1),this.instance||(this.instance=new ve(e)),this.instance},e.reset=function(e){return void 0===e&&(e=!1),this.instance&&this.instance.clear(),this.instance=new ve(e),this.instance},e}(),Se=function(){function e(e){var t=this;this.name="",this._didSceneBegin=!1,this.entities=new te(this),this.entityProcessors=new ne,this.identifierPool=new ie,this.componentStorageManager=new J,this.querySystem=new fe,this.eventSystem=new me,null!=e&&e.name&&(this.name=e.name),void 0!==(null==e?void 0:e.enableEntityDirectUpdate)&&this.entities.setEnableEntityDirectUpdate(e.enableEntityDirectUpdate),$.eventBus||($.eventBus=new ve(!1)),$.eventBus&&$.eventBus.onComponentAdded((function(e){t.eventSystem.emitSync("component:added",e)}))}var t=e.prototype;return t.initialize=function(){},t.onStart=function(){},t.unload=function(){},t.begin=function(){null!=this.entityProcessors&&this.entityProcessors.begin(),this._didSceneBegin=!0,this.onStart()},t.end=function(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this.entityProcessors&&this.entityProcessors.end(),this.unload()},t.update=function(){this.entities.updateLists(),null!=this.entityProcessors&&this.entityProcessors.update(),this.entities.update(),null!=this.entityProcessors&&this.entityProcessors.lateUpdate()},t.createEntity=function(e){var t=new $(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=s(this.entityProcessors.processors);!(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 $(t+"_"+i,this.identifierPool.checkOut());r.scene=this,n.push(r)}for(var o=0,s=n;o<s.length;o++){var a=s[o];this.entities.add(a)}return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:e}),n},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=s(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.addEntityProcessor=function(e){return this.entityProcessors.processors.includes(e)||(e.scene=this,this.entityProcessors.add(e),e.initialize(),e.setUpdateOrder(this.entityProcessors.count-1)),e},t.addSystem=function(e){return this.addEntityProcessor(e)},t.removeEntityProcessor=function(e){this.entityProcessors.remove(e),e.reset()},t.removeSystem=function(e){this.removeEntityProcessor(e)},t.getEntityProcessor=function(e){return this.entityProcessors.getProcessor(e)},t.getStats=function(){return{entityCount:this.entities.count,processorCount:this.entityProcessors.count,componentStorageStats:this.componentStorageManager.getAllStats()}},t.getDebugInfo=function(){return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:this.entityProcessors.count,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 Q(e)}))}})),processors:this.entityProcessors.processors.map((function(e){var t;return{name:V(e),updateOrder:e.updateOrder,entityCount:(null===(t=e._entities)||void 0===t?void 0:t.length)||0}})),componentStats:this.componentStorageManager.getAllStats()}},o(e,[{key:"systems",get:function(){return this.entityProcessors.processors}}])}(),Ee=function(){function e(){this.scene=new Se}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 ee(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 o=r[i];this.scene.addEntity(o)}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 o=r[i];this.scene.addSystem(o)}return this},t.build=function(){return this.scene},e}(),Ce=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}(),be=function(){function e(e){this.entities=e}var t=e.prototype;return t.addComponent=function(e){for(var t,n=s(this.entities);!(t=n()).done;){t.value.addComponent(e)}return this},t.removeComponent=function(e){for(var t,n=s(this.entities);!(t=n()).done;){t.value.removeComponentByType(e)}return this},t.setActive=function(e){for(var t,n=s(this.entities);!(t=n()).done;){t.value.active=e}return this},t.setTag=function(e){for(var t,n=s(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}(),Te=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 ee(this.scene,this.scene.componentStorageManager)},t.createScene=function(){return new Ee},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(Ce,[e].concat(n))},t.query=function(){return new pe(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 be(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 we(e,t,n){return new Te(e,t,n)}var Me=k("World"),Ae=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(),Me.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 Se;return"id"in n&&(n.id=e),"name"in n&&!n.name&&(n.name=e),this._scenes.set(e,n),n.initialize(),Me.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),Me.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.setSceneActive=function(e,t){var n=this._scenes.get(e);n?t?(this._activeScenes.add(e),n.begin&&n.begin(),Me.debug("在World '"+this.name+"' 中激活Scene: "+e)):(this._activeScenes.delete(e),Me.debug("在World '"+this.name+"' 中停用Scene: "+e)):Me.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(),Me.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(),Me.debug("从World '"+this.name+"' 中移除全局System: "+e.name),!0)},t.getGlobalSystem=function(e){for(var t,n=s(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=s(this._globalSystems);!(e=t()).done;){var n=e.value;n.initialize&&n.initialize()}Me.info("启动World: "+this.name)}},t.stop=function(){if(this._isActive){for(var e,t=s(this._activeScenes);!(e=t()).done;){var n=e.value;this.setSceneActive(n,!1)}for(var i,r=s(this._globalSystems);!(i=r()).done;){var o=i.value;o.reset&&o.reset()}this._isActive=!1,Me.info("停止World: "+this.name)}},t.updateGlobalSystems=function(){if(this._isActive)for(var e,t=s(this._globalSystems);!(e=t()).done;){var n=e.value;n.update&&n.update()}},t.updateScenes=function(){if(this._isActive){for(var e,t=s(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(){Me.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=s(this._globalSystems);!(i=r()).done;){var o=i.value;o.destroy?o.destroy():o.reset&&o.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=s(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=s(this._scenes);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];if(!this._activeScenes.has(r)&&o.entities&&0===o.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],o=this._scenes.get(r);o&&!this._activeScenes.has(r)&&o.entities&&0===o.entities.count&&t-this._createdAt>3e5&&(this.removeScene(r),Me.debug("自动清理空Scene: "+r+" from World "+this.name))}},o(e,[{key:"isActive",get:function(){return this._isActive}},{key:"sceneCount",get:function(){return this._scenes.size}},{key:"createdAt",get:function(){return this._createdAt}}])}(),Ie=k("WorldManager"),xe=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),Ie.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupInterval:this._config.cleanupInterval}),this.startCleanupTimer()}e.getInstance=function(t){return this._instance||(this._instance=new e(t)),this._instance},e.reset=function(){this._instance&&(this._instance.destroy(),this._instance=null)};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 Ae(n);return this._worlds.set(e,i),Ie.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),Ie.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(),Ie.debug("激活World: "+e)):(this._activeWorlds.delete(e),n.stop(),Ie.debug("停用World: "+e)):Ie.warn("World '"+e+"' 不存在")},t.isWorldActive=function(e){return this._activeWorlds.has(e)},t.getActiveWorlds=function(){for(var e,t=[],n=s(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=s(this._worlds.keys());!(e=t()).done;){var n=e.value;this.setWorldActive(n,!0)}Ie.info("启动所有World")},t.stopAll=function(){this._isRunning=!1;for(var e,t=s(this._activeWorlds);!(e=t()).done;){var n=e.value;this.setWorldActive(n,!1)}Ie.info("停止所有World")},t.findWorlds=function(e){for(var t,n=[],i=s(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=s(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=s(this._worlds);!(e=n()).done;){var i=e.value,r=i[0],o=i[1],c=o.getStats();t.totalScenes+=c.totalSystems,t.totalEntities+=c.totalEntities,t.totalSystems+=c.totalSystems,t.worlds.push(a({id:r,name:o.name,isActive:this._activeWorlds.has(r),sceneCount:o.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=s(this._worlds);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];this.shouldCleanupWorld(o)&&t.push(r)}for(var a=0,c=t;a<c.length;a++){var u=c[a];this.removeWorld(u)}return t.length>0&&Ie.debug("清理了 "+t.length+" 个World"),t.length},t.destroy=function(){Ie.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,Ie.info("WorldManager已销毁")},t.startCleanupTimer=function(){var e=this;this._config.autoCleanup&&!this._cleanupTimer&&(this._cleanupTimer=setInterval((function(){e.cleanup()}),this._config.cleanupInterval),Ie.debug("启动World清理定时器,间隔: "+this._config.cleanupInterval+"ms"))},t.stopCleanupTimer=function(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null,Ie.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)},o(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)}}])}();xe._instance=null;var ke=function(){function e(e){if(e&&"object"==typeof e)this._value=w.clone(e);else if("number"==typeof e)this._value=w.fromNumber(e);else if("string"==typeof e){var t=parseInt(e,10);this._value=w.fromNumber(t)}else this._value=w.clone(w.ZERO)}var t=e.prototype;return t.set=function(e){if(e<0)throw new Error("Bit index cannot be negative");if(e>=64)throw new Error("Bit index exceeds 64-bit limit. ECS framework supports max 64 component types.");w.setBit(this._value,e)},t.clear=function(e){if(e<0)throw new Error("Bit index cannot be negative");e>=64||w.clearBit(this._value,e)},t.get=function(e){if(e<0||e>=64)return!1;var t=w.create(e);return w.hasAny(this._value,t)},t.containsAll=function(e){return w.hasAll(this._value,e._value)},t.intersects=function(e){return w.hasAny(this._value,e._value)},t.excludes=function(e){return w.hasNone(this._value,e._value)},t.clearAll=function(){w.clear(this._value)},t.isEmpty=function(){return w.isZero(this._value)},t.cardinality=function(){return w.popCount(this._value)},t.and=function(t){var n=new e;return w.copy(this._value,n._value),w.andInPlace(n._value,t._value),n},t.or=function(t){var n=new e;return w.copy(this._value,n._value),w.orInPlace(n._value,t._value),n},t.xor=function(t){var n=new e;return w.copy(this._value,n._value),w.xorInPlace(n._value,t._value),n},t.not=function(t){void 0===t&&(t=64),t>64&&(t=64);var n=new e;if(w.copy(this._value,n._value),t<=32){var i=(1<<t)-1;n._value.lo=~n._value.lo&i,n._value.hi=0}else if(n._value.lo=~n._value.lo,t<64){var r=(1<<t-32)-1;n._value.hi=~n._value.hi&r}else n._value.hi=~n._value.hi;return n},t.copyFrom=function(e){w.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)w.copy(e,this._value);else if("number"==typeof e)this._value=w.fromNumber(e);else{var t=parseInt(e,10);this._value=w.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=64),e>64&&(e=64);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 w.toString(this._value,16)},e.fromBinaryString=function(t){var n,i=t.replace(/\s/g,"");if(i.length<=32){n={lo:parseInt(i,2)>>>0,hi:0}}else{var r=i.substring(i.length-32),o=i.substring(0,i.length-32);n={lo:parseInt(r,2)>>>0,hi:parseInt(o,2)>>>0}}return new e(n)},e.fromHexString=function(t){var n,i=t.replace(/^0x/i,"");if(i.length<=8){n={lo:parseInt(i,16)>>>0,hi:0}}else{var r=i.substring(i.length-8),o=i.substring(0,i.length-8);n={lo:parseInt(r,16)>>>0,hi:parseInt(o,16)>>>0}}return new e(n)},t.equals=function(e){return w.equals(this._value,e._value)},t.getHighestBitIndex=function(){if(w.isZero(this._value))return-1;if(0!==this._value.hi)for(var e=31;e>=0;e--)if(this._value.hi&1<<e)return e+32;for(var t=31;t>=0;t--)if(this._value.lo&1<<t)return t;return-1},t.getLowestBitIndex=function(){if(w.isZero(this._value))return-1;for(var e=0;e<32;e++)if(this._value.lo&1<<e)return e;for(var t=0;t<32;t++)if(this._value.hi&1<<t)return t+32;return-1},e}(),De=function(){function e(){this._componentTypes=new Map,this._typeNames=new Map,this._nextTypeId=0}var t=e.prototype;return t.getTypeId=function(e){var t=this._componentTypes.get(e);return void 0===t&&(t=this._nextTypeId++,this._componentTypes.set(e,t),this._typeNames.set(t,G(e))),t},t.getTypeName=function(e){return this._typeNames.get(e)||"Unknown"},t.createBits=function(){for(var e=new ke,t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var r=0,o=n;r<o.length;r++){var s=o[r],a=this.getTypeId(s);e.set(a)}return e},t.getEntityBits=function(e){for(var t,n=new ke,i=s(e);!(t=i()).done;){var r=t.value,o=this.getTypeId(r.constructor);n.set(o)}return n},t.reset=function(){this._componentTypes.clear(),this._typeNames.clear(),this._nextTypeId=0},o(e,[{key:"registeredTypeCount",get:function(){return this._componentTypes.size}}],[{key:"instance",get:function(){return e._instance||(e._instance=new e),e._instance}}])}(),Pe=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 Q(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 o=t.entities;if(null==o||!o.buffer)return null;var s=o.buffer.find((function(t){return t.id===e}));if(!s)return null;var c=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s,t),u=this.extractComponentDetails(s.components),h=this.getSceneInfo(t);return a({},c,{scene:h.name,sceneName:h.name,sceneType:h.type,parentName:(null===(n=s.parent)||void 0===n?void 0:n.name)||null,components:u||[],componentCount:(null===(i=s.components)||void 0===i?void 0:i.length)||0,componentTypes:(null===(r=s.components)||void 0===r?void 0:r.map((function(e){return Q(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 Q(e)})))||[],r=i.length>0?i.sort().join(", "):"无组件",o=t.get(r);o?o.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})).slice(0,10):[]},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,o=(null===(t=e.componentTypes)||void 0===t?void 0:t.map((function(e){return e.name})).join(","))||"Unknown",s=(null===(r=e.entities)||void 0===r?void 0:r.length)||0;n.push({signature:o,count:s,memory:0}),e.entities&&e.entities.slice(0,5).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,o,s=(null===(n=e.componentTypes)||void 0===n?void 0:n.map((function(e){return e.name})).join(","))||"Unknown",a=(null===(o=e.entities)||void 0===o?void 0:o.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:s,count:a,memory:c}),e.entities&&e.entities.slice(0,5).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 Q(e)})))||[],o=r.length>0?r.sort().join(", "):"无组件",s=n.get(o),a=t.estimateEntityMemoryUsage(e);(isNaN(a)||a<0)&&(a=0),s?(s.count++,s.memory+=a):n.set(o,{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 o=32;try{for(var s=Object.keys(e),a=Math.min(s.length,20),c=0;c<a;c++){var u=s[c];if(!(t.includes(u)||"constructor"===u||"__proto__"===u||u.startsWith("_cc_")||u.startsWith("__"))){var h=e[u];o+=2*u.length,"string"==typeof h?o+=Math.min(2*h.length,200):"number"==typeof h?o+=8:"boolean"==typeof h?o+=4:Array.isArray(h)?o+=40+Math.min(8*h.length,160):"object"==typeof h&&null!==h&&(o+=i(h,r+1))}}}catch(e){return 64}return o};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 Q(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,o=0;o<r.length;o+=100){r.slice(o,o+100).forEach((function(e){var r,o=e.getDebugInfo?e.getDebugInfo():n.buildFallbackEntityInfo(e,t),s=e.getComponentCacheStats?e.getComponentCacheStats():null,c=n.extractComponentDetails(e.components);i[e.id]=a({},o,{parentName:(null===(r=e.parent)||void 0===r?void 0:r.name)||null,components:c,componentTypes:o.componentTypes||c.map((function(e){return e.typeName})),cachePerformance:s?{hitRate:s.cacheStats.hitRate,size:s.cacheStats.size,maxSize:s.cacheStats.maxSize}:null})}))}return i},t.buildFallbackEntityInfo=function(e,t){var n,i,r,o=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:o.name,sceneName:o.name,sceneType:o.type,componentCount:e.components.length,componentTypes:e.components.map((function(e){return Q(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=Q(e);if(!n||"Object"===n||"Function"===n)try{var i=De.instance,r=e.constructor,o=i.getTypeId(r);n=i.getTypeName(o)}catch(e){n="UnknownComponent"}var s={};try{Object.keys(e).forEach((function(n){if(!n.startsWith("_")&&"entity"!==n&&"constructor"!==n){var i=e[n];null!=i&&(s[n]=t.formatPropertyValue(i))}})),0===Object.keys(s).length&&(s._info="该组件没有公开属性",s._componentId=Q(e))}catch(t){s._error="属性提取失败",s._componentId=Q(e)}return{typeName:n,properties:s}}))},t.getComponentProperties=function(e,t,n){var i=this;try{if(!n)return{};var r=n.entities;if(null==r||!r.buffer)return{};var o=r.buffer.find((function(t){return t.id===e}));if(!o||t>=o.components.length)return{};var s=o.components[t],a={};return Object.keys(s).forEach((function(e){if(!e.startsWith("_")&&"entity"!==e){var t=s[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={},o=0,s=0,a=i;s<a.length;s++){var c=a[s];if(o>=15){r._hasMoreProperties=!0,r._totalProperties=i.length,r._hiddenCount=i.length-o;break}if(!c.startsWith("_")&&!c.startsWith("$")&&"function"!=typeof e[c])try{var u=e[c];null!=u&&(r[c]=this.formatPropertyValue(u,1),o++)}catch(e){r[c]="[访问失败: "+(e instanceof Error?e.message:String(e))+"]",o++}}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,o,s=(null===(r=e.node)||void 0===r?void 0:r.name)||(null===(o=e.node)||void 0===o?void 0:o._name)||"";return t+(s?" on "+s:"")}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 o=r.buffer.find((function(t){return t.id===e}));if(!o)return null;if(t>=o.components.length)return null;var s=o.components[t],a=this.getObjectByPath(s,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=s(t.split("."));!(n=r()).done;){var o=n.value;if(null==i)return null;if(o.includes("[")&&o.includes("]")){var a=o.substring(0,o.indexOf("[")),c=parseInt(o.substring(o.indexOf("[")+1,o.indexOf("]")));if(a&&(i=i[a]),!(Array.isArray(i)&&c>=0&&c<i.length))return null;i=i[c]}else i=i[o]}return i},e}(),Re=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,o=new Map;if(e)try{r=e.getAllSystemStats(),o=e.getAllSystemData()}catch(e){}return{totalSystems:i.length,systemsInfo:i.map((function(e){var t,n=e.systemName||V(e),i=r.get(n),s=o.get(n);return{name:n,type:V(e),entityCount:(null===(t=e.entities)||void 0===t?void 0:t.length)||0,executionTime:(null==i?void 0:i.averageTime)||(null==s?void 0:s.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==s?void 0:s.lastUpdateTime)||0}}))}},e}(),Be=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=g.deltaTime,n=1e3*t,i=t>0?Math.round(1/t):0,r=this.getECSPerformanceData(e),o=r.totalExecutionTime,s=n>0?o/n*100:0,a=0;performance.memory&&(a=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(o),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();var c=this.frameTimeHistory.filter((function(e){return e>=0}));return{frameTime:o,engineFrameTime:n,ecsPercentage:s,memoryUsage:a,fps:i,averageFrameTime:c.length>0?c.reduce((function(e,t){return e+t}),0)/c.length:o,minFrameTime:c.length>0?Math.min.apply(Math,c):o,maxFrameTime:c.length>0?Math.max.apply(Math,c):o,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,o=s(i.entries());!(r=o()).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}(),Ne=function(){function e(e,t,n){void 0===n&&(n=1e3),this.pool=[],this.createFn=e,this.resetFn=t,this.maxSize=n}var t=e.prototype;return t.acquire=function(){return this.pool.length>0?this.pool.pop():this.createFn()},t.release=function(e){this.pool.length<this.maxSize&&(this.resetFn&&this.resetFn(e),this.pool.push(e))},t.prewarm=function(e){for(var t=0;t<e&&this.pool.length<this.maxSize;t++)this.pool.push(this.createFn())},t.clear=function(){this.pool.length=0},t.getAvailableCount=function(){return this.pool.length},t.getMaxSize=function(){return this.maxSize},e}(),Oe=function(){function e(){this.pools=new Map}e.getInstance=function(){return e.instance||(e.instance=new e),e.instance};var t=e.prototype;return t.registerPool=function(e,t,n,i){this.pools.set(e,new Ne(t,n,i))},t.acquireComponent=function(e){var t=this.pools.get(e);return t?t.acquire():null},t.releaseComponent=function(e,t){var n=this.pools.get(e);n&&n.release(t)},t.prewarmAll=function(e){void 0===e&&(e=100);for(var t,n=s(this.pools.values());!(t=n()).done;){t.value.prewarm(e)}},t.clearAll=function(){for(var e,t=s(this.pools.values());!(e=t()).done;){e.value.clear()}},t.reset=function(){this.pools.clear()},t.getPoolStats=function(){for(var e,t=new Map,n=s(this.pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1];t.set(r,{available:o.getAvailableCount(),maxSize:o.getMaxSize()})}return t},t.getPoolUtilization=function(){for(var e,t=new Map,n=s(this.pools);!(e=n()).done;){var i=e.value,r=i[0],o=i[1],a=o.getAvailableCount(),c=o.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}(),ze=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=Q(e),n=i.get(t)||{count:0,entities:0};n.count++,r++,i.set(t,n)}))}));var o=new Map,a=new Map;try{for(var c,u=Oe.getInstance(),h=u.getPoolStats(),l=u.getPoolUtilization(),d=s(h.entries());!(c=d()).done;){var f=c.value,p=f[0],m=f[1];a.set(p,m.maxSize)}for(var y,g=s(l.entries());!(y=g()).done;){var v=y.value,_=v[0],S=v[1];o.set(_,S.utilization)}}catch(e){}return{componentTypes:i.size,componentInstances:r,componentStats:Array.from(i.entries()).map((function(i){var r=i[0],s=i[1],c=a.get(r)||0,u=o.get(r)||0,h=t.getEstimatedComponentSize(r,e);return{typeName:r,instanceCount:s.count,memoryPerInstance:h,totalMemory:s.count*h,poolSize:c,poolUtilization:u,averagePerEntity:s.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 o,a=s(i.buffer);!(o=a()).done;){var c=o.value;if(c.components){var u=c.components.find((function(e){return Q(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 o=Object.keys(e),s=0;s<Math.min(o.length,20);s++){var a=o[s];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=s(n.buffer);!(i=r()).done;){var o=i.value;if(o.components){var a=o.components.find((function(t){return Q(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),o=0;o<r;o++)i+=this.estimateObjectSize(e[o],t,n+1)}else{i=32;try{for(var s=Object.getOwnPropertyNames(e),a=Math.min(s.length,30),c=0;c<a;c++){var u=s[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}();ze.componentSizeCache=new Map;var We=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,o=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==o||null===(n=o.processors)||void 0===n?void 0:n.length)||0,sceneMemory:0,sceneUptime:i}},t.setSceneStartTime=function(e){this.sceneStartTime=e},e}(),Fe=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}(),Le=function(){function e(e,t){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.config=t,this.sceneProvider=function(){return e.scene||e.constructor.scene},this.performanceMonitorProvider=function(){return e._performanceMonitor},this.entityCollector=new Pe,this.systemCollector=new Re,this.performanceCollector=new Be,this.componentCollector=new ze,this.sceneCollector=new We,this.webSocketManager=new Fe(t.websocketUrl,!1!==t.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));var n=t.debugFrameRate||30;this.sendInterval=1e3/n,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.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 Fe(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())},t.onFrameUpdate=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 o=this.entityCollector.expandLazyObject(t,n,i);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.entityCollector.getComponentProperties(t,n);this.webSocketManager.send({type:"get_component_properties_response",requestId:i,data:r})}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.entityCollector.getRawEntityList();this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t,data:n})}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.entityCollector.getEntityDetails(t);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:i})}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.sceneProvider(),i=this.entityCollector.collectEntityDataWithMemory(n),r=null!=n&&n.entities?this.collectComponentMemoryStats(n.entities):{totalMemory:0,componentTypes:0,totalInstances:0,breakdown:[]},o=this.collectSystemMemoryStats(),s=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:o.totalMemory,poolMemory:s.totalMemory},baseMemory:t,entities:{totalMemory:c,entityCount:i.totalEntities,archetypes:i.entitiesPerArchetype,largestEntities:i.topEntitiesByComponents},components:r,systems:o,pools:s,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,o=s(e.buffer);!(t=o()).done;){var a=t.value;if(a&&!a.destroyed&&a.components)for(var c,u=s(a.components);!(c=u()).done;){var h=Q(c.value);r.set(h,(r.get(h)||0)+1)}}for(var l,d=s(r.entries());!(l=d()).done;){var f=l.value,p=f[0],m=f[1],y=this.componentCollector.calculateDetailedComponentMemory(p),g=y*m;i+=g;for(var v,_=[],S=0,E=s(e.buffer);!(v=E()).done;){var C=v.value;if(C&&!C.destroyed&&C.components){for(var b,T=s(C.components);!(b=T()).done;){if(Q(b.value)===p&&(_.push({entityId:C.id,entityName:C.name||"Entity_"+C.id,memory:y}),++S>=100))break}if(S>=100)break}}n.set(p,{count:m,totalMemory:g,instances:_.slice(0,10)})}var w=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:w}},t.collectSystemMemoryStats=function(){var e=this.sceneProvider(),t=0,n=[];try{var i=null==e?void 0:e.entityProcessors;if(i&&i.processors)for(var r,o=new Map,a=s(i.processors);!(r=a()).done;){var c=r.value,u=V(c),h=void 0;o.has(u)?h=o.get(u):(h=this.calculateQuickSystemSize(c),o.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 o=e[r];t+=2*r.length,"string"==typeof o?t+=Math.min(2*o.length,100):"number"==typeof o?t+=8:"boolean"==typeof o?t+=4:Array.isArray(o)?t+=40+Math.min(8*o.length,200):"object"==typeof o&&null!==o&&(t+=64)}}}catch(e){return 128}return Math.max(t,64)},t.collectPoolMemoryStats=function(){var e=0,t=[];try{for(var n,i=s(Oe.getInstance().getPoolStats().entries());!(n=i()).done;){var r=n.value,o=r[0],a=r[1],c=32*a.maxSize;e+=c,t.push({typeName:o,maxSize:a.maxSize,currentSize:a.currentSize||0,estimatedMemory:c,utilization:a.currentSize?a.currentSize/a.maxSize*100:0})}}catch(e){}try{for(var u=C.getAllPoolStats(),h=0,l=Object.entries(u);h<l.length;h++){var d=l[h],f=d[0],p=d[1];e+=p.estimatedMemoryUsage,t.push({typeName:"Pool_"+f,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,t=this.performanceMonitorProvider();if(!t)return{enabled:!1};var n=t.getAllSystemStats(),i=t.getPerformanceWarnings();return{enabled:null!==(e=t.enabled)&&void 0!==e&&e,systemCount:n.size,warnings:i.slice(0,10),topSystems:Array.from(n.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.sceneProvider(),n={timestamp:e,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:(null==t?void 0:t.name)||"Unknown"};if(this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(t)),this.config.channels.systems){var i=this.performanceMonitorProvider();n.systems=this.systemCollector.collectSystemData(i,t)}if(this.config.channels.performance){var r=this.performanceMonitorProvider();n.performance=this.performanceCollector.collectPerformanceData(r)}return 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;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){}},e}(),qe=function(){function e(t){var n,i,r;void 0===t&&(t={}),this._globalManagers=[],e._instance=this,this._config=a({debug:!0,enableEntitySystems:!0},t),this._timerManager=new S,e.registerGlobalManager(this._timerManager),this._performanceMonitor=E.instance,this._config.debug&&this._performanceMonitor.enable(),this._poolManager=T.getInstance(),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&&(this._debugManager=new Le(this,this._config.debugConfig)),this.initialize()}e.getScene=function(){if(!this._instance)return null;this._instance.ensureDefaultWorld();var e=this._instance._worldManager.getWorld(this.DEFAULT_WORLD_ID);return(null==e?void 0:e.getScene(this.DEFAULT_SCENE_ID))||null},e.setScene=function(e){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");this._instance.ensureDefaultWorld();var t=this._instance._worldManager.getWorld(this.DEFAULT_WORLD_ID);return t.getScene(this.DEFAULT_SCENE_ID)&&t.removeScene(this.DEFAULT_SCENE_ID),t.createScene(this.DEFAULT_SCENE_ID,e),t.setSceneActive(this.DEFAULT_SCENE_ID,!0),this._instance.onSceneChanged(),e},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)}return this._instance},e.update=function(t){this._instance?this._instance.updateInternal(t):e._logger.warn("Core实例未创建,请先调用Core.create()")},e.registerGlobalManager=function(e){this._instance._globalManagers.push(e),e.enabled=!0},e.unregisterGlobalManager=function(e){this._instance._globalManagers.splice(this._instance._globalManagers.indexOf(e),1),e.enabled=!1},e.getGlobalManager=function(e){for(var t,n=s(this._instance._globalManagers);!(t=n()).done;){var i=t.value;if(i instanceof e)return i}return null},e.schedule=function(e,t,n,i){if(void 0===t&&(t=!1),!i)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(e,t,n,i)},e.enableDebug=function(t){this._instance?(this._instance._debugManager?this._instance._debugManager.updateConfig(t):this._instance._debugManager=new Le(this._instance,t),this._instance._config.debugConfig=t):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.getWorldManager=function(e){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");if(!this._instance._worldManager){var t={maxWorlds:50,autoCleanup:!0,cleanupInterval:6e4,debug:this._instance._config.debug};this._instance._worldManager=xe.getInstance(a({},t,e))}return this._instance._worldManager},e.enableWorldManager=function(e){return this.getWorldManager(e)};var t=e.prototype;return t.ensureDefaultWorld=function(){this._worldManager||(this._worldManager=xe.getInstance({maxWorlds:1,autoCleanup:!1,cleanupInterval:0,debug:this._config.debug})),this._worldManager.getWorld(e.DEFAULT_WORLD_ID)||(this._worldManager.createWorld(e.DEFAULT_WORLD_ID,{name:"DefaultWorld",maxScenes:1,autoCleanup:!1}),this._worldManager.setWorldActive(e.DEFAULT_WORLD_ID,!0))},t.onSceneChanged=function(){var t=this;g.sceneChanged();var n=e.getScene();n&&n.querySystem&&n.eventSystem&&(this._ecsAPI=we(n,n.querySystem,n.eventSystem)),this._debugManager&&queueMicrotask((function(){var e;null===(e=t._debugManager)||void 0===e||e.onSceneChanged()}))},t.initialize=function(){},t.updateInternal=function(t){if(!e.paused){var n=this._performanceMonitor.startMonitoring("Core.update");g.update(t),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(g.deltaTime);for(var i,r=this._performanceMonitor.startMonitoring("GlobalManagers.update"),o=s(this._globalManagers);!(i=o()).done;){var a=i.value;a.enabled&&a.update()}if(this._performanceMonitor.endMonitoring("GlobalManagers.update",r,this._globalManagers.length),this._poolManager.update(),this._worldManager){for(var c,u=this._performanceMonitor.startMonitoring("Worlds.update"),h=0,l=s(this._worldManager.getActiveWorlds());!(c=l()).done;){var d=c.value;d.updateGlobalSystems(),d.updateScenes(),h+=d.getStats().totalEntities}this._performanceMonitor.endMonitoring("Worlds.update",u,h)}this._debugManager&&this._debugManager.onFrameUpdate(t),this._performanceMonitor.endMonitoring("Core.update",n)}},o(e,null,[{key:"Instance",get:function(){return this._instance}},{key:"scene",get:function(){return this.getScene()}},{key:"ecsAPI",get:function(){var e;return(null===(e=this._instance)||void 0===e?void 0:e._ecsAPI)||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}}])}();qe.paused=!1,qe.DEFAULT_WORLD_ID="__default__",qe.DEFAULT_SCENE_ID="__main__",qe._logger=k("Core");var je=function(e,t){this.func=e,this.context=t},Ue=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 je(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 o,a=s(t);!(o=a()).done;){var c,u=o.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}(),He=function(){function e(){this._enabled=!0,this._updateOrder=0,this.id=e._idGenerator++}var t=e.prototype;return t.onAddedToEntity=function(){},t.onRemovedFromEntity=function(){},t.onEnabled=function(){},t.onDisabled=function(){},t.update=function(){},o(e,[{key:"enabled",get:function(){return this.entity?this.entity.enabled&&this._enabled:this._enabled},set:function(e){this._enabled!==e&&(this._enabled=e,this._enabled?this.onEnabled():this.onDisabled())}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this._updateOrder=e}}])}();He._idGenerator=0;var Ge=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 G(e)})).join(", ")+")"),this.condition.any.length>0&&e.push("any("+this.condition.any.map((function(e){return G(e)})).join(", ")+")"),this.condition.none.length>0&&e.push("none("+this.condition.none.map((function(e){return G(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("+G(this.condition.component)+")"),"Matcher["+e.join(" & ")+"]"},e}(),Ye=function(){function e(e){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=E.instance,this._systemName=V(this),this._initialized=!1,this._matcher=e||Ge.empty(),this._eventListeners=[],this._scene=null,this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.logger=k(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.setUpdateOrder=function(e){this._updateOrder=e,this.scene&&this.scene.entityProcessors&&this.scene.entityProcessors.setDirty()},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 o=this.extractEntityIds(t.queryByComponent(e.component).entities);n=n?this.intersectIdSets(n,o):o}if(e.all.length>0){var s=this.extractEntityIds(t.queryAll.apply(t,e.all).entities);n=n?this.intersectIdSets(n,s):s}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,o=new Set,a=s(n);!(r=a()).done;){var c=r.value;i.has(c)&&o.add(c)}return o},t.differenceIdSets=function(e,t){for(var n,i=new Set,r=s(e);!(n=r()).done;){var o=n.value;t.has(o)||i.add(o)}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 o=e[r];n.set(0|o.id,o)}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,o=new Array(r),a=0,c=s(e);!(n=c()).done;){var u=n.value,h=i.get(u);void 0!==h&&(o[a]=h,a=a+1|0)}return a<r&&(o.length=a),o},t.executeComplexQuery=function(e,t){return this.executeComplexQueryWithIdSets(e,t)},t.update=function(){if(this._enabled&&this.onCheckProcessing()){var e=this._performanceMonitor.startMonitoring(this._systemName),t=0;try{this.onBegin(),this._entityCache.frame=this.queryEntities(),t=this._entityCache.frame.length,this.process(this._entityCache.frame)}finally{this._performanceMonitor.endMonitoring(this._systemName,e,t)}}},t.lateUpdate=function(){if(this._enabled&&this.onCheckProcessing()){var e=this._performanceMonitor.startMonitoring(this._systemName+"_Late"),t=0;try{var n=this._entityCache.frame||[];t=n.length,this.lateProcess(n),this.onEnd()}finally{this._performanceMonitor.endMonitoring(this._systemName+"_Late",e,t),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._performanceMonitor.getSystemData(this._systemName)},t.getPerformanceStats=function(){return this._performanceMonitor.getSystemStats(this._systemName)},t.resetPerformanceData=function(){this._performanceMonitor.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=s(e);!(t=r()).done;){var o=t.value;this._entityCache.tracked.has(o)||(this._entityCache.tracked.add(o),this.onAdded(o),i=!0)}for(var a,c=s(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.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=s(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(){},o(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}}])}(),Qe=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){this.processSystem()},t}(Ye),Ve=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){},t}(Ye),Xe=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+=g.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)},n.getIntervalDelta=function(){return this.interval+this.intervalRemainder},t}(Ye),Ze=function(){function e(){this.adapter=null,this.logger=k("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}(),Je=function(e){function t(t,n){var i,r,o,s,a,c;void 0===n&&(n={}),(c=e.call(this,t)||this).workerPool=null,c.isProcessing=!1,c.sharedBuffer=null,c.sharedFloatArray=null,c.platformAdapter=Ze.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!==(o=n.useSharedArrayBuffer)&&void 0!==o?o:c.isSharedArrayBufferSupported(),entityDataSize:null!==(s=n.entityDataSize)&&void 0!==s?s: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 Ke(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,o="";if(r){var s=r.toString().match(/\{([\s\S]*)\}/);s&&(o=s[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 "+(o?"\n // 用户定义的处理函数\n const userProcessFunction = function(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig) {\n "+o+"\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.logger.info(this.systemName+": Worker不可用,使用同步处理"),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,o,a,c,u,h,d,f,p,m,y,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),o=g.deltaTime,a=r.map((function(e){return _.workerPool.execute({entities:e,deltaTime:o,systemConfig:_.config.systemConfig})})),e.n=1,Promise.all(a);case 1:for(c=e.v,u=0,h=s(c);!(d=h()).done;)for(f=d.value,p=s(f);!(m=p()).done;)y=m.value,u<t.length&&(v=t[u])&&y&&this.applyResult(v,y),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=g.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 o=Math.min(r+i,e.length);n.push(e.slice(r,o))}n.length>t&&this.logger.warn(this.systemName+": 创建了 "+n.length+" 个批次,但只有 "+t+" 个Worker。某些Worker将依次处理多个批次。")}else for(var s=Math.ceil(e.length/t),a=0;a<t;a++){var c=a*s,u=Math.min(c+s,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 o=0;o<e;o+=n){var s=o,a=Math.min(o+n,e),c=this.workerPool.executeSharedBuffer({startIndex:s,endIndex:a,deltaTime:g.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,d=Math.min(l+u,e);if(l<e){var f=this.workerPool.executeSharedBuffer({startIndex:l,endIndex:d,deltaTime:g.deltaTime,systemConfig:this.config.systemConfig});t.push(f)}}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}(Ye),Ke=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=k("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=s(this.workers);!(e=t()).done;){e.value.terminate()}this.workers.length=0,this.taskQueue.length=0,this.busyWorkers.clear()},e}(),$e=function(){function e(){}return e.getType=function(e){return e.constructor},e}(),et=function(){function e(){}return e.toNumber=function(e){return null==e?0:Number(e)},e}(),tt=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}();function nt(e){return Ze.getInstance().registerAdapter(e)}function it(){return Ze.getInstance().getAdapter()}function rt(){return Ze.getInstance().getBasicWorkerConfig()}function ot(){return Ze.getInstance().getFullPlatformConfig()}function st(e){return Ze.getInstance().supportsFeature(e)}function at(){return Ze.getInstance().hasAdapter()}export{w as BitMask64Utils,ke as Bits,q as COMPONENT_TYPE_NAME,M as Colors,He as Component,ze as ComponentDataCollector,Ne as ComponentPool,Oe as ComponentPoolManager,X as ComponentRegistry,se as ComponentSparseSet,Z as ComponentStorage,De as ComponentTypeManager,A as ConsoleLogger,qe as Core,Le as DebugManager,U as ECSComponent,le as ECSEventType,Te as ECSFluentAPI,H as ECSSystem,ye as EVENT_TYPES,Ue as Emitter,B as EnableSoA,$ as Entity,Pe as EntityDataCollector,te as EntityList,ne as EntityProcessorList,Ye as EntitySystem,ve as EventBus,de as EventPriority,ge as EventTypeValidator,z as Float32,O as Float64,je as FuncPack,_e as GlobalEventBus,y as GlobalManager,N as HighPrecision,ie as IdentifierPool,W as Int32,Xe as IntervalSystem,b as LogLevel,x as Logger,I as LoggerManager,Ge as Matcher,et as NumberExtension,Ve as PassiveSystem,Be as PerformanceDataCollector,E as PerformanceMonitor,v as PerformanceWarningType,tt as PlatformDetector,Ze as PlatformManager,C as Pool,T as PoolManager,Qe as ProcessingSystem,fe as QuerySystem,j as SYSTEM_TYPE_NAME,Se as Scene,We as SceneDataCollector,F as SerializeMap,L as SoAStorage,re as SparseSet,Re as SystemDataCollector,g as Time,_ as Timer,S as TimerManager,me as TypeSafeEventSystem,$e as TypeUtils,Fe as WebSocketManager,Je as WorkerEntitySystem,Ae as World,xe as WorldManager,we as createECSAPI,k as createLogger,rt as getBasicWorkerConfig,Q as getComponentInstanceTypeName,G as getComponentTypeName,it as getCurrentAdapter,ot as getFullPlatformConfig,V as getSystemInstanceTypeName,Y as getSystemTypeName,at as hasAdapter,nt as registerPlatformAdapter,P as resetLoggerColors,R as setGlobalLogLevel,D as setLoggerColors,st as supportsFeature};
4
4
  //# sourceMappingURL=index.mjs.map