@esengine/ecs-framework 2.2.0 → 2.2.1

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.es5.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function t(e,t,n,r,i,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(r,i)}function n(e){return function(){var n=this,r=arguments;return new Promise((function(i,o){var s=e.apply(n,r);function a(e){t(s,i,o,a,c,"next",e)}function c(e){t(s,i,o,a,c,"throw",e)}a(void 0)}))}}function r(e,t,n){if(h())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&d(i,n.prototype),i}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,p(r.key),r)}}function o(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(t,n){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}(t))||n){r&&(t=r);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}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 r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a.apply(null,arguments)}function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function u(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,d(e,t)}function h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(h=function(){return!!e})()}function l(){
2
2
  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
3
- var e,t,n="function"==typeof Symbol?Symbol:{},r=n.iterator||"@@iterator",i=n.toStringTag||"@@toStringTag";function o(n,r,i,o){var c=r&&r.prototype instanceof a?r:a,u=Object.create(c.prototype);return f(u,"_invoke",function(n,r,i){var o,a,c,u=0,h=i||[],l=!1,f={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,n){return o=t,a=0,c=e,f.n=n,s}};function d(n,r){for(a=n,c=r,t=0;!l&&u&&!i&&t<h.length;t++){var i,o=h[t],d=f.p,p=o[2];n>3?(i=p===r)&&(c=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=e):o[0]<=d&&((i=n<2&&d<o[1])?(a=0,f.v=r,f.n=o[1]):d<p&&(i=n<3||o[0]>r||r>p)&&(o[4]=n,o[5]=r,f.n=p,a=0))}if(i||n>1)return s;throw l=!0,r}return function(i,h,p){if(u>1)throw TypeError("Generator is already running");for(l&&1===h&&d(h,p),a=h,c=p;(t=a<2?e:c)||!l;){o||(a?a<3?(a>1&&(f.n=-1),d(a,c)):f.n=c:f.v=c);try{if(u=2,o){if(a||(i="next"),t=o[i]){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 '"+i+"' method"),a=1);o=e}else if((t=(l=f.n<0)?c:n.call(r,f))!==s)break}catch(t){o=e,a=1,c=t}finally{u=1}}return{value:t,done:l}}}(n,i,o),!0),u}var s={};function a(){}function c(){}function u(){}t=Object.getPrototypeOf;var h=[][r]?t(t([][r]())):(f(t={},r,(function(){return this})),t),d=u.prototype=a.prototype=Object.create(h);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,f(e,i,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=u,f(d,"constructor",u),f(u,"constructor",c),c.displayName="GeneratorFunction",f(u,i,"GeneratorFunction"),f(d),f(d,i,"Generator"),f(d,r,(function(){return this})),f(d,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:o,m:p}})()}function f(e,t,n,r){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}f=function(e,t,n,r){function o(t,n){f(e,t,(function(e){return this._invoke(t,n,e)}))}t?i?i(e,t,{value:n,enumerable:!r,configurable:!r,writable:!r}):e[t]=n:(o("next",0),o("throw",1),o("return",2))},f(e,t,n,r)}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function p(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function y(e){var t="function"==typeof Map?new Map:void 0;return y=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return r(e,arguments,c(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),d(n,e)},y(e)}var m=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}();m.deltaTime=0,m.unscaledDeltaTime=0,m.totalTime=0,m.unscaledTotalTime=0,m.timeScale=1,m.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+=m.deltaTime,this._isDone},t.initialize=function(e,t,n,r){this._timeInSeconds=e,this._repeats=t,this.context=n,this._onTime=r.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}}])}(),g=new WeakMap,_=new WeakMap,S=new WeakMap;function E(e){return void 0===e&&(e=0),function(t){var n=t.prototype;if(!n||"function"!=typeof n.update)throw new Error("@Updatable() decorator requires class "+t.name+" to implement IUpdatable interface with update() method. Please add 'implements IUpdatable' and define update(deltaTime?: number): void method.");return S.set(t,{updatable:!0,priority:e}),t}}function C(e){var t,n=g.get(e);return null!==(t=null==n?void 0:n.injectable)&&void 0!==t&&t}function b(e,t){for(var n,i=(n=e,_.get(n)||new Map),o=[],s=e.length,a=0;a<s;a++){var c=i.get(a);if(c){if("string"==typeof c||"symbol"==typeof c)throw new Error("String and Symbol service identifiers are not yet supported in constructor injection. Please use class types for "+e.name+" parameter "+a);o.push(t.resolve(c))}else o.push(void 0)}return r(e,o)}function w(e){var t,n=S.get(e);return null!==(t=null==n?void 0:n.updatable)&&void 0!==t&&t}function A(e){return S.get(e)}var T,x=function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};exports.TimerManager=function(){function e(){this._timers=[]}var t=e.prototype;return t.update=function(){for(var e=this._timers.length-1;e>=0;e--)this._timers[e].tick()&&(this._timers[e].unload(),this._timers.splice(e,1))},t.schedule=function(e,t,n,r){var i=new v;return i.initialize(e,t,n,r),this._timers.push(i),i},t.dispose=function(){for(var e,t=s(this._timers);!(e=t()).done;){e.value.unload()}this._timers=[]},e}(),exports.TimerManager=x([E()],exports.TimerManager),exports.PerformanceWarningType=void 0,(T=exports.PerformanceWarningType||(exports.PerformanceWarningType={})).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";var M=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 r=performance.now(),i=r-t,o={name:e,executionTime:i,entityCount:n,averageTimePerEntity:n>0?i/n:0,lastUpdateTime:r};this._systemData.set(e,o),this.updateStats(e,i)}},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 r=[].concat(e.recentTimes).sort((function(e,t){return e-t})),i=r.length;e.percentile95=r[Math.floor(.95*i)]||0,e.percentile99=r[Math.floor(.99*i)]||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 r=t.value,i=r[0],o=r[1],a=this._systemData.get(i);e.push("System: "+i),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=[],r=s(this._systemData.entries());!(t=r()).done;){var i=t.value,o=i[0],a=i[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 r=t.value;r.recentTimes.length>e;)r.recentTimes.shift()},t.dispose=function(){this._systemData.clear(),this._systemStats.clear(),this._warnings=[],this._fpsHistory=[],this._memoryHistory=[],this._isEnabled=!1},o(e,[{key:"isEnabled",get:function(){return this._isEnabled}}])}(),I=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,r){void 0===n&&(n=100),void 0===r&&(r=1024);var i=this._pools.get(t);return i||(i=new e((function(){return new t}),n,r),this._pools.set(t,i)),i};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 r=this._createFn();r.reset(),this._objects.push(r),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 r=e.value,i=r[0],o=r[1];t[i.name||i.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,r=Object.entries(e);n<r.length;n++){var i=r[n],o=i[0],s=i[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}();I._pools=new Map;var k,D=function(){function e(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}var t=e.prototype;return t.registerPool=function(e,t){this.pools.set(e,t)},t.getPool=function(e){return this.pools.get(e)||null},t.update=function(){var e=Date.now();e-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=e)},t.createPool=function(e,t,n,r){void 0===n&&(n=100),void 0===r&&(r=1024);var i=this.pools.get(e);return i||(i=new I(t,n,r),this.pools.set(e,i)),i},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 r=e.value,i=r[0],o=r[1];t.set(i,o.getStats())}return t},t.getGlobalStats=function(){for(var e,t=0,n=0,r=0,i=0,o=0,a=0,c=s(this.pools.values());!(e=c()).done;){var u=e.value.getStats();t+=u.size,n+=u.maxSize,r+=u.totalCreated,i+=u.totalObtained,o+=u.totalReleased,a+=u.estimatedMemoryUsage}return{size:t,maxSize:n,totalCreated:r,totalObtained:i,totalReleased:o,hitRate:0===i?0:(i-r)/i,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,r=s(this.pools);!(n=r()).done;){var i=n.value,o=i[0],a=i[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,r=n.getStats(),i=Math.floor(.2*r.maxSize);n.prewarm(i)}},t.reset=function(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0},t.dispose=function(){this.reset()},e}();!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(k||(k={}));var O=function(){function e(){}return e.create=function(t){if(t<0)throw new Error("Bit index "+t+" out of range [0, ∞)");var n={base:[0,0],segments:void 0};return e.setBit(n,t),n},e.fromNumber=function(e){return{base:[e>>>0,0],segments:void 0}},e.hasAny=function(e,t){var n=t.base,r=e.base,i=t.segments,o=e.segments,s=0!==(r[k.LOW]&n[k.LOW])||0!==(r[k.HIGH]&n[k.HIGH]);return!s&&i&&o?o.some((function(e,t){return 0!==(e[k.LOW]&i[t][k.LOW])||0!==(e[k.HIGH]&i[t][k.HIGH])})):s},e.hasAll=function(e,t){var n,r=e.base,i=t.base,o=e.segments,s=t.segments,a=(r[k.LOW]&i[k.LOW])===i[k.LOW]&&(r[k.HIGH]&i[k.HIGH])===i[k.HIGH];if(!a||!s)return a;var c=null!==(n=null==o?void 0:o.length)&&void 0!==n?n:0;if(o)for(var u=0;u<Math.min(c,s.length);u++)if((o[u][k.LOW]&s[u][k.LOW])!==s[u][k.LOW]||(o[u][k.HIGH]&s[u][k.HIGH])!==s[u][k.HIGH])return!1;for(var h=c;h<s.length;h++)if(0!==s[h][k.LOW]||0!==s[h][k.HIGH])return!1;return!0},e.hasNone=function(e,t){var n=e.base,r=t.base,i=e.segments,o=t.segments,s=0===(n[k.LOW]&r[k.LOW])&&0===(n[k.HIGH]&r[k.HIGH]);return i&&s&&o?i.every((function(e,t){return 0===(e[k.LOW]&o[t][k.LOW])&&0===(e[k.HIGH]&o[t][k.HIGH])})):s},e.isZero=function(e){var t=0===e.base[k.LOW]&&0===e.base[k.HIGH];return e.segments&&t?e.segments.every((function(e){return 0===e[k.LOW]&&0===e[k.HIGH]})):t},e.equals=function(e,t){var n,r,i=e.base[k.LOW]===t.base[k.LOW]&&e.base[k.HIGH]===t.base[k.HIGH];if(!i||!e.segments&&!t.segments)return i;for(var o=null!==(n=e.segments)&&void 0!==n?n:[],s=null!==(r=t.segments)&&void 0!==r?r:[],a=0;a<Math.max(o.length,s.length);a++){var c=o[a],u=s[a];if(c&&!u){if(0!==c[k.LOW]||0!==c[k.HIGH])return!1}else if(!c&&u){if(0!==u[k.LOW]||0!==u[k.HIGH])return!1}else if(c[k.LOW]!==u[k.LOW]||c[k.HIGH]!==u[k.HIGH])return!1}return!0},e.setBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var r=e.getSegmentByBitIndex(t,n),i=63&n;i<32?r[k.LOW]|=1<<i:r[k.HIGH]|=1<<i-32},e.getBit=function(t,n){if(n<0)return!1;var r=e.getSegmentByBitIndex(t,n,!1);if(!r)return!1;var i=63&n;return i<32?!!(r[k.LOW]&1<<i):!!(r[k.HIGH]&1<<i-32)},e.clearBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var r=e.getSegmentByBitIndex(t,n,!1);if(r){var i=63&n;i<32?r[k.LOW]&=~(1<<i):r[k.HIGH]&=~(1<<i-32)}},e.orInPlace=function(e,t){e.base[k.LOW]|=t.base[k.LOW],e.base[k.HIGH]|=t.base[k.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var r=e.segments;r.length<n.length;)r.push([0,0]);for(var i=0;i<n.length;i++)r[i][k.LOW]|=n[i][k.LOW],r[i][k.HIGH]|=n[i][k.HIGH]}},e.andInPlace=function(e,t){e.base[k.LOW]&=t.base[k.LOW],e.base[k.HIGH]&=t.base[k.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var r=e.segments;r.length<n.length;)r.push([0,0]);for(var i=0;i<n.length;i++)r[i][k.LOW]&=n[i][k.LOW],r[i][k.HIGH]&=n[i][k.HIGH]}},e.xorInPlace=function(e,t){e.base[k.LOW]^=t.base[k.LOW],e.base[k.HIGH]^=t.base[k.HIGH];var n=t.segments;if(n&&0!=n.length){e.segments||(e.segments=[]);for(var r=e.segments;r.length<n.length;)r.push([0,0]);for(var i=0;i<n.length;i++)r[i][k.LOW]^=n[i][k.LOW],r[i][k.HIGH]^=n[i][k.HIGH]}},e.clear=function(e){e.base[k.LOW]=0,e.base[k.HIGH]=0;for(var t=0;t<(null!==(n=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==n?n:0);t++){var n,r,i=e.segments[t];i[k.LOW]=0,i[k.HIGH]=0}},e.copy=function(t,n){if(e.clear(n),n.base[k.LOW]=t.base[k.LOW],n.base[k.HIGH]=t.base[k.HIGH],t.segments&&0!=t.segments.length)if(n.segments){for(var r=t.segments.length-n.segments.length,i=0;i<r;i++)n.segments.push([0,0]);for(var o=0;o<length;o++){var s=n.segments[o],a=t.segments[o];s[k.LOW]=a[k.LOW],s[k.HIGH]=a[k.HIGH]}}else n.segments=t.segments.map((function(e){return[].concat(e)}))},e.clone=function(e){return{base:e.base.slice(),segments:e.segments?e.segments.map((function(e){return[].concat(e)})):void 0}},e.toString=function(e,t,n){var r,i;void 0===t&&(t=2),void 0===n&&(n=!1),2!=t&&16!=t&&(t=2);var o=null!==(r=null===(i=e.segments)||void 0===i?void 0:i.length)&&void 0!==r?r:0,s="";if(n){var a=0;a=2===t?66:19;for(var c=0;c<=o;c++){s+=(0===c?"0 (Base):":c+" ("+64*c+"):").toString().padEnd(a)}s+="\n"}for(var u=-1;u<o;u++){var h="",l=-1==u?e.base:e.segments[u],f=l[k.HIGH],d=l[k.LOW];if(2==t){h=f.toString(2).padStart(32,"0")+"_"+d.toString(2).padStart(32,"0")}else{var p=f?f.toString(16).toUpperCase():"";n&&(p=p.padStart(8,"0"));var y=d.toString(16).toUpperCase();p&&(y=y.padStart(8,"0")),h="0x"+p+y}s+=-1===u?h:" "+h}return s},e.popCount=function(e){for(var t=0,n=-1;n<(null!==(r=null===(i=e.segments)||void 0===i?void 0:i.length)&&void 0!==r?r:0);n++){for(var r,i,o=-1==n?e.base:e.segments[n],s=o[k.LOW],a=o[k.HIGH];s;)s&=s-1,t++;for(;a;)a&=a-1,t++}return t},e.getSegmentByBitIndex=function(e,t,n){if(void 0===n&&(n=!0),t<=63)return e.base;var r=e.segments;if(!r){if(!n)return null;r=e.segments=[]}var i=(t>>6)-1;if(r.length<=i){if(!n)return null;for(var o=i-r.length+1,s=0;s<o;s++)r.push([0,0])}return r[i]},e}();O.ZERO={base:[0,0],segments:void 0};var R,B=function(){function e(e){if(e&&"object"==typeof e)this._value=O.clone(e);else if("number"==typeof e)this._value=O.fromNumber(e);else if("string"==typeof e){var t=parseInt(e,10);this._value=O.fromNumber(t)}else this._value=O.clone(O.ZERO)}var t=e.prototype;return t.set=function(e){if(e<0)throw new Error("Bit index cannot be negative");O.setBit(this._value,e)},t.clear=function(e){if(e<0)throw new Error("Bit index cannot be negative");O.clearBit(this._value,e)},t.get=function(e){return O.getBit(this._value,e)},t.containsAll=function(e){return O.hasAll(this._value,e._value)},t.intersects=function(e){return O.hasAny(this._value,e._value)},t.excludes=function(e){return O.hasNone(this._value,e._value)},t.clearAll=function(){O.clear(this._value)},t.isEmpty=function(){return O.isZero(this._value)},t.cardinality=function(){return O.popCount(this._value)},t.and=function(t){var n=new e;return O.copy(this._value,n._value),O.andInPlace(n._value,t._value),n},t.or=function(t){var n=new e;return O.copy(this._value,n._value),O.orInPlace(n._value,t._value),n},t.xor=function(t){var n=new e;return O.copy(this._value,n._value),O.xorInPlace(n._value,t._value),n},t.not=function(t){void 0===t&&(t=64),t>64&&(t=64);var n=new e;if(O.copy(this._value,n._value),t<=32){var r=(1<<t)-1;n._value.base[k.LOW]=~n._value.base[k.LOW]&r,n._value.base[k.HIGH]=0}else if(n._value.base[k.LOW]=~n._value.base[k.LOW],t<64){var i=(1<<t-32)-1;n._value.base[k.HIGH]=~n._value.base[k.HIGH]&i}else n._value.base[k.HIGH]=~n._value.base[k.HIGH];return n},t.copyFrom=function(e){O.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)O.copy(e,this._value);else if("number"==typeof e)this._value=O.fromNumber(e);else{var t=parseInt(e,10);this._value=O.fromNumber(t)}},t.toString=function(){for(var e=[],t=0;t<64;t++)this.get(t)&&e.push(t.toString());return"Bits["+e.join(", ")+"]"},t.toBinaryString=function(e){void 0===e&&(e=0),0==e&&(e=64+(this._value.segments?64*this._value.segments.length:0));for(var t="",n=e-1;n>=0;n--)t+=this.get(n)?"1":"0",n%8==0&&n>0&&(t+=" ");return t},t.toHexString=function(){return O.toString(this._value,16)},e.fromBinaryString=function(t){var n=t.replace(/\s/g,""),r={base:void 0,segments:void 0};if(n.length<=32){var i=parseInt(n,2);r.base=[i>>>0,0]}else{var o=n.substring(n.length-32),s=n.substring(0,n.length-32),a=parseInt(o,2),c=parseInt(s,2);r.base=[a>>>0,c>>>0]}return new e(r)},e.fromHexString=function(t){var n=t.replace(/^0x/i,""),r={base:void 0,segments:void 0};if(n.length<=8){var i=parseInt(n,16);r.base=[i>>>0,0]}else{var o=n.substring(n.length-8),s=n.substring(0,n.length-8),a=parseInt(o,16),c=parseInt(s,16);r.base=[a>>>0,c>>>0]}return new e(r)},t.equals=function(e){return O.equals(this._value,e._value)},t.getHighestBitIndex=function(){if(O.isZero(this._value))return-1;if(0!==this._value.base[k.HIGH])for(var e=31;e>=0;e--)if(this._value.base[k.HIGH]&1<<e)return e+32;for(var t=31;t>=0;t--)if(this._value.base[k.LOW]&1<<t)return t;return-1},t.getLowestBitIndex=function(){if(O.isZero(this._value))return-1;for(var e=0;e<32;e++)if(this._value.base[k.LOW]&1<<e)return e;for(var t=0;t<32;t++)if(this._value.base[k.HIGH]&1<<t)return t+32;return-1},e}(),P=Symbol("ComponentTypeName"),z=Symbol("SystemTypeName");function N(e){return e.__systemMetadata__}function W(e){var t=e[P];return t||(e.name||"UnknownComponent")}function L(e){var t=e[z];return t||(e.name||"UnknownSystem")}function F(e){return W(e.constructor)}function U(e){return L(e.constructor)}exports.LogLevel=void 0,(R=exports.LogLevel||(exports.LogLevel={}))[R.Debug=0]="Debug",R[R.Info=1]="Info",R[R.Warn=2]="Warn",R[R.Error=3]="Error",R[R.Fatal=4]="Fatal",R[R.None=5]="None";var H={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:""},j=function(){function e(e){void 0===e&&(e={}),this._config=a({level:exports.LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window},e)}var t=e.prototype;return t.debug=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Debug,e].concat(n))},t.info=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Info,e].concat(n))},t.warn=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Warn,e].concat(n))},t.error=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Error,e].concat(n))},t.fatal=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Fatal,e].concat(n))},t.setLevel=function(e){this._config.level=e},t.setColors=function(e){0===Object.keys(e).length?delete this._config.colors:this._config.colors=a({},this._config.colors,e)},t.setPrefix=function(e){this._config.prefix=e},t.log=function(e,t){if(!(e<this._config.level)){var n=t;if(this._config.enableTimestamp)n="["+(new Date).toISOString()+"] "+n;if(this._config.prefix&&(n="["+this._config.prefix+"] "+n),n="["+exports.LogLevel[e].toUpperCase()+"] "+n,this._config.output)this._config.output(e,n);else{for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];this.outputToConsole.apply(this,[e,n].concat(i))}}},t.outputToConsole=function(e,t){for(var n=this._config.enableColors?this.getColors():null,r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];switch(e){case exports.LogLevel.Debug:var s,a;if(n)(s=console).debug.apply(s,[""+n.debug+t+n.reset].concat(i));else(a=console).debug.apply(a,[t].concat(i));break;case exports.LogLevel.Info:var c,u;if(n)(c=console).info.apply(c,[""+n.info+t+n.reset].concat(i));else(u=console).info.apply(u,[t].concat(i));break;case exports.LogLevel.Warn:var h,l;if(n)(h=console).warn.apply(h,[""+n.warn+t+n.reset].concat(i));else(l=console).warn.apply(l,[t].concat(i));break;case exports.LogLevel.Error:var f,d;if(n)(f=console).error.apply(f,[""+n.error+t+n.reset].concat(i));else(d=console).error.apply(d,[t].concat(i));break;case exports.LogLevel.Fatal:var p,y;if(n)(p=console).error.apply(p,[""+n.fatal+t+n.reset].concat(i));else(y=console).error.apply(y,[t].concat(i))}},t.getColors=function(){return a({},{debug:H.BRIGHT_BLACK,info:H.GREEN,warn:H.YELLOW,error:H.RED,fatal:H.BRIGHT_RED,reset:H.RESET},this._config.colors)},e}(),q=function(){function e(){this._loggers=new Map,this._defaultLevel=exports.LogLevel.Info,this._defaultLogger=new j({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 j({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 j&&this._defaultLogger.setLevel(e);for(var t,n=s(this._loggers.values());!(t=n()).done;){var r=t.value;r instanceof j&&r.setLevel(e)}},t.createChildLogger=function(e,t){var n=e+"."+t;return this.getLogger(n)},t.setGlobalColors=function(e){this._defaultLogger instanceof j&&this._defaultLogger.setColors(e);for(var t,n=s(this._loggers.values());!(t=n()).done;){var r=t.value;r instanceof j&&r.setColors(e)}},t.resetColors=function(){this._defaultLogger instanceof j&&this._defaultLogger.setColors({});for(var e,t=s(this._loggers.values());!(e=t()).done;){var n=e.value;n instanceof j&&n.setColors({})}},e}(),G=q.getInstance().getLogger();function V(e){return q.getInstance().getLogger(e)}V("ReferenceTracker");var Y=function(){function e(e){this._target=e}return e.prototype.deref=function(){return this._target},e}(),Q="undefined"!=typeof globalThis&&globalThis.WeakRef||"undefined"!=typeof global&&global.WeakRef||"undefined"!=typeof window&&window.WeakRef||Y,J=new Map;function Z(e){var t=J.get(e);return(null==t?void 0:t.deref())||null}var X=function(){function e(){this._references=new Map,this._scene=null}var t=e.prototype;return t.registerReference=function(e,t,n){var r=e.id,i=this._references.get(r);i||(i=new Set,this._references.set(r,i)),this._findRecord(i,t,n)||i.add({component:new Q(t),propertyKey:n})},t.unregisterReference=function(e,t,n){var r=e.id,i=this._references.get(r);if(i){var o=this._findRecord(i,t,n);o&&(i.delete(o),0===i.size&&this._references.delete(r))}},t.clearReferencesTo=function(e){var t=this._references.get(e);if(t){for(var n,r=[],i=s(t);!(n=i()).done;){var o=n.value;o.component.deref()&&r.push(o)}for(var a=0,c=r;a<c.length;a++){var u=c[a],h=u.component.deref();h&&(h[u.propertyKey]=null)}this._references.delete(e)}},t.clearComponentReferences=function(e){for(var t,n=s(this._references.entries());!(t=n()).done;){for(var r,i=t.value,o=i[0],a=i[1],c=[],u=s(a);!(r=u()).done;){var h=r.value,l=h.component.deref();l&&l!==e||c.push(h)}for(var f=0,d=c;f<d.length;f++){var p=d[f];a.delete(p)}0===a.size&&this._references.delete(o)}},t.getReferencesTo=function(e){var t=this._references.get(e);if(!t)return[];for(var n,r=[],i=s(t);!(n=i()).done;){var o=n.value;o.component.deref()&&r.push(o)}return r},t.cleanup=function(){for(var e,t=[],n=s(this._references.entries());!(e=n()).done;){for(var r,i=e.value,o=i[0],a=i[1],c=[],u=s(a);!(r=u()).done;){var h=r.value;h.component.deref()||c.push(h)}for(var l=0,f=c;l<f.length;l++){var d=f[l];a.delete(d)}0===a.size&&t.push(o)}for(var p=0,y=t;p<y.length;p++){var m=y[p];this._references.delete(m)}},t.setScene=function(e){this._scene=new Q(e)},t.registerEntityScene=function(e,t){J.set(e,new Q(t))},t.unregisterEntityScene=function(e){J.delete(e)},t.getDebugInfo=function(){for(var e,t={},n=s(this._references.entries());!(e=n()).done;){for(var r,i=e.value,o=i[0],a=[],c=s(i[1]);!(r=c()).done;){var u=r.value,h=u.component.deref();h&&a.push({componentId:h.id,propertyKey:u.propertyKey})}a.length>0&&(t["entity_"+o]=a)}return t},t._findRecord=function(e,t,n){for(var r,i=s(e);!(r=i()).done;){var o=r.value;if(o.component.deref()===t&&o.propertyKey===n)return o}},e}(),K=V("EntityRefDecorator"),$=Symbol("EntityRefMetadata"),ee=Symbol("EntityRefValues");function te(e){var t=e[ee];return t||(t=new Map,e[ee]=t),t}function ne(e){return e&&("function"==typeof e?e:e.constructor)[$]||null}var re=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,W(e))),t},t.getTypeName=function(e){return this._typeNames.get(e)||"Unknown"},t.createBits=function(){for(var e=new B,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var i=0,o=n;i<o.length;i++){var s=o[i],a=this.getTypeId(s);e.set(a)}return e},t.getEntityBits=function(e){for(var t,n=new B,r=s(e);!(t=r()).done;){var i=t.value,o=this.getTypeId(i);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}}])}(),ie=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 r=this.collectArchetypeData(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:r.distribution,topEntitiesByComponents:r.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 F(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,r,i;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===(r=s.components)||void 0===r?void 0:r.length)||0,componentTypes:(null===(i=s.components)||void 0===i?void 0:i.map((function(e){return F(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 r,i=null===(r=Object.getPrototypeOf(e))||void 0===r||null===(r=r.constructor)||void 0===r?void 0:r.name;i&&"Object"!==i&&(t=i,n=i)}}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 r=this.collectArchetypeDataWithMemory(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:r.distribution,topEntitiesByComponents:r.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,r=(null===(n=e.components)||void 0===n?void 0:n.map((function(e){return F(e)})))||[],i=r.length>0?r.sort().join(", "):"无组件",o=t.get(i);o?o.count++:t.set(i,{count:1,componentTypes:r})})),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=[],r=[];return t.forEach((function(e){var t,i,o=(null===(t=e.componentTypes)||void 0===t?void 0:t.map((function(e){return e.name})).join(","))||"Unknown",s=(null===(i=e.entities)||void 0===i?void 0:i.length)||0;n.push({signature:o,count:s,memory:0}),e.entities&&e.entities.slice(0,5).forEach((function(e){var t;r.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})),r.sort((function(e,t){return t.componentCount-e.componentCount})),{distribution:n,topEntities:r}},t.extractArchetypeStatisticsWithMemory=function(e){var t=this,n=e.getAllArchetypes(),r=[],i=[];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}r.push({signature:s,count:a,memory:c}),e.entities&&e.entities.slice(0,5).forEach((function(e){var n;i.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)})}))})),r.sort((function(e,t){return t.count-e.count})),i.sort((function(e,t){return t.componentCount-e.componentCount})),{distribution:r,topEntities:i}},t.getArchetypeDistribution=function(e){var t=new Map;return e&&e.entities&&e.entities.forEach((function(e){var n,r=(null===(n=e.componentMask)||void 0===n?void 0:n.toString())||"0",i=t.get(r);t.set(r,(i||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 r,i=(null===(r=e.components)||void 0===r?void 0:r.map((function(e){return F(e)})))||[],o=i.length>0?i.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:i})})),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,r=this.calculateObjectSize(e,["components","children","parent"]);return!isNaN(r)&&r>0&&(n+=r),e.components&&Array.isArray(e.components)&&e.components.forEach((function(e){var r=t.calculateObjectSize(e,["entity"]);!isNaN(r)&&r>0&&(n+=r)})),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,r=function(e,i){if(void 0===i&&(i=0),!e||"object"!=typeof e||i>=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+=r(h,i+1))}}}catch(e){return 64}return o};try{var i=r(e);return Math.max(i,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 r=t.buildEntityHierarchyNode(e);n.push(r)}})),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,r={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 F(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&&(r.children=e.children.map((function(e){return n.buildEntityHierarchyNode(e)}))),"function"==typeof e.getDebugInfo)&&(r=a({},r,e.getDebugInfo()));return e.components&&e.components.length>0&&(r.componentDetails=this.extractComponentDetails(e.components)),r},t.buildEntityDetailsMap=function(e,t){var n=this;if(null==e||!e.buffer)return{};for(var r={},i=e.buffer,o=0;o<i.length;o+=100){i.slice(o,o+100).forEach((function(e){var i,o=e.getDebugInfo?e.getDebugInfo():n.buildFallbackEntityInfo(e,t),s=e.getComponentCacheStats?e.getComponentCacheStats():null,c=n.extractComponentDetails(e.components);r[e.id]=a({},o,{parentName:(null===(i=e.parent)||void 0===i?void 0:i.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 r},t.buildFallbackEntityInfo=function(e,t){var n,r,i,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 F(e)})),componentMask:(null===(n=e.componentMask)||void 0===n?void 0:n.toString())||"0",parentId:(null===(r=e.parent)||void 0===r?void 0:r.id)||null,childCount:(null===(i=e.children)||void 0===i?void 0:i.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=F(e);if(!n||"Object"===n||"Function"===n)try{var r=re.instance,i=e.constructor,o=r.getTypeId(i);n=r.getTypeName(o)}catch(e){n="UnknownComponent"}var s={};try{Object.keys(e).forEach((function(n){if(!n.startsWith("_")&&"entity"!==n&&"constructor"!==n){var r=e[n];null!=r&&(s[n]=t.formatPropertyValue(r))}})),0===Object.keys(s).length&&(s._info="该组件没有公开属性",s._componentId=F(e))}catch(t){s._error="属性提取失败",s._componentId=F(e)}return{typeName:n,properties:s}}))},t.getComponentProperties=function(e,t,n){var r=this;try{if(!n)return{};var i=n.entities;if(null==i||!i.buffer)return{};var o=i.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]=r.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 r=Object.keys(e);if(0===r.length)return{};for(var i={},o=0,s=0,a=r;s<a.length;s++){var c=a[s];if(o>=15){i._hasMoreProperties=!0,i._totalProperties=r.length,i._hiddenCount=r.length-o;break}if(!c.startsWith("_")&&!c.startsWith("$")&&"function"!=typeof e[c])try{var u=e[c];null!=u&&(i[c]=this.formatPropertyValue(u,1),o++)}catch(e){i[c]="[访问失败: "+(e instanceof Error?e.message:String(e))+"]",o++}}return i}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 r=void 0!==e.a?e.a:1;return t+"("+e.r+", "+e.g+", "+e.b+", "+r+")"}if(t.toLowerCase().includes("node"))return t+": "+(e.name||e._name||"未命名");if(t.toLowerCase().includes("component")){var i,o,s=(null===(i=e.node)||void 0===i?void 0:i.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,r){try{if(!r)return null;var i=r.entities;if(null==i||!i.buffer)return null;var o=i.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,r=e,i=s(t.split("."));!(n=i()).done;){var o=n.value;if(null==r)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&&(r=r[a]),!(Array.isArray(r)&&c>=0&&c<r.length))return null;r=r[c]}else r=r[o]}return r},e}(),oe=function(){function e(){}return e.prototype.collectSystemData=function(e,t){if(!t)return{totalSystems:0,systemsInfo:[]};var n=t.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};var r=n.processors||[],i=new Map,o=new Map;if(e)try{i=e.getAllSystemStats(),o=e.getAllSystemData()}catch(e){}return{totalSystems:r.length,systemsInfo:r.map((function(e){var t,n=e.systemName||U(e),r=i.get(n),s=o.get(n);return{name:n,type:U(e),entityCount:(null===(t=e.entities)||void 0===t?void 0:t.length)||0,executionTime:(null==r?void 0:r.averageTime)||(null==s?void 0:s.executionTime)||0,minExecutionTime:(null==r?void 0:r.minTime)===Number.MAX_VALUE?0:(null==r?void 0:r.minTime)||0,maxExecutionTime:(null==r?void 0:r.maxTime)||0,executionTimeHistory:(null==r?void 0:r.recentTimes)||[],updateOrder:e.updateOrder||0,enabled:!1!==e.enabled,lastUpdateTime:(null==s?void 0:s.lastUpdateTime)||0}}))}},e}(),se=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=m.deltaTime,n=1e3*t,r=t>0?Math.round(1/t):0,i=this.getECSPerformanceData(e),o=i.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:r,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:i.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=[],r=e.getAllSystemStats();if(0===r.size)return{totalExecutionTime:0,systemBreakdown:[]};for(var i,o=s(r.entries());!(i=o()).done;){var a=i.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],r=e[1],i=n.get(t);return{systemName:t,averageTime:r.averageTime||0,maxTime:r.maxTime||0,minTime:r.minTime===Number.MAX_VALUE?0:r.minTime||0,samples:r.executionCount||0,percentage:0,entityCount:(null==i?void 0:i.entityCount)||0,lastExecutionTime:(null==i?void 0:i.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}(),ae=function(){function e(e,t,n,r,i){void 0===n&&(n=1e3),void 0===r&&(r=10),void 0===i&&(i=1.5),this.pool=[],this.stats={totalCreated:0,totalAcquired:0,totalReleased:0},this.createFn=e,this.resetFn=t,this.maxSize=n,this.minSize=Math.max(1,r),this.growthFactor=Math.max(1.1,i)}var t=e.prototype;return t.acquire=function(){return this.stats.totalAcquired++,this.pool.length>0?this.pool.pop():(this.stats.totalCreated++,this.createFn())},t.release=function(e){this.stats.totalReleased++,this.pool.length>=this.maxSize||(this.resetFn&&this.resetFn(e),this.pool.push(e))},t.prewarm=function(e){for(var t=Math.min(e,this.maxSize),n=this.pool.length;n<t;n++){var r=this.createFn();this.resetFn&&this.resetFn(r),this.pool.push(r),this.stats.totalCreated++}},t.shrink=function(){for(;this.pool.length>this.minSize;)this.pool.pop()},t.clear=function(){this.pool.length=0},t.getAvailableCount=function(){return this.pool.length},t.getMaxSize=function(){return this.maxSize},t.getStats=function(){var e=0===this.stats.totalAcquired?0:(this.stats.totalAcquired-this.stats.totalCreated)/this.stats.totalAcquired;return{totalCreated:this.stats.totalCreated,totalAcquired:this.stats.totalAcquired,totalReleased:this.stats.totalReleased,hitRate:e,currentSize:this.pool.length,maxSize:this.maxSize,minSize:this.minSize,utilizationRate:this.pool.length/this.maxSize}},e}(),ce=function(){function e(){this.pools=new Map,this.usageTracker=new Map,this.autoCleanupInterval=6e4,this.lastCleanupTime=0}e.getInstance=function(){return e.instance||(e.instance=new e),e.instance};var t=e.prototype;return t.registerPool=function(e,t,n,r,i){this.pools.set(e,new ae(t,n,r,i)),this.usageTracker.set(e,{createCount:0,releaseCount:0,lastAccessTime:Date.now()})},t.acquireComponent=function(e){var t=this.pools.get(e);return this.trackUsage(e,"create"),t?t.acquire():null},t.releaseComponent=function(e,t){var n=this.pools.get(e);this.trackUsage(e,"release"),n&&n.release(t)},t.trackUsage=function(e,t){var n=this.usageTracker.get(e);n||(n={createCount:0,releaseCount:0,lastAccessTime:Date.now()},this.usageTracker.set(e,n)),"create"===t?n.createCount++:n.releaseCount++,n.lastAccessTime=Date.now()},t.update=function(){var e=Date.now();if(!(e-this.lastCleanupTime<this.autoCleanupInterval)){for(var t,n=s(this.usageTracker.entries());!(t=n()).done;){var r=t.value,i=r[0];if(e-r[1].lastAccessTime>12e4){var o=this.pools.get(i);o&&o.shrink()}}this.lastCleanupTime=e}},t.getHotComponents=function(e){return void 0===e&&(e=100),Array.from(this.usageTracker.entries()).filter((function(t){return t[0],t[1].createCount>e})).map((function(e){return e[0]}))},t.prewarmAll=function(e){void 0===e&&(e=100);for(var t,n=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(),this.usageTracker.clear()},t.getGlobalStats=function(){for(var e,t=[],n=s(this.pools.entries());!(e=n()).done;){var r=e.value,i=r[0],o=r[1];t.push({componentName:i,poolStats:o.getStats(),usage:this.usageTracker.get(i)})}return t},t.getPoolStats=function(){for(var e,t=new Map,n=s(this.pools);!(e=n()).done;){var r=e.value,i=r[0],o=r[1];t.set(i,{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 r=e.value,i=r[0],o=r[1],a=o.getAvailableCount(),c=o.getMaxSize(),u=c-a,h=c>0?u/c*100:0;t.set(i,{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(),r=t.getMaxSize();return r>0?(r-n)/r*100:0},e}(),ue=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 r=new Map,i=0;n.buffer.forEach((function(e){e.components&&e.components.forEach((function(e){var t=F(e),n=r.get(t)||{count:0,entities:0};n.count++,i++,r.set(t,n)}))}));var o=new Map,a=new Map;try{for(var c,u=ce.getInstance(),h=u.getPoolStats(),l=u.getPoolUtilization(),f=s(h.entries());!(c=f()).done;){var d=c.value,p=d[0],y=d[1];a.set(p,y.maxSize)}for(var m,v=s(l.entries());!(m=v()).done;){var g=m.value,_=g[0],S=g[1];o.set(_,S.utilization)}}catch(e){}return{componentTypes:r.size,componentInstances:i,componentStats:Array.from(r.entries()).map((function(r){var i=r[0],s=r[1],c=a.get(i)||0,u=o.get(i)||0,h=t.getEstimatedComponentSize(i,e);return{typeName:i,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 r=n.entities;if(null==r||!r.buffer)return 64;var i=64;try{for(var o,a=s(r.buffer);!(o=a()).done;){var c=o.value;if(c.components){var u=c.components.find((function(e){return F(e)===t}));if(u){i=this.calculateQuickObjectSize(u);break}}}}catch(e){i=64}return e.componentSizeCache.set(t,i),i},t.calculateQuickObjectSize=function(e){if(!e||"object"!=typeof e)return 8;var t=32,n=new WeakSet,r=function(e,t){if(void 0===t&&(t=0),!e||"object"!=typeof e||n.has(e)||t>3)return 0;n.add(e);var i=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];i+=2*a.length,"string"==typeof c?i+=Math.min(2*c.length,200):"number"==typeof c?i+=8:"boolean"==typeof c?i+=4:"object"==typeof c&&null!==c&&(i+=r(c,t+1))}}}catch(e){return 32}return i};return t+=r(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 r,i=s(n.buffer);!(r=i()).done;){var o=r.value;if(o.components){var a=o.components.find((function(t){return F(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 r=0;switch(typeof e){case"boolean":r=4;break;case"number":default:r=8;break;case"string":r=24+Math.min(2*e.length,1e3);break;case"object":if(t.add(e),Array.isArray(e)){r=40+8*e.length;for(var i=Math.min(e.length,50),o=0;o<i;o++)r+=this.estimateObjectSize(e[o],t,n+1)}else{r=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{r+=16+2*u.length;var h=e[u];null!=h&&(r+=this.estimateObjectSize(h,t,n+1))}catch(e){continue}}}catch(e){r=128}}}return 8*Math.ceil(r/8)},e.clearCache=function(){e.componentSizeCache.clear()},e}();ue.componentSizeCache=new Map;var he=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 r=(Date.now()-this.sceneStartTime)/1e3,i=e.entities,o=e.entityProcessors;return{currentSceneName:e.name||"Unnamed Scene",isInitialized:e._didSceneBegin||!1,sceneRunTime:r,sceneEntityCount:(null==i||null===(t=i.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:r}},t.setSceneStartTime=function(e){this.sceneStartTime=e},e}(),le=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}(),fe=function(){function e(e,t,n){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.config=n,this.sceneManager=e,this.performanceMonitor=t,this.entityCollector=new ie,this.systemCollector=new oe,this.performanceCollector=new se,this.componentCollector=new ue,this.sceneCollector=new he,this.webSocketManager=new le(n.websocketUrl,!1!==n.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));var r=n.debugFrameRate||30;this.sendInterval=1e3/r,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 le(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,r=e.propertyPath,i=e.requestId;if(void 0===t||void 0===n||!r)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,error:"缺少必要参数"});var o=this.entityCollector.expandLazyObject(t,n,r);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,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,r=e.requestId;if(void 0===t||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:r,error:"缺少必要参数"});var i=this.entityCollector.getComponentProperties(t,n);this.webSocketManager.send({type:"get_component_properties_response",requestId:r,data:i})}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 r=this.entityCollector.getEntityDetails(t);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:r})}catch(t){this.webSocketManager.send({type:"get_entity_details_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleMemorySnapshotRequest=function(){try{var e=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:e})}catch(e){this.webSocketManager.send({type:"memory_snapshot_error",error:e instanceof Error?e.message:"内存快照捕获失败"})}},t.captureMemorySnapshot=function(){var e=Date.now(),t=this.collectBaseMemoryInfo(),n=this.sceneManager.currentScene,r=this.entityCollector.collectEntityDataWithMemory(n),i=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=r.entitiesPerArchetype.reduce((function(e,t){return e+t.memory}),0);return{timestamp:e,version:"2.0",summary:{totalEntities:r.totalEntities,totalMemoryUsage:t.usedMemory,totalMemoryLimit:t.totalMemory,memoryUtilization:t.usedMemory/t.totalMemory*100,gcCollections:t.gcCollections,entityMemory:c,componentMemory:i.totalMemory,systemMemory:o.totalMemory,poolMemory:s.totalMemory},baseMemory:t,entities:{totalMemory:c,entityCount:r.totalEntities,archetypes:r.entitiesPerArchetype,largestEntities:r.topEntitiesByComponents},components:i,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,r=0,i=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=F(c.value);i.set(h,(i.get(h)||0)+1)}}for(var l,f=s(i.entries());!(l=f()).done;){var d=l.value,p=d[0],y=d[1],m=this.componentCollector.calculateDetailedComponentMemory(p),v=m*y;r+=v;for(var g,_=[],S=0,E=s(e.buffer);!(g=E()).done;){var C=g.value;if(C&&!C.destroyed&&C.components){for(var b,w=s(C.components);!(b=w()).done;){if(F(b.value)===p&&(_.push({entityId:C.id,entityName:C.name||"Entity_"+C.id,memory:m}),++S>=100))break}if(S>=100)break}}n.set(p,{count:y,totalMemory:v,instances:_.slice(0,10)})}var A=Array.from(n.entries()).map((function(e){var t=e[0],n=e[1];return{typeName:t,instanceCount:n.count,totalMemory:n.totalMemory,averageMemory:n.totalMemory/n.count,percentage:r>0?n.totalMemory/r*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:r,componentTypes:n.size,totalInstances:Array.from(n.values()).reduce((function(e,t){return e+t.count}),0),breakdown:A}},t.collectSystemMemoryStats=function(){var e=this.sceneManager.currentScene,t=0,n=[];try{var r=null==e?void 0:e.systems;if(r)for(var i,o=new Map,a=s(r);!(i=a()).done;){var c=i.value,u=U(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),r=0;r<Math.min(n.length,15);r++){var i=n[r];if("entities"!==i&&"scene"!==i&&"constructor"!==i){var o=e[i];t+=2*i.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,r=s(ce.getInstance().getPoolStats().entries());!(n=r()).done;){var i=n.value,o=i[0],a=i[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=I.getAllPoolStats(),h=0,l=Object.entries(u);h<l.length;h++){var f=l[h],d=f[0],p=f[1];e+=p.estimatedMemoryUsage,t.push({typeName:"Pool_"+d,maxSize:p.maxSize,currentSize:p.size,estimatedMemory:p.estimatedMemoryUsage,utilization:p.size/p.maxSize*100,hitRate:100*p.hitRate})}}catch(e){}return{totalMemory:e,poolCount:t.length,breakdown:t.sort((function(e,t){return t.estimatedMemory-e.estimatedMemory}))}},t.collectPerformanceStats=function(){try{var e;if(!this.performanceMonitor)return{enabled:!1};var t=this.performanceMonitor.getAllSystemStats(),n=this.performanceMonitor.getPerformanceWarnings();return{enabled:null!==(e=this.performanceMonitor.enabled)&&void 0!==e&&e,systemCount:t.size,warnings:n.slice(0,10),topSystems:Array.from(t.entries()).map((function(e){var t=e[0],n=e[1];return{name:t,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort((function(e,t){return t.averageTime-e.averageTime})).slice(0,5)}}catch(e){return{enabled:!1,error:e instanceof Error?e.message:String(e)}}},t.getDebugData=function(){var e=Date.now(),t=this.sceneManager.currentScene,n={timestamp:e,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:(null==t?void 0:t.name)||"Unknown"};return this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(t)),this.config.channels.systems&&(n.systems=this.systemCollector.collectSystemData(this.performanceMonitor,t)),this.config.channels.performance&&(n.performance=this.performanceCollector.collectPerformanceData(this.performanceMonitor)),this.config.channels.components&&(n.components=this.componentCollector.collectComponentData(t)),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData(t)),n},t.connectWebSocket=function(){var e=n(l().m((function e(){return l().w((function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.webSocketManager.connect();case 1:e.n=3;break;case 2:e.p=2,e.v;case 3:return e.a(2)}}),e,this,[[0,2]])})));return function(){return e.apply(this,arguments)}}(),t.sendDebugData=function(){if(this.webSocketManager.getConnectionStatus())try{var e={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(e)}catch(e){}},t.dispose=function(){this.stop()},e}();var de=function(){function e(){}return e.inferOptimalType=function(e,t){void 0===t&&(t={});var n=typeof e;if("boolean"===n)return"uint8";if("number"!==n)return"float32";var r=t,i=r.minValue,o=r.maxValue,s=r.precision,a=r.signed;if(!0===s)return Math.abs(e)>34028235e31||void 0!==i&&Math.abs(i)>34028235e31||void 0!==o&&Math.abs(o)>34028235e31?"float64":"float32";if(!1===s||Number.isInteger(e)){var c=void 0!==i?i:e,u=void 0!==o?o:e;return!1!==a&&(c<0||e<0)?c>=-128&&u<=127?"int8":c>=-32768&&u<=32767?"int16":c>=-2147483648&&u<=2147483647?"int32":"float64":u<=255?"uint8":u<=65535?"uint16":u<=4294967295?"uint32":"float64"}return Number.isInteger(e)?e>=0&&e<=255?"uint8":e>=-128&&e<=127?"int8":e>=0&&e<=65535?"uint16":e>=-32768&&e<=32767?"int16":e>=0&&e<=4294967295?"uint32":e>=-2147483648&&e<=2147483647?"int32":"float64":"float32"},e.getTypedArrayConstructor=function(e){switch(e){case"float32":default:return Float32Array;case"float64":return Float64Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int8":return Int8Array;case"uint8":return Uint8Array;case"uint8clamped":return Uint8ClampedArray}},e}(),pe=function(){function e(e){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=e,this.initializeFields(e)}var t=e.prototype;return t.initializeFields=function(t){var n=new t,r=t.__highPrecisionFields||new Set,i=t.__float64Fields||new Set,o=t.__float32Fields||new Set,s=t.__int32Fields||new Set,a=t.__uint32Fields||new Set,c=t.__int16Fields||new Set,u=t.__uint16Fields||new Set,h=t.__int8Fields||new Set,l=t.__uint8Fields||new Set,f=t.__uint8ClampedFields||new Set,d=t.__autoTypedFields||new Map,p=t.__serializeMapFields||new Set,y=t.__serializeSetFields||new Set,m=t.__serializeArrayFields||new Set;for(var v in n)if(n.hasOwnProperty(v)&&"id"!==v){var g=n[v],_=typeof g;if("number"===_)if(r.has(v));else if(d.has(v)){var S=d.get(v),E=de.inferOptimalType(g,S),C=de.getTypedArrayConstructor(E);this.fields.set(v,new C(this._capacity)),e._logger.info("字段 "+v+" 自动推断为 "+E+" 类型,值: "+g+", 选项:",S)}else i.has(v)?this.fields.set(v,new Float64Array(this._capacity)):s.has(v)?this.fields.set(v,new Int32Array(this._capacity)):a.has(v)?this.fields.set(v,new Uint32Array(this._capacity)):c.has(v)?this.fields.set(v,new Int16Array(this._capacity)):u.has(v)?this.fields.set(v,new Uint16Array(this._capacity)):h.has(v)?this.fields.set(v,new Int8Array(this._capacity)):l.has(v)?this.fields.set(v,new Uint8Array(this._capacity)):f.has(v)?this.fields.set(v,new Uint8ClampedArray(this._capacity)):(o.has(v),this.fields.set(v,new Float32Array(this._capacity)));else"boolean"===_?l.has(v)||!o.has(v)&&!i.has(v)?this.fields.set(v,new Uint8Array(this._capacity)):this.fields.set(v,new Float32Array(this._capacity)):"string"===_?this.stringFields.set(v,new Array(this._capacity)):"object"===_&&null!==g&&(p.has(v)||y.has(v)||m.has(v))&&this.serializedFields.set(v,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 r;this.freeIndices.length>0?r=this.freeIndices.pop():(r=this._size)>=this._capacity&&this.resize(2*this._capacity),this.entityToIndex.set(e,r),this.indexToEntity[r]=e,this.updateComponentAtIndex(r,t),this._size++}},t.updateComponentAtIndex=function(e,t){var n=this.indexToEntity[e],r=new Map,i=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(i.has(u)||!this.fields.has(u))r.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)?r.set(u,this.deepClone(h)):r.set(u,h)}r.size>0&&this.complexFields.set(n,r)},t.serializeValue=function(t,n,r,i,o){try{return r.has(n)&&t instanceof Map?JSON.stringify(Array.from(t.entries())):i.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,r,i,o){try{var s=JSON.parse(t);return r.has(n)?new Map(s):i.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,r=new Map,i=s(e.entries());!(n=i()).done;){var o=n.value,a=o[0],c=o[1];r.set(a,this.deepClone(c))}return r}if(e instanceof Set){for(var u,h=new Set,l=s(e.values());!(u=l()).done;){var f=u.value;h.add(this.deepClone(f))}return h}var d={};for(var p in e)e.hasOwnProperty(p)&&(d[p]=this.deepClone(e[p]));return d},t.getComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;for(var n,r=new this.type,i=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],f=this.getFieldType(h);r[h]="boolean"===f?1===l:l}for(var d,p=s(this.stringFields.entries());!(d=p()).done;){var y=d.value,m=y[0],v=y[1];r[m]=v[t]}for(var g,_=s(this.serializedFields.entries());!(g=_()).done;){var S=g.value,E=S[0],C=S[1][t];C&&(r[E]=this.deserializeValue(C,E,i,o,a))}var b=this.complexFields.get(e);if(b)for(var w,A=s(b.entries());!(w=A()).done;){var T=w.value,x=T[0],M=T[1];r[x]=M}return r},t.getFieldType=function(e){return typeof(new this.type)[e]},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.getComponent(e);return this.complexFields.delete(e),this.entityToIndex.delete(e),this.freeIndices.push(t),this._size--,n},t.resize=function(t){for(var n,r=s(this.fields.entries());!(n=r()).done;){var i=n.value,o=i[0],a=i[1],c=void 0;a instanceof Float32Array?c=new Float32Array(t):a instanceof Float64Array?c=new Float64Array(t):a instanceof Int32Array?c=new Int32Array(t):a instanceof Uint32Array?c=new Uint32Array(t):a instanceof Int16Array?c=new Int16Array(t):a instanceof Uint16Array?c=new Uint16Array(t):a instanceof Int8Array?c=new Int8Array(t):a instanceof Uint8Array?c=new Uint8Array(t):a instanceof Uint8ClampedArray?c=new Uint8ClampedArray(t):(c=new Float32Array(t),e._logger.warn("未知的TypedArray类型用于字段 "+o+",回退到Float32Array")),c.set(a),this.fields.set(o,c)}for(var u,h=s(this.stringFields.entries());!(u=h()).done;){for(var l=u.value,f=l[0],d=l[1],p=new Array(t),y=0;y<d.length;y++)p[y]=d[y];this.stringFields.set(f,p)}for(var m,v=s(this.serializedFields.entries());!(m=v()).done;){for(var g=m.value,_=g[0],S=g[1],E=new Array(t),C=0;C<S.length;C++)E[C]=S[C];this.serializedFields.set(_,E)}this._capacity=t},t.getActiveIndices=function(){return Array.from(this.entityToIndex.values())},t.getFieldArray=function(e){return this.fields.get(e)||null},t.getTypedFieldArray=function(e){return this.fields.get(String(e))||null},t.getEntityIndex=function(e){return this.entityToIndex.get(e)},t.getEntityIdByIndex=function(e){return this.indexToEntity[e]},t.size=function(){return this._size},t.clear=function(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(var e,t=s(this.fields.values());!(e=t()).done;){e.value.fill(0)}for(var n,r=s(this.stringFields.values());!(n=r()).done;)for(var i=n.value,o=0;o<i.length;o++)i[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=[],r=0;r<e.length;r++){var i=e[r],o=i[0],a=i[1];if(t.set(o,r),n[r]=o,r!==a){for(var c,u=s(this.fields.entries());!(c=u()).done;){var h=c.value[1];h[r]=h[a]}for(var l,f=s(this.stringFields.entries());!(l=f()).done;){var d=l.value[1];d[r]=d[a]}for(var p,y=s(this.serializedFields.entries());!(p=y()).done;){var m=p.value[1];m[r]=m[a]}}}this.entityToIndex=t,this.indexToEntity=n,this.freeIndices=[],this._size=e.length}},t.getStats=function(){for(var e,t=0,n=new Map,r=s(this.fields.entries());!(e=r()).done;){var i=e.value,o=i[0],a=i[1],c=void 0,u=void 0;a instanceof Float32Array?(c=4,u="float32"):a instanceof Float64Array?(c=8,u="float64"):a instanceof Int32Array?(c=4,u="int32"):a instanceof Uint32Array?(c=4,u="uint32"):a instanceof Int16Array?(c=2,u="int16"):a instanceof Uint16Array?(c=2,u="uint16"):a instanceof Int8Array?(c=1,u="int8"):a instanceof Uint8Array?(c=1,u="uint8"):a instanceof Uint8ClampedArray?(c=1,u="uint8clamped"):(c=4,u="unknown");var h=a.length*c;t+=h,n.set(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}();pe._logger=V("SoAStorage");var ye=function(){function e(){}return e.register=function(e){var t=W(e);if(this.componentTypes.has(e))return this.componentTypes.get(e);var n=this.nextBitIndex++;return this.componentTypes.set(e,n),this.bitIndexToType.set(n,e),this.componentNameToType.set(t,e),this.componentNameToId.set(t,n),n},e.getBitMask=function(e){var t=this.componentTypes.get(e);if(void 0===t){var n=W(e);throw new Error("Component type "+n+" is not registered")}return O.create(t)},e.getBitIndex=function(e){var t=this.componentTypes.get(e);if(void 0===t){var n=W(e);throw new Error("Component type "+n+" is not registered")}return t},e.isRegistered=function(e){return this.componentTypes.has(e)},e.getTypeByBitIndex=function(e){return this.bitIndexToType.get(e)||null},e.getRegisteredCount=function(){return this.nextBitIndex},e.getComponentType=function(e){return this.componentNameToType.get(e)||null},e.getAllRegisteredTypes=function(){return new Map(this.componentTypes)},e.getAllComponentNames=function(){return new Map(this.componentNameToType)},e.getComponentId=function(e){return this.componentNameToId.get(e)},e.registerComponentByName=function(e){if(this.componentNameToId.has(e))return this.componentNameToId.get(e);var t=this.nextBitIndex++;return this.componentNameToId.set(e,t),t},e.createSingleComponentMask=function(e){var t="single:"+e;if(this.maskCache.has(t))return this.maskCache.get(t);var n=this.getComponentId(e);if(void 0===n)throw new Error("Component type "+e+" is not registered");var r=O.create(n);return this.maskCache.set(t,r),r},e.createComponentMask=function(e){var t="multi:"+[].concat(e).sort().join(",");if(this.maskCache.has(t))return this.maskCache.get(t);for(var n,r=O.clone(O.ZERO),i=s(e);!(n=i()).done;){var o=n.value,a=this.getComponentId(o);if(void 0!==a){var c=O.create(a);O.orInPlace(r,c)}}return this.maskCache.set(t,r),r},e.clearMaskCache=function(){this.maskCache.clear()},e.reset=function(){this.componentTypes.clear(),this.bitIndexToType.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0},e}();ye._logger=V("ComponentStorage"),ye.componentTypes=new Map,ye.bitIndexToType=new Map,ye.componentNameToType=new Map,ye.componentNameToId=new Map,ye.maskCache=new Map,ye.nextBitIndex=0;var me=function(){function e(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e,ye.isRegistered(e)||ye.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 "+W(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],r=this.dense.length-1;if(t!==r){var i=this.dense[r],o=this.entityIds[r];this.dense[t]=i,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}}])}(),ve=function(){function e(){this.storages=new Map}var t=e.prototype;return t.isSoAStorage=function(e){return this.storages.get(e)instanceof pe},t.getSoAStorage=function(e){var t=this.getStorage(e);return t instanceof pe?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 pe(t),e._logger.info("为 "+W(t)+" 启用SoA优化(适用于大规模批量操作)")):n=new me(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=O.clone(O.ZERO),r=s(this.storages.entries());!(t=r()).done;){var i=t.value,o=i[0];if(i[1].hasComponent(e)){var a=ye.getBitMask(o);O.orInPlace(n,a)}}return n},t.getAllStats=function(){for(var e,t=new Map,n=s(this.storages.entries());!(e=n()).done;){var r=e.value,i=r[0],o=r[1],a=W(i);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}();ve._logger=V("ComponentStorage");var ge=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}(),_e=function(){function e(e,t){this.scene=null,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=O.clone(O.ZERO),this._componentCache=null,this.name=e,this.id=t}e.notifyQuerySystems=function(e){e.scene&&e.scene.querySystem&&(e.scene.querySystem.updateEntity(e),e.scene.clearSystemEntityCaches())};var t=e.prototype;return t._rebuildComponentCache=function(){var e,t=[];if(null!==(e=this.scene)&&void 0!==e&&e.componentStorageManager){for(var n=this._componentMask,r=ye.getRegisteredCount(),i=0;i<r;i++)if(O.getBit(n,i)){var o=ye.getTypeByBitIndex(i);if(o){var s=this.scene.componentStorageManager.getComponent(this.id,o);s&&t.push(s)}}this._componentCache=t}else this._componentCache=t},t.createComponent=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];var o=r(e,n);return this.addComponent(o)},t.addComponentInternal=function(e){var t=e.constructor;ye.isRegistered(t)||ye.register(t);var n=ye.getBitMask(t);return O.orInPlace(this._componentMask,n),this._componentCache=null,e},t.addComponent=function(t){var n,r=t.constructor;if(!this.scene)throw new Error("Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()");if(!this.scene.componentStorageManager)throw new Error("Scene does not have componentStorageManager");if(this.hasComponent(r))throw new Error("Entity "+this.name+" already has component "+W(r));(this.addComponentInternal(t),this.scene.componentStorageManager.addComponent(this.id,t),t.entityId=this.id,this.scene.referenceTracker&&this.scene.referenceTracker.registerEntityScene(this.id,this.scene),t.onAddedToEntity(),e.eventBus)&&e.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(n=this.tag)||void 0===n?void 0:n.toString(),componentType:W(r),component:t});return e.notifyQuerySystems(this),t},t.getComponent=function(e){var t;return this.hasComponent(e)&&null!==(t=this.scene)&&void 0!==t&&t.componentStorageManager?this.scene.componentStorageManager.getComponent(this.id,e):null},t.hasComponent=function(e){if(!ye.isRegistered(e))return!1;var t=ye.getBitMask(e);return O.hasAny(this._componentMask,t)},t.getOrCreateComponent=function(e){var t=this.getComponent(e);if(!t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];t=this.createComponent.apply(this,[e].concat(r))}return t},t.removeComponent=function(t){var n,r,i=t.constructor;if(ye.isRegistered(i)){var o,s=ye.getBitIndex(i);if(O.clearBit(this._componentMask,s),this._componentCache=null,null!==(n=this.scene)&&void 0!==n&&n.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,i),null!==(r=this.scene)&&void 0!==r&&r.referenceTracker&&this.scene.referenceTracker.clearComponentReferences(t),t.onRemovedFromEntity&&t.onRemovedFromEntity(),t.entityId=null,e.eventBus)e.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(o=this.tag)||void 0===o?void 0:o.toString(),componentType:W(i),component:t});e.notifyQuerySystems(this)}},t.removeComponentByType=function(e){var t=this.getComponent(e);return t?(this.removeComponent(t),t):null},t.removeAllComponents=function(){var t=[].concat(this.components);O.clear(this._componentMask),this._componentCache=null;for(var n,r=s(t);!(n=r()).done;){var i,o=n.value,a=o.constructor;null!==(i=this.scene)&&void 0!==i&&i.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,a),o.onRemovedFromEntity()}e.notifyQuerySystems(this)},t.addComponents=function(t){for(var n,r=[],i=s(t);!(n=i()).done;){var o=n.value;try{r.push(this.addComponent(o))}catch(t){e._logger.warn("添加组件失败 "+F(o)+":",t)}}return r},t.removeComponentsByTypes=function(e){for(var t,n=[],r=s(e);!(t=r()).done;){var i=t.value;n.push(this.removeComponentByType(i))}return n},t.getComponents=function(e){for(var t,n=[],r=s(this.components);!(t=r()).done;){var i=t.value;i instanceof e&&n.push(i)}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,r=s(this._children);!(n=r()).done;){var i=n.value;if(i.name===e)return i}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,r=[],i=s(this._children);!(n=i()).done;){var o=n.value;o.tag===e&&r.push(o)}if(t)for(var a,c=s(this._children);!(a=c()).done;){var u=a.value;r.push.apply(r,u.findChildrenByTag(e,!0))}return r},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,r){e(n,r),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.destroy=function(){if(!this._isDestroyed){this._isDestroyed=!0,this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id));for(var e,t=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.destroyAllChildren=function(){if(0!==this._children.length){var e=this.scene,t=[],n=function(e){for(var r,i=s(e._children);!(r=i()).done;){var o=r.value;t.push(o),n(o)}};n(this);for(var r=0,i=t;r<i.length;r++){i[r]._isDestroyed=!0}for(var o=0,a=t;o<a.length;o++){a[o].removeAllComponents()}if(e){for(var c,u=s(t);!(c=u()).done;){var h=c.value;e.entities.remove(h),e.querySystem.removeEntity(h)}e.clearSystemEntityCaches()}this._children.length=0}},t.compareTo=function(e){return ge.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 F(e)})),componentMask:O.toString(this._componentMask,2),parentId:(null===(e=this._parent)||void 0===e?void 0:e.id)||null,childCount:this._children.length,childIds:this._children.map((function(e){return e.id})),depth:this.getDepth(),cacheBuilt:null!==this._componentCache}},o(e,[{key:"isDestroyed",get:function(){return this._isDestroyed}},{key:"components",get:function(){return null===this._componentCache&&this._rebuildComponentCache(),this._componentCache}},{key:"parent",get:function(){return this._parent}},{key:"children",get:function(){return[].concat(this._children)}},{key:"childCount",get:function(){return this._children.length}},{key:"active",get:function(){return this._active},set:function(e){this._active!==e&&(this._active=e,this.onActiveChanged())}},{key:"activeInHierarchy",get:function(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}},{key:"tag",get:function(){return this._tag},set:function(e){this._tag=e}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this._updateOrder=e}},{key:"componentMask",get:function(){return this._componentMask}}])}();_e._logger=V("Entity"),_e.entityComparer=new ge,_e.eventBus=null;var Se=function(){function e(e,t){this.scene=e,this.storageManager=t;var n=e.identifierPool.checkOut();this.entity=new _e("",n),this.entity.scene=this.scene}var t=e.prototype;return t.named=function(e){return this.entity.name=e,this},t.tagged=function(e){return this.entity.tag=e,this},t.with=function(e){return this.entity.addComponent(e),this},t.withComponents=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var r=0,i=t;r<i.length;r++){var o=i[r];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 r=0,i=t;r<i.length;r++){var o=i[r].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}(),Ee=function(){function e(e){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._scene=e}var t=e.prototype;return t.add=function(e){this.addImmediate(e)},t.addImmediate=function(e){this._idToEntity.has(e.id)||(this.buffer.push(e),this._idToEntity.set(e.id,e),this.updateNameIndex(e,!0))},t.remove=function(e){this.removeImmediate(e)},t.removeImmediate=function(e){var t=this.buffer.indexOf(e);-1!==t&&(this.buffer.splice(t,1),this._idToEntity.delete(e.id),this.updateNameIndex(e,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(e.id))},t.removeAllEntities=function(){for(var e=[],t=this.buffer.length-1;t>=0;t--)e.push(this.buffer[t].id),this.buffer[t].destroy();if(this._scene&&this._scene.identifierPool)for(var n,r=s(e);!(n=r()).done;){var i=n.value;this._scene.identifierPool.checkIn(i)}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 r,i=s(this._entitiesToRemove);!(r=i()).done;){var o=r.value;this.removeImmediate(o)}this._entitiesToRemove.length=0}},t.update=function(){this.updateLists()},t.findEntity=function(e){var t=this._nameToEntities.get(e);return t&&t.length>0?t[0]:null},t.findEntitiesByName=function(e){return this._nameToEntities.get(e)||[]},t.findEntityById=function(e){return this._idToEntity.get(e)||null},t.findEntitiesByTag=function(e){for(var t,n=[],r=s(this.buffer);!(t=r()).done;){var i=t.value;i.tag===e&&n.push(i)}return n},t.findEntitiesWithComponent=function(e){for(var t,n=[],r=s(this.buffer);!(t=r()).done;){var i=t.value;i.hasComponent(e)&&n.push(i)}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,r=s(this.buffer);!(n=r()).done;){var i=n.value;e(i)&&t(i)}},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 r=this._nameToEntities.get(e.name);if(r){var i=r.indexOf(e);-1!==i&&(r.splice(i,1),0===r.length&&this._nameToEntities.delete(e.name))}}},t.getStats=function(){for(var e,t=0,n=s(this.buffer);!(e=n()).done;){var r=e.value;r.enabled&&!r.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}}])}(),Ce=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,r=0,i=s(this._generations);!(t=i()).done;){var o=t.value,a=o[0],c=o[1];a<this._nextAvailableIndex&&(n+=c,r++)}var u=r>0?n/r: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,r=Date.now(),i=[],o=[],a=s(this._pendingRecycle);!(n=a()).done;){var c=n.value;t||r-c.timestamp>=this._recycleDelay?i.push(c):o.push(c)}for(var u=0,h=i;u<h.length;u++){var l=h[u];if(this._isValidId(l.index,l.generation)){var f=l.generation+1;f>e.MAX_GENERATION&&(f=1),this._generations.set(l.index,f),this._freeIndices.push(l.index)}}this._pendingRecycle=o}},t._preAllocateGenerations=function(t,n){for(var r=0;r<n;r++){var i=t+r;i<=e.MAX_INDEX&&this._generations.set(i,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}();Ce.MAX_INDEX=65535,Ce.MAX_GENERATION=65535;var be=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,r,i=new e;return(t=i.condition.all).push.apply(t,this.condition.all),(n=i.condition.any).push.apply(n,this.condition.any),(r=i.condition.none).push.apply(r,this.condition.none),void 0!==this.condition.tag&&(i.condition.tag=this.condition.tag),void 0!==this.condition.name&&(i.condition.name=this.condition.name),void 0!==this.condition.component&&(i.condition.component=this.condition.component),i},t.toString=function(){var e=[];return this.condition.all.length>0&&e.push("all("+this.condition.all.map((function(e){return W(e)})).join(", ")+")"),this.condition.any.length>0&&e.push("any("+this.condition.any.map((function(e){return W(e)})).join(", ")+")"),this.condition.none.length>0&&e.push("none("+this.condition.none.map((function(e){return W(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("+W(this.condition.component)+")"),"Matcher["+e.join(" & ")+"]"},e}(),we=function(){function e(e){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=U(this),this._initialized=!1,this._matcher=e||be.empty(),this._eventListeners=[],this._scene=null,this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.logger=V(this.getLoggerName()),this._entityCache={frame:null,persistent:null,tracked:new Set,invalidate:function(){this.persistent=null},clearFrame:function(){this.frame=null},clearAll:function(){this.frame=null,this.persistent=null,this.tracked.clear()}}}var t=e.prototype;return t.setPerformanceMonitor=function(e){this._performanceMonitor=e},t.getPerformanceMonitor=function(){if(!this._performanceMonitor)throw new Error(this._systemName+": PerformanceMonitor未注入,请确保在Core.create()之后再添加System到Scene");return this._performanceMonitor},t.setUpdateOrder=function(e){this._updateOrder=e},t.initialize=function(){this._initialized||(this._initialized=!0,this.scene&&(this._entityCache.invalidate(),this.queryEntities()),this.onInitialize())},t.onInitialize=function(){},t.clearEntityCache=function(){this._entityCache.invalidate()},t.reset=function(){this.scene=null,this._initialized=!1,this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.destroy()},t.queryEntities=function(){var e;if(null===(e=this.scene)||void 0===e||!e.querySystem||!this._matcher)return[];var t=this._matcher.getCondition(),n=this.scene.querySystem,r=[];return r=this._matcher.isEmpty()?n.getAllEntities():this.isSingleCondition(t)?this.executeSingleConditionQuery(t,n):this.executeComplexQuery(t,n),this.updateEntityTracking(r),r},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 r=t.queryByTag(e.tag);n=this.extractEntityIds(r.entities)}if(void 0!==e.name){var i=this.extractEntityIds(t.queryByName(e.name).entities);n=n?this.intersectIdSets(n,i):i}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,r=0;r<t;r=r+1|0)n.add(0|e[r].id);return n},t.intersectIdSets=function(e,t){var n,r;e.size<=t.size?(n=e,r=t):(n=t,r=e);for(var i,o=new Set,a=s(n);!(i=a()).done;){var c=i.value;r.has(c)&&o.add(c)}return o},t.differenceIdSets=function(e,t){for(var n,r=new Set,i=s(e);!(n=i()).done;){var o=n.value;t.has(o)||r.add(o)}return r},t.getEntityIdMap=function(e){var t,n,r=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===r?this._entityIdMap:this.rebuildEntityIdMap(e,r)},t.rebuildEntityIdMap=function(e,t){var n=this._entityIdMap;n?n.clear():n=new Map;for(var r=e.length,i=0;i<r;i=i+1|0){var o=e[i];n.set(0|o.id,o)}return this._entityIdMap=n,this._entityIdMapVersion=t,this._entityIdMapSize=r,n},t.idSetToEntityArray=function(e,t){for(var n,r=this.getEntityIdMap(t),i=e.size,o=new Array(i),a=0,c=s(e);!(n=c()).done;){var u=n.value,h=r.get(u);void 0!==h&&(o[a]=h,a=a+1|0)}return a<i&&(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.getPerformanceMonitor(),t=e.startMonitoring(this._systemName),n=0;try{this.onBegin(),this._entityCache.frame=this.queryEntities(),n=this._entityCache.frame.length,this.process(this._entityCache.frame)}finally{e.endMonitoring(this._systemName,t,n)}}},t.lateUpdate=function(){if(this._enabled&&this.onCheckProcessing()){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName+"_Late"),n=0;try{var r=this._entityCache.frame||[];n=r.length,this.lateProcess(r),this.onEnd()}finally{e.endMonitoring(this._systemName+"_Late",t,n),this._entityCache.clearFrame()}}},t.onBegin=function(){},t.process=function(e){},t.lateProcess=function(e){},t.onEnd=function(){},t.onCheckProcessing=function(){return!0},t.getPerformanceData=function(){return this.getPerformanceMonitor().getSystemData(this._systemName)},t.getPerformanceStats=function(){return this.getPerformanceMonitor().getSystemStats(this._systemName)},t.resetPerformanceData=function(){this.getPerformanceMonitor().resetSystem(this._systemName)},t.toString=function(){var e=this.entities.length,t=this.getPerformanceData(),n=t?" ("+t.executionTime.toFixed(2)+"ms)":"";return this._systemName+"["+e+" entities]"+n},t.updateEntityTracking=function(e){for(var t,n=new Set(e),r=!1,i=s(e);!(t=i()).done;){var o=t.value;this._entityCache.tracked.has(o)||(this._entityCache.tracked.add(o),this.onAdded(o),r=!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),r=!0)}r&&this._entityCache.invalidate()},t.onAdded=function(e){},t.onRemoved=function(e){},t.dispose=function(){this.cleanupManualEventListeners(),this._entityCache.clearAll(),this._entityIdMap=null,this._initialized=!1,this._scene=null,this.logger.debug("System "+this._systemName+" disposed")},t.addEventListener=function(e,t,n){var r;if(null!==(r=this.scene)&&void 0!==r&&r.eventSystem){var i=this.scene.eventSystem.on(e,t,n);i&&this._eventListeners.push({eventSystem:this.scene.eventSystem,eventType:e,handler:t,listenerRef:i})}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 r=this._eventListeners[n];r.eventSystem.off(e,r.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(){},t.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" in "+this.systemName);return n},t.getComponents=function(e){for(var t=this,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r.map((function(n){return t.requireComponent(e,n)}))},t.forEach=function(e,t){for(var n=0;n<e.length;n++)t(e[n],n)},t.filterEntities=function(e,t){return Array.from(e).filter(t)},t.mapEntities=function(e,t){return Array.from(e).map(t)},t.findEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return e[n]},t.someEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1},t.everyEntity=function(e,t){for(var n=0;n<e.length;n++)if(!t(e[n],n))return!1;return!0},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}}])}(),Ae=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 r=t.value;if(r instanceof e)return r}return null},t.begin=function(){this.sortProcessors()},t.end=function(){for(var t,n=s(this._processors);!(t=n()).done;){var r=t.value;try{r.reset()}catch(t){e._logger.error("Error in processor "+U(r)+":",t)}}this._isDirty=!1,this._processors.length=0},t.update=function(){this.sortProcessors();for(var t,n=s(this._processors);!(t=n()).done;){var r=t.value;try{r.update()}catch(t){e._logger.error("Error in processor "+U(r)+":",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}}])}();Ae._logger=V("EntityProcessorList");var Te=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 r=this._dense[n];this._dense[t]=r,this._sparse.set(r,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,r=s(this._sparse);!(n=r()).done;){var i=n.value,o=i[0],a=i[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}}])}(),xe=function(e){function t(){return e.call(this)||this}return u(t,e),t.prototype.reset=function(){this.clear()},t}(y(Set)),Me=function(){function e(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new Te}var t=e.prototype;return t.addEntity=function(e){this._entities.has(e)&&this.removeEntity(e);for(var t,n=O.clone(O.ZERO),r=new Set,i=s(e.components);!(t=i()).done;){var o=t.value.constructor;r.add(o),ye.isRegistered(o)||ye.register(o);var a=ye.getBitMask(o);O.orInPlace(n,a)}this._entities.add(e);for(var c=this._entities.getIndex(e);this._componentMasks.length<=c;)this._componentMasks.push(O.clone(O.ZERO));this._componentMasks[c]=n,this.updateComponentMappings(e,r,!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 r=this._componentMasks.length-1;t!==r&&(this._componentMasks[t]=this._componentMasks[r]),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 r,i=O.clone(O.ZERO),o=s(t);!(r=o()).done;){var a=r.value;if(!ye.isRegistered(a))return new Set;var c=ye.getBitMask(a);O.orInPlace(i,c)}var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var r=n._componentMasks[t];O.hasAll(r,i)&&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 r,i=O.clone(O.ZERO),o=s(t);!(r=o()).done;){var a=r.value;if(ye.isRegistered(a)){var c=ye.getBitMask(a);O.orInPlace(i,c)}}if(O.equals(i,O.ZERO))return new Set;var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var r=n._componentMasks[t];O.hasAny(r,i)&&u.add(e)})),u},t.hasComponent=function(e,t){var n=this._entities.getIndex(e);if(void 0===n)return!1;if(!ye.isRegistered(t))return!1;var r=this._componentMasks[n],i=ye.getBitMask(t);return O.hasAny(r,i)},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,r){e(n,t._componentMasks[r],r)}))},t.clear=function(){this._entities.clear(),this._componentMasks.length=0;for(var t,n=s(this._componentToEntities.values());!(t=n()).done;){var r=t.value;e._entitySetPool.release(r)}this._componentToEntities.clear()},t.getMemoryStats=function(){for(var e,t=this._entities.getMemoryStats(),n=16*this._componentMasks.length,r=16*this._componentToEntities.size,i=s(this._componentToEntities.values());!(e=i()).done;){r+=8*e.value.size}return{entitiesMemory:t.totalMemory,masksMemory:n,mappingsMemory:r,totalMemory:t.totalMemory+n+r}},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 r,i=s(e.value);!(r=i()).done;){var o=r.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,r=s(e.components);!(t=r()).done;){var i=t.value;n.add(i.constructor)}return n},t.updateComponentMappings=function(t,n,r){for(var i,o=s(n);!(i=o()).done;){var a=i.value,c=this._componentToEntities.get(a);r?(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}}])}();Me._entitySetPool=I.getPool(xe,50,512);var Ie,ke=function(){function e(){this.buckets=new Map,this._size=0}var t=e.prototype;return t.murmur32=function(e,t){var n=t>>>0,r=function(e){e=(e=Math.imul(e,3432918353)>>>0)<<15|e>>>17,e=Math.imul(e,461845907)>>>0,n=(n^=e)<<13|n>>>19,n=Math.imul(n,5)+3864292196>>>0};if(r(e.base[0]>>>0),r(e.base[1]>>>0),e.segments)for(var i,o=s(e.segments);!(i=o()).done;){var a=i.value;r(a[0]>>>0),r(a[1]>>>0)}return n^=e.segments?8*e.segments.length:8,n^=n>>>16,n=Math.imul(n,2246822507)>>>0,n^=n>>>13,n=Math.imul(n,3266489909)>>>0,(n^=n>>>16)>>>0},t.getHashes=function(e){return[this.murmur32(e,2538058380),this.murmur32(e,305419896)]},t.set=function(e,t){var n=this.getHashes(e),r=n[0],i=n[1],o=this.buckets.get(r);o||(o=[],this.buckets.set(r,o));for(var s=0;s<o.length;s++)if(o[s][0]===i)return o[s][1]=t,this;return o.push([i,t]),this._size++,this},t.get=function(e){var t=this.getHashes(e),n=t[0],r=t[1],i=this.buckets.get(n);if(i)for(var o=0;o<i.length;o++)if(i[o][0]===r)return i[o][1]},t.has=function(e){return void 0!==this.get(e)},t.delete=function(e){var t=this.getHashes(e),n=t[0],r=t[1],i=this.buckets.get(n);if(!i)return!1;for(var o=0;o<i.length;o++)if(i[o][0]===r)return i.splice(o,1),this._size--,0===i.length&&this.buckets.delete(n),!0;return!1},t.clear=function(){this.buckets.clear(),this._size=0},t.entries=l().m((function e(){var t,n,r,i,o,a,c,u;return l().w((function(e){for(;;)switch(e.n){case 0:t=s(this.buckets);case 1:if((n=t()).done){e.n=5;break}(r=n.value)[0],i=r[1],o=s(i);case 2:if((a=o()).done){e.n=4;break}return(c=a.value)[0],u=c[1],e.n=3,[void 0,u];case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}}),e,this)})),t.values=l().m((function e(){var t,n,r,i,o,a,c;return l().w((function(e){for(;;)switch(e.n){case 0:t=s(this.buckets.values());case 1:if((n=t()).done){e.n=5;break}r=n.value,i=s(r);case 2:if((o=i()).done){e.n=4;break}return(a=o.value)[0],c=a[1],e.n=3,c;case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}}),e,this)})),o(e,[{key:"size",get:function(){return this._size}},{key:"innerBuckets",get:function(){return this.buckets}}])}(),De=function(){function e(){this._archetypes=new ke,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._entityComponentTypesCache=new Map,this._allArchetypes=[]}var t=e.prototype;return t.addEntity=function(e){var t=this.getEntityComponentTypes(e),n=this.generateArchetypeId(t),r=this._archetypes.get(n);r||(r=this.createArchetype(t)),r.entities.add(e),this._entityToArchetype.set(e,r)},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),r=this.generateArchetypeId(n);if(!t||t.id!==r){t&&t.entities.delete(e);var i=this._archetypes.get(r);i||(i=this.createArchetype(n)),i.entities.add(e),this._entityToArchetype.set(e,i)}},t.queryArchetypes=function(e,t){void 0===t&&(t="AND");var n=[],r=0;if("AND"===t){if(0===e.length){for(var i,o=s(this._allArchetypes);!(i=o()).done;){var a=i.value;n.push(a),r+=a.entities.size}return{archetypes:n,totalEntities:r}}if(1===e.length){var c=this._componentToArchetypes.get(e[0]);if(c)for(var u,h=s(c);!(u=h()).done;){var l=u.value;n.push(l),r+=l.entities.size}return{archetypes:n,totalEntities:r}}for(var f,d,p=1/0,y=s(e);!(d=y()).done;){var m=d.value,v=this._componentToArchetypes.get(m);if(!v||0===v.size)return{archetypes:[],totalEntities:0};v.size<p&&(p=v.size,f=v)}var g=this.generateArchetypeId(e);if(f)for(var _,S=s(f);!(_=S()).done;){var E=_.value;O.hasAll(E.id,g)&&(n.push(E),r+=E.entities.size)}}else{for(var C,b=new Set,w=s(e);!(C=w()).done;){var A=C.value,T=this._componentToArchetypes.get(A);if(T)for(var x,M=s(T);!(x=M()).done;){var I=x.value;b.add(I)}}for(var k,D=s(b);!(k=D()).done;){var R=k.value;n.push(R),r+=R.entities.size}}return{archetypes:n,totalEntities:r}},t.getEntityArchetype=function(e){return this._entityToArchetype.get(e)},t.getAllArchetypes=function(){return this._allArchetypes.slice()},t.getEntitiesByComponent=function(e){var t=this._componentToArchetypes.get(e);if(!t||0===t.size)return[];for(var n,r=[],i=s(t);!(n=i()).done;)for(var o,a=s(n.value.entities);!(o=a()).done;){var c=o.value;r.push(c)}return r},t.clear=function(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._entityComponentTypesCache.clear(),this._allArchetypes=[]},t.updateAllArchetypeArrays=function(){this._allArchetypes=[];for(var e,t=s(this._archetypes.values());!(e=t()).done;){var n=e.value;this._allArchetypes.push(n)}},t.getEntityComponentTypes=function(e){var t=this._entityComponentTypesCache.get(e);return t||(t=e.components.map((function(e){return e.constructor})),this._entityComponentTypesCache.set(e,t)),t},t.generateArchetypeId=function(e){return re.instance.getEntityBits(e).getValue()},t.createArchetype=function(e){var t=this.generateArchetypeId(e),n={id:t,componentTypes:[].concat(e),entities:new Set};this._archetypes.set(t,n),this.updateAllArchetypeArrays();for(var r,i=s(e);!(r=i()).done;){var o=r.value,a=this._componentToArchetypes.get(o);a||(a=new Set,this._componentToArchetypes.set(o,a)),a.add(n)}return n},e}();!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(Ie||(Ie={}));var Oe,Re,Be=function(){function e(){this._logger=V("QuerySystem"),this.entities=[],this._version=0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.componentMaskCache=new Map,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.resultArrayPool=[],this.poolMaxSize=50,this.entityIndex={byTag:new Map,byName:new Map},this.archetypeSystem=new De}var t=e.prototype;return t.acquireResultArray=function(){return this.resultArrayPool.length>0?this.resultArrayPool.pop():[]},t.releaseResultArray=function(e){this.resultArrayPool.length<this.poolMaxSize&&(e.length=0,this.resultArrayPool.push(e))},t.setEntities=function(e){this.entities=e,this.clearQueryCache(),this.rebuildIndexes()},t.addEntity=function(e,t){void 0===t&&(t=!1),this.entities.includes(e)||(this.entities.push(e),this.addEntityToIndexes(e),this.archetypeSystem.addEntity(e),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}))),r=0,i=s(e);!(t=i()).done;){var o=t.value;n.has(o.id)||(this.entities.push(o),this.addEntityToIndexes(o),this.archetypeSystem.addEntity(o),n.add(o.id),r++)}r>0&&this.clearQueryCache()}},t.addEntitiesUnchecked=function(e){if(0!==e.length){for(var t,n=s(e);!(t=n()).done;){var r=t.value;this.entities.push(r)}for(var i,o=s(e);!(i=o()).done;){var a=i.value;this.addEntityToIndexes(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.archetypeSystem.removeEntity(e),this.clearQueryCache(),this._version++)},t.updateEntity=function(e){this.entities.includes(e)?(this.removeEntityFromIndexes(e),this.archetypeSystem.updateEntity(e),this.addEntityToIndexes(e),this.clearQueryCache(),this._version++):this.addEntity(e)},t.addEntityToIndexes=function(e){var t=e.tag;void 0!==t&&(this.entityIndex.byTag.get(t)||this.createAndSetTagIndex(t)).add(e);var n=e.name;n&&(this.entityIndex.byName.get(n)||this.createAndSetNameIndex(n)).add(e)},t.createAndSetTagIndex=function(e){var t=new Set;return this.entityIndex.byTag.set(e,t),t},t.createAndSetNameIndex=function(e){var t=new Set;return this.entityIndex.byName.set(e,t),t},t.removeEntityFromIndexes=function(e){if(void 0!==e.tag){var t=this.entityIndex.byTag.get(e.tag);t&&(t.delete(e),0===t.size&&this.entityIndex.byTag.delete(e.tag))}if(e.name){var n=this.entityIndex.byName.get(e.name);n&&(n.delete(e),0===n.size&&this.entityIndex.byName.delete(e.name))}},t.rebuildIndexes=function(){this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear();for(var e,t=s(this.entities);!(e=t()).done;){var n=e.value;this.addEntityToIndexes(n),this.archetypeSystem.addEntity(n)}},t.queryAll=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var i=this.generateCacheKey("all",n),o=this.getFromCache(i);if(o)return this.queryStats.cacheHits++,{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.archetypeHits++;for(var a,c=[],u=s(this.archetypeSystem.queryArchetypes(n,"AND").archetypes);!(a=u()).done;)for(var h,l=s(a.value.entities);!(h=l()).done;){var f=h.value;c.push(f)}return this.addToCache(i,c),{entities:c,count:c.length,executionTime:performance.now()-e,fromCache:!1}},t.queryMultipleComponents=function(e){for(var t,n=[],r=s(this.archetypeSystem.queryArchetypes(e,"AND").archetypes);!(t=r()).done;)for(var i,o=s(t.value.entities);!(i=o()).done;){var a=i.value;n.push(a)}return n},t.queryAny=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var i=this.generateCacheKey("any",n),o=this.getFromCache(i);if(o)return this.queryStats.cacheHits++,{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.archetypeHits++;for(var a,c=this.archetypeSystem.queryArchetypes(n,"OR"),u=this.acquireResultArray(),h=s(c.archetypes);!(a=h()).done;)for(var l,f=s(a.value.entities);!(l=f()).done;){var d=l.value;u.push(d)}var p=[].concat(u);return this.releaseResultArray(u),this.addToCache(i,p),{entities:p,count:p.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),r=0;r<t;r++)n[r]=arguments[r];var i=this.generateCacheKey("none",n),o=this.getFromCache(i);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 O.hasNone(e.componentMask,s)}));return this.addToCache(i,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,r=this.getFromCache(n);if(r)return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var i=Array.from(this.entityIndex.byTag.get(e)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByName=function(e){var t=performance.now();this.queryStats.totalQueries++;var n="name:"+e,r=this.getFromCache(n);if(r)return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var i=Array.from(this.entityIndex.byName.get(e)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByComponent=function(e){var t=performance.now();this.queryStats.totalQueries++;var n=this.generateCacheKey("component",[e]),r=this.getFromCache(n);if(r)return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var i=this.archetypeSystem.getEntitiesByComponent(e);return this.addToCache(n,i),{entities:i,count:i.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 r=e.value,i=r[0];t-r[1].timestamp>this.cacheTimeout&&this.queryCache.delete(i)}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,f=l[0],d=l[1];(d.hitCount<a||d.hitCount===a&&d.timestamp<u)&&(a=d.hitCount,c=f,u=d.timestamp)}c&&this.queryCache.delete(c)}},t.clearQueryCache=function(){this.queryCache.clear(),this.componentMaskCache.clear()},t.generateCacheKey=function(e,t){return 1===t.length?e+":"+W(t[0]):e+":"+t.map((function(e){return W(e)})).sort().join(",")},t.clearCache=function(){this.clearQueryCache()},t.createComponentMask=function(e){var t=e.map((function(e){return W(e)})).sort().join(","),n=this.componentMaskCache.get(t);if(n)return n;var r=re.instance.getEntityBits(e);return this.componentMaskCache.set(t,r.getValue()),r.getValue()},t.getAllEntities=function(){return this.entities},t.getStats=function(){return{entityCount:this.entities.length,indexStats:{componentIndexSize:this.archetypeSystem.getAllArchetypes().length,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},queryStats:a({},this.queryStats,{cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}),optimizationStats:{archetypeSystem:this.archetypeSystem.getAllArchetypes().map((function(e){return{id:e.id,componentTypes:e.componentTypes.map((function(e){return W(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=V("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:Ie.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:Ie.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:Ie.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this},t.execute=function(){var e,t,n,r=performance.now();if(1===this.conditions.length){var i=this.conditions[0];switch(i.type){case Ie.ALL:return(e=this.querySystem).queryAll.apply(e,i.componentTypes);case Ie.ANY:return(t=this.querySystem).queryAny.apply(t,i.componentTypes);case Ie.NONE:return(n=this.querySystem).queryNone.apply(n,i.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-r,fromCache:!1}},t.createComponentMask=function(e){for(var t,n=O.clone(O.ZERO),r=s(e);!(t=r()).done;){var i=t.value;try{var o=ye.getBitMask(i);O.orInPlace(n,o)}catch(e){this._logger.warn("组件类型 "+W(i)+" 未注册,跳过")}}return n},t.reset=function(){return this.conditions=[],this},e}(),ze=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 r=n.findIndex((function(e){return e.id===t}));return-1!==r&&(n.splice(r,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 r;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==(r=this.batchConfigs.get(t))||!r.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 r=this.listeners.get(t);if(r&&0!==r.length){for(var i,o=performance.now(),a=[],c=s(this.sortListenersByPriority(r));!(i=c()).done;){var u=i.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,r){var i=this.listeners.get(t);if(i||(i=[],this.listeners.set(t,i)),i.length>=this.maxListeners)return e._logger.warn("事件类型 "+t+" 的监听器数量超过最大限制 ("+this.maxListeners+")"),"";var o="listener_"+this.nextListenerId++,s={handler:n,config:a({priority:0},r),id:o};return i.push(s),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),o},t.executeEvent=function(){var t=n(l().m((function t(r,i){var o,a,c,u,h,f,d,p,y,m;return l().w((function(t){for(;;)switch(t.n){case 0:if((o=this.listeners.get(r))&&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})),f=u.filter((function(e){return e.config.async})),d=s(h);!(p=d()).done;){y=p.value;try{y.config.context?y.handler.call(y.config.context,i):y.handler(i),y.config.once&&c.push(y.id)}catch(t){e._logger.error("同步事件处理器执行错误 "+r+":",t)}}return m=f.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,i);case 1:t.n=3;break;case 2:return t.n=3,n.handler(i);case 3:n.config.once&&c.push(n.id),t.n=5;break;case 4:t.p=4,o=t.v,e._logger.error("异步事件处理器执行错误 "+r+":",o);case 5:return t.a(2)}}),t,null,[[0,4]])})));return function(e){return t.apply(this,arguments)}}()),t.n=2,Promise.all(m);case 2:this.removeListeners(r,c),this.updateStats(r,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 r,i=function(){var e=r.value,t=n.findIndex((function(t){return t.id===e}));-1!==t&&n.splice(t,1)},o=s(t);!(r=o()).done;)i();0===n.length&&(this.listeners.delete(e),this.stats.delete(e))}}},t.addToBatch=function(e,t){var n=this,r=this.batchQueue.get(e);r||(r=[],this.batchQueue.set(e,r)),r.push(t);var i=this.batchConfigs.get(e);if(r.length>=i.batchSize)this.flushBatch(e);else if(!this.batchTimers.has(e)){var o=setTimeout((function(){n.flushBatch(e)}),i.delay);this.batchTimers.set(e,o)}},t.processBatch=function(){var e=n(l().m((function e(t,n){var r;return l().w((function(e){for(;;)switch(e.n){case 0:return r={type:t,events:n,count:n.length,timestamp:Date.now()},e.n=1,this.executeEvent(t+":batch",r);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}();ze._logger=V("EventSystem"),exports.ECSEventType=void 0,(Oe=exports.ECSEventType||(exports.ECSEventType={})).ENTITY_CREATED="entity:created",Oe.ENTITY_DESTROYED="entity:destroyed",Oe.ENTITY_ENABLED="entity:enabled",Oe.ENTITY_DISABLED="entity:disabled",Oe.ENTITY_TAG_ADDED="entity:tag:added",Oe.ENTITY_TAG_REMOVED="entity:tag:removed",Oe.ENTITY_NAME_CHANGED="entity:name:changed",Oe.COMPONENT_ADDED="component:added",Oe.COMPONENT_REMOVED="component:removed",Oe.COMPONENT_MODIFIED="component:modified",Oe.COMPONENT_ENABLED="component:enabled",Oe.COMPONENT_DISABLED="component:disabled",Oe.SYSTEM_ADDED="system:added",Oe.SYSTEM_REMOVED="system:removed",Oe.SYSTEM_ENABLED="system:enabled",Oe.SYSTEM_DISABLED="system:disabled",Oe.SYSTEM_PROCESSING_START="system:processing:start",Oe.SYSTEM_PROCESSING_END="system:processing:end",Oe.SYSTEM_ERROR="system:error",Oe.SCENE_CREATED="scene:created",Oe.SCENE_DESTROYED="scene:destroyed",Oe.SCENE_ACTIVATED="scene:activated",Oe.SCENE_DEACTIVATED="scene:deactivated",Oe.SCENE_PAUSED="scene:paused",Oe.SCENE_RESUMED="scene:resumed",Oe.QUERY_EXECUTED="query:executed",Oe.QUERY_CACHE_HIT="query:cache:hit",Oe.QUERY_CACHE_MISS="query:cache:miss",Oe.QUERY_OPTIMIZED="query:optimized",Oe.PERFORMANCE_WARNING="performance:warning",Oe.PERFORMANCE_CRITICAL="performance:critical",Oe.MEMORY_USAGE_HIGH="memory:usage:high",Oe.FRAME_RATE_DROP="frame:rate:drop",Oe.INDEX_CREATED="index:created",Oe.INDEX_UPDATED="index:updated",Oe.INDEX_OPTIMIZED="index:optimized",Oe.ARCHETYPE_CREATED="archetype:created",Oe.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",Oe.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",Oe.DIRTY_MARK_ADDED="dirty:mark:added",Oe.DIRTY_BATCH_PROCESSED="dirty:batch:processed",Oe.ERROR_OCCURRED="error:occurred",Oe.WARNING_ISSUED="warning:issued",Oe.FRAMEWORK_INITIALIZED="framework:initialized",Oe.FRAMEWORK_SHUTDOWN="framework:shutdown",Oe.DEBUG_INFO="debug:info",Oe.DEBUG_STATS_UPDATED="debug:stats:updated",exports.EventPriority=void 0,(Re=exports.EventPriority||(exports.EventPriority={}))[Re.LOWEST=0]="LOWEST",Re[Re.LOW=25]="LOW",Re[Re.NORMAL=50]="NORMAL",Re[Re.HIGH=75]="HIGH",Re[Re.HIGHEST=100]="HIGHEST",Re[Re.CRITICAL=200]="CRITICAL";var Ne={ENTITY:{CREATED:exports.ECSEventType.ENTITY_CREATED,DESTROYED:exports.ECSEventType.ENTITY_DESTROYED,ENABLED:exports.ECSEventType.ENTITY_ENABLED,DISABLED:exports.ECSEventType.ENTITY_DISABLED,TAG_ADDED:exports.ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:exports.ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:exports.ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:exports.ECSEventType.COMPONENT_ADDED,REMOVED:exports.ECSEventType.COMPONENT_REMOVED,MODIFIED:exports.ECSEventType.COMPONENT_MODIFIED,ENABLED:exports.ECSEventType.COMPONENT_ENABLED,DISABLED:exports.ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:exports.ECSEventType.SYSTEM_ADDED,REMOVED:exports.ECSEventType.SYSTEM_REMOVED,ENABLED:exports.ECSEventType.SYSTEM_ENABLED,DISABLED:exports.ECSEventType.SYSTEM_DISABLED,PROCESSING_START:exports.ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:exports.ECSEventType.SYSTEM_PROCESSING_END,ERROR:exports.ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:exports.ECSEventType.PERFORMANCE_WARNING,CRITICAL:exports.ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:exports.ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:exports.ECSEventType.FRAME_RATE_DROP}},We=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}();We.validTypes=new Set([].concat(Object.values(exports.ECSEventType),Object.values(Ne.ENTITY),Object.values(Ne.COMPONENT),Object.values(Ne.SYSTEM),Object.values(Ne.PERFORMANCE)));var Le=function(){function e(e){void 0===e&&(e=!1),this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new ze,this.isDebugMode=e}var t=e.prototype;return t.emit=function(t,n,r){void 0===r&&(r=!1),this.validateEventType(t);var i=r?this.enhanceEventData(t,n):n;this.isDebugMode&&e._logger.info("发射事件: "+t,i),this.eventSystem.emitSync(t,i)},t.emitAsync=function(){var t=n(l().m((function t(n,r,i){var o;return l().w((function(t){for(;;)switch(t.n){case 0:return void 0===i&&(i=!1),this.validateEventType(n),o=i?this.enhanceEventData(n,r):r,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,r){return t.apply(this,arguments)}}(),t.on=function(t,n,r){void 0===r&&(r={}),this.validateEventType(t);var i={once:r.once||!1,priority:r.priority||exports.EventPriority.NORMAL,async:r.async||!1,context:r.context};return this.isDebugMode&&e._logger.info("添加监听器: "+t,i),this.eventSystem.on(t,n,i)},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 r=new Map;return n.forEach((function(e,n){r.set(n,t.convertEventStats(e))})),r}return this.convertEventStats(n)},t.clear=function(){this.isDebugMode&&e._logger.info("清空所有监听器"),this.eventSystem.clear()},t.setEnabled=function(e){this.eventSystem.setEnabled(e)},t.setDebugMode=function(e){this.isDebugMode=e},t.setMaxListeners=function(e){this.eventSystem.setMaxListeners(e)},t.getListenerCount=function(e){return this.eventSystem.getListenerCount(e)},t.setBatchConfig=function(e,t,n){this.eventSystem.setBatchConfig(e,{batchSize:t,delay:n,enabled:!0})},t.flushBatch=function(e){this.eventSystem.flushBatch(e)},t.resetStats=function(e){this.eventSystem.resetStats(e)},t.emitEntityCreated=function(e){this.emit(exports.ECSEventType.ENTITY_CREATED,e)},t.emitEntityDestroyed=function(e){this.emit(exports.ECSEventType.ENTITY_DESTROYED,e)},t.emitComponentAdded=function(e){this.emit(exports.ECSEventType.COMPONENT_ADDED,e)},t.emitComponentRemoved=function(e){this.emit(exports.ECSEventType.COMPONENT_REMOVED,e)},t.emitSystemAdded=function(e){this.emit(exports.ECSEventType.SYSTEM_ADDED,e)},t.emitSystemRemoved=function(e){this.emit(exports.ECSEventType.SYSTEM_REMOVED,e)},t.emitSceneChanged=function(e){this.emit(exports.ECSEventType.SCENE_ACTIVATED,e)},t.emitPerformanceWarning=function(e){this.emit(exports.ECSEventType.PERFORMANCE_WARNING,e)},t.onEntityCreated=function(e,t){return this.on(exports.ECSEventType.ENTITY_CREATED,e,t)},t.onComponentAdded=function(e,t){return this.on(exports.ECSEventType.COMPONENT_ADDED,e,t)},t.onSystemError=function(e,t){return this.on(exports.ECSEventType.SYSTEM_ERROR,e,t)},t.onPerformanceWarning=function(e,t){return this.on(exports.ECSEventType.PERFORMANCE_WARNING,e,t)},t.validateEventType=function(t){this.isDebugMode&&(We.isValid(t)||(e._logger.warn("未知事件类型: "+t),We.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}();Le._logger=V("EventBus");var Fe=function(){function e(){}return e.getInstance=function(e){return void 0===e&&(e=!1),this.instance||(this.instance=new Le(e)),this.instance},e.reset=function(e){return void 0===e&&(e=!1),this.instance&&this.instance.clear(),this.instance=new Le(e),this.instance},e}(),Ue=function(){function e(e,t){this._entities=e,this._componentTypes=t}var t=e.prototype;return t.forEach=function(e){this._entities.forEach(e)},t.map=function(e){return this._entities.map(e)},t.filter=function(t){return new e(this._entities.filter(t),this._componentTypes)},t.find=function(e){return this._entities.find(e)},t.some=function(e){return this._entities.some(e)},t.every=function(e){return this._entities.every(e)},t.get=function(e){return this._entities[e]},t.toArray=function(){return[].concat(this._entities)},t.getComponentTypes=function(){return this._componentTypes},t[Symbol.iterator]=function(){return this._entities[Symbol.iterator]()},o(e,[{key:"entities",get:function(){return this._entities}},{key:"length",get:function(){return this._entities.length}},{key:"first",get:function(){return this._entities[0]}},{key:"last",get:function(){return this._entities[this._entities.length-1]}},{key:"isEmpty",get:function(){return 0===this._entities.length}}])}(),He=function(){function e(e,t,n,r,i){this._all=e||[],this._any=t||[],this._none=n||[],this._tag=r,this._name=i}var t=e.prototype;return t.withAll=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return new e([].concat(this._all,n),this._any,this._none,this._tag,this._name)},t.withAny=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return new e(this._all,[].concat(this._any,n),this._none,this._tag,this._name)},t.withNone=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return new e(this._all,this._any,[].concat(this._none,n),this._tag,this._name)},t.withTag=function(t){return new e(this._all,this._any,this._none,t,this._name)},t.withName=function(t){return new e(this._all,this._any,this._none,this._tag,t)},t.buildMatcher=function(){var e,t,n,r=be.complex();this._all.length>0&&(r=(e=r).all.apply(e,this._all));this._any.length>0&&(r=(t=r).any.apply(t,this._any));this._none.length>0&&(r=(n=r).none.apply(n,this._none));return void 0!==this._tag&&(r=r.withTag(this._tag)),void 0!==this._name&&(r=r.withName(this._name)),r},t.getCondition=function(){return{all:[].concat(this._all),any:[].concat(this._any),none:[].concat(this._none),tag:this._tag,name:this._name}},t.getRequiredTypes=function(){return this._all},t.clone=function(){return new e([].concat(this._all),[].concat(this._any),[].concat(this._none),this._tag,this._name)},e}();var je=Symbol("SerializableMetadata"),qe=Symbol("SerializeField"),Ge=Symbol("SerializeOptions");function Ve(e){return function(t,n){var r=t.constructor,i=r[je];i||(i={options:{version:1},fields:new Map,ignoredFields:new Set},r[je]=i),i.fields.set(n,e||{})}}function Ye(e){return e&&("function"==typeof e?e:e.constructor)[je]||null}var Qe,Je,Ze,Xe,Ke=function(){function e(){}return e.serialize=function(e){var t=Ye(e);if(!t)return null;for(var n,r=e.constructor,i=t.options.typeId||W(r),o={},a=s(t.fields);!(n=a()).done;){var c=n.value,u=c[0],h=c[1],l="symbol"==typeof u?u.toString():u,f=e[u];if(!t.ignoredFields.has(u)){var d=h.serializer?h.serializer(f):this.serializeValue(f);o[h.alias||l]=d}}return{type:i,version:t.options.version,data:o}},e.deserialize=function(e,t){var n=t.get(e.type);if(!n)return console.warn("未找到组件类型: "+e.type),null;var r=Ye(n);if(!r)return console.warn("组件 "+e.type+" 不可序列化"),null;for(var i,o=new n,a=s(r.fields);!(i=a()).done;){var c=i.value,u=c[0],h=c[1],l="symbol"==typeof u?u.toString():u,f=h.alias||l,d=e.data[f];if(void 0!==d){var p=h.deserializer?h.deserializer(d):this.deserializeValue(d);o[u]=p}}return o},e.serializeComponents=function(e){for(var t,n=[],r=s(e);!(t=r()).done;){var i=t.value,o=this.serialize(i);o&&n.push(o)}return n},e.deserializeComponents=function(e,t){for(var n,r=[],i=s(e);!(n=i()).done;){var o=n.value,a=this.deserialize(o,t);a&&r.push(a)}return r},e.serializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(Array.isArray(e))return e.map((function(e){return t.serializeValue(e)}));if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if("object"===n){var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=this.serializeValue(e[i]));return r}},e.deserializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if("object"===n&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((function(e){return t.deserializeValue(e)}));if("object"===n){var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=this.deserializeValue(e[i]));return r}return e},e.validateVersion=function(e,t){return e.version===t},e.getSerializationInfo=function(e){var t=Ye(e);if(!t)return{type:"unknown",version:0,fields:[],ignoredFields:[],isSerializable:!1};var n="function"==typeof e?e:e.constructor;return{type:t.options.typeId||W(n),version:t.options.version,fields:Array.from(t.fields.keys()).map((function(e){return"symbol"==typeof e?e.toString():e})),ignoredFields:Array.from(t.ignoredFields).map((function(e){return"symbol"==typeof e?e.toString():e})),isSerializable:!0}},e}(),$e=function(){function e(){}return e.serialize=function(e,t){void 0===t&&(t=!0);var n=Ke.serializeComponents(Array.from(e.components)),r={id:e.id,name:e.name,tag:e.tag,active:e.active,enabled:e.enabled,updateOrder:e.updateOrder,components:n,children:[]};if(e.parent&&(r.parentId=e.parent.id),t)for(var i,o=s(e.children);!(i=o()).done;){var a=i.value;r.children.push(this.serialize(a,!0))}return r},e.deserialize=function(e,t,n,r,i){void 0===r&&(r=!1);var o=r?e.id:n(),a=new _e(e.name,o);i&&(a.scene=i),a.tag=e.tag,a.active=e.active,a.enabled=e.enabled,a.updateOrder=e.updateOrder;for(var c,u=s(Ke.deserializeComponents(e.components,t));!(c=u()).done;){var h=c.value;a.addComponent(h)}for(var l,f=s(e.children);!(l=f()).done;){var d=l.value,p=this.deserialize(d,t,n,r,i);a.addChild(p)}return a},e.serializeEntities=function(e,t){void 0===t&&(t=!0);for(var n,r=[],i=s(e);!(n=i()).done;){var o=n.value;o.parent&&t||r.push(this.serialize(o,t))}return r},e.deserializeEntities=function(e,t,n,r,i){void 0===r&&(r=!1);for(var o,a=[],c=s(e);!(o=c()).done;){var u=o.value,h=this.deserialize(u,t,n,r,i);a.push(h)}return a},e.clone=function(e,t,n){var r=this.serialize(e,!0);return this.deserialize(r,t,n,!1)},e}(),et={},tt={},nt={},rt={},it={},ot={};function st(){if(Je)return Qe;function e(e){return e&&e.isBuffer&&e}return Je=1,Qe=e("undefined"!=typeof Buffer&&Buffer)||e(Qe.Buffer)||e("undefined"!=typeof window&&window.Buffer)||Qe.Buffer}function at(){if(Xe)return Ze;Xe=1;var e={}.toString;return Ze=Array.isArray||function(t){return"[object Array]"==e.call(t)}}var ct,ut={exports:{}};function ht(){if(ct)return ut.exports;ct=1;var e=At(),t=ut.exports=n(0);function n(e){return new Array(e)}return t.alloc=n,t.concat=e.concat,t.from=function(n){if(!e.isBuffer(n)&&e.isView(n))n=e.Uint8Array.from(n);else if(e.isArrayBuffer(n))n=new Uint8Array(n);else{if("string"==typeof n)return e.from.call(t,n);if("number"==typeof n)throw new TypeError('"value" argument must not be a number')}return Array.prototype.slice.call(n)},ut.exports}var lt,ft={exports:{}};function dt(){if(lt)return ft.exports;lt=1;var e=At(),t=e.global,n=ft.exports=e.hasBuffer?r(0):[];function r(e){return new t(e)}return n.alloc=e.hasBuffer&&t.alloc||r,n.concat=e.concat,n.from=function(r){if(!e.isBuffer(r)&&e.isView(r))r=e.Uint8Array.from(r);else if(e.isArrayBuffer(r))r=new Uint8Array(r);else{if("string"==typeof r)return e.from.call(n,r);if("number"==typeof r)throw new TypeError('"value" argument must not be a number')}return t.from&&1!==t.from.length?t.from(r):new t(r)},ft.exports}var pt,yt={exports:{}};function mt(){if(pt)return yt.exports;pt=1;var e=At(),t=yt.exports=e.hasArrayBuffer?n(0):[];function n(e){return new Uint8Array(e)}return t.alloc=n,t.concat=e.concat,t.from=function(n){if(e.isView(n)){var r=n.byteOffset,i=n.byteLength;(n=n.buffer).byteLength!==i&&(n.slice?n=n.slice(r,r+i):(n=new Uint8Array(n)).byteLength!==i&&(n=Array.prototype.slice.call(n,r,r+i)))}else{if("string"==typeof n)return e.from.call(t,n);if("number"==typeof n)throw new TypeError('"value" argument must not be a number')}return new Uint8Array(n)},yt.exports}var vt,gt,_t,St,Et={},Ct={};function bt(){if(vt)return Ct;return vt=1,Ct.copy=function(e,t,n,r){var i;n||(n=0);r||0===r||(r=this.length);t||(t=0);var o=r-n;if(e===this&&n<t&&t<r)for(i=o-1;i>=0;i--)e[i+t]=this[i+n];else for(i=0;i<o;i++)e[i+t]=this[i+n];return o},Ct.toString=function(e,t,n){var r=this,i=0|t;n||(n=r.length);var o="",s=0;for(;i<n;)(s=r[i++])<128?o+=String.fromCharCode(s):(192==(224&s)?s=(31&s)<<6|63&r[i++]:224==(240&s)?s=(15&s)<<12|(63&r[i++])<<6|63&r[i++]:240==(248&s)&&(s=(7&s)<<18|(63&r[i++])<<12|(63&r[i++])<<6|63&r[i++]),s>=65536?(s-=65536,o+=String.fromCharCode((s>>>10)+55296,56320+(1023&s))):o+=String.fromCharCode(s));return o},Ct.write=function(e,t){var n=this,r=t||(t|=0),i=e.length,o=0,s=0;for(;s<i;)(o=e.charCodeAt(s++))<128?n[r++]=o:o<2048?(n[r++]=192|o>>>6,n[r++]=128|63&o):o<55296||o>57343?(n[r++]=224|o>>>12,n[r++]=128|o>>>6&63,n[r++]=128|63&o):(o=65536+(o-55296<<10|e.charCodeAt(s++)-56320),n[r++]=240|o>>>18,n[r++]=128|o>>>12&63,n[r++]=128|o>>>6&63,n[r++]=128|63&o);return r-t},Ct}function wt(){if(gt)return Et;gt=1;var e,t=bt();Et.copy=s,Et.slice=a,Et.toString=function(e,r,o){return(!i&&n.isBuffer(this)?this.toString:t.toString).apply(this,arguments)},Et.write=(e="write",function(){return(this[e]||t[e]).apply(this,arguments)});var n=At(),r=n.global,i=n.hasBuffer&&"TYPED_ARRAY_SUPPORT"in r,o=i&&!r.TYPED_ARRAY_SUPPORT;function s(e,r,i,s){var c=n.isBuffer(this),u=n.isBuffer(e);if(c&&u)return this.copy(e,r,i,s);if(o||c||u||!n.isView(this)||!n.isView(e))return t.copy.call(this,e,r,i,s);var h=i||null!=s?a.call(this,i,s):this;return e.set(h,r),h.length}function a(e,t){var r=this.slice||!o&&this.subarray;if(r)return r.call(this,e,t);var i=n.alloc.call(this,t-e);return s.call(this,i,0,e,t),i}return Et}function At(){return _t||(_t=1,function(e){var t=e.global=st(),n=e.hasBuffer=t&&!!t.isBuffer,r=e.hasArrayBuffer="undefined"!=typeof ArrayBuffer,i=e.isArray=at();e.isArrayBuffer=r?function(e){return e instanceof ArrayBuffer||f(e)}:y;var o=e.isBuffer=n?t.isBuffer:y,s=e.isView=r?ArrayBuffer.isView||m("ArrayBuffer","buffer"):y;e.alloc=l,e.concat=function(t,n){n||(n=0,Array.prototype.forEach.call(t,(function(e){n+=e.length})));var r=this!==e&&this||t[0],i=l.call(r,n),o=0;return Array.prototype.forEach.call(t,(function(e){o+=h.copy.call(e,i,o)})),i},e.from=function(e){return"string"==typeof e?d.call(this,e):p(this).from(e)};var a=e.Array=ht(),c=e.Buffer=dt(),u=e.Uint8Array=mt(),h=e.prototype=wt();function l(e){return p(this).alloc(e)}var f=m("ArrayBuffer");function d(e){var t=3*e.length,n=l.call(this,t),r=h.write.call(n,e);return t!==r&&(n=h.slice.call(n,0,r)),n}function p(e){return o(e)?c:s(e)?u:i(e)?a:n?c:r?u:a}function y(){return!1}function m(e,t){return e="[object "+e+"]",function(n){return null!=n&&{}.toString.call(t?n[t]:n)===e}}}(ot)),ot}function Tt(){if(St)return it;St=1,it.ExtBuffer=function t(n,r){if(!(this instanceof t))return new t(n,r);this.buffer=e.from(n),this.type=r};var e=At();return it}var xt,Mt={};function It(){if(xt)return Mt;xt=1,Mt.setExtPackers=function(e){e.addExtPacker(14,Error,[c,o]),e.addExtPacker(1,EvalError,[c,o]),e.addExtPacker(2,RangeError,[c,o]),e.addExtPacker(3,ReferenceError,[c,o]),e.addExtPacker(4,SyntaxError,[c,o]),e.addExtPacker(5,TypeError,[c,o]),e.addExtPacker(6,URIError,[c,o]),e.addExtPacker(10,RegExp,[a,o]),e.addExtPacker(11,Boolean,[s,o]),e.addExtPacker(12,String,[s,o]),e.addExtPacker(13,Date,[Number,o]),e.addExtPacker(15,Number,[s,o]),"undefined"!=typeof Uint8Array&&(e.addExtPacker(17,Int8Array,r),e.addExtPacker(18,Uint8Array,r),e.addExtPacker(19,Int16Array,r),e.addExtPacker(20,Uint16Array,r),e.addExtPacker(21,Int32Array,r),e.addExtPacker(22,Uint32Array,r),e.addExtPacker(23,Float32Array,r),"undefined"!=typeof Float64Array&&e.addExtPacker(24,Float64Array,r),"undefined"!=typeof Uint8ClampedArray&&e.addExtPacker(25,Uint8ClampedArray,r),e.addExtPacker(26,ArrayBuffer,r),e.addExtPacker(29,DataView,r));t.hasBuffer&&e.addExtPacker(27,n,t.from)};var e,t=At(),n=t.global,r=t.Uint8Array.from,i={name:1,message:1,stack:1,columnNumber:1,fileName:1,lineNumber:1};function o(t){return e||(e=nn().encode),e(t)}function s(e){return e.valueOf()}function a(e){(e=RegExp.prototype.toString.call(e).split("/")).shift();var t=[e.pop()];return t.unshift(e.join("/")),t}function c(e){var t={};for(var n in i)t[n]=e[n];return t}return Mt}var kt,Dt={},Ot={};function Rt(){return kt||(kt=1,function(e){!function(e){var t,n="undefined",r=n!==typeof Buffer&&Buffer,i=n!==typeof Uint8Array&&Uint8Array,o=n!==typeof ArrayBuffer&&ArrayBuffer,s=[0,0,0,0,0,0,0,0],a=Array.isArray||function(e){return!!e&&"[object Array]"==Object.prototype.toString.call(e)},c=4294967296;function u(a,u,S){var E=u?0:4,C=u?4:0,b=u?0:3,w=u?1:2,A=u?2:1,T=u?3:0,x=u?m:g,M=u?v:_,I=O.prototype,k="is"+a,D="_"+k;return I.buffer=void 0,I.offset=0,I[D]=!0,I.toNumber=R,I.toString=function(e){var t=this.buffer,n=this.offset,r=P(t,n+E),i=P(t,n+C),o="",s=!S&&2147483648&r;s&&(r=~r,i=c-i);e=e||10;for(;;){var a=r%e*c+i;if(r=Math.floor(r/e),i=Math.floor(a/e),o=(a%e).toString(e)+o,!r&&!i)break}s&&(o="-"+o);return o},I.toJSON=R,I.toArray=h,r&&(I.toBuffer=l),i&&(I.toArrayBuffer=f),O[k]=function(e){return!(!e||!e[D])},e[a]=O,O;function O(e,r,a,u){return this instanceof O?function(e,r,a,u,h){i&&o&&(r instanceof o&&(r=new i(r)),u instanceof o&&(u=new i(u)));if(!(r||a||u||t))return void(e.buffer=y(s,0));if(!d(r,a)){h=a,u=r,a=0,r=new(t||Array)(8)}if(e.buffer=r,e.offset=a|=0,n===typeof u)return;"string"==typeof u?function(e,t,n,r){var i=0,o=n.length,s=0,a=0;"-"===n[0]&&i++;var u=i;for(;i<o;){var h=parseInt(n[i++],r);if(!(h>=0))break;a=a*r+h,s=s*r+Math.floor(a/c),a%=c}u&&(s=~s,a?a=c-a:s++);B(e,t+E,s),B(e,t+C,a)}(r,a,u,h||10):d(u,h)?p(r,a,u,h):"number"==typeof h?(B(r,a+E,u),B(r,a+C,h)):u>0?x(r,a,u):u<0?M(r,a,u):p(r,a,s,0)}(this,e,r,a,u):new O(e,r,a,u)}function R(){var e=this.buffer,t=this.offset,n=P(e,t+E),r=P(e,t+C);return S||(n|=0),n?n*c+r:r}function B(e,t,n){e[t+T]=255&n,n>>=8,e[t+A]=255&n,n>>=8,e[t+w]=255&n,n>>=8,e[t+b]=255&n}function P(e,t){return 16777216*e[t+b]+(e[t+w]<<16)+(e[t+A]<<8)+e[t+T]}}function h(e){var n=this.buffer,r=this.offset;return t=null,!1!==e&&0===r&&8===n.length&&a(n)?n:y(n,r)}function l(e){var n=this.buffer,i=this.offset;if(t=r,!1!==e&&0===i&&8===n.length&&Buffer.isBuffer(n))return n;var o=new r(8);return p(o,0,n,i),o}function f(e){var n=this.buffer,r=this.offset,s=n.buffer;if(t=i,!1!==e&&0===r&&s instanceof o&&8===s.byteLength)return s;var a=new i(8);return p(a,0,n,r),a.buffer}function d(e,t){var n=e&&e.length;return t|=0,n&&t+8<=n&&"string"!=typeof e[t]}function p(e,t,n,r){t|=0,r|=0;for(var i=0;i<8;i++)e[t++]=255&n[r++]}function y(e,t){return Array.prototype.slice.call(e,t,t+8)}function m(e,t,n){for(var r=t+8;r>t;)e[--r]=255&n,n/=256}function v(e,t,n){var r=t+8;for(n++;r>t;)e[--r]=255&-n^255,n/=256}function g(e,t,n){for(var r=t+8;t<r;)e[t++]=255&n,n/=256}function _(e,t,n){var r=t+8;for(n++;t<r;)e[t++]=255&-n^255,n/=256}u("Uint64BE",!0,!0),u("Int64BE",!0,!1),u("Uint64LE",!1,!0),u("Int64LE",!1,!1)}("string"!=typeof e.nodeName?e:Ot||{})}(Ot)),Ot}var Bt,Pt={},zt={};function Nt(){return Bt||(Bt=1,zt.read=function(e,t,n,r,i){var o,s,a=8*i-r-1,c=(1<<a)-1,u=c>>1,h=-7,l=n?i-1:0,f=n?-1:1,d=e[t+l];for(l+=f,o=d&(1<<-h)-1,d>>=-h,h+=a;h>0;o=256*o+e[t+l],l+=f,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=r;h>0;s=256*s+e[t+l],l+=f,h-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,r),o-=u}return(d?-1:1)*s*Math.pow(2,o-r)},zt.write=function(e,t,n,r,i,o){var s,a,c,u=8*o-i-1,h=(1<<u)-1,l=h>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=h):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+l>=1?f/c:f*Math.pow(2,1-l))*c>=2&&(s++,c/=2),s+l>=h?(a=0,s=h):s+l>=1?(a=(t*c-1)*Math.pow(2,i),s+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,i),s=0));i>=8;e[n+d]=255&a,d+=p,a/=256,i-=8);for(s=s<<i|a,u+=i;u>0;e[n+d]=255&s,d+=p,s/=256,u-=8);e[n+d-p]|=128*y}),zt}var Wt,Lt,Ft,Ut={};function Ht(){if(Wt)return Ut;Wt=1;for(var e=Ut.uint8=new Array(256),t=0;t<=255;t++)e[t]=n(t);function n(e){return function(t){var n=t.reserve(1);t.buffer[n]=e}}return Ut}function jt(){if(Lt)return Pt;Lt=1;var e=Nt(),t=Rt(),n=t.Uint64BE,r=t.Int64BE,i=Ht().uint8,o=At(),s=o.global,a=o.hasBuffer&&"TYPED_ARRAY_SUPPORT"in s&&!s.TYPED_ARRAY_SUPPORT,c=o.hasBuffer&&s.prototype||{};function u(){var e=i.slice();return e[196]=h(196),e[197]=l(197),e[198]=f(198),e[199]=h(199),e[200]=l(200),e[201]=f(201),e[202]=d(202,4,c.writeFloatBE||m,!0),e[203]=d(203,8,c.writeDoubleBE||v,!0),e[204]=h(204),e[205]=l(205),e[206]=f(206),e[207]=d(207,8,p),e[208]=h(208),e[209]=l(209),e[210]=f(210),e[211]=d(211,8,y),e[217]=h(217),e[218]=l(218),e[219]=f(219),e[220]=l(220),e[221]=f(221),e[222]=l(222),e[223]=f(223),e}function h(e){return function(t,n){var r=t.reserve(2),i=t.buffer;i[r++]=e,i[r]=n}}function l(e){return function(t,n){var r=t.reserve(3),i=t.buffer;i[r++]=e,i[r++]=n>>>8,i[r]=n}}function f(e){return function(t,n){var r=t.reserve(5),i=t.buffer;i[r++]=e,i[r++]=n>>>24,i[r++]=n>>>16,i[r++]=n>>>8,i[r]=n}}function d(e,t,n,r){return function(i,o){var s=i.reserve(t+1);i.buffer[s++]=e,n.call(i.buffer,o,s,r)}}function p(e,t){new n(this,t,e)}function y(e,t){new r(this,t,e)}function m(t,n){e.write(this,t,n,!1,23,4)}function v(t,n){e.write(this,t,n,!1,52,8)}return Pt.getWriteToken=function(e){return e&&e.uint8array?((t=u())[202]=d(202,4,m),t[203]=d(203,8,v),t):a||o.hasBuffer&&e&&e.safe?function(){var e=i.slice();return e[196]=d(196,1,s.prototype.writeUInt8),e[197]=d(197,2,s.prototype.writeUInt16BE),e[198]=d(198,4,s.prototype.writeUInt32BE),e[199]=d(199,1,s.prototype.writeUInt8),e[200]=d(200,2,s.prototype.writeUInt16BE),e[201]=d(201,4,s.prototype.writeUInt32BE),e[202]=d(202,4,s.prototype.writeFloatBE),e[203]=d(203,8,s.prototype.writeDoubleBE),e[204]=d(204,1,s.prototype.writeUInt8),e[205]=d(205,2,s.prototype.writeUInt16BE),e[206]=d(206,4,s.prototype.writeUInt32BE),e[207]=d(207,8,p),e[208]=d(208,1,s.prototype.writeInt8),e[209]=d(209,2,s.prototype.writeInt16BE),e[210]=d(210,4,s.prototype.writeInt32BE),e[211]=d(211,8,y),e[217]=d(217,1,s.prototype.writeUInt8),e[218]=d(218,2,s.prototype.writeUInt16BE),e[219]=d(219,4,s.prototype.writeUInt32BE),e[220]=d(220,2,s.prototype.writeUInt16BE),e[221]=d(221,4,s.prototype.writeUInt32BE),e[222]=d(222,2,s.prototype.writeUInt16BE),e[223]=d(223,4,s.prototype.writeUInt32BE),e}():u();var t},Pt}function qt(){if(Ft)return Dt;Ft=1;var e=at(),t=Rt(),n=t.Uint64BE,r=t.Int64BE,i=At(),o=wt(),s=jt(),a=Ht().uint8,c=Tt().ExtBuffer,u="undefined"!=typeof Uint8Array,h="undefined"!=typeof Map,l=[];return l[1]=212,l[2]=213,l[4]=214,l[8]=215,l[16]=216,Dt.getWriteType=function(t){var f=s.getWriteToken(t),d=t&&t.useraw,p=u&&t&&t.binarraybuffer,y=p?i.isArrayBuffer:i.isBuffer,m=p?function(e,t){E(e,new Uint8Array(t))}:E,v=h&&t&&t.usemap?function(e,t){if(!(t instanceof Map))return C(e,t);var n=t.size;f[n<16?128+n:n<=65535?222:223](e,n);var r=e.codec.encode;t.forEach((function(t,n,i){r(e,n),r(e,t)}))}:C,g={boolean:function(e,t){f[t?195:194](e,t)},function:S,number:function(e,t){var n,r=0|t;if(t!==r)return void f[n=203](e,t);n=-32<=r&&r<=127?255&r:0<=r?r<=255?204:r<=65535?205:206:-128<=r?208:-32768<=r?209:210;f[n](e,r)},object:d?function(e,t){if(y(t))return function(e,t){var n=t.length;f[n<32?160+n:n<=65535?218:219](e,n),e.send(t)}(e,t);_(e,t)}:_,string:function(e){return t;function t(t,n){var r=n.length,i=5+3*r;t.offset=t.reserve(i);var s=t.buffer,a=e(r),c=t.offset+a;r=o.write.call(s,n,c);var u=e(r);if(a!==u){var h=c+u-a,l=c+r;o.copy.call(s,s,h,c,l)}f[1===u?160+r:u<=3?215+u:219](t,r),t.offset+=r}}(d?function(e){return e<32?1:e<=65535?3:5}:function(e){return e<32?1:e<=255?2:e<=65535?3:5}),symbol:S,undefined:S};return g;function _(t,i){if(null===i)return S(t,i);if(y(i))return m(t,i);if(e(i))return function(e,t){var n=t.length;f[n<16?144+n:n<=65535?220:221](e,n);for(var r=e.codec.encode,i=0;i<n;i++)r(e,t[i])}(t,i);if(n.isUint64BE(i))return function(e,t){f[207](e,t.toArray())}(t,i);if(r.isInt64BE(i))return function(e,t){f[211](e,t.toArray())}(t,i);var o=t.codec.getExtPacker(i);if(o&&(i=o(i)),i instanceof c)return function(e,t){var n=t.buffer,r=n.length,i=l[r]||(r<255?199:r<=65535?200:201);f[i](e,r),a[t.type](e),e.send(n)}(t,i);v(t,i)}function S(e,t){f[192](e,t)}function E(e,t){var n=t.length;f[n<255?196:n<=65535?197:198](e,n),e.send(t)}function C(e,t){var n=Object.keys(t),r=n.length;f[r<16?128+r:r<=65535?222:223](e,r);var i=e.codec.encode;n.forEach((function(n){i(e,n),i(e,t[n])}))}},Dt}var Gt,Vt,Yt={};function Qt(){if(Gt)return Yt;Gt=1;var e=at();Yt.createCodec=i,Yt.install=function(e){for(var t in e)n.prototype[t]=r(n.prototype[t],e[t])},Yt.filter=function(t){return e(t)?function(e){return e=e.slice(),function(n){return e.reduce(t,n)};function t(e,t){return t(e)}}(t):t};var t=At();function n(e){if(!(this instanceof n))return new n(e);this.options=e,this.init()}function r(e,t){return e&&t?function(){return e.apply(this,arguments),t.apply(this,arguments)}:e||t}function i(e){return new n(e)}return n.prototype.init=function(){var e=this.options;return e&&e.uint8array&&(this.bufferish=t.Uint8Array),this},Yt.preset=i({preset:!0}),Yt}function Jt(){if(Vt)return rt;Vt=1;var e=Tt().ExtBuffer,t=It(),n=qt(),r=Qt();function i(){var e=this.options;return this.encode=function(e){var t=n.getWriteType(e);return function(e,n){var r=t[typeof n];if(!r)throw new Error('Unsupported type "'+typeof n+'": '+n);r(e,n)}}(e),e&&e.preset&&t.setExtPackers(this),this}return r.install({addExtPacker:function(t,n,i){i=r.filter(i);var o=n.name;if(o&&"Object"!==o){(this.extPackers||(this.extPackers={}))[o]=s}else{(this.extEncoderList||(this.extEncoderList=[])).unshift([n,s])}function s(n){return i&&(n=i(n)),new e(n,t)}},getExtPacker:function(e){var t=this.extPackers||(this.extPackers={}),n=e.constructor,r=n&&n.name&&t[n.name];if(r)return r;for(var i=this.extEncoderList||(this.extEncoderList=[]),o=i.length,s=0;s<o;s++){var a=i[s];if(n===a[0])return a[1]}},init:i}),rt.preset=i.call(r.preset),rt}var Zt,Xt,Kt,$t={};function en(){if(Zt)return $t;Zt=1,$t.FlexDecoder=n,$t.FlexEncoder=r;var e=At(),t="BUFFER_SHORTAGE";function n(){if(!(this instanceof n))return new n}function r(){if(!(this instanceof r))return new r}function i(){throw new Error("method not implemented: write()")}function o(){throw new Error("method not implemented: fetch()")}function s(){return this.buffers&&this.buffers.length?(this.flush(),this.pull()):this.fetch()}function a(e){(this.buffers||(this.buffers=[])).push(e)}function c(){return(this.buffers||(this.buffers=[])).shift()}function u(e){return function(t){for(var n in e)t[n]=e[n];return t}}return n.mixin=u({bufferish:e,write:function(t){var n=this.offset?e.prototype.slice.call(this.buffer,this.offset):this.buffer;this.buffer=n?t?this.bufferish.concat([n,t]):n:t,this.offset=0},fetch:o,flush:function(){for(;this.offset<this.buffer.length;){var e,n=this.offset;try{e=this.fetch()}catch(e){if(e&&e.message!=t)throw e;this.offset=n;break}this.push(e)}},push:a,pull:c,read:s,reserve:function(e){var n=this.offset,r=n+e;if(r>this.buffer.length)throw new Error(t);return this.offset=r,n},offset:0}),n.mixin(n.prototype),r.mixin=u({bufferish:e,write:i,fetch:function(){var t=this.start;if(t<this.offset){var n=this.start=this.offset;return e.prototype.slice.call(this.buffer,t,n)}},flush:function(){for(;this.start<this.offset;){var e=this.fetch();e&&this.push(e)}},push:a,pull:function(){var e=this.buffers||(this.buffers=[]),t=e.length>1?this.bufferish.concat(e):e[0];return e.length=0,t},read:s,reserve:function(e){var t=0|e;if(this.buffer){var n=this.buffer.length,r=0|this.offset,i=r+t;if(i<n)return this.offset=i,r;this.flush(),e=Math.max(e,Math.min(2*n,this.maxBufferSize))}return e=Math.max(e,this.minBufferSize),this.buffer=this.bufferish.alloc(e),this.start=0,this.offset=t,0},send:function(t){var n=t.length;if(n>this.minBufferSize)this.flush(),this.push(t);else{var r=this.reserve(n);e.prototype.copy.call(t,this.buffer,r)}},maxBufferSize:65536,minBufferSize:2048,offset:0,start:0}),r.mixin(r.prototype),$t}function tn(){if(Xt)return nt;Xt=1,nt.EncodeBuffer=t;var e=Jt().preset;function t(e){if(!(this instanceof t))return new t(e);if(e&&(this.options=e,e.codec)){var n=this.codec=e.codec;n.bufferish&&(this.bufferish=n.bufferish)}}return en().FlexEncoder.mixin(t.prototype),t.prototype.codec=e,t.prototype.write=function(e){this.codec.encode(this,e)},nt}function nn(){if(Kt)return tt;Kt=1,tt.encode=function(t,n){var r=new e(n);return r.write(t),r.read()};var e=tn().EncodeBuffer;return tt}var rn,on={},sn={},an={},cn={};function un(){if(rn)return cn;rn=1,cn.setExtUnpackers=function(e){e.addExtUnpacker(14,[i,s(Error)]),e.addExtUnpacker(1,[i,s(EvalError)]),e.addExtUnpacker(2,[i,s(RangeError)]),e.addExtUnpacker(3,[i,s(ReferenceError)]),e.addExtUnpacker(4,[i,s(SyntaxError)]),e.addExtUnpacker(5,[i,s(TypeError)]),e.addExtUnpacker(6,[i,s(URIError)]),e.addExtUnpacker(10,[i,o]),e.addExtUnpacker(11,[i,a(Boolean)]),e.addExtUnpacker(12,[i,a(String)]),e.addExtUnpacker(13,[i,a(Date)]),e.addExtUnpacker(15,[i,a(Number)]),"undefined"!=typeof Uint8Array&&(e.addExtUnpacker(17,a(Int8Array)),e.addExtUnpacker(18,a(Uint8Array)),e.addExtUnpacker(19,[c,a(Int16Array)]),e.addExtUnpacker(20,[c,a(Uint16Array)]),e.addExtUnpacker(21,[c,a(Int32Array)]),e.addExtUnpacker(22,[c,a(Uint32Array)]),e.addExtUnpacker(23,[c,a(Float32Array)]),"undefined"!=typeof Float64Array&&e.addExtUnpacker(24,[c,a(Float64Array)]),"undefined"!=typeof Uint8ClampedArray&&e.addExtUnpacker(25,a(Uint8ClampedArray)),e.addExtUnpacker(26,c),e.addExtUnpacker(29,[c,a(DataView)]));t.hasBuffer&&e.addExtUnpacker(27,a(n))};var e,t=At(),n=t.global,r={name:1,message:1,stack:1,columnNumber:1,fileName:1,lineNumber:1};function i(t){return e||(e=En().decode),e(t)}function o(e){return RegExp.apply(null,e)}function s(e){return function(t){var n=new e;for(var i in r)n[i]=t[i];return n}}function a(e){return function(t){return new e(t)}}function c(e){return new Uint8Array(e).buffer}return cn}var hn,ln={};function fn(){if(hn)return ln;hn=1;var e=Nt(),t=Rt(),n=t.Uint64BE,r=t.Int64BE;ln.getReadFormat=function(e){var t=i.hasArrayBuffer&&e&&e.binarraybuffer,n=e&&e.int64,r={map:s&&e&&e.usemap?u:c,array:h,str:l,bin:t?d:f,ext:p,uint8:y,uint16:v,uint32:_,uint64:E(8,n?w:C),int8:m,int16:g,int32:S,int64:E(8,n?A:b),float32:E(4,T),float64:E(8,x)};return r},ln.readUint8=y;var i=At(),o=wt(),s="undefined"!=typeof Map,a=!0;function c(e,t){var n,r={},i=new Array(t),o=new Array(t),s=e.codec.decode;for(n=0;n<t;n++)i[n]=s(e),o[n]=s(e);for(n=0;n<t;n++)r[i[n]]=o[n];return r}function u(e,t){var n,r=new Map,i=new Array(t),o=new Array(t),s=e.codec.decode;for(n=0;n<t;n++)i[n]=s(e),o[n]=s(e);for(n=0;n<t;n++)r.set(i[n],o[n]);return r}function h(e,t){for(var n=new Array(t),r=e.codec.decode,i=0;i<t;i++)n[i]=r(e);return n}function l(e,t){var n=e.reserve(t),r=n+t;return o.toString.call(e.buffer,"utf-8",n,r)}function f(e,t){var n=e.reserve(t),r=n+t,s=o.slice.call(e.buffer,n,r);return i.from(s)}function d(e,t){var n=e.reserve(t),r=n+t,s=o.slice.call(e.buffer,n,r);return i.Uint8Array.from(s).buffer}function p(e,t){var n=e.reserve(t+1),r=e.buffer[n++],i=n+t,s=e.codec.getExtUnpacker(r);if(!s)throw new Error("Invalid ext type: "+(r?"0x"+r.toString(16):r));return s(o.slice.call(e.buffer,n,i))}function y(e){var t=e.reserve(1);return e.buffer[t]}function m(e){var t=e.reserve(1),n=e.buffer[t];return 128&n?n-256:n}function v(e){var t=e.reserve(2),n=e.buffer;return n[t++]<<8|n[t]}function g(e){var t=e.reserve(2),n=e.buffer,r=n[t++]<<8|n[t];return 32768&r?r-65536:r}function _(e){var t=e.reserve(4),n=e.buffer;return 16777216*n[t++]+(n[t++]<<16)+(n[t++]<<8)+n[t]}function S(e){var t=e.reserve(4),n=e.buffer;return n[t++]<<24|n[t++]<<16|n[t++]<<8|n[t]}function E(e,t){return function(n){var r=n.reserve(e);return t.call(n.buffer,r,a)}}function C(e){return new n(this,e).toNumber()}function b(e){return new r(this,e).toNumber()}function w(e){return new n(this,e)}function A(e){return new r(this,e)}function T(t){return e.read(this,t,!1,23,4)}function x(t){return e.read(this,t,!1,52,8)}return ln}var dn,pn,yn,mn,vn={};function gn(){if(dn)return vn;dn=1;var e=fn();function t(e){var t,o=new Array(256);for(t=0;t<=127;t++)o[t]=n(t);for(t=128;t<=143;t++)o[t]=i(t-128,e.map);for(t=144;t<=159;t++)o[t]=i(t-144,e.array);for(t=160;t<=191;t++)o[t]=i(t-160,e.str);for(o[192]=n(null),o[193]=null,o[194]=n(!1),o[195]=n(!0),o[196]=r(e.uint8,e.bin),o[197]=r(e.uint16,e.bin),o[198]=r(e.uint32,e.bin),o[199]=r(e.uint8,e.ext),o[200]=r(e.uint16,e.ext),o[201]=r(e.uint32,e.ext),o[202]=e.float32,o[203]=e.float64,o[204]=e.uint8,o[205]=e.uint16,o[206]=e.uint32,o[207]=e.uint64,o[208]=e.int8,o[209]=e.int16,o[210]=e.int32,o[211]=e.int64,o[212]=i(1,e.ext),o[213]=i(2,e.ext),o[214]=i(4,e.ext),o[215]=i(8,e.ext),o[216]=i(16,e.ext),o[217]=r(e.uint8,e.str),o[218]=r(e.uint16,e.str),o[219]=r(e.uint32,e.str),o[220]=r(e.uint16,e.array),o[221]=r(e.uint32,e.array),o[222]=r(e.uint16,e.map),o[223]=r(e.uint32,e.map),t=224;t<=255;t++)o[t]=n(t-256);return o}function n(e){return function(){return e}}function r(e,t){return function(n){var r=e(n);return t(n,r)}}function i(e,t){return function(n){return t(n,e)}}return vn.getReadToken=function(n){var r=e.getReadFormat(n);return n&&n.useraw?function(e){var n,r=t(e).slice();for(r[217]=r[196],r[218]=r[197],r[219]=r[198],n=160;n<=191;n++)r[n]=i(n-160,e.bin);return r}(r):t(r)},vn}function _n(){if(pn)return an;pn=1;var e=Tt().ExtBuffer,t=un(),n=fn().readUint8,r=gn(),i=Qt();function o(){var e=this.options;return this.decode=function(e){var t=r.getReadToken(e);return function(e){var r=n(e),i=t[r];if(!i)throw new Error("Invalid type: "+(r?"0x"+r.toString(16):r));return i(e)}}(e),e&&e.preset&&t.setExtUnpackers(this),this}return i.install({addExtUnpacker:function(e,t){(this.extUnpackers||(this.extUnpackers=[]))[e]=i.filter(t)},getExtUnpacker:function(t){return(this.extUnpackers||(this.extUnpackers=[]))[t]||function(n){return new e(n,t)}},init:o}),an.preset=o.call(i.preset),an}function Sn(){if(yn)return sn;yn=1,sn.DecodeBuffer=t;var e=_n().preset;function t(e){if(!(this instanceof t))return new t(e);if(e&&(this.options=e,e.codec)){var n=this.codec=e.codec;n.bufferish&&(this.bufferish=n.bufferish)}}return en().FlexDecoder.mixin(t.prototype),t.prototype.codec=e,t.prototype.fetch=function(){return this.codec.decode(this)},sn}function En(){if(mn)return on;mn=1,on.decode=function(t,n){var r=new e(n);return r.write(t),r.read()};var e=Sn().DecodeBuffer;return on}var Cn,bn,wn={},An={exports:{}};function Tn(){return Cn||(Cn=1,function(e){!function(t){e.exports=t;var n="listeners",r={on:function(e,t){return s(this,e).push(t),this},once:function(e,t){var n=this;return r.originalListener=t,s(n,e).push(r),n;function r(){o.call(n,e,r),t.apply(this,arguments)}},off:o,emit:function(e,t){var n=this,r=s(n,e,!0);if(!r)return!1;var i=arguments.length;if(1===i)r.forEach((function(e){e.call(n)}));else if(2===i)r.forEach((function(e){e.call(n,t)}));else{var o=Array.prototype.slice.call(arguments,1);r.forEach((function(e){e.apply(n,o)}))}return!!r.length}};function i(e){for(var t in r)e[t]=r[t];return e}function o(e,t){var r,i=this;if(arguments.length){if(t){if(r=s(i,e,!0)){if(!(r=r.filter((function(e){return e!==t&&e.originalListener!==t}))).length)return o.call(i,e);i[n][e]=r}}else if((r=i[n])&&(delete r[e],!Object.keys(r).length))return o.call(i)}else delete i[n];return i}function s(e,t,r){if(!r||e[n]){var i=e[n]||(e[n]={});return i[t]||(i[t]=[])}}i(t.prototype),t.mixin=i}((function e(){if(!(this instanceof e))return new e}))}(An)),An.exports}function xn(){if(bn)return wn;bn=1,wn.Encoder=n;var e=Tn(),t=tn().EncodeBuffer;function n(e){if(!(this instanceof n))return new n(e);t.call(this,e)}return n.prototype=new t,e.mixin(n.prototype),n.prototype.encode=function(e){this.write(e),this.emit("data",this.read())},n.prototype.end=function(e){arguments.length&&this.encode(e),this.flush(),this.emit("end")},wn}var Mn,In={};function kn(){if(Mn)return In;Mn=1,In.Decoder=n;var e=Tn(),t=Sn().DecodeBuffer;function n(e){if(!(this instanceof n))return new n(e);t.call(this,e)}return n.prototype=new t,e.mixin(n.prototype),n.prototype.decode=function(e){arguments.length&&this.write(e),this.flush()},n.prototype.push=function(e){this.emit("data",e)},n.prototype.end=function(e){this.decode(e),this.emit("end")},In}var Dn,On={};function Rn(){return Dn||(Dn=1,On.createCodec=Qt().createCodec),On}var Bn,Pn,zn={};function Nn(){return Bn||(Bn=1,zn.codec={preset:Qt().preset}),zn}function Wn(){return Pn||(Pn=1,et.encode=nn().encode,et.decode=En().decode,et.Encoder=xn().Encoder,et.Decoder=kn().Decoder,et.createCodec=Rn().createCodec,et.codec=Nn().codec),et}var Ln,Fn=Wn(),Un=function(){function e(){}return e.serialize=function(e,t){var n=a({systems:!1,format:"json",pretty:!0,includeMetadata:!0},t),r=this.filterEntities(e,n),i=$e.serializeEntities(r,!0),o=this.buildComponentTypeRegistry(r),s=this.serializeSceneData(e.sceneData),c={name:e.name,version:this.SERIALIZATION_VERSION,entities:i,componentTypeRegistry:o};return s&&Object.keys(s).length>0&&(c.sceneData=s),n.includeMetadata&&(c.timestamp=Date.now(),c.metadata={entityCount:i.length,componentTypeCount:o.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(c,null,2):JSON.stringify(c):Fn.encode(c)},e.deserialize=function(e,t,n){var r,i=a({strategy:"replace",preserveIds:!1},n);try{r="string"==typeof t?JSON.parse(t):Fn.decode(t)}catch(e){throw new Error("Failed to parse save data: "+e)}i.migration&&r.version!==this.SERIALIZATION_VERSION&&(r=i.migration(r.version,this.SERIALIZATION_VERSION,r));var o=i.componentRegistry||this.getGlobalComponentRegistry();"replace"===i.strategy&&e.destroyAllEntities();for(var c,u=s($e.deserializeEntities(r.entities,o,(function(){return e.identifierPool.checkOut()}),i.preserveIds||!1,e));!(c=u()).done;){var h=c.value;e.addEntity(h)}r.sceneData&&this.deserializeSceneData(r.sceneData,e.sceneData)},e.serializeSceneData=function(e){for(var t,n={},r=s(e);!(t=r()).done;){var i=t.value,o=i[0],a=i[1];n[o]=this.serializeValue(a)}return n},e.deserializeSceneData=function(e,t){t.clear();for(var n=0,r=Object.entries(e);n<r.length;n++){var i=r[n],o=i[0],s=i[1];t.set(o,this.deserializeValue(s))}},e.serializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if(Array.isArray(e))return e.map((function(e){return t.serializeValue(e)}));if("object"===n){var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=this.serializeValue(e[i]));return r}},e.deserializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if("object"===n&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((function(e){return t.deserializeValue(e)}));if("object"===n){var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=this.deserializeValue(e[i]));return r}return e},e.filterEntities=function(e,t){var n=Array.from(e.entities.buffer);if(t.components&&t.components.length>0){var r=new Set(t.components);return n.filter((function(e){return Array.from(e.components).some((function(e){return r.has(e.constructor)}))}))}return n},e.buildComponentTypeRegistry=function(e){for(var t,n=new Map,r=s(e);!(t=r()).done;)for(var i,o=s(t.value.components);!(i=o()).done;){var a=i.value,c=W(a.constructor),u=Ye(a);u&&!n.has(c)&&n.set(c,u.options.version)}return Array.from(n.entries()).map((function(e){return{typeName:e[0],version:e[1]}}))},e.getGlobalComponentRegistry=function(){return ye.getAllComponentNames()},e.validate=function(e){var t=[];try{var n=JSON.parse(e);return n.version||t.push("Missing version field"),n.entities&&Array.isArray(n.entities)||t.push("Missing or invalid entities field"),n.componentTypeRegistry&&Array.isArray(n.componentTypeRegistry)||t.push("Missing or invalid componentTypeRegistry field"),{valid:0===t.length,version:n.version,errors:t.length>0?t:void 0}}catch(e){return{valid:!1,errors:["JSON parse error: "+e]}}},e.getInfo=function(e){try{var t,n=JSON.parse(e);return{name:n.name,version:n.version,timestamp:n.timestamp,entityCount:(null===(t=n.metadata)||void 0===t?void 0:t.entityCount)||n.entities.length,componentTypeCount:n.componentTypeRegistry.length}}catch(e){return null}},e}();Un.SERIALIZATION_VERSION=1,exports.ChangeOperation=void 0,(Ln=exports.ChangeOperation||(exports.ChangeOperation={})).EntityAdded="entity_added",Ln.EntityRemoved="entity_removed",Ln.EntityUpdated="entity_updated",Ln.ComponentAdded="component_added",Ln.ComponentRemoved="component_removed",Ln.ComponentUpdated="component_updated",Ln.SceneDataUpdated="scene_data_updated";var Hn=function(){function e(){}return e.createSnapshot=function(e,t){for(var n,r=a({deepComponentComparison:!0,trackSceneData:!0,compressSnapshot:!1},t),i={version:++this.snapshotVersion,entityIds:new Set,entities:new Map,components:new Map,sceneData:new Map},o=s(e.entities.buffer);!(n=o()).done;){var c,u=n.value;if(i.entityIds.add(u.id),i.entities.set(u.id,{name:u.name,tag:u.tag,active:u.active,enabled:u.enabled,updateOrder:u.updateOrder,parentId:null===(c=u.parent)||void 0===c?void 0:c.id}),r.deepComponentComparison){for(var h,l=new Map,f=s(u.components);!(h=f()).done;){var d=h.value,p=Ke.serialize(d);p&&l.set(p.type,JSON.stringify(p.data))}l.size>0&&i.components.set(u.id,l)}}if(r.trackSceneData)for(var y,m=s(e.sceneData);!(y=m()).done;){var v=y.value,g=v[0],_=v[1];i.sceneData.set(g,JSON.stringify(_))}return i},e.computeIncremental=function(e,t,n){for(var r,i=a({deepComponentComparison:!0,trackSceneData:!0},n),o={version:++this.snapshotVersion,timestamp:Date.now(),sceneName:e.name,baseVersion:t.version,entityChanges:[],componentChanges:[],sceneDataChanges:[]},c=new Set,u=s(e.entities.buffer);!(r=u()).done;){var h=r.value;if(c.add(h.id),t.entityIds.has(h.id)){var l,f,d=t.entities.get(h.id);if(d.name!==h.name||d.tag!==h.tag||d.active!==h.active||d.enabled!==h.enabled||d.updateOrder!==h.updateOrder||d.parentId!==(null===(l=h.parent)||void 0===l?void 0:l.id))o.entityChanges.push({operation:exports.ChangeOperation.EntityUpdated,entityId:h.id,entityData:{name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder,parentId:null===(f=h.parent)||void 0===f?void 0:f.id}});i.deepComponentComparison&&this.detectComponentChanges(h,t,o.componentChanges)}else{var p;o.entityChanges.push({operation:exports.ChangeOperation.EntityAdded,entityId:h.id,entityName:h.name,entityData:{id:h.id,name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder,parentId:null===(p=h.parent)||void 0===p?void 0:p.id,components:[],children:[]}});for(var y,m=s(h.components);!(y=m()).done;){var v=y.value,g=Ke.serialize(v);g&&o.componentChanges.push({operation:exports.ChangeOperation.ComponentAdded,entityId:h.id,componentType:g.type,componentData:g})}}}for(var _,S=s(t.entityIds);!(_=S()).done;){var E=_.value;c.has(E)||o.entityChanges.push({operation:exports.ChangeOperation.EntityRemoved,entityId:E})}return i.trackSceneData&&this.detectSceneDataChanges(e,t,o.sceneDataChanges),o},e.detectComponentChanges=function(e,t,n){for(var r,i=t.components.get(e.id),o=new Map,a=s(e.components);!(r=a()).done;){var c=r.value,u=Ke.serialize(c);u&&o.set(u.type,u)}for(var h,l=s(o);!(h=l()).done;){var f=h.value,d=f[0],p=f[1],y=JSON.stringify(p.data);i&&i.has(d)?i.get(d)!==y&&n.push({operation:exports.ChangeOperation.ComponentUpdated,entityId:e.id,componentType:d,componentData:p}):n.push({operation:exports.ChangeOperation.ComponentAdded,entityId:e.id,componentType:d,componentData:p})}if(i)for(var m,v=s(i.keys());!(m=v()).done;){var g=m.value;o.has(g)||n.push({operation:exports.ChangeOperation.ComponentRemoved,entityId:e.id,componentType:g})}},e.detectSceneDataChanges=function(e,t,n){for(var r,i=new Set,o=s(e.sceneData);!(r=o()).done;){var a=r.value,c=a[0],u=a[1];i.add(c);var h=JSON.stringify(u),l=t.sceneData.get(c);l&&l===h||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:c,value:u})}for(var f,d=s(t.sceneData.keys());!(f=d()).done;){var p=f.value;i.has(p)||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:p,value:void 0,deleted:!0})}},e.applyIncremental=function(e,t,n){for(var r,i=s(t.entityChanges);!(r=i()).done;){var o=r.value;switch(o.operation){case exports.ChangeOperation.EntityAdded:this.applyEntityAdded(e,o);break;case exports.ChangeOperation.EntityRemoved:this.applyEntityRemoved(e,o);break;case exports.ChangeOperation.EntityUpdated:this.applyEntityUpdated(e,o)}}for(var a,c=s(t.componentChanges);!(a=c()).done;){var u=a.value;switch(u.operation){case exports.ChangeOperation.ComponentAdded:this.applyComponentAdded(e,u,n);break;case exports.ChangeOperation.ComponentRemoved:this.applyComponentRemoved(e,u,n);break;case exports.ChangeOperation.ComponentUpdated:this.applyComponentUpdated(e,u,n)}}for(var h,l=s(t.sceneDataChanges);!(h=l()).done;){var f=h.value;f.deleted?e.sceneData.delete(f.key):e.sceneData.set(f.key,f.value)}},e.applyEntityAdded=function(e,t){var n,r;if(t.entityData){var i=new _e(t.entityName||"Entity",t.entityId);i.tag=t.entityData.tag||0,i.active=null===(n=t.entityData.active)||void 0===n||n,i.enabled=null===(r=t.entityData.enabled)||void 0===r||r,i.updateOrder=t.entityData.updateOrder||0,e.addEntity(i)}},e.applyEntityRemoved=function(e,t){var n=e.entities.findEntityById(t.entityId);n&&n.destroy()},e.applyEntityUpdated=function(e,t){if(t.entityData){var n=e.entities.findEntityById(t.entityId);if(n)if(void 0!==t.entityData.name&&(n.name=t.entityData.name),void 0!==t.entityData.tag&&(n.tag=t.entityData.tag),void 0!==t.entityData.active&&(n.active=t.entityData.active),void 0!==t.entityData.enabled&&(n.enabled=t.entityData.enabled),void 0!==t.entityData.updateOrder&&(n.updateOrder=t.entityData.updateOrder),void 0!==t.entityData.parentId){var r=e.entities.findEntityById(t.entityData.parentId);r&&n.parent!==r&&(n.parent&&n.parent.removeChild(n),r.addChild(n))}else n.parent&&n.parent.removeChild(n)}},e.applyComponentAdded=function(e,t,n){if(t.componentData){var r=e.entities.findEntityById(t.entityId);if(r){var i=Ke.deserialize(t.componentData,n);i&&r.addComponent(i)}}},e.applyComponentRemoved=function(e,t,n){var r=e.entities.findEntityById(t.entityId);if(r){var i=n.get(t.componentType);i&&r.removeComponentByType(i)}},e.applyComponentUpdated=function(e,t,n){if(t.componentData){var r=e.entities.findEntityById(t.entityId);if(r){var i=n.get(t.componentType);if(i){r.removeComponentByType(i);var o=Ke.deserialize(t.componentData,n);o&&r.addComponent(o)}}}},e.serializeIncremental=function(e,t){var n=a({format:"json",pretty:!1},t);return"binary"===n.format?Fn.encode(e):n.pretty?JSON.stringify(e,null,2):JSON.stringify(e)},e.deserializeIncremental=function(e){return"string"==typeof e?JSON.parse(e):Fn.decode(e)},e.getIncrementalSize=function(e,t){void 0===t&&(t="json");var n=this.serializeIncremental(e,{format:t});return"string"==typeof n?"undefined"!=typeof Blob?new Blob([n]).size:"undefined"!=typeof Buffer?Buffer.byteLength(n,"utf8"):(new TextEncoder).encode(n).length:n.length},e.getIncrementalStats=function(e){return{totalChanges:e.entityChanges.length+e.componentChanges.length+e.sceneDataChanges.length,entityChanges:e.entityChanges.length,componentChanges:e.componentChanges.length,sceneDataChanges:e.sceneDataChanges.length,addedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityAdded})).length,removedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityRemoved})).length,updatedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityUpdated})).length,addedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentAdded})).length,removedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentRemoved})).length,updatedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentUpdated})).length}},e.resetVersion=function(){this.snapshotVersion=0},e}();Hn.snapshotVersion=0;var jn,qn=V("ServiceContainer");exports.ServiceLifetime=void 0,(jn=exports.ServiceLifetime||(exports.ServiceLifetime={})).Singleton="singleton",jn.Transient="transient";var Gn=function(){function e(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}var t=e.prototype;return t.registerSingleton=function(e,t){this._services.has(e)?qn.warn("Service "+e.name+" is already registered"):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Singleton}),qn.debug("Registered singleton service: "+e.name))},t.registerTransient=function(e,t){this._services.has(e)?qn.warn("Service "+e.name+" is already registered"):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Transient}),qn.debug("Registered transient service: "+e.name))},t.registerInstance=function(e,t){if(this._services.has(e))qn.warn("Service "+e.name+" is already registered");else{if(this._services.set(e,{type:e,instance:t,lifetime:exports.ServiceLifetime.Singleton}),w(e)){var n,r=A(e),i=null!==(n=null==r?void 0:r.priority)&&void 0!==n?n:0;this._updatableServices.push({instance:t,priority:i}),this._updatableServices.sort((function(e,t){return e.priority-t.priority})),qn.debug("Service "+e.name+" is updatable (priority: "+i+"), added to update list")}qn.debug("Registered service instance: "+e.name)}},t.resolve=function(e){var t=this._services.get(e);if(!t)throw new Error("Service "+e.name+" is not registered");if(this._resolving.has(e)){var n=Array.from(this._resolving).map((function(e){return e.name})).join(" -> ");throw new Error("Circular dependency detected: "+n+" -> "+e.name)}if(t.lifetime===exports.ServiceLifetime.Singleton&&t.instance)return t.instance;this._resolving.add(e);try{var r;if(r=t.factory?t.factory(this):new t.type,t.lifetime===exports.ServiceLifetime.Singleton&&(t.instance=r,w(t.type))){var i,o=A(t.type),s=null!==(i=null==o?void 0:o.priority)&&void 0!==i?i:0;this._updatableServices.push({instance:r,priority:s}),this._updatableServices.sort((function(e,t){return e.priority-t.priority})),qn.debug("Service "+e.name+" is updatable (priority: "+s+"), added to update list")}return r}finally{this._resolving.delete(e)}},t.tryResolve=function(e){try{return this.resolve(e)}catch(e){return null}},t.isRegistered=function(e){return this._services.has(e)},t.unregister=function(e){var t=this._services.get(e);if(!t)return!1;if(t.instance){var n=this._updatableServices.findIndex((function(e){return e.instance===t.instance}));-1!==n&&this._updatableServices.splice(n,1),t.instance.dispose()}return this._services.delete(e),qn.debug("Unregistered service: "+e.name),!0},t.clear=function(){for(var e,t=s(this._services);!(e=t()).done;){var n=e.value[1];n.instance&&n.instance.dispose()}this._services.clear(),this._updatableServices=[],qn.debug("Cleared all services")},t.getRegisteredServices=function(){return Array.from(this._services.keys())},t.updateAll=function(e){for(var t,n=s(this._updatableServices);!(t=n()).done;){t.value.instance.update(e)}},t.getUpdatableCount=function(){return this._updatableServices.length},t.getAll=function(){for(var e,t=[],n=s(this._services.values());!(e=n()).done;){var r=e.value;r.instance&&t.push(r.instance)}return t},e}(),Vn=function(){function e(e){var t=this;this.name="",this.sceneData=new Map,this._didSceneBegin=!1,this.entities=new Ee(this),this.identifierPool=new Ce,this.componentStorageManager=new ve,this.querySystem=new Be,this.eventSystem=new ze,this.referenceTracker=new X,this._services=new Gn,this.logger=V("Scene"),null!=e&&e.performanceMonitor?this._performanceMonitor=e.performanceMonitor:this._performanceMonitor=nr.services.resolve(M),null!=e&&e.name&&(this.name=e.name),_e.eventBus||(_e.eventBus=new Le(!1)),_e.eventBus&&_e.eventBus.onComponentAdded((function(e){t.eventSystem.emitSync("component:added",e)}))}var t=e.prototype;return t.getSystem=function(e){return this._services.tryResolve(e)},t.initialize=function(){},t.onStart=function(){},t.unload=function(){},t.begin=function(){this._didSceneBegin=!0,this.onStart()},t.end=function(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this._services.clear(),this.unload()},t.update=function(){ce.getInstance().update(),this.entities.updateLists();for(var e,t=this.systems,n=s(t);!(e=n()).done;){var r=e.value;if(r.enabled)try{r.update()}catch(e){this.logger.error("Error in system "+r.constructor.name+".update():",e)}}for(var i,o=s(t);!(i=o()).done;){var a=i.value;if(a.enabled)try{a.lateUpdate()}catch(e){this.logger.error("Error in system "+a.constructor.name+".lateUpdate():",e)}}},t.createEntity=function(e){var t=new _e(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.systems);!(e=t()).done;){e.value.clearEntityCache()}},t.addEntity=function(e,t){return void 0===t&&(t=!1),this.entities.add(e),e.scene=this,this.querySystem.addEntity(e,t),t||this.clearSystemEntityCaches(),this.eventSystem.emitSync("entity:added",{entity:e,scene:this}),e},t.createEntities=function(e,t){void 0===t&&(t="Entity");for(var n=[],r=0;r<e;r++){var i=new _e(t+"_"+r,this.identifierPool.checkOut());i.scene=this,n.push(i)}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.destroyEntities=function(e){if(0!==e.length){for(var t,n=s(e);!(t=n()).done;){t.value._isDestroyed=!0}for(var r,i=s(e);!(r=i()).done;){r.value.removeAllComponents()}for(var o,a=s(e);!(o=a()).done;){var c=o.value;this.entities.remove(c),this.querySystem.removeEntity(c)}this.querySystem.clearCache(),this.clearSystemEntityCaches()}},t.destroyAllEntities=function(){this.entities.removeAllEntities(),this.querySystem.setEntities([])},t.findEntity=function(e){return this.entities.findEntity(e)},t.findEntityById=function(e){return this.entities.findEntityById(e)},t.findEntitiesByTag=function(e){for(var t,n=[],r=s(this.entities.buffer);!(t=r()).done;){var i=t.value;i.tag===e&&n.push(i)}return n},t.getEntityByName=function(e){return this.findEntity(e)},t.getEntitiesByTag=function(e){return this.findEntitiesByTag(e)},t.queryAll=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments)},t.queryAny=function(){var e;return(e=this.querySystem).queryAny.apply(e,arguments)},t.queryNone=function(){var e;return(e=this.querySystem).queryNone.apply(e,arguments)},t.query=function(){return new He},t.addEntityProcessor=function(e){var t,n;if("function"==typeof e){if(n=e,this._services.isRegistered(n))return this._services.resolve(n);t=C(n)?b(n,this._services):new n}else if(n=(t=e).constructor,this._services.isRegistered(n))return t;t.scene=this,t.setPerformanceMonitor(this._performanceMonitor);var r=N(n);return void 0!==(null==r?void 0:r.updateOrder)&&t.setUpdateOrder(r.updateOrder),void 0!==(null==r?void 0:r.enabled)&&(t.enabled=r.enabled),this._services.registerInstance(n,t),t.initialize(),t},t.registerSystems=function(e){for(var t,n=[],r=s(e);!(t=r()).done;){var i=t.value,o=this.addEntityProcessor(i);n.push(o)}return n},t.addSystem=function(e){return this.addEntityProcessor(e)},t.removeEntityProcessor=function(e){var t=e.constructor;this._services.unregister(t),e.reset()},t.removeSystem=function(e){this.removeEntityProcessor(e)},t.getEntityProcessor=function(e){return this._services.tryResolve(e)},t.getStats=function(){return{entityCount:this.entities.count,processorCount:this.systems.length,componentStorageStats:this.componentStorageManager.getAllStats()}},t.getDebugInfo=function(){var e=this.systems;return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:e.length,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((function(e){return{name:e.name,id:e.id,componentCount:e.components.length,componentTypes:e.components.map((function(e){return F(e)}))}})),processors:e.map((function(e){var t;return{name:U(e),updateOrder:e.updateOrder,entityCount:(null===(t=e._entities)||void 0===t?void 0:t.length)||0}})),componentStats:this.componentStorageManager.getAllStats()}},t.serialize=function(e){return Un.serialize(this,e)},t.deserialize=function(e,t){Un.deserialize(this,e,t)},t.createIncrementalSnapshot=function(e){this._incrementalBaseSnapshot=Hn.createSnapshot(this,e)},t.serializeIncremental=function(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return Hn.computeIncremental(this,this._incrementalBaseSnapshot,e)},t.applyIncremental=function(e,t){var n="string"==typeof e||"undefined"!=typeof Buffer&&Buffer.isBuffer(e)||e instanceof Uint8Array?Hn.deserializeIncremental(e):e,r=t||ye.getAllComponentNames();Hn.applyIncremental(this,n,r)},t.updateIncrementalSnapshot=function(e){this.createIncrementalSnapshot(e)},t.clearIncrementalSnapshot=function(){this._incrementalBaseSnapshot=void 0},t.hasIncrementalSnapshot=function(){return void 0!==this._incrementalBaseSnapshot},o(e,[{key:"systems",get:function(){for(var e,t=[],n=s(this._services.getAll());!(e=n()).done;){var r=e.value;r instanceof we&&t.push(r)}return t.sort((function(e,t){return e.updateOrder-t.updateOrder})),t}},{key:"services",get:function(){return this._services}}])}(),Yn=function(){function e(){this.scene=new Vn}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 Se(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 r=0,i=t;r<i.length;r++){var o=i[r];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 r=0,i=t;r<i.length;r++){var o=i[r];this.scene.addSystem(o)}return this},t.build=function(){return this.scene},e}(),Qn=function(){function e(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.component=r(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}(),Jn=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}(),Zn=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 Se(this.scene,this.scene.componentStorageManager)},t.createScene=function(){return new Yn},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return r(Qn,[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 Jn(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 Xn(e,t,n){return new Zn(e,t,n)}var Kn,$n=function(){function e(){this._currentScene=null,this._nextScene=null,this._ecsAPI=null,this._logger=V("SceneManager")}var t=e.prototype;return t.setScene=function(e){this._currentScene&&(this._logger.info("Ending scene: "+this._currentScene.name),this._currentScene.end()),this._currentScene=e,this._currentScene.initialize(),this._currentScene.begin(),e.querySystem&&e.eventSystem?this._ecsAPI=Xn(e,e.querySystem,e.eventSystem):this._ecsAPI=null,m.sceneChanged();var t=nr.Instance;return t&&t._debugManager&&t._debugManager.onSceneChanged(),this._logger.info("Scene changed to: "+e.name),e},t.loadScene=function(e){this._nextScene=e,this._logger.info("Scheduled scene load: "+e.name)},t.update=function(){this._nextScene&&(this.setScene(this._nextScene),this._nextScene=null),this._currentScene&&this._currentScene.update()},t.destroy=function(){this._currentScene&&(this._logger.info("Destroying scene: "+this._currentScene.name),this._currentScene.end(),this._currentScene=null),this._nextScene=null,this._ecsAPI=null,this._logger.info("SceneManager destroyed")},t.dispose=function(){this.destroy()},o(e,[{key:"currentScene",get:function(){return this._currentScene}},{key:"api",get:function(){return this._ecsAPI}},{key:"hasScene",get:function(){return null!==this._currentScene}},{key:"hasPendingScene",get:function(){return null!==this._nextScene}}])}();exports.PluginState=void 0,(Kn=exports.PluginState||(exports.PluginState={})).NotInstalled="not_installed",Kn.Installed="installed",Kn.Failed="failed";var er=V("PluginManager"),tr=function(){function e(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}var t=e.prototype;return t.initialize=function(e,t){this._core=e,this._services=t,er.info("PluginManager initialized")},t.install=function(){var e=n(l().m((function e(t){var n,r;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(this._core&&this._services){e.n=1;break}throw new Error("PluginManager not initialized. Call initialize() first.");case 1:if(!this._plugins.has(t.name)){e.n=2;break}return er.warn("Plugin "+t.name+" is already installed"),e.a(2);case 2:return t.dependencies&&t.dependencies.length>0&&this._checkDependencies(t),n={name:t.name,version:t.version,state:exports.PluginState.NotInstalled,installedAt:Date.now()},this._metadata.set(t.name,n),e.p=3,er.info("Installing plugin: "+t.name+" v"+t.version),e.n=4,t.install(this._core,this._services);case 4:this._plugins.set(t.name,t),n.state=exports.PluginState.Installed,er.info("Plugin "+t.name+" installed successfully"),e.n=6;break;case 5:throw e.p=5,r=e.v,n.state=exports.PluginState.Failed,n.error=r instanceof Error?r.message:String(r),er.error("Failed to install plugin "+t.name+":",r),r;case 6:return e.a(2)}}),e,this,[[3,5]])})));return function(t){return e.apply(this,arguments)}}(),t.uninstall=function(){var e=n(l().m((function e(t){var n,r;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(n=this._plugins.get(t)){e.n=1;break}throw new Error("Plugin "+t+" is not installed");case 1:return this._checkDependents(t),e.p=2,er.info("Uninstalling plugin: "+t),e.n=3,n.uninstall();case 3:this._plugins.delete(t),this._metadata.delete(t),er.info("Plugin "+t+" uninstalled successfully"),e.n=5;break;case 4:throw e.p=4,r=e.v,er.error("Failed to uninstall plugin "+t+":",r),r;case 5:return e.a(2)}}),e,this,[[2,4]])})));return function(t){return e.apply(this,arguments)}}(),t.getPlugin=function(e){return this._plugins.get(e)},t.getMetadata=function(e){return this._metadata.get(e)},t.getAllPlugins=function(){return Array.from(this._plugins.values())},t.getAllMetadata=function(){return Array.from(this._metadata.values())},t.isInstalled=function(e){return this._plugins.has(e)},t._checkDependencies=function(e){if(e.dependencies){for(var t,n=[],r=s(e.dependencies);!(t=r()).done;){var i=t.value;this._plugins.has(i)||n.push(i)}if(n.length>0)throw new Error("Plugin "+e.name+" has unmet dependencies: "+n.join(", "))}},t._checkDependents=function(e){for(var t,n=[],r=s(this._plugins.values());!(t=r()).done;){var i=t.value;i.dependencies&&i.dependencies.includes(e)&&n.push(i.name)}if(n.length>0)throw new Error("Cannot uninstall plugin "+e+": it is required by "+n.join(", "))},t.dispose=function(){for(var e,t=s(Array.from(this._plugins.values()).reverse());!(e=t()).done;){var n=e.value;try{er.info("Disposing plugin: "+n.name),n.uninstall()}catch(e){er.error("Error disposing plugin "+n.name+":",e)}}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,er.info("PluginManager disposed")},e}(),nr=function(){function e(t){var n,r,i;if(void 0===t&&(t={}),e._instance=this,this._config=a({debug:!0,enableEntitySystems:!0},t),this._serviceContainer=new Gn,this._timerManager=new exports.TimerManager,this._serviceContainer.registerInstance(exports.TimerManager,this._timerManager),this._performanceMonitor=new M,this._serviceContainer.registerInstance(M,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new D,this._serviceContainer.registerInstance(D,this._poolManager),this._sceneManager=new $n,this._serviceContainer.registerInstance($n,this._sceneManager),this._pluginManager=new tr,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(tr,this._pluginManager),e.entitySystemsEnabled=null===(n=this._config.enableEntitySystems)||void 0===n||n,this.debug=null===(r=this._config.debug)||void 0===r||r,null!==(i=this._config.debugConfig)&&void 0!==i&&i.enabled){var o=this._config.debugConfig;this._debugManager=new fe(this._serviceContainer.resolve($n),this._serviceContainer.resolve(M),o),this._serviceContainer.registerInstance(fe,this._debugManager)}this.initialize()}e.create=function(t){if(void 0===t&&(t=!0),null==this._instance){var n="boolean"==typeof t?{debug:t,enableEntitySystems:!0}:t;this._instance=new e(n)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance},e.setScene=function(t){if(!this._instance)throw e._logger.warn("Core实例未创建,请先调用Core.create()"),new Error("Core实例未创建");return this._instance._sceneManager.setScene(t)},e.loadScene=function(t){this._instance?this._instance._sceneManager.loadScene(t):e._logger.warn("Core实例未创建,请先调用Core.create()")},e.update=function(t){this._instance?this._instance.updateInternal(t):e._logger.warn("Core实例未创建,请先调用Core.create()")},e.schedule=function(e,t,n,r){if(void 0===t&&(t=!1),!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");if(!r)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(e,t,n,r)},e.enableDebug=function(t){this._instance?(this._instance._debugManager?this._instance._debugManager.updateConfig(t):(this._instance._debugManager=new fe(this._instance._serviceContainer.resolve($n),this._instance._serviceContainer.resolve(M),t),this._instance._serviceContainer.registerInstance(fe,this._instance._debugManager)),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.installPlugin=function(){var e=n(l().m((function e(t){return l().w((function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.install(t);case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.uninstallPlugin=function(){var e=n(l().m((function e(t){return l().w((function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.uninstall(t);case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.getPlugin=function(e){if(this._instance)return this._instance._pluginManager.getPlugin(e)},e.isPluginInstalled=function(e){return!!this._instance&&this._instance._pluginManager.isInstalled(e)};var t=e.prototype;return t.initialize=function(){var t;e._logger.info("Core initialized",{debug:this.debug,entitySystemsEnabled:e.entitySystemsEnabled,debugEnabled:(null===(t=this._config.debugConfig)||void 0===t?void 0:t.enabled)||!1})},t.updateInternal=function(t){if(!e.paused){var n=this._performanceMonitor.startMonitoring("Core.update");m.update(t),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(m.deltaTime);var r=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(t),this._performanceMonitor.endMonitoring("Services.update",r,this._serviceContainer.getUpdatableCount()),this._poolManager.update(),this._sceneManager.update(),this._debugManager&&this._debugManager.onFrameUpdate(t),this._performanceMonitor.endMonitoring("Core.update",n)}},e.destroy=function(){this._instance&&(this._instance._debugManager&&this._instance._debugManager.stop(),this._instance._serviceContainer.clear(),e._logger.info("Core destroyed"),this._instance=null)},o(e,null,[{key:"Instance",get:function(){return this._instance}},{key:"services",get:function(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}},{key:"scene",get:function(){return this._instance?this._instance._sceneManager.currentScene:null}},{key:"ecsAPI",get:function(){return this._instance?this._instance._sceneManager.api:null}},{key:"isDebugEnabled",get:function(){var e;return(null===(e=this._instance)||void 0===e||null===(e=e._config.debugConfig)||void 0===e?void 0:e.enabled)||!1}}])}();nr.paused=!1,nr._instance=null,nr._logger=V("Core");var rr=function(e,t){this.func=e,this.context=t},ir=function(){function e(){this._messageTable=new Map}var t=e.prototype;return t.addObserver=function(e,t,n){var r=this._messageTable.get(e);r||(r=[],this._messageTable.set(e,r)),this.hasObserver(e,t)||r.push(new rr(t,n))},t.removeObserver=function(e,t){var n=this._messageTable.get(e);if(n){var r=n.findIndex((function(e){return e.func==t}));-1!=r&&n.splice(r,1)}},t.emit=function(e){var t=this._messageTable.get(e);if(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];for(var o,a=s(t);!(o=a()).done;){var c,u=o.value;(c=u.func).call.apply(c,[u.context].concat(r))}}},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}(),or=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)}}])}(),sr=function(){function e(){this.entityId=null,this.id=e._idGenerator++}var t=e.prototype;return t.onAddedToEntity=function(){},t.onRemovedFromEntity=function(){},e}();sr._idGenerator=0;var ar=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){this.processSystem()},t}(we),cr=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){},t}(we),ur=function(e){function t(t,n){var r;return(r=e.call(this,n)||this).acc=0,r.intervalRemainder=0,r.interval=t,r}u(t,e);var n=t.prototype;return n.onCheckProcessing=function(){return this.acc+=m.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)},n.getIntervalDelta=function(){return this.interval+this.intervalRemainder},t}(we),hr=function(){function e(){this.adapter=null,this.logger=V("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}(),lr=function(e){function t(t,n){var r,i,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.hasLoggedSyncMode=!1,c.platformAdapter=hr.getInstance().getAdapter();var u=null!==(r=n.workerCount)&&void 0!==r?r: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===(i=n.enableWorker)||void 0===i||i,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 r=t.prototype;return r.isWorkerSupported=function(){return this.platformAdapter.isWorkerSupported()},r.isSharedArrayBufferSupported=function(){return this.platformAdapter.isSharedArrayBufferSupported()},r.getMaxSystemWorkerCount=function(){return this.platformAdapter.getPlatformConfig().maxWorkerCount},r.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}},r.initializeWorkerPool=function(){try{for(var e=this.createWorkerScript(),t=[],n=(this.platformAdapter.getPlatformConfig().workerScriptPrefix||"")+e,r=0;r<this.config.workerCount;r++)try{var i=this.platformAdapter.createWorker(n,{name:"WorkerEntitySystem-"+r});t.push(i)}catch(e){throw this.logger.error("创建Worker "+r+" 失败:",e),e}this.workerPool=new fr(t,this.sharedBuffer)}catch(e){this.logger.error(this.systemName+": Worker池初始化失败",e),this.config.enableWorker=!1}},r.createWorkerScript=function(){var e,t=this.workerProcess.toString().match(/\{([\s\S]*)\}/);if(!t)throw new Error("无法解析workerProcess方法");var n=t[1],r=this.config.entityDataSize,i=(null===(e=this.getSharedArrayBufferProcessFunction)||void 0===e?void 0:e.call(this))||null,o="";if(i){var s=i.toString().match(/\{([\s\S]*)\}/);s&&(o=s[1])}return"\n // Worker脚本 - 支持SharedArrayBuffer\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = "+r+";\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 "},r.process=function(e){var t=this;if(!this.isProcessing){this.isProcessing=!0;try{this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?this.processWithSharedArrayBuffer(e).finally((function(){t.isProcessing=!1})):(this.config.useSharedArrayBuffer&&this.logger.info(this.systemName+": 本帧降级到传统Worker模式"),this.processWithWorker(e).finally((function(){t.isProcessing=!1}))):(this.hasLoggedSyncMode||(this.logger.info(this.systemName+": Worker不可用,使用同步处理"),this.hasLoggedSyncMode=!0),this.processSynchronously(e),this.isProcessing=!1)}catch(e){throw this.isProcessing=!1,this.logger.error(this.systemName+": 处理失败",e),e}}},r.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)}}(),r.processWithWorker=function(){var e=n(l().m((function e(t){var n,r,i,o,a,c,u,h,f,d,p,y,v,g,_=this;return l().w((function(e){for(;;)switch(e.n){case 0:for(n=[],r=0;r<t.length;r++)n[r]=this.extractEntityData(t[r]);return i=this.createBatches(n),o=m.deltaTime,a=i.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);!(f=h()).done;)for(d=f.value,p=s(d);!(y=p()).done;)v=y.value,u<t.length&&(g=t[u])&&v&&this.applyResult(g,v),u++;case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),r.processSynchronously=function(e){var t=this,n=e.map((function(e){return t.extractEntityData(e)})),r=m.deltaTime,i=this.workerProcess(n,r,this.config.systemConfig);i&&"function"==typeof i.then?i.then((function(n){e.forEach((function(e,r){t.applyResult(e,n[r])}))})):e.forEach((function(e,n){t.applyResult(e,i[n])}))},r.createBatches=function(e){var t=this.config.workerCount,n=[];if(this.config.entitiesPerWorker){for(var r=this.config.entitiesPerWorker,i=0;i<e.length;i+=r){var o=Math.min(i+r,e.length);n.push(e.slice(i,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},r.writeEntitiesToSharedBuffer=function(e){if(this.sharedFloatArray)for(var t=0;t<e.length&&t<this.config.maxEntities;t++){var n=e[t],r=this.extractEntityData(n),i=t*this.config.entityDataSize;this.writeEntityToBuffer(r,i)}},r.createSharedArrayBufferTasks=function(e){var t=[];if(this.config.entitiesPerWorker){var n=this.config.entitiesPerWorker,r=Math.ceil(e/n),i=this.config.workerCount;r>i&&this.logger.warn(this.systemName+": 需要 "+r+" 个任务处理 "+e+" 个实体(每任务 "+n+" 个),但只有 "+i+" 个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:m.deltaTime,systemConfig:this.config.systemConfig});t.push(c)}}else for(var u=Math.ceil(e/this.config.workerCount),h=0;h<this.config.workerCount;h++){var l=h*u,f=Math.min(l+u,e);if(l<e){var d=this.workerPool.executeSharedBuffer({startIndex:l,endIndex:f,deltaTime:m.deltaTime,systemConfig:this.config.systemConfig});t.push(d)}}return t},r.readResultsFromSharedBuffer=function(e){if(this.sharedFloatArray)for(var t=0;t<e.length&&t<this.config.maxEntities;t++){var n=e[t],r=t*this.config.entityDataSize,i=this.readEntityFromBuffer(r);i&&this.applyResult(n,i)}},r.updateConfig=function(e){var t=a({},this.config);if(void 0!==e.workerCount){var n=this.getMaxSystemWorkerCount(),r=Math.min(e.workerCount,n);e.workerCount>n&&this.logger.warn("请求 "+e.workerCount+" 个Worker,但系统最多支持 "+n+" 个。实际使用 "+r+" 个Worker。"),e.workerCount=r}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()},r.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())},r.reinitializeWorkerPool=function(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()},r.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}},r.onDestroy=function(){e.prototype.onDestroy.call(this),this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)},r.getLoggerName=function(){return"WorkerEntitySystem"},t}(we),fr=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=V("PlatformWorkerPool"),this.sharedBuffer=t,this.workers=e;for(var r=function(r){var i=e[r];i.onMessage((function(e){return n.handleWorkerMessage(r,e.data)})),i.onError((function(e){return n.handleWorkerError(r,e)})),t&&i.postMessage({type:"init",sharedBuffer:t})},i=0;i<e.length;i++)r(i)}var t=e.prototype;return t.executeSharedBuffer=function(e){var t=this;return new Promise((function(n,r){var i={id:"shared-task-"+ ++t.taskCounter,data:a({},e,{type:"shared"}),resolve:function(){return n()},reject:r};t.taskQueue.push(i),t.processQueue()}))},t.execute=function(e){var t=this;return new Promise((function(n,r){var i={id:"task-"+ ++t.taskCounter,data:e,resolve:function(e){n(e)},reject:r};t.taskQueue.push(i),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],r=n._currentTask;r&&(this.busyWorkers.delete(e),n._currentTask=null,t.error?r.reject(new Error(t.error)):r.resolve(t.result),this.processQueue())},t.handleWorkerError=function(e,t){var n=this.workers[e],r=n._currentTask;r&&(this.busyWorkers.delete(e),n._currentTask=null,r.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}(),dr=V("World"),pr=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(),dr.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 Vn;return"id"in n&&(n.id=e),"name"in n&&!n.name&&(n.name=e),this._scenes.set(e,n),n.initialize(),dr.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),dr.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(),dr.debug("在World '"+this.name+"' 中激活Scene: "+e)):(this._activeScenes.delete(e),dr.debug("在World '"+this.name+"' 中停用Scene: "+e)):dr.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(),dr.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(),dr.debug("从World '"+this.name+"' 中移除全局System: "+e.name),!0)},t.getGlobalSystem=function(e){for(var t,n=s(this._globalSystems);!(t=n()).done;){var r=t.value;if(r instanceof e)return r}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()}dr.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 r,i=s(this._globalSystems);!(r=i()).done;){var o=r.value;o.reset&&o.reset()}this._isActive=!1,dr.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,r=this._scenes.get(n);r&&r.update&&r.update()}this._config.autoCleanup&&this.shouldAutoCleanup()&&this.cleanup()}},t.destroy=function(){dr.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 r,i=s(this._globalSystems);!(r=i()).done;){var o=r.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 r=e.value;r.entities&&(t.totalEntities+=r.entities.count),r.systems&&(t.totalSystems+=r.systems.length)}return t},t.shouldAutoCleanup=function(){for(var e,t=Date.now(),n=s(this._scenes);!(e=n()).done;){var r=e.value,i=r[0],o=r[1];if(!this._activeScenes.has(i)&&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,r=e;n<r.length;n++){var i=r[n],o=this._scenes.get(i);o&&!this._activeScenes.has(i)&&o.entities&&0===o.entities.count&&t-this._createdAt>3e5&&(this.removeScene(i),dr.debug("自动清理空Scene: "+i+" 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}}])}(),yr=V("WorldManager"),mr=function(){function e(e){void 0===e&&(e={}),this._worlds=new Map,this._activeWorlds=new Set,this._cleanupTimer=null,this._isRunning=!1,this._config=a({maxWorlds:50,autoCleanup:!0,cleanupInterval:3e4,debug:!1},e),this._isRunning=!0,yr.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupInterval:this._config.cleanupInterval}),this.startCleanupTimer()}var t=e.prototype;return t.createWorld=function(e,t){if(!e||"string"!=typeof e||""===e.trim())throw new Error("World ID不能为空");if(this._worlds.has(e))throw new Error("World ID '"+e+"' 已存在");if(this._worlds.size>=this._config.maxWorlds)throw new Error("已达到最大World数量限制: "+this._config.maxWorlds);var n=a({name:e,debug:this._config.debug},t),r=new pr(n);return this._worlds.set(e,r),yr.info("创建World: "+e,{config:n}),r},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),yr.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(),yr.debug("激活World: "+e)):(this._activeWorlds.delete(e),n.stop(),yr.debug("停用World: "+e)):yr.warn("World '"+e+"' 不存在")},t.isWorldActive=function(e){return this._activeWorlds.has(e)},t.updateAll=function(){if(this._isRunning)for(var e,t=s(this._activeWorlds);!(e=t()).done;){var n=e.value,r=this._worlds.get(n);r&&r.isActive&&(r.updateGlobalSystems(),r.updateScenes())}},t.getActiveWorlds=function(){for(var e,t=[],n=s(this._activeWorlds);!(e=n()).done;){var r=e.value,i=this._worlds.get(r);i&&t.push(i)}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)}yr.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)}yr.info("停止所有World")},t.findWorlds=function(e){for(var t,n=[],r=s(this._worlds.values());!(t=r()).done;){var i=t.value;e(i)&&n.push(i)}return n},t.findWorldByName=function(e){for(var t,n=s(this._worlds.values());!(t=n()).done;){var r=t.value;if(r.name===e)return r}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 r=e.value,i=r[0],o=r[1],c=o.getStats();t.totalScenes+=c.totalSystems,t.totalEntities+=c.totalEntities,t.totalSystems+=c.totalSystems,t.worlds.push(a({id:i,name:o.name,isActive:this._activeWorlds.has(i),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],r=t[1];return{id:n,isActive:e._activeWorlds.has(n),status:r.getStatus()}}))})},t.cleanup=function(){for(var e,t=[],n=s(this._worlds);!(e=n()).done;){var r=e.value,i=r[0],o=r[1];this.shouldCleanupWorld(o)&&t.push(i)}for(var a=0,c=t;a<c.length;a++){var u=c[a];this.removeWorld(u)}return t.length>0&&yr.debug("清理了 "+t.length+" 个World"),t.length},t.destroy=function(){yr.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,yr.info("WorldManager已销毁")},t.startCleanupTimer=function(){var e=this;this._config.autoCleanup&&!this._cleanupTimer&&(this._cleanupTimer=setInterval((function(){e.cleanup()}),this._config.cleanupInterval),yr.debug("启动World清理定时器,间隔: "+this._config.cleanupInterval+"ms"))},t.stopCleanupTimer=function(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null,yr.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)}}])}(),vr=function(){function e(){}return e.registerComponentMigration=function(e,t,n,r){this.componentMigrations.has(e)||this.componentMigrations.set(e,new Map),this.componentMigrations.get(e).set(t,r)},e.registerSceneMigration=function(e,t,n){this.sceneMigrations.set(e,n)},e.migrateComponent=function(e,t){var n=e.version;if(n===t)return e;var r=this.componentMigrations.get(e.type);if(!r)return console.warn("No migration path found for component "+e.type),e;for(var i=a({},e),o=n;o<t;){var s=r.get(o);if(!s){console.warn("Missing migration from version "+o+" to "+(o+1)+" for "+e.type);break}i.data=s(i.data,o,o+1),o++}return i.version=o,i},e.migrateScene=function(e,t){var n=e.version;if(n===t)return e;for(var r=a({},e),i=n;i<t;){var o=this.sceneMigrations.get(i);if(!o){console.warn("Missing scene migration from version "+i+" to "+(i+1));break}r=o(r,i,i+1),i++}return r.version=i,r=this.migrateSceneComponents(r)},e.migrateSceneComponents=function(e){var t=this,n=a({},e);return n.entities=e.entities.map((function(n){return a({},n,{components:n.components.map((function(n){var r=e.componentTypeRegistry.find((function(e){return e.typeName===n.type}));return r&&r.version!==n.version?t.migrateComponent(n,r.version):n})),children:t.migrateEntitiesComponents(n.children,e.componentTypeRegistry)})})),n},e.migrateEntitiesComponents=function(e,t){var n=this;return e.map((function(e){return a({},e,{components:e.components.map((function(e){var r=t.find((function(t){return t.typeName===e.type}));return r&&r.version!==e.version?n.migrateComponent(e,r.version):e})),children:n.migrateEntitiesComponents(e.children,t)})}))},e.clearMigrations=function(){this.componentMigrations.clear(),this.sceneMigrations.clear()},e.getComponentMigrationPath=function(e){var t=this.componentMigrations.get(e);return t?Array.from(t.keys()).sort((function(e,t){return e-t})):[]},e.getSceneMigrationPath=function(){return Array.from(this.sceneMigrations.keys()).sort((function(e,t){return e-t}))},e.canMigrateComponent=function(e,t,n){if(t===n)return!0;var r=this.componentMigrations.get(e);if(!r)return!1;for(var i=t;i<n;i++)if(!r.has(i))return!1;return!0},e.canMigrateScene=function(e,t){if(e===t)return!0;for(var n=e;n<t;n++)if(!this.sceneMigrations.has(n))return!1;return!0},e}();vr.componentMigrations=new Map,vr.sceneMigrations=new Map;var gr=function(){function e(){this.fromVersion=1,this.toVersion=2}var t=e.prototype;return t.forComponent=function(e){return this.componentType=e,this},t.fromVersionToVersion=function(e,t){return this.fromVersion=e,this.toVersion=t,this},t.migrate=function(e){this.componentType?vr.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):vr.registerSceneMigration(this.fromVersion,this.toVersion,e)},e}();var _r=function(){function e(e){this._entity=e}var t=e.prototype;return t.with=function(e){return this._entity.addComponent(e),this},t.withConfigured=function(e,t){return this._entity.addComponent(e),t(e),this},t.withTag=function(e){return this._entity.tag=e,this},t.withName=function(e){return this._entity.name=e,this},t.withActive=function(e){return this._entity.active=e,this},t.withEnabled=function(e){return this._entity.enabled=e,this},t.withUpdateOrder=function(e){return this._entity.updateOrder=e,this},t.withChild=function(e){return this._entity.addChild(e),this},t.build=function(){return this._entity},o(e,[{key:"entity",get:function(){return this._entity}}])}();var Sr=function(){function e(){}return e.getType=function(e){return e.constructor},e}(),Er=function(){function e(){}return e.toNumber=function(e){return null==e?0:Number(e)},e}();function Cr(e){return"function"==typeof e&&e.prototype instanceof sr}var br=function(){function e(){}return e.detect=function(){var e,t=[],n="unknown",r=!1;return"undefined"!=typeof globalThis&&t.push("globalThis"),"undefined"!=typeof window&&t.push("window"),"undefined"!=typeof self&&t.push("self"),this.isNodeJS()?(n="nodejs",r=!0,e="NodeAdapter",t.push("nodejs","process","require")):this.isWeChatMiniGame()?(n="wechat-minigame",r=!0,e="WeChatMiniGameAdapter",t.push("wx","wechat-minigame")):this.isByteDanceMiniGame()?(n="bytedance-minigame",r=!0,e="ByteDanceMiniGameAdapter",t.push("tt","bytedance-minigame")):this.isAlipayMiniGame()?(n="alipay-minigame",r=!0,e="AlipayMiniGameAdapter",t.push("my","alipay-minigame")):this.isBaiduMiniGame()?(n="baidu-minigame",r=!0,e="BaiduMiniGameAdapter",t.push("swan","baidu-minigame")):this.isBrowser()&&(n="browser",r=!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:r,features:t,adapterClass:e}},e.isWeChatMiniGame=function(){if(void 0!==globalThis.wx){var e=globalThis.wx;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1},e.isByteDanceMiniGame=function(){if(void 0!==globalThis.tt){var e=globalThis.tt;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1},e.isNodeJS=function(){try{return!("undefined"==typeof process||!process.versions||!process.versions.node||"undefined"==typeof require||"undefined"==typeof module||"undefined"==typeof exports||"undefined"!=typeof window||"undefined"!=typeof document)}catch(e){return!1}},e.isAlipayMiniGame=function(){if(void 0!==globalThis.my){var e=globalThis.my;return!(!e.getSystemInfo||!e.createCanvas)}return!1},e.isBaiduMiniGame=function(){if(void 0!==globalThis.swan){var e=globalThis.swan;return!(!e.getSystemInfo||!e.createCanvas)}return!1},e.isBrowser=function(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location},e.getDetailedInfo=function(){var e={};return e.userAgent="undefined"!=typeof navigator?navigator.userAgent:"unknown",e.platform="undefined"!=typeof navigator?navigator.platform:"unknown",e.globalObjects={window:"undefined"!=typeof window,document:"undefined"!=typeof document,navigator:"undefined"!=typeof navigator,wx:void 0!==globalThis.wx,tt:void 0!==globalThis.tt,my:void 0!==globalThis.my,swan:void 0!==globalThis.swan},e.workerSupport={Worker:"undefined"!=typeof Worker,SharedWorker:"undefined"!=typeof SharedWorker,ServiceWorker:"undefined"!=typeof navigator&&"serviceWorker"in navigator,SharedArrayBuffer:"undefined"!=typeof SharedArrayBuffer,crossOriginIsolated:"undefined"!=typeof self&&self.crossOriginIsolated},e.performance={performanceNow:"undefined"!=typeof performance&&"function"==typeof performance.now,hardwareConcurrency:"undefined"!=typeof navigator?navigator.hardwareConcurrency:void 0},e.apiSupport={Blob:"undefined"!=typeof Blob,URL:"undefined"!=typeof URL,createObjectURL:"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL,ArrayBuffer:"undefined"!=typeof ArrayBuffer,TypedArrays:"undefined"!=typeof Float32Array},e},e}();exports.AutoTyped=function(e){return function(t,n){var r=String(n);t.constructor.__autoTypedFields||(t.constructor.__autoTypedFields=new Map),t.constructor.__autoTypedFields.set(r,e||{})}},exports.BitMask64Utils=O,exports.Bits=B,exports.COMPONENT_TYPE_NAME=P,exports.Colors=H,exports.Component=sr,exports.ComponentDataCollector=ue,exports.ComponentPool=ae,exports.ComponentPoolManager=ce,exports.ComponentRegistry=ye,exports.ComponentSerializer=Ke,exports.ComponentSparseSet=Me,exports.ComponentStorage=me,exports.ComponentTypeManager=re,exports.ConsoleLogger=j,exports.Core=nr,exports.DebugManager=fe,exports.DeepCopy=function(e,t){var n=String(t);e.constructor.__deepCopyFields||(e.constructor.__deepCopyFields=new Set),e.constructor.__deepCopyFields.add(n)},exports.ECSComponent=function(e){return function(t){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return t[P]=e,t}},exports.ECSFluentAPI=Zn,exports.ECSSystem=function(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return n[z]=e,t&&(n.__systemMetadata__=t),n}},exports.ENTITY_REF_METADATA=$,exports.EVENT_TYPES=Ne,exports.Emitter=ir,exports.EnableSoA=function(e){return e.__enableSoA=!0,e},exports.Entity=_e,exports.EntityDataCollector=ie,exports.EntityList=Ee,exports.EntityProcessorList=Ae,exports.EntityRef=function(){return function(e,t){var n=e.constructor,r=n[$];r||(r={properties:new Set},n[$]=r);var i="symbol"==typeof t?t.toString():t;r.properties.add(i),Object.defineProperty(e,t,{get:function(){return te(this).get(i)||null},set:function(e){var t=te(this),n=t.get(i)||null;if(n!==e){var r=null!==this.entityId?Z(this.entityId):null;if(r&&r.referenceTracker){var o=r.referenceTracker;if(n&&o.unregisterReference(n,this,i),e){var s;if(e.scene!==r)return void K.error("Cannot reference Entity from different Scene. Entity: "+e.name+", Scene: "+((null===(s=e.scene)||void 0===s?void 0:s.name)||"null"));if(e.isDestroyed)return K.warn("Cannot reference destroyed Entity: "+e.name),void t.set(i,null);o.registerReference(e,this,i)}t.set(i,e)}else t.set(i,e)}},enumerable:!0,configurable:!0})}},exports.EntitySerializer=$e,exports.EntitySystem=we,exports.EventBus=Le,exports.EventTypeValidator=We,exports.Float32=function(e,t){var n=String(t);e.constructor.__float32Fields||(e.constructor.__float32Fields=new Set),e.constructor.__float32Fields.add(n)},exports.Float64=function(e,t){var n=String(t);e.constructor.__float64Fields||(e.constructor.__float64Fields=new Set),e.constructor.__float64Fields.add(n)},exports.FuncPack=rr,exports.GlobalEventBus=Fe,exports.GlobalManager=or,exports.HighPrecision=function(e,t){var n=String(t);e.constructor.__highPrecisionFields||(e.constructor.__highPrecisionFields=new Set),e.constructor.__highPrecisionFields.add(n)},exports.IdentifierPool=Ce,exports.IgnoreSerialization=function(){return function(e,t){var n=e.constructor,r=n[je];r||(r={options:{version:1},fields:new Map,ignoredFields:new Set},n[je]=r),r.ignoredFields.add(t)}},exports.IncrementalSerializer=Hn,exports.Inject=function(e){return function(t,n,r){var i=_.get(t);i||(i=new Map,_.set(t,i)),i.set(r,e)}},exports.Injectable=function(){return function(e){return g.set(e,{injectable:!0,dependencies:[]}),e}},exports.Int16=function(e,t){var n=String(t);e.constructor.__int16Fields||(e.constructor.__int16Fields=new Set),e.constructor.__int16Fields.add(n)},exports.Int32=function(e,t){var n=String(t);e.constructor.__int32Fields||(e.constructor.__int32Fields=new Set),e.constructor.__int32Fields.add(n)},exports.Int8=function(e,t){var n=String(t);e.constructor.__int8Fields||(e.constructor.__int8Fields=new Set),e.constructor.__int8Fields.add(n)},exports.IntervalSystem=ur,exports.Logger=G,exports.LoggerManager=q,exports.Matcher=be,exports.MigrationBuilder=gr,exports.NumberExtension=Er,exports.PassiveSystem=cr,exports.PerformanceDataCollector=se,exports.PerformanceMonitor=M,exports.PlatformDetector=br,exports.PlatformManager=hr,exports.PluginManager=tr,exports.Pool=I,exports.PoolManager=D,exports.ProcessingSystem=ar,exports.QuerySystem=Be,exports.ReferenceTracker=X,exports.SERIALIZABLE_METADATA=je,exports.SERIALIZE_FIELD=qe,exports.SERIALIZE_OPTIONS=Ge,exports.SYSTEM_TYPE_NAME=z,exports.Scene=Vn,exports.SceneDataCollector=he,exports.SceneManager=$n,exports.SceneSerializer=Un,exports.Serializable=function(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");var n=t[je];return n?n.options=e:(n={options:e,fields:new Map,ignoredFields:new Set},t[je]=n),t}},exports.Serialize=Ve,exports.SerializeArray=function(e,t){var n=String(t);e.constructor.__serializeArrayFields||(e.constructor.__serializeArrayFields=new Set),e.constructor.__serializeArrayFields.add(n)},exports.SerializeAsMap=function(){return function(e,t){Ve({serializer:function(e){return e instanceof Map?Array.from(e.entries()):null},deserializer:function(e){return Array.isArray(e)?new Map(e):new Map}})(e,t)}},exports.SerializeAsSet=function(){return function(e,t){Ve({serializer:function(e){return e instanceof Set?Array.from(e):null},deserializer:function(e){return Array.isArray(e)?new Set(e):new Set}})(e,t)}},exports.SerializeMap=function(e,t){var n=String(t);e.constructor.__serializeMapFields||(e.constructor.__serializeMapFields=new Set),e.constructor.__serializeMapFields.add(n)},exports.SerializeSet=function(e,t){var n=String(t);e.constructor.__serializeSetFields||(e.constructor.__serializeSetFields=new Set),e.constructor.__serializeSetFields.add(n)},exports.ServiceContainer=Gn,exports.SoAStorage=pe,exports.SparseSet=Te,exports.SystemDataCollector=oe,exports.Time=m,exports.Timer=v,exports.TypeInference=de,exports.TypeSafeEventSystem=ze,exports.TypeUtils=Sr,exports.TypedEntityBuilder=_r,exports.TypedQueryBuilder=He,exports.TypedQueryResult=Ue,exports.Uint16=function(e,t){var n=String(t);e.constructor.__uint16Fields||(e.constructor.__uint16Fields=new Set),e.constructor.__uint16Fields.add(n)},exports.Uint32=function(e,t){var n=String(t);e.constructor.__uint32Fields||(e.constructor.__uint32Fields=new Set),e.constructor.__uint32Fields.add(n)},exports.Uint8=function(e,t){var n=String(t);e.constructor.__uint8Fields||(e.constructor.__uint8Fields=new Set),e.constructor.__uint8Fields.add(n)},exports.Uint8Clamped=function(e,t){var n=String(t);e.constructor.__uint8ClampedFields||(e.constructor.__uint8ClampedFields=new Set),e.constructor.__uint8ClampedFields.add(n)},exports.Updatable=E,exports.VersionMigrationManager=vr,exports.WebSocketManager=le,exports.WorkerEntitySystem=lr,exports.World=pr,exports.WorldManager=mr,exports.addAndConfigure=function(e,t,n){return e.addComponent(t),n(t),e},exports.buildEntity=function(e){return new _r(e)},exports.createECSAPI=Xn,exports.createInstance=b,exports.createLogger=V,exports.createQuery=function(){return new He},exports.getBasicWorkerConfig=function(){return hr.getInstance().getBasicWorkerConfig()},exports.getComponentInstanceTypeName=F,exports.getComponentTypeName=W,exports.getComponents=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 n.map((function(t){return e.getComponent(t)}))},exports.getCurrentAdapter=function(){return hr.getInstance().getAdapter()},exports.getEntityRefMetadata=ne,exports.getFullPlatformConfig=function(){return hr.getInstance().getFullPlatformConfig()},exports.getOrAddComponent=function(e,t,n){var r=e.getComponent(t);return r||(r=n(),e.addComponent(r)),r},exports.getSceneByEntityId=Z,exports.getSerializationMetadata=Ye,exports.getSystemInstanceTypeName=U,exports.getSystemMetadata=N,exports.getSystemTypeName=L,exports.getUpdatableMetadata=A,exports.hasAdapter=function(){return hr.getInstance().hasAdapter()},exports.hasAnyComponent=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 n.some((function(t){return e.hasComponent(t)}))},exports.hasComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return n.every((function(t){return e.hasComponent(t)}))},exports.hasEntityRef=function(e){return null!==ne(e)},exports.isComponentArray=function(e){return e.every(Cr)},exports.isComponentType=Cr,exports.isSerializable=function(e){return null!==Ye(e)},exports.isUpdatable=w,exports.queryFor=function(e){return new He([e])},exports.queryForAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new He(t)},exports.registerInjectable=function(e,t,n){if(void 0===n&&(n=!0),!C(t))throw new Error(t.name+" is not marked as @Injectable(). Please add @Injectable() decorator to the class.");var r=function(e){return b(t,e)};n?e.registerSingleton(t,r):e.registerTransient(t,r)},exports.registerPlatformAdapter=function(e){return hr.getInstance().registerAdapter(e)},exports.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" (id: "+e.id+")");return n},exports.resetLoggerColors=function(){q.getInstance().resetColors()},exports.setGlobalLogLevel=function(e){q.getInstance().setGlobalLevel(e)},exports.setLoggerColors=function(e){q.getInstance().setGlobalColors(e)},exports.supportsFeature=function(e){return hr.getInstance().supportsFeature(e)},exports.tryGetComponent=function(e,t){var n=e.getComponent(t);return null!==n?n:void 0},exports.updateComponent=function(e,t,n){var r=e.getComponent(t);return!!r&&(Object.assign(r,n),!0)};
3
+ var e,t,n="function"==typeof Symbol?Symbol:{},r=n.iterator||"@@iterator",i=n.toStringTag||"@@toStringTag";function o(n,r,i,o){var c=r&&r.prototype instanceof a?r:a,u=Object.create(c.prototype);return f(u,"_invoke",function(n,r,i){var o,a,c,u=0,h=i||[],l=!1,f={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,n){return o=t,a=0,c=e,f.n=n,s}};function d(n,r){for(a=n,c=r,t=0;!l&&u&&!i&&t<h.length;t++){var i,o=h[t],d=f.p,p=o[2];n>3?(i=p===r)&&(c=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=e):o[0]<=d&&((i=n<2&&d<o[1])?(a=0,f.v=r,f.n=o[1]):d<p&&(i=n<3||o[0]>r||r>p)&&(o[4]=n,o[5]=r,f.n=p,a=0))}if(i||n>1)return s;throw l=!0,r}return function(i,h,p){if(u>1)throw TypeError("Generator is already running");for(l&&1===h&&d(h,p),a=h,c=p;(t=a<2?e:c)||!l;){o||(a?a<3?(a>1&&(f.n=-1),d(a,c)):f.n=c:f.v=c);try{if(u=2,o){if(a||(i="next"),t=o[i]){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 '"+i+"' method"),a=1);o=e}else if((t=(l=f.n<0)?c:n.call(r,f))!==s)break}catch(t){o=e,a=1,c=t}finally{u=1}}return{value:t,done:l}}}(n,i,o),!0),u}var s={};function a(){}function c(){}function u(){}t=Object.getPrototypeOf;var h=[][r]?t(t([][r]())):(f(t={},r,(function(){return this})),t),d=u.prototype=a.prototype=Object.create(h);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,f(e,i,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=u,f(d,"constructor",u),f(u,"constructor",c),c.displayName="GeneratorFunction",f(u,i,"GeneratorFunction"),f(d),f(d,i,"Generator"),f(d,r,(function(){return this})),f(d,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:o,m:p}})()}function f(e,t,n,r){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}f=function(e,t,n,r){function o(t,n){f(e,t,(function(e){return this._invoke(t,n,e)}))}t?i?i(e,t,{value:n,enumerable:!r,configurable:!r,writable:!r}):e[t]=n:(o("next",0),o("throw",1),o("return",2))},f(e,t,n,r)}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function p(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function y(e){var t="function"==typeof Map?new Map:void 0;return y=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return r(e,arguments,c(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),d(n,e)},y(e)}"function"==typeof SuppressedError&&SuppressedError;var m=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}();m.deltaTime=0,m.unscaledDeltaTime=0,m.totalTime=0,m.unscaledTotalTime=0,m.timeScale=1,m.frameCount=0;var v,g=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+=m.deltaTime,this._isDone},t.initialize=function(e,t,n,r){this._timeInSeconds=e,this._repeats=t,this.context=n,this._onTime=r.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}}])}(),_=new WeakMap,S=new WeakMap,E=new WeakMap;function C(e){return void 0===e&&(e=0),function(t){var n=t.prototype;if(!n||"function"!=typeof n.update)throw new Error("@Updatable() decorator requires class "+t.name+" to implement IUpdatable interface with update() method. Please add 'implements IUpdatable' and define update(deltaTime?: number): void method.");return E.set(t,{updatable:!0,priority:e}),t}}function b(e){var t,n=_.get(e);return null!==(t=null==n?void 0:n.injectable)&&void 0!==t&&t}function w(e,t){for(var n,i=(n=e,S.get(n)||new Map),o=[],s=e.length,a=0;a<s;a++){var c=i.get(a);if(c){if("string"==typeof c||"symbol"==typeof c)throw new Error("String and Symbol service identifiers are not yet supported in constructor injection. Please use class types for "+e.name+" parameter "+a);o.push(t.resolve(c))}else o.push(void 0)}return r(e,o)}function A(e){var t,n=E.get(e);return null!==(t=null==n?void 0:n.updatable)&&void 0!==t&&t}function T(e){return E.get(e)}exports.TimerManager=function(){function e(){this._timers=[]}var t=e.prototype;return t.update=function(){for(var e=this._timers.length-1;e>=0;e--)this._timers[e].tick()&&(this._timers[e].unload(),this._timers.splice(e,1))},t.schedule=function(e,t,n,r){var i=new g;return i.initialize(e,t,n,r),this._timers.push(i),i},t.dispose=function(){for(var e,t=s(this._timers);!(e=t()).done;){e.value.unload()}this._timers=[]},e}(),exports.TimerManager=function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s}([C()],exports.TimerManager),exports.PerformanceWarningType=void 0,(v=exports.PerformanceWarningType||(exports.PerformanceWarningType={})).HIGH_EXECUTION_TIME="high_execution_time",v.HIGH_MEMORY_USAGE="high_memory_usage",v.HIGH_CPU_USAGE="high_cpu_usage",v.FREQUENT_GC="frequent_gc",v.LOW_FPS="low_fps",v.HIGH_ENTITY_COUNT="high_entity_count";var x=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 r=performance.now(),i=r-t,o={name:e,executionTime:i,entityCount:n,averageTimePerEntity:n>0?i/n:0,lastUpdateTime:r};this._systemData.set(e,o),this.updateStats(e,i)}},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 r=[].concat(e.recentTimes).sort((function(e,t){return e-t})),i=r.length;e.percentile95=r[Math.floor(.95*i)]||0,e.percentile99=r[Math.floor(.99*i)]||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 r=t.value,i=r[0],o=r[1],a=this._systemData.get(i);e.push("System: "+i),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=[],r=s(this._systemData.entries());!(t=r()).done;){var i=t.value,o=i[0],a=i[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 r=t.value;r.recentTimes.length>e;)r.recentTimes.shift()},t.dispose=function(){this._systemData.clear(),this._systemStats.clear(),this._warnings=[],this._fpsHistory=[],this._memoryHistory=[],this._isEnabled=!1},o(e,[{key:"isEnabled",get:function(){return this._isEnabled}}])}(),M=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,r){void 0===n&&(n=100),void 0===r&&(r=1024);var i=this._pools.get(t);return i||(i=new e((function(){return new t}),n,r),this._pools.set(t,i)),i};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 r=this._createFn();r.reset(),this._objects.push(r),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 r=e.value,i=r[0],o=r[1];t[i.name||i.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,r=Object.entries(e);n<r.length;n++){var i=r[n],o=i[0],s=i[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}();M._pools=new Map;var I,k=function(){function e(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}var t=e.prototype;return t.registerPool=function(e,t){this.pools.set(e,t)},t.getPool=function(e){return this.pools.get(e)||null},t.update=function(){var e=Date.now();e-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=e)},t.createPool=function(e,t,n,r){void 0===n&&(n=100),void 0===r&&(r=1024);var i=this.pools.get(e);return i||(i=new M(t,n,r),this.pools.set(e,i)),i},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 r=e.value,i=r[0],o=r[1];t.set(i,o.getStats())}return t},t.getGlobalStats=function(){for(var e,t=0,n=0,r=0,i=0,o=0,a=0,c=s(this.pools.values());!(e=c()).done;){var u=e.value.getStats();t+=u.size,n+=u.maxSize,r+=u.totalCreated,i+=u.totalObtained,o+=u.totalReleased,a+=u.estimatedMemoryUsage}return{size:t,maxSize:n,totalCreated:r,totalObtained:i,totalReleased:o,hitRate:0===i?0:(i-r)/i,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,r=s(this.pools);!(n=r()).done;){var i=n.value,o=i[0],a=i[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,r=n.getStats(),i=Math.floor(.2*r.maxSize);n.prewarm(i)}},t.reset=function(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0},t.dispose=function(){this.reset()},e}();!function(e){e[e.LOW=0]="LOW",e[e.HIGH=1]="HIGH"}(I||(I={}));var D=function(){function e(){}return e.create=function(t){if(t<0)throw new Error("Bit index "+t+" out of range [0, ∞)");var n={base:[0,0],segments:void 0};return e.setBit(n,t),n},e.fromNumber=function(e){return{base:[e>>>0,0],segments:void 0}},e.hasAny=function(e,t){var n=t.base,r=e.base,i=t.segments,o=e.segments,s=0!==(r[I.LOW]&n[I.LOW])||0!==(r[I.HIGH]&n[I.HIGH]);return!s&&i&&o?o.some((function(e,t){return 0!==(e[I.LOW]&i[t][I.LOW])||0!==(e[I.HIGH]&i[t][I.HIGH])})):s},e.hasAll=function(e,t){var n,r=e.base,i=t.base,o=e.segments,s=t.segments,a=(r[I.LOW]&i[I.LOW])===i[I.LOW]&&(r[I.HIGH]&i[I.HIGH])===i[I.HIGH];if(!a||!s)return a;var c=null!==(n=null==o?void 0:o.length)&&void 0!==n?n:0;if(o)for(var u=0;u<Math.min(c,s.length);u++)if((o[u][I.LOW]&s[u][I.LOW])!==s[u][I.LOW]||(o[u][I.HIGH]&s[u][I.HIGH])!==s[u][I.HIGH])return!1;for(var h=c;h<s.length;h++)if(0!==s[h][I.LOW]||0!==s[h][I.HIGH])return!1;return!0},e.hasNone=function(e,t){var n=e.base,r=t.base,i=e.segments,o=t.segments,s=0===(n[I.LOW]&r[I.LOW])&&0===(n[I.HIGH]&r[I.HIGH]);return i&&s&&o?i.every((function(e,t){return 0===(e[I.LOW]&o[t][I.LOW])&&0===(e[I.HIGH]&o[t][I.HIGH])})):s},e.isZero=function(e){var t=0===e.base[I.LOW]&&0===e.base[I.HIGH];return e.segments&&t?e.segments.every((function(e){return 0===e[I.LOW]&&0===e[I.HIGH]})):t},e.equals=function(e,t){var n,r,i=e.base[I.LOW]===t.base[I.LOW]&&e.base[I.HIGH]===t.base[I.HIGH];if(!i||!e.segments&&!t.segments)return i;for(var o=null!==(n=e.segments)&&void 0!==n?n:[],s=null!==(r=t.segments)&&void 0!==r?r:[],a=0;a<Math.max(o.length,s.length);a++){var c=o[a],u=s[a];if(c&&!u){if(0!==c[I.LOW]||0!==c[I.HIGH])return!1}else if(!c&&u){if(0!==u[I.LOW]||0!==u[I.HIGH])return!1}else if(c[I.LOW]!==u[I.LOW]||c[I.HIGH]!==u[I.HIGH])return!1}return!0},e.setBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var r=e.getSegmentByBitIndex(t,n),i=63&n;i<32?r[I.LOW]|=1<<i:r[I.HIGH]|=1<<i-32},e.getBit=function(t,n){if(n<0)return!1;var r=e.getSegmentByBitIndex(t,n,!1);if(!r)return!1;var i=63&n;return i<32?!!(r[I.LOW]&1<<i):!!(r[I.HIGH]&1<<i-32)},e.clearBit=function(t,n){if(n<0)throw new Error("Bit index "+n+" out of range [0, 63]");var r=e.getSegmentByBitIndex(t,n,!1);if(r){var i=63&n;i<32?r[I.LOW]&=~(1<<i):r[I.HIGH]&=~(1<<i-32)}},e.orInPlace=function(e,t){e.base[I.LOW]|=t.base[I.LOW],e.base[I.HIGH]|=t.base[I.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var r=e.segments;r.length<n.length;)r.push([0,0]);for(var i=0;i<n.length;i++)r[i][I.LOW]|=n[i][I.LOW],r[i][I.HIGH]|=n[i][I.HIGH]}},e.andInPlace=function(e,t){e.base[I.LOW]&=t.base[I.LOW],e.base[I.HIGH]&=t.base[I.HIGH];var n=t.segments;if(n&&n.length>0){e.segments||(e.segments=[]);for(var r=e.segments;r.length<n.length;)r.push([0,0]);for(var i=0;i<n.length;i++)r[i][I.LOW]&=n[i][I.LOW],r[i][I.HIGH]&=n[i][I.HIGH]}},e.xorInPlace=function(e,t){e.base[I.LOW]^=t.base[I.LOW],e.base[I.HIGH]^=t.base[I.HIGH];var n=t.segments;if(n&&0!=n.length){e.segments||(e.segments=[]);for(var r=e.segments;r.length<n.length;)r.push([0,0]);for(var i=0;i<n.length;i++)r[i][I.LOW]^=n[i][I.LOW],r[i][I.HIGH]^=n[i][I.HIGH]}},e.clear=function(e){e.base[I.LOW]=0,e.base[I.HIGH]=0;for(var t=0;t<(null!==(n=null===(r=e.segments)||void 0===r?void 0:r.length)&&void 0!==n?n:0);t++){var n,r,i=e.segments[t];i[I.LOW]=0,i[I.HIGH]=0}},e.copy=function(t,n){if(e.clear(n),n.base[I.LOW]=t.base[I.LOW],n.base[I.HIGH]=t.base[I.HIGH],t.segments&&0!=t.segments.length)if(n.segments){for(var r=t.segments.length-n.segments.length,i=0;i<r;i++)n.segments.push([0,0]);for(var o=0;o<length;o++){var s=n.segments[o],a=t.segments[o];s[I.LOW]=a[I.LOW],s[I.HIGH]=a[I.HIGH]}}else n.segments=t.segments.map((function(e){return[].concat(e)}))},e.clone=function(e){return{base:e.base.slice(),segments:e.segments?e.segments.map((function(e){return[].concat(e)})):void 0}},e.toString=function(e,t,n){var r,i;void 0===t&&(t=2),void 0===n&&(n=!1),2!=t&&16!=t&&(t=2);var o=null!==(r=null===(i=e.segments)||void 0===i?void 0:i.length)&&void 0!==r?r:0,s="";if(n){var a=0;a=2===t?66:19;for(var c=0;c<=o;c++){s+=(0===c?"0 (Base):":c+" ("+64*c+"):").toString().padEnd(a)}s+="\n"}for(var u=-1;u<o;u++){var h="",l=-1==u?e.base:e.segments[u],f=l[I.HIGH],d=l[I.LOW];if(2==t){h=f.toString(2).padStart(32,"0")+"_"+d.toString(2).padStart(32,"0")}else{var p=f?f.toString(16).toUpperCase():"";n&&(p=p.padStart(8,"0"));var y=d.toString(16).toUpperCase();p&&(y=y.padStart(8,"0")),h="0x"+p+y}s+=-1===u?h:" "+h}return s},e.popCount=function(e){for(var t=0,n=-1;n<(null!==(r=null===(i=e.segments)||void 0===i?void 0:i.length)&&void 0!==r?r:0);n++){for(var r,i,o=-1==n?e.base:e.segments[n],s=o[I.LOW],a=o[I.HIGH];s;)s&=s-1,t++;for(;a;)a&=a-1,t++}return t},e.getSegmentByBitIndex=function(e,t,n){if(void 0===n&&(n=!0),t<=63)return e.base;var r=e.segments;if(!r){if(!n)return null;r=e.segments=[]}var i=(t>>6)-1;if(r.length<=i){if(!n)return null;for(var o=i-r.length+1,s=0;s<o;s++)r.push([0,0])}return r[i]},e}();D.ZERO={base:[0,0],segments:void 0};var O,R=function(){function e(e){if(e&&"object"==typeof e)this._value=D.clone(e);else if("number"==typeof e)this._value=D.fromNumber(e);else if("string"==typeof e){var t=parseInt(e,10);this._value=D.fromNumber(t)}else this._value=D.clone(D.ZERO)}var t=e.prototype;return t.set=function(e){if(e<0)throw new Error("Bit index cannot be negative");D.setBit(this._value,e)},t.clear=function(e){if(e<0)throw new Error("Bit index cannot be negative");D.clearBit(this._value,e)},t.get=function(e){return D.getBit(this._value,e)},t.containsAll=function(e){return D.hasAll(this._value,e._value)},t.intersects=function(e){return D.hasAny(this._value,e._value)},t.excludes=function(e){return D.hasNone(this._value,e._value)},t.clearAll=function(){D.clear(this._value)},t.isEmpty=function(){return D.isZero(this._value)},t.cardinality=function(){return D.popCount(this._value)},t.and=function(t){var n=new e;return D.copy(this._value,n._value),D.andInPlace(n._value,t._value),n},t.or=function(t){var n=new e;return D.copy(this._value,n._value),D.orInPlace(n._value,t._value),n},t.xor=function(t){var n=new e;return D.copy(this._value,n._value),D.xorInPlace(n._value,t._value),n},t.not=function(t){void 0===t&&(t=64),t>64&&(t=64);var n=new e;if(D.copy(this._value,n._value),t<=32){var r=(1<<t)-1;n._value.base[I.LOW]=~n._value.base[I.LOW]&r,n._value.base[I.HIGH]=0}else if(n._value.base[I.LOW]=~n._value.base[I.LOW],t<64){var i=(1<<t-32)-1;n._value.base[I.HIGH]=~n._value.base[I.HIGH]&i}else n._value.base[I.HIGH]=~n._value.base[I.HIGH];return n},t.copyFrom=function(e){D.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)D.copy(e,this._value);else if("number"==typeof e)this._value=D.fromNumber(e);else{var t=parseInt(e,10);this._value=D.fromNumber(t)}},t.toString=function(){for(var e=[],t=0;t<64;t++)this.get(t)&&e.push(t.toString());return"Bits["+e.join(", ")+"]"},t.toBinaryString=function(e){void 0===e&&(e=0),0==e&&(e=64+(this._value.segments?64*this._value.segments.length:0));for(var t="",n=e-1;n>=0;n--)t+=this.get(n)?"1":"0",n%8==0&&n>0&&(t+=" ");return t},t.toHexString=function(){return D.toString(this._value,16)},e.fromBinaryString=function(t){var n=t.replace(/\s/g,""),r={base:void 0,segments:void 0};if(n.length<=32){var i=parseInt(n,2);r.base=[i>>>0,0]}else{var o=n.substring(n.length-32),s=n.substring(0,n.length-32),a=parseInt(o,2),c=parseInt(s,2);r.base=[a>>>0,c>>>0]}return new e(r)},e.fromHexString=function(t){var n=t.replace(/^0x/i,""),r={base:void 0,segments:void 0};if(n.length<=8){var i=parseInt(n,16);r.base=[i>>>0,0]}else{var o=n.substring(n.length-8),s=n.substring(0,n.length-8),a=parseInt(o,16),c=parseInt(s,16);r.base=[a>>>0,c>>>0]}return new e(r)},t.equals=function(e){return D.equals(this._value,e._value)},t.getHighestBitIndex=function(){if(D.isZero(this._value))return-1;if(0!==this._value.base[I.HIGH])for(var e=31;e>=0;e--)if(this._value.base[I.HIGH]&1<<e)return e+32;for(var t=31;t>=0;t--)if(this._value.base[I.LOW]&1<<t)return t;return-1},t.getLowestBitIndex=function(){if(D.isZero(this._value))return-1;for(var e=0;e<32;e++)if(this._value.base[I.LOW]&1<<e)return e;for(var t=0;t<32;t++)if(this._value.base[I.HIGH]&1<<t)return t+32;return-1},e}(),B=Symbol("ComponentTypeName"),P=Symbol("SystemTypeName");function z(e){return e.__systemMetadata__}function N(e){var t=e[B];return t||(e.name||"UnknownComponent")}function W(e){var t=e[P];return t||(e.name||"UnknownSystem")}function L(e){return N(e.constructor)}function F(e){return W(e.constructor)}exports.LogLevel=void 0,(O=exports.LogLevel||(exports.LogLevel={}))[O.Debug=0]="Debug",O[O.Info=1]="Info",O[O.Warn=2]="Warn",O[O.Error=3]="Error",O[O.Fatal=4]="Fatal",O[O.None=5]="None";var U={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:""},H=function(){function e(e){void 0===e&&(e={}),this._config=a({level:exports.LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window},e)}var t=e.prototype;return t.debug=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Debug,e].concat(n))},t.info=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Info,e].concat(n))},t.warn=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Warn,e].concat(n))},t.error=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Error,e].concat(n))},t.fatal=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.log.apply(this,[exports.LogLevel.Fatal,e].concat(n))},t.setLevel=function(e){this._config.level=e},t.setColors=function(e){0===Object.keys(e).length?delete this._config.colors:this._config.colors=a({},this._config.colors,e)},t.setPrefix=function(e){this._config.prefix=e},t.log=function(e,t){if(!(e<this._config.level)){var n=t;if(this._config.enableTimestamp)n="["+(new Date).toISOString()+"] "+n;if(this._config.prefix&&(n="["+this._config.prefix+"] "+n),n="["+exports.LogLevel[e].toUpperCase()+"] "+n,this._config.output)this._config.output(e,n);else{for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];this.outputToConsole.apply(this,[e,n].concat(i))}}},t.outputToConsole=function(e,t){for(var n=this._config.enableColors?this.getColors():null,r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];switch(e){case exports.LogLevel.Debug:var s,a;if(n)(s=console).debug.apply(s,[""+n.debug+t+n.reset].concat(i));else(a=console).debug.apply(a,[t].concat(i));break;case exports.LogLevel.Info:var c,u;if(n)(c=console).info.apply(c,[""+n.info+t+n.reset].concat(i));else(u=console).info.apply(u,[t].concat(i));break;case exports.LogLevel.Warn:var h,l;if(n)(h=console).warn.apply(h,[""+n.warn+t+n.reset].concat(i));else(l=console).warn.apply(l,[t].concat(i));break;case exports.LogLevel.Error:var f,d;if(n)(f=console).error.apply(f,[""+n.error+t+n.reset].concat(i));else(d=console).error.apply(d,[t].concat(i));break;case exports.LogLevel.Fatal:var p,y;if(n)(p=console).error.apply(p,[""+n.fatal+t+n.reset].concat(i));else(y=console).error.apply(y,[t].concat(i))}},t.getColors=function(){return a({},{debug:U.BRIGHT_BLACK,info:U.GREEN,warn:U.YELLOW,error:U.RED,fatal:U.BRIGHT_RED,reset:U.RESET},this._config.colors)},e}(),j=function(){function e(){this._loggers=new Map,this._defaultLevel=exports.LogLevel.Info,this._defaultLogger=new H({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 H({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 H&&this._defaultLogger.setLevel(e);for(var t,n=s(this._loggers.values());!(t=n()).done;){var r=t.value;r instanceof H&&r.setLevel(e)}},t.createChildLogger=function(e,t){var n=e+"."+t;return this.getLogger(n)},t.setGlobalColors=function(e){this._defaultLogger instanceof H&&this._defaultLogger.setColors(e);for(var t,n=s(this._loggers.values());!(t=n()).done;){var r=t.value;r instanceof H&&r.setColors(e)}},t.resetColors=function(){this._defaultLogger instanceof H&&this._defaultLogger.setColors({});for(var e,t=s(this._loggers.values());!(e=t()).done;){var n=e.value;n instanceof H&&n.setColors({})}},e}(),q=j.getInstance().getLogger();function G(e){return j.getInstance().getLogger(e)}G("ReferenceTracker");var V=function(){function e(e){this._target=e}return e.prototype.deref=function(){return this._target},e}(),Y="undefined"!=typeof globalThis&&globalThis.WeakRef||"undefined"!=typeof global&&global.WeakRef||"undefined"!=typeof window&&window.WeakRef||V,Q=new Map;function J(e){var t=Q.get(e);return(null==t?void 0:t.deref())||null}var Z=function(){function e(){this._references=new Map,this._scene=null}var t=e.prototype;return t.registerReference=function(e,t,n){var r=e.id,i=this._references.get(r);i||(i=new Set,this._references.set(r,i)),this._findRecord(i,t,n)||i.add({component:new Y(t),propertyKey:n})},t.unregisterReference=function(e,t,n){var r=e.id,i=this._references.get(r);if(i){var o=this._findRecord(i,t,n);o&&(i.delete(o),0===i.size&&this._references.delete(r))}},t.clearReferencesTo=function(e){var t=this._references.get(e);if(t){for(var n,r=[],i=s(t);!(n=i()).done;){var o=n.value;o.component.deref()&&r.push(o)}for(var a=0,c=r;a<c.length;a++){var u=c[a],h=u.component.deref();h&&(h[u.propertyKey]=null)}this._references.delete(e)}},t.clearComponentReferences=function(e){for(var t,n=s(this._references.entries());!(t=n()).done;){for(var r,i=t.value,o=i[0],a=i[1],c=[],u=s(a);!(r=u()).done;){var h=r.value,l=h.component.deref();l&&l!==e||c.push(h)}for(var f=0,d=c;f<d.length;f++){var p=d[f];a.delete(p)}0===a.size&&this._references.delete(o)}},t.getReferencesTo=function(e){var t=this._references.get(e);if(!t)return[];for(var n,r=[],i=s(t);!(n=i()).done;){var o=n.value;o.component.deref()&&r.push(o)}return r},t.cleanup=function(){for(var e,t=[],n=s(this._references.entries());!(e=n()).done;){for(var r,i=e.value,o=i[0],a=i[1],c=[],u=s(a);!(r=u()).done;){var h=r.value;h.component.deref()||c.push(h)}for(var l=0,f=c;l<f.length;l++){var d=f[l];a.delete(d)}0===a.size&&t.push(o)}for(var p=0,y=t;p<y.length;p++){var m=y[p];this._references.delete(m)}},t.setScene=function(e){this._scene=new Y(e)},t.registerEntityScene=function(e,t){Q.set(e,new Y(t))},t.unregisterEntityScene=function(e){Q.delete(e)},t.getDebugInfo=function(){for(var e,t={},n=s(this._references.entries());!(e=n()).done;){for(var r,i=e.value,o=i[0],a=[],c=s(i[1]);!(r=c()).done;){var u=r.value,h=u.component.deref();h&&a.push({componentId:h.id,propertyKey:u.propertyKey})}a.length>0&&(t["entity_"+o]=a)}return t},t._findRecord=function(e,t,n){for(var r,i=s(e);!(r=i()).done;){var o=r.value;if(o.component.deref()===t&&o.propertyKey===n)return o}},e}(),X=G("EntityRefDecorator"),K=Symbol("EntityRefMetadata"),$=Symbol("EntityRefValues");function ee(e){var t=e[$];return t||(t=new Map,e[$]=t),t}function te(e){return e&&("function"==typeof e?e:e.constructor)[K]||null}var ne=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,N(e))),t},t.getTypeName=function(e){return this._typeNames.get(e)||"Unknown"},t.createBits=function(){for(var e=new R,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var i=0,o=n;i<o.length;i++){var s=o[i],a=this.getTypeId(s);e.set(a)}return e},t.getEntityBits=function(e){for(var t,n=new R,r=s(e);!(t=r()).done;){var i=t.value,o=this.getTypeId(i);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}}])}(),re=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 r=this.collectArchetypeData(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:r.distribution,topEntitiesByComponents:r.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 L(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,r,i;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===(r=s.components)||void 0===r?void 0:r.length)||0,componentTypes:(null===(i=s.components)||void 0===i?void 0:i.map((function(e){return L(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 r,i=null===(r=Object.getPrototypeOf(e))||void 0===r||null===(r=r.constructor)||void 0===r?void 0:r.name;i&&"Object"!==i&&(t=i,n=i)}}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 r=this.collectArchetypeDataWithMemory(e);return{totalEntities:t.totalEntities,activeEntities:t.activeEntities,pendingAdd:t.pendingAdd||0,pendingRemove:t.pendingRemove||0,entitiesPerArchetype:r.distribution,topEntitiesByComponents:r.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,r=(null===(n=e.components)||void 0===n?void 0:n.map((function(e){return L(e)})))||[],i=r.length>0?r.sort().join(", "):"无组件",o=t.get(i);o?o.count++:t.set(i,{count:1,componentTypes:r})})),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=[],r=[];return t.forEach((function(e){var t,i,o=(null===(t=e.componentTypes)||void 0===t?void 0:t.map((function(e){return e.name})).join(","))||"Unknown",s=(null===(i=e.entities)||void 0===i?void 0:i.length)||0;n.push({signature:o,count:s,memory:0}),e.entities&&e.entities.slice(0,5).forEach((function(e){var t;r.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})),r.sort((function(e,t){return t.componentCount-e.componentCount})),{distribution:n,topEntities:r}},t.extractArchetypeStatisticsWithMemory=function(e){var t=this,n=e.getAllArchetypes(),r=[],i=[];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}r.push({signature:s,count:a,memory:c}),e.entities&&e.entities.slice(0,5).forEach((function(e){var n;i.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)})}))})),r.sort((function(e,t){return t.count-e.count})),i.sort((function(e,t){return t.componentCount-e.componentCount})),{distribution:r,topEntities:i}},t.getArchetypeDistribution=function(e){var t=new Map;return e&&e.entities&&e.entities.forEach((function(e){var n,r=(null===(n=e.componentMask)||void 0===n?void 0:n.toString())||"0",i=t.get(r);t.set(r,(i||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 r,i=(null===(r=e.components)||void 0===r?void 0:r.map((function(e){return L(e)})))||[],o=i.length>0?i.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:i})})),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,r=this.calculateObjectSize(e,["components","children","parent"]);return!isNaN(r)&&r>0&&(n+=r),e.components&&Array.isArray(e.components)&&e.components.forEach((function(e){var r=t.calculateObjectSize(e,["entity"]);!isNaN(r)&&r>0&&(n+=r)})),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,r=function(e,i){if(void 0===i&&(i=0),!e||"object"!=typeof e||i>=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+=r(h,i+1))}}}catch(e){return 64}return o};try{var i=r(e);return Math.max(i,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 r=t.buildEntityHierarchyNode(e);n.push(r)}})),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,r={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 L(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&&(r.children=e.children.map((function(e){return n.buildEntityHierarchyNode(e)}))),"function"==typeof e.getDebugInfo)&&(r=a({},r,e.getDebugInfo()));return e.components&&e.components.length>0&&(r.componentDetails=this.extractComponentDetails(e.components)),r},t.buildEntityDetailsMap=function(e,t){var n=this;if(null==e||!e.buffer)return{};for(var r={},i=e.buffer,o=0;o<i.length;o+=100){i.slice(o,o+100).forEach((function(e){var i,o=e.getDebugInfo?e.getDebugInfo():n.buildFallbackEntityInfo(e,t),s=e.getComponentCacheStats?e.getComponentCacheStats():null,c=n.extractComponentDetails(e.components);r[e.id]=a({},o,{parentName:(null===(i=e.parent)||void 0===i?void 0:i.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 r},t.buildFallbackEntityInfo=function(e,t){var n,r,i,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 L(e)})),componentMask:(null===(n=e.componentMask)||void 0===n?void 0:n.toString())||"0",parentId:(null===(r=e.parent)||void 0===r?void 0:r.id)||null,childCount:(null===(i=e.children)||void 0===i?void 0:i.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=L(e);if(!n||"Object"===n||"Function"===n)try{var r=ne.instance,i=e.constructor,o=r.getTypeId(i);n=r.getTypeName(o)}catch(e){n="UnknownComponent"}var s={};try{Object.keys(e).forEach((function(n){if(!n.startsWith("_")&&"entity"!==n&&"constructor"!==n){var r=e[n];null!=r&&(s[n]=t.formatPropertyValue(r))}})),0===Object.keys(s).length&&(s._info="该组件没有公开属性",s._componentId=L(e))}catch(t){s._error="属性提取失败",s._componentId=L(e)}return{typeName:n,properties:s}}))},t.getComponentProperties=function(e,t,n){var r=this;try{if(!n)return{};var i=n.entities;if(null==i||!i.buffer)return{};var o=i.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]=r.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 r=Object.keys(e);if(0===r.length)return{};for(var i={},o=0,s=0,a=r;s<a.length;s++){var c=a[s];if(o>=15){i._hasMoreProperties=!0,i._totalProperties=r.length,i._hiddenCount=r.length-o;break}if(!c.startsWith("_")&&!c.startsWith("$")&&"function"!=typeof e[c])try{var u=e[c];null!=u&&(i[c]=this.formatPropertyValue(u,1),o++)}catch(e){i[c]="[访问失败: "+(e instanceof Error?e.message:String(e))+"]",o++}}return i}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 r=void 0!==e.a?e.a:1;return t+"("+e.r+", "+e.g+", "+e.b+", "+r+")"}if(t.toLowerCase().includes("node"))return t+": "+(e.name||e._name||"未命名");if(t.toLowerCase().includes("component")){var i,o,s=(null===(i=e.node)||void 0===i?void 0:i.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,r){try{if(!r)return null;var i=r.entities;if(null==i||!i.buffer)return null;var o=i.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,r=e,i=s(t.split("."));!(n=i()).done;){var o=n.value;if(null==r)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&&(r=r[a]),!(Array.isArray(r)&&c>=0&&c<r.length))return null;r=r[c]}else r=r[o]}return r},e}(),ie=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 r=n.processors||[],i=new Map,o=new Map;if(e)try{i=e.getAllSystemStats(),o=e.getAllSystemData()}catch(e){}return{totalSystems:r.length,systemsInfo:r.map((function(e){var t,n=e.systemName||F(e),r=i.get(n),s=o.get(n);return{name:n,type:F(e),entityCount:(null===(t=e.entities)||void 0===t?void 0:t.length)||0,executionTime:(null==r?void 0:r.averageTime)||(null==s?void 0:s.executionTime)||0,minExecutionTime:(null==r?void 0:r.minTime)===Number.MAX_VALUE?0:(null==r?void 0:r.minTime)||0,maxExecutionTime:(null==r?void 0:r.maxTime)||0,executionTimeHistory:(null==r?void 0:r.recentTimes)||[],updateOrder:e.updateOrder||0,enabled:!1!==e.enabled,lastUpdateTime:(null==s?void 0:s.lastUpdateTime)||0}}))}},e}(),oe=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=m.deltaTime,n=1e3*t,r=t>0?Math.round(1/t):0,i=this.getECSPerformanceData(e),o=i.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:r,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:i.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=[],r=e.getAllSystemStats();if(0===r.size)return{totalExecutionTime:0,systemBreakdown:[]};for(var i,o=s(r.entries());!(i=o()).done;){var a=i.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],r=e[1],i=n.get(t);return{systemName:t,averageTime:r.averageTime||0,maxTime:r.maxTime||0,minTime:r.minTime===Number.MAX_VALUE?0:r.minTime||0,samples:r.executionCount||0,percentage:0,entityCount:(null==i?void 0:i.entityCount)||0,lastExecutionTime:(null==i?void 0:i.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}(),se=function(){function e(e,t,n,r,i){void 0===n&&(n=1e3),void 0===r&&(r=10),void 0===i&&(i=1.5),this.pool=[],this.stats={totalCreated:0,totalAcquired:0,totalReleased:0},this.createFn=e,this.resetFn=t,this.maxSize=n,this.minSize=Math.max(1,r),this.growthFactor=Math.max(1.1,i)}var t=e.prototype;return t.acquire=function(){return this.stats.totalAcquired++,this.pool.length>0?this.pool.pop():(this.stats.totalCreated++,this.createFn())},t.release=function(e){this.stats.totalReleased++,this.pool.length>=this.maxSize||(this.resetFn&&this.resetFn(e),this.pool.push(e))},t.prewarm=function(e){for(var t=Math.min(e,this.maxSize),n=this.pool.length;n<t;n++){var r=this.createFn();this.resetFn&&this.resetFn(r),this.pool.push(r),this.stats.totalCreated++}},t.shrink=function(){for(;this.pool.length>this.minSize;)this.pool.pop()},t.clear=function(){this.pool.length=0},t.getAvailableCount=function(){return this.pool.length},t.getMaxSize=function(){return this.maxSize},t.getStats=function(){var e=0===this.stats.totalAcquired?0:(this.stats.totalAcquired-this.stats.totalCreated)/this.stats.totalAcquired;return{totalCreated:this.stats.totalCreated,totalAcquired:this.stats.totalAcquired,totalReleased:this.stats.totalReleased,hitRate:e,currentSize:this.pool.length,maxSize:this.maxSize,minSize:this.minSize,utilizationRate:this.pool.length/this.maxSize}},e}(),ae=function(){function e(){this.pools=new Map,this.usageTracker=new Map,this.autoCleanupInterval=6e4,this.lastCleanupTime=0}e.getInstance=function(){return e.instance||(e.instance=new e),e.instance};var t=e.prototype;return t.registerPool=function(e,t,n,r,i){this.pools.set(e,new se(t,n,r,i)),this.usageTracker.set(e,{createCount:0,releaseCount:0,lastAccessTime:Date.now()})},t.acquireComponent=function(e){var t=this.pools.get(e);return this.trackUsage(e,"create"),t?t.acquire():null},t.releaseComponent=function(e,t){var n=this.pools.get(e);this.trackUsage(e,"release"),n&&n.release(t)},t.trackUsage=function(e,t){var n=this.usageTracker.get(e);n||(n={createCount:0,releaseCount:0,lastAccessTime:Date.now()},this.usageTracker.set(e,n)),"create"===t?n.createCount++:n.releaseCount++,n.lastAccessTime=Date.now()},t.update=function(){var e=Date.now();if(!(e-this.lastCleanupTime<this.autoCleanupInterval)){for(var t,n=s(this.usageTracker.entries());!(t=n()).done;){var r=t.value,i=r[0];if(e-r[1].lastAccessTime>12e4){var o=this.pools.get(i);o&&o.shrink()}}this.lastCleanupTime=e}},t.getHotComponents=function(e){return void 0===e&&(e=100),Array.from(this.usageTracker.entries()).filter((function(t){return t[0],t[1].createCount>e})).map((function(e){return e[0]}))},t.prewarmAll=function(e){void 0===e&&(e=100);for(var t,n=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(),this.usageTracker.clear()},t.getGlobalStats=function(){for(var e,t=[],n=s(this.pools.entries());!(e=n()).done;){var r=e.value,i=r[0],o=r[1];t.push({componentName:i,poolStats:o.getStats(),usage:this.usageTracker.get(i)})}return t},t.getPoolStats=function(){for(var e,t=new Map,n=s(this.pools);!(e=n()).done;){var r=e.value,i=r[0],o=r[1];t.set(i,{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 r=e.value,i=r[0],o=r[1],a=o.getAvailableCount(),c=o.getMaxSize(),u=c-a,h=c>0?u/c*100:0;t.set(i,{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(),r=t.getMaxSize();return r>0?(r-n)/r*100:0},e}(),ce=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 r=new Map,i=0;n.buffer.forEach((function(e){e.components&&e.components.forEach((function(e){var t=L(e),n=r.get(t)||{count:0,entities:0};n.count++,i++,r.set(t,n)}))}));var o=new Map,a=new Map;try{for(var c,u=ae.getInstance(),h=u.getPoolStats(),l=u.getPoolUtilization(),f=s(h.entries());!(c=f()).done;){var d=c.value,p=d[0],y=d[1];a.set(p,y.maxSize)}for(var m,v=s(l.entries());!(m=v()).done;){var g=m.value,_=g[0],S=g[1];o.set(_,S.utilization)}}catch(e){}return{componentTypes:r.size,componentInstances:i,componentStats:Array.from(r.entries()).map((function(r){var i=r[0],s=r[1],c=a.get(i)||0,u=o.get(i)||0,h=t.getEstimatedComponentSize(i,e);return{typeName:i,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 r=n.entities;if(null==r||!r.buffer)return 64;var i=64;try{for(var o,a=s(r.buffer);!(o=a()).done;){var c=o.value;if(c.components){var u=c.components.find((function(e){return L(e)===t}));if(u){i=this.calculateQuickObjectSize(u);break}}}}catch(e){i=64}return e.componentSizeCache.set(t,i),i},t.calculateQuickObjectSize=function(e){if(!e||"object"!=typeof e)return 8;var t=32,n=new WeakSet,r=function(e,t){if(void 0===t&&(t=0),!e||"object"!=typeof e||n.has(e)||t>3)return 0;n.add(e);var i=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];i+=2*a.length,"string"==typeof c?i+=Math.min(2*c.length,200):"number"==typeof c?i+=8:"boolean"==typeof c?i+=4:"object"==typeof c&&null!==c&&(i+=r(c,t+1))}}}catch(e){return 32}return i};return t+=r(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 r,i=s(n.buffer);!(r=i()).done;){var o=r.value;if(o.components){var a=o.components.find((function(t){return L(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 r=0;switch(typeof e){case"boolean":r=4;break;case"number":default:r=8;break;case"string":r=24+Math.min(2*e.length,1e3);break;case"object":if(t.add(e),Array.isArray(e)){r=40+8*e.length;for(var i=Math.min(e.length,50),o=0;o<i;o++)r+=this.estimateObjectSize(e[o],t,n+1)}else{r=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{r+=16+2*u.length;var h=e[u];null!=h&&(r+=this.estimateObjectSize(h,t,n+1))}catch(e){continue}}}catch(e){r=128}}}return 8*Math.ceil(r/8)},e.clearCache=function(){e.componentSizeCache.clear()},e}();ce.componentSizeCache=new Map;var ue=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 r=(Date.now()-this.sceneStartTime)/1e3,i=e.entities,o=e.entityProcessors;return{currentSceneName:e.name||"Unnamed Scene",isInitialized:e._didSceneBegin||!1,sceneRunTime:r,sceneEntityCount:(null==i||null===(t=i.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:r}},t.setSceneStartTime=function(e){this.sceneStartTime=e},e}(),he=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,n){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.config=n,this.sceneManager=e,this.performanceMonitor=t,this.entityCollector=new re,this.systemCollector=new ie,this.performanceCollector=new oe,this.componentCollector=new ce,this.sceneCollector=new ue,this.webSocketManager=new he(n.websocketUrl,!1!==n.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));var r=n.debugFrameRate||30;this.sendInterval=1e3/r,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 he(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,r=e.propertyPath,i=e.requestId;if(void 0===t||void 0===n||!r)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,error:"缺少必要参数"});var o=this.entityCollector.expandLazyObject(t,n,r);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,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,r=e.requestId;if(void 0===t||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:r,error:"缺少必要参数"});var i=this.entityCollector.getComponentProperties(t,n);this.webSocketManager.send({type:"get_component_properties_response",requestId:r,data:i})}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 r=this.entityCollector.getEntityDetails(t);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:r})}catch(t){this.webSocketManager.send({type:"get_entity_details_response",requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}},t.handleMemorySnapshotRequest=function(){try{var e=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:e})}catch(e){this.webSocketManager.send({type:"memory_snapshot_error",error:e instanceof Error?e.message:"内存快照捕获失败"})}},t.captureMemorySnapshot=function(){var e=Date.now(),t=this.collectBaseMemoryInfo(),n=this.sceneManager.currentScene,r=this.entityCollector.collectEntityDataWithMemory(n),i=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=r.entitiesPerArchetype.reduce((function(e,t){return e+t.memory}),0);return{timestamp:e,version:"2.0",summary:{totalEntities:r.totalEntities,totalMemoryUsage:t.usedMemory,totalMemoryLimit:t.totalMemory,memoryUtilization:t.usedMemory/t.totalMemory*100,gcCollections:t.gcCollections,entityMemory:c,componentMemory:i.totalMemory,systemMemory:o.totalMemory,poolMemory:s.totalMemory},baseMemory:t,entities:{totalMemory:c,entityCount:r.totalEntities,archetypes:r.entitiesPerArchetype,largestEntities:r.topEntitiesByComponents},components:i,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,r=0,i=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=L(c.value);i.set(h,(i.get(h)||0)+1)}}for(var l,f=s(i.entries());!(l=f()).done;){var d=l.value,p=d[0],y=d[1],m=this.componentCollector.calculateDetailedComponentMemory(p),v=m*y;r+=v;for(var g,_=[],S=0,E=s(e.buffer);!(g=E()).done;){var C=g.value;if(C&&!C.destroyed&&C.components){for(var b,w=s(C.components);!(b=w()).done;){if(L(b.value)===p&&(_.push({entityId:C.id,entityName:C.name||"Entity_"+C.id,memory:m}),++S>=100))break}if(S>=100)break}}n.set(p,{count:y,totalMemory:v,instances:_.slice(0,10)})}var A=Array.from(n.entries()).map((function(e){var t=e[0],n=e[1];return{typeName:t,instanceCount:n.count,totalMemory:n.totalMemory,averageMemory:n.totalMemory/n.count,percentage:r>0?n.totalMemory/r*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:r,componentTypes:n.size,totalInstances:Array.from(n.values()).reduce((function(e,t){return e+t.count}),0),breakdown:A}},t.collectSystemMemoryStats=function(){var e=this.sceneManager.currentScene,t=0,n=[];try{var r=null==e?void 0:e.systems;if(r)for(var i,o=new Map,a=s(r);!(i=a()).done;){var c=i.value,u=F(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),r=0;r<Math.min(n.length,15);r++){var i=n[r];if("entities"!==i&&"scene"!==i&&"constructor"!==i){var o=e[i];t+=2*i.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,r=s(ae.getInstance().getPoolStats().entries());!(n=r()).done;){var i=n.value,o=i[0],a=i[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=M.getAllPoolStats(),h=0,l=Object.entries(u);h<l.length;h++){var f=l[h],d=f[0],p=f[1];e+=p.estimatedMemoryUsage,t.push({typeName:"Pool_"+d,maxSize:p.maxSize,currentSize:p.size,estimatedMemory:p.estimatedMemoryUsage,utilization:p.size/p.maxSize*100,hitRate:100*p.hitRate})}}catch(e){}return{totalMemory:e,poolCount:t.length,breakdown:t.sort((function(e,t){return t.estimatedMemory-e.estimatedMemory}))}},t.collectPerformanceStats=function(){try{var e;if(!this.performanceMonitor)return{enabled:!1};var t=this.performanceMonitor.getAllSystemStats(),n=this.performanceMonitor.getPerformanceWarnings();return{enabled:null!==(e=this.performanceMonitor.enabled)&&void 0!==e&&e,systemCount:t.size,warnings:n.slice(0,10),topSystems:Array.from(t.entries()).map((function(e){var t=e[0],n=e[1];return{name:t,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort((function(e,t){return t.averageTime-e.averageTime})).slice(0,5)}}catch(e){return{enabled:!1,error:e instanceof Error?e.message:String(e)}}},t.getDebugData=function(){var e=Date.now(),t=this.sceneManager.currentScene,n={timestamp:e,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:(null==t?void 0:t.name)||"Unknown"};return this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData(t)),this.config.channels.systems&&(n.systems=this.systemCollector.collectSystemData(this.performanceMonitor,t)),this.config.channels.performance&&(n.performance=this.performanceCollector.collectPerformanceData(this.performanceMonitor)),this.config.channels.components&&(n.components=this.componentCollector.collectComponentData(t)),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData(t)),n},t.connectWebSocket=function(){var e=n(l().m((function e(){return l().w((function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.webSocketManager.connect();case 1:e.n=3;break;case 2:e.p=2,e.v;case 3:return e.a(2)}}),e,this,[[0,2]])})));return function(){return e.apply(this,arguments)}}(),t.sendDebugData=function(){if(this.webSocketManager.getConnectionStatus())try{var e={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(e)}catch(e){}},t.dispose=function(){this.stop()},e}();var fe=function(){function e(){}return e.inferOptimalType=function(e,t){void 0===t&&(t={});var n=typeof e;if("boolean"===n)return"uint8";if("number"!==n)return"float32";var r=t,i=r.minValue,o=r.maxValue,s=r.precision,a=r.signed;if(!0===s)return Math.abs(e)>34028235e31||void 0!==i&&Math.abs(i)>34028235e31||void 0!==o&&Math.abs(o)>34028235e31?"float64":"float32";if(!1===s||Number.isInteger(e)){var c=void 0!==i?i:e,u=void 0!==o?o:e;return!1!==a&&(c<0||e<0)?c>=-128&&u<=127?"int8":c>=-32768&&u<=32767?"int16":c>=-2147483648&&u<=2147483647?"int32":"float64":u<=255?"uint8":u<=65535?"uint16":u<=4294967295?"uint32":"float64"}return Number.isInteger(e)?e>=0&&e<=255?"uint8":e>=-128&&e<=127?"int8":e>=0&&e<=65535?"uint16":e>=-32768&&e<=32767?"int16":e>=0&&e<=4294967295?"uint32":e>=-2147483648&&e<=2147483647?"int32":"float64":"float32"},e.getTypedArrayConstructor=function(e){switch(e){case"float32":default:return Float32Array;case"float64":return Float64Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int8":return Int8Array;case"uint8":return Uint8Array;case"uint8clamped":return Uint8ClampedArray}},e}(),de=function(){function e(e){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=e,this.initializeFields(e)}var t=e.prototype;return t.initializeFields=function(t){var n=new t,r=t.__highPrecisionFields||new Set,i=t.__float64Fields||new Set,o=t.__float32Fields||new Set,s=t.__int32Fields||new Set,a=t.__uint32Fields||new Set,c=t.__int16Fields||new Set,u=t.__uint16Fields||new Set,h=t.__int8Fields||new Set,l=t.__uint8Fields||new Set,f=t.__uint8ClampedFields||new Set,d=t.__autoTypedFields||new Map,p=t.__serializeMapFields||new Set,y=t.__serializeSetFields||new Set,m=t.__serializeArrayFields||new Set;for(var v in n)if(n.hasOwnProperty(v)&&"id"!==v){var g=n[v],_=typeof g;if("number"===_)if(r.has(v));else if(d.has(v)){var S=d.get(v),E=fe.inferOptimalType(g,S),C=fe.getTypedArrayConstructor(E);this.fields.set(v,new C(this._capacity)),e._logger.info("字段 "+v+" 自动推断为 "+E+" 类型,值: "+g+", 选项:",S)}else i.has(v)?this.fields.set(v,new Float64Array(this._capacity)):s.has(v)?this.fields.set(v,new Int32Array(this._capacity)):a.has(v)?this.fields.set(v,new Uint32Array(this._capacity)):c.has(v)?this.fields.set(v,new Int16Array(this._capacity)):u.has(v)?this.fields.set(v,new Uint16Array(this._capacity)):h.has(v)?this.fields.set(v,new Int8Array(this._capacity)):l.has(v)?this.fields.set(v,new Uint8Array(this._capacity)):f.has(v)?this.fields.set(v,new Uint8ClampedArray(this._capacity)):(o.has(v),this.fields.set(v,new Float32Array(this._capacity)));else"boolean"===_?l.has(v)||!o.has(v)&&!i.has(v)?this.fields.set(v,new Uint8Array(this._capacity)):this.fields.set(v,new Float32Array(this._capacity)):"string"===_?this.stringFields.set(v,new Array(this._capacity)):"object"===_&&null!==g&&(p.has(v)||y.has(v)||m.has(v))&&this.serializedFields.set(v,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 r;this.freeIndices.length>0?r=this.freeIndices.pop():(r=this._size)>=this._capacity&&this.resize(2*this._capacity),this.entityToIndex.set(e,r),this.indexToEntity[r]=e,this.updateComponentAtIndex(r,t),this._size++}},t.updateComponentAtIndex=function(e,t){var n=this.indexToEntity[e],r=new Map,i=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(i.has(u)||!this.fields.has(u))r.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)?r.set(u,this.deepClone(h)):r.set(u,h)}r.size>0&&this.complexFields.set(n,r)},t.serializeValue=function(t,n,r,i,o){try{return r.has(n)&&t instanceof Map?JSON.stringify(Array.from(t.entries())):i.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,r,i,o){try{var s=JSON.parse(t);return r.has(n)?new Map(s):i.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,r=new Map,i=s(e.entries());!(n=i()).done;){var o=n.value,a=o[0],c=o[1];r.set(a,this.deepClone(c))}return r}if(e instanceof Set){for(var u,h=new Set,l=s(e.values());!(u=l()).done;){var f=u.value;h.add(this.deepClone(f))}return h}var d={};for(var p in e)e.hasOwnProperty(p)&&(d[p]=this.deepClone(e[p]));return d},t.getComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;for(var n,r=new this.type,i=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],f=this.getFieldType(h);r[h]="boolean"===f?1===l:l}for(var d,p=s(this.stringFields.entries());!(d=p()).done;){var y=d.value,m=y[0],v=y[1];r[m]=v[t]}for(var g,_=s(this.serializedFields.entries());!(g=_()).done;){var S=g.value,E=S[0],C=S[1][t];C&&(r[E]=this.deserializeValue(C,E,i,o,a))}var b=this.complexFields.get(e);if(b)for(var w,A=s(b.entries());!(w=A()).done;){var T=w.value,x=T[0],M=T[1];r[x]=M}return r},t.getFieldType=function(e){return typeof(new this.type)[e]},t.hasComponent=function(e){return this.entityToIndex.has(e)},t.removeComponent=function(e){var t=this.entityToIndex.get(e);if(void 0===t)return null;var n=this.getComponent(e);return this.complexFields.delete(e),this.entityToIndex.delete(e),this.freeIndices.push(t),this._size--,n},t.resize=function(t){for(var n,r=s(this.fields.entries());!(n=r()).done;){var i=n.value,o=i[0],a=i[1],c=void 0;a instanceof Float32Array?c=new Float32Array(t):a instanceof Float64Array?c=new Float64Array(t):a instanceof Int32Array?c=new Int32Array(t):a instanceof Uint32Array?c=new Uint32Array(t):a instanceof Int16Array?c=new Int16Array(t):a instanceof Uint16Array?c=new Uint16Array(t):a instanceof Int8Array?c=new Int8Array(t):a instanceof Uint8Array?c=new Uint8Array(t):a instanceof Uint8ClampedArray?c=new Uint8ClampedArray(t):(c=new Float32Array(t),e._logger.warn("未知的TypedArray类型用于字段 "+o+",回退到Float32Array")),c.set(a),this.fields.set(o,c)}for(var u,h=s(this.stringFields.entries());!(u=h()).done;){for(var l=u.value,f=l[0],d=l[1],p=new Array(t),y=0;y<d.length;y++)p[y]=d[y];this.stringFields.set(f,p)}for(var m,v=s(this.serializedFields.entries());!(m=v()).done;){for(var g=m.value,_=g[0],S=g[1],E=new Array(t),C=0;C<S.length;C++)E[C]=S[C];this.serializedFields.set(_,E)}this._capacity=t},t.getActiveIndices=function(){return Array.from(this.entityToIndex.values())},t.getFieldArray=function(e){return this.fields.get(e)||null},t.getTypedFieldArray=function(e){return this.fields.get(String(e))||null},t.getEntityIndex=function(e){return this.entityToIndex.get(e)},t.getEntityIdByIndex=function(e){return this.indexToEntity[e]},t.size=function(){return this._size},t.clear=function(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(var e,t=s(this.fields.values());!(e=t()).done;){e.value.fill(0)}for(var n,r=s(this.stringFields.values());!(n=r()).done;)for(var i=n.value,o=0;o<i.length;o++)i[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=[],r=0;r<e.length;r++){var i=e[r],o=i[0],a=i[1];if(t.set(o,r),n[r]=o,r!==a){for(var c,u=s(this.fields.entries());!(c=u()).done;){var h=c.value[1];h[r]=h[a]}for(var l,f=s(this.stringFields.entries());!(l=f()).done;){var d=l.value[1];d[r]=d[a]}for(var p,y=s(this.serializedFields.entries());!(p=y()).done;){var m=p.value[1];m[r]=m[a]}}}this.entityToIndex=t,this.indexToEntity=n,this.freeIndices=[],this._size=e.length}},t.getStats=function(){for(var e,t=0,n=new Map,r=s(this.fields.entries());!(e=r()).done;){var i=e.value,o=i[0],a=i[1],c=void 0,u=void 0;a instanceof Float32Array?(c=4,u="float32"):a instanceof Float64Array?(c=8,u="float64"):a instanceof Int32Array?(c=4,u="int32"):a instanceof Uint32Array?(c=4,u="uint32"):a instanceof Int16Array?(c=2,u="int16"):a instanceof Uint16Array?(c=2,u="uint16"):a instanceof Int8Array?(c=1,u="int8"):a instanceof Uint8Array?(c=1,u="uint8"):a instanceof Uint8ClampedArray?(c=1,u="uint8clamped"):(c=4,u="unknown");var h=a.length*c;t+=h,n.set(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}();de._logger=G("SoAStorage");var pe=function(){function e(){}return e.register=function(e){var t=N(e);if(this.componentTypes.has(e))return this.componentTypes.get(e);var n=this.nextBitIndex++;return this.componentTypes.set(e,n),this.bitIndexToType.set(n,e),this.componentNameToType.set(t,e),this.componentNameToId.set(t,n),n},e.getBitMask=function(e){var t=this.componentTypes.get(e);if(void 0===t){var n=N(e);throw new Error("Component type "+n+" is not registered")}return D.create(t)},e.getBitIndex=function(e){var t=this.componentTypes.get(e);if(void 0===t){var n=N(e);throw new Error("Component type "+n+" is not registered")}return t},e.isRegistered=function(e){return this.componentTypes.has(e)},e.getTypeByBitIndex=function(e){return this.bitIndexToType.get(e)||null},e.getRegisteredCount=function(){return this.nextBitIndex},e.getComponentType=function(e){return this.componentNameToType.get(e)||null},e.getAllRegisteredTypes=function(){return new Map(this.componentTypes)},e.getAllComponentNames=function(){return new Map(this.componentNameToType)},e.getComponentId=function(e){return this.componentNameToId.get(e)},e.registerComponentByName=function(e){if(this.componentNameToId.has(e))return this.componentNameToId.get(e);var t=this.nextBitIndex++;return this.componentNameToId.set(e,t),t},e.createSingleComponentMask=function(e){var t="single:"+e;if(this.maskCache.has(t))return this.maskCache.get(t);var n=this.getComponentId(e);if(void 0===n)throw new Error("Component type "+e+" is not registered");var r=D.create(n);return this.maskCache.set(t,r),r},e.createComponentMask=function(e){var t="multi:"+[].concat(e).sort().join(",");if(this.maskCache.has(t))return this.maskCache.get(t);for(var n,r=D.clone(D.ZERO),i=s(e);!(n=i()).done;){var o=n.value,a=this.getComponentId(o);if(void 0!==a){var c=D.create(a);D.orInPlace(r,c)}}return this.maskCache.set(t,r),r},e.clearMaskCache=function(){this.maskCache.clear()},e.reset=function(){this.componentTypes.clear(),this.bitIndexToType.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0},e}();pe._logger=G("ComponentStorage"),pe.componentTypes=new Map,pe.bitIndexToType=new Map,pe.componentNameToType=new Map,pe.componentNameToId=new Map,pe.maskCache=new Map,pe.nextBitIndex=0;var ye=function(){function e(e){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=e,pe.isRegistered(e)||pe.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 "+N(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],r=this.dense.length-1;if(t!==r){var i=this.dense[r],o=this.entityIds[r];this.dense[t]=i,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}}])}(),me=function(){function e(){this.storages=new Map}var t=e.prototype;return t.isSoAStorage=function(e){return this.storages.get(e)instanceof de},t.getSoAStorage=function(e){var t=this.getStorage(e);return t instanceof de?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 de(t),e._logger.info("为 "+N(t)+" 启用SoA优化(适用于大规模批量操作)")):n=new ye(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=D.clone(D.ZERO),r=s(this.storages.entries());!(t=r()).done;){var i=t.value,o=i[0];if(i[1].hasComponent(e)){var a=pe.getBitMask(o);D.orInPlace(n,a)}}return n},t.getAllStats=function(){for(var e,t=new Map,n=s(this.storages.entries());!(e=n()).done;){var r=e.value,i=r[0],o=r[1],a=N(i);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}();me._logger=G("ComponentStorage");var ve=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}(),ge=function(){function e(e,t){this.scene=null,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=D.clone(D.ZERO),this._componentCache=null,this.name=e,this.id=t}e.notifyQuerySystems=function(e){e.scene&&e.scene.querySystem&&(e.scene.querySystem.updateEntity(e),e.scene.clearSystemEntityCaches())};var t=e.prototype;return t._rebuildComponentCache=function(){var e,t=[];if(null!==(e=this.scene)&&void 0!==e&&e.componentStorageManager){for(var n=this._componentMask,r=pe.getRegisteredCount(),i=0;i<r;i++)if(D.getBit(n,i)){var o=pe.getTypeByBitIndex(i);if(o){var s=this.scene.componentStorageManager.getComponent(this.id,o);s&&t.push(s)}}this._componentCache=t}else this._componentCache=t},t.createComponent=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];var o=r(e,n);return this.addComponent(o)},t.addComponentInternal=function(e){var t=e.constructor;pe.isRegistered(t)||pe.register(t);var n=pe.getBitMask(t);return D.orInPlace(this._componentMask,n),this._componentCache=null,e},t.addComponent=function(t){var n,r=t.constructor;if(!this.scene)throw new Error("Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()");if(!this.scene.componentStorageManager)throw new Error("Scene does not have componentStorageManager");if(this.hasComponent(r))throw new Error("Entity "+this.name+" already has component "+N(r));(this.addComponentInternal(t),this.scene.componentStorageManager.addComponent(this.id,t),t.entityId=this.id,this.scene.referenceTracker&&this.scene.referenceTracker.registerEntityScene(this.id,this.scene),t.onAddedToEntity(),e.eventBus)&&e.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(n=this.tag)||void 0===n?void 0:n.toString(),componentType:N(r),component:t});return e.notifyQuerySystems(this),t},t.getComponent=function(e){var t;return this.hasComponent(e)&&null!==(t=this.scene)&&void 0!==t&&t.componentStorageManager?this.scene.componentStorageManager.getComponent(this.id,e):null},t.hasComponent=function(e){if(!pe.isRegistered(e))return!1;var t=pe.getBitMask(e);return D.hasAny(this._componentMask,t)},t.getOrCreateComponent=function(e){var t=this.getComponent(e);if(!t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];t=this.createComponent.apply(this,[e].concat(r))}return t},t.removeComponent=function(t){var n,r,i=t.constructor;if(pe.isRegistered(i)){var o,s=pe.getBitIndex(i);if(D.clearBit(this._componentMask,s),this._componentCache=null,null!==(n=this.scene)&&void 0!==n&&n.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,i),null!==(r=this.scene)&&void 0!==r&&r.referenceTracker&&this.scene.referenceTracker.clearComponentReferences(t),t.onRemovedFromEntity&&t.onRemovedFromEntity(),t.entityId=null,e.eventBus)e.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(o=this.tag)||void 0===o?void 0:o.toString(),componentType:N(i),component:t});e.notifyQuerySystems(this)}},t.removeComponentByType=function(e){var t=this.getComponent(e);return t?(this.removeComponent(t),t):null},t.removeAllComponents=function(){var t=[].concat(this.components);D.clear(this._componentMask),this._componentCache=null;for(var n,r=s(t);!(n=r()).done;){var i,o=n.value,a=o.constructor;null!==(i=this.scene)&&void 0!==i&&i.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,a),o.onRemovedFromEntity()}e.notifyQuerySystems(this)},t.addComponents=function(t){for(var n,r=[],i=s(t);!(n=i()).done;){var o=n.value;try{r.push(this.addComponent(o))}catch(t){e._logger.warn("添加组件失败 "+L(o)+":",t)}}return r},t.removeComponentsByTypes=function(e){for(var t,n=[],r=s(e);!(t=r()).done;){var i=t.value;n.push(this.removeComponentByType(i))}return n},t.getComponents=function(e){for(var t,n=[],r=s(this.components);!(t=r()).done;){var i=t.value;i instanceof e&&n.push(i)}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,r=s(this._children);!(n=r()).done;){var i=n.value;if(i.name===e)return i}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,r=[],i=s(this._children);!(n=i()).done;){var o=n.value;o.tag===e&&r.push(o)}if(t)for(var a,c=s(this._children);!(a=c()).done;){var u=a.value;r.push.apply(r,u.findChildrenByTag(e,!0))}return r},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,r){e(n,r),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.destroy=function(){if(!this._isDestroyed){this._isDestroyed=!0,this.scene&&this.scene.referenceTracker&&(this.scene.referenceTracker.clearReferencesTo(this.id),this.scene.referenceTracker.unregisterEntityScene(this.id));for(var e,t=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.destroyAllChildren=function(){if(0!==this._children.length){var e=this.scene,t=[],n=function(e){for(var r,i=s(e._children);!(r=i()).done;){var o=r.value;t.push(o),n(o)}};n(this);for(var r=0,i=t;r<i.length;r++){i[r]._isDestroyed=!0}for(var o=0,a=t;o<a.length;o++){a[o].removeAllComponents()}if(e){for(var c,u=s(t);!(c=u()).done;){var h=c.value;e.entities.remove(h),e.querySystem.removeEntity(h)}e.clearSystemEntityCaches()}this._children.length=0}},t.compareTo=function(e){return ve.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 L(e)})),componentMask:D.toString(this._componentMask,2),parentId:(null===(e=this._parent)||void 0===e?void 0:e.id)||null,childCount:this._children.length,childIds:this._children.map((function(e){return e.id})),depth:this.getDepth(),cacheBuilt:null!==this._componentCache}},o(e,[{key:"isDestroyed",get:function(){return this._isDestroyed}},{key:"components",get:function(){return null===this._componentCache&&this._rebuildComponentCache(),this._componentCache}},{key:"parent",get:function(){return this._parent}},{key:"children",get:function(){return[].concat(this._children)}},{key:"childCount",get:function(){return this._children.length}},{key:"active",get:function(){return this._active},set:function(e){this._active!==e&&(this._active=e,this.onActiveChanged())}},{key:"activeInHierarchy",get:function(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}},{key:"tag",get:function(){return this._tag},set:function(e){this._tag=e}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(e){this._updateOrder=e}},{key:"componentMask",get:function(){return this._componentMask}}])}();ge._logger=G("Entity"),ge.entityComparer=new ve,ge.eventBus=null;var _e=function(){function e(e,t){this.scene=e,this.storageManager=t;var n=e.identifierPool.checkOut();this.entity=new ge("",n),this.entity.scene=this.scene}var t=e.prototype;return t.named=function(e){return this.entity.name=e,this},t.tagged=function(e){return this.entity.tag=e,this},t.with=function(e){return this.entity.addComponent(e),this},t.withComponents=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var r=0,i=t;r<i.length;r++){var o=i[r];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 r=0,i=t;r<i.length;r++){var o=i[r].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}(),Se=function(){function e(e){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._scene=e}var t=e.prototype;return t.add=function(e){this.addImmediate(e)},t.addImmediate=function(e){this._idToEntity.has(e.id)||(this.buffer.push(e),this._idToEntity.set(e.id,e),this.updateNameIndex(e,!0))},t.remove=function(e){this.removeImmediate(e)},t.removeImmediate=function(e){var t=this.buffer.indexOf(e);-1!==t&&(this.buffer.splice(t,1),this._idToEntity.delete(e.id),this.updateNameIndex(e,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(e.id))},t.removeAllEntities=function(){for(var e=[],t=this.buffer.length-1;t>=0;t--)e.push(this.buffer[t].id),this.buffer[t].destroy();if(this._scene&&this._scene.identifierPool)for(var n,r=s(e);!(n=r()).done;){var i=n.value;this._scene.identifierPool.checkIn(i)}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 r,i=s(this._entitiesToRemove);!(r=i()).done;){var o=r.value;this.removeImmediate(o)}this._entitiesToRemove.length=0}},t.update=function(){this.updateLists()},t.findEntity=function(e){var t=this._nameToEntities.get(e);return t&&t.length>0?t[0]:null},t.findEntitiesByName=function(e){return this._nameToEntities.get(e)||[]},t.findEntityById=function(e){return this._idToEntity.get(e)||null},t.findEntitiesByTag=function(e){for(var t,n=[],r=s(this.buffer);!(t=r()).done;){var i=t.value;i.tag===e&&n.push(i)}return n},t.findEntitiesWithComponent=function(e){for(var t,n=[],r=s(this.buffer);!(t=r()).done;){var i=t.value;i.hasComponent(e)&&n.push(i)}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,r=s(this.buffer);!(n=r()).done;){var i=n.value;e(i)&&t(i)}},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 r=this._nameToEntities.get(e.name);if(r){var i=r.indexOf(e);-1!==i&&(r.splice(i,1),0===r.length&&this._nameToEntities.delete(e.name))}}},t.getStats=function(){for(var e,t=0,n=s(this.buffer);!(e=n()).done;){var r=e.value;r.enabled&&!r.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}}])}(),Ee=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,r=0,i=s(this._generations);!(t=i()).done;){var o=t.value,a=o[0],c=o[1];a<this._nextAvailableIndex&&(n+=c,r++)}var u=r>0?n/r: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,r=Date.now(),i=[],o=[],a=s(this._pendingRecycle);!(n=a()).done;){var c=n.value;t||r-c.timestamp>=this._recycleDelay?i.push(c):o.push(c)}for(var u=0,h=i;u<h.length;u++){var l=h[u];if(this._isValidId(l.index,l.generation)){var f=l.generation+1;f>e.MAX_GENERATION&&(f=1),this._generations.set(l.index,f),this._freeIndices.push(l.index)}}this._pendingRecycle=o}},t._preAllocateGenerations=function(t,n){for(var r=0;r<n;r++){var i=t+r;i<=e.MAX_INDEX&&this._generations.set(i,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}();Ee.MAX_INDEX=65535,Ee.MAX_GENERATION=65535;var Ce=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,r,i=new e;return(t=i.condition.all).push.apply(t,this.condition.all),(n=i.condition.any).push.apply(n,this.condition.any),(r=i.condition.none).push.apply(r,this.condition.none),void 0!==this.condition.tag&&(i.condition.tag=this.condition.tag),void 0!==this.condition.name&&(i.condition.name=this.condition.name),void 0!==this.condition.component&&(i.condition.component=this.condition.component),i},t.toString=function(){var e=[];return this.condition.all.length>0&&e.push("all("+this.condition.all.map((function(e){return N(e)})).join(", ")+")"),this.condition.any.length>0&&e.push("any("+this.condition.any.map((function(e){return N(e)})).join(", ")+")"),this.condition.none.length>0&&e.push("none("+this.condition.none.map((function(e){return N(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("+N(this.condition.component)+")"),"Matcher["+e.join(" & ")+"]"},e}(),be=function(){function e(e){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=null,this._systemName=F(this),this._initialized=!1,this._matcher=e||Ce.empty(),this._eventListeners=[],this._scene=null,this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.logger=G(this.getLoggerName()),this._entityCache={frame:null,persistent:null,tracked:new Set,invalidate:function(){this.persistent=null},clearFrame:function(){this.frame=null},clearAll:function(){this.frame=null,this.persistent=null,this.tracked.clear()}}}var t=e.prototype;return t.setPerformanceMonitor=function(e){this._performanceMonitor=e},t.getPerformanceMonitor=function(){if(!this._performanceMonitor)throw new Error(this._systemName+": PerformanceMonitor未注入,请确保在Core.create()之后再添加System到Scene");return this._performanceMonitor},t.setUpdateOrder=function(e){this._updateOrder=e},t.initialize=function(){this._initialized||(this._initialized=!0,this.scene&&(this._entityCache.invalidate(),this.queryEntities()),this.onInitialize())},t.onInitialize=function(){},t.clearEntityCache=function(){this._entityCache.invalidate()},t.reset=function(){this.scene=null,this._initialized=!1,this._entityCache.clearAll(),this._entityIdMap=null,this._entityIdMapVersion=-1,this._entityIdMapSize=0,this.destroy()},t.queryEntities=function(){var e;if(null===(e=this.scene)||void 0===e||!e.querySystem||!this._matcher)return[];var t=this._matcher.getCondition(),n=this.scene.querySystem,r=[];return r=this._matcher.isEmpty()?n.getAllEntities():this.isSingleCondition(t)?this.executeSingleConditionQuery(t,n):this.executeComplexQuery(t,n),this.updateEntityTracking(r),r},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 r=t.queryByTag(e.tag);n=this.extractEntityIds(r.entities)}if(void 0!==e.name){var i=this.extractEntityIds(t.queryByName(e.name).entities);n=n?this.intersectIdSets(n,i):i}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,r=0;r<t;r=r+1|0)n.add(0|e[r].id);return n},t.intersectIdSets=function(e,t){var n,r;e.size<=t.size?(n=e,r=t):(n=t,r=e);for(var i,o=new Set,a=s(n);!(i=a()).done;){var c=i.value;r.has(c)&&o.add(c)}return o},t.differenceIdSets=function(e,t){for(var n,r=new Set,i=s(e);!(n=i()).done;){var o=n.value;t.has(o)||r.add(o)}return r},t.getEntityIdMap=function(e){var t,n,r=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===r?this._entityIdMap:this.rebuildEntityIdMap(e,r)},t.rebuildEntityIdMap=function(e,t){var n=this._entityIdMap;n?n.clear():n=new Map;for(var r=e.length,i=0;i<r;i=i+1|0){var o=e[i];n.set(0|o.id,o)}return this._entityIdMap=n,this._entityIdMapVersion=t,this._entityIdMapSize=r,n},t.idSetToEntityArray=function(e,t){for(var n,r=this.getEntityIdMap(t),i=e.size,o=new Array(i),a=0,c=s(e);!(n=c()).done;){var u=n.value,h=r.get(u);void 0!==h&&(o[a]=h,a=a+1|0)}return a<i&&(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.getPerformanceMonitor(),t=e.startMonitoring(this._systemName),n=0;try{this.onBegin(),this._entityCache.frame=this.queryEntities(),n=this._entityCache.frame.length,this.process(this._entityCache.frame)}finally{e.endMonitoring(this._systemName,t,n)}}},t.lateUpdate=function(){if(this._enabled&&this.onCheckProcessing()){var e=this.getPerformanceMonitor(),t=e.startMonitoring(this._systemName+"_Late"),n=0;try{var r=this._entityCache.frame||[];n=r.length,this.lateProcess(r),this.onEnd()}finally{e.endMonitoring(this._systemName+"_Late",t,n),this._entityCache.clearFrame()}}},t.onBegin=function(){},t.process=function(e){},t.lateProcess=function(e){},t.onEnd=function(){},t.onCheckProcessing=function(){return!0},t.getPerformanceData=function(){return this.getPerformanceMonitor().getSystemData(this._systemName)},t.getPerformanceStats=function(){return this.getPerformanceMonitor().getSystemStats(this._systemName)},t.resetPerformanceData=function(){this.getPerformanceMonitor().resetSystem(this._systemName)},t.toString=function(){var e=this.entities.length,t=this.getPerformanceData(),n=t?" ("+t.executionTime.toFixed(2)+"ms)":"";return this._systemName+"["+e+" entities]"+n},t.updateEntityTracking=function(e){for(var t,n=new Set(e),r=!1,i=s(e);!(t=i()).done;){var o=t.value;this._entityCache.tracked.has(o)||(this._entityCache.tracked.add(o),this.onAdded(o),r=!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),r=!0)}r&&this._entityCache.invalidate()},t.onAdded=function(e){},t.onRemoved=function(e){},t.dispose=function(){this.cleanupManualEventListeners(),this._entityCache.clearAll(),this._entityIdMap=null,this._initialized=!1,this._scene=null,this.logger.debug("System "+this._systemName+" disposed")},t.addEventListener=function(e,t,n){var r;if(null!==(r=this.scene)&&void 0!==r&&r.eventSystem){var i=this.scene.eventSystem.on(e,t,n);i&&this._eventListeners.push({eventSystem:this.scene.eventSystem,eventType:e,handler:t,listenerRef:i})}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 r=this._eventListeners[n];r.eventSystem.off(e,r.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(){},t.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" in "+this.systemName);return n},t.getComponents=function(e){for(var t=this,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r.map((function(n){return t.requireComponent(e,n)}))},t.forEach=function(e,t){for(var n=0;n<e.length;n++)t(e[n],n)},t.filterEntities=function(e,t){return Array.from(e).filter(t)},t.mapEntities=function(e,t){return Array.from(e).map(t)},t.findEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return e[n]},t.someEntity=function(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1},t.everyEntity=function(e,t){for(var n=0;n<e.length;n++)if(!t(e[n],n))return!1;return!0},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}}])}(),we=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 r=t.value;if(r instanceof e)return r}return null},t.begin=function(){this.sortProcessors()},t.end=function(){for(var t,n=s(this._processors);!(t=n()).done;){var r=t.value;try{r.reset()}catch(t){e._logger.error("Error in processor "+F(r)+":",t)}}this._isDirty=!1,this._processors.length=0},t.update=function(){this.sortProcessors();for(var t,n=s(this._processors);!(t=n()).done;){var r=t.value;try{r.update()}catch(t){e._logger.error("Error in processor "+F(r)+":",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}}])}();we._logger=G("EntityProcessorList");var Ae=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 r=this._dense[n];this._dense[t]=r,this._sparse.set(r,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,r=s(this._sparse);!(n=r()).done;){var i=n.value,o=i[0],a=i[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}}])}(),Te=function(e){function t(){return e.call(this)||this}return u(t,e),t.prototype.reset=function(){this.clear()},t}(y(Set)),xe=function(){function e(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new Ae}var t=e.prototype;return t.addEntity=function(e){this._entities.has(e)&&this.removeEntity(e);for(var t,n=D.clone(D.ZERO),r=new Set,i=s(e.components);!(t=i()).done;){var o=t.value.constructor;r.add(o),pe.isRegistered(o)||pe.register(o);var a=pe.getBitMask(o);D.orInPlace(n,a)}this._entities.add(e);for(var c=this._entities.getIndex(e);this._componentMasks.length<=c;)this._componentMasks.push(D.clone(D.ZERO));this._componentMasks[c]=n,this.updateComponentMappings(e,r,!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 r=this._componentMasks.length-1;t!==r&&(this._componentMasks[t]=this._componentMasks[r]),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 r,i=D.clone(D.ZERO),o=s(t);!(r=o()).done;){var a=r.value;if(!pe.isRegistered(a))return new Set;var c=pe.getBitMask(a);D.orInPlace(i,c)}var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var r=n._componentMasks[t];D.hasAll(r,i)&&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 r,i=D.clone(D.ZERO),o=s(t);!(r=o()).done;){var a=r.value;if(pe.isRegistered(a)){var c=pe.getBitMask(a);D.orInPlace(i,c)}}if(D.equals(i,D.ZERO))return new Set;var u=e._entitySetPool.obtain();return this._entities.forEach((function(e,t){var r=n._componentMasks[t];D.hasAny(r,i)&&u.add(e)})),u},t.hasComponent=function(e,t){var n=this._entities.getIndex(e);if(void 0===n)return!1;if(!pe.isRegistered(t))return!1;var r=this._componentMasks[n],i=pe.getBitMask(t);return D.hasAny(r,i)},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,r){e(n,t._componentMasks[r],r)}))},t.clear=function(){this._entities.clear(),this._componentMasks.length=0;for(var t,n=s(this._componentToEntities.values());!(t=n()).done;){var r=t.value;e._entitySetPool.release(r)}this._componentToEntities.clear()},t.getMemoryStats=function(){for(var e,t=this._entities.getMemoryStats(),n=16*this._componentMasks.length,r=16*this._componentToEntities.size,i=s(this._componentToEntities.values());!(e=i()).done;){r+=8*e.value.size}return{entitiesMemory:t.totalMemory,masksMemory:n,mappingsMemory:r,totalMemory:t.totalMemory+n+r}},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 r,i=s(e.value);!(r=i()).done;){var o=r.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,r=s(e.components);!(t=r()).done;){var i=t.value;n.add(i.constructor)}return n},t.updateComponentMappings=function(t,n,r){for(var i,o=s(n);!(i=o()).done;){var a=i.value,c=this._componentToEntities.get(a);r?(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}}])}();xe._entitySetPool=M.getPool(Te,50,512);var Me,Ie=function(){function e(){this.buckets=new Map,this._size=0}var t=e.prototype;return t.murmur32=function(e,t){var n=t>>>0,r=function(e){e=(e=Math.imul(e,3432918353)>>>0)<<15|e>>>17,e=Math.imul(e,461845907)>>>0,n=(n^=e)<<13|n>>>19,n=Math.imul(n,5)+3864292196>>>0};if(r(e.base[0]>>>0),r(e.base[1]>>>0),e.segments)for(var i,o=s(e.segments);!(i=o()).done;){var a=i.value;r(a[0]>>>0),r(a[1]>>>0)}return n^=e.segments?8*e.segments.length:8,n^=n>>>16,n=Math.imul(n,2246822507)>>>0,n^=n>>>13,n=Math.imul(n,3266489909)>>>0,(n^=n>>>16)>>>0},t.getHashes=function(e){return[this.murmur32(e,2538058380),this.murmur32(e,305419896)]},t.set=function(e,t){var n=this.getHashes(e),r=n[0],i=n[1],o=this.buckets.get(r);o||(o=[],this.buckets.set(r,o));for(var s=0;s<o.length;s++)if(o[s][0]===i)return o[s][1]=t,this;return o.push([i,t]),this._size++,this},t.get=function(e){var t=this.getHashes(e),n=t[0],r=t[1],i=this.buckets.get(n);if(i)for(var o=0;o<i.length;o++)if(i[o][0]===r)return i[o][1]},t.has=function(e){return void 0!==this.get(e)},t.delete=function(e){var t=this.getHashes(e),n=t[0],r=t[1],i=this.buckets.get(n);if(!i)return!1;for(var o=0;o<i.length;o++)if(i[o][0]===r)return i.splice(o,1),this._size--,0===i.length&&this.buckets.delete(n),!0;return!1},t.clear=function(){this.buckets.clear(),this._size=0},t.entries=l().m((function e(){var t,n,r,i,o,a,c,u;return l().w((function(e){for(;;)switch(e.n){case 0:t=s(this.buckets);case 1:if((n=t()).done){e.n=5;break}(r=n.value)[0],i=r[1],o=s(i);case 2:if((a=o()).done){e.n=4;break}return(c=a.value)[0],u=c[1],e.n=3,[void 0,u];case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}}),e,this)})),t.values=l().m((function e(){var t,n,r,i,o,a,c;return l().w((function(e){for(;;)switch(e.n){case 0:t=s(this.buckets.values());case 1:if((n=t()).done){e.n=5;break}r=n.value,i=s(r);case 2:if((o=i()).done){e.n=4;break}return(a=o.value)[0],c=a[1],e.n=3,c;case 3:e.n=2;break;case 4:e.n=1;break;case 5:return e.a(2)}}),e,this)})),o(e,[{key:"size",get:function(){return this._size}},{key:"innerBuckets",get:function(){return this.buckets}}])}(),ke=function(){function e(){this._archetypes=new Ie,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._entityComponentTypesCache=new Map,this._allArchetypes=[]}var t=e.prototype;return t.addEntity=function(e){var t=this.getEntityComponentTypes(e),n=this.generateArchetypeId(t),r=this._archetypes.get(n);r||(r=this.createArchetype(t)),r.entities.add(e),this._entityToArchetype.set(e,r)},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),r=this.generateArchetypeId(n);if(!t||t.id!==r){t&&t.entities.delete(e);var i=this._archetypes.get(r);i||(i=this.createArchetype(n)),i.entities.add(e),this._entityToArchetype.set(e,i)}},t.queryArchetypes=function(e,t){void 0===t&&(t="AND");var n=[],r=0;if("AND"===t){if(0===e.length){for(var i,o=s(this._allArchetypes);!(i=o()).done;){var a=i.value;n.push(a),r+=a.entities.size}return{archetypes:n,totalEntities:r}}if(1===e.length){var c=this._componentToArchetypes.get(e[0]);if(c)for(var u,h=s(c);!(u=h()).done;){var l=u.value;n.push(l),r+=l.entities.size}return{archetypes:n,totalEntities:r}}for(var f,d,p=1/0,y=s(e);!(d=y()).done;){var m=d.value,v=this._componentToArchetypes.get(m);if(!v||0===v.size)return{archetypes:[],totalEntities:0};v.size<p&&(p=v.size,f=v)}var g=this.generateArchetypeId(e);if(f)for(var _,S=s(f);!(_=S()).done;){var E=_.value;D.hasAll(E.id,g)&&(n.push(E),r+=E.entities.size)}}else{for(var C,b=new Set,w=s(e);!(C=w()).done;){var A=C.value,T=this._componentToArchetypes.get(A);if(T)for(var x,M=s(T);!(x=M()).done;){var I=x.value;b.add(I)}}for(var k,O=s(b);!(k=O()).done;){var R=k.value;n.push(R),r+=R.entities.size}}return{archetypes:n,totalEntities:r}},t.getEntityArchetype=function(e){return this._entityToArchetype.get(e)},t.getAllArchetypes=function(){return this._allArchetypes.slice()},t.getEntitiesByComponent=function(e){var t=this._componentToArchetypes.get(e);if(!t||0===t.size)return[];for(var n,r=[],i=s(t);!(n=i()).done;)for(var o,a=s(n.value.entities);!(o=a()).done;){var c=o.value;r.push(c)}return r},t.clear=function(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._entityComponentTypesCache.clear(),this._allArchetypes=[]},t.updateAllArchetypeArrays=function(){this._allArchetypes=[];for(var e,t=s(this._archetypes.values());!(e=t()).done;){var n=e.value;this._allArchetypes.push(n)}},t.getEntityComponentTypes=function(e){var t=this._entityComponentTypesCache.get(e);return t||(t=e.components.map((function(e){return e.constructor})),this._entityComponentTypesCache.set(e,t)),t},t.generateArchetypeId=function(e){return ne.instance.getEntityBits(e).getValue()},t.createArchetype=function(e){var t=this.generateArchetypeId(e),n={id:t,componentTypes:[].concat(e),entities:new Set};this._archetypes.set(t,n),this.updateAllArchetypeArrays();for(var r,i=s(e);!(r=i()).done;){var o=r.value,a=this._componentToArchetypes.get(o);a||(a=new Set,this._componentToArchetypes.set(o,a)),a.add(n)}return n},e}();!function(e){e.ALL="all",e.ANY="any",e.NONE="none"}(Me||(Me={}));var De,Oe,Re=function(){function e(){this._logger=G("QuerySystem"),this.entities=[],this._version=0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.componentMaskCache=new Map,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.resultArrayPool=[],this.poolMaxSize=50,this.entityIndex={byTag:new Map,byName:new Map},this.archetypeSystem=new ke}var t=e.prototype;return t.acquireResultArray=function(){return this.resultArrayPool.length>0?this.resultArrayPool.pop():[]},t.releaseResultArray=function(e){this.resultArrayPool.length<this.poolMaxSize&&(e.length=0,this.resultArrayPool.push(e))},t.setEntities=function(e){this.entities=e,this.clearQueryCache(),this.rebuildIndexes()},t.addEntity=function(e,t){void 0===t&&(t=!1),this.entities.includes(e)||(this.entities.push(e),this.addEntityToIndexes(e),this.archetypeSystem.addEntity(e),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}))),r=0,i=s(e);!(t=i()).done;){var o=t.value;n.has(o.id)||(this.entities.push(o),this.addEntityToIndexes(o),this.archetypeSystem.addEntity(o),n.add(o.id),r++)}r>0&&this.clearQueryCache()}},t.addEntitiesUnchecked=function(e){if(0!==e.length){for(var t,n=s(e);!(t=n()).done;){var r=t.value;this.entities.push(r)}for(var i,o=s(e);!(i=o()).done;){var a=i.value;this.addEntityToIndexes(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.archetypeSystem.removeEntity(e),this.clearQueryCache(),this._version++)},t.updateEntity=function(e){this.entities.includes(e)?(this.removeEntityFromIndexes(e),this.archetypeSystem.updateEntity(e),this.addEntityToIndexes(e),this.clearQueryCache(),this._version++):this.addEntity(e)},t.addEntityToIndexes=function(e){var t=e.tag;void 0!==t&&(this.entityIndex.byTag.get(t)||this.createAndSetTagIndex(t)).add(e);var n=e.name;n&&(this.entityIndex.byName.get(n)||this.createAndSetNameIndex(n)).add(e)},t.createAndSetTagIndex=function(e){var t=new Set;return this.entityIndex.byTag.set(e,t),t},t.createAndSetNameIndex=function(e){var t=new Set;return this.entityIndex.byName.set(e,t),t},t.removeEntityFromIndexes=function(e){if(void 0!==e.tag){var t=this.entityIndex.byTag.get(e.tag);t&&(t.delete(e),0===t.size&&this.entityIndex.byTag.delete(e.tag))}if(e.name){var n=this.entityIndex.byName.get(e.name);n&&(n.delete(e),0===n.size&&this.entityIndex.byName.delete(e.name))}},t.rebuildIndexes=function(){this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear();for(var e,t=s(this.entities);!(e=t()).done;){var n=e.value;this.addEntityToIndexes(n),this.archetypeSystem.addEntity(n)}},t.queryAll=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var i=this.generateCacheKey("all",n),o=this.getFromCache(i);if(o)return this.queryStats.cacheHits++,{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.archetypeHits++;for(var a,c=[],u=s(this.archetypeSystem.queryArchetypes(n,"AND").archetypes);!(a=u()).done;)for(var h,l=s(a.value.entities);!(h=l()).done;){var f=h.value;c.push(f)}return this.addToCache(i,c),{entities:c,count:c.length,executionTime:performance.now()-e,fromCache:!1}},t.queryMultipleComponents=function(e){for(var t,n=[],r=s(this.archetypeSystem.queryArchetypes(e,"AND").archetypes);!(t=r()).done;)for(var i,o=s(t.value.entities);!(i=o()).done;){var a=i.value;n.push(a)}return n},t.queryAny=function(){var e=performance.now();this.queryStats.totalQueries++;for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var i=this.generateCacheKey("any",n),o=this.getFromCache(i);if(o)return this.queryStats.cacheHits++,{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.archetypeHits++;for(var a,c=this.archetypeSystem.queryArchetypes(n,"OR"),u=this.acquireResultArray(),h=s(c.archetypes);!(a=h()).done;)for(var l,f=s(a.value.entities);!(l=f()).done;){var d=l.value;u.push(d)}var p=[].concat(u);return this.releaseResultArray(u),this.addToCache(i,p),{entities:p,count:p.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),r=0;r<t;r++)n[r]=arguments[r];var i=this.generateCacheKey("none",n),o=this.getFromCache(i);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 D.hasNone(e.componentMask,s)}));return this.addToCache(i,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,r=this.getFromCache(n);if(r)return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var i=Array.from(this.entityIndex.byTag.get(e)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByName=function(e){var t=performance.now();this.queryStats.totalQueries++;var n="name:"+e,r=this.getFromCache(n);if(r)return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var i=Array.from(this.entityIndex.byName.get(e)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-t,fromCache:!1}},t.queryByComponent=function(e){var t=performance.now();this.queryStats.totalQueries++;var n=this.generateCacheKey("component",[e]),r=this.getFromCache(n);if(r)return this.queryStats.cacheHits++,{entities:r,count:r.length,executionTime:performance.now()-t,fromCache:!0};this.queryStats.indexHits++;var i=this.archetypeSystem.getEntitiesByComponent(e);return this.addToCache(n,i),{entities:i,count:i.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 r=e.value,i=r[0];t-r[1].timestamp>this.cacheTimeout&&this.queryCache.delete(i)}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,f=l[0],d=l[1];(d.hitCount<a||d.hitCount===a&&d.timestamp<u)&&(a=d.hitCount,c=f,u=d.timestamp)}c&&this.queryCache.delete(c)}},t.clearQueryCache=function(){this.queryCache.clear(),this.componentMaskCache.clear()},t.generateCacheKey=function(e,t){return 1===t.length?e+":"+N(t[0]):e+":"+t.map((function(e){return N(e)})).sort().join(",")},t.clearCache=function(){this.clearQueryCache()},t.createComponentMask=function(e){var t=e.map((function(e){return N(e)})).sort().join(","),n=this.componentMaskCache.get(t);if(n)return n;var r=ne.instance.getEntityBits(e);return this.componentMaskCache.set(t,r.getValue()),r.getValue()},t.getAllEntities=function(){return this.entities},t.getStats=function(){return{entityCount:this.entities.length,indexStats:{componentIndexSize:this.archetypeSystem.getAllArchetypes().length,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},queryStats:a({},this.queryStats,{cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}),optimizationStats:{archetypeSystem:this.archetypeSystem.getAllArchetypes().map((function(e){return{id:e.id,componentTypes:e.componentTypes.map((function(e){return N(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}}])}(),Be=function(){function e(e){this._logger=G("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:Me.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:Me.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:Me.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this},t.execute=function(){var e,t,n,r=performance.now();if(1===this.conditions.length){var i=this.conditions[0];switch(i.type){case Me.ALL:return(e=this.querySystem).queryAll.apply(e,i.componentTypes);case Me.ANY:return(t=this.querySystem).queryAny.apply(t,i.componentTypes);case Me.NONE:return(n=this.querySystem).queryNone.apply(n,i.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-r,fromCache:!1}},t.createComponentMask=function(e){for(var t,n=D.clone(D.ZERO),r=s(e);!(t=r()).done;){var i=t.value;try{var o=pe.getBitMask(i);D.orInPlace(n,o)}catch(e){this._logger.warn("组件类型 "+N(i)+" 未注册,跳过")}}return n},t.reset=function(){return this.conditions=[],this},e}(),Pe=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 r=n.findIndex((function(e){return e.id===t}));return-1!==r&&(n.splice(r,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 r;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==(r=this.batchConfigs.get(t))||!r.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 r=this.listeners.get(t);if(r&&0!==r.length){for(var i,o=performance.now(),a=[],c=s(this.sortListenersByPriority(r));!(i=c()).done;){var u=i.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,r){var i=this.listeners.get(t);if(i||(i=[],this.listeners.set(t,i)),i.length>=this.maxListeners)return e._logger.warn("事件类型 "+t+" 的监听器数量超过最大限制 ("+this.maxListeners+")"),"";var o="listener_"+this.nextListenerId++,s={handler:n,config:a({priority:0},r),id:o};return i.push(s),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),o},t.executeEvent=function(){var t=n(l().m((function t(r,i){var o,a,c,u,h,f,d,p,y,m;return l().w((function(t){for(;;)switch(t.n){case 0:if((o=this.listeners.get(r))&&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})),f=u.filter((function(e){return e.config.async})),d=s(h);!(p=d()).done;){y=p.value;try{y.config.context?y.handler.call(y.config.context,i):y.handler(i),y.config.once&&c.push(y.id)}catch(t){e._logger.error("同步事件处理器执行错误 "+r+":",t)}}return m=f.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,i);case 1:t.n=3;break;case 2:return t.n=3,n.handler(i);case 3:n.config.once&&c.push(n.id),t.n=5;break;case 4:t.p=4,o=t.v,e._logger.error("异步事件处理器执行错误 "+r+":",o);case 5:return t.a(2)}}),t,null,[[0,4]])})));return function(e){return t.apply(this,arguments)}}()),t.n=2,Promise.all(m);case 2:this.removeListeners(r,c),this.updateStats(r,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 r,i=function(){var e=r.value,t=n.findIndex((function(t){return t.id===e}));-1!==t&&n.splice(t,1)},o=s(t);!(r=o()).done;)i();0===n.length&&(this.listeners.delete(e),this.stats.delete(e))}}},t.addToBatch=function(e,t){var n=this,r=this.batchQueue.get(e);r||(r=[],this.batchQueue.set(e,r)),r.push(t);var i=this.batchConfigs.get(e);if(r.length>=i.batchSize)this.flushBatch(e);else if(!this.batchTimers.has(e)){var o=setTimeout((function(){n.flushBatch(e)}),i.delay);this.batchTimers.set(e,o)}},t.processBatch=function(){var e=n(l().m((function e(t,n){var r;return l().w((function(e){for(;;)switch(e.n){case 0:return r={type:t,events:n,count:n.length,timestamp:Date.now()},e.n=1,this.executeEvent(t+":batch",r);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}();Pe._logger=G("EventSystem"),exports.ECSEventType=void 0,(De=exports.ECSEventType||(exports.ECSEventType={})).ENTITY_CREATED="entity:created",De.ENTITY_DESTROYED="entity:destroyed",De.ENTITY_ENABLED="entity:enabled",De.ENTITY_DISABLED="entity:disabled",De.ENTITY_TAG_ADDED="entity:tag:added",De.ENTITY_TAG_REMOVED="entity:tag:removed",De.ENTITY_NAME_CHANGED="entity:name:changed",De.COMPONENT_ADDED="component:added",De.COMPONENT_REMOVED="component:removed",De.COMPONENT_MODIFIED="component:modified",De.COMPONENT_ENABLED="component:enabled",De.COMPONENT_DISABLED="component:disabled",De.SYSTEM_ADDED="system:added",De.SYSTEM_REMOVED="system:removed",De.SYSTEM_ENABLED="system:enabled",De.SYSTEM_DISABLED="system:disabled",De.SYSTEM_PROCESSING_START="system:processing:start",De.SYSTEM_PROCESSING_END="system:processing:end",De.SYSTEM_ERROR="system:error",De.SCENE_CREATED="scene:created",De.SCENE_DESTROYED="scene:destroyed",De.SCENE_ACTIVATED="scene:activated",De.SCENE_DEACTIVATED="scene:deactivated",De.SCENE_PAUSED="scene:paused",De.SCENE_RESUMED="scene:resumed",De.QUERY_EXECUTED="query:executed",De.QUERY_CACHE_HIT="query:cache:hit",De.QUERY_CACHE_MISS="query:cache:miss",De.QUERY_OPTIMIZED="query:optimized",De.PERFORMANCE_WARNING="performance:warning",De.PERFORMANCE_CRITICAL="performance:critical",De.MEMORY_USAGE_HIGH="memory:usage:high",De.FRAME_RATE_DROP="frame:rate:drop",De.INDEX_CREATED="index:created",De.INDEX_UPDATED="index:updated",De.INDEX_OPTIMIZED="index:optimized",De.ARCHETYPE_CREATED="archetype:created",De.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",De.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",De.DIRTY_MARK_ADDED="dirty:mark:added",De.DIRTY_BATCH_PROCESSED="dirty:batch:processed",De.ERROR_OCCURRED="error:occurred",De.WARNING_ISSUED="warning:issued",De.FRAMEWORK_INITIALIZED="framework:initialized",De.FRAMEWORK_SHUTDOWN="framework:shutdown",De.DEBUG_INFO="debug:info",De.DEBUG_STATS_UPDATED="debug:stats:updated",exports.EventPriority=void 0,(Oe=exports.EventPriority||(exports.EventPriority={}))[Oe.LOWEST=0]="LOWEST",Oe[Oe.LOW=25]="LOW",Oe[Oe.NORMAL=50]="NORMAL",Oe[Oe.HIGH=75]="HIGH",Oe[Oe.HIGHEST=100]="HIGHEST",Oe[Oe.CRITICAL=200]="CRITICAL";var ze={ENTITY:{CREATED:exports.ECSEventType.ENTITY_CREATED,DESTROYED:exports.ECSEventType.ENTITY_DESTROYED,ENABLED:exports.ECSEventType.ENTITY_ENABLED,DISABLED:exports.ECSEventType.ENTITY_DISABLED,TAG_ADDED:exports.ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:exports.ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:exports.ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:exports.ECSEventType.COMPONENT_ADDED,REMOVED:exports.ECSEventType.COMPONENT_REMOVED,MODIFIED:exports.ECSEventType.COMPONENT_MODIFIED,ENABLED:exports.ECSEventType.COMPONENT_ENABLED,DISABLED:exports.ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:exports.ECSEventType.SYSTEM_ADDED,REMOVED:exports.ECSEventType.SYSTEM_REMOVED,ENABLED:exports.ECSEventType.SYSTEM_ENABLED,DISABLED:exports.ECSEventType.SYSTEM_DISABLED,PROCESSING_START:exports.ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:exports.ECSEventType.SYSTEM_PROCESSING_END,ERROR:exports.ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:exports.ECSEventType.PERFORMANCE_WARNING,CRITICAL:exports.ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:exports.ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:exports.ECSEventType.FRAME_RATE_DROP}},Ne=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}();Ne.validTypes=new Set([].concat(Object.values(exports.ECSEventType),Object.values(ze.ENTITY),Object.values(ze.COMPONENT),Object.values(ze.SYSTEM),Object.values(ze.PERFORMANCE)));var We=function(){function e(e){void 0===e&&(e=!1),this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new Pe,this.isDebugMode=e}var t=e.prototype;return t.emit=function(t,n,r){void 0===r&&(r=!1),this.validateEventType(t);var i=r?this.enhanceEventData(t,n):n;this.isDebugMode&&e._logger.info("发射事件: "+t,i),this.eventSystem.emitSync(t,i)},t.emitAsync=function(){var t=n(l().m((function t(n,r,i){var o;return l().w((function(t){for(;;)switch(t.n){case 0:return void 0===i&&(i=!1),this.validateEventType(n),o=i?this.enhanceEventData(n,r):r,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,r){return t.apply(this,arguments)}}(),t.on=function(t,n,r){void 0===r&&(r={}),this.validateEventType(t);var i={once:r.once||!1,priority:r.priority||exports.EventPriority.NORMAL,async:r.async||!1,context:r.context};return this.isDebugMode&&e._logger.info("添加监听器: "+t,i),this.eventSystem.on(t,n,i)},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 r=new Map;return n.forEach((function(e,n){r.set(n,t.convertEventStats(e))})),r}return this.convertEventStats(n)},t.clear=function(){this.isDebugMode&&e._logger.info("清空所有监听器"),this.eventSystem.clear()},t.setEnabled=function(e){this.eventSystem.setEnabled(e)},t.setDebugMode=function(e){this.isDebugMode=e},t.setMaxListeners=function(e){this.eventSystem.setMaxListeners(e)},t.getListenerCount=function(e){return this.eventSystem.getListenerCount(e)},t.setBatchConfig=function(e,t,n){this.eventSystem.setBatchConfig(e,{batchSize:t,delay:n,enabled:!0})},t.flushBatch=function(e){this.eventSystem.flushBatch(e)},t.resetStats=function(e){this.eventSystem.resetStats(e)},t.emitEntityCreated=function(e){this.emit(exports.ECSEventType.ENTITY_CREATED,e)},t.emitEntityDestroyed=function(e){this.emit(exports.ECSEventType.ENTITY_DESTROYED,e)},t.emitComponentAdded=function(e){this.emit(exports.ECSEventType.COMPONENT_ADDED,e)},t.emitComponentRemoved=function(e){this.emit(exports.ECSEventType.COMPONENT_REMOVED,e)},t.emitSystemAdded=function(e){this.emit(exports.ECSEventType.SYSTEM_ADDED,e)},t.emitSystemRemoved=function(e){this.emit(exports.ECSEventType.SYSTEM_REMOVED,e)},t.emitSceneChanged=function(e){this.emit(exports.ECSEventType.SCENE_ACTIVATED,e)},t.emitPerformanceWarning=function(e){this.emit(exports.ECSEventType.PERFORMANCE_WARNING,e)},t.onEntityCreated=function(e,t){return this.on(exports.ECSEventType.ENTITY_CREATED,e,t)},t.onComponentAdded=function(e,t){return this.on(exports.ECSEventType.COMPONENT_ADDED,e,t)},t.onSystemError=function(e,t){return this.on(exports.ECSEventType.SYSTEM_ERROR,e,t)},t.onPerformanceWarning=function(e,t){return this.on(exports.ECSEventType.PERFORMANCE_WARNING,e,t)},t.validateEventType=function(t){this.isDebugMode&&(Ne.isValid(t)||(e._logger.warn("未知事件类型: "+t),Ne.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}();We._logger=G("EventBus");var Le=function(){function e(){}return e.getInstance=function(e){return void 0===e&&(e=!1),this.instance||(this.instance=new We(e)),this.instance},e.reset=function(e){return void 0===e&&(e=!1),this.instance&&this.instance.clear(),this.instance=new We(e),this.instance},e}(),Fe=function(){function e(e,t){this._entities=e,this._componentTypes=t}var t=e.prototype;return t.forEach=function(e){this._entities.forEach(e)},t.map=function(e){return this._entities.map(e)},t.filter=function(t){return new e(this._entities.filter(t),this._componentTypes)},t.find=function(e){return this._entities.find(e)},t.some=function(e){return this._entities.some(e)},t.every=function(e){return this._entities.every(e)},t.get=function(e){return this._entities[e]},t.toArray=function(){return[].concat(this._entities)},t.getComponentTypes=function(){return this._componentTypes},t[Symbol.iterator]=function(){return this._entities[Symbol.iterator]()},o(e,[{key:"entities",get:function(){return this._entities}},{key:"length",get:function(){return this._entities.length}},{key:"first",get:function(){return this._entities[0]}},{key:"last",get:function(){return this._entities[this._entities.length-1]}},{key:"isEmpty",get:function(){return 0===this._entities.length}}])}(),Ue=function(){function e(e,t,n,r,i){this._all=e||[],this._any=t||[],this._none=n||[],this._tag=r,this._name=i}var t=e.prototype;return t.withAll=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return new e([].concat(this._all,n),this._any,this._none,this._tag,this._name)},t.withAny=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return new e(this._all,[].concat(this._any,n),this._none,this._tag,this._name)},t.withNone=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return new e(this._all,this._any,[].concat(this._none,n),this._tag,this._name)},t.withTag=function(t){return new e(this._all,this._any,this._none,t,this._name)},t.withName=function(t){return new e(this._all,this._any,this._none,this._tag,t)},t.buildMatcher=function(){var e,t,n,r=Ce.complex();this._all.length>0&&(r=(e=r).all.apply(e,this._all));this._any.length>0&&(r=(t=r).any.apply(t,this._any));this._none.length>0&&(r=(n=r).none.apply(n,this._none));return void 0!==this._tag&&(r=r.withTag(this._tag)),void 0!==this._name&&(r=r.withName(this._name)),r},t.getCondition=function(){return{all:[].concat(this._all),any:[].concat(this._any),none:[].concat(this._none),tag:this._tag,name:this._name}},t.getRequiredTypes=function(){return this._all},t.clone=function(){return new e([].concat(this._all),[].concat(this._any),[].concat(this._none),this._tag,this._name)},e}();var He=Symbol("SerializableMetadata"),je=Symbol("SerializeField"),qe=Symbol("SerializeOptions");function Ge(e){return function(t,n){var r=t.constructor,i=r[He];i||(i={options:{version:1},fields:new Map,ignoredFields:new Set},r[He]=i),i.fields.set(n,e||{})}}function Ve(e){return e&&("function"==typeof e?e:e.constructor)[He]||null}var Ye,Qe,Je,Ze,Xe=function(){function e(){}return e.serialize=function(e){var t=Ve(e);if(!t)return null;for(var n,r=e.constructor,i=t.options.typeId||N(r),o={},a=s(t.fields);!(n=a()).done;){var c=n.value,u=c[0],h=c[1],l="symbol"==typeof u?u.toString():u,f=e[u];if(!t.ignoredFields.has(u)){var d=h.serializer?h.serializer(f):this.serializeValue(f);o[h.alias||l]=d}}return{type:i,version:t.options.version,data:o}},e.deserialize=function(e,t){var n=t.get(e.type);if(!n)return console.warn("未找到组件类型: "+e.type),null;var r=Ve(n);if(!r)return console.warn("组件 "+e.type+" 不可序列化"),null;for(var i,o=new n,a=s(r.fields);!(i=a()).done;){var c=i.value,u=c[0],h=c[1],l="symbol"==typeof u?u.toString():u,f=h.alias||l,d=e.data[f];if(void 0!==d){var p=h.deserializer?h.deserializer(d):this.deserializeValue(d);o[u]=p}}return o},e.serializeComponents=function(e){for(var t,n=[],r=s(e);!(t=r()).done;){var i=t.value,o=this.serialize(i);o&&n.push(o)}return n},e.deserializeComponents=function(e,t){for(var n,r=[],i=s(e);!(n=i()).done;){var o=n.value,a=this.deserialize(o,t);a&&r.push(a)}return r},e.serializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(Array.isArray(e))return e.map((function(e){return t.serializeValue(e)}));if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if("object"===n){var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=this.serializeValue(e[i]));return r}},e.deserializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if("object"===n&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((function(e){return t.deserializeValue(e)}));if("object"===n){var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=this.deserializeValue(e[i]));return r}return e},e.validateVersion=function(e,t){return e.version===t},e.getSerializationInfo=function(e){var t=Ve(e);if(!t)return{type:"unknown",version:0,fields:[],ignoredFields:[],isSerializable:!1};var n="function"==typeof e?e:e.constructor;return{type:t.options.typeId||N(n),version:t.options.version,fields:Array.from(t.fields.keys()).map((function(e){return"symbol"==typeof e?e.toString():e})),ignoredFields:Array.from(t.ignoredFields).map((function(e){return"symbol"==typeof e?e.toString():e})),isSerializable:!0}},e}(),Ke=function(){function e(){}return e.serialize=function(e,t){void 0===t&&(t=!0);var n=Xe.serializeComponents(Array.from(e.components)),r={id:e.id,name:e.name,tag:e.tag,active:e.active,enabled:e.enabled,updateOrder:e.updateOrder,components:n,children:[]};if(e.parent&&(r.parentId=e.parent.id),t)for(var i,o=s(e.children);!(i=o()).done;){var a=i.value;r.children.push(this.serialize(a,!0))}return r},e.deserialize=function(e,t,n,r,i){void 0===r&&(r=!1);var o=r?e.id:n(),a=new ge(e.name,o);i&&(a.scene=i),a.tag=e.tag,a.active=e.active,a.enabled=e.enabled,a.updateOrder=e.updateOrder;for(var c,u=s(Xe.deserializeComponents(e.components,t));!(c=u()).done;){var h=c.value;a.addComponent(h)}for(var l,f=s(e.children);!(l=f()).done;){var d=l.value,p=this.deserialize(d,t,n,r,i);a.addChild(p)}return a},e.serializeEntities=function(e,t){void 0===t&&(t=!0);for(var n,r=[],i=s(e);!(n=i()).done;){var o=n.value;o.parent&&t||r.push(this.serialize(o,t))}return r},e.deserializeEntities=function(e,t,n,r,i){void 0===r&&(r=!1);for(var o,a=[],c=s(e);!(o=c()).done;){var u=o.value,h=this.deserialize(u,t,n,r,i);a.push(h)}return a},e.clone=function(e,t,n){var r=this.serialize(e,!0);return this.deserialize(r,t,n,!1)},e}(),$e={},et={},tt={},nt={},rt={},it={};function ot(){if(Qe)return Ye;function e(e){return e&&e.isBuffer&&e}return Qe=1,Ye=e("undefined"!=typeof Buffer&&Buffer)||e(Ye.Buffer)||e("undefined"!=typeof window&&window.Buffer)||Ye.Buffer}function st(){if(Ze)return Je;Ze=1;var e={}.toString;return Je=Array.isArray||function(t){return"[object Array]"==e.call(t)}}var at,ct={exports:{}};function ut(){if(at)return ct.exports;at=1;var e=wt(),t=ct.exports=n(0);function n(e){return new Array(e)}return t.alloc=n,t.concat=e.concat,t.from=function(n){if(!e.isBuffer(n)&&e.isView(n))n=e.Uint8Array.from(n);else if(e.isArrayBuffer(n))n=new Uint8Array(n);else{if("string"==typeof n)return e.from.call(t,n);if("number"==typeof n)throw new TypeError('"value" argument must not be a number')}return Array.prototype.slice.call(n)},ct.exports}var ht,lt={exports:{}};function ft(){if(ht)return lt.exports;ht=1;var e=wt(),t=e.global,n=lt.exports=e.hasBuffer?r(0):[];function r(e){return new t(e)}return n.alloc=e.hasBuffer&&t.alloc||r,n.concat=e.concat,n.from=function(r){if(!e.isBuffer(r)&&e.isView(r))r=e.Uint8Array.from(r);else if(e.isArrayBuffer(r))r=new Uint8Array(r);else{if("string"==typeof r)return e.from.call(n,r);if("number"==typeof r)throw new TypeError('"value" argument must not be a number')}return t.from&&1!==t.from.length?t.from(r):new t(r)},lt.exports}var dt,pt={exports:{}};function yt(){if(dt)return pt.exports;dt=1;var e=wt(),t=pt.exports=e.hasArrayBuffer?n(0):[];function n(e){return new Uint8Array(e)}return t.alloc=n,t.concat=e.concat,t.from=function(n){if(e.isView(n)){var r=n.byteOffset,i=n.byteLength;(n=n.buffer).byteLength!==i&&(n.slice?n=n.slice(r,r+i):(n=new Uint8Array(n)).byteLength!==i&&(n=Array.prototype.slice.call(n,r,r+i)))}else{if("string"==typeof n)return e.from.call(t,n);if("number"==typeof n)throw new TypeError('"value" argument must not be a number')}return new Uint8Array(n)},pt.exports}var mt,vt,gt,_t,St={},Et={};function Ct(){if(mt)return Et;return mt=1,Et.copy=function(e,t,n,r){var i;n||(n=0);r||0===r||(r=this.length);t||(t=0);var o=r-n;if(e===this&&n<t&&t<r)for(i=o-1;i>=0;i--)e[i+t]=this[i+n];else for(i=0;i<o;i++)e[i+t]=this[i+n];return o},Et.toString=function(e,t,n){var r=this,i=0|t;n||(n=r.length);var o="",s=0;for(;i<n;)(s=r[i++])<128?o+=String.fromCharCode(s):(192==(224&s)?s=(31&s)<<6|63&r[i++]:224==(240&s)?s=(15&s)<<12|(63&r[i++])<<6|63&r[i++]:240==(248&s)&&(s=(7&s)<<18|(63&r[i++])<<12|(63&r[i++])<<6|63&r[i++]),s>=65536?(s-=65536,o+=String.fromCharCode((s>>>10)+55296,56320+(1023&s))):o+=String.fromCharCode(s));return o},Et.write=function(e,t){var n=this,r=t||(t|=0),i=e.length,o=0,s=0;for(;s<i;)(o=e.charCodeAt(s++))<128?n[r++]=o:o<2048?(n[r++]=192|o>>>6,n[r++]=128|63&o):o<55296||o>57343?(n[r++]=224|o>>>12,n[r++]=128|o>>>6&63,n[r++]=128|63&o):(o=65536+(o-55296<<10|e.charCodeAt(s++)-56320),n[r++]=240|o>>>18,n[r++]=128|o>>>12&63,n[r++]=128|o>>>6&63,n[r++]=128|63&o);return r-t},Et}function bt(){if(vt)return St;vt=1;var e,t=Ct();St.copy=s,St.slice=a,St.toString=function(e,r,o){return(!i&&n.isBuffer(this)?this.toString:t.toString).apply(this,arguments)},St.write=(e="write",function(){return(this[e]||t[e]).apply(this,arguments)});var n=wt(),r=n.global,i=n.hasBuffer&&"TYPED_ARRAY_SUPPORT"in r,o=i&&!r.TYPED_ARRAY_SUPPORT;function s(e,r,i,s){var c=n.isBuffer(this),u=n.isBuffer(e);if(c&&u)return this.copy(e,r,i,s);if(o||c||u||!n.isView(this)||!n.isView(e))return t.copy.call(this,e,r,i,s);var h=i||null!=s?a.call(this,i,s):this;return e.set(h,r),h.length}function a(e,t){var r=this.slice||!o&&this.subarray;if(r)return r.call(this,e,t);var i=n.alloc.call(this,t-e);return s.call(this,i,0,e,t),i}return St}function wt(){return gt||(gt=1,function(e){var t=e.global=ot(),n=e.hasBuffer=t&&!!t.isBuffer,r=e.hasArrayBuffer="undefined"!=typeof ArrayBuffer,i=e.isArray=st();e.isArrayBuffer=r?function(e){return e instanceof ArrayBuffer||f(e)}:y;var o=e.isBuffer=n?t.isBuffer:y,s=e.isView=r?ArrayBuffer.isView||m("ArrayBuffer","buffer"):y;e.alloc=l,e.concat=function(t,n){n||(n=0,Array.prototype.forEach.call(t,(function(e){n+=e.length})));var r=this!==e&&this||t[0],i=l.call(r,n),o=0;return Array.prototype.forEach.call(t,(function(e){o+=h.copy.call(e,i,o)})),i},e.from=function(e){return"string"==typeof e?d.call(this,e):p(this).from(e)};var a=e.Array=ut(),c=e.Buffer=ft(),u=e.Uint8Array=yt(),h=e.prototype=bt();function l(e){return p(this).alloc(e)}var f=m("ArrayBuffer");function d(e){var t=3*e.length,n=l.call(this,t),r=h.write.call(n,e);return t!==r&&(n=h.slice.call(n,0,r)),n}function p(e){return o(e)?c:s(e)?u:i(e)?a:n?c:r?u:a}function y(){return!1}function m(e,t){return e="[object "+e+"]",function(n){return null!=n&&{}.toString.call(t?n[t]:n)===e}}}(it)),it}function At(){if(_t)return rt;_t=1,rt.ExtBuffer=function t(n,r){if(!(this instanceof t))return new t(n,r);this.buffer=e.from(n),this.type=r};var e=wt();return rt}var Tt,xt={};function Mt(){if(Tt)return xt;Tt=1,xt.setExtPackers=function(e){e.addExtPacker(14,Error,[c,o]),e.addExtPacker(1,EvalError,[c,o]),e.addExtPacker(2,RangeError,[c,o]),e.addExtPacker(3,ReferenceError,[c,o]),e.addExtPacker(4,SyntaxError,[c,o]),e.addExtPacker(5,TypeError,[c,o]),e.addExtPacker(6,URIError,[c,o]),e.addExtPacker(10,RegExp,[a,o]),e.addExtPacker(11,Boolean,[s,o]),e.addExtPacker(12,String,[s,o]),e.addExtPacker(13,Date,[Number,o]),e.addExtPacker(15,Number,[s,o]),"undefined"!=typeof Uint8Array&&(e.addExtPacker(17,Int8Array,r),e.addExtPacker(18,Uint8Array,r),e.addExtPacker(19,Int16Array,r),e.addExtPacker(20,Uint16Array,r),e.addExtPacker(21,Int32Array,r),e.addExtPacker(22,Uint32Array,r),e.addExtPacker(23,Float32Array,r),"undefined"!=typeof Float64Array&&e.addExtPacker(24,Float64Array,r),"undefined"!=typeof Uint8ClampedArray&&e.addExtPacker(25,Uint8ClampedArray,r),e.addExtPacker(26,ArrayBuffer,r),e.addExtPacker(29,DataView,r));t.hasBuffer&&e.addExtPacker(27,n,t.from)};var e,t=wt(),n=t.global,r=t.Uint8Array.from,i={name:1,message:1,stack:1,columnNumber:1,fileName:1,lineNumber:1};function o(t){return e||(e=tn().encode),e(t)}function s(e){return e.valueOf()}function a(e){(e=RegExp.prototype.toString.call(e).split("/")).shift();var t=[e.pop()];return t.unshift(e.join("/")),t}function c(e){var t={};for(var n in i)t[n]=e[n];return t}return xt}var It,kt={},Dt={};function Ot(){return It||(It=1,function(e){!function(e){var t,n="undefined",r=n!==typeof Buffer&&Buffer,i=n!==typeof Uint8Array&&Uint8Array,o=n!==typeof ArrayBuffer&&ArrayBuffer,s=[0,0,0,0,0,0,0,0],a=Array.isArray||function(e){return!!e&&"[object Array]"==Object.prototype.toString.call(e)},c=4294967296;function u(a,u,S){var E=u?0:4,C=u?4:0,b=u?0:3,w=u?1:2,A=u?2:1,T=u?3:0,x=u?m:g,M=u?v:_,I=O.prototype,k="is"+a,D="_"+k;return I.buffer=void 0,I.offset=0,I[D]=!0,I.toNumber=R,I.toString=function(e){var t=this.buffer,n=this.offset,r=P(t,n+E),i=P(t,n+C),o="",s=!S&&2147483648&r;s&&(r=~r,i=c-i);e=e||10;for(;;){var a=r%e*c+i;if(r=Math.floor(r/e),i=Math.floor(a/e),o=(a%e).toString(e)+o,!r&&!i)break}s&&(o="-"+o);return o},I.toJSON=R,I.toArray=h,r&&(I.toBuffer=l),i&&(I.toArrayBuffer=f),O[k]=function(e){return!(!e||!e[D])},e[a]=O,O;function O(e,r,a,u){return this instanceof O?function(e,r,a,u,h){i&&o&&(r instanceof o&&(r=new i(r)),u instanceof o&&(u=new i(u)));if(!(r||a||u||t))return void(e.buffer=y(s,0));if(!d(r,a)){h=a,u=r,a=0,r=new(t||Array)(8)}if(e.buffer=r,e.offset=a|=0,n===typeof u)return;"string"==typeof u?function(e,t,n,r){var i=0,o=n.length,s=0,a=0;"-"===n[0]&&i++;var u=i;for(;i<o;){var h=parseInt(n[i++],r);if(!(h>=0))break;a=a*r+h,s=s*r+Math.floor(a/c),a%=c}u&&(s=~s,a?a=c-a:s++);B(e,t+E,s),B(e,t+C,a)}(r,a,u,h||10):d(u,h)?p(r,a,u,h):"number"==typeof h?(B(r,a+E,u),B(r,a+C,h)):u>0?x(r,a,u):u<0?M(r,a,u):p(r,a,s,0)}(this,e,r,a,u):new O(e,r,a,u)}function R(){var e=this.buffer,t=this.offset,n=P(e,t+E),r=P(e,t+C);return S||(n|=0),n?n*c+r:r}function B(e,t,n){e[t+T]=255&n,n>>=8,e[t+A]=255&n,n>>=8,e[t+w]=255&n,n>>=8,e[t+b]=255&n}function P(e,t){return 16777216*e[t+b]+(e[t+w]<<16)+(e[t+A]<<8)+e[t+T]}}function h(e){var n=this.buffer,r=this.offset;return t=null,!1!==e&&0===r&&8===n.length&&a(n)?n:y(n,r)}function l(e){var n=this.buffer,i=this.offset;if(t=r,!1!==e&&0===i&&8===n.length&&Buffer.isBuffer(n))return n;var o=new r(8);return p(o,0,n,i),o}function f(e){var n=this.buffer,r=this.offset,s=n.buffer;if(t=i,!1!==e&&0===r&&s instanceof o&&8===s.byteLength)return s;var a=new i(8);return p(a,0,n,r),a.buffer}function d(e,t){var n=e&&e.length;return t|=0,n&&t+8<=n&&"string"!=typeof e[t]}function p(e,t,n,r){t|=0,r|=0;for(var i=0;i<8;i++)e[t++]=255&n[r++]}function y(e,t){return Array.prototype.slice.call(e,t,t+8)}function m(e,t,n){for(var r=t+8;r>t;)e[--r]=255&n,n/=256}function v(e,t,n){var r=t+8;for(n++;r>t;)e[--r]=255&-n^255,n/=256}function g(e,t,n){for(var r=t+8;t<r;)e[t++]=255&n,n/=256}function _(e,t,n){var r=t+8;for(n++;t<r;)e[t++]=255&-n^255,n/=256}u("Uint64BE",!0,!0),u("Int64BE",!0,!1),u("Uint64LE",!1,!0),u("Int64LE",!1,!1)}("string"!=typeof e.nodeName?e:Dt||{})}(Dt)),Dt}var Rt,Bt={},Pt={};function zt(){return Rt||(Rt=1,Pt.read=function(e,t,n,r,i){var o,s,a=8*i-r-1,c=(1<<a)-1,u=c>>1,h=-7,l=n?i-1:0,f=n?-1:1,d=e[t+l];for(l+=f,o=d&(1<<-h)-1,d>>=-h,h+=a;h>0;o=256*o+e[t+l],l+=f,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=r;h>0;s=256*s+e[t+l],l+=f,h-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,r),o-=u}return(d?-1:1)*s*Math.pow(2,o-r)},Pt.write=function(e,t,n,r,i,o){var s,a,c,u=8*o-i-1,h=(1<<u)-1,l=h>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=h):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+l>=1?f/c:f*Math.pow(2,1-l))*c>=2&&(s++,c/=2),s+l>=h?(a=0,s=h):s+l>=1?(a=(t*c-1)*Math.pow(2,i),s+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,i),s=0));i>=8;e[n+d]=255&a,d+=p,a/=256,i-=8);for(s=s<<i|a,u+=i;u>0;e[n+d]=255&s,d+=p,s/=256,u-=8);e[n+d-p]|=128*y}),Pt}var Nt,Wt,Lt,Ft={};function Ut(){if(Nt)return Ft;Nt=1;for(var e=Ft.uint8=new Array(256),t=0;t<=255;t++)e[t]=n(t);function n(e){return function(t){var n=t.reserve(1);t.buffer[n]=e}}return Ft}function Ht(){if(Wt)return Bt;Wt=1;var e=zt(),t=Ot(),n=t.Uint64BE,r=t.Int64BE,i=Ut().uint8,o=wt(),s=o.global,a=o.hasBuffer&&"TYPED_ARRAY_SUPPORT"in s&&!s.TYPED_ARRAY_SUPPORT,c=o.hasBuffer&&s.prototype||{};function u(){var e=i.slice();return e[196]=h(196),e[197]=l(197),e[198]=f(198),e[199]=h(199),e[200]=l(200),e[201]=f(201),e[202]=d(202,4,c.writeFloatBE||m,!0),e[203]=d(203,8,c.writeDoubleBE||v,!0),e[204]=h(204),e[205]=l(205),e[206]=f(206),e[207]=d(207,8,p),e[208]=h(208),e[209]=l(209),e[210]=f(210),e[211]=d(211,8,y),e[217]=h(217),e[218]=l(218),e[219]=f(219),e[220]=l(220),e[221]=f(221),e[222]=l(222),e[223]=f(223),e}function h(e){return function(t,n){var r=t.reserve(2),i=t.buffer;i[r++]=e,i[r]=n}}function l(e){return function(t,n){var r=t.reserve(3),i=t.buffer;i[r++]=e,i[r++]=n>>>8,i[r]=n}}function f(e){return function(t,n){var r=t.reserve(5),i=t.buffer;i[r++]=e,i[r++]=n>>>24,i[r++]=n>>>16,i[r++]=n>>>8,i[r]=n}}function d(e,t,n,r){return function(i,o){var s=i.reserve(t+1);i.buffer[s++]=e,n.call(i.buffer,o,s,r)}}function p(e,t){new n(this,t,e)}function y(e,t){new r(this,t,e)}function m(t,n){e.write(this,t,n,!1,23,4)}function v(t,n){e.write(this,t,n,!1,52,8)}return Bt.getWriteToken=function(e){return e&&e.uint8array?((t=u())[202]=d(202,4,m),t[203]=d(203,8,v),t):a||o.hasBuffer&&e&&e.safe?function(){var e=i.slice();return e[196]=d(196,1,s.prototype.writeUInt8),e[197]=d(197,2,s.prototype.writeUInt16BE),e[198]=d(198,4,s.prototype.writeUInt32BE),e[199]=d(199,1,s.prototype.writeUInt8),e[200]=d(200,2,s.prototype.writeUInt16BE),e[201]=d(201,4,s.prototype.writeUInt32BE),e[202]=d(202,4,s.prototype.writeFloatBE),e[203]=d(203,8,s.prototype.writeDoubleBE),e[204]=d(204,1,s.prototype.writeUInt8),e[205]=d(205,2,s.prototype.writeUInt16BE),e[206]=d(206,4,s.prototype.writeUInt32BE),e[207]=d(207,8,p),e[208]=d(208,1,s.prototype.writeInt8),e[209]=d(209,2,s.prototype.writeInt16BE),e[210]=d(210,4,s.prototype.writeInt32BE),e[211]=d(211,8,y),e[217]=d(217,1,s.prototype.writeUInt8),e[218]=d(218,2,s.prototype.writeUInt16BE),e[219]=d(219,4,s.prototype.writeUInt32BE),e[220]=d(220,2,s.prototype.writeUInt16BE),e[221]=d(221,4,s.prototype.writeUInt32BE),e[222]=d(222,2,s.prototype.writeUInt16BE),e[223]=d(223,4,s.prototype.writeUInt32BE),e}():u();var t},Bt}function jt(){if(Lt)return kt;Lt=1;var e=st(),t=Ot(),n=t.Uint64BE,r=t.Int64BE,i=wt(),o=bt(),s=Ht(),a=Ut().uint8,c=At().ExtBuffer,u="undefined"!=typeof Uint8Array,h="undefined"!=typeof Map,l=[];return l[1]=212,l[2]=213,l[4]=214,l[8]=215,l[16]=216,kt.getWriteType=function(t){var f=s.getWriteToken(t),d=t&&t.useraw,p=u&&t&&t.binarraybuffer,y=p?i.isArrayBuffer:i.isBuffer,m=p?function(e,t){E(e,new Uint8Array(t))}:E,v=h&&t&&t.usemap?function(e,t){if(!(t instanceof Map))return C(e,t);var n=t.size;f[n<16?128+n:n<=65535?222:223](e,n);var r=e.codec.encode;t.forEach((function(t,n,i){r(e,n),r(e,t)}))}:C,g={boolean:function(e,t){f[t?195:194](e,t)},function:S,number:function(e,t){var n,r=0|t;if(t!==r)return void f[n=203](e,t);n=-32<=r&&r<=127?255&r:0<=r?r<=255?204:r<=65535?205:206:-128<=r?208:-32768<=r?209:210;f[n](e,r)},object:d?function(e,t){if(y(t))return function(e,t){var n=t.length;f[n<32?160+n:n<=65535?218:219](e,n),e.send(t)}(e,t);_(e,t)}:_,string:function(e){return t;function t(t,n){var r=n.length,i=5+3*r;t.offset=t.reserve(i);var s=t.buffer,a=e(r),c=t.offset+a;r=o.write.call(s,n,c);var u=e(r);if(a!==u){var h=c+u-a,l=c+r;o.copy.call(s,s,h,c,l)}f[1===u?160+r:u<=3?215+u:219](t,r),t.offset+=r}}(d?function(e){return e<32?1:e<=65535?3:5}:function(e){return e<32?1:e<=255?2:e<=65535?3:5}),symbol:S,undefined:S};return g;function _(t,i){if(null===i)return S(t,i);if(y(i))return m(t,i);if(e(i))return function(e,t){var n=t.length;f[n<16?144+n:n<=65535?220:221](e,n);for(var r=e.codec.encode,i=0;i<n;i++)r(e,t[i])}(t,i);if(n.isUint64BE(i))return function(e,t){f[207](e,t.toArray())}(t,i);if(r.isInt64BE(i))return function(e,t){f[211](e,t.toArray())}(t,i);var o=t.codec.getExtPacker(i);if(o&&(i=o(i)),i instanceof c)return function(e,t){var n=t.buffer,r=n.length,i=l[r]||(r<255?199:r<=65535?200:201);f[i](e,r),a[t.type](e),e.send(n)}(t,i);v(t,i)}function S(e,t){f[192](e,t)}function E(e,t){var n=t.length;f[n<255?196:n<=65535?197:198](e,n),e.send(t)}function C(e,t){var n=Object.keys(t),r=n.length;f[r<16?128+r:r<=65535?222:223](e,r);var i=e.codec.encode;n.forEach((function(n){i(e,n),i(e,t[n])}))}},kt}var qt,Gt,Vt={};function Yt(){if(qt)return Vt;qt=1;var e=st();Vt.createCodec=i,Vt.install=function(e){for(var t in e)n.prototype[t]=r(n.prototype[t],e[t])},Vt.filter=function(t){return e(t)?function(e){return e=e.slice(),function(n){return e.reduce(t,n)};function t(e,t){return t(e)}}(t):t};var t=wt();function n(e){if(!(this instanceof n))return new n(e);this.options=e,this.init()}function r(e,t){return e&&t?function(){return e.apply(this,arguments),t.apply(this,arguments)}:e||t}function i(e){return new n(e)}return n.prototype.init=function(){var e=this.options;return e&&e.uint8array&&(this.bufferish=t.Uint8Array),this},Vt.preset=i({preset:!0}),Vt}function Qt(){if(Gt)return nt;Gt=1;var e=At().ExtBuffer,t=Mt(),n=jt(),r=Yt();function i(){var e=this.options;return this.encode=function(e){var t=n.getWriteType(e);return function(e,n){var r=t[typeof n];if(!r)throw new Error('Unsupported type "'+typeof n+'": '+n);r(e,n)}}(e),e&&e.preset&&t.setExtPackers(this),this}return r.install({addExtPacker:function(t,n,i){i=r.filter(i);var o=n.name;if(o&&"Object"!==o){(this.extPackers||(this.extPackers={}))[o]=s}else{(this.extEncoderList||(this.extEncoderList=[])).unshift([n,s])}function s(n){return i&&(n=i(n)),new e(n,t)}},getExtPacker:function(e){var t=this.extPackers||(this.extPackers={}),n=e.constructor,r=n&&n.name&&t[n.name];if(r)return r;for(var i=this.extEncoderList||(this.extEncoderList=[]),o=i.length,s=0;s<o;s++){var a=i[s];if(n===a[0])return a[1]}},init:i}),nt.preset=i.call(r.preset),nt}var Jt,Zt,Xt,Kt={};function $t(){if(Jt)return Kt;Jt=1,Kt.FlexDecoder=n,Kt.FlexEncoder=r;var e=wt(),t="BUFFER_SHORTAGE";function n(){if(!(this instanceof n))return new n}function r(){if(!(this instanceof r))return new r}function i(){throw new Error("method not implemented: write()")}function o(){throw new Error("method not implemented: fetch()")}function s(){return this.buffers&&this.buffers.length?(this.flush(),this.pull()):this.fetch()}function a(e){(this.buffers||(this.buffers=[])).push(e)}function c(){return(this.buffers||(this.buffers=[])).shift()}function u(e){return function(t){for(var n in e)t[n]=e[n];return t}}return n.mixin=u({bufferish:e,write:function(t){var n=this.offset?e.prototype.slice.call(this.buffer,this.offset):this.buffer;this.buffer=n?t?this.bufferish.concat([n,t]):n:t,this.offset=0},fetch:o,flush:function(){for(;this.offset<this.buffer.length;){var e,n=this.offset;try{e=this.fetch()}catch(e){if(e&&e.message!=t)throw e;this.offset=n;break}this.push(e)}},push:a,pull:c,read:s,reserve:function(e){var n=this.offset,r=n+e;if(r>this.buffer.length)throw new Error(t);return this.offset=r,n},offset:0}),n.mixin(n.prototype),r.mixin=u({bufferish:e,write:i,fetch:function(){var t=this.start;if(t<this.offset){var n=this.start=this.offset;return e.prototype.slice.call(this.buffer,t,n)}},flush:function(){for(;this.start<this.offset;){var e=this.fetch();e&&this.push(e)}},push:a,pull:function(){var e=this.buffers||(this.buffers=[]),t=e.length>1?this.bufferish.concat(e):e[0];return e.length=0,t},read:s,reserve:function(e){var t=0|e;if(this.buffer){var n=this.buffer.length,r=0|this.offset,i=r+t;if(i<n)return this.offset=i,r;this.flush(),e=Math.max(e,Math.min(2*n,this.maxBufferSize))}return e=Math.max(e,this.minBufferSize),this.buffer=this.bufferish.alloc(e),this.start=0,this.offset=t,0},send:function(t){var n=t.length;if(n>this.minBufferSize)this.flush(),this.push(t);else{var r=this.reserve(n);e.prototype.copy.call(t,this.buffer,r)}},maxBufferSize:65536,minBufferSize:2048,offset:0,start:0}),r.mixin(r.prototype),Kt}function en(){if(Zt)return tt;Zt=1,tt.EncodeBuffer=t;var e=Qt().preset;function t(e){if(!(this instanceof t))return new t(e);if(e&&(this.options=e,e.codec)){var n=this.codec=e.codec;n.bufferish&&(this.bufferish=n.bufferish)}}return $t().FlexEncoder.mixin(t.prototype),t.prototype.codec=e,t.prototype.write=function(e){this.codec.encode(this,e)},tt}function tn(){if(Xt)return et;Xt=1,et.encode=function(t,n){var r=new e(n);return r.write(t),r.read()};var e=en().EncodeBuffer;return et}var nn,rn={},on={},sn={},an={};function cn(){if(nn)return an;nn=1,an.setExtUnpackers=function(e){e.addExtUnpacker(14,[i,s(Error)]),e.addExtUnpacker(1,[i,s(EvalError)]),e.addExtUnpacker(2,[i,s(RangeError)]),e.addExtUnpacker(3,[i,s(ReferenceError)]),e.addExtUnpacker(4,[i,s(SyntaxError)]),e.addExtUnpacker(5,[i,s(TypeError)]),e.addExtUnpacker(6,[i,s(URIError)]),e.addExtUnpacker(10,[i,o]),e.addExtUnpacker(11,[i,a(Boolean)]),e.addExtUnpacker(12,[i,a(String)]),e.addExtUnpacker(13,[i,a(Date)]),e.addExtUnpacker(15,[i,a(Number)]),"undefined"!=typeof Uint8Array&&(e.addExtUnpacker(17,a(Int8Array)),e.addExtUnpacker(18,a(Uint8Array)),e.addExtUnpacker(19,[c,a(Int16Array)]),e.addExtUnpacker(20,[c,a(Uint16Array)]),e.addExtUnpacker(21,[c,a(Int32Array)]),e.addExtUnpacker(22,[c,a(Uint32Array)]),e.addExtUnpacker(23,[c,a(Float32Array)]),"undefined"!=typeof Float64Array&&e.addExtUnpacker(24,[c,a(Float64Array)]),"undefined"!=typeof Uint8ClampedArray&&e.addExtUnpacker(25,a(Uint8ClampedArray)),e.addExtUnpacker(26,c),e.addExtUnpacker(29,[c,a(DataView)]));t.hasBuffer&&e.addExtUnpacker(27,a(n))};var e,t=wt(),n=t.global,r={name:1,message:1,stack:1,columnNumber:1,fileName:1,lineNumber:1};function i(t){return e||(e=Sn().decode),e(t)}function o(e){return RegExp.apply(null,e)}function s(e){return function(t){var n=new e;for(var i in r)n[i]=t[i];return n}}function a(e){return function(t){return new e(t)}}function c(e){return new Uint8Array(e).buffer}return an}var un,hn={};function ln(){if(un)return hn;un=1;var e=zt(),t=Ot(),n=t.Uint64BE,r=t.Int64BE;hn.getReadFormat=function(e){var t=i.hasArrayBuffer&&e&&e.binarraybuffer,n=e&&e.int64,r={map:s&&e&&e.usemap?u:c,array:h,str:l,bin:t?d:f,ext:p,uint8:y,uint16:v,uint32:_,uint64:E(8,n?w:C),int8:m,int16:g,int32:S,int64:E(8,n?A:b),float32:E(4,T),float64:E(8,x)};return r},hn.readUint8=y;var i=wt(),o=bt(),s="undefined"!=typeof Map,a=!0;function c(e,t){var n,r={},i=new Array(t),o=new Array(t),s=e.codec.decode;for(n=0;n<t;n++)i[n]=s(e),o[n]=s(e);for(n=0;n<t;n++)r[i[n]]=o[n];return r}function u(e,t){var n,r=new Map,i=new Array(t),o=new Array(t),s=e.codec.decode;for(n=0;n<t;n++)i[n]=s(e),o[n]=s(e);for(n=0;n<t;n++)r.set(i[n],o[n]);return r}function h(e,t){for(var n=new Array(t),r=e.codec.decode,i=0;i<t;i++)n[i]=r(e);return n}function l(e,t){var n=e.reserve(t),r=n+t;return o.toString.call(e.buffer,"utf-8",n,r)}function f(e,t){var n=e.reserve(t),r=n+t,s=o.slice.call(e.buffer,n,r);return i.from(s)}function d(e,t){var n=e.reserve(t),r=n+t,s=o.slice.call(e.buffer,n,r);return i.Uint8Array.from(s).buffer}function p(e,t){var n=e.reserve(t+1),r=e.buffer[n++],i=n+t,s=e.codec.getExtUnpacker(r);if(!s)throw new Error("Invalid ext type: "+(r?"0x"+r.toString(16):r));return s(o.slice.call(e.buffer,n,i))}function y(e){var t=e.reserve(1);return e.buffer[t]}function m(e){var t=e.reserve(1),n=e.buffer[t];return 128&n?n-256:n}function v(e){var t=e.reserve(2),n=e.buffer;return n[t++]<<8|n[t]}function g(e){var t=e.reserve(2),n=e.buffer,r=n[t++]<<8|n[t];return 32768&r?r-65536:r}function _(e){var t=e.reserve(4),n=e.buffer;return 16777216*n[t++]+(n[t++]<<16)+(n[t++]<<8)+n[t]}function S(e){var t=e.reserve(4),n=e.buffer;return n[t++]<<24|n[t++]<<16|n[t++]<<8|n[t]}function E(e,t){return function(n){var r=n.reserve(e);return t.call(n.buffer,r,a)}}function C(e){return new n(this,e).toNumber()}function b(e){return new r(this,e).toNumber()}function w(e){return new n(this,e)}function A(e){return new r(this,e)}function T(t){return e.read(this,t,!1,23,4)}function x(t){return e.read(this,t,!1,52,8)}return hn}var fn,dn,pn,yn,mn={};function vn(){if(fn)return mn;fn=1;var e=ln();function t(e){var t,o=new Array(256);for(t=0;t<=127;t++)o[t]=n(t);for(t=128;t<=143;t++)o[t]=i(t-128,e.map);for(t=144;t<=159;t++)o[t]=i(t-144,e.array);for(t=160;t<=191;t++)o[t]=i(t-160,e.str);for(o[192]=n(null),o[193]=null,o[194]=n(!1),o[195]=n(!0),o[196]=r(e.uint8,e.bin),o[197]=r(e.uint16,e.bin),o[198]=r(e.uint32,e.bin),o[199]=r(e.uint8,e.ext),o[200]=r(e.uint16,e.ext),o[201]=r(e.uint32,e.ext),o[202]=e.float32,o[203]=e.float64,o[204]=e.uint8,o[205]=e.uint16,o[206]=e.uint32,o[207]=e.uint64,o[208]=e.int8,o[209]=e.int16,o[210]=e.int32,o[211]=e.int64,o[212]=i(1,e.ext),o[213]=i(2,e.ext),o[214]=i(4,e.ext),o[215]=i(8,e.ext),o[216]=i(16,e.ext),o[217]=r(e.uint8,e.str),o[218]=r(e.uint16,e.str),o[219]=r(e.uint32,e.str),o[220]=r(e.uint16,e.array),o[221]=r(e.uint32,e.array),o[222]=r(e.uint16,e.map),o[223]=r(e.uint32,e.map),t=224;t<=255;t++)o[t]=n(t-256);return o}function n(e){return function(){return e}}function r(e,t){return function(n){var r=e(n);return t(n,r)}}function i(e,t){return function(n){return t(n,e)}}return mn.getReadToken=function(n){var r=e.getReadFormat(n);return n&&n.useraw?function(e){var n,r=t(e).slice();for(r[217]=r[196],r[218]=r[197],r[219]=r[198],n=160;n<=191;n++)r[n]=i(n-160,e.bin);return r}(r):t(r)},mn}function gn(){if(dn)return sn;dn=1;var e=At().ExtBuffer,t=cn(),n=ln().readUint8,r=vn(),i=Yt();function o(){var e=this.options;return this.decode=function(e){var t=r.getReadToken(e);return function(e){var r=n(e),i=t[r];if(!i)throw new Error("Invalid type: "+(r?"0x"+r.toString(16):r));return i(e)}}(e),e&&e.preset&&t.setExtUnpackers(this),this}return i.install({addExtUnpacker:function(e,t){(this.extUnpackers||(this.extUnpackers=[]))[e]=i.filter(t)},getExtUnpacker:function(t){return(this.extUnpackers||(this.extUnpackers=[]))[t]||function(n){return new e(n,t)}},init:o}),sn.preset=o.call(i.preset),sn}function _n(){if(pn)return on;pn=1,on.DecodeBuffer=t;var e=gn().preset;function t(e){if(!(this instanceof t))return new t(e);if(e&&(this.options=e,e.codec)){var n=this.codec=e.codec;n.bufferish&&(this.bufferish=n.bufferish)}}return $t().FlexDecoder.mixin(t.prototype),t.prototype.codec=e,t.prototype.fetch=function(){return this.codec.decode(this)},on}function Sn(){if(yn)return rn;yn=1,rn.decode=function(t,n){var r=new e(n);return r.write(t),r.read()};var e=_n().DecodeBuffer;return rn}var En,Cn,bn={},wn={exports:{}};function An(){return En||(En=1,function(e){!function(t){e.exports=t;var n="listeners",r={on:function(e,t){return s(this,e).push(t),this},once:function(e,t){var n=this;return r.originalListener=t,s(n,e).push(r),n;function r(){o.call(n,e,r),t.apply(this,arguments)}},off:o,emit:function(e,t){var n=this,r=s(n,e,!0);if(!r)return!1;var i=arguments.length;if(1===i)r.forEach((function(e){e.call(n)}));else if(2===i)r.forEach((function(e){e.call(n,t)}));else{var o=Array.prototype.slice.call(arguments,1);r.forEach((function(e){e.apply(n,o)}))}return!!r.length}};function i(e){for(var t in r)e[t]=r[t];return e}function o(e,t){var r,i=this;if(arguments.length){if(t){if(r=s(i,e,!0)){if(!(r=r.filter((function(e){return e!==t&&e.originalListener!==t}))).length)return o.call(i,e);i[n][e]=r}}else if((r=i[n])&&(delete r[e],!Object.keys(r).length))return o.call(i)}else delete i[n];return i}function s(e,t,r){if(!r||e[n]){var i=e[n]||(e[n]={});return i[t]||(i[t]=[])}}i(t.prototype),t.mixin=i}((function e(){if(!(this instanceof e))return new e}))}(wn)),wn.exports}function Tn(){if(Cn)return bn;Cn=1,bn.Encoder=n;var e=An(),t=en().EncodeBuffer;function n(e){if(!(this instanceof n))return new n(e);t.call(this,e)}return n.prototype=new t,e.mixin(n.prototype),n.prototype.encode=function(e){this.write(e),this.emit("data",this.read())},n.prototype.end=function(e){arguments.length&&this.encode(e),this.flush(),this.emit("end")},bn}var xn,Mn={};function In(){if(xn)return Mn;xn=1,Mn.Decoder=n;var e=An(),t=_n().DecodeBuffer;function n(e){if(!(this instanceof n))return new n(e);t.call(this,e)}return n.prototype=new t,e.mixin(n.prototype),n.prototype.decode=function(e){arguments.length&&this.write(e),this.flush()},n.prototype.push=function(e){this.emit("data",e)},n.prototype.end=function(e){this.decode(e),this.emit("end")},Mn}var kn,Dn={};function On(){return kn||(kn=1,Dn.createCodec=Yt().createCodec),Dn}var Rn,Bn,Pn={};function zn(){return Rn||(Rn=1,Pn.codec={preset:Yt().preset}),Pn}function Nn(){return Bn||(Bn=1,$e.encode=tn().encode,$e.decode=Sn().decode,$e.Encoder=Tn().Encoder,$e.Decoder=In().Decoder,$e.createCodec=On().createCodec,$e.codec=zn().codec),$e}var Wn,Ln=Nn(),Fn=function(){function e(){}return e.serialize=function(e,t){var n=a({systems:!1,format:"json",pretty:!0,includeMetadata:!0},t),r=this.filterEntities(e,n),i=Ke.serializeEntities(r,!0),o=this.buildComponentTypeRegistry(r),s=this.serializeSceneData(e.sceneData),c={name:e.name,version:this.SERIALIZATION_VERSION,entities:i,componentTypeRegistry:o};return s&&Object.keys(s).length>0&&(c.sceneData=s),n.includeMetadata&&(c.timestamp=Date.now(),c.metadata={entityCount:i.length,componentTypeCount:o.length,serializationOptions:n}),"json"===n.format?n.pretty?JSON.stringify(c,null,2):JSON.stringify(c):Ln.encode(c)},e.deserialize=function(e,t,n){var r,i=a({strategy:"replace",preserveIds:!1},n);try{r="string"==typeof t?JSON.parse(t):Ln.decode(t)}catch(e){throw new Error("Failed to parse save data: "+e)}i.migration&&r.version!==this.SERIALIZATION_VERSION&&(r=i.migration(r.version,this.SERIALIZATION_VERSION,r));var o=i.componentRegistry||this.getGlobalComponentRegistry();"replace"===i.strategy&&e.destroyAllEntities();for(var c,u=s(Ke.deserializeEntities(r.entities,o,(function(){return e.identifierPool.checkOut()}),i.preserveIds||!1,e));!(c=u()).done;){var h=c.value;e.addEntity(h)}r.sceneData&&this.deserializeSceneData(r.sceneData,e.sceneData)},e.serializeSceneData=function(e){for(var t,n={},r=s(e);!(t=r()).done;){var i=t.value,o=i[0],a=i[1];n[o]=this.serializeValue(a)}return n},e.deserializeSceneData=function(e,t){t.clear();for(var n=0,r=Object.entries(e);n<r.length;n++){var i=r[n],o=i[0],s=i[1];t.set(o,this.deserializeValue(s))}},e.serializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if(e instanceof Date)return{__type:"Date",value:e.toISOString()};if(e instanceof Map)return{__type:"Map",value:Array.from(e.entries())};if(e instanceof Set)return{__type:"Set",value:Array.from(e)};if(Array.isArray(e))return e.map((function(e){return t.serializeValue(e)}));if("object"===n){var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=this.serializeValue(e[i]));return r}},e.deserializeValue=function(e){var t=this;if(null==e)return e;var n=typeof e;if("string"===n||"number"===n||"boolean"===n)return e;if("object"===n&&e.__type)switch(e.__type){case"Date":return new Date(e.value);case"Map":return new Map(e.value);case"Set":return new Set(e.value)}if(Array.isArray(e))return e.map((function(e){return t.deserializeValue(e)}));if("object"===n){var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=this.deserializeValue(e[i]));return r}return e},e.filterEntities=function(e,t){var n=Array.from(e.entities.buffer);if(t.components&&t.components.length>0){var r=new Set(t.components);return n.filter((function(e){return Array.from(e.components).some((function(e){return r.has(e.constructor)}))}))}return n},e.buildComponentTypeRegistry=function(e){for(var t,n=new Map,r=s(e);!(t=r()).done;)for(var i,o=s(t.value.components);!(i=o()).done;){var a=i.value,c=N(a.constructor),u=Ve(a);u&&!n.has(c)&&n.set(c,u.options.version)}return Array.from(n.entries()).map((function(e){return{typeName:e[0],version:e[1]}}))},e.getGlobalComponentRegistry=function(){return pe.getAllComponentNames()},e.validate=function(e){var t=[];try{var n=JSON.parse(e);return n.version||t.push("Missing version field"),n.entities&&Array.isArray(n.entities)||t.push("Missing or invalid entities field"),n.componentTypeRegistry&&Array.isArray(n.componentTypeRegistry)||t.push("Missing or invalid componentTypeRegistry field"),{valid:0===t.length,version:n.version,errors:t.length>0?t:void 0}}catch(e){return{valid:!1,errors:["JSON parse error: "+e]}}},e.getInfo=function(e){try{var t,n=JSON.parse(e);return{name:n.name,version:n.version,timestamp:n.timestamp,entityCount:(null===(t=n.metadata)||void 0===t?void 0:t.entityCount)||n.entities.length,componentTypeCount:n.componentTypeRegistry.length}}catch(e){return null}},e}();Fn.SERIALIZATION_VERSION=1,exports.ChangeOperation=void 0,(Wn=exports.ChangeOperation||(exports.ChangeOperation={})).EntityAdded="entity_added",Wn.EntityRemoved="entity_removed",Wn.EntityUpdated="entity_updated",Wn.ComponentAdded="component_added",Wn.ComponentRemoved="component_removed",Wn.ComponentUpdated="component_updated",Wn.SceneDataUpdated="scene_data_updated";var Un=function(){function e(){}return e.createSnapshot=function(e,t){for(var n,r=a({deepComponentComparison:!0,trackSceneData:!0,compressSnapshot:!1},t),i={version:++this.snapshotVersion,entityIds:new Set,entities:new Map,components:new Map,sceneData:new Map},o=s(e.entities.buffer);!(n=o()).done;){var c,u=n.value;if(i.entityIds.add(u.id),i.entities.set(u.id,{name:u.name,tag:u.tag,active:u.active,enabled:u.enabled,updateOrder:u.updateOrder,parentId:null===(c=u.parent)||void 0===c?void 0:c.id}),r.deepComponentComparison){for(var h,l=new Map,f=s(u.components);!(h=f()).done;){var d=h.value,p=Xe.serialize(d);p&&l.set(p.type,JSON.stringify(p.data))}l.size>0&&i.components.set(u.id,l)}}if(r.trackSceneData)for(var y,m=s(e.sceneData);!(y=m()).done;){var v=y.value,g=v[0],_=v[1];i.sceneData.set(g,JSON.stringify(_))}return i},e.computeIncremental=function(e,t,n){for(var r,i=a({deepComponentComparison:!0,trackSceneData:!0},n),o={version:++this.snapshotVersion,timestamp:Date.now(),sceneName:e.name,baseVersion:t.version,entityChanges:[],componentChanges:[],sceneDataChanges:[]},c=new Set,u=s(e.entities.buffer);!(r=u()).done;){var h=r.value;if(c.add(h.id),t.entityIds.has(h.id)){var l,f,d=t.entities.get(h.id);if(d.name!==h.name||d.tag!==h.tag||d.active!==h.active||d.enabled!==h.enabled||d.updateOrder!==h.updateOrder||d.parentId!==(null===(l=h.parent)||void 0===l?void 0:l.id))o.entityChanges.push({operation:exports.ChangeOperation.EntityUpdated,entityId:h.id,entityData:{name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder,parentId:null===(f=h.parent)||void 0===f?void 0:f.id}});i.deepComponentComparison&&this.detectComponentChanges(h,t,o.componentChanges)}else{var p;o.entityChanges.push({operation:exports.ChangeOperation.EntityAdded,entityId:h.id,entityName:h.name,entityData:{id:h.id,name:h.name,tag:h.tag,active:h.active,enabled:h.enabled,updateOrder:h.updateOrder,parentId:null===(p=h.parent)||void 0===p?void 0:p.id,components:[],children:[]}});for(var y,m=s(h.components);!(y=m()).done;){var v=y.value,g=Xe.serialize(v);g&&o.componentChanges.push({operation:exports.ChangeOperation.ComponentAdded,entityId:h.id,componentType:g.type,componentData:g})}}}for(var _,S=s(t.entityIds);!(_=S()).done;){var E=_.value;c.has(E)||o.entityChanges.push({operation:exports.ChangeOperation.EntityRemoved,entityId:E})}return i.trackSceneData&&this.detectSceneDataChanges(e,t,o.sceneDataChanges),o},e.detectComponentChanges=function(e,t,n){for(var r,i=t.components.get(e.id),o=new Map,a=s(e.components);!(r=a()).done;){var c=r.value,u=Xe.serialize(c);u&&o.set(u.type,u)}for(var h,l=s(o);!(h=l()).done;){var f=h.value,d=f[0],p=f[1],y=JSON.stringify(p.data);i&&i.has(d)?i.get(d)!==y&&n.push({operation:exports.ChangeOperation.ComponentUpdated,entityId:e.id,componentType:d,componentData:p}):n.push({operation:exports.ChangeOperation.ComponentAdded,entityId:e.id,componentType:d,componentData:p})}if(i)for(var m,v=s(i.keys());!(m=v()).done;){var g=m.value;o.has(g)||n.push({operation:exports.ChangeOperation.ComponentRemoved,entityId:e.id,componentType:g})}},e.detectSceneDataChanges=function(e,t,n){for(var r,i=new Set,o=s(e.sceneData);!(r=o()).done;){var a=r.value,c=a[0],u=a[1];i.add(c);var h=JSON.stringify(u),l=t.sceneData.get(c);l&&l===h||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:c,value:u})}for(var f,d=s(t.sceneData.keys());!(f=d()).done;){var p=f.value;i.has(p)||n.push({operation:exports.ChangeOperation.SceneDataUpdated,key:p,value:void 0,deleted:!0})}},e.applyIncremental=function(e,t,n){for(var r,i=s(t.entityChanges);!(r=i()).done;){var o=r.value;switch(o.operation){case exports.ChangeOperation.EntityAdded:this.applyEntityAdded(e,o);break;case exports.ChangeOperation.EntityRemoved:this.applyEntityRemoved(e,o);break;case exports.ChangeOperation.EntityUpdated:this.applyEntityUpdated(e,o)}}for(var a,c=s(t.componentChanges);!(a=c()).done;){var u=a.value;switch(u.operation){case exports.ChangeOperation.ComponentAdded:this.applyComponentAdded(e,u,n);break;case exports.ChangeOperation.ComponentRemoved:this.applyComponentRemoved(e,u,n);break;case exports.ChangeOperation.ComponentUpdated:this.applyComponentUpdated(e,u,n)}}for(var h,l=s(t.sceneDataChanges);!(h=l()).done;){var f=h.value;f.deleted?e.sceneData.delete(f.key):e.sceneData.set(f.key,f.value)}},e.applyEntityAdded=function(e,t){var n,r;if(t.entityData){var i=new ge(t.entityName||"Entity",t.entityId);i.tag=t.entityData.tag||0,i.active=null===(n=t.entityData.active)||void 0===n||n,i.enabled=null===(r=t.entityData.enabled)||void 0===r||r,i.updateOrder=t.entityData.updateOrder||0,e.addEntity(i)}},e.applyEntityRemoved=function(e,t){var n=e.entities.findEntityById(t.entityId);n&&n.destroy()},e.applyEntityUpdated=function(e,t){if(t.entityData){var n=e.entities.findEntityById(t.entityId);if(n)if(void 0!==t.entityData.name&&(n.name=t.entityData.name),void 0!==t.entityData.tag&&(n.tag=t.entityData.tag),void 0!==t.entityData.active&&(n.active=t.entityData.active),void 0!==t.entityData.enabled&&(n.enabled=t.entityData.enabled),void 0!==t.entityData.updateOrder&&(n.updateOrder=t.entityData.updateOrder),void 0!==t.entityData.parentId){var r=e.entities.findEntityById(t.entityData.parentId);r&&n.parent!==r&&(n.parent&&n.parent.removeChild(n),r.addChild(n))}else n.parent&&n.parent.removeChild(n)}},e.applyComponentAdded=function(e,t,n){if(t.componentData){var r=e.entities.findEntityById(t.entityId);if(r){var i=Xe.deserialize(t.componentData,n);i&&r.addComponent(i)}}},e.applyComponentRemoved=function(e,t,n){var r=e.entities.findEntityById(t.entityId);if(r){var i=n.get(t.componentType);i&&r.removeComponentByType(i)}},e.applyComponentUpdated=function(e,t,n){if(t.componentData){var r=e.entities.findEntityById(t.entityId);if(r){var i=n.get(t.componentType);if(i){r.removeComponentByType(i);var o=Xe.deserialize(t.componentData,n);o&&r.addComponent(o)}}}},e.serializeIncremental=function(e,t){var n=a({format:"json",pretty:!1},t);return"binary"===n.format?Ln.encode(e):n.pretty?JSON.stringify(e,null,2):JSON.stringify(e)},e.deserializeIncremental=function(e){return"string"==typeof e?JSON.parse(e):Ln.decode(e)},e.getIncrementalSize=function(e,t){void 0===t&&(t="json");var n=this.serializeIncremental(e,{format:t});return"string"==typeof n?"undefined"!=typeof Blob?new Blob([n]).size:"undefined"!=typeof Buffer?Buffer.byteLength(n,"utf8"):(new TextEncoder).encode(n).length:n.length},e.getIncrementalStats=function(e){return{totalChanges:e.entityChanges.length+e.componentChanges.length+e.sceneDataChanges.length,entityChanges:e.entityChanges.length,componentChanges:e.componentChanges.length,sceneDataChanges:e.sceneDataChanges.length,addedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityAdded})).length,removedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityRemoved})).length,updatedEntities:e.entityChanges.filter((function(e){return e.operation===exports.ChangeOperation.EntityUpdated})).length,addedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentAdded})).length,removedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentRemoved})).length,updatedComponents:e.componentChanges.filter((function(e){return e.operation===exports.ChangeOperation.ComponentUpdated})).length}},e.resetVersion=function(){this.snapshotVersion=0},e}();Un.snapshotVersion=0;var Hn,jn=G("ServiceContainer");exports.ServiceLifetime=void 0,(Hn=exports.ServiceLifetime||(exports.ServiceLifetime={})).Singleton="singleton",Hn.Transient="transient";var qn=function(){function e(){this._services=new Map,this._resolving=new Set,this._updatableServices=[]}var t=e.prototype;return t.registerSingleton=function(e,t){this._services.has(e)?jn.warn("Service "+e.name+" is already registered"):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Singleton}),jn.debug("Registered singleton service: "+e.name))},t.registerTransient=function(e,t){this._services.has(e)?jn.warn("Service "+e.name+" is already registered"):(this._services.set(e,{type:e,factory:t,lifetime:exports.ServiceLifetime.Transient}),jn.debug("Registered transient service: "+e.name))},t.registerInstance=function(e,t){if(this._services.has(e))jn.warn("Service "+e.name+" is already registered");else{if(this._services.set(e,{type:e,instance:t,lifetime:exports.ServiceLifetime.Singleton}),A(e)){var n,r=T(e),i=null!==(n=null==r?void 0:r.priority)&&void 0!==n?n:0;this._updatableServices.push({instance:t,priority:i}),this._updatableServices.sort((function(e,t){return e.priority-t.priority})),jn.debug("Service "+e.name+" is updatable (priority: "+i+"), added to update list")}jn.debug("Registered service instance: "+e.name)}},t.resolve=function(e){var t=this._services.get(e);if(!t)throw new Error("Service "+e.name+" is not registered");if(this._resolving.has(e)){var n=Array.from(this._resolving).map((function(e){return e.name})).join(" -> ");throw new Error("Circular dependency detected: "+n+" -> "+e.name)}if(t.lifetime===exports.ServiceLifetime.Singleton&&t.instance)return t.instance;this._resolving.add(e);try{var r;if(r=t.factory?t.factory(this):new t.type,t.lifetime===exports.ServiceLifetime.Singleton&&(t.instance=r,A(t.type))){var i,o=T(t.type),s=null!==(i=null==o?void 0:o.priority)&&void 0!==i?i:0;this._updatableServices.push({instance:r,priority:s}),this._updatableServices.sort((function(e,t){return e.priority-t.priority})),jn.debug("Service "+e.name+" is updatable (priority: "+s+"), added to update list")}return r}finally{this._resolving.delete(e)}},t.tryResolve=function(e){try{return this.resolve(e)}catch(e){return null}},t.isRegistered=function(e){return this._services.has(e)},t.unregister=function(e){var t=this._services.get(e);if(!t)return!1;if(t.instance){var n=this._updatableServices.findIndex((function(e){return e.instance===t.instance}));-1!==n&&this._updatableServices.splice(n,1),t.instance.dispose()}return this._services.delete(e),jn.debug("Unregistered service: "+e.name),!0},t.clear=function(){for(var e,t=s(this._services);!(e=t()).done;){var n=e.value[1];n.instance&&n.instance.dispose()}this._services.clear(),this._updatableServices=[],jn.debug("Cleared all services")},t.getRegisteredServices=function(){return Array.from(this._services.keys())},t.updateAll=function(e){for(var t,n=s(this._updatableServices);!(t=n()).done;){t.value.instance.update(e)}},t.getUpdatableCount=function(){return this._updatableServices.length},t.getAll=function(){for(var e,t=[],n=s(this._services.values());!(e=n()).done;){var r=e.value;r.instance&&t.push(r.instance)}return t},e}(),Gn=function(){function e(e){var t=this;this.name="",this.sceneData=new Map,this._didSceneBegin=!1,this.entities=new Se(this),this.identifierPool=new Ee,this.componentStorageManager=new me,this.querySystem=new Re,this.eventSystem=new Pe,this.referenceTracker=new Z,this._services=new qn,this.logger=G("Scene"),this._performanceMonitor=(null==e?void 0:e.performanceMonitor)||new x,null!=e&&e.name&&(this.name=e.name),ge.eventBus||(ge.eventBus=new We(!1)),ge.eventBus&&ge.eventBus.onComponentAdded((function(e){t.eventSystem.emitSync("component:added",e)}))}var t=e.prototype;return t.getSystem=function(e){return this._services.tryResolve(e)},t.initialize=function(){},t.onStart=function(){},t.unload=function(){},t.begin=function(){this._didSceneBegin=!0,this.onStart()},t.end=function(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this._services.clear(),this.unload()},t.update=function(){ae.getInstance().update(),this.entities.updateLists();for(var e,t=this.systems,n=s(t);!(e=n()).done;){var r=e.value;if(r.enabled)try{r.update()}catch(e){this.logger.error("Error in system "+r.constructor.name+".update():",e)}}for(var i,o=s(t);!(i=o()).done;){var a=i.value;if(a.enabled)try{a.lateUpdate()}catch(e){this.logger.error("Error in system "+a.constructor.name+".lateUpdate():",e)}}},t.createEntity=function(e){var t=new ge(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.systems);!(e=t()).done;){e.value.clearEntityCache()}},t.addEntity=function(e,t){return void 0===t&&(t=!1),this.entities.add(e),e.scene=this,this.querySystem.addEntity(e,t),t||this.clearSystemEntityCaches(),this.eventSystem.emitSync("entity:added",{entity:e,scene:this}),e},t.createEntities=function(e,t){void 0===t&&(t="Entity");for(var n=[],r=0;r<e;r++){var i=new ge(t+"_"+r,this.identifierPool.checkOut());i.scene=this,n.push(i)}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.destroyEntities=function(e){if(0!==e.length){for(var t,n=s(e);!(t=n()).done;){t.value._isDestroyed=!0}for(var r,i=s(e);!(r=i()).done;){r.value.removeAllComponents()}for(var o,a=s(e);!(o=a()).done;){var c=o.value;this.entities.remove(c),this.querySystem.removeEntity(c)}this.querySystem.clearCache(),this.clearSystemEntityCaches()}},t.destroyAllEntities=function(){this.entities.removeAllEntities(),this.querySystem.setEntities([])},t.findEntity=function(e){return this.entities.findEntity(e)},t.findEntityById=function(e){return this.entities.findEntityById(e)},t.findEntitiesByTag=function(e){for(var t,n=[],r=s(this.entities.buffer);!(t=r()).done;){var i=t.value;i.tag===e&&n.push(i)}return n},t.getEntityByName=function(e){return this.findEntity(e)},t.getEntitiesByTag=function(e){return this.findEntitiesByTag(e)},t.queryAll=function(){var e;return(e=this.querySystem).queryAll.apply(e,arguments)},t.queryAny=function(){var e;return(e=this.querySystem).queryAny.apply(e,arguments)},t.queryNone=function(){var e;return(e=this.querySystem).queryNone.apply(e,arguments)},t.query=function(){return new Ue},t.addEntityProcessor=function(e){var t,n;if("function"==typeof e){if(n=e,this._services.isRegistered(n))return this._services.resolve(n);t=b(n)?w(n,this._services):new n}else if(n=(t=e).constructor,this._services.isRegistered(n))return t;t.scene=this,t.setPerformanceMonitor(this._performanceMonitor);var r=z(n);return void 0!==(null==r?void 0:r.updateOrder)&&t.setUpdateOrder(r.updateOrder),void 0!==(null==r?void 0:r.enabled)&&(t.enabled=r.enabled),this._services.registerInstance(n,t),t.initialize(),t},t.registerSystems=function(e){for(var t,n=[],r=s(e);!(t=r()).done;){var i=t.value,o=this.addEntityProcessor(i);n.push(o)}return n},t.addSystem=function(e){return this.addEntityProcessor(e)},t.removeEntityProcessor=function(e){var t=e.constructor;this._services.unregister(t),e.reset()},t.removeSystem=function(e){this.removeEntityProcessor(e)},t.getEntityProcessor=function(e){return this._services.tryResolve(e)},t.getStats=function(){return{entityCount:this.entities.count,processorCount:this.systems.length,componentStorageStats:this.componentStorageManager.getAllStats()}},t.getDebugInfo=function(){var e=this.systems;return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:e.length,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((function(e){return{name:e.name,id:e.id,componentCount:e.components.length,componentTypes:e.components.map((function(e){return L(e)}))}})),processors:e.map((function(e){var t;return{name:F(e),updateOrder:e.updateOrder,entityCount:(null===(t=e._entities)||void 0===t?void 0:t.length)||0}})),componentStats:this.componentStorageManager.getAllStats()}},t.serialize=function(e){return Fn.serialize(this,e)},t.deserialize=function(e,t){Fn.deserialize(this,e,t)},t.createIncrementalSnapshot=function(e){this._incrementalBaseSnapshot=Un.createSnapshot(this,e)},t.serializeIncremental=function(e){if(!this._incrementalBaseSnapshot)throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照");return Un.computeIncremental(this,this._incrementalBaseSnapshot,e)},t.applyIncremental=function(e,t){var n="string"==typeof e||"undefined"!=typeof Buffer&&Buffer.isBuffer(e)||e instanceof Uint8Array?Un.deserializeIncremental(e):e,r=t||pe.getAllComponentNames();Un.applyIncremental(this,n,r)},t.updateIncrementalSnapshot=function(e){this.createIncrementalSnapshot(e)},t.clearIncrementalSnapshot=function(){this._incrementalBaseSnapshot=void 0},t.hasIncrementalSnapshot=function(){return void 0!==this._incrementalBaseSnapshot},o(e,[{key:"systems",get:function(){for(var e,t=[],n=s(this._services.getAll());!(e=n()).done;){var r=e.value;r instanceof be&&t.push(r)}return t.sort((function(e,t){return e.updateOrder-t.updateOrder})),t}},{key:"services",get:function(){return this._services}}])}(),Vn=function(){function e(){this.scene=new Gn}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 _e(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 r=0,i=t;r<i.length;r++){var o=i[r];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 r=0,i=t;r<i.length;r++){var o=i[r];this.scene.addSystem(o)}return this},t.build=function(){return this.scene},e}(),Yn=function(){function e(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.component=r(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}(),Qn=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}(),Jn=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 _e(this.scene,this.scene.componentStorageManager)},t.createScene=function(){return new Vn},t.createComponent=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return r(Yn,[e].concat(n))},t.query=function(){return new Be(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 Qn(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 Zn(e,t,n){return new Jn(e,t,n)}var Xn,Kn=function(){function e(){this._currentScene=null,this._nextScene=null,this._ecsAPI=null,this._logger=G("SceneManager")}var t=e.prototype;return t.setSceneChangedCallback=function(e){this._onSceneChangedCallback=e},t.setScene=function(e){return this._currentScene&&(this._logger.info("Ending scene: "+this._currentScene.name),this._currentScene.end()),this._currentScene=e,this._currentScene.initialize(),this._currentScene.begin(),e.querySystem&&e.eventSystem?this._ecsAPI=Zn(e,e.querySystem,e.eventSystem):this._ecsAPI=null,m.sceneChanged(),this._onSceneChangedCallback&&this._onSceneChangedCallback(),this._logger.info("Scene changed to: "+e.name),e},t.loadScene=function(e){this._nextScene=e,this._logger.info("Scheduled scene load: "+e.name)},t.update=function(){this._nextScene&&(this.setScene(this._nextScene),this._nextScene=null),this._currentScene&&this._currentScene.update()},t.destroy=function(){this._currentScene&&(this._logger.info("Destroying scene: "+this._currentScene.name),this._currentScene.end(),this._currentScene=null),this._nextScene=null,this._ecsAPI=null,this._logger.info("SceneManager destroyed")},t.dispose=function(){this.destroy()},o(e,[{key:"currentScene",get:function(){return this._currentScene}},{key:"api",get:function(){return this._ecsAPI}},{key:"hasScene",get:function(){return null!==this._currentScene}},{key:"hasPendingScene",get:function(){return null!==this._nextScene}}])}();exports.PluginState=void 0,(Xn=exports.PluginState||(exports.PluginState={})).NotInstalled="not_installed",Xn.Installed="installed",Xn.Failed="failed";var $n=G("PluginManager"),er=function(){function e(){this._plugins=new Map,this._metadata=new Map,this._core=null,this._services=null}var t=e.prototype;return t.initialize=function(e,t){this._core=e,this._services=t,$n.info("PluginManager initialized")},t.install=function(){var e=n(l().m((function e(t){var n,r;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(this._core&&this._services){e.n=1;break}throw new Error("PluginManager not initialized. Call initialize() first.");case 1:if(!this._plugins.has(t.name)){e.n=2;break}return $n.warn("Plugin "+t.name+" is already installed"),e.a(2);case 2:return t.dependencies&&t.dependencies.length>0&&this._checkDependencies(t),n={name:t.name,version:t.version,state:exports.PluginState.NotInstalled,installedAt:Date.now()},this._metadata.set(t.name,n),e.p=3,$n.info("Installing plugin: "+t.name+" v"+t.version),e.n=4,t.install(this._core,this._services);case 4:this._plugins.set(t.name,t),n.state=exports.PluginState.Installed,$n.info("Plugin "+t.name+" installed successfully"),e.n=6;break;case 5:throw e.p=5,r=e.v,n.state=exports.PluginState.Failed,n.error=r instanceof Error?r.message:String(r),$n.error("Failed to install plugin "+t.name+":",r),r;case 6:return e.a(2)}}),e,this,[[3,5]])})));return function(t){return e.apply(this,arguments)}}(),t.uninstall=function(){var e=n(l().m((function e(t){var n,r;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(n=this._plugins.get(t)){e.n=1;break}throw new Error("Plugin "+t+" is not installed");case 1:return this._checkDependents(t),e.p=2,$n.info("Uninstalling plugin: "+t),e.n=3,n.uninstall();case 3:this._plugins.delete(t),this._metadata.delete(t),$n.info("Plugin "+t+" uninstalled successfully"),e.n=5;break;case 4:throw e.p=4,r=e.v,$n.error("Failed to uninstall plugin "+t+":",r),r;case 5:return e.a(2)}}),e,this,[[2,4]])})));return function(t){return e.apply(this,arguments)}}(),t.getPlugin=function(e){return this._plugins.get(e)},t.getMetadata=function(e){return this._metadata.get(e)},t.getAllPlugins=function(){return Array.from(this._plugins.values())},t.getAllMetadata=function(){return Array.from(this._metadata.values())},t.isInstalled=function(e){return this._plugins.has(e)},t._checkDependencies=function(e){if(e.dependencies){for(var t,n=[],r=s(e.dependencies);!(t=r()).done;){var i=t.value;this._plugins.has(i)||n.push(i)}if(n.length>0)throw new Error("Plugin "+e.name+" has unmet dependencies: "+n.join(", "))}},t._checkDependents=function(e){for(var t,n=[],r=s(this._plugins.values());!(t=r()).done;){var i=t.value;i.dependencies&&i.dependencies.includes(e)&&n.push(i.name)}if(n.length>0)throw new Error("Cannot uninstall plugin "+e+": it is required by "+n.join(", "))},t.dispose=function(){for(var e,t=s(Array.from(this._plugins.values()).reverse());!(e=t()).done;){var n=e.value;try{$n.info("Disposing plugin: "+n.name),n.uninstall()}catch(e){$n.error("Error disposing plugin "+n.name+":",e)}}this._plugins.clear(),this._metadata.clear(),this._core=null,this._services=null,$n.info("PluginManager disposed")},e}(),tr=G("World"),nr=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(),tr.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 Gn;return"id"in n&&(n.id=e),"name"in n&&!n.name&&(n.name=e),this._scenes.set(e,n),n.initialize(),tr.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),tr.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(),tr.debug("在World '"+this.name+"' 中激活Scene: "+e)):(this._activeScenes.delete(e),tr.debug("在World '"+this.name+"' 中停用Scene: "+e)):tr.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(),tr.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(),tr.debug("从World '"+this.name+"' 中移除全局System: "+e.name),!0)},t.getGlobalSystem=function(e){for(var t,n=s(this._globalSystems);!(t=n()).done;){var r=t.value;if(r instanceof e)return r}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()}tr.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 r,i=s(this._globalSystems);!(r=i()).done;){var o=r.value;o.reset&&o.reset()}this._isActive=!1,tr.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,r=this._scenes.get(n);r&&r.update&&r.update()}this._config.autoCleanup&&this.shouldAutoCleanup()&&this.cleanup()}},t.destroy=function(){tr.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 r,i=s(this._globalSystems);!(r=i()).done;){var o=r.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 r=e.value;r.entities&&(t.totalEntities+=r.entities.count),r.systems&&(t.totalSystems+=r.systems.length)}return t},t.shouldAutoCleanup=function(){for(var e,t=Date.now(),n=s(this._scenes);!(e=n()).done;){var r=e.value,i=r[0],o=r[1];if(!this._activeScenes.has(i)&&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,r=e;n<r.length;n++){var i=r[n],o=this._scenes.get(i);o&&!this._activeScenes.has(i)&&o.entities&&0===o.entities.count&&t-this._createdAt>3e5&&(this.removeScene(i),tr.debug("自动清理空Scene: "+i+" 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}}])}(),rr=G("WorldManager"),ir=function(){function e(e){void 0===e&&(e={}),this._worlds=new Map,this._activeWorlds=new Set,this._cleanupTimer=null,this._isRunning=!1,this._config=a({maxWorlds:50,autoCleanup:!0,cleanupInterval:3e4,debug:!1},e),this._isRunning=!0,rr.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupInterval:this._config.cleanupInterval}),this.startCleanupTimer()}var t=e.prototype;return t.createWorld=function(e,t){if(!e||"string"!=typeof e||""===e.trim())throw new Error("World ID不能为空");if(this._worlds.has(e))throw new Error("World ID '"+e+"' 已存在");if(this._worlds.size>=this._config.maxWorlds)throw new Error("已达到最大World数量限制: "+this._config.maxWorlds);var n=a({name:e,debug:this._config.debug},t),r=new nr(n);return this._worlds.set(e,r),rr.info("创建World: "+e,{config:n}),r},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),rr.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(),rr.debug("激活World: "+e)):(this._activeWorlds.delete(e),n.stop(),rr.debug("停用World: "+e)):rr.warn("World '"+e+"' 不存在")},t.isWorldActive=function(e){return this._activeWorlds.has(e)},t.updateAll=function(){if(this._isRunning)for(var e,t=s(this._activeWorlds);!(e=t()).done;){var n=e.value,r=this._worlds.get(n);r&&r.isActive&&(r.updateGlobalSystems(),r.updateScenes())}},t.getActiveWorlds=function(){for(var e,t=[],n=s(this._activeWorlds);!(e=n()).done;){var r=e.value,i=this._worlds.get(r);i&&t.push(i)}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)}rr.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)}rr.info("停止所有World")},t.findWorlds=function(e){for(var t,n=[],r=s(this._worlds.values());!(t=r()).done;){var i=t.value;e(i)&&n.push(i)}return n},t.findWorldByName=function(e){for(var t,n=s(this._worlds.values());!(t=n()).done;){var r=t.value;if(r.name===e)return r}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 r=e.value,i=r[0],o=r[1],c=o.getStats();t.totalScenes+=c.totalSystems,t.totalEntities+=c.totalEntities,t.totalSystems+=c.totalSystems,t.worlds.push(a({id:i,name:o.name,isActive:this._activeWorlds.has(i),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],r=t[1];return{id:n,isActive:e._activeWorlds.has(n),status:r.getStatus()}}))})},t.cleanup=function(){for(var e,t=[],n=s(this._worlds);!(e=n()).done;){var r=e.value,i=r[0],o=r[1];this.shouldCleanupWorld(o)&&t.push(i)}for(var a=0,c=t;a<c.length;a++){var u=c[a];this.removeWorld(u)}return t.length>0&&rr.debug("清理了 "+t.length+" 个World"),t.length},t.destroy=function(){rr.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,rr.info("WorldManager已销毁")},t.dispose=function(){this.destroy()},t.startCleanupTimer=function(){var e=this;this._config.autoCleanup&&!this._cleanupTimer&&(this._cleanupTimer=setInterval((function(){e.cleanup()}),this._config.cleanupInterval),rr.debug("启动World清理定时器,间隔: "+this._config.cleanupInterval+"ms"))},t.stopCleanupTimer=function(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null,rr.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)}}])}(),or=function(){function e(t){var n,r,i,o=this;if(void 0===t&&(t={}),e._instance=this,this._config=a({debug:!0,enableEntitySystems:!0},t),this._serviceContainer=new qn,this._timerManager=new exports.TimerManager,this._serviceContainer.registerInstance(exports.TimerManager,this._timerManager),this._performanceMonitor=new x,this._serviceContainer.registerInstance(x,this._performanceMonitor),this._config.debug&&this._performanceMonitor.enable(),this._poolManager=new k,this._serviceContainer.registerInstance(k,this._poolManager),this._sceneManager=new Kn,this._serviceContainer.registerInstance(Kn,this._sceneManager),this._sceneManager.setSceneChangedCallback((function(){o._debugManager&&o._debugManager.onSceneChanged()})),this._worldManager=new ir,this._serviceContainer.registerInstance(ir,this._worldManager),this._pluginManager=new er,this._pluginManager.initialize(this,this._serviceContainer),this._serviceContainer.registerInstance(er,this._pluginManager),e.entitySystemsEnabled=null===(n=this._config.enableEntitySystems)||void 0===n||n,this.debug=null===(r=this._config.debug)||void 0===r||r,null!==(i=this._config.debugConfig)&&void 0!==i&&i.enabled){var s=this._config.debugConfig;this._debugManager=new le(this._serviceContainer.resolve(Kn),this._serviceContainer.resolve(x),s),this._serviceContainer.registerInstance(le,this._debugManager)}this.initialize()}e.create=function(t){if(void 0===t&&(t=!0),null==this._instance){var n="boolean"==typeof t?{debug:t,enableEntitySystems:!0}:t;this._instance=new e(n)}else this._logger.warn("Core实例已创建,返回现有实例");return this._instance},e.setScene=function(t){if(!this._instance)throw e._logger.warn("Core实例未创建,请先调用Core.create()"),new Error("Core实例未创建");return this._instance._sceneManager.setScene(t)},e.loadScene=function(t){this._instance?this._instance._sceneManager.loadScene(t):e._logger.warn("Core实例未创建,请先调用Core.create()")},e.update=function(t){this._instance?this._instance.updateInternal(t):e._logger.warn("Core实例未创建,请先调用Core.create()")},e.schedule=function(e,t,n,r){if(void 0===t&&(t=!1),!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");if(!r)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(e,t,n,r)},e.enableDebug=function(t){this._instance?(this._instance._debugManager?this._instance._debugManager.updateConfig(t):(this._instance._debugManager=new le(this._instance._serviceContainer.resolve(Kn),this._instance._serviceContainer.resolve(x),t),this._instance._serviceContainer.registerInstance(le,this._instance._debugManager)),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.installPlugin=function(){var e=n(l().m((function e(t){return l().w((function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.install(t);case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.uninstallPlugin=function(){var e=n(l().m((function e(t){return l().w((function(e){for(;;)switch(e.n){case 0:if(this._instance){e.n=1;break}throw new Error("Core实例未创建,请先调用Core.create()");case 1:return e.n=2,this._instance._pluginManager.uninstall(t);case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.getPlugin=function(e){if(this._instance)return this._instance._pluginManager.getPlugin(e)},e.isPluginInstalled=function(e){return!!this._instance&&this._instance._pluginManager.isInstalled(e)};var t=e.prototype;return t.initialize=function(){var t;e._logger.info("Core initialized",{debug:this.debug,entitySystemsEnabled:e.entitySystemsEnabled,debugEnabled:(null===(t=this._config.debugConfig)||void 0===t?void 0:t.enabled)||!1})},t.updateInternal=function(t){if(!e.paused){var n=this._performanceMonitor.startMonitoring("Core.update");m.update(t),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(m.deltaTime);var r=this._performanceMonitor.startMonitoring("Services.update");this._serviceContainer.updateAll(t),this._performanceMonitor.endMonitoring("Services.update",r,this._serviceContainer.getUpdatableCount()),this._poolManager.update(),this._sceneManager.update(),this._debugManager&&this._debugManager.onFrameUpdate(t),this._performanceMonitor.endMonitoring("Core.update",n)}},e.destroy=function(){this._instance&&(this._instance._debugManager&&this._instance._debugManager.stop(),this._instance._serviceContainer.clear(),e._logger.info("Core destroyed"),this._instance=null)},o(e,null,[{key:"Instance",get:function(){return this._instance}},{key:"services",get:function(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._serviceContainer}},{key:"scene",get:function(){return this._instance?this._instance._sceneManager.currentScene:null}},{key:"ecsAPI",get:function(){return this._instance?this._instance._sceneManager.api:null}},{key:"isDebugEnabled",get:function(){var e;return(null===(e=this._instance)||void 0===e||null===(e=e._config.debugConfig)||void 0===e?void 0:e.enabled)||!1}}])}();or.paused=!1,or._instance=null,or._logger=G("Core");var sr=function(e,t){this.func=e,this.context=t},ar=function(){function e(){this._messageTable=new Map}var t=e.prototype;return t.addObserver=function(e,t,n){var r=this._messageTable.get(e);r||(r=[],this._messageTable.set(e,r)),this.hasObserver(e,t)||r.push(new sr(t,n))},t.removeObserver=function(e,t){var n=this._messageTable.get(e);if(n){var r=n.findIndex((function(e){return e.func==t}));-1!=r&&n.splice(r,1)}},t.emit=function(e){var t=this._messageTable.get(e);if(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];for(var o,a=s(t);!(o=a()).done;){var c,u=o.value;(c=u.func).call.apply(c,[u.context].concat(r))}}},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}(),cr=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)}}])}(),ur=function(){function e(){this.entityId=null,this.id=e._idGenerator++}var t=e.prototype;return t.onAddedToEntity=function(){},t.onRemovedFromEntity=function(){},e}();ur._idGenerator=0;var hr=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){this.processSystem()},t}(be),lr=function(e){function t(t){return e.call(this,t)||this}return u(t,e),t.prototype.process=function(e){},t}(be),fr=function(e){function t(t,n){var r;return(r=e.call(this,n)||this).acc=0,r.intervalRemainder=0,r.interval=t,r}u(t,e);var n=t.prototype;return n.onCheckProcessing=function(){return this.acc+=m.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)},n.getIntervalDelta=function(){return this.interval+this.intervalRemainder},t}(be),dr=function(){function e(){this.adapter=null,this.logger=G("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}(),pr=function(e){function t(t,n){var r,i,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.hasLoggedSyncMode=!1,c.platformAdapter=dr.getInstance().getAdapter();var u=null!==(r=n.workerCount)&&void 0!==r?r: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===(i=n.enableWorker)||void 0===i||i,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 r=t.prototype;return r.isWorkerSupported=function(){return this.platformAdapter.isWorkerSupported()},r.isSharedArrayBufferSupported=function(){return this.platformAdapter.isSharedArrayBufferSupported()},r.getMaxSystemWorkerCount=function(){return this.platformAdapter.getPlatformConfig().maxWorkerCount},r.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}},r.initializeWorkerPool=function(){try{for(var e=this.createWorkerScript(),t=[],n=(this.platformAdapter.getPlatformConfig().workerScriptPrefix||"")+e,r=0;r<this.config.workerCount;r++)try{var i=this.platformAdapter.createWorker(n,{name:"WorkerEntitySystem-"+r});t.push(i)}catch(e){throw this.logger.error("创建Worker "+r+" 失败:",e),e}this.workerPool=new yr(t,this.sharedBuffer)}catch(e){this.logger.error(this.systemName+": Worker池初始化失败",e),this.config.enableWorker=!1}},r.createWorkerScript=function(){var e,t=this.workerProcess.toString().match(/\{([\s\S]*)\}/);if(!t)throw new Error("无法解析workerProcess方法");var n=t[1],r=this.config.entityDataSize,i=(null===(e=this.getSharedArrayBufferProcessFunction)||void 0===e?void 0:e.call(this))||null,o="";if(i){var s=i.toString().match(/\{([\s\S]*)\}/);s&&(o=s[1])}return"\n // Worker脚本 - 支持SharedArrayBuffer\n let sharedFloatArray = null;\n const ENTITY_DATA_SIZE = "+r+";\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 "},r.process=function(e){var t=this;if(!this.isProcessing){this.isProcessing=!0;try{this.config.enableWorker&&this.workerPool?this.config.useSharedArrayBuffer&&this.sharedFloatArray&&this.isSharedArrayBufferSupported()?this.processWithSharedArrayBuffer(e).finally((function(){t.isProcessing=!1})):(this.config.useSharedArrayBuffer&&this.logger.info(this.systemName+": 本帧降级到传统Worker模式"),this.processWithWorker(e).finally((function(){t.isProcessing=!1}))):(this.hasLoggedSyncMode||(this.logger.info(this.systemName+": Worker不可用,使用同步处理"),this.hasLoggedSyncMode=!0),this.processSynchronously(e),this.isProcessing=!1)}catch(e){throw this.isProcessing=!1,this.logger.error(this.systemName+": 处理失败",e),e}}},r.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)}}(),r.processWithWorker=function(){var e=n(l().m((function e(t){var n,r,i,o,a,c,u,h,f,d,p,y,v,g,_=this;return l().w((function(e){for(;;)switch(e.n){case 0:for(n=[],r=0;r<t.length;r++)n[r]=this.extractEntityData(t[r]);return i=this.createBatches(n),o=m.deltaTime,a=i.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);!(f=h()).done;)for(d=f.value,p=s(d);!(y=p()).done;)v=y.value,u<t.length&&(g=t[u])&&v&&this.applyResult(g,v),u++;case 2:return e.a(2)}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),r.processSynchronously=function(e){var t=this,n=e.map((function(e){return t.extractEntityData(e)})),r=m.deltaTime,i=this.workerProcess(n,r,this.config.systemConfig);i&&"function"==typeof i.then?i.then((function(n){e.forEach((function(e,r){t.applyResult(e,n[r])}))})):e.forEach((function(e,n){t.applyResult(e,i[n])}))},r.createBatches=function(e){var t=this.config.workerCount,n=[];if(this.config.entitiesPerWorker){for(var r=this.config.entitiesPerWorker,i=0;i<e.length;i+=r){var o=Math.min(i+r,e.length);n.push(e.slice(i,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},r.writeEntitiesToSharedBuffer=function(e){if(this.sharedFloatArray)for(var t=0;t<e.length&&t<this.config.maxEntities;t++){var n=e[t],r=this.extractEntityData(n),i=t*this.config.entityDataSize;this.writeEntityToBuffer(r,i)}},r.createSharedArrayBufferTasks=function(e){var t=[];if(this.config.entitiesPerWorker){var n=this.config.entitiesPerWorker,r=Math.ceil(e/n),i=this.config.workerCount;r>i&&this.logger.warn(this.systemName+": 需要 "+r+" 个任务处理 "+e+" 个实体(每任务 "+n+" 个),但只有 "+i+" 个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:m.deltaTime,systemConfig:this.config.systemConfig});t.push(c)}}else for(var u=Math.ceil(e/this.config.workerCount),h=0;h<this.config.workerCount;h++){var l=h*u,f=Math.min(l+u,e);if(l<e){var d=this.workerPool.executeSharedBuffer({startIndex:l,endIndex:f,deltaTime:m.deltaTime,systemConfig:this.config.systemConfig});t.push(d)}}return t},r.readResultsFromSharedBuffer=function(e){if(this.sharedFloatArray)for(var t=0;t<e.length&&t<this.config.maxEntities;t++){var n=e[t],r=t*this.config.entityDataSize,i=this.readEntityFromBuffer(r);i&&this.applyResult(n,i)}},r.updateConfig=function(e){var t=a({},this.config);if(void 0!==e.workerCount){var n=this.getMaxSystemWorkerCount(),r=Math.min(e.workerCount,n);e.workerCount>n&&this.logger.warn("请求 "+e.workerCount+" 个Worker,但系统最多支持 "+n+" 个。实际使用 "+r+" 个Worker。"),e.workerCount=r}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()},r.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())},r.reinitializeWorkerPool=function(){this.workerPool&&(this.workerPool.destroy(),this.workerPool=null),this.config.enableWorker&&this.isWorkerSupported()&&this.initializeWorkerPool()},r.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}},r.onDestroy=function(){e.prototype.onDestroy.call(this),this.workerPool&&(this.workerPool.destroy(),this.workerPool=null)},r.getLoggerName=function(){return"WorkerEntitySystem"},t}(be),yr=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=G("PlatformWorkerPool"),this.sharedBuffer=t,this.workers=e;for(var r=function(r){var i=e[r];i.onMessage((function(e){return n.handleWorkerMessage(r,e.data)})),i.onError((function(e){return n.handleWorkerError(r,e)})),t&&i.postMessage({type:"init",sharedBuffer:t})},i=0;i<e.length;i++)r(i)}var t=e.prototype;return t.executeSharedBuffer=function(e){var t=this;return new Promise((function(n,r){var i={id:"shared-task-"+ ++t.taskCounter,data:a({},e,{type:"shared"}),resolve:function(){return n()},reject:r};t.taskQueue.push(i),t.processQueue()}))},t.execute=function(e){var t=this;return new Promise((function(n,r){var i={id:"task-"+ ++t.taskCounter,data:e,resolve:function(e){n(e)},reject:r};t.taskQueue.push(i),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],r=n._currentTask;r&&(this.busyWorkers.delete(e),n._currentTask=null,t.error?r.reject(new Error(t.error)):r.resolve(t.result),this.processQueue())},t.handleWorkerError=function(e,t){var n=this.workers[e],r=n._currentTask;r&&(this.busyWorkers.delete(e),n._currentTask=null,r.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}(),mr=function(){function e(){}return e.registerComponentMigration=function(e,t,n,r){this.componentMigrations.has(e)||this.componentMigrations.set(e,new Map),this.componentMigrations.get(e).set(t,r)},e.registerSceneMigration=function(e,t,n){this.sceneMigrations.set(e,n)},e.migrateComponent=function(e,t){var n=e.version;if(n===t)return e;var r=this.componentMigrations.get(e.type);if(!r)return console.warn("No migration path found for component "+e.type),e;for(var i=a({},e),o=n;o<t;){var s=r.get(o);if(!s){console.warn("Missing migration from version "+o+" to "+(o+1)+" for "+e.type);break}i.data=s(i.data,o,o+1),o++}return i.version=o,i},e.migrateScene=function(e,t){var n=e.version;if(n===t)return e;for(var r=a({},e),i=n;i<t;){var o=this.sceneMigrations.get(i);if(!o){console.warn("Missing scene migration from version "+i+" to "+(i+1));break}r=o(r,i,i+1),i++}return r.version=i,r=this.migrateSceneComponents(r)},e.migrateSceneComponents=function(e){var t=this,n=a({},e);return n.entities=e.entities.map((function(n){return a({},n,{components:n.components.map((function(n){var r=e.componentTypeRegistry.find((function(e){return e.typeName===n.type}));return r&&r.version!==n.version?t.migrateComponent(n,r.version):n})),children:t.migrateEntitiesComponents(n.children,e.componentTypeRegistry)})})),n},e.migrateEntitiesComponents=function(e,t){var n=this;return e.map((function(e){return a({},e,{components:e.components.map((function(e){var r=t.find((function(t){return t.typeName===e.type}));return r&&r.version!==e.version?n.migrateComponent(e,r.version):e})),children:n.migrateEntitiesComponents(e.children,t)})}))},e.clearMigrations=function(){this.componentMigrations.clear(),this.sceneMigrations.clear()},e.getComponentMigrationPath=function(e){var t=this.componentMigrations.get(e);return t?Array.from(t.keys()).sort((function(e,t){return e-t})):[]},e.getSceneMigrationPath=function(){return Array.from(this.sceneMigrations.keys()).sort((function(e,t){return e-t}))},e.canMigrateComponent=function(e,t,n){if(t===n)return!0;var r=this.componentMigrations.get(e);if(!r)return!1;for(var i=t;i<n;i++)if(!r.has(i))return!1;return!0},e.canMigrateScene=function(e,t){if(e===t)return!0;for(var n=e;n<t;n++)if(!this.sceneMigrations.has(n))return!1;return!0},e}();mr.componentMigrations=new Map,mr.sceneMigrations=new Map;var vr=function(){function e(){this.fromVersion=1,this.toVersion=2}var t=e.prototype;return t.forComponent=function(e){return this.componentType=e,this},t.fromVersionToVersion=function(e,t){return this.fromVersion=e,this.toVersion=t,this},t.migrate=function(e){this.componentType?mr.registerComponentMigration(this.componentType,this.fromVersion,this.toVersion,e):mr.registerSceneMigration(this.fromVersion,this.toVersion,e)},e}();var gr=function(){function e(e){this._entity=e}var t=e.prototype;return t.with=function(e){return this._entity.addComponent(e),this},t.withConfigured=function(e,t){return this._entity.addComponent(e),t(e),this},t.withTag=function(e){return this._entity.tag=e,this},t.withName=function(e){return this._entity.name=e,this},t.withActive=function(e){return this._entity.active=e,this},t.withEnabled=function(e){return this._entity.enabled=e,this},t.withUpdateOrder=function(e){return this._entity.updateOrder=e,this},t.withChild=function(e){return this._entity.addChild(e),this},t.build=function(){return this._entity},o(e,[{key:"entity",get:function(){return this._entity}}])}();var _r=function(){function e(){}return e.getType=function(e){return e.constructor},e}(),Sr=function(){function e(){}return e.toNumber=function(e){return null==e?0:Number(e)},e}();function Er(e){return"function"==typeof e&&e.prototype instanceof ur}var Cr=function(){function e(){}return e.detect=function(){var e,t=[],n="unknown",r=!1;return"undefined"!=typeof globalThis&&t.push("globalThis"),"undefined"!=typeof window&&t.push("window"),"undefined"!=typeof self&&t.push("self"),this.isNodeJS()?(n="nodejs",r=!0,e="NodeAdapter",t.push("nodejs","process","require")):this.isWeChatMiniGame()?(n="wechat-minigame",r=!0,e="WeChatMiniGameAdapter",t.push("wx","wechat-minigame")):this.isByteDanceMiniGame()?(n="bytedance-minigame",r=!0,e="ByteDanceMiniGameAdapter",t.push("tt","bytedance-minigame")):this.isAlipayMiniGame()?(n="alipay-minigame",r=!0,e="AlipayMiniGameAdapter",t.push("my","alipay-minigame")):this.isBaiduMiniGame()?(n="baidu-minigame",r=!0,e="BaiduMiniGameAdapter",t.push("swan","baidu-minigame")):this.isBrowser()&&(n="browser",r=!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:r,features:t,adapterClass:e}},e.isWeChatMiniGame=function(){if(void 0!==globalThis.wx){var e=globalThis.wx;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1},e.isByteDanceMiniGame=function(){if(void 0!==globalThis.tt){var e=globalThis.tt;return!!(e.getSystemInfo&&e.createCanvas&&e.createImage)}return!1},e.isNodeJS=function(){try{return!("undefined"==typeof process||!process.versions||!process.versions.node||"undefined"==typeof require||"undefined"==typeof module||"undefined"==typeof exports||"undefined"!=typeof window||"undefined"!=typeof document)}catch(e){return!1}},e.isAlipayMiniGame=function(){if(void 0!==globalThis.my){var e=globalThis.my;return!(!e.getSystemInfo||!e.createCanvas)}return!1},e.isBaiduMiniGame=function(){if(void 0!==globalThis.swan){var e=globalThis.swan;return!(!e.getSystemInfo||!e.createCanvas)}return!1},e.isBrowser=function(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator&&void 0!==window.location},e.getDetailedInfo=function(){var e={};return e.userAgent="undefined"!=typeof navigator?navigator.userAgent:"unknown",e.platform="undefined"!=typeof navigator?navigator.platform:"unknown",e.globalObjects={window:"undefined"!=typeof window,document:"undefined"!=typeof document,navigator:"undefined"!=typeof navigator,wx:void 0!==globalThis.wx,tt:void 0!==globalThis.tt,my:void 0!==globalThis.my,swan:void 0!==globalThis.swan},e.workerSupport={Worker:"undefined"!=typeof Worker,SharedWorker:"undefined"!=typeof SharedWorker,ServiceWorker:"undefined"!=typeof navigator&&"serviceWorker"in navigator,SharedArrayBuffer:"undefined"!=typeof SharedArrayBuffer,crossOriginIsolated:"undefined"!=typeof self&&self.crossOriginIsolated},e.performance={performanceNow:"undefined"!=typeof performance&&"function"==typeof performance.now,hardwareConcurrency:"undefined"!=typeof navigator?navigator.hardwareConcurrency:void 0},e.apiSupport={Blob:"undefined"!=typeof Blob,URL:"undefined"!=typeof URL,createObjectURL:"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL,ArrayBuffer:"undefined"!=typeof ArrayBuffer,TypedArrays:"undefined"!=typeof Float32Array},e},e}();exports.AutoTyped=function(e){return function(t,n){var r=String(n);t.constructor.__autoTypedFields||(t.constructor.__autoTypedFields=new Map),t.constructor.__autoTypedFields.set(r,e||{})}},exports.BitMask64Utils=D,exports.Bits=R,exports.COMPONENT_TYPE_NAME=B,exports.Colors=U,exports.Component=ur,exports.ComponentDataCollector=ce,exports.ComponentPool=se,exports.ComponentPoolManager=ae,exports.ComponentRegistry=pe,exports.ComponentSerializer=Xe,exports.ComponentSparseSet=xe,exports.ComponentStorage=ye,exports.ComponentTypeManager=ne,exports.ConsoleLogger=H,exports.Core=or,exports.DebugManager=le,exports.DeepCopy=function(e,t){var n=String(t);e.constructor.__deepCopyFields||(e.constructor.__deepCopyFields=new Set),e.constructor.__deepCopyFields.add(n)},exports.ECSComponent=function(e){return function(t){if(!e||"string"!=typeof e)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return t[B]=e,t}},exports.ECSFluentAPI=Jn,exports.ECSSystem=function(e,t){return function(n){if(!e||"string"!=typeof e)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return n[P]=e,t&&(n.__systemMetadata__=t),n}},exports.ENTITY_REF_METADATA=K,exports.EVENT_TYPES=ze,exports.Emitter=ar,exports.EnableSoA=function(e){return e.__enableSoA=!0,e},exports.Entity=ge,exports.EntityDataCollector=re,exports.EntityList=Se,exports.EntityProcessorList=we,exports.EntityRef=function(){return function(e,t){var n=e.constructor,r=n[K];r||(r={properties:new Set},n[K]=r);var i="symbol"==typeof t?t.toString():t;r.properties.add(i),Object.defineProperty(e,t,{get:function(){return ee(this).get(i)||null},set:function(e){var t=ee(this),n=t.get(i)||null;if(n!==e){var r=null!==this.entityId?J(this.entityId):null;if(r&&r.referenceTracker){var o=r.referenceTracker;if(n&&o.unregisterReference(n,this,i),e){var s;if(e.scene!==r)return void X.error("Cannot reference Entity from different Scene. Entity: "+e.name+", Scene: "+((null===(s=e.scene)||void 0===s?void 0:s.name)||"null"));if(e.isDestroyed)return X.warn("Cannot reference destroyed Entity: "+e.name),void t.set(i,null);o.registerReference(e,this,i)}t.set(i,e)}else t.set(i,e)}},enumerable:!0,configurable:!0})}},exports.EntitySerializer=Ke,exports.EntitySystem=be,exports.EventBus=We,exports.EventTypeValidator=Ne,exports.Float32=function(e,t){var n=String(t);e.constructor.__float32Fields||(e.constructor.__float32Fields=new Set),e.constructor.__float32Fields.add(n)},exports.Float64=function(e,t){var n=String(t);e.constructor.__float64Fields||(e.constructor.__float64Fields=new Set),e.constructor.__float64Fields.add(n)},exports.FuncPack=sr,exports.GlobalEventBus=Le,exports.GlobalManager=cr,exports.HighPrecision=function(e,t){var n=String(t);e.constructor.__highPrecisionFields||(e.constructor.__highPrecisionFields=new Set),e.constructor.__highPrecisionFields.add(n)},exports.IdentifierPool=Ee,exports.IgnoreSerialization=function(){return function(e,t){var n=e.constructor,r=n[He];r||(r={options:{version:1},fields:new Map,ignoredFields:new Set},n[He]=r),r.ignoredFields.add(t)}},exports.IncrementalSerializer=Un,exports.Inject=function(e){return function(t,n,r){var i=S.get(t);i||(i=new Map,S.set(t,i)),i.set(r,e)}},exports.Injectable=function(){return function(e){return _.set(e,{injectable:!0,dependencies:[]}),e}},exports.Int16=function(e,t){var n=String(t);e.constructor.__int16Fields||(e.constructor.__int16Fields=new Set),e.constructor.__int16Fields.add(n)},exports.Int32=function(e,t){var n=String(t);e.constructor.__int32Fields||(e.constructor.__int32Fields=new Set),e.constructor.__int32Fields.add(n)},exports.Int8=function(e,t){var n=String(t);e.constructor.__int8Fields||(e.constructor.__int8Fields=new Set),e.constructor.__int8Fields.add(n)},exports.IntervalSystem=fr,exports.Logger=q,exports.LoggerManager=j,exports.Matcher=Ce,exports.MigrationBuilder=vr,exports.NumberExtension=Sr,exports.PassiveSystem=lr,exports.PerformanceDataCollector=oe,exports.PerformanceMonitor=x,exports.PlatformDetector=Cr,exports.PlatformManager=dr,exports.PluginManager=er,exports.Pool=M,exports.PoolManager=k,exports.ProcessingSystem=hr,exports.QuerySystem=Re,exports.ReferenceTracker=Z,exports.SERIALIZABLE_METADATA=He,exports.SERIALIZE_FIELD=je,exports.SERIALIZE_OPTIONS=qe,exports.SYSTEM_TYPE_NAME=P,exports.Scene=Gn,exports.SceneDataCollector=ue,exports.SceneManager=Kn,exports.SceneSerializer=Fn,exports.Serializable=function(e){return function(t){if(!e||"number"!=typeof e.version)throw new Error("Serializable装饰器必须提供有效的版本号");var n=t[He];return n?n.options=e:(n={options:e,fields:new Map,ignoredFields:new Set},t[He]=n),t}},exports.Serialize=Ge,exports.SerializeArray=function(e,t){var n=String(t);e.constructor.__serializeArrayFields||(e.constructor.__serializeArrayFields=new Set),e.constructor.__serializeArrayFields.add(n)},exports.SerializeAsMap=function(){return function(e,t){Ge({serializer:function(e){return e instanceof Map?Array.from(e.entries()):null},deserializer:function(e){return Array.isArray(e)?new Map(e):new Map}})(e,t)}},exports.SerializeAsSet=function(){return function(e,t){Ge({serializer:function(e){return e instanceof Set?Array.from(e):null},deserializer:function(e){return Array.isArray(e)?new Set(e):new Set}})(e,t)}},exports.SerializeMap=function(e,t){var n=String(t);e.constructor.__serializeMapFields||(e.constructor.__serializeMapFields=new Set),e.constructor.__serializeMapFields.add(n)},exports.SerializeSet=function(e,t){var n=String(t);e.constructor.__serializeSetFields||(e.constructor.__serializeSetFields=new Set),e.constructor.__serializeSetFields.add(n)},exports.ServiceContainer=qn,exports.SoAStorage=de,exports.SparseSet=Ae,exports.SystemDataCollector=ie,exports.Time=m,exports.Timer=g,exports.TypeInference=fe,exports.TypeSafeEventSystem=Pe,exports.TypeUtils=_r,exports.TypedEntityBuilder=gr,exports.TypedQueryBuilder=Ue,exports.TypedQueryResult=Fe,exports.Uint16=function(e,t){var n=String(t);e.constructor.__uint16Fields||(e.constructor.__uint16Fields=new Set),e.constructor.__uint16Fields.add(n)},exports.Uint32=function(e,t){var n=String(t);e.constructor.__uint32Fields||(e.constructor.__uint32Fields=new Set),e.constructor.__uint32Fields.add(n)},exports.Uint8=function(e,t){var n=String(t);e.constructor.__uint8Fields||(e.constructor.__uint8Fields=new Set),e.constructor.__uint8Fields.add(n)},exports.Uint8Clamped=function(e,t){var n=String(t);e.constructor.__uint8ClampedFields||(e.constructor.__uint8ClampedFields=new Set),e.constructor.__uint8ClampedFields.add(n)},exports.Updatable=C,exports.VersionMigrationManager=mr,exports.WebSocketManager=he,exports.WorkerEntitySystem=pr,exports.World=nr,exports.WorldManager=ir,exports.addAndConfigure=function(e,t,n){return e.addComponent(t),n(t),e},exports.buildEntity=function(e){return new gr(e)},exports.createECSAPI=Zn,exports.createInstance=w,exports.createLogger=G,exports.createQuery=function(){return new Ue},exports.getBasicWorkerConfig=function(){return dr.getInstance().getBasicWorkerConfig()},exports.getComponentInstanceTypeName=L,exports.getComponentTypeName=N,exports.getComponents=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 n.map((function(t){return e.getComponent(t)}))},exports.getCurrentAdapter=function(){return dr.getInstance().getAdapter()},exports.getEntityRefMetadata=te,exports.getFullPlatformConfig=function(){return dr.getInstance().getFullPlatformConfig()},exports.getOrAddComponent=function(e,t,n){var r=e.getComponent(t);return r||(r=n(),e.addComponent(r)),r},exports.getSceneByEntityId=J,exports.getSerializationMetadata=Ve,exports.getSystemInstanceTypeName=F,exports.getSystemMetadata=z,exports.getSystemTypeName=W,exports.getUpdatableMetadata=T,exports.hasAdapter=function(){return dr.getInstance().hasAdapter()},exports.hasAnyComponent=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 n.some((function(t){return e.hasComponent(t)}))},exports.hasComponents=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return n.every((function(t){return e.hasComponent(t)}))},exports.hasEntityRef=function(e){return null!==te(e)},exports.isComponentArray=function(e){return e.every(Er)},exports.isComponentType=Er,exports.isSerializable=function(e){return null!==Ve(e)},exports.isUpdatable=A,exports.queryFor=function(e){return new Ue([e])},exports.queryForAll=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new Ue(t)},exports.registerInjectable=function(e,t,n){if(void 0===n&&(n=!0),!b(t))throw new Error(t.name+" is not marked as @Injectable(). Please add @Injectable() decorator to the class.");var r=function(e){return w(t,e)};n?e.registerSingleton(t,r):e.registerTransient(t,r)},exports.registerPlatformAdapter=function(e){return dr.getInstance().registerAdapter(e)},exports.requireComponent=function(e,t){var n=e.getComponent(t);if(!n)throw new Error("Component "+t.name+" not found on entity "+e.name+" (id: "+e.id+")");return n},exports.resetLoggerColors=function(){j.getInstance().resetColors()},exports.setGlobalLogLevel=function(e){j.getInstance().setGlobalLevel(e)},exports.setLoggerColors=function(e){j.getInstance().setGlobalColors(e)},exports.supportsFeature=function(e){return dr.getInstance().supportsFeature(e)},exports.tryGetComponent=function(e,t){var n=e.getComponent(t);return null!==n?n:void 0},exports.updateComponent=function(e,t,n){var r=e.getComponent(t);return!!r&&(Object.assign(r,n),!0)};
4
4
  //# sourceMappingURL=index.es5.js.map