@esengine/ecs-framework 2.1.45 → 2.1.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -1,2 +1,4 @@
1
- class GlobalManager{constructor(){this._enabled=!1}get enabled(){return this._enabled}set enabled(t){this.setEnabled(t)}setEnabled(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}onEnabled(){}onDisabled(){}update(){}}class Time{static update(t){this.unscaledDeltaTime=t,this.deltaTime=t*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++}static sceneChanged(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0}static checkEvery(t,e){return this.totalTime-e>=t}}Time.deltaTime=0,Time.unscaledDeltaTime=0,Time.totalTime=0,Time.unscaledTotalTime=0,Time.timeScale=1,Time.frameCount=0;class Timer{constructor(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}getContext(){return this.context}get isDone(){return this._isDone}get elapsedTime(){return this._elapsedTime}reset(){this._elapsedTime=0}stop(){this._isDone=!0}tick(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=Time.deltaTime,this._isDone}initialize(t,e,n,s){this._timeInSeconds=t,this._repeats=e,this.context=n,this._onTime=s.bind(n)}unload(){this.context=null,this._onTime=null}}class TimerManager extends GlobalManager{constructor(){super(...arguments),this._timers=[]}update(){for(let t=this._timers.length-1;t>=0;t--)this._timers[t].tick()&&(this._timers[t].unload(),this._timers.splice(t,1))}schedule(t,e,n,s){let i=new Timer;return i.initialize(t,e,n,s),this._timers.push(i),i}}var PerformanceWarningType,LogLevel;!function(t){t.HIGH_EXECUTION_TIME="high_execution_time",t.HIGH_MEMORY_USAGE="high_memory_usage",t.HIGH_CPU_USAGE="high_cpu_usage",t.FREQUENT_GC="frequent_gc",t.LOW_FPS="low_fps",t.HIGH_ENTITY_COUNT="high_entity_count"}(PerformanceWarningType||(PerformanceWarningType={}));class PerformanceMonitor{static get instance(){return PerformanceMonitor._instance||(PerformanceMonitor._instance=new PerformanceMonitor),PerformanceMonitor._instance}constructor(){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}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}get isEnabled(){return this._isEnabled}startMonitoring(t){return this._isEnabled?performance.now():0}endMonitoring(t,e,n=0){if(!this._isEnabled||0===e)return;const s=performance.now(),i=s-e,o={name:t,executionTime:i,entityCount:n,averageTimePerEntity:n>0?i/n:0,lastUpdateTime:s};this._systemData.set(t,o),this.updateStats(t,i)}updateStats(t,e){let n=this._systemStats.get(t);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(t,n)),n.totalTime+=e,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,e),n.maxTime=Math.max(n.maxTime,e),n.recentTimes.push(e),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)}calculateAdvancedStats(t){if(0===t.recentTimes.length)return;const e=t.recentTimes.reduce(((t,e)=>t+e),0)/t.recentTimes.length,n=t.recentTimes.reduce(((t,n)=>t+Math.pow(n-e,2)),0)/t.recentTimes.length;t.standardDeviation=Math.sqrt(n);const s=[...t.recentTimes].sort(((t,e)=>t-e)),i=s.length;t.percentile95=s[Math.floor(.95*i)]||0,t.percentile99=s[Math.floor(.99*i)]||0}getSystemData(t){return this._systemData.get(t)}getSystemStats(t){return this._systemStats.get(t)}getAllSystemData(){return new Map(this._systemData)}getAllSystemStats(){return new Map(this._systemStats)}getPerformanceReport(){if(!this._isEnabled)return"Performance monitoring is disabled.";const t=[];t.push("=== ECS Performance Report ==="),t.push("");const e=Array.from(this._systemStats.entries()).sort(((t,e)=>e[1].averageTime-t[1].averageTime));for(const[n,s]of e){const e=this._systemData.get(n);t.push(`System: ${n}`),t.push(` Current: ${e?.executionTime.toFixed(2)}ms (${e?.entityCount} entities)`),t.push(` Average: ${s.averageTime.toFixed(2)}ms`),t.push(` Min/Max: ${s.minTime.toFixed(2)}ms / ${s.maxTime.toFixed(2)}ms`),t.push(` Total: ${s.totalTime.toFixed(2)}ms (${s.executionCount} calls)`),e?.averageTimePerEntity&&e.averageTimePerEntity>0&&t.push(` Per Entity: ${e.averageTimePerEntity.toFixed(4)}ms`),t.push("")}const n=Array.from(this._systemData.values()).reduce(((t,e)=>t+e.executionTime),0);return t.push(`Total Frame Time: ${n.toFixed(2)}ms`),t.push(`Systems Count: ${this._systemData.size}`),t.join("\n")}reset(){this._systemData.clear(),this._systemStats.clear()}resetSystem(t){this._systemData.delete(t),this._systemStats.delete(t)}getPerformanceWarnings(t=16.67){const e=[];for(const[n,s]of this._systemData.entries())s.executionTime>t&&e.push(`${n}: ${s.executionTime.toFixed(2)}ms (>${t}ms)`);return e}setMaxRecentSamples(t){this._maxRecentSamples=t;for(const e of this._systemStats.values())for(;e.recentTimes.length>t;)e.recentTimes.shift()}}class Pool{constructor(t,e=100,n=1024){this._objects=[],this._createFn=t,this._maxSize=e,this._objectSize=n,this._stats={size:0,maxSize:e,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}static getPool(t,e=100,n=1024){let s=this._pools.get(t);return s||(s=new Pool((()=>new t),e,n),this._pools.set(t,s)),s}obtain(){if(this._stats.totalObtained++,this._objects.length>0){const t=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),t}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()}release(t){t&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(t.reset(),this._objects.push(t),this._stats.size++,this._updateMemoryUsage()))}getStats(){return{...this._stats}}clear(){for(const t of this._objects)t.reset();this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()}compact(t){const e=t??Math.floor(this._objects.length/2);for(;this._objects.length>e;){const t=this._objects.pop();t&&(t.reset(),this._stats.size--)}this._updateMemoryUsage()}prewarm(t){const e=Math.min(t,this._maxSize-this._objects.length);for(let t=0;t<e;t++){const t=this._createFn();t.reset(),this._objects.push(t),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()}setMaxSize(t){this._maxSize=t,this._stats.maxSize=t,this._objects.length>t&&this.compact(t)}getAvailableCount(){return this._objects.length}isEmpty(){return 0===this._objects.length}isFull(){return this._objects.length>=this._maxSize}static getAllPoolTypes(){return Array.from(this._pools.keys())}static getAllPoolStats(){const t={};for(const[e,n]of this._pools){t[e.name||e.toString()]=n.getStats()}return t}static compactAllPools(){for(const t of this._pools.values())t.compact()}static clearAllPools(){for(const t of this._pools.values())t.clear();this._pools.clear()}static getGlobalStatsString(){const t=this.getAllPoolStats(),e=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(t).length)return e.push("No pools registered"),e.join("\n");for(const[n,s]of Object.entries(t))e.push(`${n}:`),e.push(` Size: ${s.size}/${s.maxSize}`),e.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),e.push(` Total Created: ${s.totalCreated}`),e.push(` Total Obtained: ${s.totalObtained}`),e.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("");return e.join("\n")}_updateHitRate(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{const t=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=t/this._stats.totalObtained}}_updateMemoryUsage(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize}}Pool._pools=new Map;class PoolManager{constructor(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}static getInstance(){return PoolManager.instance||(PoolManager.instance=new PoolManager),PoolManager.instance}registerPool(t,e){this.pools.set(t,e)}getPool(t){return this.pools.get(t)||null}update(){const t=Date.now();t-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=t)}createPool(t,e,n=100,s=1024){let i=this.pools.get(t);return i||(i=new Pool(e,n,s),this.pools.set(t,i)),i}removePool(t){const e=this.pools.get(t);return!!e&&(e.clear(),this.pools.delete(t),!0)}getPoolNames(){return Array.from(this.pools.keys())}getPoolCount(){return this.pools.size}compactAllPools(){for(const t of this.pools.values())t.compact()}clearAllPools(){for(const t of this.pools.values())t.clear()}getAllStats(){const t=new Map;for(const[e,n]of this.pools)t.set(e,n.getStats());return t}getGlobalStats(){let t=0,e=0,n=0,s=0,i=0,o=0;for(const r of this.pools.values()){const a=r.getStats();t+=a.size,e+=a.maxSize,n+=a.totalCreated,s+=a.totalObtained,i+=a.totalReleased,o+=a.estimatedMemoryUsage}return{size:t,maxSize:e,totalCreated:n,totalObtained:s,totalReleased:i,hitRate:0===s?0:(s-n)/s,estimatedMemoryUsage:o}}getStatsString(){const t=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return t.push("No pools registered"),t.join("\n");const e=this.getGlobalStats();t.push(`Total Pools: ${this.pools.size}`),t.push(`Global Hit Rate: ${(100*e.hitRate).toFixed(1)}%`),t.push(`Global Memory Usage: ${(e.estimatedMemoryUsage/1024).toFixed(1)} KB`),t.push("");for(const[e,n]of this.pools){const s=n.getStats();t.push(`${e}:`),t.push(` Size: ${s.size}/${s.maxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Memory: ${(s.estimatedMemoryUsage/1024).toFixed(1)} KB`),t.push("")}return t.join("\n")}setAutoCompactInterval(t){this.autoCompactInterval=t}prewarmAllPools(){for(const t of this.pools.values()){const e=t.getStats(),n=Math.floor(.2*e.maxSize);t.prewarm(n)}}reset(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0}}class NativeBigInt{constructor(t){this.value=t}valueOf(){return Number(this.value)}toString(t){if(void 0!==t&&10!==t&&16!==t&&2!==t)throw new Error("Only radix 2, 10, and 16 are supported");const e=this.value.toString(t);return 16===t?e.toUpperCase():e}and(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return new NativeBigInt(this.value&e)}or(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return new NativeBigInt(this.value|e)}xor(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return new NativeBigInt(this.value^e)}not(t=64){const e=(BigInt(1)<<BigInt(t))-BigInt(1);return new NativeBigInt(~this.value&e)}shiftLeft(t){return new NativeBigInt(this.value<<BigInt(t))}shiftRight(t){return new NativeBigInt(this.value>>BigInt(t))}equals(t){const e=t instanceof NativeBigInt?t.value:BigInt(t.valueOf());return this.value===e}isZero(){return this.value===BigInt(0)}clone(){return new NativeBigInt(this.value)}}class ArrayBigInt{constructor(t=0){this.chunks=[],"number"==typeof t?this.fromNumber(t):"string"==typeof t?this.fromString(t):this.chunks=t.slice(),this.normalize()}fromNumber(t){if(this.chunks=[],t<0&&(t=Math.abs(t)),0!==t)for(;t>0;)this.chunks.push(t&ArrayBigInt.CHUNK_MASK),t=Math.floor(t/ArrayBigInt.CHUNK_MAX);else this.chunks=[0]}fromString(t){(t=t.trim()).startsWith("0x")||t.startsWith("0X")?this.fromHexString(t.substring(2)):t.startsWith("0b")||t.startsWith("0B")?this.fromBinaryString(t.substring(2)):this.fromDecimalString(t)}fromHexString(t){this.chunks=[0];for(let e=t.length-1;e>=0;e-=8){const n=Math.max(0,e-7),s=parseInt(t.substring(n,e+1),16);this.chunks.push(s)}this.normalize()}fromBinaryString(t){this.chunks=[0];for(let e=t.length-1;e>=0;e-=32){const n=Math.max(0,e-31),s=parseInt(t.substring(n,e+1),2);this.chunks.push(s)}this.normalize()}fromDecimalString(t){const e=parseInt(t,10);this.fromNumber(e)}normalize(){for(;this.chunks.length>1&&0===this.chunks[this.chunks.length-1];)this.chunks.pop();0===this.chunks.length&&(this.chunks=[0])}valueOf(){let t=0,e=1;for(const n of this.chunks)if(t+=n*e,e*=ArrayBigInt.CHUNK_MAX,e>Number.MAX_SAFE_INTEGER)break;return t}toString(t=10){if(10!==t&&16!==t&&2!==t)throw new Error("Only radix 2, 10, and 16 are supported");if(this.isZero())return"0";if(10===t)return this.valueOf().toString(10);if(16===t){let t="";for(let e=this.chunks.length-1;e>=0;e--){const n=this.chunks[e].toString(16);t+=e===this.chunks.length-1?n:n.padStart(8,"0")}return t.toUpperCase()}if(2===t){let t="";for(let e=this.chunks.length-1;e>=0;e--){const n=this.chunks[e].toString(2);t+=e===this.chunks.length-1?n:n.padStart(32,"0")}return t}return this.valueOf().toString(t)}and(t){const e=t,n=Math.max(this.chunks.length,e.chunks.length),s=[];for(let t=0;t<n;t++){const n=t<this.chunks.length?this.chunks[t]:0,i=t<e.chunks.length?e.chunks[t]:0;s.push(n&i)}return new ArrayBigInt(s)}or(t){const e=t,n=Math.max(this.chunks.length,e.chunks.length),s=[];for(let t=0;t<n;t++){const n=t<this.chunks.length?this.chunks[t]:0,i=t<e.chunks.length?e.chunks[t]:0;s.push(n|i)}return new ArrayBigInt(s)}xor(t){const e=t,n=Math.max(this.chunks.length,e.chunks.length),s=[];for(let t=0;t<n;t++){const n=t<this.chunks.length?this.chunks[t]:0,i=t<e.chunks.length?e.chunks[t]:0;s.push(n^i)}return new ArrayBigInt(s)}not(t=64){const e=Math.ceil(t/ArrayBigInt.CHUNK_SIZE),n=[];for(let s=0;s<e;s++){const i=s<this.chunks.length?this.chunks[s]:0;if(s===e-1){const e=t%ArrayBigInt.CHUNK_SIZE;if(e>0){const t=(1<<e)-1;n.push(~i&t)}else n.push(~i&ArrayBigInt.CHUNK_MASK)}else n.push(~i&ArrayBigInt.CHUNK_MASK)}return new ArrayBigInt(n)}shiftLeft(t){if(0===t)return this.clone();if(t<0)return this.shiftRight(-t);const e=Math.floor(t/ArrayBigInt.CHUNK_SIZE),n=t%ArrayBigInt.CHUNK_SIZE,s=new Array(e).fill(0);if(0===n)s.push(...this.chunks);else{let t=0;for(const e of this.chunks){const i=e<<n|t;s.push(i&ArrayBigInt.CHUNK_MASK),t=e>>>ArrayBigInt.CHUNK_SIZE-n}t>0&&s.push(t)}return new ArrayBigInt(s)}shiftRight(t){if(0===t)return this.clone();if(t<0)return this.shiftLeft(-t);const e=Math.floor(t/ArrayBigInt.CHUNK_SIZE),n=t%ArrayBigInt.CHUNK_SIZE;if(e>=this.chunks.length)return new ArrayBigInt(0);const s=[];if(0===n)for(let t=e;t<this.chunks.length;t++)s.push(this.chunks[t]);else{let t=0;for(let i=this.chunks.length-1;i>=e;i--){const e=this.chunks[i],o=t<<ArrayBigInt.CHUNK_SIZE-n|e>>>n;s.unshift(o),t=e&(1<<n)-1}}return new ArrayBigInt(s.length>0?s:[0])}equals(t){if(!(t instanceof ArrayBigInt))return!1;if(this.chunks.length!==t.chunks.length)return!1;for(let e=0;e<this.chunks.length;e++)if(this.chunks[e]!==t.chunks[e])return!1;return!0}isZero(){return 1===this.chunks.length&&0===this.chunks[0]}clone(){return new ArrayBigInt(this.chunks.slice())}}ArrayBigInt.CHUNK_SIZE=32,ArrayBigInt.CHUNK_MASK=4294967295,ArrayBigInt.CHUNK_MAX=4294967296;class BigIntFactory{static isNativeSupported(){return null===this._supportsBigInt&&(this._supportsBigInt=this.detectBigIntSupport()),this._supportsBigInt}static detectBigIntSupport(){try{if("undefined"==typeof BigInt)return!1;const test1=BigInt(1),test2=BigInt(2),result=test1|test2,literal=eval("1n");if("bigint"!=typeof result||"bigint"!=typeof literal)return!1;const shifted=test1<<BigInt(1),compared=test1===BigInt(1);return"bigint"==typeof shifted&&!0===compared}catch(t){return!1}}static create(t=0){if(this.isNativeSupported()){let e;return e="bigint"==typeof t?t:BigInt(t),new NativeBigInt(e)}{let e;return e="bigint"==typeof t?t.toString():t,new ArrayBigInt(e)}}static zero(){return this._cachedZero||(this._cachedZero=this.create(0)),this._cachedZero}static one(){return this._cachedOne||(this._cachedOne=this.create(1)),this._cachedOne}static fromBinaryString(t){if(this.isNativeSupported()){const e=BigInt("0b"+t);return new NativeBigInt(e)}return new ArrayBigInt("0b"+t)}static fromHexString(t){if(this.isNativeSupported()){const e=t.replace(/^0x/i,""),n=BigInt("0x"+e);return new NativeBigInt(n)}return new ArrayBigInt(t)}static getEnvironmentInfo(){return{supportsBigInt:this.isNativeSupported(),environment:this.detectEnvironment(),jsEngine:this.detectJSEngine()}}static detectEnvironment(){if("undefined"!=typeof window){if("undefined"!=typeof navigator){const t=navigator.userAgent;if(t.includes("Chrome")){const e=t.match(/Chrome\/(\d+)/);return`Chrome ${e?parseInt(e[1]):0}`}if(t.includes("Firefox")){const e=t.match(/Firefox\/(\d+)/);return`Firefox ${e?parseInt(e[1]):0}`}if(t.includes("Safari")&&!t.includes("Chrome")){const e=t.match(/Version\/(\d+)/);return`Safari ${e?parseInt(e[1]):0}`}return"Browser (Unknown)"}return"Browser"}return"undefined"!=typeof global?"undefined"!=typeof process&&process.version?`Node.js ${process.version}`:"Node.js":void 0!==globalThis.wx?"WeChat MiniProgram":void 0!==globalThis.cc?"Cocos Creator":void 0!==globalThis.Laya?"Laya Engine":"Unknown"}static detectJSEngine(){try{return"undefined"!=typeof process&&process.versions&&process.versions.v8?`V8 ${process.versions.v8}`:void 0!==globalThis.Components?"SpiderMonkey":"undefined"!=typeof window&&void 0!==window.safari?"JavaScriptCore":"Unknown"}catch{return"Unknown"}}}BigIntFactory._supportsBigInt=null,BigIntFactory._cachedZero=null,BigIntFactory._cachedOne=null,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error",t[t.Fatal=4]="Fatal",t[t.None=5]="None"}(LogLevel||(LogLevel={}));class ConsoleLogger{constructor(t={}){this._config={level:LogLevel.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window,...t}}debug(t,...e){this.log(LogLevel.Debug,t,...e)}info(t,...e){this.log(LogLevel.Info,t,...e)}warn(t,...e){this.log(LogLevel.Warn,t,...e)}error(t,...e){this.log(LogLevel.Error,t,...e)}fatal(t,...e){this.log(LogLevel.Fatal,t,...e)}setLevel(t){this._config.level=t}setPrefix(t){this._config.prefix=t}log(t,e,...n){if(t<this._config.level)return;let s=e;if(this._config.enableTimestamp){s=`[${(new Date).toISOString()}] ${s}`}this._config.prefix&&(s=`[${this._config.prefix}] ${s}`);s=`[${LogLevel[t].toUpperCase()}] ${s}`,this._config.output?this._config.output(t,s):this.outputToConsole(t,s,...n)}outputToConsole(t,e,...n){const s=this._config.enableColors?this.getColors():null;switch(t){case LogLevel.Debug:s?console.debug(`${s.gray}${e}${s.reset}`,...n):console.debug(e,...n);break;case LogLevel.Info:s?console.info(`${s.blue}${e}${s.reset}`,...n):console.info(e,...n);break;case LogLevel.Warn:s?console.warn(`${s.yellow}${e}${s.reset}`,...n):console.warn(e,...n);break;case LogLevel.Error:case LogLevel.Fatal:s?console.error(`${s.red}${e}${s.reset}`,...n):console.error(e,...n)}}getColors(){return{reset:"",red:"",yellow:"",blue:"",gray:""}}}class LoggerManager{constructor(){this._loggers=new Map,this._defaultLogger=new ConsoleLogger}static getInstance(){return LoggerManager._instance||(LoggerManager._instance=new LoggerManager),LoggerManager._instance}getLogger(t){if(!t)return this._defaultLogger;if(!this._loggers.has(t)){const e=new ConsoleLogger({prefix:t,level:LogLevel.Info});this._loggers.set(t,e)}return this._loggers.get(t)}setLogger(t,e){this._loggers.set(t,e)}setGlobalLevel(t){this._defaultLogger instanceof ConsoleLogger&&this._defaultLogger.setLevel(t);for(const e of this._loggers.values())e instanceof ConsoleLogger&&e.setLevel(t)}createChildLogger(t,e){const n=`${t}.${e}`;return this.getLogger(n)}}const Logger=LoggerManager.getInstance().getLogger();function createLogger(t){return LoggerManager.getInstance().getLogger(t)}function setGlobalLogLevel(t){LoggerManager.getInstance().setGlobalLevel(t)}function EnableSoA(t){return t.__enableSoA=!0,t}function HighPrecision(t,e){const n=String(e);t.constructor.__highPrecisionFields||(t.constructor.__highPrecisionFields=new Set),t.constructor.__highPrecisionFields.add(n)}function Float64(t,e){const n=String(e);t.constructor.__float64Fields||(t.constructor.__float64Fields=new Set),t.constructor.__float64Fields.add(n)}function Float32(t,e){const n=String(e);t.constructor.__float32Fields||(t.constructor.__float32Fields=new Set),t.constructor.__float32Fields.add(n)}function Int32(t,e){const n=String(e);t.constructor.__int32Fields||(t.constructor.__int32Fields=new Set),t.constructor.__int32Fields.add(n)}function SerializeMap(t,e){const n=String(e);t.constructor.__serializeMapFields||(t.constructor.__serializeMapFields=new Set),t.constructor.__serializeMapFields.add(n)}class SoAStorage{constructor(t){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=t,this.initializeFields(t)}initializeFields(t){const e=new t,n=t.__highPrecisionFields||new Set,s=t.__float64Fields||new Set,i=t.__float32Fields||new Set,o=t.__int32Fields||new Set,r=t.__serializeMapFields||new Set,a=t.__serializeSetFields||new Set,c=t.__serializeArrayFields||new Set;for(const t in e)if(e.hasOwnProperty(t)&&"id"!==t){const h=e[t],l=typeof h;"number"===l?n.has(t)||(s.has(t)?this.fields.set(t,new Float64Array(this._capacity)):o.has(t)?this.fields.set(t,new Int32Array(this._capacity)):(i.has(t),this.fields.set(t,new Float32Array(this._capacity)))):"boolean"===l?this.fields.set(t,new Float32Array(this._capacity)):"string"===l?this.stringFields.set(t,new Array(this._capacity)):"object"===l&&null!==h&&(r.has(t)||a.has(t)||c.has(t))&&this.serializedFields.set(t,new Array(this._capacity))}}addComponent(t,e){if(this.entityToIndex.has(t)){const n=this.entityToIndex.get(t);return void this.updateComponentAtIndex(n,e)}let n;this.freeIndices.length>0?n=this.freeIndices.pop():(n=this._size,n>=this._capacity&&this.resize(2*this._capacity)),this.entityToIndex.set(t,n),this.indexToEntity[n]=t,this.updateComponentAtIndex(n,e),this._size++}updateComponentAtIndex(t,e){const n=this.indexToEntity[t],s=new Map,i=this.type.__highPrecisionFields||new Set,o=this.type.__serializeMapFields||new Set,r=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=this.type.__deepCopyFields||new Set;for(const n in e)if(e.hasOwnProperty(n)&&"id"!==n){const h=e[n],l=typeof h;if("number"===l)if(i.has(n)||!this.fields.has(n))s.set(n,h);else{this.fields.get(n)[t]=h}else if("boolean"===l&&this.fields.has(n)){this.fields.get(n)[t]=h?1:0}else if(this.stringFields.has(n)){this.stringFields.get(n)[t]=String(h)}else if(this.serializedFields.has(n)){this.serializedFields.get(n)[t]=this.serializeValue(h,n,o,r,a)}else c.has(n)?s.set(n,this.deepClone(h)):s.set(n,h)}s.size>0&&this.complexFields.set(n,s)}serializeValue(t,e,n,s,i){try{return n.has(e)&&t instanceof Map?JSON.stringify(Array.from(t.entries())):s.has(e)&&t instanceof Set?JSON.stringify(Array.from(t)):(i.has(e)&&Array.isArray(t),JSON.stringify(t))}catch(t){return SoAStorage._logger.warn(`SoA序列化字段 ${e} 失败:`,t),"{}"}}deserializeValue(t,e,n,s,i){try{const o=JSON.parse(t);return n.has(e)?new Map(o):s.has(e)?new Set(o):(i.has(e),o)}catch(t){return SoAStorage._logger.warn(`SoA反序列化字段 ${e} 失败:`,t),null}}deepClone(t){if(null===t||"object"!=typeof t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array)return t.map((t=>this.deepClone(t)));if(t instanceof Map){const e=new Map;for(const[n,s]of t.entries())e.set(n,this.deepClone(s));return e}if(t instanceof Set){const e=new Set;for(const n of t.values())e.add(this.deepClone(n));return e}const e={};for(const n in t)t.hasOwnProperty(n)&&(e[n]=this.deepClone(t[n]));return e}getComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const n=new this.type,s=this.type.__serializeMapFields||new Set,i=this.type.__serializeSetFields||new Set,o=this.type.__serializeArrayFields||new Set;for(const[t,s]of this.fields.entries()){const i=s[e],o=this.getFieldType(t);n[t]="boolean"===o?1===i:i}for(const[t,s]of this.stringFields.entries())n[t]=s[e];for(const[t,r]of this.serializedFields.entries()){const a=r[e];a&&(n[t]=this.deserializeValue(a,t,s,i,o))}const r=this.complexFields.get(t);if(r)for(const[t,e]of r.entries())n[t]=e;return n}getFieldType(t){return typeof(new this.type)[t]}hasComponent(t){return this.entityToIndex.has(t)}removeComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const n=this.getComponent(t);return this.complexFields.delete(t),this.entityToIndex.delete(t),this.freeIndices.push(e),this._size--,n}resize(t){for(const[e,n]of this.fields.entries()){let s;s=n instanceof Float32Array?new Float32Array(t):n instanceof Float64Array?new Float64Array(t):new Int32Array(t),s.set(n),this.fields.set(e,s)}for(const[e,n]of this.stringFields.entries()){const s=new Array(t);for(let t=0;t<n.length;t++)s[t]=n[t];this.stringFields.set(e,s)}for(const[e,n]of this.serializedFields.entries()){const s=new Array(t);for(let t=0;t<n.length;t++)s[t]=n[t];this.serializedFields.set(e,s)}this._capacity=t}getActiveIndices(){return Array.from(this.entityToIndex.values())}getFieldArray(t){return this.fields.get(t)||null}getTypedFieldArray(t){return this.fields.get(String(t))||null}getEntityIndex(t){return this.entityToIndex.get(t)}getEntityIdByIndex(t){return this.indexToEntity[t]}size(){return this._size}clear(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(const t of this.fields.values())t.fill(0);for(const t of this.stringFields.values())for(let e=0;e<t.length;e++)t[e]=void 0;for(const t of this.serializedFields.values())for(let e=0;e<t.length;e++)t[e]=void 0}compact(){if(0===this.freeIndices.length)return;const t=Array.from(this.entityToIndex.entries()).sort(((t,e)=>t[1]-e[1])),e=new Map,n=[];for(let s=0;s<t.length;s++){const[i,o]=t[s];if(e.set(i,s),n[s]=i,s!==o){for(const[,t]of this.fields.entries())t[s]=t[o];for(const[,t]of this.stringFields.entries())t[s]=t[o];for(const[,t]of this.serializedFields.entries())t[s]=t[o]}}this.entityToIndex=e,this.indexToEntity=n,this.freeIndices=[],this._size=t.length}getStats(){let t=0;const e=new Map;for(const[n,s]of this.fields.entries()){let i,o;s instanceof Float32Array?(i=4,o="float32"):s instanceof Float64Array?(i=8,o="float64"):(i=4,o="int32");const r=s.length*i;t+=r,e.set(n,{size:this._size,capacity:s.length,type:o,memory:r})}return{size:this._size,capacity:this._capacity,usedSlots:this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:t,fieldStats:e}}performVectorizedOperation(t){const e=this.getActiveIndices();t(this.fields,e)}}SoAStorage._logger=createLogger("SoAStorage");const COMPONENT_TYPE_NAME=Symbol("ComponentTypeName"),SYSTEM_TYPE_NAME=Symbol("SystemTypeName");function ECSComponent(t){return function(e){if(!t||"string"!=typeof t)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return e[COMPONENT_TYPE_NAME]=t,e}}function ECSSystem(t){return function(e){if(!t||"string"!=typeof t)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return e[SYSTEM_TYPE_NAME]=t,e}}function getComponentTypeName(t){const e=t[COMPONENT_TYPE_NAME];return e||(t.name||"UnknownComponent")}function getSystemTypeName(t){const e=t[SYSTEM_TYPE_NAME];return e||(t.name||"UnknownSystem")}function getComponentInstanceTypeName(t){return getComponentTypeName(t.constructor)}function getSystemInstanceTypeName(t){return getSystemTypeName(t.constructor)}class ComponentRegistry{static register(t){if(this.componentTypes.has(t))return this.componentTypes.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error(`Maximum number of component types (${this.maxComponents}) exceeded`);const e=this.nextBitIndex++;return this.componentTypes.set(t,e),this.componentNameToType.set(getComponentTypeName(t),t),this.componentNameToId.set(getComponentTypeName(t),e),e}static getBitMask(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${getComponentTypeName(t)} is not registered`);return BigIntFactory.one().shiftLeft(e)}static getBitIndex(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${getComponentTypeName(t)} is not registered`);return e}static isRegistered(t){return this.componentTypes.has(t)}static getComponentType(t){return this.componentNameToType.get(t)||null}static getAllRegisteredTypes(){return new Map(this.componentTypes)}static getAllComponentNames(){return new Map(this.componentNameToType)}static getComponentId(t){return this.componentNameToId.get(t)}static registerComponentByName(t){if(this.componentNameToId.has(t))return this.componentNameToId.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error(`Maximum number of component types (${this.maxComponents}) exceeded`);const e=this.nextBitIndex++;return this.componentNameToId.set(t,e),e}static createSingleComponentMask(t){const e=`single:${t}`;if(this.maskCache.has(e))return this.maskCache.get(e);const n=this.getComponentId(t);if(void 0===n)throw new Error(`Component type ${t} is not registered`);const s=BigIntFactory.one().shiftLeft(n);return this.maskCache.set(e,s),s}static createComponentMask(t){const e=`multi:${[...t].sort().join(",")}`;if(this.maskCache.has(e))return this.maskCache.get(e);let n=BigIntFactory.zero();for(const e of t){const t=this.getComponentId(e);void 0!==t&&(n=n.or(BigIntFactory.one().shiftLeft(t)))}return this.maskCache.set(e,n),n}static clearMaskCache(){this.maskCache.clear()}static reset(){this.componentTypes.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0}}ComponentRegistry._logger=createLogger("ComponentStorage"),ComponentRegistry.componentTypes=new Map,ComponentRegistry.componentNameToType=new Map,ComponentRegistry.componentNameToId=new Map,ComponentRegistry.maskCache=new Map,ComponentRegistry.nextBitIndex=0,ComponentRegistry.maxComponents=64;class ComponentStorage{constructor(t){this.components=[],this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this.componentType=t,ComponentRegistry.isRegistered(t)||ComponentRegistry.register(t)}addComponent(t,e){if(this.entityToIndex.has(t))throw new Error(`Entity ${t} already has component ${getComponentTypeName(this.componentType)}`);let n;this.freeIndices.length>0?(n=this.freeIndices.pop(),this.components[n]=e,this.indexToEntity[n]=t):(n=this.components.length,this.components.push(e),this.indexToEntity.push(t)),this.entityToIndex.set(t,n),this._size++}getComponent(t){const e=this.entityToIndex.get(t);return void 0!==e?this.components[e]:null}hasComponent(t){return this.entityToIndex.has(t)}removeComponent(t){const e=this.entityToIndex.get(t);if(void 0===e)return null;const n=this.components[e];return this.entityToIndex.delete(t),this.components[e]=null,this.freeIndices.push(e),this._size--,n}forEach(t){for(let e=0;e<this.components.length;e++){const n=this.components[e];n&&t(n,this.indexToEntity[e],e)}}getDenseArray(){const t=[],e=[];for(let n=0;n<this.components.length;n++){const s=this.components[n];s&&(t.push(s),e.push(this.indexToEntity[n]))}return{components:t,entityIds:e}}clear(){this.components.length=0,this.entityToIndex.clear(),this.indexToEntity.length=0,this.freeIndices.length=0,this._size=0}get size(){return this._size}get type(){return this.componentType}compact(){if(0===this.freeIndices.length)return;const t=[],e=[],n=new Map;let s=0;for(let i=0;i<this.components.length;i++){const o=this.components[i];o&&(t[s]=o,e[s]=this.indexToEntity[i],n.set(this.indexToEntity[i],s),s++)}this.components=t,this.indexToEntity=e,this.entityToIndex=n,this.freeIndices.length=0}getStats(){const t=this.components.length,e=this._size,n=this.freeIndices.length;return{totalSlots:t,usedSlots:e,freeSlots:n,fragmentation:t>0?n/t:0}}}class ComponentStorageManager{constructor(){this.storages=new Map}isSoAStorage(t){return this.storages.get(t)instanceof SoAStorage}getSoAStorage(t){const e=this.getStorage(t);return e instanceof SoAStorage?e:null}getFieldArray(t,e){const n=this.getSoAStorage(t);return n?n.getFieldArray(e):null}getTypedFieldArray(t,e){const n=this.getSoAStorage(t);return n?n.getTypedFieldArray(e):null}getActiveIndices(t){const e=this.getSoAStorage(t);return e?e.getActiveIndices():[]}getEntityIndex(t,e){const n=this.getSoAStorage(t);return n?n.getEntityIndex(e):void 0}getEntityIdByIndex(t,e){const n=this.getSoAStorage(t);return n?n.getEntityIdByIndex(e):void 0}getStorage(t){let e=this.storages.get(t);if(!e){t.__enableSoA?(e=new SoAStorage(t),ComponentStorageManager._logger.info(`为 ${getComponentTypeName(t)} 启用SoA优化(适用于大规模批量操作)`)):e=new ComponentStorage(t),this.storages.set(t,e)}return e}addComponent(t,e){const n=e.constructor;this.getStorage(n).addComponent(t,e)}getComponent(t,e){const n=this.storages.get(e);return n?n.getComponent(t):null}hasComponent(t,e){const n=this.storages.get(e);return!!n&&n.hasComponent(t)}removeComponent(t,e){const n=this.storages.get(e);return n?n.removeComponent(t):null}removeAllComponents(t){for(const e of this.storages.values())e.removeComponent(t)}getComponentMask(t){let e=BigIntFactory.zero();for(const[n,s]of this.storages.entries())if(s.hasComponent(t)){const t=ComponentRegistry.getBitMask(n);e=e.or(t)}return e}compactAll(){for(const t of this.storages.values())t.compact()}getAllStats(){const t=new Map;for(const[e,n]of this.storages.entries()){const s=getComponentTypeName(e);t.set(s,n.getStats())}return t}clear(){for(const t of this.storages.values())t.clear();this.storages.clear()}}ComponentStorageManager._logger=createLogger("ComponentStorage");class EntityComparer{compare(t,e){let n=t.updateOrder-e.updateOrder;return 0==n&&(n=t.id-e.id),n}}class Entity{constructor(t,e){this.components=[],this.scene=null,this.updateInterval=1,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=BigIntFactory.zero(),this._componentTypeToIndex=new Map,this.name=t,this.id=e}get isDestroyed(){return this._isDestroyed}get parent(){return this._parent}get children(){return[...this._children]}get childCount(){return this._children.length}get active(){return this._active}set active(t){this._active!==t&&(this._active=t,this.onActiveChanged())}get activeInHierarchy(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}get tag(){return this._tag}set tag(t){this._tag=t}get enabled(){return this._enabled}set enabled(t){this._enabled=t}get updateOrder(){return this._updateOrder}set updateOrder(t){this._updateOrder=t}get componentMask(){return this._componentMask}createComponent(t,...e){const n=new t(...e);return this.addComponent(n)}addComponentInternal(t){const e=t.constructor;ComponentRegistry.isRegistered(e)||ComponentRegistry.register(e),t.entity=this;const n=this.components.length;this.components.push(t),this._componentTypeToIndex.set(e,n);const s=ComponentRegistry.getBitMask(e);return this._componentMask=this._componentMask.or(s),t}addComponent(t){const e=t.constructor;if(this.hasComponent(e))throw new Error(`Entity ${this.name} already has component ${getComponentTypeName(e)}`);return this.addComponentInternal(t),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.addComponent(this.id,t),t.onAddedToEntity(),Entity.eventBus&&Entity.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:getComponentTypeName(e),component:t}),this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this)),t}getComponent(t){if(!ComponentRegistry.isRegistered(t))return null;const e=ComponentRegistry.getBitMask(t);if(this._componentMask.and(e).isZero())return null;const n=this._componentTypeToIndex.get(t);if(void 0!==n&&n<this.components.length){const e=this.components[n];if(e&&e.constructor===t)return e}if(this.scene&&this.scene.componentStorageManager){const e=this.scene.componentStorageManager.getComponent(this.id,t);if(e)return this.rebuildComponentIndex(),e}for(let e=0;e<this.components.length;e++){const n=this.components[e];if(n instanceof t)return this._componentTypeToIndex.set(t,e),n}return null}rebuildComponentIndex(){this._componentTypeToIndex.clear();for(let t=0;t<this.components.length;t++){const e=this.components[t].constructor;this._componentTypeToIndex.set(e,t)}}hasComponent(t){if(!ComponentRegistry.isRegistered(t))return!1;const e=ComponentRegistry.getBitMask(t);return!this._componentMask.and(e).isZero()}getOrCreateComponent(t,...e){let n=this.getComponent(t);return n||(n=this.createComponent(t,...e)),n}removeComponent(t){const e=t.constructor,n=this.components.indexOf(t);if(-1!==n&&(this.components.splice(n,1),this.rebuildComponentIndex()),ComponentRegistry.isRegistered(e)){const t=ComponentRegistry.getBitMask(e);this._componentMask=this._componentMask.and(t.not())}this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,e),t.onRemovedFromEntity&&t.onRemovedFromEntity(),Entity.eventBus&&Entity.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:getComponentTypeName(e),component:t}),t.entity=null,this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this))}removeComponentByType(t){const e=this.getComponent(t);return e?(this.removeComponent(e),e):null}removeAllComponents(){const t=[...this.components];this._componentTypeToIndex.clear(),this._componentMask=BigIntFactory.zero();for(const e of t){const t=e.constructor;this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,t),e.onRemovedFromEntity(),e.entity=null}this.components.length=0}addComponents(t){const e=[];for(const n of t)try{e.push(this.addComponent(n))}catch(t){Entity._logger.warn(`添加组件失败 ${getComponentInstanceTypeName(n)}:`,t)}return e}removeComponentsByTypes(t){const e=[];for(const n of t)e.push(this.removeComponentByType(n));return e}getComponents(t){const e=[];for(const n of this.components)n instanceof t&&e.push(n);return e}addChild(t){if(t===this)throw new Error("Entity cannot be its own child");return t._parent===this||(t._parent&&t._parent.removeChild(t),t._parent=this,this._children.push(t),!t.scene&&this.scene&&(t.scene=this.scene,this.scene.addEntity(t))),t}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&(this._children.splice(e,1),t._parent=null,!0)}removeAllChildren(){const t=[...this._children];for(const e of t)this.removeChild(e)}findChild(t,e=!1){for(const e of this._children)if(e.name===t)return e;if(e)for(const e of this._children){const n=e.findChild(t,!0);if(n)return n}return null}findChildrenByTag(t,e=!1){const n=[];for(const e of this._children)e.tag===t&&n.push(e);if(e)for(const e of this._children)n.push(...e.findChildrenByTag(t,!0));return n}getRoot(){let t=this;for(;t._parent;)t=t._parent;return t}isAncestorOf(t){let e=t._parent;for(;e;){if(e===this)return!0;e=e._parent}return!1}isDescendantOf(t){return t.isAncestorOf(this)}getDepth(){let t=0,e=this._parent;for(;e;)t++,e=e._parent;return t}forEachChild(t,e=!1){this._children.forEach(((n,s)=>{t(n,s),e&&n.forEachChild(t,!0)}))}onActiveChanged(){for(const t of this.components)"onActiveChanged"in t&&"function"==typeof t.onActiveChanged&&t.onActiveChanged();this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})}update(){if(this.activeInHierarchy&&!this._isDestroyed){for(const t of this.components)t.enabled&&t.update();for(const t of this._children)t.update()}}destroy(){if(this._isDestroyed)return;this._isDestroyed=!0;const t=[...this._children];for(const e of t)e.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))}compareTo(t){return EntityComparer.prototype.compare(this,t)}toString(){return`Entity[${this.name}:${this.id}]`}getDebugInfo(){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((t=>getComponentInstanceTypeName(t))),componentMask:this._componentMask.toString(2),parentId:this._parent?.id||null,childCount:this._children.length,childIds:this._children.map((t=>t.id)),depth:this.getDepth(),indexMappingSize:this._componentTypeToIndex.size}}}Entity._logger=createLogger("Entity"),Entity.entityComparer=new EntityComparer,Entity.eventBus=null;class EntityBuilder{constructor(t,e){this.scene=t,this.storageManager=e,this.entity=new Entity("",t.identifierPool.checkOut())}named(t){return this.entity.name=t,this}tagged(t){return this.entity.tag=t,this}with(t){return this.entity.addComponent(t),this}withComponents(...t){for(const e of t)this.entity.addComponent(e);return this}withIf(t,e){return t&&this.entity.addComponent(e),this}withFactory(t){const e=t();return this.entity.addComponent(e),this}configure(t,e){const n=this.entity.getComponent(t);return n&&e(n),this}enabled(t=!0){return this.entity.enabled=t,this}active(t=!0){return this.entity.active=t,this}withChild(t){const e=t.build();return this.entity.addChild(e),this}withChildren(...t){for(const e of t){const t=e.build();this.entity.addChild(t)}return this}withChildFactory(t){const e=t(this.entity).build();return this.entity.addChild(e),this}withChildIf(t,e){if(t){const t=e.build();this.entity.addChild(t)}return this}build(){return this.entity}spawn(){return this.scene.addEntity(this.entity),this.entity}clone(){const t=new EntityBuilder(this.scene,this.storageManager);return t.entity=this.entity,t}}class EntityList{get count(){return this.buffer.length}constructor(t){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._isUpdating=!1,this._scene=t}add(t){this._isUpdating?this._entitiesToAdd.push(t):this.addImmediate(t)}addImmediate(t){this._idToEntity.has(t.id)||(this.buffer.push(t),this._idToEntity.set(t.id,t),this.updateNameIndex(t,!0))}remove(t){this._isUpdating?this._entitiesToRemove.push(t):this.removeImmediate(t)}removeImmediate(t){const e=this.buffer.indexOf(t);-1!==e&&(this.buffer.splice(e,1),this._idToEntity.delete(t.id),this.updateNameIndex(t,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(t.id))}removeAllEntities(){const t=[];for(let e=this.buffer.length-1;e>=0;e--)t.push(this.buffer[e].id),this.buffer[e].destroy();if(this._scene&&this._scene.identifierPool)for(const e of t)this._scene.identifierPool.checkIn(e);this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0}updateLists(){if(this._entitiesToAdd.length>0){for(const t of this._entitiesToAdd)this.addImmediate(t);this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(const t of this._entitiesToRemove)this.removeImmediate(t);this._entitiesToRemove.length=0}}update(){this._isUpdating=!0;try{for(let t=0;t<this.buffer.length;t++){const e=this.buffer[t];e.enabled&&!e.isDestroyed&&e.update()}}finally{this._isUpdating=!1}this.updateLists()}findEntity(t){const e=this._nameToEntities.get(t);return e&&e.length>0?e[0]:null}findEntitiesByName(t){return this._nameToEntities.get(t)||[]}findEntityById(t){return this._idToEntity.get(t)||null}findEntitiesByTag(t){const e=[];for(const n of this.buffer)n.tag===t&&e.push(n);return e}findEntitiesWithComponent(t){const e=[];for(const n of this.buffer)n.hasComponent(t)&&e.push(n);return e}forEach(t){for(const e of this.buffer)t(e)}forEachWhere(t,e){for(const n of this.buffer)t(n)&&e(n)}updateNameIndex(t,e){if(t.name)if(e){let e=this._nameToEntities.get(t.name);e||(e=[],this._nameToEntities.set(t.name,e)),e.push(t)}else{const e=this._nameToEntities.get(t.name);if(e){const n=e.indexOf(t);-1!==n&&(e.splice(n,1),0===e.length&&this._nameToEntities.delete(t.name))}}}getStats(){let t=0;for(const e of this.buffer)e.enabled&&!e.isDestroyed&&t++;return{totalEntities:this.buffer.length,activeEntities:t,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}}}class EntityProcessorList{constructor(){this._processors=[],this._isDirty=!1}setDirty(){this._isDirty=!0}add(t){this._processors.push(t),this.setDirty()}remove(t){const e=this._processors.indexOf(t);-1!==e&&this._processors.splice(e,1)}getProcessor(t){for(const e of this._processors)if(e instanceof t)return e;return null}begin(){this.sortProcessors()}end(){}update(){this.sortProcessors();for(const t of this._processors)try{t.update()}catch(e){EntityProcessorList._logger.error(`Error in processor ${getSystemInstanceTypeName(t)}:`,e)}}lateUpdate(){for(const t of this._processors)t.lateUpdate()}sortProcessors(){this._isDirty&&(this._processors.sort(((t,e)=>t.updateOrder-e.updateOrder)),this._isDirty=!1)}get processors(){return this._processors}get count(){return this._processors.length}}EntityProcessorList._logger=createLogger("EntityProcessorList");class IdentifierPool{constructor(t=100,e=1024){this._nextAvailableIndex=0,this._freeIndices=[],this._generations=new Map,this._pendingRecycle=[],this._recycleDelay=100,this._stats={totalAllocated:0,totalRecycled:0,currentActive:0,memoryExpansions:0},this._recycleDelay=t,this._expansionBlockSize=e,this._preAllocateGenerations(0,this._expansionBlockSize)}checkOut(){let t;if(this._processDelayedRecycle(),this._freeIndices.length>0)t=this._freeIndices.pop();else{if(this._nextAvailableIndex>IdentifierPool.MAX_INDEX)throw new Error(`实体索引已达到框架设计限制 (${IdentifierPool.MAX_INDEX})。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。`);t=this._nextAvailableIndex++,this._ensureGenerationCapacity(t)}const e=this._generations.get(t)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(t,e)}checkIn(t){const e=this._unpackIndex(t),n=this._unpackGeneration(t);if(!this._isValidId(e,n))return!1;return!this._pendingRecycle.some((t=>t.index===e&&t.generation===n))&&(this._pendingRecycle.push({index:e,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0)}isValid(t){const e=this._unpackIndex(t),n=this._unpackGeneration(t);return this._isValidId(e,n)}getStats(){let t=0,e=0;for(const[n,s]of this._generations)n<this._nextAvailableIndex&&(t+=s,e++);const n=e>0?t/e:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:IdentifierPool.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*n)/100,generationStorageSize:this._generations.size}}forceProcessDelayedRecycle(){this._processDelayedRecycle(!0)}_processDelayedRecycle(t=!1){if(0===this._pendingRecycle.length)return;const e=Date.now(),n=[],s=[];for(const i of this._pendingRecycle)t||e-i.timestamp>=this._recycleDelay?n.push(i):s.push(i);for(const t of n)if(this._isValidId(t.index,t.generation)){let e=t.generation+1;e>IdentifierPool.MAX_GENERATION&&(e=1),this._generations.set(t.index,e),this._freeIndices.push(t.index)}this._pendingRecycle=s}_preAllocateGenerations(t,e){for(let n=0;n<e;n++){const e=t+n;e<=IdentifierPool.MAX_INDEX&&this._generations.set(e,1)}this._stats.memoryExpansions++}_ensureGenerationCapacity(t){if(!this._generations.has(t)){const e=Math.floor(t/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(e,this._expansionBlockSize)}}_calculateMemoryUsage(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length}_packId(t,e){return e<<16|t}_unpackIndex(t){return 65535&t}_unpackGeneration(t){return t>>>16&65535}_isValidId(t,e){if(t<0||t>=this._nextAvailableIndex)return!1;const n=this._generations.get(t);return void 0!==n&&n===e}}IdentifierPool.MAX_INDEX=65535,IdentifierPool.MAX_GENERATION=65535;class ComponentPool{constructor(t,e,n=1e3){this.pool=[],this.createFn=t,this.resetFn=e,this.maxSize=n}acquire(){return this.pool.length>0?this.pool.pop():this.createFn()}release(t){this.pool.length<this.maxSize&&(this.resetFn&&this.resetFn(t),this.pool.push(t))}prewarm(t){for(let e=0;e<t&&this.pool.length<this.maxSize;e++)this.pool.push(this.createFn())}clear(){this.pool.length=0}getAvailableCount(){return this.pool.length}getMaxSize(){return this.maxSize}}class ComponentPoolManager{constructor(){this.pools=new Map}static getInstance(){return ComponentPoolManager.instance||(ComponentPoolManager.instance=new ComponentPoolManager),ComponentPoolManager.instance}registerPool(t,e,n,s){this.pools.set(t,new ComponentPool(e,n,s))}acquireComponent(t){const e=this.pools.get(t);return e?e.acquire():null}releaseComponent(t,e){const n=this.pools.get(t);n&&n.release(e)}prewarmAll(t=100){for(const e of this.pools.values())e.prewarm(t)}clearAll(){for(const t of this.pools.values())t.clear()}reset(){this.pools.clear()}getPoolStats(){const t=new Map;for(const[e,n]of this.pools)t.set(e,{available:n.getAvailableCount(),maxSize:n.getMaxSize()});return t}getPoolUtilization(){const t=new Map;for(const[e,n]of this.pools){const s=n.getAvailableCount(),i=n.getMaxSize(),o=i-s,r=i>0?o/i*100:0;t.set(e,{used:o,total:i,utilization:r})}return t}getComponentUtilization(t){const e=this.pools.get(t);if(!e)return 0;const n=e.getAvailableCount(),s=e.getMaxSize();return s>0?(s-n)/s*100:0}}class SparseSet{constructor(){this._dense=[],this._sparse=new Map}add(t){if(this._sparse.has(t))return!1;const e=this._dense.length;return this._dense.push(t),this._sparse.set(t,e),!0}remove(t){const e=this._sparse.get(t);if(void 0===e)return!1;const n=this._dense.length-1;if(e!==n){const t=this._dense[n];this._dense[e]=t,this._sparse.set(t,e)}return this._dense.pop(),this._sparse.delete(t),!0}has(t){return this._sparse.has(t)}getIndex(t){return this._sparse.get(t)}getByIndex(t){return this._dense[t]}get size(){return this._dense.length}get isEmpty(){return 0===this._dense.length}forEach(t){for(let e=0;e<this._dense.length;e++)t(this._dense[e],e)}map(t){const e=[];for(let n=0;n<this._dense.length;n++)e.push(t(this._dense[n],n));return e}filter(t){const e=[];for(let n=0;n<this._dense.length;n++)t(this._dense[n],n)&&e.push(this._dense[n]);return e}find(t){for(let e=0;e<this._dense.length;e++)if(t(this._dense[e],e))return this._dense[e]}some(t){for(let e=0;e<this._dense.length;e++)if(t(this._dense[e],e))return!0;return!1}every(t){for(let e=0;e<this._dense.length;e++)if(!t(this._dense[e],e))return!1;return!0}getDenseArray(){return[...this._dense]}getDenseArrayUnsafe(){return this._dense}clear(){this._dense.length=0,this._sparse.clear()}toArray(){return[...this._dense]}toSet(){return new Set(this._dense)}getMemoryStats(){const t=8*this._dense.length,e=16*this._sparse.size;return{denseArraySize:t,sparseMapSize:e,totalMemory:t+e}}validate(){if(this._dense.length!==this._sparse.size)return!1;for(let t=0;t<this._dense.length;t++){const e=this._dense[t];if(this._sparse.get(e)!==t)return!1}for(const[t,e]of this._sparse)if(e>=this._dense.length||this._dense[e]!==t)return!1;return!0}}class PoolableEntitySet extends Set{constructor(...t){super()}reset(){this.clear()}}class ComponentSparseSet{constructor(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new SparseSet}addEntity(t){this._entities.has(t)&&this.removeEntity(t);let e=BigIntFactory.zero();const n=new Set;for(const s of t.components){const t=s.constructor;n.add(t),ComponentRegistry.isRegistered(t)||ComponentRegistry.register(t);const i=ComponentRegistry.getBitMask(t);e=e.or(i)}this._entities.add(t);const s=this._entities.getIndex(t);for(;this._componentMasks.length<=s;)this._componentMasks.push(BigIntFactory.zero());this._componentMasks[s]=e,this.updateComponentMappings(t,n,!0)}removeEntity(t){const e=this._entities.getIndex(t);if(void 0===e)return;const n=this.getEntityComponentTypes(t);this.updateComponentMappings(t,n,!1),this._entities.remove(t);const s=this._componentMasks.length-1;e!==s&&(this._componentMasks[e]=this._componentMasks[s]),this._componentMasks.pop()}queryByComponent(t){const e=this._componentToEntities.get(t);return e?new Set(e):new Set}queryMultipleAnd(t){if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);let e=BigIntFactory.zero();for(const n of t){if(!ComponentRegistry.isRegistered(n))return new Set;const t=ComponentRegistry.getBitMask(n);e=e.or(t)}const n=ComponentSparseSet._entitySetPool.obtain();return this._entities.forEach(((t,s)=>{this._componentMasks[s].and(e).equals(e)&&n.add(t)})),n}queryMultipleOr(t){if(0===t.length)return new Set;if(1===t.length)return this.queryByComponent(t[0]);let e=BigIntFactory.zero();for(const n of t)if(ComponentRegistry.isRegistered(n)){const t=ComponentRegistry.getBitMask(n);e=e.or(t)}if(e.equals(BigIntFactory.zero()))return new Set;const n=ComponentSparseSet._entitySetPool.obtain();return this._entities.forEach(((t,s)=>{this._componentMasks[s].and(e).equals(BigIntFactory.zero())||n.add(t)})),n}hasComponent(t,e){const n=this._entities.getIndex(t);if(void 0===n)return!1;if(!ComponentRegistry.isRegistered(e))return!1;const s=this._componentMasks[n],i=ComponentRegistry.getBitMask(e);return!s.and(i).equals(BigIntFactory.zero())}getEntityMask(t){const e=this._entities.getIndex(t);if(void 0!==e)return this._componentMasks[e]}getAllEntities(){return this._entities.toArray()}get size(){return this._entities.size}get isEmpty(){return this._entities.isEmpty}forEach(t){this._entities.forEach(((e,n)=>{t(e,this._componentMasks[n],n)}))}clear(){this._entities.clear(),this._componentMasks.length=0;for(const t of this._componentToEntities.values())ComponentSparseSet._entitySetPool.release(t);this._componentToEntities.clear()}getMemoryStats(){const t=this._entities.getMemoryStats(),e=16*this._componentMasks.length;let n=16*this._componentToEntities.size;for(const t of this._componentToEntities.values())n+=8*t.size;return{entitiesMemory:t.totalMemory,masksMemory:e,mappingsMemory:n,totalMemory:t.totalMemory+e+n}}validate(){if(!this._entities.validate())return!1;if(this._componentMasks.length!==this._entities.size)return!1;const t=new Set;for(const e of this._componentToEntities.values())for(const n of e)t.add(n);for(const e of t)if(!this._entities.has(e))return!1;return!0}getEntityComponentTypes(t){const e=new Set;for(const n of t.components)e.add(n.constructor);return e}updateComponentMappings(t,e,n){for(const s of e){let e=this._componentToEntities.get(s);n?(e||(e=ComponentSparseSet._entitySetPool.obtain(),this._componentToEntities.set(s,e)),e.add(t)):e&&(e.delete(t),0===e.size&&(this._componentToEntities.delete(s),ComponentSparseSet._entitySetPool.release(e)))}}}ComponentSparseSet._entitySetPool=Pool.getPool(PoolableEntitySet,50,512);class ComponentIndex{constructor(){this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now(),this._sparseSet=new ComponentSparseSet}addEntity(t){this._sparseSet.addEntity(t),this._lastUpdated=Date.now()}removeEntity(t){this._sparseSet.removeEntity(t),this._lastUpdated=Date.now()}query(t){const e=performance.now(),n=this._sparseSet.queryByComponent(t);return this._queryCount++,this._totalQueryTime+=performance.now()-e,n}queryMultiple(t,e){const n=performance.now();let s;return s=0===t.length?new Set:1===t.length?this.query(t[0]):"AND"===e?this._sparseSet.queryMultipleAnd(t):this._sparseSet.queryMultipleOr(t),this._queryCount++,this._totalQueryTime+=performance.now()-n,s}clear(){this._sparseSet.clear(),this._lastUpdated=Date.now()}getStats(){const t=this._sparseSet.getMemoryStats();return{size:this._sparseSet.size,memoryUsage:t.totalMemory,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}}}class ComponentIndexManager{constructor(){this._index=new ComponentIndex}addEntity(t){this._index.addEntity(t)}removeEntity(t){this._index.removeEntity(t)}query(t){return this._index.query(t)}queryMultiple(t,e){return this._index.queryMultiple(t,e)}getStats(){return this._index.getStats()}clear(){this._index.clear()}}class ArchetypeSystem{constructor(){this._archetypes=new Map,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._queryCache=new Map,this._cacheTimeout=5e3,this._maxCacheSize=100}addEntity(t){const e=this.getEntityComponentTypes(t),n=this.generateArchetypeId(e);let s=this._archetypes.get(n);s||(s=this.createArchetype(e)),s.entities.push(t),s.updatedAt=Date.now(),this._entityToArchetype.set(t,s),this.updateComponentIndexes(s,e,!0),this.invalidateQueryCache()}removeEntity(t){const e=this._entityToArchetype.get(t);if(!e)return;const n=e.entities.indexOf(t);-1!==n&&(e.entities.splice(n,1),e.updatedAt=Date.now()),this._entityToArchetype.delete(t),this.invalidateQueryCache()}queryArchetypes(t,e="AND"){const n=performance.now(),s=`${e}:${t.map((t=>getComponentTypeName(t))).sort().join(",")}`,i=this._queryCache.get(s);if(i&&Date.now()-i.timestamp<this._cacheTimeout)return{...i.result,executionTime:performance.now()-n,fromCache:!0};const o=[];let r=0;if("AND"===e)for(const e of this._archetypes.values())this.archetypeContainsAllComponents(e,t)&&(o.push(e),r+=e.entities.length);else{const e=new Set;for(const n of t){const t=this._componentToArchetypes.get(n);if(t)for(const n of t)e.add(n)}for(const t of e)o.push(t),r+=t.entities.length}const a={archetypes:o,totalEntities:r,executionTime:performance.now()-n,fromCache:!1};return this._queryCache.set(s,{result:a,timestamp:Date.now()}),a}getEntityArchetype(t){return this._entityToArchetype.get(t)}getAllArchetypes(){return Array.from(this._archetypes.values())}clear(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._queryCache.clear()}getEntityComponentTypes(t){return t.components.map((t=>t.constructor))}generateArchetypeId(t){return t.map((t=>getComponentTypeName(t))).sort().join("|")}createArchetype(t){const e=this.generateArchetypeId(t),n={id:e,componentTypes:[...t],entities:[],createdAt:Date.now(),updatedAt:Date.now()};return this._archetypes.set(e,n),n}archetypeContainsAllComponents(t,e){for(const n of e)if(!t.componentTypes.includes(n))return!1;return!0}updateComponentIndexes(t,e,n){for(const s of e){let e=this._componentToArchetypes.get(s);e||(e=new Set,this._componentToArchetypes.set(s,e)),n?e.add(t):(e.delete(t),0===e.size&&this._componentToArchetypes.delete(s))}}invalidateQueryCache(){this._queryCache.clear()}}var DirtyFlag,QueryConditionType,ECSEventType,EventPriority;!function(t){t[t.COMPONENT_MODIFIED=1]="COMPONENT_MODIFIED",t[t.COMPONENT_ADDED=2]="COMPONENT_ADDED",t[t.COMPONENT_REMOVED=4]="COMPONENT_REMOVED",t[t.TRANSFORM_CHANGED=8]="TRANSFORM_CHANGED",t[t.STATE_CHANGED=16]="STATE_CHANGED",t[t.CUSTOM_1=256]="CUSTOM_1",t[t.CUSTOM_2=512]="CUSTOM_2",t[t.CUSTOM_3=1024]="CUSTOM_3",t[t.ALL=4294967295]="ALL"}(DirtyFlag||(DirtyFlag={}));class DirtyTrackingSystem{constructor(){this._dirtyEntities=new Map,this._listeners=[],this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0},this._currentFrame=0,this._batchSize=100,this._maxProcessingTime=16,this._processingQueue=[],this._isProcessing=!1}markDirty(t,e,n=[]){this._stats.totalMarkings++;let s=this._dirtyEntities.get(t);s||(s={entity:t,flags:0,modifiedComponents:new Set,timestamp:performance.now(),frameNumber:this._currentFrame},this._dirtyEntities.set(t,s)),s.flags|=e,s.timestamp=performance.now(),s.frameNumber=this._currentFrame;for(const t of n)s.modifiedComponents.add(t);this.notifyListeners(s,e)}isDirty(t,e=DirtyFlag.ALL){const n=this._dirtyEntities.get(t);return!!n&&0!==(n.flags&e)}clearDirty(t,e=DirtyFlag.ALL){const n=this._dirtyEntities.get(t);n&&(e===DirtyFlag.ALL?this._dirtyEntities.delete(t):(n.flags&=~e,0===n.flags&&this._dirtyEntities.delete(t)),this._stats.totalCleanups++)}getDirtyEntities(t=DirtyFlag.ALL){const e=[];for(const n of this._dirtyEntities.values())0!==(n.flags&t)&&e.push(n);return e}processDirtyEntities(){if(this._isProcessing)return;this._isProcessing=!0;const t=performance.now();0===this._processingQueue.length&&this._processingQueue.push(...this._dirtyEntities.values());let e=0;for(;this._processingQueue.length>0&&e<this._batchSize;){if(performance.now()-t>this._maxProcessingTime)break;const n=this._processingQueue.shift();this.processEntity(n),e++}0===this._processingQueue.length&&(this._isProcessing=!1,this.onFrameEnd())}addListener(t){this._listeners.push(t),this._listeners.sort(((t,e)=>(t.priority||100)-(e.priority||100)))}removeListener(t){const e=this._listeners.findIndex((e=>e.callback===t));-1!==e&&this._listeners.splice(e,1)}beginFrame(){this._currentFrame++}endFrame(){this._isProcessing||this.processDirtyEntities()}getStats(){return{dirtyEntityCount:this._dirtyEntities.size,totalMarkings:this._stats.totalMarkings,totalCleanups:this._stats.totalCleanups,listenerCount:this._listeners.length,avgDirtyPerFrame:this._stats.frameCount>0?this._stats.totalDirtyPerFrame/this._stats.frameCount:0,estimatedMemoryUsage:this.estimateMemoryUsage()}}clear(){this._dirtyEntities.clear(),this._processingQueue.length=0,this._isProcessing=!1,this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0}}configureBatchProcessing(t,e){this._batchSize=t,this._maxProcessingTime=e}processEntity(t){for(const e of this._listeners)if(0!==(t.flags&e.flags))try{e.callback(t)}catch(t){DirtyTrackingSystem._logger.error("脏数据监听器错误:",t)}this.clearDirty(t.entity)}notifyListeners(t,e){for(const n of this._listeners)if(0!==(e&n.flags))try{n.callback(t)}catch(t){DirtyTrackingSystem._logger.error("脏数据监听器通知错误:",t)}}onFrameEnd(){this._stats.frameCount++,this._stats.totalDirtyPerFrame+=this._dirtyEntities.size}estimateMemoryUsage(){let t=0;return t+=100*this._dirtyEntities.size,t+=50*this._listeners.length,t+=8*this._processingQueue.length,t}}DirtyTrackingSystem._logger=createLogger("DirtyTrackingSystem"),function(t){t.ALL="all",t.ANY="any",t.NONE="none"}(QueryConditionType||(QueryConditionType={}));class QuerySystem{constructor(){this._logger=createLogger("QuerySystem"),this.entities=[],this.indexDirty=!0,this._version=0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.entityIndex={byMask:new Map,byComponentType:new Map,byTag:new Map,byName:new Map},this.componentPoolManager=ComponentPoolManager.getInstance(),this.componentIndexManager=new ComponentIndexManager,this.archetypeSystem=new ArchetypeSystem,this.dirtyTrackingSystem=new DirtyTrackingSystem}setEntities(t){this.entities=t,this.clearQueryCache(),this.rebuildIndexes()}addEntity(t,e=!1){this.entities.includes(t)||(this.entities.push(t),this.addEntityToIndexes(t),this.componentIndexManager.addEntity(t),this.archetypeSystem.addEntity(t),this.dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_ADDED),e||this.clearQueryCache(),this._version++)}addEntities(t){if(0===t.length)return;const e=new Set(this.entities.map((t=>t.id)));let n=0;for(const s of t)e.has(s.id)||(this.entities.push(s),this.addEntityToIndexes(s),e.add(s.id),n++);n>0&&this.clearQueryCache()}addEntitiesUnchecked(t){if(0!==t.length){for(const e of t)this.entities.push(e);for(const e of t)this.addEntityToIndexes(e);this.clearQueryCache()}}removeEntity(t){const e=this.entities.indexOf(t);-1!==e&&(this.entities.splice(e,1),this.removeEntityFromIndexes(t),this.componentIndexManager.removeEntity(t),this.archetypeSystem.removeEntity(t),this.dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_REMOVED),this.clearQueryCache(),this._version++)}addEntityToIndexes(t){const e=t.componentMask.toString();let n=this.entityIndex.byMask.get(e);n||(n=new Set,this.entityIndex.byMask.set(e,n)),n.add(t);const s=t.components;for(let e=0;e<s.length;e++){const n=s[e].constructor;let i=this.entityIndex.byComponentType.get(n);i||(i=new Set,this.entityIndex.byComponentType.set(n,i)),i.add(t)}const i=t.tag;if(void 0!==i){let e=this.entityIndex.byTag.get(i);e||(e=new Set,this.entityIndex.byTag.set(i,e)),e.add(t)}const o=t.name;if(o){let e=this.entityIndex.byName.get(o);e||(e=new Set,this.entityIndex.byName.set(o,e)),e.add(t)}}removeEntityFromIndexes(t){const e=t.componentMask.toString(),n=this.entityIndex.byMask.get(e);n&&(n.delete(t),0===n.size&&this.entityIndex.byMask.delete(e));for(const e of t.components){const n=e.constructor,s=this.entityIndex.byComponentType.get(n);s&&(s.delete(t),0===s.size&&this.entityIndex.byComponentType.delete(n))}if(void 0!==t.tag){const e=this.entityIndex.byTag.get(t.tag);e&&(e.delete(t),0===e.size&&this.entityIndex.byTag.delete(t.tag))}if(t.name){const e=this.entityIndex.byName.get(t.name);e&&(e.delete(t),0===e.size&&this.entityIndex.byName.delete(t.name))}}rebuildIndexes(){this.entityIndex.byMask.clear(),this.entityIndex.byComponentType.clear(),this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear(),this.componentIndexManager.clear();for(const t of this.entities)this.addEntityToIndexes(t),this.componentIndexManager.addEntity(t),this.archetypeSystem.addEntity(t);this.indexDirty=!1}queryAll(...t){const e=performance.now();this.queryStats.totalQueries++;const n=`all:${t.map((t=>getComponentTypeName(t))).sort().join(",")}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};let i=[];const o=this.archetypeSystem.queryArchetypes(t,"AND");if(o.archetypes.length>0){this.queryStats.archetypeHits++;for(const t of o.archetypes)i.push(...t.entities)}else try{if(1===t.length){this.queryStats.indexHits++;const e=this.componentIndexManager.query(t[0]);i=Array.from(e)}else{const e=this.componentIndexManager.queryMultiple(t,"AND");i=Array.from(e)}}catch(t){i=[]}return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryMultipleComponents(t){let e=null,n=1/0;for(const s of t){const t=this.entityIndex.byComponentType.get(s);if(!t||0===t.size)return[];t.size<n&&(n=t.size,e=t)}if(!e)return[];const s=this.createComponentMask(t),i=[];for(const t of e)t.componentMask.and(s).equals(s)&&i.push(t);return i}queryAny(...t){const e=performance.now();this.queryStats.totalQueries++;const n=`any:${t.map((t=>getComponentTypeName(t))).sort().join(",")}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};const i=this.archetypeSystem.queryArchetypes(t,"OR");let o;if(i.archetypes.length>0){this.queryStats.archetypeHits++,o=[];for(const t of i.archetypes)o.push(...t.entities)}else{const e=this.componentIndexManager.queryMultiple(t,"OR");o=Array.from(e)}return this.addToCache(n,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryNone(...t){const e=performance.now();this.queryStats.totalQueries++;const n=`none:${t.map((t=>getComponentTypeName(t))).sort().join(",")}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};const i=this.createComponentMask(t),o=this.entities.filter((t=>t.componentMask.and(i).isZero()));return this.addToCache(n,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryByTag(t){const e=performance.now();this.queryStats.totalQueries++;const n=`tag:${t}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byTag.get(t)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByName(t){const e=performance.now();this.queryStats.totalQueries++;const n=`name:${t}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byName.get(t)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByComponent(t){const e=performance.now();this.queryStats.totalQueries++;const n=`component:${getComponentTypeName(t)}`,s=this.getFromCache(n);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byComponentType.get(t)||[]);return this.addToCache(n,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}getFromCache(t){const e=this.queryCache.get(t);return e?Date.now()-e.timestamp>this.cacheTimeout?(this.queryCache.delete(t),null):(e.hitCount++,e.entities):null}addToCache(t,e){this.queryCache.size>=this.cacheMaxSize&&this.cleanupCache(),this.queryCache.set(t,{entities:[...e],timestamp:Date.now(),hitCount:0})}cleanupCache(){const t=Date.now();for(const[e,n]of this.queryCache.entries())t-n.timestamp>this.cacheTimeout&&this.queryCache.delete(e);if(this.queryCache.size>=this.cacheMaxSize){const t=Array.from(this.queryCache.entries());t.sort(((t,e)=>t[1].hitCount-e[1].hitCount));const e=Math.floor(.2*this.cacheMaxSize);for(let n=0;n<e&&n<t.length;n++)this.queryCache.delete(t[n][0])}}clearQueryCache(){this.queryCache.clear()}clearCache(){this.clearQueryCache()}batchUpdateComponents(t){const e=[];for(const n of t){const t=this.entities.find((t=>t.id===n.entityId));t&&(this.removeEntityFromIndexes(t),e.push(t))}for(const t of e)this.addEntityToIndexes(t);for(const t of e)this.dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_MODIFIED,[]);this.clearQueryCache()}createComponentMask(t){let e=BigIntFactory.zero(),n=!1;for(const s of t)try{const t=ComponentRegistry.getBitMask(s);e=e.or(t),n=!0}catch(t){this._logger.warn(`组件类型 ${getComponentTypeName(s)} 未注册,跳过`)}return n?e:BigIntFactory.create(-1)}get version(){return this._version}getAllEntities(){return[...this.entities]}getStats(){return{entityCount:this.entities.length,indexStats:{maskIndexSize:this.entityIndex.byMask.size,componentIndexSize:this.entityIndex.byComponentType.size,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},queryStats:{...this.queryStats,cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"},optimizationStats:{componentIndex:this.componentIndexManager.getStats(),archetypeSystem:this.archetypeSystem.getAllArchetypes().map((t=>({id:t.id,componentTypes:t.componentTypes.map((t=>getComponentTypeName(t))),entityCount:t.entities.length}))),dirtyTracking:this.dirtyTrackingSystem.getStats()},cacheStats:{size:this.queryCache.size,hitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}}configureDirtyTracking(t,e){this.dirtyTrackingSystem.configureBatchProcessing(t,e)}optimizePerformance(){this.dirtyTrackingSystem.processDirtyEntities(),this.cleanupCache(),this.componentIndexManager.getStats()}beginFrame(){this.dirtyTrackingSystem.beginFrame()}endFrame(){this.dirtyTrackingSystem.endFrame()}markEntityDirty(t,e){this.queryStats.dirtyChecks++,this.dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_MODIFIED,e),this.clearQueryCache()}getEntityArchetype(t){return this.archetypeSystem.getEntityArchetype(t)}}class QueryBuilder{constructor(t){this._logger=createLogger("QueryBuilder"),this.conditions=[],this.querySystem=t}withAll(...t){return this.conditions.push({type:QueryConditionType.ALL,componentTypes:t,mask:this.createComponentMask(t)}),this}withAny(...t){return this.conditions.push({type:QueryConditionType.ANY,componentTypes:t,mask:this.createComponentMask(t)}),this}without(...t){return this.conditions.push({type:QueryConditionType.NONE,componentTypes:t,mask:this.createComponentMask(t)}),this}execute(){const t=performance.now();if(1===this.conditions.length){const t=this.conditions[0];switch(t.type){case QueryConditionType.ALL:return this.querySystem.queryAll(...t.componentTypes);case QueryConditionType.ANY:return this.querySystem.queryAny(...t.componentTypes);case QueryConditionType.NONE:return this.querySystem.queryNone(...t.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-t,fromCache:!1}}createComponentMask(t){let e=BigIntFactory.zero();for(const n of t)try{const t=ComponentRegistry.getBitMask(n);e=e.or(t)}catch(t){this._logger.warn(`组件类型 ${getComponentTypeName(n)} 未注册,跳过`)}return e}reset(){return this.conditions=[],this}}class TypeSafeEventSystem{constructor(){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}on(t,e,n={}){return this.addListener(t,e,n)}once(t,e,n={}){return this.addListener(t,e,{...n,once:!0})}onAsync(t,e,n={}){return this.addListener(t,e,{...n,async:!0})}off(t,e){const n=this.listeners.get(t);if(!n)return!1;const s=n.findIndex((t=>t.id===e));return-1!==s&&(n.splice(s,1),0===n.length&&(this.listeners.delete(t),this.stats.delete(t)),!0)}offAll(t){this.listeners.delete(t),this.stats.delete(t),this.clearBatch(t)}async emit(t,e){if(!this.isEnabled)return;const n=this.batchConfigs.get(t);n?.enabled?this.addToBatch(t,e):await this.executeEvent(t,e)}emitSync(t,e){if(!this.isEnabled)return;const n=this.listeners.get(t);if(!n||0===n.length)return;const s=performance.now(),i=[],o=this.sortListenersByPriority(n);for(const n of o)if(!n.config.async)try{n.config.context?n.handler.call(n.config.context,e):n.handler(e),n.config.once&&i.push(n.id)}catch(e){TypeSafeEventSystem._logger.error(`事件处理器执行错误 ${t}:`,e)}this.removeListeners(t,i),this.updateStats(t,performance.now()-s)}setBatchConfig(t,e){this.batchConfigs.set(t,e)}flushBatch(t){const e=this.batchQueue.get(t);if(!e||0===e.length)return;const n=this.batchTimers.get(t);n&&(clearTimeout(n),this.batchTimers.delete(t)),this.processBatch(t,e),this.batchQueue.delete(t)}getStats(t){return t?this.stats.get(t)||this.createEmptyStats(t):new Map(this.stats)}resetStats(t){t?this.stats.delete(t):this.stats.clear()}setEnabled(t){this.isEnabled=t}hasListeners(t){const e=this.listeners.get(t);return!!e&&e.length>0}getListenerCount(t){const e=this.listeners.get(t);return e?e.length:0}clear(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()}setMaxListeners(t){this.maxListeners=t}addListener(t,e,n){let s=this.listeners.get(t);if(s||(s=[],this.listeners.set(t,s)),s.length>=this.maxListeners)return TypeSafeEventSystem._logger.warn(`事件类型 ${t} 的监听器数量超过最大限制 (${this.maxListeners})`),"";const i="listener_"+this.nextListenerId++,o={handler:e,config:{priority:0,...n},id:i};return s.push(o),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),i}async executeEvent(t,e){const n=this.listeners.get(t);if(!n||0===n.length)return;const s=performance.now(),i=[],o=this.sortListenersByPriority(n),r=o.filter((t=>!t.config.async)),a=o.filter((t=>t.config.async));for(const n of r)try{n.config.context?n.handler.call(n.config.context,e):n.handler(e),n.config.once&&i.push(n.id)}catch(e){TypeSafeEventSystem._logger.error(`同步事件处理器执行错误 ${t}:`,e)}const c=a.map((async n=>{try{n.config.context?await n.handler.call(n.config.context,e):await n.handler(e),n.config.once&&i.push(n.id)}catch(e){TypeSafeEventSystem._logger.error(`异步事件处理器执行错误 ${t}:`,e)}}));await Promise.all(c),this.removeListeners(t,i),this.updateStats(t,performance.now()-s)}sortListenersByPriority(t){return t.slice().sort(((t,e)=>(e.config.priority||0)-(t.config.priority||0)))}removeListeners(t,e){if(0===e.length)return;const n=this.listeners.get(t);if(n){for(const t of e){const e=n.findIndex((e=>e.id===t));-1!==e&&n.splice(e,1)}0===n.length&&(this.listeners.delete(t),this.stats.delete(t))}}addToBatch(t,e){let n=this.batchQueue.get(t);n||(n=[],this.batchQueue.set(t,n)),n.push(e);const s=this.batchConfigs.get(t);if(n.length>=s.batchSize)this.flushBatch(t);else if(!this.batchTimers.has(t)){const e=setTimeout((()=>{this.flushBatch(t)}),s.delay);this.batchTimers.set(t,e)}}async processBatch(t,e){const n={type:t,events:e,count:e.length,timestamp:Date.now()};await this.executeEvent(`${t}:batch`,n)}clearBatch(t){this.batchQueue.delete(t);const e=this.batchTimers.get(t);e&&(clearTimeout(e),this.batchTimers.delete(t))}clearAllBatches(){this.batchQueue.clear();for(const t of this.batchTimers.values())clearTimeout(t);this.batchTimers.clear(),this.batchConfigs.clear()}updateStats(t,e){let n=this.stats.get(t);n||(n=this.createEmptyStats(t),this.stats.set(t,n)),n.triggerCount++,n.totalExecutionTime+=e,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(t)}createEmptyStats(t){return{eventType:t,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}}}TypeSafeEventSystem._logger=createLogger("EventSystem"),function(t){t.ENTITY_CREATED="entity:created",t.ENTITY_DESTROYED="entity:destroyed",t.ENTITY_ENABLED="entity:enabled",t.ENTITY_DISABLED="entity:disabled",t.ENTITY_TAG_ADDED="entity:tag:added",t.ENTITY_TAG_REMOVED="entity:tag:removed",t.ENTITY_NAME_CHANGED="entity:name:changed",t.COMPONENT_ADDED="component:added",t.COMPONENT_REMOVED="component:removed",t.COMPONENT_MODIFIED="component:modified",t.COMPONENT_ENABLED="component:enabled",t.COMPONENT_DISABLED="component:disabled",t.SYSTEM_ADDED="system:added",t.SYSTEM_REMOVED="system:removed",t.SYSTEM_ENABLED="system:enabled",t.SYSTEM_DISABLED="system:disabled",t.SYSTEM_PROCESSING_START="system:processing:start",t.SYSTEM_PROCESSING_END="system:processing:end",t.SYSTEM_ERROR="system:error",t.SCENE_CREATED="scene:created",t.SCENE_DESTROYED="scene:destroyed",t.SCENE_ACTIVATED="scene:activated",t.SCENE_DEACTIVATED="scene:deactivated",t.SCENE_PAUSED="scene:paused",t.SCENE_RESUMED="scene:resumed",t.QUERY_EXECUTED="query:executed",t.QUERY_CACHE_HIT="query:cache:hit",t.QUERY_CACHE_MISS="query:cache:miss",t.QUERY_OPTIMIZED="query:optimized",t.PERFORMANCE_WARNING="performance:warning",t.PERFORMANCE_CRITICAL="performance:critical",t.MEMORY_USAGE_HIGH="memory:usage:high",t.FRAME_RATE_DROP="frame:rate:drop",t.INDEX_CREATED="index:created",t.INDEX_UPDATED="index:updated",t.INDEX_OPTIMIZED="index:optimized",t.ARCHETYPE_CREATED="archetype:created",t.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",t.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",t.DIRTY_MARK_ADDED="dirty:mark:added",t.DIRTY_BATCH_PROCESSED="dirty:batch:processed",t.ERROR_OCCURRED="error:occurred",t.WARNING_ISSUED="warning:issued",t.FRAMEWORK_INITIALIZED="framework:initialized",t.FRAMEWORK_SHUTDOWN="framework:shutdown",t.DEBUG_INFO="debug:info",t.DEBUG_STATS_UPDATED="debug:stats:updated"}(ECSEventType||(ECSEventType={})),function(t){t[t.LOWEST=0]="LOWEST",t[t.LOW=25]="LOW",t[t.NORMAL=50]="NORMAL",t[t.HIGH=75]="HIGH",t[t.HIGHEST=100]="HIGHEST",t[t.CRITICAL=200]="CRITICAL"}(EventPriority||(EventPriority={}));const EVENT_TYPES={ENTITY:{CREATED:ECSEventType.ENTITY_CREATED,DESTROYED:ECSEventType.ENTITY_DESTROYED,ENABLED:ECSEventType.ENTITY_ENABLED,DISABLED:ECSEventType.ENTITY_DISABLED,TAG_ADDED:ECSEventType.ENTITY_TAG_ADDED,TAG_REMOVED:ECSEventType.ENTITY_TAG_REMOVED,NAME_CHANGED:ECSEventType.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:ECSEventType.COMPONENT_ADDED,REMOVED:ECSEventType.COMPONENT_REMOVED,MODIFIED:ECSEventType.COMPONENT_MODIFIED,ENABLED:ECSEventType.COMPONENT_ENABLED,DISABLED:ECSEventType.COMPONENT_DISABLED},SYSTEM:{ADDED:ECSEventType.SYSTEM_ADDED,REMOVED:ECSEventType.SYSTEM_REMOVED,ENABLED:ECSEventType.SYSTEM_ENABLED,DISABLED:ECSEventType.SYSTEM_DISABLED,PROCESSING_START:ECSEventType.SYSTEM_PROCESSING_START,PROCESSING_END:ECSEventType.SYSTEM_PROCESSING_END,ERROR:ECSEventType.SYSTEM_ERROR},PERFORMANCE:{WARNING:ECSEventType.PERFORMANCE_WARNING,CRITICAL:ECSEventType.PERFORMANCE_CRITICAL,MEMORY_HIGH:ECSEventType.MEMORY_USAGE_HIGH,FRAME_DROP:ECSEventType.FRAME_RATE_DROP}};class EventTypeValidator{static isValid(t){return this.validTypes.has(t)}static getAllValidTypes(){return Array.from(this.validTypes)}static addCustomType(t){this.validTypes.add(t)}static removeCustomType(t){this.validTypes.delete(t)}}EventTypeValidator.validTypes=new Set([...Object.values(ECSEventType),...Object.values(EVENT_TYPES.ENTITY),...Object.values(EVENT_TYPES.COMPONENT),...Object.values(EVENT_TYPES.SYSTEM),...Object.values(EVENT_TYPES.PERFORMANCE)]);class EventBus{constructor(t=!1){this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new TypeSafeEventSystem,this.isDebugMode=t}emit(t,e){this.validateEventType(t);const n=this.enhanceEventData(t,e);this.isDebugMode&&EventBus._logger.info(`发射事件: ${t}`,n),this.eventSystem.emitSync(t,n)}async emitAsync(t,e){this.validateEventType(t);const n=this.enhanceEventData(t,e);this.isDebugMode&&EventBus._logger.info(`发射异步事件: ${t}`,n),await this.eventSystem.emit(t,n)}on(t,e,n={}){this.validateEventType(t);const s={once:n.once||!1,priority:n.priority||EventPriority.NORMAL,async:n.async||!1,context:n.context};return this.isDebugMode&&EventBus._logger.info(`添加监听器: ${t}`,s),this.eventSystem.on(t,e,s)}once(t,e,n={}){return this.on(t,e,{...n,once:!0})}onAsync(t,e,n={}){return this.on(t,e,{...n,async:!0})}off(t,e){return this.isDebugMode&&EventBus._logger.info(`移除监听器: ${e} 事件: ${t}`),this.eventSystem.off(t,e)}offAll(t){this.isDebugMode&&EventBus._logger.info(`移除所有监听器: ${t}`),this.eventSystem.offAll(t)}hasListeners(t){return this.eventSystem.hasListeners(t)}getStats(t){const e=this.eventSystem.getStats(t);if(e instanceof Map){const t=new Map;return e.forEach(((e,n)=>{t.set(n,this.convertEventStats(e))})),t}return this.convertEventStats(e)}clear(){this.isDebugMode&&EventBus._logger.info("清空所有监听器"),this.eventSystem.clear()}setEnabled(t){this.eventSystem.setEnabled(t)}setDebugMode(t){this.isDebugMode=t}setMaxListeners(t){this.eventSystem.setMaxListeners(t)}getListenerCount(t){return this.eventSystem.getListenerCount(t)}setBatchConfig(t,e,n){this.eventSystem.setBatchConfig(t,{batchSize:e,delay:n,enabled:!0})}flushBatch(t){this.eventSystem.flushBatch(t)}resetStats(t){this.eventSystem.resetStats(t)}emitEntityCreated(t){this.emit(ECSEventType.ENTITY_CREATED,t)}emitEntityDestroyed(t){this.emit(ECSEventType.ENTITY_DESTROYED,t)}emitComponentAdded(t){this.emit(ECSEventType.COMPONENT_ADDED,t)}emitComponentRemoved(t){this.emit(ECSEventType.COMPONENT_REMOVED,t)}emitSystemAdded(t){this.emit(ECSEventType.SYSTEM_ADDED,t)}emitSystemRemoved(t){this.emit(ECSEventType.SYSTEM_REMOVED,t)}emitSceneChanged(t){this.emit(ECSEventType.SCENE_ACTIVATED,t)}emitPerformanceWarning(t){this.emit(ECSEventType.PERFORMANCE_WARNING,t)}onEntityCreated(t,e){return this.on(ECSEventType.ENTITY_CREATED,t,e)}onComponentAdded(t,e){return this.on(ECSEventType.COMPONENT_ADDED,t,e)}onSystemError(t,e){return this.on(ECSEventType.SYSTEM_ERROR,t,e)}onPerformanceWarning(t,e){return this.on(ECSEventType.PERFORMANCE_WARNING,t,e)}validateEventType(t){EventTypeValidator.isValid(t)||(this.isDebugMode&&EventBus._logger.warn(`未知事件类型: ${t}`),this.isDebugMode&&EventTypeValidator.addCustomType(t))}enhanceEventData(t,e){if(null==e)return{timestamp:Date.now(),eventId:`${t}_${++this.eventIdCounter}`,source:"EventBus"};const n=e;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=`${t}_${++this.eventIdCounter}`),n.source||(n.source="EventBus"),n}convertEventStats(t){return{eventType:t.eventType,listenerCount:t.listenerCount,triggerCount:t.triggerCount,totalExecutionTime:t.totalExecutionTime,averageExecutionTime:t.averageExecutionTime,lastTriggerTime:t.lastTriggerTime}}}EventBus._logger=createLogger("EventBus");class GlobalEventBus{static getInstance(t=!1){return this.instance||(this.instance=new EventBus(t)),this.instance}static reset(t=!1){return this.instance&&this.instance.clear(),this.instance=new EventBus(t),this.instance}}function EventHandler(t,e={}){return function(n,s,i){const o=i.value,r=n.constructor.prototype.initEventListeners||function(){};return n.constructor.prototype.initEventListeners=function(){r.call(this);GlobalEventBus.getInstance().on(t,o.bind(this),e)},i}}function AsyncEventHandler(t,e={}){return function(n,s,i){const o=i.value,r=n.constructor.prototype.initEventListeners||function(){};return n.constructor.prototype.initEventListeners=function(){r.call(this);GlobalEventBus.getInstance().onAsync(t,o.bind(this),e)},i}}class Scene{get systems(){return this.entityProcessors.processors}constructor(t){this.name="",this._didSceneBegin=!1,this.entities=new EntityList(this),this.entityProcessors=new EntityProcessorList,this.identifierPool=new IdentifierPool,this.componentStorageManager=new ComponentStorageManager,this.querySystem=new QuerySystem,this.eventSystem=new TypeSafeEventSystem,t?.name&&(this.name=t.name),Entity.eventBus||(Entity.eventBus=new EventBus(!1)),Entity.eventBus&&Entity.eventBus.onComponentAdded((t=>{this.eventSystem.emitSync("component:added",t)}))}initialize(){}onStart(){}unload(){}begin(){null!=this.entityProcessors&&this.entityProcessors.begin(),this._didSceneBegin=!0,this.onStart()}end(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this.entityProcessors&&this.entityProcessors.end(),this.unload()}update(){this.entities.updateLists(),null!=this.entityProcessors&&this.entityProcessors.update(),this.entities.update(),null!=this.entityProcessors&&this.entityProcessors.lateUpdate()}createEntity(t){let e=new Entity(t,this.identifierPool.checkOut());return this.eventSystem.emitSync("entity:created",{entityName:t,entity:e,scene:this}),this.addEntity(e)}addEntity(t,e=!1){return this.entities.add(t),t.scene=this,this.querySystem.addEntity(t,e),this.eventSystem.emitSync("entity:added",{entity:t,scene:this}),t}createEntities(t,e="Entity"){const n=[];for(let s=0;s<t;s++){const t=new Entity(`${e}_${s}`,this.identifierPool.checkOut());t.scene=this,n.push(t)}for(const t of n)this.entities.add(t);return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:t}),n}destroyAllEntities(){this.entities.removeAllEntities(),this.querySystem.setEntities([])}findEntity(t){return this.entities.findEntity(t)}findEntityById(t){return this.entities.findEntityById(t)}findEntitiesByTag(t){const e=[];for(const n of this.entities.buffer)n.tag===t&&e.push(n);return e}getEntityByName(t){return this.findEntity(t)}getEntitiesByTag(t){return this.findEntitiesByTag(t)}addEntityProcessor(t){return this.entityProcessors.processors.includes(t)||(t.scene=this,this.entityProcessors.add(t),t.initialize(),t.setUpdateOrder(this.entityProcessors.count-1)),t}addSystem(t){return this.addEntityProcessor(t)}removeEntityProcessor(t){this.entityProcessors.remove(t),t.reset(),t.scene=null}getEntityProcessor(t){return this.entityProcessors.getProcessor(t)}getStats(){return{entityCount:this.entities.count,processorCount:this.entityProcessors.count,componentStorageStats:this.componentStorageManager.getAllStats()}}compactComponentStorage(){this.componentStorageManager.compactAll()}getDebugInfo(){return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:this.entityProcessors.count,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((t=>({name:t.name,id:t.id,componentCount:t.components.length,componentTypes:t.components.map((t=>getComponentInstanceTypeName(t)))}))),processors:this.entityProcessors.processors.map((t=>({name:getSystemInstanceTypeName(t),updateOrder:t.updateOrder,entityCount:t._entities?.length||0}))),componentStats:this.componentStorageManager.getAllStats()}}}class SceneBuilder{constructor(){this.scene=new Scene}named(t){return this.scene.name=t,this}withEntity(t){return this.scene.addEntity(t),this}withEntityBuilder(t){const e=t(new EntityBuilder(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(e),this}withEntities(...t){for(const e of t)this.scene.addEntity(e);return this}withSystem(t){return this.scene.addSystem(t),this}withSystems(...t){for(const e of t)this.scene.addSystem(e);return this}build(){return this.scene}}class ComponentBuilder{constructor(t,...e){this.component=new t(...e)}set(t,e){return this.component[t]=e,this}configure(t){return t(this.component),this}setIf(t,e,n){return t&&(this.component[e]=n),this}build(){return this.component}}class EntityBatchOperator{constructor(t){this.entities=t}addComponent(t){for(const e of this.entities)e.addComponent(t);return this}removeComponent(t){for(const e of this.entities)e.removeComponentByType(t);return this}setActive(t){for(const e of this.entities)e.active=t;return this}setTag(t){for(const e of this.entities)e.tag=t;return this}forEach(t){return this.entities.forEach(t),this}filter(t){return new EntityBatchOperator(this.entities.filter(t))}toArray(){return this.entities.slice()}count(){return this.entities.length}}class ECSFluentAPI{constructor(t,e,n){this.scene=t,this.querySystem=e,this.eventSystem=n}createEntity(){return new EntityBuilder(this.scene,this.scene.componentStorageManager)}createScene(){return new SceneBuilder}createComponent(t,...e){return new ComponentBuilder(t,...e)}query(){return new QueryBuilder(this.querySystem)}find(...t){return this.querySystem.queryAll(...t).entities}findFirst(...t){const e=this.querySystem.queryAll(...t);return e.entities.length>0?e.entities[0]:null}findByName(t){return this.scene.findEntity(t)}findByTag(t){return this.scene.findEntitiesByTag(t)}emit(t,e){this.eventSystem.emitSync(t,e)}async emitAsync(t,e){await this.eventSystem.emit(t,e)}on(t,e){return this.eventSystem.on(t,e)}once(t,e){return this.eventSystem.once(t,e)}off(t,e){this.eventSystem.off(t,e)}batch(t){return new EntityBatchOperator(t)}getStats(){return{entityCount:this.scene.entities.count,systemCount:this.scene.systems.length,componentStats:this.scene.componentStorageManager.getAllStats(),queryStats:this.querySystem.getStats(),eventStats:this.eventSystem.getStats()}}}function createECSAPI(t,e,n){return new ECSFluentAPI(t,e,n)}const logger$1=createLogger("World");class World{constructor(t={}){this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config={name:"World",debug:!1,maxScenes:10,autoCleanup:!0,...t},this.name=this._config.name,this._createdAt=Date.now(),logger$1.info(`创建World: ${this.name}`)}createScene(t,e){if(this._scenes.has(t))throw new Error(`Scene ID '${t}' 已存在于World '${this.name}' 中`);if(this._scenes.size>=this._config.maxScenes)throw new Error(`World '${this.name}' 已达到最大Scene数量限制: ${this._config.maxScenes}`);const n=e||new Scene;return"id"in n&&(n.id=t),"name"in n&&!n.name&&(n.name=t),this._scenes.set(t,n),n.initialize(),logger$1.info(`在World '${this.name}' 中创建Scene: ${t}`),n}removeScene(t){const e=this._scenes.get(t);return!!e&&(this._activeScenes.has(t)&&this.setSceneActive(t,!1),e.end(),this._scenes.delete(t),logger$1.info(`从World '${this.name}' 中移除Scene: ${t}`),!0)}getScene(t){return this._scenes.get(t)||null}getSceneIds(){return Array.from(this._scenes.keys())}getAllScenes(){return Array.from(this._scenes.values())}setSceneActive(t,e){const n=this._scenes.get(t);n?e?(this._activeScenes.add(t),n.begin&&n.begin(),logger$1.debug(`在World '${this.name}' 中激活Scene: ${t}`)):(this._activeScenes.delete(t),logger$1.debug(`在World '${this.name}' 中停用Scene: ${t}`)):logger$1.warn(`Scene '${t}' 不存在于World '${this.name}' 中`)}isSceneActive(t){return this._activeScenes.has(t)}getActiveSceneCount(){return this._activeScenes.size}addGlobalSystem(t){return this._globalSystems.includes(t)||(this._globalSystems.push(t),t.initialize&&t.initialize(),logger$1.debug(`在World '${this.name}' 中添加全局System: ${t.name}`)),t}removeGlobalSystem(t){const e=this._globalSystems.indexOf(t);return-1!==e&&(this._globalSystems.splice(e,1),t.reset&&t.reset(),logger$1.debug(`从World '${this.name}' 中移除全局System: ${t.name}`),!0)}getGlobalSystem(t){for(const e of this._globalSystems)if(e instanceof t)return e;return null}start(){if(!this._isActive){this._isActive=!0;for(const t of this._globalSystems)t.initialize&&t.initialize();logger$1.info(`启动World: ${this.name}`)}}stop(){if(this._isActive){for(const t of this._activeScenes)this.setSceneActive(t,!1);for(const t of this._globalSystems)t.reset&&t.reset();this._isActive=!1,logger$1.info(`停止World: ${this.name}`)}}updateGlobalSystems(){if(this._isActive)for(const t of this._globalSystems)t.update&&t.update()}updateScenes(){if(this._isActive){for(const t of this._activeScenes){const e=this._scenes.get(t);e&&e.update&&e.update()}this._config.autoCleanup&&this.shouldAutoCleanup()&&this.cleanup()}}destroy(){logger$1.info(`销毁World: ${this.name}`),this.stop();const t=Array.from(this._scenes.keys());for(const e of t)this.removeScene(e);for(const t of this._globalSystems)t.destroy?t.destroy():t.reset&&t.reset();this._globalSystems.length=0,this._scenes.clear(),this._activeScenes.clear()}getStatus(){return{name:this.name,isActive:this._isActive,sceneCount:this._scenes.size,activeSceneCount:this._activeScenes.size,globalSystemCount:this._globalSystems.length,createdAt:this._createdAt,config:{...this._config},scenes:Array.from(this._scenes.keys()).map((t=>({id:t,isActive:this._activeScenes.has(t),name:this._scenes.get(t)?.name||t})))}}getStats(){const t={totalEntities:0,totalSystems:this._globalSystems.length,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}};for(const e of this._scenes.values())e.entities&&(t.totalEntities+=e.entities.count),e.systems&&(t.totalSystems+=e.systems.length);return t}shouldAutoCleanup(){const t=Date.now();for(const[e,n]of this._scenes)if(!this._activeScenes.has(e)&&n.entities&&0===n.entities.count&&t-this._createdAt>3e5)return!0;return!1}cleanup(){const t=Array.from(this._scenes.keys()),e=Date.now();for(const n of t){const t=this._scenes.get(n);t&&!this._activeScenes.has(n)&&t.entities&&0===t.entities.count&&e-this._createdAt>3e5&&(this.removeScene(n),logger$1.debug(`自动清理空Scene: ${n} from World ${this.name}`))}}get isActive(){return this._isActive}get sceneCount(){return this._scenes.size}get createdAt(){return this._createdAt}}const logger=createLogger("WorldManager");class WorldManager{constructor(t={}){this._worlds=new Map,this._activeWorlds=new Set,this._cleanupTimer=null,this._isRunning=!1,this._config={maxWorlds:50,autoCleanup:!0,cleanupInterval:3e4,debug:!1,...t},logger.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupInterval:this._config.cleanupInterval}),this.startCleanupTimer()}static getInstance(t){return this._instance||(this._instance=new WorldManager(t)),this._instance}static reset(){this._instance&&(this._instance.destroy(),this._instance=null)}createWorld(t,e){if(!t||"string"!=typeof t||""===t.trim())throw new Error("World ID不能为空");if(this._worlds.has(t))throw new Error(`World ID '${t}' 已存在`);if(this._worlds.size>=this._config.maxWorlds)throw new Error(`已达到最大World数量限制: ${this._config.maxWorlds}`);const n={name:t,debug:this._config.debug,...e},s=new World(n);return this._worlds.set(t,s),logger.info(`创建World: ${t}`,{config:n}),s}removeWorld(t){const e=this._worlds.get(t);return!!e&&(this._activeWorlds.has(t)&&this.setWorldActive(t,!1),e.destroy(),this._worlds.delete(t),logger.info(`移除World: ${t}`),!0)}getWorld(t){return this._worlds.get(t)||null}getWorldIds(){return Array.from(this._worlds.keys())}getAllWorlds(){return Array.from(this._worlds.values())}setWorldActive(t,e){const n=this._worlds.get(t);n?e?(this._activeWorlds.add(t),n.start(),logger.debug(`激活World: ${t}`)):(this._activeWorlds.delete(t),n.stop(),logger.debug(`停用World: ${t}`)):logger.warn(`World '${t}' 不存在`)}isWorldActive(t){return this._activeWorlds.has(t)}getActiveWorlds(){const t=[];for(const e of this._activeWorlds){const n=this._worlds.get(e);n&&t.push(n)}return t}startAll(){this._isRunning=!0;for(const t of this._worlds.keys())this.setWorldActive(t,!0);logger.info("启动所有World")}stopAll(){this._isRunning=!1;for(const t of this._activeWorlds)this.setWorldActive(t,!1);logger.info("停止所有World")}findWorlds(t){const e=[];for(const n of this._worlds.values())t(n)&&e.push(n);return e}findWorldByName(t){for(const e of this._worlds.values())if(e.name===t)return e;return null}getStats(){const t={totalWorlds:this._worlds.size,activeWorlds:this._activeWorlds.size,totalScenes:0,totalEntities:0,totalSystems:0,memoryUsage:0,isRunning:this._isRunning,config:{...this._config},worlds:[]};for(const[e,n]of this._worlds){const s=n.getStats();t.totalScenes+=s.totalSystems,t.totalEntities+=s.totalEntities,t.totalSystems+=s.totalSystems,t.worlds.push({id:e,name:n.name,isActive:this._activeWorlds.has(e),sceneCount:n.sceneCount,...s})}return t}getDetailedStatus(){return{...this.getStats(),worlds:Array.from(this._worlds.entries()).map((([t,e])=>({id:t,isActive:this._activeWorlds.has(t),status:e.getStatus()})))}}cleanup(){const t=[];for(const[e,n]of this._worlds)this.shouldCleanupWorld(n)&&t.push(e);for(const e of t)this.removeWorld(e);return t.length>0&&logger.debug(`清理了 ${t.length} 个World`),t.length}destroy(){logger.info("正在销毁WorldManager..."),this.stopCleanupTimer(),this.stopAll();const t=Array.from(this._worlds.keys());for(const e of t)this.removeWorld(e);this._worlds.clear(),this._activeWorlds.clear(),this._isRunning=!1,logger.info("WorldManager已销毁")}startCleanupTimer(){this._config.autoCleanup&&!this._cleanupTimer&&(this._cleanupTimer=setInterval((()=>{this.cleanup()}),this._config.cleanupInterval),logger.debug(`启动World清理定时器,间隔: ${this._config.cleanupInterval}ms`))}stopCleanupTimer(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null,logger.debug("停止World清理定时器"))}shouldCleanupWorld(t){if(t.isActive)return!1;if(0===t.sceneCount){return Date.now()-t.createdAt>6e5}if(!t.getAllScenes().some((t=>t.entities&&t.entities.count>0))){return Date.now()-t.createdAt>6e5}return!1}get worldCount(){return this._worlds.size}get activeWorldCount(){return this._activeWorlds.size}get isRunning(){return this._isRunning}get config(){return{...this._config}}}WorldManager._instance=null;class Bits{constructor(t){this._value=t&&"object"==typeof t?t:BigIntFactory.create(t||0)}set(t){if(t<0)throw new Error("Bit index cannot be negative");const e=BigIntFactory.one().shiftLeft(t);this._value=this._value.or(e)}clear(t){if(t<0)throw new Error("Bit index cannot be negative");const e=BigIntFactory.one().shiftLeft(t).not();this._value=this._value.and(e)}get(t){if(t<0)return!1;const e=BigIntFactory.one().shiftLeft(t);return!this._value.and(e).isZero()}containsAll(t){return this._value.and(t._value).equals(t._value)}intersects(t){return!this._value.and(t._value).isZero()}excludes(t){return!this.intersects(t)}clearAll(){this._value=BigIntFactory.zero()}isEmpty(){return this._value.isZero()}cardinality(){let t=0,e=this._value.clone();for(;!e.isZero();){const n=BigIntFactory.one();e.and(n).isZero()||t++,e=e.shiftRight(1)}return t}and(t){return new Bits(this._value.and(t._value))}or(t){return new Bits(this._value.or(t._value))}xor(t){return new Bits(this._value.xor(t._value))}not(t=64){return new Bits(this._value.not(t))}copyFrom(t){this._value=t._value.clone()}clone(){return new Bits(this._value.clone())}getValue(){return this._value}setValue(t){this._value="object"==typeof t?t:BigIntFactory.create(t)}toString(){const t=[];let e=0,n=this._value.clone();for(;!n.isZero();){const s=BigIntFactory.one();n.and(s).isZero()||t.push(e.toString()),n=n.shiftRight(1),e++}return`Bits[${t.join(", ")}]`}toBinaryString(t=64){let e="";for(let n=t-1;n>=0;n--)e+=this.get(n)?"1":"0",n%8==0&&n>0&&(e+=" ");return e}toHexString(){return"0x"+this._value.toString(16).toUpperCase()}static fromBinaryString(t){const e=t.replace(/\s/g,""),n=BigIntFactory.fromBinaryString(e);return new Bits(n)}static fromHexString(t){const e=BigIntFactory.fromHexString(t);return new Bits(e)}equals(t){return this._value.equals(t._value)}getHighestBitIndex(){if(this._value.isZero())return-1;let t=0,e=this._value.clone();for(;!e.shiftRight(1).isZero();)e=e.shiftRight(1),t++;return t}getLowestBitIndex(){if(this._value.isZero())return-1;let t=0,e=this._value.clone();const n=BigIntFactory.one();for(;e.and(n).isZero();)e=e.shiftRight(1),t++;return t}}class ComponentTypeManager{static get instance(){return ComponentTypeManager._instance||(ComponentTypeManager._instance=new ComponentTypeManager),ComponentTypeManager._instance}constructor(){this._componentTypes=new Map,this._typeNames=new Map,this._nextTypeId=0}getTypeId(t){let e=this._componentTypes.get(t);return void 0===e&&(e=this._nextTypeId++,this._componentTypes.set(t,e),this._typeNames.set(e,getComponentTypeName(t))),e}getTypeName(t){return this._typeNames.get(t)||"Unknown"}createBits(...t){const e=new Bits;for(const n of t){const t=this.getTypeId(n);e.set(t)}return e}getEntityBits(t){const e=new Bits;for(const n of t){const t=this.getTypeId(n.constructor);e.set(t)}return e}reset(){this._componentTypes.clear(),this._typeNames.clear(),this._nextTypeId=0}get registeredTypeCount(){return this._componentTypes.size}}class EntityDataCollector{collectEntityData(){const t=Core.scene;if(!t)return this.getEmptyEntityDebugData();const e=t.entities;if(!e)return this.getEmptyEntityDebugData();let n;try{n=e.getStats?e.getStats():this.calculateFallbackEntityStats(e)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeData(t);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:[],entityDetailsMap:{}}}getRawEntityList(){const t=Core.scene;if(!t)return[];const e=t.entities;return e?.buffer?e.buffer.map((t=>({id:t.id,name:t.name||`Entity_${t.id}`,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:!1!==t.activeInHierarchy,componentCount:t.components.length,componentTypes:t.components.map((t=>getComponentInstanceTypeName(t))),parentId:t.parent?.id||null,childIds:t.children?.map((t=>t.id))||[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0}))):[]}getEntityDetails(t){try{const e=Core.scene;if(!e)return null;const n=e.entities;if(!n?.buffer)return null;const s=n.buffer.find((e=>e.id===t));if(!s)return null;const i=s.getDebugInfo?s.getDebugInfo():this.buildFallbackEntityInfo(s),o=this.extractComponentDetails(s.components),r=this.getSceneInfo(e);return{...i,scene:r.name,sceneName:r.name,sceneType:r.type,parentName:s.parent?.name||null,components:o||[],componentCount:s.components?.length||0,componentTypes:s.components?.map((t=>getComponentInstanceTypeName(t)))||[]}}catch(t){return{error:`获取实体详情失败: ${t instanceof Error?t.message:String(t)}`,scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}}getSceneInfo(t){let e="当前场景",n="Scene";try{if(t.name&&"string"==typeof t.name&&t.name.trim())e=t.name.trim();else if(t.constructor&&t.constructor.name)e=t.constructor.name,n=t.constructor.name;else if(t._name&&"string"==typeof t._name&&t._name.trim())e=t._name.trim();else{const s=Object.getPrototypeOf(t)?.constructor?.name;s&&"Object"!==s&&(e=s,n=s)}}catch(t){e="场景名获取失败"}return{name:e,type:n}}collectEntityDataWithMemory(){const t=Core.scene;if(!t)return this.getEmptyEntityDebugData();const e=t.entities;if(!e)return this.getEmptyEntityDebugData();let n;try{n=e.getStats?e.getStats():this.calculateFallbackEntityStats(e)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const s=this.collectArchetypeDataWithMemory(t);return{totalEntities:n.totalEntities,activeEntities:n.activeEntities,pendingAdd:n.pendingAdd||0,pendingRemove:n.pendingRemove||0,entitiesPerArchetype:s.distribution,topEntitiesByComponents:s.topEntities,entityHierarchy:this.buildEntityHierarchyTree(e),entityDetailsMap:this.buildEntityDetailsMap(e)}}collectArchetypeData(t){if(t&&t.archetypeSystem&&"function"==typeof t.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(t.archetypeSystem);const e={entities:t.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionFast(e),topEntities:this.getTopEntitiesByComponentsFast(e)}}getArchetypeDistributionFast(t){const e=new Map;return t&&t.entities&&t.entities.forEach((t=>{const n=t.components?.map((t=>getComponentInstanceTypeName(t)))||[],s=n.length>0?n.sort().join(", "):"无组件",i=e.get(s);i?i.count++:e.set(s,{count:1,componentTypes:n})})),Array.from(e.entries()).map((([t,e])=>({signature:t,count:e.count,memory:0}))).sort(((t,e)=>e.count-t.count)).slice(0,20)}getTopEntitiesByComponentsFast(t){return t&&t.entities?t.entities.map((t=>({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:0}))).sort(((t,e)=>e.componentCount-t.componentCount)).slice(0,10):[]}collectArchetypeDataWithMemory(t){if(t&&t.archetypeSystem&&"function"==typeof t.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(t.archetypeSystem);const e={entities:t.entities?.buffer||[]};return{distribution:this.getArchetypeDistributionWithMemory(e),topEntities:this.getTopEntitiesByComponentsWithMemory(e)}}extractArchetypeStatistics(t){const e=t.getAllArchetypes(),n=[],s=[];return e.forEach((t=>{const e=t.componentTypes?.map((t=>t.name)).join(",")||"Unknown",i=t.entities?.length||0;n.push({signature:e,count:i,memory:0}),t.entities&&t.entities.slice(0,5).forEach((t=>{s.push({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:0})}))})),n.sort(((t,e)=>e.count-t.count)),s.sort(((t,e)=>e.componentCount-t.componentCount)),{distribution:n,topEntities:s}}extractArchetypeStatisticsWithMemory(t){const e=t.getAllArchetypes(),n=[],s=[];return e.forEach((t=>{const e=t.componentTypes?.map((t=>t.name)).join(",")||"Unknown",i=t.entities?.length||0;let o=0;if(t.entities&&t.entities.length>0){const e=Math.min(5,t.entities.length);let n=0;for(let s=0;s<e;s++)n+=this.estimateEntityMemoryUsage(t.entities[s]);o=n/e*i}n.push({signature:e,count:i,memory:o}),t.entities&&t.entities.slice(0,5).forEach((t=>{s.push({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:this.estimateEntityMemoryUsage(t)})}))})),n.sort(((t,e)=>e.count-t.count)),s.sort(((t,e)=>e.componentCount-t.componentCount)),{distribution:n,topEntities:s}}getArchetypeDistribution(t){const e=new Map;return t&&t.entities&&t.entities.forEach((t=>{const n=t.componentMask?.toString()||"0",s=e.get(n);e.set(n,(s||0)+1)})),Array.from(e.entries()).map((([t,e])=>({signature:t,count:e,memory:0}))).sort(((t,e)=>e.count-t.count))}getArchetypeDistributionWithMemory(t){const e=new Map;return t&&t.entities&&t.entities.forEach((t=>{const n=t.components?.map((t=>getComponentInstanceTypeName(t)))||[],s=n.length>0?n.sort().join(", "):"无组件",i=e.get(s);let o=this.estimateEntityMemoryUsage(t);(isNaN(o)||o<0)&&(o=0),i?(i.count++,i.memory+=o):e.set(s,{count:1,memory:o,componentTypes:n})})),Array.from(e.entries()).map((([t,e])=>({signature:t,count:e.count,memory:isNaN(e.memory)?0:e.memory}))).sort(((t,e)=>e.count-t.count))}getTopEntitiesByComponents(t){return t&&t.entities?t.entities.map((t=>({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:0}))).sort(((t,e)=>e.componentCount-t.componentCount)):[]}getTopEntitiesByComponentsWithMemory(t){return t&&t.entities?t.entities.map((t=>({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:this.estimateEntityMemoryUsage(t)}))).sort(((t,e)=>e.componentCount-t.componentCount)):[]}getEmptyEntityDebugData(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}calculateFallbackEntityStats(t){const e=t.buffer||[],n=e.filter((t=>t.enabled&&!t._isDestroyed));return{totalEntities:e.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?e.reduce(((t,e)=>t+(e.components?.length||0)),0)/n.length:0}}estimateEntityMemoryUsage(t){try{let e=0;const n=this.calculateObjectSize(t,["components","children","parent"]);return!isNaN(n)&&n>0&&(e+=n),t.components&&Array.isArray(t.components)&&t.components.forEach((t=>{const n=this.calculateObjectSize(t,["entity"]);!isNaN(n)&&n>0&&(e+=n)})),isNaN(e)||e<0?0:e}catch(t){return 0}}calculateObjectSize(t,e=[]){if(!t||"object"!=typeof t)return 0;const n=new WeakSet,s=(t,i=0)=>{if(!t||"object"!=typeof t||i>=2)return 0;if(n.has(t))return 0;n.add(t);let o=32;try{const n=Object.keys(t),r=Math.min(n.length,20);for(let a=0;a<r;a++){const r=n[a];if(e.includes(r)||"constructor"===r||"__proto__"===r||r.startsWith("_cc_")||r.startsWith("__"))continue;const c=t[r];o+=2*r.length,"string"==typeof c?o+=Math.min(2*c.length,200):"number"==typeof c?o+=8:"boolean"==typeof c?o+=4:Array.isArray(c)?o+=40+Math.min(8*c.length,160):"object"==typeof c&&null!==c&&(o+=s(c,i+1))}}catch(t){return 64}return o};try{const e=s(t);return Math.max(e,32)}catch(t){return 64}}buildEntityHierarchyTree(t){if(!t?.buffer)return[];const e=[];return t.buffer.forEach((t=>{if(!t.parent){const n=this.buildEntityHierarchyNode(t);e.push(n)}})),e.sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:t.id-e.id)),e}buildEntityHierarchyNode(t){let e={id:t.id,name:t.name||`Entity_${t.id}`,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:!1!==t.activeInHierarchy,componentCount:t.components.length,componentTypes:t.components.map((t=>getComponentInstanceTypeName(t))),parentId:t.parent?.id||null,children:[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0};if(t.children&&t.children.length>0&&(e.children=t.children.map((t=>this.buildEntityHierarchyNode(t)))),"function"==typeof t.getDebugInfo){const n=t.getDebugInfo();e={...e,...n}}return t.components&&t.components.length>0&&(e.componentDetails=this.extractComponentDetails(t.components)),e}buildEntityDetailsMap(t){if(!t?.buffer)return{};const e={},n=t.buffer;for(let t=0;t<n.length;t+=100){n.slice(t,t+100).forEach((t=>{const n=t.getDebugInfo?t.getDebugInfo():this.buildFallbackEntityInfo(t),s=t.getComponentCacheStats?t.getComponentCacheStats():null,i=this.extractComponentDetails(t.components);e[t.id]={...n,parentName:t.parent?.name||null,components:i,componentTypes:n.componentTypes||i.map((t=>t.typeName)),cachePerformance:s?{hitRate:s.cacheStats.hitRate,size:s.cacheStats.size,maxSize:s.cacheStats.maxSize}:null}}))}return e}buildFallbackEntityInfo(t){const e=Core.scene,n=this.getSceneInfo(e);return{name:t.name||`Entity_${t.id}`,id:t.id,enabled:!1!==t.enabled,active:!1!==t.active,activeInHierarchy:!1!==t.activeInHierarchy,destroyed:t.isDestroyed||!1,scene:n.name,sceneName:n.name,sceneType:n.type,componentCount:t.components.length,componentTypes:t.components.map((t=>getComponentInstanceTypeName(t))),componentMask:t.componentMask?.toString()||"0",parentId:t.parent?.id||null,childCount:t.children?.length||0,childIds:t.children.map((t=>t.id))||[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0}}extractComponentDetails(t){return t.map((t=>{let e=getComponentInstanceTypeName(t);if(!e||"Object"===e||"Function"===e)try{const n=ComponentTypeManager.instance,s=t.constructor,i=n.getTypeId(s);e=n.getTypeName(i)}catch(t){e="UnknownComponent"}const n={};try{Object.keys(t).forEach((e=>{if(!e.startsWith("_")&&"entity"!==e&&"constructor"!==e){const s=t[e];null!=s&&(n[e]=this.formatPropertyValue(s))}})),0===Object.keys(n).length&&(n._info="该组件没有公开属性",n._componentId=getComponentInstanceTypeName(t))}catch(e){n._error="属性提取失败",n._componentId=getComponentInstanceTypeName(t)}return{typeName:e,properties:n}}))}getComponentProperties(t,e){try{const n=Core.scene;if(!n)return{};const s=n.entities;if(!s?.buffer)return{};const i=s.buffer.find((e=>e.id===t));if(!i||e>=i.components.length)return{};const o=i.components[e],r={};return Object.keys(o).forEach((t=>{if(!t.startsWith("_")&&"entity"!==t){const e=o[t];null!=e&&(r[t]=this.formatPropertyValue(e))}})),r}catch(t){return{_error:"属性提取失败"}}}formatPropertyValue(t,e=0){return null==t?t:"object"!=typeof t?"string"==typeof t&&t.length>200?`[长字符串: ${t.length}字符] ${t.substring(0,100)}...`:t:0===e?this.formatObjectFirstLevel(t):this.createLazyLoadPlaceholder(t)}formatObjectFirstLevel(t){try{if(Array.isArray(t)){if(0===t.length)return[];if(t.length>10){const e=t.slice(0,3).map((t=>this.formatPropertyValue(t,1)));return{_isLazyArray:!0,_arrayLength:t.length,_sample:e,_summary:`数组[${t.length}个元素]`}}return t.map((t=>this.formatPropertyValue(t,1)))}const e=Object.keys(t);if(0===e.length)return{};const n={};let s=0;const i=15;for(const o of e){if(s>=i){n._hasMoreProperties=!0,n._totalProperties=e.length,n._hiddenCount=e.length-s;break}if(!o.startsWith("_")&&!o.startsWith("$")&&"function"!=typeof t[o])try{const e=t[o];null!=e&&(n[o]=this.formatPropertyValue(e,1),s++)}catch(t){n[o]=`[访问失败: ${t instanceof Error?t.message:String(t)}]`,s++}}return n}catch(t){return`[对象解析失败: ${t instanceof Error?t.message:String(t)}]`}}createLazyLoadPlaceholder(t){try{const e=t.constructor?.name||"Object";return{_isLazyObject:!0,_typeName:e,_summary:this.getObjectSummary(t,e),_objectId:this.generateObjectId(t)}}catch(t){return{_isLazyObject:!0,_typeName:"Unknown",_summary:`无法分析的对象: ${t instanceof Error?t.message:String(t)}`,_objectId:Math.random().toString(36).substr(2,9)}}}getObjectSummary(t,e){try{if((e.toLowerCase().includes("vec")||e.toLowerCase().includes("vector"))&&void 0!==t.x&&void 0!==t.y){const n=void 0!==t.z?t.z:"";return`${e}(${t.x}, ${t.y}${n?", "+n:""})`}if(e.toLowerCase().includes("color")&&void 0!==t.r&&void 0!==t.g&&void 0!==t.b){const n=void 0!==t.a?t.a:1;return`${e}(${t.r}, ${t.g}, ${t.b}, ${n})`}if(e.toLowerCase().includes("node")){return`${e}: ${t.name||t._name||"未命名"}`}if(e.toLowerCase().includes("component")){const n=t.node?.name||t.node?._name||"";return`${e}${n?` on ${n}`:""}`}const n=Object.keys(t);return 0===n.length?`${e} (空对象)`:`${e} (${n.length}个属性)`}catch(t){return`${e} (无法分析)`}}generateObjectId(t){try{return void 0!==t.id?`obj_${t.id}`:void 0!==t._id?`obj_${t._id}`:void 0!==t.uuid?`obj_${t.uuid}`:void 0!==t._uuid?`obj_${t._uuid}`:`obj_${Math.random().toString(36).substr(2,9)}`}catch{return`obj_${Math.random().toString(36).substr(2,9)}`}}expandLazyObject(t,e,n){try{const s=Core.scene;if(!s)return null;const i=s.entities;if(!i?.buffer)return null;const o=i.buffer.find((e=>e.id===t));if(!o)return null;if(e>=o.components.length)return null;const r=o.components[e],a=this.getObjectByPath(r,n);return a?this.formatObjectFirstLevel(a):null}catch(t){return{error:`展开失败: ${t instanceof Error?t.message:String(t)}`}}}getObjectByPath(t,e){if(!e)return t;const n=e.split(".");let s=t;for(const t of n){if(null==s)return null;if(t.includes("[")&&t.includes("]")){const e=t.substring(0,t.indexOf("[")),n=parseInt(t.substring(t.indexOf("[")+1,t.indexOf("]")));if(e&&(s=s[e]),!(Array.isArray(s)&&n>=0&&n<s.length))return null;s=s[n]}else s=s[t]}return s}}class SystemDataCollector{collectSystemData(t){const e=Core.scene;if(!e)return{totalSystems:0,systemsInfo:[]};const n=e.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};const s=n.processors||[];let i=new Map,o=new Map;if(t)try{i=t.getAllSystemStats(),o=t.getAllSystemData()}catch(t){}return{totalSystems:s.length,systemsInfo:s.map((t=>{const e=t.systemName||getSystemInstanceTypeName(t),n=i.get(e),s=o.get(e);return{name:e,type:getSystemInstanceTypeName(t),entityCount:t.entities?.length||0,executionTime:n?.averageTime||s?.executionTime||0,minExecutionTime:n?.minTime===Number.MAX_VALUE?0:n?.minTime||0,maxExecutionTime:n?.maxTime||0,executionTimeHistory:n?.recentTimes||[],updateOrder:t.updateOrder||0,enabled:!1!==t.enabled,lastUpdateTime:s?.lastUpdateTime||0}}))}}}class PerformanceDataCollector{constructor(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.lastGCCount=0,this.gcCollections=0,this.lastMemoryCheck=0}collectPerformanceData(t){const e=Time.deltaTime,n=1e3*e,s=e>0?Math.round(1/e):0,i=this.getECSPerformanceData(t),o=i.totalExecutionTime,r=n>0?o/n*100:0;let a=0;performance.memory&&(a=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(o),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();const c=this.frameTimeHistory.filter((t=>t>=0));return{frameTime:o,engineFrameTime:n,ecsPercentage:r,memoryUsage:a,fps:s,averageFrameTime:c.length>0?c.reduce(((t,e)=>t+e),0)/c.length:o,minFrameTime:c.length>0?Math.min(...c):o,maxFrameTime:c.length>0?Math.max(...c):o,frameTimeHistory:[...this.frameTimeHistory],systemPerformance:this.getSystemPerformance(t),systemBreakdown:i.systemBreakdown,memoryDetails:this.getMemoryDetails()}}getECSPerformanceData(t){if(!t)try{const e=Core.Instance;if(!e||!e._performanceMonitor)return{totalExecutionTime:0,systemBreakdown:[]};t=e._performanceMonitor}catch(t){return{totalExecutionTime:0,systemBreakdown:[]}}if(!t.enabled){try{t.enabled=!0}catch(t){}return{totalExecutionTime:0,systemBreakdown:[]}}try{let e=0;const n=[],s=t.getAllSystemStats();if(0===s.size)return{totalExecutionTime:0,systemBreakdown:[]};for(const[t,i]of s.entries()){const s=i.recentTimes&&i.recentTimes.length>0?i.recentTimes[i.recentTimes.length-1]:i.averageTime||0;e+=s,n.push({systemName:t,executionTime:s,percentage:0})}return n.forEach((t=>{t.percentage=e>0?t.executionTime/e*100:0})),n.sort(((t,e)=>e.executionTime-t.executionTime)),{totalExecutionTime:e,systemBreakdown:n}}catch(t){return{totalExecutionTime:0,systemBreakdown:[]}}}getSystemPerformance(t){if(!t)return[];try{const e=t.getAllSystemStats(),n=t.getAllSystemData();return Array.from(e.entries()).map((([t,e])=>{const s=n.get(t);return{systemName:t,averageTime:e.averageTime||0,maxTime:e.maxTime||0,minTime:e.minTime===Number.MAX_VALUE?0:e.minTime||0,samples:e.executionCount||0,percentage:0,entityCount:s?.entityCount||0,lastExecutionTime:s?.executionTime||0}}))}catch(t){return[]}}getMemoryDetails(){const t={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){const e=performance.memory;if(t.totalMemory=e.jsHeapSizeLimit||536870912,t.usedMemory=e.usedJSHeapSize||0,t.freeMemory=t.totalMemory-t.usedMemory,this.lastMemoryCheck>0){this.lastMemoryCheck-t.usedMemory>1048576&&this.gcCollections++}this.lastMemoryCheck=t.usedMemory}else t.totalMemory=536870912,t.freeMemory=536870912}catch(t){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return t}updateGCCount(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(t){return this.gcCollections}}}class ComponentDataCollector{collectComponentData(){const t=Core.scene;if(!t)return{componentTypes:0,componentInstances:0,componentStats:[]};const e=t.entities;if(!e?.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};const n=new Map;let s=0;e.buffer.forEach((t=>{t.components&&t.components.forEach((t=>{const e=getComponentInstanceTypeName(t),i=n.get(e)||{count:0,entities:0};i.count++,s++,n.set(e,i)}))}));let i=new Map,o=new Map;try{const t=ComponentPoolManager.getInstance(),e=t.getPoolStats(),n=t.getPoolUtilization();for(const[t,n]of e.entries())o.set(t,n.maxSize);for(const[t,e]of n.entries())i.set(t,e.utilization)}catch(t){}return{componentTypes:n.size,componentInstances:s,componentStats:Array.from(n.entries()).map((([t,n])=>{const s=o.get(t)||0,r=i.get(t)||0,a=this.getEstimatedComponentSize(t);return{typeName:t,instanceCount:n.count,memoryPerInstance:a,totalMemory:n.count*a,poolSize:s,poolUtilization:r,averagePerEntity:n.count/e.buffer.length}}))}}getEstimatedComponentSize(t){if(ComponentDataCollector.componentSizeCache.has(t))return ComponentDataCollector.componentSizeCache.get(t);const e=Core.scene;if(!e)return 64;const n=e.entities;if(!n?.buffer)return 64;let s=64;try{for(const e of n.buffer)if(e.components){const n=e.components.find((e=>getComponentInstanceTypeName(e)===t));if(n){s=this.calculateQuickObjectSize(n);break}}}catch(t){s=64}return ComponentDataCollector.componentSizeCache.set(t,s),s}calculateQuickObjectSize(t){if(!t||"object"!=typeof t)return 8;let e=32;const n=new WeakSet,s=(t,e=0)=>{if(!t||"object"!=typeof t||n.has(t)||e>3)return 0;n.add(t);let i=0;try{const n=Object.keys(t);for(let o=0;o<Math.min(n.length,20);o++){const r=n[o];if("entity"===r||"_entity"===r||"constructor"===r)continue;const a=t[r];i+=2*r.length,"string"==typeof a?i+=Math.min(2*a.length,200):"number"==typeof a?i+=8:"boolean"==typeof a?i+=4:"object"==typeof a&&null!==a&&(i+=s(a,e+1))}}catch(t){return 32}return i};return e+=s(t),Math.max(e,32)}calculateDetailedComponentMemory(t){const e=Core.scene;if(!e)return this.getEstimatedComponentSize(t);const n=e.entities;if(!n?.buffer)return this.getEstimatedComponentSize(t);try{for(const e of n.buffer)if(e.components){const n=e.components.find((e=>getComponentInstanceTypeName(e)===t));if(n)return this.estimateObjectSize(n)}}catch(t){}return this.getEstimatedComponentSize(t)}estimateObjectSize(t,e=new WeakSet,n=0){if(null==t||n>10)return 0;if(e.has(t))return 0;let s=0;switch(typeof t){case"boolean":s=4;break;case"number":default:s=8;break;case"string":s=24+Math.min(2*t.length,1e3);break;case"object":if(e.add(t),Array.isArray(t)){s=40+8*t.length;const i=Math.min(t.length,50);for(let o=0;o<i;o++)s+=this.estimateObjectSize(t[o],e,n+1)}else{s=32;try{const i=Object.getOwnPropertyNames(t),o=Math.min(i.length,30);for(let r=0;r<o;r++){const o=i[r];if("constructor"!==o&&"__proto__"!==o&&"entity"!==o&&"_entity"!==o&&!o.startsWith("_cc_")&&!o.startsWith("__"))try{s+=16+2*o.length;const i=t[o];null!=i&&(s+=this.estimateObjectSize(i,e,n+1))}catch(t){continue}}}catch(t){s=128}}}return 8*Math.ceil(s/8)}static clearCache(){ComponentDataCollector.componentSizeCache.clear()}}ComponentDataCollector.componentSizeCache=new Map;class SceneDataCollector{constructor(){this.sceneStartTime=Date.now()}collectSceneData(){const t=Core.scene;if(!t)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneMemory:0,sceneUptime:0};const e=(Date.now()-this.sceneStartTime)/1e3,n=t.entities,s=t.entityProcessors;return{currentSceneName:t.name||"Unnamed Scene",isInitialized:t._didSceneBegin||!1,sceneRunTime:e,sceneEntityCount:n?.buffer?.length||0,sceneSystemCount:s?.processors?.length||0,sceneMemory:0,sceneUptime:e}}setSceneStartTime(t){this.sceneStartTime=t}}class WebSocketManager{constructor(t,e=!0){this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectInterval=2e3,this.url=t,this.autoReconnect=e}setMessageHandler(t){this.messageHandler=t}connect(){return new Promise(((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=e=>{this.handleOpen(e),t()},this.ws.onclose=t=>{this.handleClose(t)},this.ws.onerror=t=>{this.handleError(t),e(t)},this.ws.onmessage=t=>{this.handleMessage(t)}}catch(t){this.handleConnectionFailure(t),e(t)}}))}disconnect(){this.ws&&(this.autoReconnect=!1,this.ws.close(),this.ws=void 0),this.isConnected=!1}send(t){if(this.isConnected&&this.ws)try{const e="string"==typeof t?t:JSON.stringify(t);this.ws.send(e)}catch(t){}}getConnectionStatus(){return this.isConnected}setMaxReconnectAttempts(t){this.maxReconnectAttempts=t}setReconnectInterval(t){this.reconnectInterval=t}scheduleReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer);const t=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout((()=>{this.connect().catch((t=>{this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}))}),t)}handleMessage(t){try{const e=JSON.parse(t.data);this.messageHandler&&this.messageHandler(e)}catch(t){}}handleOpen(t){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(t)}handleClose(t){this.isConnected=!1,this.onClose&&this.onClose(t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}handleError(t){this.onError&&this.onError(t)}handleConnectionFailure(t){this.onError&&this.onError(t)}}class DebugManager{constructor(t,e){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.config=e,this.entityCollector=new EntityDataCollector,this.systemCollector=new SystemDataCollector,this.performanceCollector=new PerformanceDataCollector,this.componentCollector=new ComponentDataCollector,this.sceneCollector=new SceneDataCollector,this.webSocketManager=new WebSocketManager(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));const n=e.debugFrameRate||30;this.sendInterval=1e3/n,this.start()}start(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())}stop(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())}updateConfig(t){this.config=t;const e=t.debugFrameRate||30;this.sendInterval=1e3/e,this.webSocketManager&&t.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new WebSocketManager(t.websocketUrl,!1!==t.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())}onFrameUpdate(t){if(!this.isRunning||!this.config.enabled)return;this.frameCounter++;const e=Date.now();e-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=e)}onSceneChanged(){this.isRunning&&this.config.enabled&&this.sendDebugData()}handleMessage(t){try{switch(t.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":t.config&&this.updateConfig({...this.config,...t.config});break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(t);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(t);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(t);break;case"get_entity_details":this.handleGetEntityDetailsRequest(t);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(e){t.requestId&&this.webSocketManager.send({type:"error_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleExpandLazyObjectRequest(t){try{const{entityId:e,componentIndex:n,propertyPath:s,requestId:i}=t;if(void 0===e||void 0===n||!s)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,error:"缺少必要参数"});const o=this.entityCollector.expandLazyObject(e,n,s);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,data:o})}catch(e){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleGetComponentPropertiesRequest(t){try{const{entityId:e,componentIndex:n,requestId:s}=t;if(void 0===e||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:s,error:"缺少必要参数"});const i=this.entityCollector.getComponentProperties(e,n);this.webSocketManager.send({type:"get_component_properties_response",requestId:s,data:i})}catch(e){this.webSocketManager.send({type:"get_component_properties_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleGetRawEntityListRequest(t){try{const{requestId:e}=t,n=this.entityCollector.getRawEntityList();this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e,data:n})}catch(e){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleGetEntityDetailsRequest(t){try{const{entityId:e,requestId:n}=t;if(void 0===e)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});const s=this.entityCollector.getEntityDetails(e);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:s})}catch(e){this.webSocketManager.send({type:"get_entity_details_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}handleMemorySnapshotRequest(){try{const t=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:t})}catch(t){this.webSocketManager.send({type:"memory_snapshot_error",error:t instanceof Error?t.message:"内存快照捕获失败"})}}captureMemorySnapshot(){const t=Date.now(),e=this.entityCollector.collectEntityDataWithMemory(),n=this.collectBaseMemoryInfo(),s=Core.scene,i=s?.entities?this.collectComponentMemoryStats(s.entities):{totalMemory:0,componentTypes:0,totalInstances:0,breakdown:[]},o=this.collectSystemMemoryStats(),r=this.collectPoolMemoryStats(),a=this.collectPerformanceStats(),c=e.entitiesPerArchetype.reduce(((t,e)=>t+e.memory),0);return{timestamp:t,version:"2.0",summary:{totalEntities:e.totalEntities,totalMemoryUsage:n.usedMemory,totalMemoryLimit:n.totalMemory,memoryUtilization:n.usedMemory/n.totalMemory*100,gcCollections:n.gcCollections,entityMemory:c,componentMemory:i.totalMemory,systemMemory:o.totalMemory,poolMemory:r.totalMemory},baseMemory:n,entities:{totalMemory:c,entityCount:e.totalEntities,archetypes:e.entitiesPerArchetype,largestEntities:e.topEntitiesByComponents},components:i,systems:o,pools:r,performance:a}}collectBaseMemoryInfo(){const t={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null,detailedMemory:void 0};try{const e=performance;if(e.memory){const n=e.memory;t.totalMemory=n.jsHeapSizeLimit||536870912,t.usedMemory=n.usedJSHeapSize||0,t.freeMemory=t.totalMemory-t.usedMemory,t.heapInfo={totalJSHeapSize:n.totalJSHeapSize||0,usedJSHeapSize:n.usedJSHeapSize||0,jsHeapSizeLimit:n.jsHeapSizeLimit||0}}else t.totalMemory=536870912,t.freeMemory=536870912;e.measureUserAgentSpecificMemory&&e.measureUserAgentSpecificMemory().then((e=>{t.detailedMemory=e})).catch((()=>{}))}catch(t){}return t}collectComponentMemoryStats(t){const e=new Map;let n=0;const s=new Map;for(const e of t.buffer)if(e&&!e.destroyed&&e.components)for(const t of e.components){const e=getComponentInstanceTypeName(t);s.set(e,(s.get(e)||0)+1)}for(const[i,o]of s.entries()){const s=this.componentCollector.calculateDetailedComponentMemory(i),r=s*o;n+=r;const a=[];let c=0;for(const e of t.buffer)if(e&&!e.destroyed&&e.components){for(const t of e.components)if(getComponentInstanceTypeName(t)===i&&(a.push({entityId:e.id,entityName:e.name||`Entity_${e.id}`,memory:s}),c++,c>=100))break;if(c>=100)break}e.set(i,{count:o,totalMemory:r,instances:a.slice(0,10)})}const i=Array.from(e.entries()).map((([t,e])=>({typeName:t,instanceCount:e.count,totalMemory:e.totalMemory,averageMemory:e.totalMemory/e.count,percentage:n>0?e.totalMemory/n*100:0,largestInstances:e.instances.sort(((t,e)=>e.memory-t.memory)).slice(0,3)}))).sort(((t,e)=>e.totalMemory-t.totalMemory));return{totalMemory:n,componentTypes:e.size,totalInstances:Array.from(e.values()).reduce(((t,e)=>t+e.count),0),breakdown:i}}collectSystemMemoryStats(){const t=Core.scene;let e=0;const n=[];try{const s=t?.entityProcessors;if(s&&s.processors){const t=new Map;for(const i of s.processors){const s=getSystemInstanceTypeName(i);let o;t.has(s)?o=t.get(s):(o=this.calculateQuickSystemSize(i),t.set(s,o)),e+=o,n.push({name:s,memory:o,enabled:!1!==i.enabled,updateOrder:i.updateOrder||0})}}}catch(t){}return{totalMemory:e,systemCount:n.length,breakdown:n.sort(((t,e)=>e.memory-t.memory))}}calculateQuickSystemSize(t){if(!t||"object"!=typeof t)return 64;let e=128;try{const n=Object.keys(t);for(let s=0;s<Math.min(n.length,15);s++){const i=n[s];if("entities"===i||"scene"===i||"constructor"===i)continue;const o=t[i];e+=2*i.length,"string"==typeof o?e+=Math.min(2*o.length,100):"number"==typeof o?e+=8:"boolean"==typeof o?e+=4:Array.isArray(o)?e+=40+Math.min(8*o.length,200):"object"==typeof o&&null!==o&&(e+=64)}}catch(t){return 128}return Math.max(e,64)}collectPoolMemoryStats(){let t=0;const e=[];try{const n=ComponentPoolManager.getInstance().getPoolStats();for(const[s,i]of n.entries()){const n=i,o=32*n.maxSize;t+=o,e.push({typeName:s,maxSize:n.maxSize,currentSize:n.currentSize||0,estimatedMemory:o,utilization:n.currentSize?n.currentSize/n.maxSize*100:0})}}catch(t){}try{const n=Pool.getAllPoolStats();for(const[s,i]of Object.entries(n)){const n=i;t+=n.estimatedMemoryUsage,e.push({typeName:`Pool_${s}`,maxSize:n.maxSize,currentSize:n.size,estimatedMemory:n.estimatedMemoryUsage,utilization:n.size/n.maxSize*100,hitRate:100*n.hitRate})}}catch(t){}return{totalMemory:t,poolCount:e.length,breakdown:e.sort(((t,e)=>e.estimatedMemory-t.estimatedMemory))}}collectPerformanceStats(){try{const t=Core.Instance._performanceMonitor;if(!t)return{enabled:!1};const e=t.getAllSystemStats(),n=t.getPerformanceWarnings();return{enabled:t.enabled??!1,systemCount:e.size,warnings:n.slice(0,10),topSystems:Array.from(e.entries()).map((t=>{const[e,n]=t;return{name:e,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort(((t,e)=>e.averageTime-t.averageTime)).slice(0,5)}}catch(t){return{enabled:!1,error:t instanceof Error?t.message:String(t)}}}getDebugData(){const t=Date.now(),e=Core.scene,n={timestamp:t,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:e?.name||"Unknown"};if(this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData()),this.config.channels.systems){const t=Core.Instance._performanceMonitor;n.systems=this.systemCollector.collectSystemData(t)}if(this.config.channels.performance){const t=Core.Instance._performanceMonitor;n.performance=this.performanceCollector.collectPerformanceData(t)}return this.config.channels.components&&(n.components=this.componentCollector.collectComponentData()),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData()),n}async connectWebSocket(){try{await this.webSocketManager.connect()}catch(t){}}sendDebugData(){if(this.webSocketManager.getConnectionStatus())try{const t={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(t)}catch(t){}}}class Core{constructor(t={}){this._globalManagers=[],Core._instance=this,this._config={debug:!0,enableEntitySystems:!0,...t},this._environmentInfo=BigIntFactory.getEnvironmentInfo(),this._timerManager=new TimerManager,Core.registerGlobalManager(this._timerManager),this._performanceMonitor=PerformanceMonitor.instance,this._config.debug&&this._performanceMonitor.enable(),this._poolManager=PoolManager.getInstance(),Core.entitySystemsEnabled=this._config.enableEntitySystems??!0,this.debug=this._config.debug??!0,this._config.debugConfig?.enabled&&(this._debugManager=new DebugManager(this,this._config.debugConfig)),this._config.debug&&this.logCompatibilityInfo(),this.initialize()}static get Instance(){return this._instance}static get scene(){return this.getScene()}static getScene(){if(!this._instance)return null;this._instance.ensureDefaultWorld();const t=this._instance._worldManager.getWorld(this.DEFAULT_WORLD_ID);return t?.getScene(this.DEFAULT_SCENE_ID)||null}static setScene(t){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");this._instance.ensureDefaultWorld();const e=this._instance._worldManager.getWorld(this.DEFAULT_WORLD_ID);return e.getScene(this.DEFAULT_SCENE_ID)&&e.removeScene(this.DEFAULT_SCENE_ID),e.createScene(this.DEFAULT_SCENE_ID,t),e.setSceneActive(this.DEFAULT_SCENE_ID,!0),this._instance.onSceneChanged(),t}static create(t=!0){if(null==this._instance){const e="boolean"==typeof t?{debug:t,enableEntitySystems:!0}:t;this._instance=new Core(e)}return this._instance}static update(t){this._instance?this._instance.updateInternal(t):Core._logger.warn("Core实例未创建,请先调用Core.create()")}static registerGlobalManager(t){this._instance._globalManagers.push(t),t.enabled=!0}static unregisterGlobalManager(t){this._instance._globalManagers.splice(this._instance._globalManagers.indexOf(t),1),t.enabled=!1}static getGlobalManager(t){for(const e of this._instance._globalManagers)if(e instanceof t)return e;return null}static schedule(t,e=!1,n,s){if(!s)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(t,e,n,s)}static get ecsAPI(){return this._instance?._ecsAPI||null}static enableDebug(t){this._instance?(this._instance._debugManager?this._instance._debugManager.updateConfig(t):this._instance._debugManager=new DebugManager(this._instance,t),this._instance._config.debugConfig=t):Core._logger.warn("Core实例未创建,请先调用Core.create()")}static disableDebug(){this._instance&&(this._instance._debugManager&&(this._instance._debugManager.stop(),this._instance._debugManager=void 0),this._instance._config.debugConfig&&(this._instance._config.debugConfig.enabled=!1))}static getDebugData(){return this._instance?._debugManager?this._instance._debugManager.getDebugData():null}static get isDebugEnabled(){return this._instance?._config.debugConfig?.enabled||!1}static getEnvironmentInfo(){return this._instance?._environmentInfo||null}static get supportsBigInt(){return this._instance?._environmentInfo.supportsBigInt||!1}static getWorldManager(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._worldManager||(this._instance._worldManager=WorldManager.getInstance({maxWorlds:50,autoCleanup:!0,cleanupInterval:6e4,debug:this._instance._config.debug})),this._instance._worldManager}static enableWorldManager(){return this.getWorldManager()}ensureDefaultWorld(){this._worldManager||(this._worldManager=WorldManager.getInstance({maxWorlds:1,autoCleanup:!1,cleanupInterval:0,debug:this._config.debug})),this._worldManager.getWorld(Core.DEFAULT_WORLD_ID)||(this._worldManager.createWorld(Core.DEFAULT_WORLD_ID,{name:"DefaultWorld",maxScenes:1,autoCleanup:!1}),this._worldManager.setWorldActive(Core.DEFAULT_WORLD_ID,!0))}onSceneChanged(){Time.sceneChanged();const t=Core.getScene();t&&t.querySystem&&t.eventSystem&&(this._ecsAPI=createECSAPI(t,t.querySystem,t.eventSystem)),this._debugManager&&queueMicrotask((()=>{this._debugManager?.onSceneChanged()}))}initialize(){}logCompatibilityInfo(){const t=this._environmentInfo;Core._logger.info("ECS Framework 兼容性检测结果:"),Core._logger.info(` 环境: ${t.environment}`),Core._logger.info(` JavaScript引擎: ${t.jsEngine}`),Core._logger.info(" BigInt支持: "+(t.supportsBigInt?"支持":"不支持")),t.supportsBigInt||Core._logger.warn("BigInt兼容模式已启用")}updateInternal(t){if(Core.paused)return;const e=this._performanceMonitor.startMonitoring("Core.update");Time.update(t),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(Time.deltaTime);const n=this._performanceMonitor.startMonitoring("GlobalManagers.update");for(const t of this._globalManagers)t.enabled&&t.update();if(this._performanceMonitor.endMonitoring("GlobalManagers.update",n,this._globalManagers.length),this._poolManager.update(),this._worldManager){const t=this._performanceMonitor.startMonitoring("Worlds.update"),e=this._worldManager.getActiveWorlds();let n=0;for(const t of e){t.updateGlobalSystems(),t.updateScenes();n+=t.getStats().totalEntities}this._performanceMonitor.endMonitoring("Worlds.update",t,n)}this._debugManager&&this._debugManager.onFrameUpdate(t),this._performanceMonitor.endMonitoring("Core.update",e)}}Core.paused=!1,Core.DEFAULT_WORLD_ID="__default__",Core.DEFAULT_SCENE_ID="__main__",Core._logger=createLogger("Core");class FuncPack{constructor(t,e){this.func=t,this.context=e}}class Emitter{constructor(){this._messageTable=new Map}addObserver(t,e,n){let s=this._messageTable.get(t);s||(s=[],this._messageTable.set(t,s)),this.hasObserver(t,e)||s.push(new FuncPack(e,n))}removeObserver(t,e){let n=this._messageTable.get(t);if(n){let t=n.findIndex((t=>t.func==e));-1!=t&&n.splice(t,1)}}emit(t,...e){let n=this._messageTable.get(t);if(n)for(let t of n)t.func.call(t.context,...e)}hasObserver(t,e){let n=this._messageTable.get(t);return!!n&&n.some((t=>t.func===e))}removeAllObservers(t){void 0!==t?this._messageTable.delete(t):this._messageTable.clear()}dispose(){this._messageTable.clear()}getEventTypeCount(){return this._messageTable.size}getObserverCount(t){const e=this._messageTable.get(t);return e?e.length:0}}class Component{constructor(){this._enabled=!0,this._updateOrder=0,this.id=Component._idGenerator++}get enabled(){return this.entity?this.entity.enabled&&this._enabled:this._enabled}set enabled(t){this._enabled!==t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}get updateOrder(){return this._updateOrder}set updateOrder(t){this._updateOrder=t}onAddedToEntity(){}onRemovedFromEntity(){}onEnabled(){}onDisabled(){}update(){}}Component._idGenerator=0;class Matcher{constructor(){this.condition={all:[],any:[],none:[]}}static all(...t){return(new Matcher).all(...t)}static any(...t){return(new Matcher).any(...t)}static none(...t){return(new Matcher).none(...t)}static byTag(t){return(new Matcher).withTag(t)}static byName(t){return(new Matcher).withName(t)}static byComponent(t){return(new Matcher).withComponent(t)}static complex(){return new Matcher}static empty(){return new Matcher}all(...t){return this.condition.all.push(...t),this}any(...t){return this.condition.any.push(...t),this}none(...t){return this.condition.none.push(...t),this}exclude(...t){return this.none(...t)}one(...t){return this.any(...t)}withTag(t){return this.condition.tag=t,this}withName(t){return this.condition.name=t,this}withComponent(t){return this.condition.component=t,this}withoutTag(){return delete this.condition.tag,this}withoutName(){return delete this.condition.name,this}withoutComponent(){return delete this.condition.component,this}getCondition(){return{all:[...this.condition.all],any:[...this.condition.any],none:[...this.condition.none],tag:this.condition.tag,name:this.condition.name,component:this.condition.component}}isEmpty(){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}reset(){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}clone(){const t=new Matcher;return t.condition.all.push(...this.condition.all),t.condition.any.push(...this.condition.any),t.condition.none.push(...this.condition.none),void 0!==this.condition.tag&&(t.condition.tag=this.condition.tag),void 0!==this.condition.name&&(t.condition.name=this.condition.name),void 0!==this.condition.component&&(t.condition.component=this.condition.component),t}toString(){const t=[];return this.condition.all.length>0&&t.push(`all(${this.condition.all.map((t=>getComponentTypeName(t))).join(", ")})`),this.condition.any.length>0&&t.push(`any(${this.condition.any.map((t=>getComponentTypeName(t))).join(", ")})`),this.condition.none.length>0&&t.push(`none(${this.condition.none.map((t=>getComponentTypeName(t))).join(", ")})`),void 0!==this.condition.tag&&t.push(`tag(${this.condition.tag})`),void 0!==this.condition.name&&t.push(`name(${this.condition.name})`),void 0!==this.condition.component&&t.push(`component(${getComponentTypeName(this.condition.component)})`),`Matcher[${t.join(" & ")}]`}}class EntitySystem{get entities(){return this.queryEntities()}get updateOrder(){return this._updateOrder}set updateOrder(t){this.setUpdateOrder(t)}get enabled(){return this._enabled}set enabled(t){this._enabled=t}get systemName(){return this._systemName}constructor(t){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=PerformanceMonitor.instance,this._initialized=!1,this._trackedEntities=new Set,this._scene=null,this._matcher=t||Matcher.empty(),this._systemName=getSystemInstanceTypeName(this)}get scene(){return this._scene}set scene(t){this._scene=t}get matcher(){return this._matcher}setUpdateOrder(t){this._updateOrder=t,this.scene&&this.scene.entityProcessors&&this.scene.entityProcessors.setDirty()}initialize(){this._initialized||(this._initialized=!0,this.scene&&this.queryEntities(),this.onInitialize())}onInitialize(){}reset(){this._initialized=!1,this._trackedEntities.clear()}queryEntities(){if(!this.scene?.querySystem||!this._matcher)return[];const t=this._matcher.getCondition(),e=this.scene.querySystem;let n=[];return n=this._matcher.isEmpty()?e.getAllEntities():this.isSingleCondition(t)?this.executeSingleConditionQuery(t,e):this.executeComplexQuery(t,e),this.updateEntityTracking(n),n}isSingleCondition(t){return 1===(t.all.length>0?1:0)+(t.any.length>0?1:0)+(t.none.length>0?1:0)+(void 0!==t.tag?1:0)+(void 0!==t.name?1:0)+(void 0!==t.component?1:0)}executeSingleConditionQuery(t,e){return void 0!==t.tag?e.queryByTag(t.tag).entities:void 0!==t.name?e.queryByName(t.name).entities:void 0!==t.component?e.queryByComponent(t.component).entities:t.all.length>0&&0===t.any.length&&0===t.none.length?e.queryAll(...t.all).entities:0===t.all.length&&t.any.length>0&&0===t.none.length?e.queryAny(...t.any).entities:0===t.all.length&&0===t.any.length&&t.none.length>0?e.queryNone(...t.none).entities:[]}executeComplexQuery(t,e){let n=null;if(void 0!==t.tag){const s=e.queryByTag(t.tag);n=new Set(s.entities)}if(void 0!==t.name){const s=e.queryByName(t.name),i=new Set(s.entities);if(n){const t=[];for(const e of n)for(const n of i)if(e===n||e.id===n.id){t.push(e);break}n=new Set(t)}else n=i}if(void 0!==t.component){const s=e.queryByComponent(t.component),i=new Set(s.entities);if(n){const t=[];for(const e of n)for(const n of i)if(e===n||e.id===n.id){t.push(e);break}n=new Set(t)}else n=i}if(t.all.length>0){const s=e.queryAll(...t.all),i=new Set(s.entities);if(n){const t=[];for(const e of n)for(const n of i)if(e===n||e.id===n.id){t.push(e);break}n=new Set(t)}else n=i}if(t.any.length>0){const s=e.queryAny(...t.any),i=new Set(s.entities);if(n){const t=[];for(const e of n)for(const n of i)if(e===n||e.id===n.id){t.push(e);break}n=new Set(t)}else n=i}if(t.none.length>0){n||(n=new Set(e.getAllEntities()));const s=e.queryAny(...t.none),i=new Set(s.entities),o=[];for(const t of n){let e=!1;for(const n of i)if(t===n||t.id===n.id){e=!0;break}e||o.push(t)}n=new Set(o)}return n?Array.from(n):[]}update(){if(!this._enabled||!this.onCheckProcessing())return;const t=this._performanceMonitor.startMonitoring(this._systemName);let e=0;try{this.onBegin();const t=this.queryEntities();e=t.length,this.process(t)}finally{this._performanceMonitor.endMonitoring(this._systemName,t,e)}}lateUpdate(){if(!this._enabled||!this.onCheckProcessing())return;const t=this._performanceMonitor.startMonitoring(`${this._systemName}_Late`);let e=0;try{const t=this.queryEntities();e=t.length,this.lateProcess(t),this.onEnd()}finally{this._performanceMonitor.endMonitoring(`${this._systemName}_Late`,t,e)}}onBegin(){}process(t){}lateProcess(t){}onEnd(){}onCheckProcessing(){return!0}getPerformanceData(){return this._performanceMonitor.getSystemData(this._systemName)}getPerformanceStats(){return this._performanceMonitor.getSystemStats(this._systemName)}resetPerformanceData(){this._performanceMonitor.resetSystem(this._systemName)}toString(){const t=this.entities.length,e=this.getPerformanceData(),n=e?` (${e.executionTime.toFixed(2)}ms)`:"";return`${this._systemName}[${t} entities]${n}`}updateEntityTracking(t){const e=new Set(t);for(const e of t)this._trackedEntities.has(e)||(this._trackedEntities.add(e),this.onAdded(e));for(const t of this._trackedEntities)e.has(t)||(this._trackedEntities.delete(t),this.onRemoved(t))}onAdded(t){}onRemoved(t){}}class ProcessingSystem extends EntitySystem{constructor(t){super(t)}process(t){this.processSystem()}}class PassiveSystem extends EntitySystem{constructor(t){super(t)}process(t){}}class IntervalSystem extends EntitySystem{constructor(t,e){super(e),this.acc=0,this.intervalRemainder=0,this.interval=t}onCheckProcessing(){return this.acc+=Time.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)}getIntervalDelta(){return this.interval+this.intervalRemainder}}class EntityQueryBuilder{constructor(t){this.entityManager=t,this._allComponents=[],this._anyComponents=[],this._withoutComponents=[],this._withTags=[],this._withoutTags=[],this._activeOnly=!1,this._enabledOnly=!1,this._customPredicates=[]}withAll(...t){return this._allComponents.push(...t),this}withAny(...t){return this._anyComponents.push(...t),this}without(...t){return this._withoutComponents.push(...t),this}withTag(t){return this._withTags.push(t),this}withoutTag(t){return this._withoutTags.push(t),this}active(){return this._activeOnly=!0,this}enabled(){return this._enabledOnly=!0,this}where(t){return this._customPredicates.push(t),this}execute(){let t=[];if(this._allComponents.length>0){const e=this.entityManager.queryWithComponentIndex(this._allComponents,"AND");t=Array.from(e)}else if(this._anyComponents.length>0){const e=this.entityManager.queryWithComponentIndex(this._anyComponents,"OR");t=Array.from(e)}else t=this.entityManager.getAllEntities();return t.filter((t=>this.matchesEntity(t)))}first(){return this.entityManager.getAllEntities().find((t=>this.matchesEntity(t)))||null}count(){return this.entityManager.getAllEntities().filter((t=>this.matchesEntity(t))).length}forEach(t){this.entityManager.getAllEntities().forEach((e=>{this.matchesEntity(e)&&t(e)}))}matchesEntity(t){if(this._activeOnly&&!t.active)return!1;if(this._enabledOnly&&!t.enabled)return!1;if(this._allComponents.length>0)for(const e of this._allComponents)if(!t.hasComponent(e))return!1;if(this._anyComponents.length>0){let e=!1;for(const n of this._anyComponents)if(t.hasComponent(n)){e=!0;break}if(!e)return!1}if(this._withoutComponents.length>0)for(const e of this._withoutComponents)if(t.hasComponent(e))return!1;if(this._withTags.length>0&&!this._withTags.includes(t.tag))return!1;if(this._withoutTags.length>0&&this._withoutTags.includes(t.tag))return!1;if(this._customPredicates.length>0)for(const e of this._customPredicates)if(!e(t))return!1;return!0}}class EntityManager{constructor(){this._entities=new Map,this._entitiesByName=new Map,this._entitiesByTag=new Map,this._destroyedEntities=new Set,this._identifierPool=new IdentifierPool,this._componentIndexManager=new ComponentIndexManager,this._archetypeSystem=new ArchetypeSystem,this._dirtyTrackingSystem=new DirtyTrackingSystem,this._eventBus=new EventBus(!1),Entity.eventBus=this._eventBus,this._eventBus.on("component:added",(t=>{const e=this._entities.get(t.entityId);e&&(this._componentIndexManager.addEntity(e),this._archetypeSystem.addEntity(e))})),this._eventBus.on("component:removed",(t=>{const e=this._entities.get(t.entityId);e&&(this._componentIndexManager.removeEntity(e),this._archetypeSystem.removeEntity(e))}))}get entityCount(){return this._entities.size}get activeEntityCount(){let t=0;for(const e of this._entities.values())e.active&&!e.isDestroyed&&t++;return t}createEntity(t){const e=this._identifierPool.checkOut();t||(t=`Entity_${e}`);const n=new Entity(t,e);return this._entities.set(e,n),this.updateNameIndex(n,!0),this.updateTagIndex(n,!0),n.components.length>0&&(this._componentIndexManager.addEntity(n),this._archetypeSystem.addEntity(n),this._dirtyTrackingSystem.markDirty(n,DirtyFlag.COMPONENT_ADDED)),this._eventBus.emitEntityCreated({timestamp:Date.now(),source:"EntityManager",entityId:n.id,entityName:n.name,entityTag:n.tag?.toString()}),n}createEntitiesBatch(t,e="Entity",n=!1){if(t<=0)return[];const s=[];for(let n=0;n<t;n++){const t=this._identifierPool.checkOut(),n=new Entity(`${e}_${t}`,t);s.push(n),this._entities.set(t,n)}for(const t of s)this.updateNameIndex(t,!0),this.updateTagIndex(t,!0),t.components.length>0&&(this._componentIndexManager.addEntity(t),this._archetypeSystem.addEntity(t),this._dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_ADDED));if(!n){const t=Date.now();for(const e of s)this._eventBus.emitEntityCreated({timestamp:t,source:"EntityManager",entityId:e.id,entityName:e.name,entityTag:e.tag?.toString()})}return s}destroyEntity(t){let e=null;return e="string"==typeof t?this.getEntityByName(t):"number"==typeof t?this._entities.get(t)||null:this._entities.get(t.id)||null,!!e&&(this._destroyedEntities.add(e.id),this.updateNameIndex(e,!1),this.updateTagIndex(e,!1),this._componentIndexManager.removeEntity(e),this._archetypeSystem.removeEntity(e),this._dirtyTrackingSystem.markDirty(e,DirtyFlag.COMPONENT_REMOVED),this._eventBus.emitEntityDestroyed({timestamp:Date.now(),source:"EntityManager",entityId:e.id,entityName:e.name,entityTag:e.tag?.toString()}),e.destroy(),this._entities.delete(e.id),this._identifierPool.checkIn(e.id),!0)}getAllEntities(){return Array.from(this._entities.values())}getEntity(t){const e="string"==typeof t?parseInt(t):t;return this._entities.get(e)||null}getEntityByName(t){const e=this._entitiesByName.get(t);return e&&e.length>0?e[0]:null}getEntitiesByTag(t){return Array.from(this._entities.values()).filter((e=>e.tag===t))}getEntitiesWithComponent(t){const e=this._componentIndexManager.query(t);return Array.from(e)}query(){return new EntityQueryBuilder(this)}queryWithComponentIndex(t,e){return this._componentIndexManager.queryMultiple(t,e)}markEntityDirty(t,e){this._dirtyTrackingSystem.markDirty(t,DirtyFlag.COMPONENT_MODIFIED,e)}getOptimizationStats(){return{componentIndex:this._componentIndexManager.getStats(),archetypeSystem:this._archetypeSystem.getAllArchetypes().map((t=>({id:t.id,componentTypes:t.componentTypes.map((t=>t.name)),entityCount:t.entities.length}))),dirtyTracking:this._dirtyTrackingSystem.getStats()}}get eventBus(){return this._eventBus}updateNameIndex(t,e){if(t.name)if(e){let e=this._entitiesByName.get(t.name);e||(e=[],this._entitiesByName.set(t.name,e)),e.push(t)}else{const e=this._entitiesByName.get(t.name);if(e){const n=e.indexOf(t);-1!==n&&(e.splice(n,1),0===e.length&&this._entitiesByName.delete(t.name))}}}updateTagIndex(t,e){if(e){let e=this._entitiesByTag.get(t.tag);e||(e=[],this._entitiesByTag.set(t.tag,e)),e.push(t)}else{const e=this._entitiesByTag.get(t.tag);if(e){const n=e.indexOf(t);-1!==n&&(e.splice(n,1),0===e.length&&this._entitiesByTag.delete(t.tag))}}}}class TypeUtils{static getType(t){return t.constructor}}class NumberExtension{static toNumber(t){return null==t?0:Number(t)}}export{ArchetypeSystem,AsyncEventHandler,BigIntFactory,Bits,COMPONENT_TYPE_NAME,Component,ComponentDataCollector,ComponentIndex,ComponentIndexManager,ComponentPool,ComponentPoolManager,ComponentRegistry,ComponentSparseSet,ComponentStorage,ComponentTypeManager,ConsoleLogger,Core,DebugManager,DirtyFlag,DirtyTrackingSystem,ECSComponent,ECSEventType,ECSFluentAPI,ECSSystem,EVENT_TYPES,Emitter,EnableSoA,Entity,EntityDataCollector,EntityList,EntityManager,EntityProcessorList,EntityQueryBuilder,EntitySystem,EventBus,EventHandler,EventPriority,EventTypeValidator,Float32,Float64,FuncPack,GlobalEventBus,GlobalManager,HighPrecision,IdentifierPool,Int32,IntervalSystem,LogLevel,Logger,LoggerManager,Matcher,NumberExtension,PassiveSystem,PerformanceDataCollector,PerformanceMonitor,PerformanceWarningType,Pool,PoolManager,ProcessingSystem,QuerySystem,SYSTEM_TYPE_NAME,Scene,SceneDataCollector,SerializeMap,SoAStorage,SparseSet,SystemDataCollector,Time,Timer,TimerManager,TypeSafeEventSystem,TypeUtils,WebSocketManager,World,WorldManager,createECSAPI,createLogger,getComponentInstanceTypeName,getComponentTypeName,getSystemInstanceTypeName,getSystemTypeName,setGlobalLogLevel};
1
+ function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,i=Array(e);n<e;n++)i[n]=t[n];return i}function e(t,e,n,i,r,s,o){try{var a=t[s](o),c=a.value}catch(t){return void n(t)}a.done?e(c):Promise.resolve(c).then(i,r)}function n(t){return function(){var n=this,i=arguments;return new Promise((function(r,s){var o=t.apply(n,i);function a(t){e(o,r,s,a,c,"next",t)}function c(t){e(o,r,s,a,c,"throw",t)}a(void 0)}))}}function i(t,e,n){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,e);var r=new(t.bind.apply(t,i));return n&&f(r,n.prototype),r}function r(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,m(i.key),i)}}function s(t,e,n){return e&&r(t.prototype,e),n&&r(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function o(e,n){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=function(e,n){if(e){if("string"==typeof e)return t(e,n);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(e,n):void 0}}(e))||n){i&&(e=i);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function a(){return a=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},a.apply(null,arguments)}function c(t){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},c(t)}function u(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,f(t,e)}function h(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(h=function(){return!!t})()}function l(){
2
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
3
+ var t,e,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function s(n,i,r,s){var c=i&&i.prototype instanceof a?i:a,u=Object.create(c.prototype);return d(u,"_invoke",function(n,i,r){var s,a,c,u=0,h=r||[],l=!1,d={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return s=e,a=0,c=t,d.n=n,o}};function f(n,i){for(a=n,c=i,e=0;!l&&u&&!r&&e<h.length;e++){var r,s=h[e],f=d.p,m=s[2];n>3?(r=m===i)&&(c=s[(a=s[4])?5:(a=3,3)],s[4]=s[5]=t):s[0]<=f&&((r=n<2&&f<s[1])?(a=0,d.v=i,d.n=s[1]):f<m&&(r=n<3||s[0]>i||i>m)&&(s[4]=n,s[5]=i,d.n=m,a=0))}if(r||n>1)return o;throw l=!0,i}return function(r,h,m){if(u>1)throw TypeError("Generator is already running");for(l&&1===h&&f(h,m),a=h,c=m;(e=a<2?t:c)||!l;){s||(a?a<3?(a>1&&(d.n=-1),f(a,c)):d.n=c:d.v=c);try{if(u=2,s){if(a||(r="next"),e=s[r]){if(!(e=e.call(s,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,a<2&&(a=0)}else 1===a&&(e=s.return)&&e.call(s),a<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),a=1);s=t}else if((e=(l=d.n<0)?c:n.call(i,d))!==o)break}catch(e){s=t,a=1,c=e}finally{u=1}}return{value:e,done:l}}}(n,r,s),!0),u}var o={};function a(){}function c(){}function u(){}e=Object.getPrototypeOf;var h=[][i]?e(e([][i]())):(d(e={},i,(function(){return this})),e),f=u.prototype=a.prototype=Object.create(h);function m(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,u):(t.__proto__=u,d(t,r,"GeneratorFunction")),t.prototype=Object.create(f),t}return c.prototype=u,d(f,"constructor",u),d(u,"constructor",c),c.displayName="GeneratorFunction",d(u,r,"GeneratorFunction"),d(f),d(f,r,"Generator"),d(f,i,(function(){return this})),d(f,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:s,m:m}})()}function d(t,e,n,i){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}d=function(t,e,n,i){function s(e,n){d(t,e,(function(t){return this._invoke(e,n,t)}))}e?r?r(t,e,{value:n,enumerable:!i,configurable:!i,writable:!i}):t[e]=n:(s("next",0),s("throw",1),s("return",2))},d(t,e,n,i)}function f(t,e){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},f(t,e)}function m(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var i=n.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}function p(t){var e="function"==typeof Map?new Map:void 0;return p=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(e){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,n)}function n(){return i(t,arguments,c(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),f(n,t)},p(t)}var y=function(){function t(){this._enabled=!1}var e=t.prototype;return e.setEnabled=function(t){this._enabled!=t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())},e.onEnabled=function(){},e.onDisabled=function(){},e.update=function(){},s(t,[{key:"enabled",get:function(){return this._enabled},set:function(t){this.setEnabled(t)}}])}(),g=function(){function t(){}return t.update=function(t){this.unscaledDeltaTime=t,this.deltaTime=t*this.timeScale,this.unscaledTotalTime+=this.unscaledDeltaTime,this.totalTime+=this.deltaTime,this.frameCount++},t.sceneChanged=function(){this.frameCount=0,this.totalTime=0,this.unscaledTotalTime=0,this.deltaTime=0,this.unscaledDeltaTime=0},t.checkEvery=function(t,e){return this.totalTime-e>=t},t}();g.deltaTime=0,g.unscaledDeltaTime=0,g.totalTime=0,g.unscaledTotalTime=0,g.timeScale=1,g.frameCount=0;var v,_=function(){function t(){this._timeInSeconds=0,this._repeats=!1,this._isDone=!1,this._elapsedTime=0}var e=t.prototype;return e.getContext=function(){return this.context},e.reset=function(){this._elapsedTime=0},e.stop=function(){this._isDone=!0},e.tick=function(){return!this._isDone&&this._elapsedTime>this._timeInSeconds&&(this._elapsedTime-=this._timeInSeconds,this._onTime(this),this._isDone||this._repeats||(this._isDone=!0)),this._elapsedTime+=g.deltaTime,this._isDone},e.initialize=function(t,e,n,i){this._timeInSeconds=t,this._repeats=e,this.context=n,this._onTime=i.bind(n)},e.unload=function(){this.context=null,this._onTime=null},s(t,[{key:"isDone",get:function(){return this._isDone}},{key:"elapsedTime",get:function(){return this._elapsedTime}}])}(),S=function(t){function e(){var e;return(e=t.apply(this,arguments)||this)._timers=[],e}u(e,t);var n=e.prototype;return n.update=function(){for(var t=this._timers.length-1;t>=0;t--)this._timers[t].tick()&&(this._timers[t].unload(),this._timers.splice(t,1))},n.schedule=function(t,e,n,i){var r=new _;return r.initialize(t,e,n,i),this._timers.push(r),r},e}(y);!function(t){t.HIGH_EXECUTION_TIME="high_execution_time",t.HIGH_MEMORY_USAGE="high_memory_usage",t.HIGH_CPU_USAGE="high_cpu_usage",t.FREQUENT_GC="frequent_gc",t.LOW_FPS="low_fps",t.HIGH_ENTITY_COUNT="high_entity_count"}(v||(v={}));var E=function(){function t(){this._systemData=new Map,this._systemStats=new Map,this._warnings=[],this._isEnabled=!1,this._maxRecentSamples=60,this._maxWarnings=100,this._thresholds={executionTime:{warning:16.67,critical:33.33},memoryUsage:{warning:100,critical:200},cpuUsage:{warning:70,critical:90},fps:{warning:45,critical:30},entityCount:{warning:1e3,critical:5e3}},this._fpsHistory=[],this._lastFrameTime=0,this._frameCount=0,this._fpsUpdateInterval=1e3,this._lastFpsUpdate=0,this._currentFps=60,this._memoryCheckInterval=5e3,this._lastMemoryCheck=0,this._memoryHistory=[],this._gcCount=0,this._lastGcCheck=0,this._gcCheckInterval=1e3}var e=t.prototype;return e.enable=function(){this._isEnabled=!0},e.disable=function(){this._isEnabled=!1},e.startMonitoring=function(t){return this._isEnabled?performance.now():0},e.endMonitoring=function(t,e,n){if(void 0===n&&(n=0),this._isEnabled&&0!==e){var i=performance.now(),r=i-e,s={name:t,executionTime:r,entityCount:n,averageTimePerEntity:n>0?r/n:0,lastUpdateTime:i};this._systemData.set(t,s),this.updateStats(t,r)}},e.updateStats=function(t,e){var n=this._systemStats.get(t);n||(n={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(t,n)),n.totalTime+=e,n.executionCount++,n.averageTime=n.totalTime/n.executionCount,n.minTime=Math.min(n.minTime,e),n.maxTime=Math.max(n.maxTime,e),n.recentTimes.push(e),n.recentTimes.length>this._maxRecentSamples&&n.recentTimes.shift(),this.calculateAdvancedStats(n)},e.calculateAdvancedStats=function(t){if(0!==t.recentTimes.length){var e=t.recentTimes.reduce((function(t,e){return t+e}),0)/t.recentTimes.length,n=t.recentTimes.reduce((function(t,n){return t+Math.pow(n-e,2)}),0)/t.recentTimes.length;t.standardDeviation=Math.sqrt(n);var i=[].concat(t.recentTimes).sort((function(t,e){return t-e})),r=i.length;t.percentile95=i[Math.floor(.95*r)]||0,t.percentile99=i[Math.floor(.99*r)]||0}},e.getSystemData=function(t){return this._systemData.get(t)},e.getSystemStats=function(t){return this._systemStats.get(t)},e.getAllSystemData=function(){return new Map(this._systemData)},e.getAllSystemStats=function(){return new Map(this._systemStats)},e.getPerformanceReport=function(){if(!this._isEnabled)return"Performance monitoring is disabled.";var t=[];t.push("=== ECS Performance Report ==="),t.push("");for(var e,n=o(Array.from(this._systemStats.entries()).sort((function(t,e){return e[1].averageTime-t[1].averageTime})));!(e=n()).done;){var i=e.value,r=i[0],s=i[1],a=this._systemData.get(r);t.push("System: "+r),t.push(" Current: "+(null==a?void 0:a.executionTime.toFixed(2))+"ms ("+(null==a?void 0:a.entityCount)+" entities)"),t.push(" Average: "+s.averageTime.toFixed(2)+"ms"),t.push(" Min/Max: "+s.minTime.toFixed(2)+"ms / "+s.maxTime.toFixed(2)+"ms"),t.push(" Total: "+s.totalTime.toFixed(2)+"ms ("+s.executionCount+" calls)"),null!=a&&a.averageTimePerEntity&&a.averageTimePerEntity>0&&t.push(" Per Entity: "+a.averageTimePerEntity.toFixed(4)+"ms"),t.push("")}var c=Array.from(this._systemData.values()).reduce((function(t,e){return t+e.executionTime}),0);return t.push("Total Frame Time: "+c.toFixed(2)+"ms"),t.push("Systems Count: "+this._systemData.size),t.join("\n")},e.reset=function(){this._systemData.clear(),this._systemStats.clear()},e.resetSystem=function(t){this._systemData.delete(t),this._systemStats.delete(t)},e.getPerformanceWarnings=function(t){void 0===t&&(t=16.67);for(var e,n=[],i=o(this._systemData.entries());!(e=i()).done;){var r=e.value,s=r[0],a=r[1];a.executionTime>t&&n.push(s+": "+a.executionTime.toFixed(2)+"ms (>"+t+"ms)")}return n},e.setMaxRecentSamples=function(t){this._maxRecentSamples=t;for(var e,n=o(this._systemStats.values());!(e=n()).done;)for(var i=e.value;i.recentTimes.length>t;)i.recentTimes.shift()},s(t,[{key:"isEnabled",get:function(){return this._isEnabled}}],[{key:"instance",get:function(){return t._instance||(t._instance=new t),t._instance}}])}(),T=function(){function t(t,e,n){void 0===e&&(e=100),void 0===n&&(n=1024),this._objects=[],this._createFn=t,this._maxSize=e,this._objectSize=n,this._stats={size:0,maxSize:e,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}t.getPool=function(e,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this._pools.get(e);return r||(r=new t((function(){return new e}),n,i),this._pools.set(e,r)),r};var e=t.prototype;return e.obtain=function(){if(this._stats.totalObtained++,this._objects.length>0){var t=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),t}return this._stats.totalCreated++,this._updateHitRate(),this._createFn()},e.release=function(t){t&&(this._stats.totalReleased++,this._stats.size<this._maxSize&&(t.reset(),this._objects.push(t),this._stats.size++,this._updateMemoryUsage()))},e.getStats=function(){return a({},this._stats)},e.clear=function(){for(var t,e=o(this._objects);!(t=e()).done;){t.value.reset()}this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()},e.compact=function(t){for(var e=null!=t?t:Math.floor(this._objects.length/2);this._objects.length>e;){var n=this._objects.pop();n&&(n.reset(),this._stats.size--)}this._updateMemoryUsage()},e.prewarm=function(t){for(var e=Math.min(t,this._maxSize-this._objects.length),n=0;n<e;n++){var i=this._createFn();i.reset(),this._objects.push(i),this._stats.totalCreated++,this._stats.size++}this._updateMemoryUsage()},e.setMaxSize=function(t){this._maxSize=t,this._stats.maxSize=t,this._objects.length>t&&this.compact(t)},e.getAvailableCount=function(){return this._objects.length},e.isEmpty=function(){return 0===this._objects.length},e.isFull=function(){return this._objects.length>=this._maxSize},t.getAllPoolTypes=function(){return Array.from(this._pools.keys())},t.getAllPoolStats=function(){for(var t,e={},n=o(this._pools);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];e[r.name||r.toString()]=s.getStats()}return e},t.compactAllPools=function(){for(var t,e=o(this._pools.values());!(t=e()).done;){t.value.compact()}},t.clearAllPools=function(){for(var t,e=o(this._pools.values());!(t=e()).done;){t.value.clear()}this._pools.clear()},t.getGlobalStatsString=function(){var t=this.getAllPoolStats(),e=["=== Object Pool Global Statistics ===",""];if(0===Object.keys(t).length)return e.push("No pools registered"),e.join("\n");for(var n=0,i=Object.entries(t);n<i.length;n++){var r=i[n],s=r[0],o=r[1];e.push(s+":"),e.push(" Size: "+o.size+"/"+o.maxSize),e.push(" Hit Rate: "+(100*o.hitRate).toFixed(1)+"%"),e.push(" Total Created: "+o.totalCreated),e.push(" Total Obtained: "+o.totalObtained),e.push(" Memory: "+(o.estimatedMemoryUsage/1024).toFixed(1)+" KB"),e.push("")}return e.join("\n")},e._updateHitRate=function(){if(0===this._stats.totalObtained)this._stats.hitRate=0;else{var t=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=t/this._stats.totalObtained}},e._updateMemoryUsage=function(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize},t}();T._pools=new Map;var C,b=function(){function t(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}t.getInstance=function(){return t.instance||(t.instance=new t),t.instance};var e=t.prototype;return e.registerPool=function(t,e){this.pools.set(t,e)},e.getPool=function(t){return this.pools.get(t)||null},e.update=function(){var t=Date.now();t-this.lastCompactTime>this.autoCompactInterval&&(this.compactAllPools(),this.lastCompactTime=t)},e.createPool=function(t,e,n,i){void 0===n&&(n=100),void 0===i&&(i=1024);var r=this.pools.get(t);return r||(r=new T(e,n,i),this.pools.set(t,r)),r},e.removePool=function(t){var e=this.pools.get(t);return!!e&&(e.clear(),this.pools.delete(t),!0)},e.getPoolNames=function(){return Array.from(this.pools.keys())},e.getPoolCount=function(){return this.pools.size},e.compactAllPools=function(){for(var t,e=o(this.pools.values());!(t=e()).done;){t.value.compact()}},e.clearAllPools=function(){for(var t,e=o(this.pools.values());!(t=e()).done;){t.value.clear()}},e.getAllStats=function(){for(var t,e=new Map,n=o(this.pools);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];e.set(r,s.getStats())}return e},e.getGlobalStats=function(){for(var t,e=0,n=0,i=0,r=0,s=0,a=0,c=o(this.pools.values());!(t=c()).done;){var u=t.value.getStats();e+=u.size,n+=u.maxSize,i+=u.totalCreated,r+=u.totalObtained,s+=u.totalReleased,a+=u.estimatedMemoryUsage}return{size:e,maxSize:n,totalCreated:i,totalObtained:r,totalReleased:s,hitRate:0===r?0:(r-i)/r,estimatedMemoryUsage:a}},e.getStatsString=function(){var t=["=== Pool Manager Statistics ===",""];if(0===this.pools.size)return t.push("No pools registered"),t.join("\n");var e=this.getGlobalStats();t.push("Total Pools: "+this.pools.size),t.push("Global Hit Rate: "+(100*e.hitRate).toFixed(1)+"%"),t.push("Global Memory Usage: "+(e.estimatedMemoryUsage/1024).toFixed(1)+" KB"),t.push("");for(var n,i=o(this.pools);!(n=i()).done;){var r=n.value,s=r[0],a=r[1].getStats();t.push(s+":"),t.push(" Size: "+a.size+"/"+a.maxSize),t.push(" Hit Rate: "+(100*a.hitRate).toFixed(1)+"%"),t.push(" Memory: "+(a.estimatedMemoryUsage/1024).toFixed(1)+" KB"),t.push("")}return t.join("\n")},e.setAutoCompactInterval=function(t){this.autoCompactInterval=t},e.prewarmAllPools=function(){for(var t,e=o(this.pools.values());!(t=e()).done;){var n=t.value,i=n.getStats(),r=Math.floor(.2*i.maxSize);n.prewarm(r)}},e.reset=function(){this.clearAllPools(),this.pools.clear(),this.lastCompactTime=0},t}(),M=function(){function t(){}return t.create=function(t){if(t<0||t>=64)throw new Error("Bit index "+t+" out of range [0, 63]");return t<32?{lo:1<<t,hi:0}:{lo:0,hi:1<<t-32}},t.fromNumber=function(t){return{lo:t>>>0,hi:0}},t.hasAny=function(t,e){return 0!==(t.lo&e.lo)||0!==(t.hi&e.hi)},t.hasAll=function(t,e){return(t.lo&e.lo)===e.lo&&(t.hi&e.hi)===e.hi},t.hasNone=function(t,e){return 0===(t.lo&e.lo)&&0===(t.hi&e.hi)},t.isZero=function(t){return 0===t.lo&&0===t.hi},t.equals=function(t,e){return t.lo===e.lo&&t.hi===e.hi},t.setBit=function(t,e){if(e<0||e>=64)throw new Error("Bit index "+e+" out of range [0, 63]");e<32?t.lo|=1<<e:t.hi|=1<<e-32},t.clearBit=function(t,e){if(e<0||e>=64)throw new Error("Bit index "+e+" out of range [0, 63]");e<32?t.lo&=~(1<<e):t.hi&=~(1<<e-32)},t.orInPlace=function(t,e){t.lo|=e.lo,t.hi|=e.hi},t.andInPlace=function(t,e){t.lo&=e.lo,t.hi&=e.hi},t.xorInPlace=function(t,e){t.lo^=e.lo,t.hi^=e.hi},t.clear=function(t){t.lo=0,t.hi=0},t.copy=function(t,e){e.lo=t.lo,e.hi=t.hi},t.clone=function(t){return{lo:t.lo,hi:t.hi}},t.toString=function(t,e){if(void 0===e&&(e=2),2===e)return 0===t.hi?t.lo.toString(2):t.hi.toString(2)+t.lo.toString(2).padStart(32,"0");if(16===e)return 0===t.hi?"0x"+t.lo.toString(16).toUpperCase():"0x"+t.hi.toString(16).toUpperCase()+t.lo.toString(16).toUpperCase().padStart(8,"0");throw new Error("Only radix 2 and 16 are supported")},t.popCount=function(t){for(var e=0,n=t.lo,i=t.hi;n;)n&=n-1,e++;for(;i;)i&=i-1,e++;return e},t}();M.ZERO={lo:0,hi:0},function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error",t[t.Fatal=4]="Fatal",t[t.None=5]="None"}(C||(C={}));var w={BLACK:"",RED:"",GREEN:"",YELLOW:"",BLUE:"",MAGENTA:"",CYAN:"",WHITE:"",BRIGHT_BLACK:"",BRIGHT_RED:"",BRIGHT_GREEN:"",BRIGHT_YELLOW:"",BRIGHT_BLUE:"",BRIGHT_MAGENTA:"",BRIGHT_CYAN:"",BRIGHT_WHITE:"",RESET:"",BOLD:"",UNDERLINE:""},I=function(){function t(t){void 0===t&&(t={}),this._config=a({level:C.Info,enableTimestamp:!0,enableColors:"undefined"==typeof window},t)}var e=t.prototype;return e.debug=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Debug,t].concat(n))},e.info=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Info,t].concat(n))},e.warn=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Warn,t].concat(n))},e.error=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Error,t].concat(n))},e.fatal=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.log.apply(this,[C.Fatal,t].concat(n))},e.setLevel=function(t){this._config.level=t},e.setColors=function(t){0===Object.keys(t).length?delete this._config.colors:this._config.colors=a({},this._config.colors,t)},e.setPrefix=function(t){this._config.prefix=t},e.log=function(t,e){if(!(t<this._config.level)){var n=e;if(this._config.enableTimestamp)n="["+(new Date).toISOString()+"] "+n;if(this._config.prefix&&(n="["+this._config.prefix+"] "+n),n="["+C[t].toUpperCase()+"] "+n,this._config.output)this._config.output(t,n);else{for(var i=arguments.length,r=new Array(i>2?i-2:0),s=2;s<i;s++)r[s-2]=arguments[s];this.outputToConsole.apply(this,[t,n].concat(r))}}},e.outputToConsole=function(t,e){for(var n=this._config.enableColors?this.getColors():null,i=arguments.length,r=new Array(i>2?i-2:0),s=2;s<i;s++)r[s-2]=arguments[s];switch(t){case C.Debug:var o,a;if(n)(o=console).debug.apply(o,[""+n.debug+e+n.reset].concat(r));else(a=console).debug.apply(a,[e].concat(r));break;case C.Info:var c,u;if(n)(c=console).info.apply(c,[""+n.info+e+n.reset].concat(r));else(u=console).info.apply(u,[e].concat(r));break;case C.Warn:var h,l;if(n)(h=console).warn.apply(h,[""+n.warn+e+n.reset].concat(r));else(l=console).warn.apply(l,[e].concat(r));break;case C.Error:var d,f;if(n)(d=console).error.apply(d,[""+n.error+e+n.reset].concat(r));else(f=console).error.apply(f,[e].concat(r));break;case C.Fatal:var m,p;if(n)(m=console).error.apply(m,[""+n.fatal+e+n.reset].concat(r));else(p=console).error.apply(p,[e].concat(r))}},e.getColors=function(){return a({},{debug:w.BRIGHT_BLACK,info:w.GREEN,warn:w.YELLOW,error:w.RED,fatal:w.BRIGHT_RED,reset:w.RESET},this._config.colors)},t}(),A=function(){function t(){this._loggers=new Map,this._defaultLogger=new I}t.getInstance=function(){return t._instance||(t._instance=new t),t._instance};var e=t.prototype;return e.getLogger=function(t){if(!t)return this._defaultLogger;if(!this._loggers.has(t)){var e=new I({prefix:t,level:C.Info});this._loggers.set(t,e)}return this._loggers.get(t)},e.setLogger=function(t,e){this._loggers.set(t,e)},e.setGlobalLevel=function(t){this._defaultLogger instanceof I&&this._defaultLogger.setLevel(t);for(var e,n=o(this._loggers.values());!(e=n()).done;){var i=e.value;i instanceof I&&i.setLevel(t)}},e.createChildLogger=function(t,e){var n=t+"."+e;return this.getLogger(n)},e.setGlobalColors=function(t){this._defaultLogger instanceof I&&this._defaultLogger.setColors(t);for(var e,n=o(this._loggers.values());!(e=n()).done;){var i=e.value;i instanceof I&&i.setColors(t)}},e.resetColors=function(){this._defaultLogger instanceof I&&this._defaultLogger.setColors({});for(var t,e=o(this._loggers.values());!(t=e()).done;){var n=t.value;n instanceof I&&n.setColors({})}},t}(),x=A.getInstance().getLogger();function D(t){return A.getInstance().getLogger(t)}function O(t){A.getInstance().setGlobalColors(t)}function k(){A.getInstance().resetColors()}function N(t){A.getInstance().setGlobalLevel(t)}function R(t){return t.__enableSoA=!0,t}function P(t,e){var n=String(e);t.constructor.__highPrecisionFields||(t.constructor.__highPrecisionFields=new Set),t.constructor.__highPrecisionFields.add(n)}function z(t,e){var n=String(e);t.constructor.__float64Fields||(t.constructor.__float64Fields=new Set),t.constructor.__float64Fields.add(n)}function B(t,e){var n=String(e);t.constructor.__float32Fields||(t.constructor.__float32Fields=new Set),t.constructor.__float32Fields.add(n)}function F(t,e){var n=String(e);t.constructor.__int32Fields||(t.constructor.__int32Fields=new Set),t.constructor.__int32Fields.add(n)}function q(t,e){var n=String(e);t.constructor.__serializeMapFields||(t.constructor.__serializeMapFields=new Set),t.constructor.__serializeMapFields.add(n)}var L=function(){function t(t){this.fields=new Map,this.stringFields=new Map,this.serializedFields=new Map,this.complexFields=new Map,this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this._capacity=1e3,this.type=t,this.initializeFields(t)}var e=t.prototype;return e.initializeFields=function(t){var e=new t,n=t.__highPrecisionFields||new Set,i=t.__float64Fields||new Set,r=t.__float32Fields||new Set,s=t.__int32Fields||new Set,o=t.__serializeMapFields||new Set,a=t.__serializeSetFields||new Set,c=t.__serializeArrayFields||new Set;for(var u in e)if(e.hasOwnProperty(u)&&"id"!==u){var h=e[u],l=typeof h;"number"===l?n.has(u)||(i.has(u)?this.fields.set(u,new Float64Array(this._capacity)):s.has(u)?this.fields.set(u,new Int32Array(this._capacity)):(r.has(u),this.fields.set(u,new Float32Array(this._capacity)))):"boolean"===l?this.fields.set(u,new Float32Array(this._capacity)):"string"===l?this.stringFields.set(u,new Array(this._capacity)):"object"===l&&null!==h&&(o.has(u)||a.has(u)||c.has(u))&&this.serializedFields.set(u,new Array(this._capacity))}},e.addComponent=function(t,e){if(this.entityToIndex.has(t)){var n=this.entityToIndex.get(t);this.updateComponentAtIndex(n,e)}else{var i;this.freeIndices.length>0?i=this.freeIndices.pop():(i=this._size)>=this._capacity&&this.resize(2*this._capacity),this.entityToIndex.set(t,i),this.indexToEntity[i]=t,this.updateComponentAtIndex(i,e),this._size++}},e.updateComponentAtIndex=function(t,e){var n=this.indexToEntity[t],i=new Map,r=this.type.__highPrecisionFields||new Set,s=this.type.__serializeMapFields||new Set,o=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=this.type.__deepCopyFields||new Set;for(var u in e)if(e.hasOwnProperty(u)&&"id"!==u){var h=e[u],l=typeof h;if("number"===l)if(r.has(u)||!this.fields.has(u))i.set(u,h);else this.fields.get(u)[t]=h;else if("boolean"===l&&this.fields.has(u)){this.fields.get(u)[t]=h?1:0}else if(this.stringFields.has(u)){this.stringFields.get(u)[t]=String(h)}else if(this.serializedFields.has(u)){this.serializedFields.get(u)[t]=this.serializeValue(h,u,s,o,a)}else c.has(u)?i.set(u,this.deepClone(h)):i.set(u,h)}i.size>0&&this.complexFields.set(n,i)},e.serializeValue=function(e,n,i,r,s){try{return i.has(n)&&e instanceof Map?JSON.stringify(Array.from(e.entries())):r.has(n)&&e instanceof Set?JSON.stringify(Array.from(e)):(s.has(n)&&Array.isArray(e),JSON.stringify(e))}catch(e){return t._logger.warn("SoA序列化字段 "+n+" 失败:",e),"{}"}},e.deserializeValue=function(e,n,i,r,s){try{var o=JSON.parse(e);return i.has(n)?new Map(o):r.has(n)?new Set(o):(s.has(n),o)}catch(e){return t._logger.warn("SoA反序列化字段 "+n+" 失败:",e),null}},e.deepClone=function(t){var e=this;if(null===t||"object"!=typeof t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array)return t.map((function(t){return e.deepClone(t)}));if(t instanceof Map){for(var n,i=new Map,r=o(t.entries());!(n=r()).done;){var s=n.value,a=s[0],c=s[1];i.set(a,this.deepClone(c))}return i}if(t instanceof Set){for(var u,h=new Set,l=o(t.values());!(u=l()).done;){var d=u.value;h.add(this.deepClone(d))}return h}var f={};for(var m in t)t.hasOwnProperty(m)&&(f[m]=this.deepClone(t[m]));return f},e.getComponent=function(t){var e=this.entityToIndex.get(t);if(void 0===e)return null;for(var n,i=new this.type,r=this.type.__serializeMapFields||new Set,s=this.type.__serializeSetFields||new Set,a=this.type.__serializeArrayFields||new Set,c=o(this.fields.entries());!(n=c()).done;){var u=n.value,h=u[0],l=u[1][e],d=this.getFieldType(h);i[h]="boolean"===d?1===l:l}for(var f,m=o(this.stringFields.entries());!(f=m()).done;){var p=f.value,y=p[0],g=p[1];i[y]=g[e]}for(var v,_=o(this.serializedFields.entries());!(v=_()).done;){var S=v.value,E=S[0],T=S[1][e];T&&(i[E]=this.deserializeValue(T,E,r,s,a))}var C=this.complexFields.get(t);if(C)for(var b,M=o(C.entries());!(b=M()).done;){var w=b.value,I=w[0],A=w[1];i[I]=A}return i},e.getFieldType=function(t){return typeof(new this.type)[t]},e.hasComponent=function(t){return this.entityToIndex.has(t)},e.removeComponent=function(t){var e=this.entityToIndex.get(t);if(void 0===e)return null;var n=this.getComponent(t);return this.complexFields.delete(t),this.entityToIndex.delete(t),this.freeIndices.push(e),this._size--,n},e.resize=function(t){for(var e,n=o(this.fields.entries());!(e=n()).done;){var i=e.value,r=i[0],s=i[1],a=void 0;(a=s instanceof Float32Array?new Float32Array(t):s instanceof Float64Array?new Float64Array(t):new Int32Array(t)).set(s),this.fields.set(r,a)}for(var c,u=o(this.stringFields.entries());!(c=u()).done;){for(var h=c.value,l=h[0],d=h[1],f=new Array(t),m=0;m<d.length;m++)f[m]=d[m];this.stringFields.set(l,f)}for(var p,y=o(this.serializedFields.entries());!(p=y()).done;){for(var g=p.value,v=g[0],_=g[1],S=new Array(t),E=0;E<_.length;E++)S[E]=_[E];this.serializedFields.set(v,S)}this._capacity=t},e.getActiveIndices=function(){return Array.from(this.entityToIndex.values())},e.getFieldArray=function(t){return this.fields.get(t)||null},e.getTypedFieldArray=function(t){return this.fields.get(String(t))||null},e.getEntityIndex=function(t){return this.entityToIndex.get(t)},e.getEntityIdByIndex=function(t){return this.indexToEntity[t]},e.size=function(){return this._size},e.clear=function(){this.entityToIndex.clear(),this.indexToEntity=[],this.freeIndices=[],this.complexFields.clear(),this._size=0;for(var t,e=o(this.fields.values());!(t=e()).done;){t.value.fill(0)}for(var n,i=o(this.stringFields.values());!(n=i()).done;)for(var r=n.value,s=0;s<r.length;s++)r[s]=void 0;for(var a,c=o(this.serializedFields.values());!(a=c()).done;)for(var u=a.value,h=0;h<u.length;h++)u[h]=void 0},e.compact=function(){if(0!==this.freeIndices.length){for(var t=Array.from(this.entityToIndex.entries()).sort((function(t,e){return t[1]-e[1]})),e=new Map,n=[],i=0;i<t.length;i++){var r=t[i],s=r[0],a=r[1];if(e.set(s,i),n[i]=s,i!==a){for(var c,u=o(this.fields.entries());!(c=u()).done;){var h=c.value[1];h[i]=h[a]}for(var l,d=o(this.stringFields.entries());!(l=d()).done;){var f=l.value[1];f[i]=f[a]}for(var m,p=o(this.serializedFields.entries());!(m=p()).done;){var y=m.value[1];y[i]=y[a]}}}this.entityToIndex=e,this.indexToEntity=n,this.freeIndices=[],this._size=t.length}},e.getStats=function(){for(var t,e=0,n=new Map,i=o(this.fields.entries());!(t=i()).done;){var r=t.value,s=r[0],a=r[1],c=void 0,u=void 0;a instanceof Float32Array?(c=4,u="float32"):a instanceof Float64Array?(c=8,u="float64"):(c=4,u="int32");var h=a.length*c;e+=h,n.set(s,{size:this._size,capacity:a.length,type:u,memory:h})}return{size:this._size,capacity:this._capacity,usedSlots:this._size,fragmentation:this.freeIndices.length/this._capacity,memoryUsage:e,fieldStats:n}},e.performVectorizedOperation=function(t){var e=this.getActiveIndices();t(this.fields,e)},t}();L._logger=D("SoAStorage");var W=Symbol("ComponentTypeName"),U=Symbol("SystemTypeName");function j(t){return function(e){if(!t||"string"!=typeof t)throw new Error("ECSComponent装饰器必须提供有效的类型名称");return e[W]=t,e}}function H(t){return function(e){if(!t||"string"!=typeof t)throw new Error("ECSSystem装饰器必须提供有效的类型名称");return e[U]=t,e}}function G(t){var e=t[W];return e||(t.name||"UnknownComponent")}function Y(t){var e=t[U];return e||(t.name||"UnknownSystem")}function Q(t){return G(t.constructor)}function V(t){return Y(t.constructor)}var X=function(){function t(){}return t.register=function(t){var e=G(t);if(this.componentTypes.has(t))return this.componentTypes.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error("Maximum number of component types ("+this.maxComponents+") exceeded");var n=this.nextBitIndex++;return this.componentTypes.set(t,n),this.componentNameToType.set(e,t),this.componentNameToId.set(e,n),n},t.getBitMask=function(t){var e=this.componentTypes.get(t);if(void 0===e){var n=G(t);throw new Error("Component type "+n+" is not registered")}return M.create(e)},t.getBitIndex=function(t){var e=this.componentTypes.get(t);if(void 0===e){var n=G(t);throw new Error("Component type "+n+" is not registered")}return e},t.isRegistered=function(t){return this.componentTypes.has(t)},t.getComponentType=function(t){return this.componentNameToType.get(t)||null},t.getAllRegisteredTypes=function(){return new Map(this.componentTypes)},t.getAllComponentNames=function(){return new Map(this.componentNameToType)},t.getComponentId=function(t){return this.componentNameToId.get(t)},t.registerComponentByName=function(t){if(this.componentNameToId.has(t))return this.componentNameToId.get(t);if(this.nextBitIndex>=this.maxComponents)throw new Error("Maximum number of component types ("+this.maxComponents+") exceeded");var e=this.nextBitIndex++;return this.componentNameToId.set(t,e),e},t.createSingleComponentMask=function(t){var e="single:"+t;if(this.maskCache.has(e))return this.maskCache.get(e);var n=this.getComponentId(t);if(void 0===n)throw new Error("Component type "+t+" is not registered");var i=M.create(n);return this.maskCache.set(e,i),i},t.createComponentMask=function(t){var e="multi:"+[].concat(t).sort().join(",");if(this.maskCache.has(e))return this.maskCache.get(e);for(var n,i=M.clone(M.ZERO),r=o(t);!(n=r()).done;){var s=n.value,a=this.getComponentId(s);if(void 0!==a){var c=M.create(a);M.orInPlace(i,c)}}return this.maskCache.set(e,i),i},t.clearMaskCache=function(){this.maskCache.clear()},t.reset=function(){this.componentTypes.clear(),this.componentNameToType.clear(),this.componentNameToId.clear(),this.maskCache.clear(),this.nextBitIndex=0},t}();X._logger=D("ComponentStorage"),X.componentTypes=new Map,X.componentNameToType=new Map,X.componentNameToId=new Map,X.maskCache=new Map,X.nextBitIndex=0,X.maxComponents=64;var Z=function(){function t(t){this.dense=[],this.entityIds=[],this.entityToIndex=new Map,this.componentType=t,X.isRegistered(t)||X.register(t)}var e=t.prototype;return e.addComponent=function(t,e){if(this.entityToIndex.has(t))throw new Error("Entity "+t+" already has component "+G(this.componentType));var n=this.dense.length;this.dense.push(e),this.entityIds.push(t),this.entityToIndex.set(t,n)},e.getComponent=function(t){var e=this.entityToIndex.get(t);return void 0!==e?this.dense[e]:null},e.hasComponent=function(t){return this.entityToIndex.has(t)},e.removeComponent=function(t){var e=this.entityToIndex.get(t);if(void 0===e)return null;var n=this.dense[e],i=this.dense.length-1;if(e!==i){var r=this.dense[i],s=this.entityIds[i];this.dense[e]=r,this.entityIds[e]=s,this.entityToIndex.set(s,e)}return this.dense.pop(),this.entityIds.pop(),this.entityToIndex.delete(t),n},e.forEach=function(t){for(var e=0;e<this.dense.length;e++)t(this.dense[e],this.entityIds[e],e)},e.getDenseArray=function(){return{components:[].concat(this.dense),entityIds:[].concat(this.entityIds)}},e.clear=function(){this.dense.length=0,this.entityIds.length=0,this.entityToIndex.clear()},e.getStats=function(){return{totalSlots:this.dense.length,usedSlots:this.dense.length,freeSlots:0,fragmentation:0}},s(t,[{key:"size",get:function(){return this.dense.length}},{key:"type",get:function(){return this.componentType}}])}(),J=function(){function t(){this.storages=new Map}var e=t.prototype;return e.isSoAStorage=function(t){return this.storages.get(t)instanceof L},e.getSoAStorage=function(t){var e=this.getStorage(t);return e instanceof L?e:null},e.getFieldArray=function(t,e){var n=this.getSoAStorage(t);return n?n.getFieldArray(e):null},e.getTypedFieldArray=function(t,e){var n=this.getSoAStorage(t);return n?n.getTypedFieldArray(e):null},e.getActiveIndices=function(t){var e=this.getSoAStorage(t);return e?e.getActiveIndices():[]},e.getEntityIndex=function(t,e){var n=this.getSoAStorage(t);return n?n.getEntityIndex(e):void 0},e.getEntityIdByIndex=function(t,e){var n=this.getSoAStorage(t);return n?n.getEntityIdByIndex(e):void 0},e.getStorage=function(e){var n=this.storages.get(e);n||(e.__enableSoA?(n=new L(e),t._logger.info("为 "+G(e)+" 启用SoA优化(适用于大规模批量操作)")):n=new Z(e),this.storages.set(e,n));return n},e.addComponent=function(t,e){var n=e.constructor;this.getStorage(n).addComponent(t,e)},e.getComponent=function(t,e){var n=this.storages.get(e);return n?n.getComponent(t):null},e.hasComponent=function(t,e){var n=this.storages.get(e);return!!n&&n.hasComponent(t)},e.removeComponent=function(t,e){var n=this.storages.get(e);return n?n.removeComponent(t):null},e.removeAllComponents=function(t){for(var e,n=o(this.storages.values());!(e=n()).done;){e.value.removeComponent(t)}},e.getComponentMask=function(t){for(var e,n=M.clone(M.ZERO),i=o(this.storages.entries());!(e=i()).done;){var r=e.value,s=r[0];if(r[1].hasComponent(t)){var a=X.getBitMask(s);M.orInPlace(n,a)}}return n},e.getAllStats=function(){for(var t,e=new Map,n=o(this.storages.entries());!(t=n()).done;){var i=t.value,r=i[0],s=i[1],a=G(r);e.set(a,s.getStats())}return e},e.clear=function(){for(var t,e=o(this.storages.values());!(t=e()).done;){t.value.clear()}this.storages.clear()},t}();J._logger=D("ComponentStorage");var K=function(){function t(){}return t.prototype.compare=function(t,e){var n=t.updateOrder-e.updateOrder;return 0==n&&(n=t.id-e.id),n},t}(),$=function(){function t(t,e){this.components=[],this.scene=null,this.updateInterval=1,this._isDestroyed=!1,this._parent=null,this._children=[],this._active=!0,this._tag=0,this._enabled=!0,this._updateOrder=0,this._componentMask=M.clone(M.ZERO),this._componentsByTypeId=[],this._componentDenseIndexByTypeId=[],this.name=t,this.id=e}var e=t.prototype;return e.createComponent=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];var s=i(t,n);return this.addComponent(s)},e.addComponentInternal=function(t){var e=t.constructor;X.isRegistered(e)||X.register(e);var n=X.getBitIndex(e);t.entity=this,this._componentsByTypeId[n]=t;var i=this.components.length;this._componentDenseIndexByTypeId[n]=i,this.components.push(t);var r=X.getBitMask(e);return M.orInPlace(this._componentMask,r),t},e.addComponent=function(e){var n,i=e.constructor;if(this.hasComponent(i))throw new Error("Entity "+this.name+" already has component "+G(i));(this.addComponentInternal(e),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.addComponent(this.id,e),e.onAddedToEntity(),t.eventBus)&&t.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(n=this.tag)||void 0===n?void 0:n.toString(),componentType:G(i),component:e});return this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this)),e},e.getComponent=function(t){if(!X.isRegistered(t))return null;var e=X.getBitMask(t);if(M.hasNone(this._componentMask,e))return null;var n=X.getBitIndex(t),i=this._componentsByTypeId[n];if(i&&i.constructor===t)return i;if(this.scene&&this.scene.componentStorageManager){var r=this.scene.componentStorageManager.getComponent(this.id,t);if(r){if(this._componentsByTypeId[n]=r,!this.components.includes(r)){var s=this.components.length;this._componentDenseIndexByTypeId[n]=s,this.components.push(r)}return r}}for(var o=0;o<this.components.length;o++){var a=this.components[o];if(a instanceof t)return this._componentsByTypeId[n]=a,this._componentDenseIndexByTypeId[n]=o,a}return null},e.hasComponent=function(t){if(!X.isRegistered(t))return!1;var e=X.getBitMask(t);return M.hasAny(this._componentMask,e)},e.getOrCreateComponent=function(t){var e=this.getComponent(t);if(!e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];e=this.createComponent.apply(this,[t].concat(i))}return e},e.removeComponent=function(e){var n=e.constructor;if(X.isRegistered(n)){var i=X.getBitIndex(n);this._componentsByTypeId[i]=void 0,M.clearBit(this._componentMask,i);var r,s=this._componentDenseIndexByTypeId[i];if(void 0!==s&&s<this.components.length){var o=this.components.length-1;if(s!==o){var a=this.components[o];this.components[s]=a;var c=a.constructor,u=X.getBitIndex(c);this._componentDenseIndexByTypeId[u]=s}this.components.pop()}if(this._componentDenseIndexByTypeId[i]=-1,this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,n),e.onRemovedFromEntity&&e.onRemovedFromEntity(),t.eventBus)t.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:null===(r=this.tag)||void 0===r?void 0:r.toString(),componentType:G(n),component:e});e.entity=null,this.scene&&this.scene.querySystem&&(this.scene.querySystem.removeEntity(this),this.scene.querySystem.addEntity(this))}},e.removeComponentByType=function(t){var e=this.getComponent(t);return e?(this.removeComponent(e),e):null},e.removeAllComponents=function(){var t=[].concat(this.components);this._componentsByTypeId.length=0,this._componentDenseIndexByTypeId.length=0,M.clear(this._componentMask);for(var e,n=o(t);!(e=n()).done;){var i=e.value,r=i.constructor;this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,r),i.onRemovedFromEntity(),i.entity=null}this.components.length=0},e.addComponents=function(e){for(var n,i=[],r=o(e);!(n=r()).done;){var s=n.value;try{i.push(this.addComponent(s))}catch(e){t._logger.warn("添加组件失败 "+Q(s)+":",e)}}return i},e.removeComponentsByTypes=function(t){for(var e,n=[],i=o(t);!(e=i()).done;){var r=e.value;n.push(this.removeComponentByType(r))}return n},e.getComponents=function(t){for(var e,n=[],i=o(this.components);!(e=i()).done;){var r=e.value;r instanceof t&&n.push(r)}return n},e.addChild=function(t){if(t===this)throw new Error("Entity cannot be its own child");return t._parent===this||(t._parent&&t._parent.removeChild(t),t._parent=this,this._children.push(t),!t.scene&&this.scene&&(t.scene=this.scene,this.scene.addEntity(t))),t},e.removeChild=function(t){var e=this._children.indexOf(t);return-1!==e&&(this._children.splice(e,1),t._parent=null,!0)},e.removeAllChildren=function(){for(var t,e=o([].concat(this._children));!(t=e()).done;){var n=t.value;this.removeChild(n)}},e.findChild=function(t,e){void 0===e&&(e=!1);for(var n,i=o(this._children);!(n=i()).done;){var r=n.value;if(r.name===t)return r}if(e)for(var s,a=o(this._children);!(s=a()).done;){var c=s.value.findChild(t,!0);if(c)return c}return null},e.findChildrenByTag=function(t,e){void 0===e&&(e=!1);for(var n,i=[],r=o(this._children);!(n=r()).done;){var s=n.value;s.tag===t&&i.push(s)}if(e)for(var a,c=o(this._children);!(a=c()).done;){var u=a.value;i.push.apply(i,u.findChildrenByTag(t,!0))}return i},e.getRoot=function(){for(var t=this;t._parent;)t=t._parent;return t},e.isAncestorOf=function(t){for(var e=t._parent;e;){if(e===this)return!0;e=e._parent}return!1},e.isDescendantOf=function(t){return t.isAncestorOf(this)},e.getDepth=function(){for(var t=0,e=this._parent;e;)t++,e=e._parent;return t},e.forEachChild=function(t,e){void 0===e&&(e=!1),this._children.forEach((function(n,i){t(n,i),e&&n.forEachChild(t,!0)}))},e.onActiveChanged=function(){for(var t,e=o(this.components);!(t=e()).done;){var n=t.value;"onActiveChanged"in n&&"function"==typeof n.onActiveChanged&&n.onActiveChanged()}this.scene&&this.scene.eventSystem&&this.scene.eventSystem.emitSync("entity:activeChanged",{entity:this,active:this._active,activeInHierarchy:this.activeInHierarchy})},e.update=function(){if(this.activeInHierarchy&&!this._isDestroyed){for(var t,e=o(this.components);!(t=e()).done;){var n=t.value;n.enabled&&n.update()}for(var i,r=o(this._children);!(i=r()).done;){i.value.update()}}},e.destroy=function(){if(!this._isDestroyed){this._isDestroyed=!0;for(var t,e=o([].concat(this._children));!(t=e()).done;){t.value.destroy()}this._parent&&this._parent.removeChild(this),this.removeAllComponents(),this.scene&&(this.scene.querySystem&&this.scene.querySystem.removeEntity(this),this.scene.entities&&this.scene.entities.remove(this))}},e.compareTo=function(t){return K.prototype.compare(this,t)},e.toString=function(){return"Entity["+this.name+":"+this.id+"]"},e.getDebugInfo=function(){var t;return{name:this.name,id:this.id,enabled:this._enabled,active:this._active,activeInHierarchy:this.activeInHierarchy,destroyed:this._isDestroyed,componentCount:this.components.length,componentTypes:this.components.map((function(t){return Q(t)})),componentMask:M.toString(this._componentMask,2),parentId:(null===(t=this._parent)||void 0===t?void 0:t.id)||null,childCount:this._children.length,childIds:this._children.map((function(t){return t.id})),depth:this.getDepth(),indexMappingSize:this._componentsByTypeId.filter((function(t){return void 0!==t})).length,denseIndexMappingSize:this._componentDenseIndexByTypeId.filter((function(t){return-1!==t&&void 0!==t})).length}},s(t,[{key:"isDestroyed",get:function(){return this._isDestroyed}},{key:"parent",get:function(){return this._parent}},{key:"children",get:function(){return[].concat(this._children)}},{key:"childCount",get:function(){return this._children.length}},{key:"active",get:function(){return this._active},set:function(t){this._active!==t&&(this._active=t,this.onActiveChanged())}},{key:"activeInHierarchy",get:function(){return!!this._active&&(!this._parent||this._parent.activeInHierarchy)}},{key:"tag",get:function(){return this._tag},set:function(t){this._tag=t}},{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled=t}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(t){this._updateOrder=t}},{key:"componentMask",get:function(){return this._componentMask}}])}();$._logger=D("Entity"),$.entityComparer=new K,$.eventBus=null;var tt=function(){function t(t,e){this.scene=t,this.storageManager=e,this.entity=new $("",t.identifierPool.checkOut())}var e=t.prototype;return e.named=function(t){return this.entity.name=t,this},e.tagged=function(t){return this.entity.tag=t,this},e.with=function(t){return this.entity.addComponent(t),this},e.withComponents=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var i=0,r=e;i<r.length;i++){var s=r[i];this.entity.addComponent(s)}return this},e.withIf=function(t,e){return t&&this.entity.addComponent(e),this},e.withFactory=function(t){var e=t();return this.entity.addComponent(e),this},e.configure=function(t,e){var n=this.entity.getComponent(t);return n&&e(n),this},e.enabled=function(t){return void 0===t&&(t=!0),this.entity.enabled=t,this},e.active=function(t){return void 0===t&&(t=!0),this.entity.active=t,this},e.withChild=function(t){var e=t.build();return this.entity.addChild(e),this},e.withChildren=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var i=0,r=e;i<r.length;i++){var s=r[i].build();this.entity.addChild(s)}return this},e.withChildFactory=function(t){var e=t(this.entity).build();return this.entity.addChild(e),this},e.withChildIf=function(t,e){if(t){var n=e.build();this.entity.addChild(n)}return this},e.build=function(){return this.entity},e.spawn=function(){return this.scene.addEntity(this.entity),this.entity},e.clone=function(){var e=new t(this.scene,this.storageManager);return e.entity=this.entity,e},t}(),et=function(){function t(t){this.buffer=[],this._idToEntity=new Map,this._nameToEntities=new Map,this._entitiesToAdd=[],this._entitiesToRemove=[],this._isUpdating=!1,this._scene=t}var e=t.prototype;return e.add=function(t){this._isUpdating?this._entitiesToAdd.push(t):this.addImmediate(t)},e.addImmediate=function(t){this._idToEntity.has(t.id)||(this.buffer.push(t),this._idToEntity.set(t.id,t),this.updateNameIndex(t,!0))},e.remove=function(t){this._isUpdating?this._entitiesToRemove.push(t):this.removeImmediate(t)},e.removeImmediate=function(t){var e=this.buffer.indexOf(t);-1!==e&&(this.buffer.splice(e,1),this._idToEntity.delete(t.id),this.updateNameIndex(t,!1),this._scene&&this._scene.identifierPool&&this._scene.identifierPool.checkIn(t.id))},e.removeAllEntities=function(){for(var t=[],e=this.buffer.length-1;e>=0;e--)t.push(this.buffer[e].id),this.buffer[e].destroy();if(this._scene&&this._scene.identifierPool)for(var n,i=o(t);!(n=i()).done;){var r=n.value;this._scene.identifierPool.checkIn(r)}this.buffer.length=0,this._idToEntity.clear(),this._nameToEntities.clear(),this._entitiesToAdd.length=0,this._entitiesToRemove.length=0},e.updateLists=function(){if(this._entitiesToAdd.length>0){for(var t,e=o(this._entitiesToAdd);!(t=e()).done;){var n=t.value;this.addImmediate(n)}this._entitiesToAdd.length=0}if(this._entitiesToRemove.length>0){for(var i,r=o(this._entitiesToRemove);!(i=r()).done;){var s=i.value;this.removeImmediate(s)}this._entitiesToRemove.length=0}},e.update=function(){this._isUpdating=!0;try{for(var t=0;t<this.buffer.length;t++){var e=this.buffer[t];e.enabled&&!e.isDestroyed&&e.update()}}finally{this._isUpdating=!1}this.updateLists()},e.findEntity=function(t){var e=this._nameToEntities.get(t);return e&&e.length>0?e[0]:null},e.findEntitiesByName=function(t){return this._nameToEntities.get(t)||[]},e.findEntityById=function(t){return this._idToEntity.get(t)||null},e.findEntitiesByTag=function(t){for(var e,n=[],i=o(this.buffer);!(e=i()).done;){var r=e.value;r.tag===t&&n.push(r)}return n},e.findEntitiesWithComponent=function(t){for(var e,n=[],i=o(this.buffer);!(e=i()).done;){var r=e.value;r.hasComponent(t)&&n.push(r)}return n},e.forEach=function(t){for(var e,n=o(this.buffer);!(e=n()).done;){t(e.value)}},e.forEachWhere=function(t,e){for(var n,i=o(this.buffer);!(n=i()).done;){var r=n.value;t(r)&&e(r)}},e.updateNameIndex=function(t,e){if(t.name)if(e){var n=this._nameToEntities.get(t.name);n||(n=[],this._nameToEntities.set(t.name,n)),n.push(t)}else{var i=this._nameToEntities.get(t.name);if(i){var r=i.indexOf(t);-1!==r&&(i.splice(r,1),0===i.length&&this._nameToEntities.delete(t.name))}}},e.getStats=function(){for(var t,e=0,n=o(this.buffer);!(t=n()).done;){var i=t.value;i.enabled&&!i.isDestroyed&&e++}return{totalEntities:this.buffer.length,activeEntities:e,pendingAdd:this._entitiesToAdd.length,pendingRemove:this._entitiesToRemove.length,nameIndexSize:this._nameToEntities.size}},s(t,[{key:"count",get:function(){return this.buffer.length}}])}(),nt=function(){function t(){this._processors=[],this._isDirty=!1}var e=t.prototype;return e.setDirty=function(){this._isDirty=!0},e.add=function(t){this._processors.push(t),this.setDirty()},e.remove=function(t){var e=this._processors.indexOf(t);-1!==e&&this._processors.splice(e,1)},e.getProcessor=function(t){for(var e,n=o(this._processors);!(e=n()).done;){var i=e.value;if(i instanceof t)return i}return null},e.begin=function(){this.sortProcessors()},e.end=function(){},e.update=function(){this.sortProcessors();for(var e,n=o(this._processors);!(e=n()).done;){var i=e.value;try{i.update()}catch(e){t._logger.error("Error in processor "+V(i)+":",e)}}},e.lateUpdate=function(){for(var t,e=o(this._processors);!(t=e()).done;){t.value.lateUpdate()}},e.sortProcessors=function(){this._isDirty&&(this._processors.sort((function(t,e){return t.updateOrder-e.updateOrder})),this._isDirty=!1)},s(t,[{key:"processors",get:function(){return this._processors}},{key:"count",get:function(){return this._processors.length}}])}();nt._logger=D("EntityProcessorList");var it=function(){function t(t,e){void 0===t&&(t=100),void 0===e&&(e=1024),this._nextAvailableIndex=0,this._freeIndices=[],this._generations=new Map,this._pendingRecycle=[],this._recycleDelay=100,this._stats={totalAllocated:0,totalRecycled:0,currentActive:0,memoryExpansions:0},this._recycleDelay=t,this._expansionBlockSize=e,this._preAllocateGenerations(0,this._expansionBlockSize)}var e=t.prototype;return e.checkOut=function(){var e;if(this._processDelayedRecycle(),this._freeIndices.length>0)e=this._freeIndices.pop();else{if(this._nextAvailableIndex>t.MAX_INDEX)throw new Error("实体索引已达到框架设计限制 ("+t.MAX_INDEX+")。这意味着您已经分配了超过65535个不同的实体索引。这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。");e=this._nextAvailableIndex++,this._ensureGenerationCapacity(e)}var n=this._generations.get(e)||1;return this._stats.totalAllocated++,this._stats.currentActive++,this._packId(e,n)},e.checkIn=function(t){var e=this._unpackIndex(t),n=this._unpackGeneration(t);return!!this._isValidId(e,n)&&(!this._pendingRecycle.some((function(t){return t.index===e&&t.generation===n}))&&(this._pendingRecycle.push({index:e,generation:n,timestamp:Date.now()}),this._stats.currentActive--,this._stats.totalRecycled++,!0))},e.isValid=function(t){var e=this._unpackIndex(t),n=this._unpackGeneration(t);return this._isValidId(e,n)},e.getStats=function(){for(var e,n=0,i=0,r=o(this._generations);!(e=r()).done;){var s=e.value,a=s[0],c=s[1];a<this._nextAvailableIndex&&(n+=c,i++)}var u=i>0?n/i:1;return{totalAllocated:this._stats.totalAllocated,totalRecycled:this._stats.totalRecycled,currentActive:this._stats.currentActive,currentlyFree:this._freeIndices.length,pendingRecycle:this._pendingRecycle.length,maxPossibleEntities:t.MAX_INDEX+1,maxUsedIndex:this._nextAvailableIndex-1,memoryUsage:this._calculateMemoryUsage(),memoryExpansions:this._stats.memoryExpansions,averageGeneration:Math.round(100*u)/100,generationStorageSize:this._generations.size}},e.forceProcessDelayedRecycle=function(){this._processDelayedRecycle(!0)},e._processDelayedRecycle=function(e){if(void 0===e&&(e=!1),0!==this._pendingRecycle.length){for(var n,i=Date.now(),r=[],s=[],a=o(this._pendingRecycle);!(n=a()).done;){var c=n.value;e||i-c.timestamp>=this._recycleDelay?r.push(c):s.push(c)}for(var u=0,h=r;u<h.length;u++){var l=h[u];if(this._isValidId(l.index,l.generation)){var d=l.generation+1;d>t.MAX_GENERATION&&(d=1),this._generations.set(l.index,d),this._freeIndices.push(l.index)}}this._pendingRecycle=s}},e._preAllocateGenerations=function(e,n){for(var i=0;i<n;i++){var r=e+i;r<=t.MAX_INDEX&&this._generations.set(r,1)}this._stats.memoryExpansions++},e._ensureGenerationCapacity=function(t){if(!this._generations.has(t)){var e=Math.floor(t/this._expansionBlockSize)*this._expansionBlockSize;this._preAllocateGenerations(e,this._expansionBlockSize)}},e._calculateMemoryUsage=function(){return 16*this._generations.size+8*this._freeIndices.length+32*this._pendingRecycle.length},e._packId=function(t,e){return e<<16|t},e._unpackIndex=function(t){return 65535&t},e._unpackGeneration=function(t){return t>>>16&65535},e._isValidId=function(t,e){if(t<0||t>=this._nextAvailableIndex)return!1;var n=this._generations.get(t);return void 0!==n&&n===e},t}();it.MAX_INDEX=65535,it.MAX_GENERATION=65535;var rt=function(){function t(t,e,n){void 0===n&&(n=1e3),this.pool=[],this.createFn=t,this.resetFn=e,this.maxSize=n}var e=t.prototype;return e.acquire=function(){return this.pool.length>0?this.pool.pop():this.createFn()},e.release=function(t){this.pool.length<this.maxSize&&(this.resetFn&&this.resetFn(t),this.pool.push(t))},e.prewarm=function(t){for(var e=0;e<t&&this.pool.length<this.maxSize;e++)this.pool.push(this.createFn())},e.clear=function(){this.pool.length=0},e.getAvailableCount=function(){return this.pool.length},e.getMaxSize=function(){return this.maxSize},t}(),st=function(){function t(){this.pools=new Map}t.getInstance=function(){return t.instance||(t.instance=new t),t.instance};var e=t.prototype;return e.registerPool=function(t,e,n,i){this.pools.set(t,new rt(e,n,i))},e.acquireComponent=function(t){var e=this.pools.get(t);return e?e.acquire():null},e.releaseComponent=function(t,e){var n=this.pools.get(t);n&&n.release(e)},e.prewarmAll=function(t){void 0===t&&(t=100);for(var e,n=o(this.pools.values());!(e=n()).done;){e.value.prewarm(t)}},e.clearAll=function(){for(var t,e=o(this.pools.values());!(t=e()).done;){t.value.clear()}},e.reset=function(){this.pools.clear()},e.getPoolStats=function(){for(var t,e=new Map,n=o(this.pools);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];e.set(r,{available:s.getAvailableCount(),maxSize:s.getMaxSize()})}return e},e.getPoolUtilization=function(){for(var t,e=new Map,n=o(this.pools);!(t=n()).done;){var i=t.value,r=i[0],s=i[1],a=s.getAvailableCount(),c=s.getMaxSize(),u=c-a,h=c>0?u/c*100:0;e.set(r,{used:u,total:c,utilization:h})}return e},e.getComponentUtilization=function(t){var e=this.pools.get(t);if(!e)return 0;var n=e.getAvailableCount(),i=e.getMaxSize();return i>0?(i-n)/i*100:0},t}(),ot=function(){function t(){this._dense=[],this._sparse=new Map}var e=t.prototype;return e.add=function(t){if(this._sparse.has(t))return!1;var e=this._dense.length;return this._dense.push(t),this._sparse.set(t,e),!0},e.remove=function(t){var e=this._sparse.get(t);if(void 0===e)return!1;var n=this._dense.length-1;if(e!==n){var i=this._dense[n];this._dense[e]=i,this._sparse.set(i,e)}return this._dense.pop(),this._sparse.delete(t),!0},e.has=function(t){return this._sparse.has(t)},e.getIndex=function(t){return this._sparse.get(t)},e.getByIndex=function(t){return this._dense[t]},e.forEach=function(t){for(var e=0;e<this._dense.length;e++)t(this._dense[e],e)},e.map=function(t){for(var e=[],n=0;n<this._dense.length;n++)e.push(t(this._dense[n],n));return e},e.filter=function(t){for(var e=[],n=0;n<this._dense.length;n++)t(this._dense[n],n)&&e.push(this._dense[n]);return e},e.find=function(t){for(var e=0;e<this._dense.length;e++)if(t(this._dense[e],e))return this._dense[e]},e.some=function(t){for(var e=0;e<this._dense.length;e++)if(t(this._dense[e],e))return!0;return!1},e.every=function(t){for(var e=0;e<this._dense.length;e++)if(!t(this._dense[e],e))return!1;return!0},e.getDenseArray=function(){return[].concat(this._dense)},e.getDenseArrayUnsafe=function(){return this._dense},e.clear=function(){this._dense.length=0,this._sparse.clear()},e.toArray=function(){return[].concat(this._dense)},e.toSet=function(){return new Set(this._dense)},e.getMemoryStats=function(){var t=8*this._dense.length,e=16*this._sparse.size;return{denseArraySize:t,sparseMapSize:e,totalMemory:t+e}},e.validate=function(){if(this._dense.length!==this._sparse.size)return!1;for(var t=0;t<this._dense.length;t++){var e=this._dense[t];if(this._sparse.get(e)!==t)return!1}for(var n,i=o(this._sparse);!(n=i()).done;){var r=n.value,s=r[0],a=r[1];if(a>=this._dense.length||this._dense[a]!==s)return!1}return!0},s(t,[{key:"size",get:function(){return this._dense.length}},{key:"isEmpty",get:function(){return 0===this._dense.length}}])}(),at=function(t){function e(){return t.call(this)||this}return u(e,t),e.prototype.reset=function(){this.clear()},e}(p(Set)),ct=function(){function t(){this._componentMasks=[],this._componentToEntities=new Map,this._entities=new ot}var e=t.prototype;return e.addEntity=function(t){this._entities.has(t)&&this.removeEntity(t);for(var e,n=M.clone(M.ZERO),i=new Set,r=o(t.components);!(e=r()).done;){var s=e.value.constructor;i.add(s),X.isRegistered(s)||X.register(s);var a=X.getBitMask(s);M.orInPlace(n,a)}this._entities.add(t);for(var c=this._entities.getIndex(t);this._componentMasks.length<=c;)this._componentMasks.push(M.clone(M.ZERO));this._componentMasks[c]=n,this.updateComponentMappings(t,i,!0)},e.removeEntity=function(t){var e=this._entities.getIndex(t);if(void 0!==e){var n=this.getEntityComponentTypes(t);this.updateComponentMappings(t,n,!1),this._entities.remove(t);var i=this._componentMasks.length-1;e!==i&&(this._componentMasks[e]=this._componentMasks[i]),this._componentMasks.pop()}},e.queryByComponent=function(t){var e=this._componentToEntities.get(t);return e?new Set(e):new Set},e.queryMultipleAnd=function(e){var n=this;if(0===e.length)return new Set;if(1===e.length)return this.queryByComponent(e[0]);for(var i,r=M.clone(M.ZERO),s=o(e);!(i=s()).done;){var a=i.value;if(!X.isRegistered(a))return new Set;var c=X.getBitMask(a);M.orInPlace(r,c)}var u=t._entitySetPool.obtain();return this._entities.forEach((function(t,e){var i=n._componentMasks[e];M.hasAll(i,r)&&u.add(t)})),u},e.queryMultipleOr=function(e){var n=this;if(0===e.length)return new Set;if(1===e.length)return this.queryByComponent(e[0]);for(var i,r=M.clone(M.ZERO),s=o(e);!(i=s()).done;){var a=i.value;if(X.isRegistered(a)){var c=X.getBitMask(a);M.orInPlace(r,c)}}if(M.equals(r,M.ZERO))return new Set;var u=t._entitySetPool.obtain();return this._entities.forEach((function(t,e){var i=n._componentMasks[e];M.hasAny(i,r)&&u.add(t)})),u},e.hasComponent=function(t,e){var n=this._entities.getIndex(t);if(void 0===n)return!1;if(!X.isRegistered(e))return!1;var i=this._componentMasks[n],r=X.getBitMask(e);return M.hasAny(i,r)},e.getEntityMask=function(t){var e=this._entities.getIndex(t);if(void 0!==e)return this._componentMasks[e]},e.getAllEntities=function(){return this._entities.toArray()},e.forEach=function(t){var e=this;this._entities.forEach((function(n,i){t(n,e._componentMasks[i],i)}))},e.clear=function(){this._entities.clear(),this._componentMasks.length=0;for(var e,n=o(this._componentToEntities.values());!(e=n()).done;){var i=e.value;t._entitySetPool.release(i)}this._componentToEntities.clear()},e.getMemoryStats=function(){for(var t,e=this._entities.getMemoryStats(),n=16*this._componentMasks.length,i=16*this._componentToEntities.size,r=o(this._componentToEntities.values());!(t=r()).done;){i+=8*t.value.size}return{entitiesMemory:e.totalMemory,masksMemory:n,mappingsMemory:i,totalMemory:e.totalMemory+n+i}},e.validate=function(){if(!this._entities.validate())return!1;if(this._componentMasks.length!==this._entities.size)return!1;for(var t,e=new Set,n=o(this._componentToEntities.values());!(t=n()).done;)for(var i,r=o(t.value);!(i=r()).done;){var s=i.value;e.add(s)}for(var a,c=o(e);!(a=c()).done;){var u=a.value;if(!this._entities.has(u))return!1}return!0},e.getEntityComponentTypes=function(t){for(var e,n=new Set,i=o(t.components);!(e=i()).done;){var r=e.value;n.add(r.constructor)}return n},e.updateComponentMappings=function(e,n,i){for(var r,s=o(n);!(r=s()).done;){var a=r.value,c=this._componentToEntities.get(a);i?(c||(c=t._entitySetPool.obtain(),this._componentToEntities.set(a,c)),c.add(e)):c&&(c.delete(e),0===c.size&&(this._componentToEntities.delete(a),t._entitySetPool.release(c)))}},s(t,[{key:"size",get:function(){return this._entities.size}},{key:"isEmpty",get:function(){return this._entities.isEmpty}}])}();ct._entitySetPool=T.getPool(at,50,512);var ut,ht=function(){function t(){this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now(),this._sparseSet=new ct}var e=t.prototype;return e.addEntity=function(t){this._sparseSet.addEntity(t),this._lastUpdated=Date.now()},e.removeEntity=function(t){this._sparseSet.removeEntity(t),this._lastUpdated=Date.now()},e.query=function(t){var e=performance.now(),n=this._sparseSet.queryByComponent(t);return this._queryCount++,this._totalQueryTime+=performance.now()-e,n},e.queryMultiple=function(t,e){var n,i=performance.now();return n=0===t.length?new Set:1===t.length?this.query(t[0]):"AND"===e?this._sparseSet.queryMultipleAnd(t):this._sparseSet.queryMultipleOr(t),this._queryCount++,this._totalQueryTime+=performance.now()-i,n},e.clear=function(){this._sparseSet.clear(),this._lastUpdated=Date.now()},e.getStats=function(){var t=this._sparseSet.getMemoryStats();return{size:this._sparseSet.size,memoryUsage:t.totalMemory,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}},t}(),lt=function(){function t(){this._index=new ht}var e=t.prototype;return e.addEntity=function(t){this._index.addEntity(t)},e.removeEntity=function(t){this._index.removeEntity(t)},e.query=function(t){return this._index.query(t)},e.queryMultiple=function(t,e){return this._index.queryMultiple(t,e)},e.getStats=function(){return this._index.getStats()},e.clear=function(){this._index.clear()},t}(),dt=function(){function t(){this._archetypes=new Map,this._entityToArchetype=new Map,this._componentToArchetypes=new Map,this._queryCache=new Map,this._cacheTimeout=5e3,this._maxCacheSize=100}var e=t.prototype;return e.addEntity=function(t){var e=this.getEntityComponentTypes(t),n=this.generateArchetypeId(e),i=this._archetypes.get(n);i||(i=this.createArchetype(e)),i.entities.push(t),i.updatedAt=Date.now(),this._entityToArchetype.set(t,i),this.updateComponentIndexes(i,e,!0),this.invalidateQueryCache()},e.removeEntity=function(t){var e=this._entityToArchetype.get(t);if(e){var n=e.entities.indexOf(t);-1!==n&&(e.entities.splice(n,1),e.updatedAt=Date.now()),this._entityToArchetype.delete(t),this.invalidateQueryCache()}},e.queryArchetypes=function(t,e){void 0===e&&(e="AND");var n=performance.now(),i=e+":"+t.map((function(t){return G(t)})).sort().join(","),r=this._queryCache.get(i);if(r&&Date.now()-r.timestamp<this._cacheTimeout)return a({},r.result,{executionTime:performance.now()-n,fromCache:!0});var s=[],c=0;if("AND"===e)for(var u,h=o(this._archetypes.values());!(u=h()).done;){var l=u.value;this.archetypeContainsAllComponents(l,t)&&(s.push(l),c+=l.entities.length)}else{for(var d,f=new Set,m=o(t);!(d=m()).done;){var p=d.value,y=this._componentToArchetypes.get(p);if(y)for(var g,v=o(y);!(g=v()).done;){var _=g.value;f.add(_)}}for(var S,E=o(f);!(S=E()).done;){var T=S.value;s.push(T),c+=T.entities.length}}var C={archetypes:s,totalEntities:c,executionTime:performance.now()-n,fromCache:!1};return this._queryCache.set(i,{result:C,timestamp:Date.now()}),C},e.getEntityArchetype=function(t){return this._entityToArchetype.get(t)},e.getAllArchetypes=function(){return Array.from(this._archetypes.values())},e.clear=function(){this._archetypes.clear(),this._entityToArchetype.clear(),this._componentToArchetypes.clear(),this._queryCache.clear()},e.getEntityComponentTypes=function(t){return t.components.map((function(t){return t.constructor}))},e.generateArchetypeId=function(t){return t.map((function(t){return G(t)})).sort().join("|")},e.createArchetype=function(t){var e=this.generateArchetypeId(t),n={id:e,componentTypes:[].concat(t),entities:[],createdAt:Date.now(),updatedAt:Date.now()};return this._archetypes.set(e,n),n},e.archetypeContainsAllComponents=function(t,e){for(var n,i=o(e);!(n=i()).done;){var r=n.value;if(!t.componentTypes.includes(r))return!1}return!0},e.updateComponentIndexes=function(t,e,n){for(var i,r=o(e);!(i=r()).done;){var s=i.value,a=this._componentToArchetypes.get(s);a||(a=new Set,this._componentToArchetypes.set(s,a)),n?a.add(t):(a.delete(t),0===a.size&&this._componentToArchetypes.delete(s))}},e.invalidateQueryCache=function(){this._queryCache.clear()},t}();!function(t){t[t.COMPONENT_MODIFIED=1]="COMPONENT_MODIFIED",t[t.COMPONENT_ADDED=2]="COMPONENT_ADDED",t[t.COMPONENT_REMOVED=4]="COMPONENT_REMOVED",t[t.TRANSFORM_CHANGED=8]="TRANSFORM_CHANGED",t[t.STATE_CHANGED=16]="STATE_CHANGED",t[t.CUSTOM_1=256]="CUSTOM_1",t[t.CUSTOM_2=512]="CUSTOM_2",t[t.CUSTOM_3=1024]="CUSTOM_3",t[t.ALL=4294967295]="ALL"}(ut||(ut={}));var ft,mt=function(){function t(){this._dirtyEntities=new Map,this._listeners=[],this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0},this._currentFrame=0,this._batchSize=100,this._maxProcessingTime=16,this._processingQueue=[],this._isProcessing=!1}var e=t.prototype;return e.markDirty=function(t,e,n){void 0===n&&(n=[]),this._stats.totalMarkings++;var i=this._dirtyEntities.get(t);i||(i={entity:t,flags:0,modifiedComponents:new Set,timestamp:performance.now(),frameNumber:this._currentFrame},this._dirtyEntities.set(t,i)),i.flags|=e,i.timestamp=performance.now(),i.frameNumber=this._currentFrame;for(var r,s=o(n);!(r=s()).done;){var a=r.value;i.modifiedComponents.add(a)}this.notifyListeners(i,e)},e.isDirty=function(t,e){void 0===e&&(e=ut.ALL);var n=this._dirtyEntities.get(t);return!!n&&0!==(n.flags&e)},e.clearDirty=function(t,e){void 0===e&&(e=ut.ALL);var n=this._dirtyEntities.get(t);n&&(e===ut.ALL?this._dirtyEntities.delete(t):(n.flags&=~e,0===n.flags&&this._dirtyEntities.delete(t)),this._stats.totalCleanups++)},e.getDirtyEntities=function(t){void 0===t&&(t=ut.ALL);for(var e,n=[],i=o(this._dirtyEntities.values());!(e=i()).done;){var r=e.value;0!==(r.flags&t)&&n.push(r)}return n},e.processDirtyEntities=function(){if(!this._isProcessing){this._isProcessing=!0;var t,e=performance.now();if(0===this._processingQueue.length)(t=this._processingQueue).push.apply(t,this._dirtyEntities.values());for(var n=0;this._processingQueue.length>0&&n<this._batchSize;){if(performance.now()-e>this._maxProcessingTime)break;var i=this._processingQueue.shift();this.processEntity(i),n++}0===this._processingQueue.length&&(this._isProcessing=!1,this.onFrameEnd())}},e.addListener=function(t){this._listeners.push(t),this._listeners.sort((function(t,e){return(t.priority||100)-(e.priority||100)}))},e.removeListener=function(t){var e=this._listeners.findIndex((function(e){return e.callback===t}));-1!==e&&this._listeners.splice(e,1)},e.beginFrame=function(){this._currentFrame++},e.endFrame=function(){this._isProcessing||this.processDirtyEntities()},e.getStats=function(){return{dirtyEntityCount:this._dirtyEntities.size,totalMarkings:this._stats.totalMarkings,totalCleanups:this._stats.totalCleanups,listenerCount:this._listeners.length,avgDirtyPerFrame:this._stats.frameCount>0?this._stats.totalDirtyPerFrame/this._stats.frameCount:0,estimatedMemoryUsage:this.estimateMemoryUsage()}},e.clear=function(){this._dirtyEntities.clear(),this._processingQueue.length=0,this._isProcessing=!1,this._stats={totalMarkings:0,totalCleanups:0,frameCount:0,totalDirtyPerFrame:0}},e.configureBatchProcessing=function(t,e){this._batchSize=t,this._maxProcessingTime=e},e.processEntity=function(e){for(var n,i=o(this._listeners);!(n=i()).done;){var r=n.value;if(0!==(e.flags&r.flags))try{r.callback(e)}catch(e){t._logger.error("脏数据监听器错误:",e)}}this.clearDirty(e.entity)},e.notifyListeners=function(e,n){for(var i,r=o(this._listeners);!(i=r()).done;){var s=i.value;if(0!==(n&s.flags))try{s.callback(e)}catch(e){t._logger.error("脏数据监听器通知错误:",e)}}},e.onFrameEnd=function(){this._stats.frameCount++,this._stats.totalDirtyPerFrame+=this._dirtyEntities.size},e.estimateMemoryUsage=function(){var t=0;return t+=100*this._dirtyEntities.size,t+=50*this._listeners.length,t+=8*this._processingQueue.length},t}();mt._logger=D("DirtyTrackingSystem"),function(t){t.ALL="all",t.ANY="any",t.NONE="none"}(ft||(ft={}));var pt,yt,gt=function(){function t(){this._logger=D("QuerySystem"),this.entities=[],this.indexDirty=!0,this._version=0,this.queryCache=new Map,this.cacheMaxSize=1e3,this.cacheTimeout=5e3,this.queryStats={totalQueries:0,cacheHits:0,indexHits:0,linearScans:0,archetypeHits:0,dirtyChecks:0},this.entityIndex={byMask:new Map,byComponentType:new Map,byTag:new Map,byName:new Map},this.componentPoolManager=st.getInstance(),this.componentIndexManager=new lt,this.archetypeSystem=new dt,this.dirtyTrackingSystem=new mt}var e=t.prototype;return e.setEntities=function(t){this.entities=t,this.clearQueryCache(),this.rebuildIndexes()},e.addEntity=function(t,e){void 0===e&&(e=!1),this.entities.includes(t)||(this.entities.push(t),this.addEntityToIndexes(t),this.componentIndexManager.addEntity(t),this.archetypeSystem.addEntity(t),this.dirtyTrackingSystem.markDirty(t,ut.COMPONENT_ADDED),e||this.clearQueryCache(),this._version++)},e.addEntities=function(t){if(0!==t.length){for(var e,n=new Set(this.entities.map((function(t){return t.id}))),i=0,r=o(t);!(e=r()).done;){var s=e.value;n.has(s.id)||(this.entities.push(s),this.addEntityToIndexes(s),n.add(s.id),i++)}i>0&&this.clearQueryCache()}},e.addEntitiesUnchecked=function(t){if(0!==t.length){for(var e,n=o(t);!(e=n()).done;){var i=e.value;this.entities.push(i)}for(var r,s=o(t);!(r=s()).done;){var a=r.value;this.addEntityToIndexes(a)}this.clearQueryCache()}},e.removeEntity=function(t){var e=this.entities.indexOf(t);-1!==e&&(this.entities.splice(e,1),this.removeEntityFromIndexes(t),this.componentIndexManager.removeEntity(t),this.archetypeSystem.removeEntity(t),this.dirtyTrackingSystem.markDirty(t,ut.COMPONENT_REMOVED),this.clearQueryCache(),this._version++)},e.addEntityToIndexes=function(t){var e=t.componentMask.toString(),n=this.entityIndex.byMask.get(e);n||(n=new Set,this.entityIndex.byMask.set(e,n)),n.add(t);for(var i=t.components,r=0;r<i.length;r++){var s=i[r].constructor,o=this.entityIndex.byComponentType.get(s);o||(o=new Set,this.entityIndex.byComponentType.set(s,o)),o.add(t)}var a=t.tag;if(void 0!==a){var c=this.entityIndex.byTag.get(a);c||(c=new Set,this.entityIndex.byTag.set(a,c)),c.add(t)}var u=t.name;if(u){var h=this.entityIndex.byName.get(u);h||(h=new Set,this.entityIndex.byName.set(u,h)),h.add(t)}},e.removeEntityFromIndexes=function(t){var e=t.componentMask.toString(),n=this.entityIndex.byMask.get(e);n&&(n.delete(t),0===n.size&&this.entityIndex.byMask.delete(e));for(var i,r=o(t.components);!(i=r()).done;){var s=i.value.constructor,a=this.entityIndex.byComponentType.get(s);a&&(a.delete(t),0===a.size&&this.entityIndex.byComponentType.delete(s))}if(void 0!==t.tag){var c=this.entityIndex.byTag.get(t.tag);c&&(c.delete(t),0===c.size&&this.entityIndex.byTag.delete(t.tag))}if(t.name){var u=this.entityIndex.byName.get(t.name);u&&(u.delete(t),0===u.size&&this.entityIndex.byName.delete(t.name))}},e.rebuildIndexes=function(){this.entityIndex.byMask.clear(),this.entityIndex.byComponentType.clear(),this.entityIndex.byTag.clear(),this.entityIndex.byName.clear(),this.archetypeSystem.clear(),this.componentIndexManager.clear();for(var t,e=o(this.entities);!(t=e()).done;){var n=t.value;this.addEntityToIndexes(n),this.componentIndexManager.addEntity(n),this.archetypeSystem.addEntity(n)}this.indexDirty=!1},e.queryAll=function(){var t=performance.now();this.queryStats.totalQueries++;for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];var r="all:"+n.map((function(t){return G(t)})).sort().join(","),s=this.getFromCache(r);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};var a=[],c=this.archetypeSystem.queryArchetypes(n,"AND");if(c.archetypes.length>0){this.queryStats.archetypeHits++;for(var u,h=o(c.archetypes);!(u=h()).done;){var l,d=u.value;(l=a).push.apply(l,d.entities)}}else try{if(1===n.length){this.queryStats.indexHits++;var f=this.componentIndexManager.query(n[0]);a=Array.from(f)}else{var m=this.componentIndexManager.queryMultiple(n,"AND");a=Array.from(m)}}catch(t){a=[]}return this.addToCache(r,a),{entities:a,count:a.length,executionTime:performance.now()-t,fromCache:!1}},e.queryMultipleComponents=function(t){for(var e,n=null,i=1/0,r=o(t);!(e=r()).done;){var s=e.value,a=this.entityIndex.byComponentType.get(s);if(!a||0===a.size)return[];a.size<i&&(i=a.size,n=a)}if(!n)return[];for(var c,u=this.createComponentMask(t),h=[],l=o(n);!(c=l()).done;){var d=c.value;M.hasAll(d.componentMask,u)&&h.push(d)}return h},e.queryAny=function(){var t=performance.now();this.queryStats.totalQueries++;for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];var r="any:"+n.map((function(t){return G(t)})).sort().join(","),s=this.getFromCache(r);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};var a,c=this.archetypeSystem.queryArchetypes(n,"OR");if(c.archetypes.length>0){this.queryStats.archetypeHits++,a=[];for(var u,h=o(c.archetypes);!(u=h()).done;){var l,d=u.value;(l=a).push.apply(l,d.entities)}}else{var f=this.componentIndexManager.queryMultiple(n,"OR");a=Array.from(f)}return this.addToCache(r,a),{entities:a,count:a.length,executionTime:performance.now()-t,fromCache:!1}},e.queryNone=function(){var t=performance.now();this.queryStats.totalQueries++;for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];var r="none:"+n.map((function(t){return G(t)})).sort().join(","),s=this.getFromCache(r);if(s)return this.queryStats.cacheHits++,{entities:s,count:s.length,executionTime:performance.now()-t,fromCache:!0};var o=this.createComponentMask(n),a=this.entities.filter((function(t){return M.hasNone(t.componentMask,o)}));return this.addToCache(r,a),{entities:a,count:a.length,executionTime:performance.now()-t,fromCache:!1}},e.queryByTag=function(t){var e=performance.now();this.queryStats.totalQueries++;var n="tag:"+t,i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byTag.get(t)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!1}},e.queryByName=function(t){var e=performance.now();this.queryStats.totalQueries++;var n="name:"+t,i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byName.get(t)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!1}},e.queryByComponent=function(t){var e=performance.now();this.queryStats.totalQueries++;var n="component:"+G(t),i=this.getFromCache(n);if(i)return this.queryStats.cacheHits++,{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;var r=Array.from(this.entityIndex.byComponentType.get(t)||[]);return this.addToCache(n,r),{entities:r,count:r.length,executionTime:performance.now()-e,fromCache:!1}},e.getFromCache=function(t){var e=this.queryCache.get(t);return e?Date.now()-e.timestamp>this.cacheTimeout?(this.queryCache.delete(t),null):(e.hitCount++,e.entities):null},e.addToCache=function(t,e){this.queryCache.size>=this.cacheMaxSize&&this.cleanupCache(),this.queryCache.set(t,{entities:[].concat(e),timestamp:Date.now(),hitCount:0})},e.cleanupCache=function(){for(var t,e=Date.now(),n=o(this.queryCache.entries());!(t=n()).done;){var i=t.value,r=i[0];e-i[1].timestamp>this.cacheTimeout&&this.queryCache.delete(r)}if(this.queryCache.size>=this.cacheMaxSize){var s=Array.from(this.queryCache.entries());s.sort((function(t,e){return t[1].hitCount-e[1].hitCount}));for(var a=Math.floor(.2*this.cacheMaxSize),c=0;c<a&&c<s.length;c++)this.queryCache.delete(s[c][0])}},e.clearQueryCache=function(){this.queryCache.clear()},e.clearCache=function(){this.clearQueryCache()},e.batchUpdateComponents=function(t){for(var e,n=this,i=[],r=function(){var t=e.value,r=n.entities.find((function(e){return e.id===t.entityId}));r&&(n.removeEntityFromIndexes(r),i.push(r))},s=o(t);!(e=s()).done;)r();for(var a=0,c=i;a<c.length;a++){var u=c[a];this.addEntityToIndexes(u)}for(var h=0,l=i;h<l.length;h++){var d=l[h];this.dirtyTrackingSystem.markDirty(d,ut.COMPONENT_MODIFIED,[])}this.clearQueryCache()},e.createComponentMask=function(t){for(var e,n=M.clone(M.ZERO),i=!1,r=o(t);!(e=r()).done;){var s=e.value;try{var a=X.getBitMask(s);M.orInPlace(n,a),i=!0}catch(t){this._logger.warn("组件类型 "+G(s)+" 未注册,跳过")}}return i?n:{lo:4294967295,hi:4294967295}},e.getAllEntities=function(){return[].concat(this.entities)},e.getStats=function(){return{entityCount:this.entities.length,indexStats:{maskIndexSize:this.entityIndex.byMask.size,componentIndexSize:this.entityIndex.byComponentType.size,tagIndexSize:this.entityIndex.byTag.size,nameIndexSize:this.entityIndex.byName.size},queryStats:a({},this.queryStats,{cacheHitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}),optimizationStats:{componentIndex:this.componentIndexManager.getStats(),archetypeSystem:this.archetypeSystem.getAllArchetypes().map((function(t){return{id:t.id,componentTypes:t.componentTypes.map((function(t){return G(t)})),entityCount:t.entities.length}})),dirtyTracking:this.dirtyTrackingSystem.getStats()},cacheStats:{size:this.queryCache.size,hitRate:this.queryStats.totalQueries>0?(this.queryStats.cacheHits/this.queryStats.totalQueries*100).toFixed(2)+"%":"0%"}}},e.configureDirtyTracking=function(t,e){this.dirtyTrackingSystem.configureBatchProcessing(t,e)},e.optimizePerformance=function(){this.dirtyTrackingSystem.processDirtyEntities(),this.cleanupCache(),this.componentIndexManager.getStats()},e.beginFrame=function(){this.dirtyTrackingSystem.beginFrame()},e.endFrame=function(){this.dirtyTrackingSystem.endFrame()},e.markEntityDirty=function(t,e){this.queryStats.dirtyChecks++,this.dirtyTrackingSystem.markDirty(t,ut.COMPONENT_MODIFIED,e),this.clearQueryCache()},e.getEntityArchetype=function(t){return this.archetypeSystem.getEntityArchetype(t)},s(t,[{key:"version",get:function(){return this._version}}])}(),vt=function(){function t(t){this._logger=D("QueryBuilder"),this.conditions=[],this.querySystem=t}var e=t.prototype;return e.withAll=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return this.conditions.push({type:ft.ALL,componentTypes:e,mask:this.createComponentMask(e)}),this},e.withAny=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return this.conditions.push({type:ft.ANY,componentTypes:e,mask:this.createComponentMask(e)}),this},e.without=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return this.conditions.push({type:ft.NONE,componentTypes:e,mask:this.createComponentMask(e)}),this},e.execute=function(){var t,e,n,i=performance.now();if(1===this.conditions.length){var r=this.conditions[0];switch(r.type){case ft.ALL:return(t=this.querySystem).queryAll.apply(t,r.componentTypes);case ft.ANY:return(e=this.querySystem).queryAny.apply(e,r.componentTypes);case ft.NONE:return(n=this.querySystem).queryNone.apply(n,r.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-i,fromCache:!1}},e.createComponentMask=function(t){for(var e,n=M.clone(M.ZERO),i=o(t);!(e=i()).done;){var r=e.value;try{var s=X.getBitMask(r);M.orInPlace(n,s)}catch(t){this._logger.warn("组件类型 "+G(r)+" 未注册,跳过")}}return n},e.reset=function(){return this.conditions=[],this},t}(),_t=function(){function t(){this.listeners=new Map,this.stats=new Map,this.batchQueue=new Map,this.batchTimers=new Map,this.batchConfigs=new Map,this.nextListenerId=0,this.isEnabled=!0,this.maxListeners=100}var e=t.prototype;return e.on=function(t,e,n){return void 0===n&&(n={}),this.addListener(t,e,n)},e.once=function(t,e,n){return void 0===n&&(n={}),this.addListener(t,e,a({},n,{once:!0}))},e.onAsync=function(t,e,n){return void 0===n&&(n={}),this.addListener(t,e,a({},n,{async:!0}))},e.off=function(t,e){var n=this.listeners.get(t);if(!n)return!1;var i=n.findIndex((function(t){return t.id===e}));return-1!==i&&(n.splice(i,1),0===n.length&&(this.listeners.delete(t),this.stats.delete(t)),!0)},e.offAll=function(t){this.listeners.delete(t),this.stats.delete(t),this.clearBatch(t)},e.emit=function(){var t=n(l().m((function t(e,n){var i;return l().w((function(t){for(;;)switch(t.n){case 0:if(this.isEnabled){t.n=1;break}return t.a(2);case 1:if(null==(i=this.batchConfigs.get(e))||!i.enabled){t.n=2;break}return this.addToBatch(e,n),t.a(2);case 2:return t.n=3,this.executeEvent(e,n);case 3:return t.a(2)}}),t,this)})));return function(e,n){return t.apply(this,arguments)}}(),e.emitSync=function(e,n){if(this.isEnabled){var i=this.listeners.get(e);if(i&&0!==i.length){for(var r,s=performance.now(),a=[],c=o(this.sortListenersByPriority(i));!(r=c()).done;){var u=r.value;if(!u.config.async)try{u.config.context?u.handler.call(u.config.context,n):u.handler(n),u.config.once&&a.push(u.id)}catch(n){t._logger.error("事件处理器执行错误 "+e+":",n)}}this.removeListeners(e,a),this.updateStats(e,performance.now()-s)}}},e.setBatchConfig=function(t,e){this.batchConfigs.set(t,e)},e.flushBatch=function(t){var e=this.batchQueue.get(t);if(e&&0!==e.length){var n=this.batchTimers.get(t);n&&(clearTimeout(n),this.batchTimers.delete(t)),this.processBatch(t,e),this.batchQueue.delete(t)}},e.getStats=function(t){return t?this.stats.get(t)||this.createEmptyStats(t):new Map(this.stats)},e.resetStats=function(t){t?this.stats.delete(t):this.stats.clear()},e.setEnabled=function(t){this.isEnabled=t},e.hasListeners=function(t){var e=this.listeners.get(t);return!!e&&e.length>0},e.getListenerCount=function(t){var e=this.listeners.get(t);return e?e.length:0},e.clear=function(){this.listeners.clear(),this.stats.clear(),this.clearAllBatches()},e.setMaxListeners=function(t){this.maxListeners=t},e.addListener=function(e,n,i){var r=this.listeners.get(e);if(r||(r=[],this.listeners.set(e,r)),r.length>=this.maxListeners)return t._logger.warn("事件类型 "+e+" 的监听器数量超过最大限制 ("+this.maxListeners+")"),"";var s="listener_"+this.nextListenerId++,o={handler:n,config:a({priority:0},i),id:s};return r.push(o),this.stats.has(e)||this.stats.set(e,this.createEmptyStats(e)),s},e.executeEvent=function(){var e=n(l().m((function e(i,r){var s,a,c,u,h,d,f,m,p,y;return l().w((function(e){for(;;)switch(e.n){case 0:if((s=this.listeners.get(i))&&0!==s.length){e.n=1;break}return e.a(2);case 1:for(a=performance.now(),c=[],u=this.sortListenersByPriority(s),h=u.filter((function(t){return!t.config.async})),d=u.filter((function(t){return t.config.async})),f=o(h);!(m=f()).done;){p=m.value;try{p.config.context?p.handler.call(p.config.context,r):p.handler(r),p.config.once&&c.push(p.id)}catch(e){t._logger.error("同步事件处理器执行错误 "+i+":",e)}}return y=d.map(function(){var e=n(l().m((function e(n){var s;return l().w((function(e){for(;;)switch(e.p=e.n){case 0:if(e.p=0,!n.config.context){e.n=2;break}return e.n=1,n.handler.call(n.config.context,r);case 1:e.n=3;break;case 2:return e.n=3,n.handler(r);case 3:n.config.once&&c.push(n.id),e.n=5;break;case 4:e.p=4,s=e.v,t._logger.error("异步事件处理器执行错误 "+i+":",s);case 5:return e.a(2)}}),e,null,[[0,4]])})));return function(t){return e.apply(this,arguments)}}()),e.n=2,Promise.all(y);case 2:this.removeListeners(i,c),this.updateStats(i,performance.now()-a);case 3:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),e.sortListenersByPriority=function(t){return t.slice().sort((function(t,e){return(e.config.priority||0)-(t.config.priority||0)}))},e.removeListeners=function(t,e){if(0!==e.length){var n=this.listeners.get(t);if(n){for(var i,r=function(){var t=i.value,e=n.findIndex((function(e){return e.id===t}));-1!==e&&n.splice(e,1)},s=o(e);!(i=s()).done;)r();0===n.length&&(this.listeners.delete(t),this.stats.delete(t))}}},e.addToBatch=function(t,e){var n=this,i=this.batchQueue.get(t);i||(i=[],this.batchQueue.set(t,i)),i.push(e);var r=this.batchConfigs.get(t);if(i.length>=r.batchSize)this.flushBatch(t);else if(!this.batchTimers.has(t)){var s=setTimeout((function(){n.flushBatch(t)}),r.delay);this.batchTimers.set(t,s)}},e.processBatch=function(){var t=n(l().m((function t(e,n){var i;return l().w((function(t){for(;;)switch(t.n){case 0:return i={type:e,events:n,count:n.length,timestamp:Date.now()},t.n=1,this.executeEvent(e+":batch",i);case 1:return t.a(2)}}),t,this)})));return function(e,n){return t.apply(this,arguments)}}(),e.clearBatch=function(t){this.batchQueue.delete(t);var e=this.batchTimers.get(t);e&&(clearTimeout(e),this.batchTimers.delete(t))},e.clearAllBatches=function(){this.batchQueue.clear();for(var t,e=o(this.batchTimers.values());!(t=e()).done;){var n=t.value;clearTimeout(n)}this.batchTimers.clear(),this.batchConfigs.clear()},e.updateStats=function(t,e){var n=this.stats.get(t);n||(n=this.createEmptyStats(t),this.stats.set(t,n)),n.triggerCount++,n.totalExecutionTime+=e,n.averageExecutionTime=n.totalExecutionTime/n.triggerCount,n.lastTriggerTime=Date.now(),n.listenerCount=this.getListenerCount(t)},e.createEmptyStats=function(t){return{eventType:t,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}},t}();_t._logger=D("EventSystem"),function(t){t.ENTITY_CREATED="entity:created",t.ENTITY_DESTROYED="entity:destroyed",t.ENTITY_ENABLED="entity:enabled",t.ENTITY_DISABLED="entity:disabled",t.ENTITY_TAG_ADDED="entity:tag:added",t.ENTITY_TAG_REMOVED="entity:tag:removed",t.ENTITY_NAME_CHANGED="entity:name:changed",t.COMPONENT_ADDED="component:added",t.COMPONENT_REMOVED="component:removed",t.COMPONENT_MODIFIED="component:modified",t.COMPONENT_ENABLED="component:enabled",t.COMPONENT_DISABLED="component:disabled",t.SYSTEM_ADDED="system:added",t.SYSTEM_REMOVED="system:removed",t.SYSTEM_ENABLED="system:enabled",t.SYSTEM_DISABLED="system:disabled",t.SYSTEM_PROCESSING_START="system:processing:start",t.SYSTEM_PROCESSING_END="system:processing:end",t.SYSTEM_ERROR="system:error",t.SCENE_CREATED="scene:created",t.SCENE_DESTROYED="scene:destroyed",t.SCENE_ACTIVATED="scene:activated",t.SCENE_DEACTIVATED="scene:deactivated",t.SCENE_PAUSED="scene:paused",t.SCENE_RESUMED="scene:resumed",t.QUERY_EXECUTED="query:executed",t.QUERY_CACHE_HIT="query:cache:hit",t.QUERY_CACHE_MISS="query:cache:miss",t.QUERY_OPTIMIZED="query:optimized",t.PERFORMANCE_WARNING="performance:warning",t.PERFORMANCE_CRITICAL="performance:critical",t.MEMORY_USAGE_HIGH="memory:usage:high",t.FRAME_RATE_DROP="frame:rate:drop",t.INDEX_CREATED="index:created",t.INDEX_UPDATED="index:updated",t.INDEX_OPTIMIZED="index:optimized",t.ARCHETYPE_CREATED="archetype:created",t.ARCHETYPE_ENTITY_ADDED="archetype:entity:added",t.ARCHETYPE_ENTITY_REMOVED="archetype:entity:removed",t.DIRTY_MARK_ADDED="dirty:mark:added",t.DIRTY_BATCH_PROCESSED="dirty:batch:processed",t.ERROR_OCCURRED="error:occurred",t.WARNING_ISSUED="warning:issued",t.FRAMEWORK_INITIALIZED="framework:initialized",t.FRAMEWORK_SHUTDOWN="framework:shutdown",t.DEBUG_INFO="debug:info",t.DEBUG_STATS_UPDATED="debug:stats:updated"}(pt||(pt={})),function(t){t[t.LOWEST=0]="LOWEST",t[t.LOW=25]="LOW",t[t.NORMAL=50]="NORMAL",t[t.HIGH=75]="HIGH",t[t.HIGHEST=100]="HIGHEST",t[t.CRITICAL=200]="CRITICAL"}(yt||(yt={}));var St={ENTITY:{CREATED:pt.ENTITY_CREATED,DESTROYED:pt.ENTITY_DESTROYED,ENABLED:pt.ENTITY_ENABLED,DISABLED:pt.ENTITY_DISABLED,TAG_ADDED:pt.ENTITY_TAG_ADDED,TAG_REMOVED:pt.ENTITY_TAG_REMOVED,NAME_CHANGED:pt.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:pt.COMPONENT_ADDED,REMOVED:pt.COMPONENT_REMOVED,MODIFIED:pt.COMPONENT_MODIFIED,ENABLED:pt.COMPONENT_ENABLED,DISABLED:pt.COMPONENT_DISABLED},SYSTEM:{ADDED:pt.SYSTEM_ADDED,REMOVED:pt.SYSTEM_REMOVED,ENABLED:pt.SYSTEM_ENABLED,DISABLED:pt.SYSTEM_DISABLED,PROCESSING_START:pt.SYSTEM_PROCESSING_START,PROCESSING_END:pt.SYSTEM_PROCESSING_END,ERROR:pt.SYSTEM_ERROR},PERFORMANCE:{WARNING:pt.PERFORMANCE_WARNING,CRITICAL:pt.PERFORMANCE_CRITICAL,MEMORY_HIGH:pt.MEMORY_USAGE_HIGH,FRAME_DROP:pt.FRAME_RATE_DROP}},Et=function(){function t(){}return t.isValid=function(t){return this.validTypes.has(t)},t.getAllValidTypes=function(){return Array.from(this.validTypes)},t.addCustomType=function(t){this.validTypes.add(t)},t.removeCustomType=function(t){this.validTypes.delete(t)},t}();Et.validTypes=new Set([].concat(Object.values(pt),Object.values(St.ENTITY),Object.values(St.COMPONENT),Object.values(St.SYSTEM),Object.values(St.PERFORMANCE)));var Tt=function(){function t(t){void 0===t&&(t=!1),this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new _t,this.isDebugMode=t}var e=t.prototype;return e.emit=function(e,n){this.validateEventType(e);var i=this.enhanceEventData(e,n);this.isDebugMode&&t._logger.info("发射事件: "+e,i),this.eventSystem.emitSync(e,i)},e.emitAsync=function(){var e=n(l().m((function e(n,i){var r;return l().w((function(e){for(;;)switch(e.n){case 0:return this.validateEventType(n),r=this.enhanceEventData(n,i),this.isDebugMode&&t._logger.info("发射异步事件: "+n,r),e.n=1,this.eventSystem.emit(n,r);case 1:return e.a(2)}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}(),e.on=function(e,n,i){void 0===i&&(i={}),this.validateEventType(e);var r={once:i.once||!1,priority:i.priority||yt.NORMAL,async:i.async||!1,context:i.context};return this.isDebugMode&&t._logger.info("添加监听器: "+e,r),this.eventSystem.on(e,n,r)},e.once=function(t,e,n){return void 0===n&&(n={}),this.on(t,e,a({},n,{once:!0}))},e.onAsync=function(t,e,n){return void 0===n&&(n={}),this.on(t,e,a({},n,{async:!0}))},e.off=function(e,n){return this.isDebugMode&&t._logger.info("移除监听器: "+n+" 事件: "+e),this.eventSystem.off(e,n)},e.offAll=function(e){this.isDebugMode&&t._logger.info("移除所有监听器: "+e),this.eventSystem.offAll(e)},e.hasListeners=function(t){return this.eventSystem.hasListeners(t)},e.getStats=function(t){var e=this,n=this.eventSystem.getStats(t);if(n instanceof Map){var i=new Map;return n.forEach((function(t,n){i.set(n,e.convertEventStats(t))})),i}return this.convertEventStats(n)},e.clear=function(){this.isDebugMode&&t._logger.info("清空所有监听器"),this.eventSystem.clear()},e.setEnabled=function(t){this.eventSystem.setEnabled(t)},e.setDebugMode=function(t){this.isDebugMode=t},e.setMaxListeners=function(t){this.eventSystem.setMaxListeners(t)},e.getListenerCount=function(t){return this.eventSystem.getListenerCount(t)},e.setBatchConfig=function(t,e,n){this.eventSystem.setBatchConfig(t,{batchSize:e,delay:n,enabled:!0})},e.flushBatch=function(t){this.eventSystem.flushBatch(t)},e.resetStats=function(t){this.eventSystem.resetStats(t)},e.emitEntityCreated=function(t){this.emit(pt.ENTITY_CREATED,t)},e.emitEntityDestroyed=function(t){this.emit(pt.ENTITY_DESTROYED,t)},e.emitComponentAdded=function(t){this.emit(pt.COMPONENT_ADDED,t)},e.emitComponentRemoved=function(t){this.emit(pt.COMPONENT_REMOVED,t)},e.emitSystemAdded=function(t){this.emit(pt.SYSTEM_ADDED,t)},e.emitSystemRemoved=function(t){this.emit(pt.SYSTEM_REMOVED,t)},e.emitSceneChanged=function(t){this.emit(pt.SCENE_ACTIVATED,t)},e.emitPerformanceWarning=function(t){this.emit(pt.PERFORMANCE_WARNING,t)},e.onEntityCreated=function(t,e){return this.on(pt.ENTITY_CREATED,t,e)},e.onComponentAdded=function(t,e){return this.on(pt.COMPONENT_ADDED,t,e)},e.onSystemError=function(t,e){return this.on(pt.SYSTEM_ERROR,t,e)},e.onPerformanceWarning=function(t,e){return this.on(pt.PERFORMANCE_WARNING,t,e)},e.validateEventType=function(e){Et.isValid(e)||(this.isDebugMode&&t._logger.warn("未知事件类型: "+e),this.isDebugMode&&Et.addCustomType(e))},e.enhanceEventData=function(t,e){if(null==e)return{timestamp:Date.now(),eventId:t+"_"+ ++this.eventIdCounter,source:"EventBus"};var n=e;return n.timestamp||(n.timestamp=Date.now()),n.eventId||(n.eventId=t+"_"+ ++this.eventIdCounter),n.source||(n.source="EventBus"),n},e.convertEventStats=function(t){return{eventType:t.eventType,listenerCount:t.listenerCount,triggerCount:t.triggerCount,totalExecutionTime:t.totalExecutionTime,averageExecutionTime:t.averageExecutionTime,lastTriggerTime:t.lastTriggerTime}},t}();Tt._logger=D("EventBus");var Ct=function(){function t(){}return t.getInstance=function(t){return void 0===t&&(t=!1),this.instance||(this.instance=new Tt(t)),this.instance},t.reset=function(t){return void 0===t&&(t=!1),this.instance&&this.instance.clear(),this.instance=new Tt(t),this.instance},t}();function bt(t,e){return void 0===e&&(e={}),function(n,i,r){var s=r.value,o=n.constructor.prototype.initEventListeners||function(){};return n.constructor.prototype.initEventListeners=function(){o.call(this),Ct.getInstance().on(t,s.bind(this),e)},r}}function Mt(t,e){return void 0===e&&(e={}),function(n,i,r){var s=r.value,o=n.constructor.prototype.initEventListeners||function(){};return n.constructor.prototype.initEventListeners=function(){o.call(this),Ct.getInstance().onAsync(t,s.bind(this),e)},r}}var wt=function(){function t(t){var e=this;this.name="",this._didSceneBegin=!1,this.entities=new et(this),this.entityProcessors=new nt,this.identifierPool=new it,this.componentStorageManager=new J,this.querySystem=new gt,this.eventSystem=new _t,null!=t&&t.name&&(this.name=t.name),$.eventBus||($.eventBus=new Tt(!1)),$.eventBus&&$.eventBus.onComponentAdded((function(t){e.eventSystem.emitSync("component:added",t)}))}var e=t.prototype;return e.initialize=function(){},e.onStart=function(){},e.unload=function(){},e.begin=function(){null!=this.entityProcessors&&this.entityProcessors.begin(),this._didSceneBegin=!0,this.onStart()},e.end=function(){this._didSceneBegin=!1,this.entities.removeAllEntities(),this.querySystem.setEntities([]),this.componentStorageManager.clear(),this.entityProcessors&&this.entityProcessors.end(),this.unload()},e.update=function(){this.entities.updateLists(),null!=this.entityProcessors&&this.entityProcessors.update(),this.entities.update(),null!=this.entityProcessors&&this.entityProcessors.lateUpdate()},e.createEntity=function(t){var e=new $(t,this.identifierPool.checkOut());return this.eventSystem.emitSync("entity:created",{entityName:t,entity:e,scene:this}),this.addEntity(e)},e.addEntity=function(t,e){return void 0===e&&(e=!1),this.entities.add(t),t.scene=this,this.querySystem.addEntity(t,e),this.eventSystem.emitSync("entity:added",{entity:t,scene:this}),t},e.createEntities=function(t,e){void 0===e&&(e="Entity");for(var n=[],i=0;i<t;i++){var r=new $(e+"_"+i,this.identifierPool.checkOut());r.scene=this,n.push(r)}for(var s=0,o=n;s<o.length;s++){var a=o[s];this.entities.add(a)}return this.querySystem.addEntitiesUnchecked(n),this.eventSystem.emitSync("entities:batch_added",{entities:n,scene:this,count:t}),n},e.destroyAllEntities=function(){this.entities.removeAllEntities(),this.querySystem.setEntities([])},e.findEntity=function(t){return this.entities.findEntity(t)},e.findEntityById=function(t){return this.entities.findEntityById(t)},e.findEntitiesByTag=function(t){for(var e,n=[],i=o(this.entities.buffer);!(e=i()).done;){var r=e.value;r.tag===t&&n.push(r)}return n},e.getEntityByName=function(t){return this.findEntity(t)},e.getEntitiesByTag=function(t){return this.findEntitiesByTag(t)},e.addEntityProcessor=function(t){return this.entityProcessors.processors.includes(t)||(t.scene=this,this.entityProcessors.add(t),t.initialize(),t.setUpdateOrder(this.entityProcessors.count-1)),t},e.addSystem=function(t){return this.addEntityProcessor(t)},e.removeEntityProcessor=function(t){this.entityProcessors.remove(t),t.reset(),t.scene=null},e.getEntityProcessor=function(t){return this.entityProcessors.getProcessor(t)},e.getStats=function(){return{entityCount:this.entities.count,processorCount:this.entityProcessors.count,componentStorageStats:this.componentStorageManager.getAllStats()}},e.getDebugInfo=function(){return{name:this.name||this.constructor.name,entityCount:this.entities.count,processorCount:this.entityProcessors.count,isRunning:this._didSceneBegin,entities:this.entities.buffer.map((function(t){return{name:t.name,id:t.id,componentCount:t.components.length,componentTypes:t.components.map((function(t){return Q(t)}))}})),processors:this.entityProcessors.processors.map((function(t){var e;return{name:V(t),updateOrder:t.updateOrder,entityCount:(null===(e=t._entities)||void 0===e?void 0:e.length)||0}})),componentStats:this.componentStorageManager.getAllStats()}},s(t,[{key:"systems",get:function(){return this.entityProcessors.processors}}])}(),It=function(){function t(){this.scene=new wt}var e=t.prototype;return e.named=function(t){return this.scene.name=t,this},e.withEntity=function(t){return this.scene.addEntity(t),this},e.withEntityBuilder=function(t){var e=t(new tt(this.scene,this.scene.componentStorageManager)).build();return this.scene.addEntity(e),this},e.withEntities=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var i=0,r=e;i<r.length;i++){var s=r[i];this.scene.addEntity(s)}return this},e.withSystem=function(t){return this.scene.addSystem(t),this},e.withSystems=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];for(var i=0,r=e;i<r.length;i++){var s=r[i];this.scene.addSystem(s)}return this},e.build=function(){return this.scene},t}(),At=function(){function t(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];this.component=i(t,n)}var e=t.prototype;return e.set=function(t,e){return this.component[t]=e,this},e.configure=function(t){return t(this.component),this},e.setIf=function(t,e,n){return t&&(this.component[e]=n),this},e.build=function(){return this.component},t}(),xt=function(){function t(t){this.entities=t}var e=t.prototype;return e.addComponent=function(t){for(var e,n=o(this.entities);!(e=n()).done;){e.value.addComponent(t)}return this},e.removeComponent=function(t){for(var e,n=o(this.entities);!(e=n()).done;){e.value.removeComponentByType(t)}return this},e.setActive=function(t){for(var e,n=o(this.entities);!(e=n()).done;){e.value.active=t}return this},e.setTag=function(t){for(var e,n=o(this.entities);!(e=n()).done;){e.value.tag=t}return this},e.forEach=function(t){return this.entities.forEach(t),this},e.filter=function(e){return new t(this.entities.filter(e))},e.toArray=function(){return this.entities.slice()},e.count=function(){return this.entities.length},t}(),Dt=function(){function t(t,e,n){this.scene=t,this.querySystem=e,this.eventSystem=n}var e=t.prototype;return e.createEntity=function(){return new tt(this.scene,this.scene.componentStorageManager)},e.createScene=function(){return new It},e.createComponent=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return i(At,[t].concat(n))},e.query=function(){return new vt(this.querySystem)},e.find=function(){var t;return(t=this.querySystem).queryAll.apply(t,arguments).entities},e.findFirst=function(){var t,e=(t=this.querySystem).queryAll.apply(t,arguments);return e.entities.length>0?e.entities[0]:null},e.findByName=function(t){return this.scene.findEntity(t)},e.findByTag=function(t){return this.scene.findEntitiesByTag(t)},e.emit=function(t,e){this.eventSystem.emitSync(t,e)},e.emitAsync=function(){var t=n(l().m((function t(e,n){return l().w((function(t){for(;;)switch(t.n){case 0:return t.n=1,this.eventSystem.emit(e,n);case 1:return t.a(2)}}),t,this)})));return function(e,n){return t.apply(this,arguments)}}(),e.on=function(t,e){return this.eventSystem.on(t,e)},e.once=function(t,e){return this.eventSystem.once(t,e)},e.off=function(t,e){this.eventSystem.off(t,e)},e.batch=function(t){return new xt(t)},e.getStats=function(){return{entityCount:this.scene.entities.count,systemCount:this.scene.systems.length,componentStats:this.scene.componentStorageManager.getAllStats(),queryStats:this.querySystem.getStats(),eventStats:this.eventSystem.getStats()}},t}();function Ot(t,e,n){return new Dt(t,e,n)}var kt=D("World"),Nt=function(){function t(t){void 0===t&&(t={}),this._scenes=new Map,this._activeScenes=new Set,this._globalSystems=[],this._isActive=!1,this._config=a({name:"World",debug:!1,maxScenes:10,autoCleanup:!0},t),this.name=this._config.name,this._createdAt=Date.now(),kt.info("创建World: "+this.name)}var e=t.prototype;return e.createScene=function(t,e){if(this._scenes.has(t))throw new Error("Scene ID '"+t+"' 已存在于World '"+this.name+"' 中");if(this._scenes.size>=this._config.maxScenes)throw new Error("World '"+this.name+"' 已达到最大Scene数量限制: "+this._config.maxScenes);var n=e||new wt;return"id"in n&&(n.id=t),"name"in n&&!n.name&&(n.name=t),this._scenes.set(t,n),n.initialize(),kt.info("在World '"+this.name+"' 中创建Scene: "+t),n},e.removeScene=function(t){var e=this._scenes.get(t);return!!e&&(this._activeScenes.has(t)&&this.setSceneActive(t,!1),e.end(),this._scenes.delete(t),kt.info("从World '"+this.name+"' 中移除Scene: "+t),!0)},e.getScene=function(t){return this._scenes.get(t)||null},e.getSceneIds=function(){return Array.from(this._scenes.keys())},e.getAllScenes=function(){return Array.from(this._scenes.values())},e.setSceneActive=function(t,e){var n=this._scenes.get(t);n?e?(this._activeScenes.add(t),n.begin&&n.begin(),kt.debug("在World '"+this.name+"' 中激活Scene: "+t)):(this._activeScenes.delete(t),kt.debug("在World '"+this.name+"' 中停用Scene: "+t)):kt.warn("Scene '"+t+"' 不存在于World '"+this.name+"' 中")},e.isSceneActive=function(t){return this._activeScenes.has(t)},e.getActiveSceneCount=function(){return this._activeScenes.size},e.addGlobalSystem=function(t){return this._globalSystems.includes(t)||(this._globalSystems.push(t),t.initialize&&t.initialize(),kt.debug("在World '"+this.name+"' 中添加全局System: "+t.name)),t},e.removeGlobalSystem=function(t){var e=this._globalSystems.indexOf(t);return-1!==e&&(this._globalSystems.splice(e,1),t.reset&&t.reset(),kt.debug("从World '"+this.name+"' 中移除全局System: "+t.name),!0)},e.getGlobalSystem=function(t){for(var e,n=o(this._globalSystems);!(e=n()).done;){var i=e.value;if(i instanceof t)return i}return null},e.start=function(){if(!this._isActive){this._isActive=!0;for(var t,e=o(this._globalSystems);!(t=e()).done;){var n=t.value;n.initialize&&n.initialize()}kt.info("启动World: "+this.name)}},e.stop=function(){if(this._isActive){for(var t,e=o(this._activeScenes);!(t=e()).done;){var n=t.value;this.setSceneActive(n,!1)}for(var i,r=o(this._globalSystems);!(i=r()).done;){var s=i.value;s.reset&&s.reset()}this._isActive=!1,kt.info("停止World: "+this.name)}},e.updateGlobalSystems=function(){if(this._isActive)for(var t,e=o(this._globalSystems);!(t=e()).done;){var n=t.value;n.update&&n.update()}},e.updateScenes=function(){if(this._isActive){for(var t,e=o(this._activeScenes);!(t=e()).done;){var n=t.value,i=this._scenes.get(n);i&&i.update&&i.update()}this._config.autoCleanup&&this.shouldAutoCleanup()&&this.cleanup()}},e.destroy=function(){kt.info("销毁World: "+this.name),this.stop();for(var t=0,e=Array.from(this._scenes.keys());t<e.length;t++){var n=e[t];this.removeScene(n)}for(var i,r=o(this._globalSystems);!(i=r()).done;){var s=i.value;s.destroy?s.destroy():s.reset&&s.reset()}this._globalSystems.length=0,this._scenes.clear(),this._activeScenes.clear()},e.getStatus=function(){var t=this;return{name:this.name,isActive:this._isActive,sceneCount:this._scenes.size,activeSceneCount:this._activeScenes.size,globalSystemCount:this._globalSystems.length,createdAt:this._createdAt,config:a({},this._config),scenes:Array.from(this._scenes.keys()).map((function(e){var n;return{id:e,isActive:t._activeScenes.has(e),name:(null===(n=t._scenes.get(e))||void 0===n?void 0:n.name)||e}}))}},e.getStats=function(){for(var t,e={totalEntities:0,totalSystems:this._globalSystems.length,memoryUsage:0,performance:{averageUpdateTime:0,maxUpdateTime:0}},n=o(this._scenes.values());!(t=n()).done;){var i=t.value;i.entities&&(e.totalEntities+=i.entities.count),i.systems&&(e.totalSystems+=i.systems.length)}return e},e.shouldAutoCleanup=function(){for(var t,e=Date.now(),n=o(this._scenes);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];if(!this._activeScenes.has(r)&&s.entities&&0===s.entities.count&&e-this._createdAt>3e5)return!0}return!1},e.cleanup=function(){for(var t=Array.from(this._scenes.keys()),e=Date.now(),n=0,i=t;n<i.length;n++){var r=i[n],s=this._scenes.get(r);s&&!this._activeScenes.has(r)&&s.entities&&0===s.entities.count&&e-this._createdAt>3e5&&(this.removeScene(r),kt.debug("自动清理空Scene: "+r+" from World "+this.name))}},s(t,[{key:"isActive",get:function(){return this._isActive}},{key:"sceneCount",get:function(){return this._scenes.size}},{key:"createdAt",get:function(){return this._createdAt}}])}(),Rt=D("WorldManager"),Pt=function(){function t(t){void 0===t&&(t={}),this._worlds=new Map,this._activeWorlds=new Set,this._cleanupTimer=null,this._isRunning=!1,this._config=a({maxWorlds:50,autoCleanup:!0,cleanupInterval:3e4,debug:!1},t),Rt.info("WorldManager已初始化",{maxWorlds:this._config.maxWorlds,autoCleanup:this._config.autoCleanup,cleanupInterval:this._config.cleanupInterval}),this.startCleanupTimer()}t.getInstance=function(e){return this._instance||(this._instance=new t(e)),this._instance},t.reset=function(){this._instance&&(this._instance.destroy(),this._instance=null)};var e=t.prototype;return e.createWorld=function(t,e){if(!t||"string"!=typeof t||""===t.trim())throw new Error("World ID不能为空");if(this._worlds.has(t))throw new Error("World ID '"+t+"' 已存在");if(this._worlds.size>=this._config.maxWorlds)throw new Error("已达到最大World数量限制: "+this._config.maxWorlds);var n=a({name:t,debug:this._config.debug},e),i=new Nt(n);return this._worlds.set(t,i),Rt.info("创建World: "+t,{config:n}),i},e.removeWorld=function(t){var e=this._worlds.get(t);return!!e&&(this._activeWorlds.has(t)&&this.setWorldActive(t,!1),e.destroy(),this._worlds.delete(t),Rt.info("移除World: "+t),!0)},e.getWorld=function(t){return this._worlds.get(t)||null},e.getWorldIds=function(){return Array.from(this._worlds.keys())},e.getAllWorlds=function(){return Array.from(this._worlds.values())},e.setWorldActive=function(t,e){var n=this._worlds.get(t);n?e?(this._activeWorlds.add(t),n.start(),Rt.debug("激活World: "+t)):(this._activeWorlds.delete(t),n.stop(),Rt.debug("停用World: "+t)):Rt.warn("World '"+t+"' 不存在")},e.isWorldActive=function(t){return this._activeWorlds.has(t)},e.getActiveWorlds=function(){for(var t,e=[],n=o(this._activeWorlds);!(t=n()).done;){var i=t.value,r=this._worlds.get(i);r&&e.push(r)}return e},e.startAll=function(){this._isRunning=!0;for(var t,e=o(this._worlds.keys());!(t=e()).done;){var n=t.value;this.setWorldActive(n,!0)}Rt.info("启动所有World")},e.stopAll=function(){this._isRunning=!1;for(var t,e=o(this._activeWorlds);!(t=e()).done;){var n=t.value;this.setWorldActive(n,!1)}Rt.info("停止所有World")},e.findWorlds=function(t){for(var e,n=[],i=o(this._worlds.values());!(e=i()).done;){var r=e.value;t(r)&&n.push(r)}return n},e.findWorldByName=function(t){for(var e,n=o(this._worlds.values());!(e=n()).done;){var i=e.value;if(i.name===t)return i}return null},e.getStats=function(){for(var t,e={totalWorlds:this._worlds.size,activeWorlds:this._activeWorlds.size,totalScenes:0,totalEntities:0,totalSystems:0,memoryUsage:0,isRunning:this._isRunning,config:a({},this._config),worlds:[]},n=o(this._worlds);!(t=n()).done;){var i=t.value,r=i[0],s=i[1],c=s.getStats();e.totalScenes+=c.totalSystems,e.totalEntities+=c.totalEntities,e.totalSystems+=c.totalSystems,e.worlds.push(a({id:r,name:s.name,isActive:this._activeWorlds.has(r),sceneCount:s.sceneCount},c))}return e},e.getDetailedStatus=function(){var t=this;return a({},this.getStats(),{worlds:Array.from(this._worlds.entries()).map((function(e){var n=e[0],i=e[1];return{id:n,isActive:t._activeWorlds.has(n),status:i.getStatus()}}))})},e.cleanup=function(){for(var t,e=[],n=o(this._worlds);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];this.shouldCleanupWorld(s)&&e.push(r)}for(var a=0,c=e;a<c.length;a++){var u=c[a];this.removeWorld(u)}return e.length>0&&Rt.debug("清理了 "+e.length+" 个World"),e.length},e.destroy=function(){Rt.info("正在销毁WorldManager..."),this.stopCleanupTimer(),this.stopAll();for(var t=0,e=Array.from(this._worlds.keys());t<e.length;t++){var n=e[t];this.removeWorld(n)}this._worlds.clear(),this._activeWorlds.clear(),this._isRunning=!1,Rt.info("WorldManager已销毁")},e.startCleanupTimer=function(){var t=this;this._config.autoCleanup&&!this._cleanupTimer&&(this._cleanupTimer=setInterval((function(){t.cleanup()}),this._config.cleanupInterval),Rt.debug("启动World清理定时器,间隔: "+this._config.cleanupInterval+"ms"))},e.stopCleanupTimer=function(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null,Rt.debug("停止World清理定时器"))},e.shouldCleanupWorld=function(t){return!t.isActive&&((0===t.sceneCount||!t.getAllScenes().some((function(t){return t.entities&&t.entities.count>0})))&&Date.now()-t.createdAt>6e5)},s(t,[{key:"worldCount",get:function(){return this._worlds.size}},{key:"activeWorldCount",get:function(){return this._activeWorlds.size}},{key:"isRunning",get:function(){return this._isRunning}},{key:"config",get:function(){return a({},this._config)}}])}();Pt._instance=null;var zt=function(){function t(t){if(t&&"object"==typeof t)this._value=M.clone(t);else if("number"==typeof t)this._value=M.fromNumber(t);else if("string"==typeof t){var e=parseInt(t,10);this._value=M.fromNumber(e)}else this._value=M.clone(M.ZERO)}var e=t.prototype;return e.set=function(t){if(t<0)throw new Error("Bit index cannot be negative");if(t>=64)throw new Error("Bit index exceeds 64-bit limit. ECS framework supports max 64 component types.");M.setBit(this._value,t)},e.clear=function(t){if(t<0)throw new Error("Bit index cannot be negative");t>=64||M.clearBit(this._value,t)},e.get=function(t){if(t<0||t>=64)return!1;var e=M.create(t);return M.hasAny(this._value,e)},e.containsAll=function(t){return M.hasAll(this._value,t._value)},e.intersects=function(t){return M.hasAny(this._value,t._value)},e.excludes=function(t){return M.hasNone(this._value,t._value)},e.clearAll=function(){M.clear(this._value)},e.isEmpty=function(){return M.isZero(this._value)},e.cardinality=function(){return M.popCount(this._value)},e.and=function(e){var n=new t;return M.copy(this._value,n._value),M.andInPlace(n._value,e._value),n},e.or=function(e){var n=new t;return M.copy(this._value,n._value),M.orInPlace(n._value,e._value),n},e.xor=function(e){var n=new t;return M.copy(this._value,n._value),M.xorInPlace(n._value,e._value),n},e.not=function(e){void 0===e&&(e=64),e>64&&(e=64);var n=new t;if(M.copy(this._value,n._value),e<=32){var i=(1<<e)-1;n._value.lo=~n._value.lo&i,n._value.hi=0}else if(n._value.lo=~n._value.lo,e<64){var r=(1<<e-32)-1;n._value.hi=~n._value.hi&r}else n._value.hi=~n._value.hi;return n},e.copyFrom=function(t){M.copy(t._value,this._value)},e.clone=function(){return new t(this._value)},e.getValue=function(){return this._value},e.setValue=function(t){if("object"==typeof t)M.copy(t,this._value);else if("number"==typeof t)this._value=M.fromNumber(t);else{var e=parseInt(t,10);this._value=M.fromNumber(e)}},e.toString=function(){for(var t=[],e=0;e<64;e++)this.get(e)&&t.push(e.toString());return"Bits["+t.join(", ")+"]"},e.toBinaryString=function(t){void 0===t&&(t=64),t>64&&(t=64);for(var e="",n=t-1;n>=0;n--)e+=this.get(n)?"1":"0",n%8==0&&n>0&&(e+=" ");return e},e.toHexString=function(){return M.toString(this._value,16)},t.fromBinaryString=function(e){var n,i=e.replace(/\s/g,"");if(i.length<=32){n={lo:parseInt(i,2)>>>0,hi:0}}else{var r=i.substring(i.length-32),s=i.substring(0,i.length-32);n={lo:parseInt(r,2)>>>0,hi:parseInt(s,2)>>>0}}return new t(n)},t.fromHexString=function(e){var n,i=e.replace(/^0x/i,"");if(i.length<=8){n={lo:parseInt(i,16)>>>0,hi:0}}else{var r=i.substring(i.length-8),s=i.substring(0,i.length-8);n={lo:parseInt(r,16)>>>0,hi:parseInt(s,16)>>>0}}return new t(n)},e.equals=function(t){return M.equals(this._value,t._value)},e.getHighestBitIndex=function(){if(M.isZero(this._value))return-1;if(0!==this._value.hi)for(var t=31;t>=0;t--)if(this._value.hi&1<<t)return t+32;for(var e=31;e>=0;e--)if(this._value.lo&1<<e)return e;return-1},e.getLowestBitIndex=function(){if(M.isZero(this._value))return-1;for(var t=0;t<32;t++)if(this._value.lo&1<<t)return t;for(var e=0;e<32;e++)if(this._value.hi&1<<e)return e+32;return-1},t}(),Bt=function(){function t(){this._componentTypes=new Map,this._typeNames=new Map,this._nextTypeId=0}var e=t.prototype;return e.getTypeId=function(t){var e=this._componentTypes.get(t);return void 0===e&&(e=this._nextTypeId++,this._componentTypes.set(t,e),this._typeNames.set(e,G(t))),e},e.getTypeName=function(t){return this._typeNames.get(t)||"Unknown"},e.createBits=function(){for(var t=new zt,e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];for(var r=0,s=n;r<s.length;r++){var o=s[r],a=this.getTypeId(o);t.set(a)}return t},e.getEntityBits=function(t){for(var e,n=new zt,i=o(t);!(e=i()).done;){var r=e.value,s=this.getTypeId(r.constructor);n.set(s)}return n},e.reset=function(){this._componentTypes.clear(),this._typeNames.clear(),this._nextTypeId=0},s(t,[{key:"registeredTypeCount",get:function(){return this._componentTypes.size}}],[{key:"instance",get:function(){return t._instance||(t._instance=new t),t._instance}}])}(),Ft=function(){function t(){}var e=t.prototype;return e.collectEntityData=function(){var t=Gt.scene;if(!t)return this.getEmptyEntityDebugData();var e,n=t.entities;if(!n)return this.getEmptyEntityDebugData();try{e=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeData(t);return{totalEntities:e.totalEntities,activeEntities:e.activeEntities,pendingAdd:e.pendingAdd||0,pendingRemove:e.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:[],entityDetailsMap:{}}},e.getRawEntityList=function(){var t=Gt.scene;if(!t)return[];var e=t.entities;return null!=e&&e.buffer?e.buffer.map((function(t){var e,n;return{id:t.id,name:t.name||"Entity_"+t.id,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:!1!==t.activeInHierarchy,componentCount:t.components.length,componentTypes:t.components.map((function(t){return Q(t)})),parentId:(null===(e=t.parent)||void 0===e?void 0:e.id)||null,childIds:(null===(n=t.children)||void 0===n?void 0:n.map((function(t){return t.id})))||[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0}})):[]},e.getEntityDetails=function(t){try{var e,n,i,r=Gt.scene;if(!r)return null;var s=r.entities;if(null==s||!s.buffer)return null;var o=s.buffer.find((function(e){return e.id===t}));if(!o)return null;var c=o.getDebugInfo?o.getDebugInfo():this.buildFallbackEntityInfo(o),u=this.extractComponentDetails(o.components),h=this.getSceneInfo(r);return a({},c,{scene:h.name,sceneName:h.name,sceneType:h.type,parentName:(null===(e=o.parent)||void 0===e?void 0:e.name)||null,components:u||[],componentCount:(null===(n=o.components)||void 0===n?void 0:n.length)||0,componentTypes:(null===(i=o.components)||void 0===i?void 0:i.map((function(t){return Q(t)})))||[]})}catch(t){return{error:"获取实体详情失败: "+(t instanceof Error?t.message:String(t)),scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}},e.getSceneInfo=function(t){var e="当前场景",n="Scene";try{if(t.name&&"string"==typeof t.name&&t.name.trim())e=t.name.trim();else if(t.constructor&&t.constructor.name)e=t.constructor.name,n=t.constructor.name;else if(t._name&&"string"==typeof t._name&&t._name.trim())e=t._name.trim();else{var i,r=null===(i=Object.getPrototypeOf(t))||void 0===i||null===(i=i.constructor)||void 0===i?void 0:i.name;r&&"Object"!==r&&(e=r,n=r)}}catch(t){e="场景名获取失败"}return{name:e,type:n}},e.collectEntityDataWithMemory=function(){var t=Gt.scene;if(!t)return this.getEmptyEntityDebugData();var e,n=t.entities;if(!n)return this.getEmptyEntityDebugData();try{e=n.getStats?n.getStats():this.calculateFallbackEntityStats(n)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}var i=this.collectArchetypeDataWithMemory(t);return{totalEntities:e.totalEntities,activeEntities:e.activeEntities,pendingAdd:e.pendingAdd||0,pendingRemove:e.pendingRemove||0,entitiesPerArchetype:i.distribution,topEntitiesByComponents:i.topEntities,entityHierarchy:this.buildEntityHierarchyTree(n),entityDetailsMap:this.buildEntityDetailsMap(n)}},e.collectArchetypeData=function(t){var e;if(t&&t.archetypeSystem&&"function"==typeof t.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatistics(t.archetypeSystem);var n={entities:(null===(e=t.entities)||void 0===e?void 0:e.buffer)||[]};return{distribution:this.getArchetypeDistributionFast(n),topEntities:this.getTopEntitiesByComponentsFast(n)}},e.getArchetypeDistributionFast=function(t){var e=new Map;return t&&t.entities&&t.entities.forEach((function(t){var n,i=(null===(n=t.components)||void 0===n?void 0:n.map((function(t){return Q(t)})))||[],r=i.length>0?i.sort().join(", "):"无组件",s=e.get(r);s?s.count++:e.set(r,{count:1,componentTypes:i})})),Array.from(e.entries()).map((function(t){return{signature:t[0],count:t[1].count,memory:0}})).sort((function(t,e){return e.count-t.count})).slice(0,20)},e.getTopEntitiesByComponentsFast=function(t){return t&&t.entities?t.entities.map((function(t){var e;return{id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(e=t.components)||void 0===e?void 0:e.length)||0,memory:0}})).sort((function(t,e){return e.componentCount-t.componentCount})).slice(0,10):[]},e.collectArchetypeDataWithMemory=function(t){var e;if(t&&t.archetypeSystem&&"function"==typeof t.archetypeSystem.getAllArchetypes)return this.extractArchetypeStatisticsWithMemory(t.archetypeSystem);var n={entities:(null===(e=t.entities)||void 0===e?void 0:e.buffer)||[]};return{distribution:this.getArchetypeDistributionWithMemory(n),topEntities:this.getTopEntitiesByComponentsWithMemory(n)}},e.extractArchetypeStatistics=function(t){var e=t.getAllArchetypes(),n=[],i=[];return e.forEach((function(t){var e,r,s=(null===(e=t.componentTypes)||void 0===e?void 0:e.map((function(t){return t.name})).join(","))||"Unknown",o=(null===(r=t.entities)||void 0===r?void 0:r.length)||0;n.push({signature:s,count:o,memory:0}),t.entities&&t.entities.slice(0,5).forEach((function(t){var e;i.push({id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(e=t.components)||void 0===e?void 0:e.length)||0,memory:0})}))})),n.sort((function(t,e){return e.count-t.count})),i.sort((function(t,e){return e.componentCount-t.componentCount})),{distribution:n,topEntities:i}},e.extractArchetypeStatisticsWithMemory=function(t){var e=this,n=t.getAllArchetypes(),i=[],r=[];return n.forEach((function(t){var n,s,o=(null===(n=t.componentTypes)||void 0===n?void 0:n.map((function(t){return t.name})).join(","))||"Unknown",a=(null===(s=t.entities)||void 0===s?void 0:s.length)||0,c=0;if(t.entities&&t.entities.length>0){for(var u=Math.min(5,t.entities.length),h=0,l=0;l<u;l++)h+=e.estimateEntityMemoryUsage(t.entities[l]);c=h/u*a}i.push({signature:o,count:a,memory:c}),t.entities&&t.entities.slice(0,5).forEach((function(t){var n;r.push({id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(n=t.components)||void 0===n?void 0:n.length)||0,memory:e.estimateEntityMemoryUsage(t)})}))})),i.sort((function(t,e){return e.count-t.count})),r.sort((function(t,e){return e.componentCount-t.componentCount})),{distribution:i,topEntities:r}},e.getArchetypeDistribution=function(t){var e=new Map;return t&&t.entities&&t.entities.forEach((function(t){var n,i=(null===(n=t.componentMask)||void 0===n?void 0:n.toString())||"0",r=e.get(i);e.set(i,(r||0)+1)})),Array.from(e.entries()).map((function(t){return{signature:t[0],count:t[1],memory:0}})).sort((function(t,e){return e.count-t.count}))},e.getArchetypeDistributionWithMemory=function(t){var e=this,n=new Map;return t&&t.entities&&t.entities.forEach((function(t){var i,r=(null===(i=t.components)||void 0===i?void 0:i.map((function(t){return Q(t)})))||[],s=r.length>0?r.sort().join(", "):"无组件",o=n.get(s),a=e.estimateEntityMemoryUsage(t);(isNaN(a)||a<0)&&(a=0),o?(o.count++,o.memory+=a):n.set(s,{count:1,memory:a,componentTypes:r})})),Array.from(n.entries()).map((function(t){var e=t[0],n=t[1];return{signature:e,count:n.count,memory:isNaN(n.memory)?0:n.memory}})).sort((function(t,e){return e.count-t.count}))},e.getTopEntitiesByComponents=function(t){return t&&t.entities?t.entities.map((function(t){var e;return{id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(e=t.components)||void 0===e?void 0:e.length)||0,memory:0}})).sort((function(t,e){return e.componentCount-t.componentCount})):[]},e.getTopEntitiesByComponentsWithMemory=function(t){var e=this;return t&&t.entities?t.entities.map((function(t){var n;return{id:t.id.toString(),name:t.name||"Entity_"+t.id,componentCount:(null===(n=t.components)||void 0===n?void 0:n.length)||0,memory:e.estimateEntityMemoryUsage(t)}})).sort((function(t,e){return e.componentCount-t.componentCount})):[]},e.getEmptyEntityDebugData=function(){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}},e.calculateFallbackEntityStats=function(t){var e=t.buffer||[],n=e.filter((function(t){return t.enabled&&!t._isDestroyed}));return{totalEntities:e.length,activeEntities:n.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:n.length>0?e.reduce((function(t,e){var n;return t+((null===(n=e.components)||void 0===n?void 0:n.length)||0)}),0)/n.length:0}},e.estimateEntityMemoryUsage=function(t){var e=this;try{var n=0,i=this.calculateObjectSize(t,["components","children","parent"]);return!isNaN(i)&&i>0&&(n+=i),t.components&&Array.isArray(t.components)&&t.components.forEach((function(t){var i=e.calculateObjectSize(t,["entity"]);!isNaN(i)&&i>0&&(n+=i)})),isNaN(n)||n<0?0:n}catch(t){return 0}},e.calculateObjectSize=function(t,e){if(void 0===e&&(e=[]),!t||"object"!=typeof t)return 0;var n=new WeakSet,i=function(t,r){if(void 0===r&&(r=0),!t||"object"!=typeof t||r>=2)return 0;if(n.has(t))return 0;n.add(t);var s=32;try{for(var o=Object.keys(t),a=Math.min(o.length,20),c=0;c<a;c++){var u=o[c];if(!(e.includes(u)||"constructor"===u||"__proto__"===u||u.startsWith("_cc_")||u.startsWith("__"))){var h=t[u];s+=2*u.length,"string"==typeof h?s+=Math.min(2*h.length,200):"number"==typeof h?s+=8:"boolean"==typeof h?s+=4:Array.isArray(h)?s+=40+Math.min(8*h.length,160):"object"==typeof h&&null!==h&&(s+=i(h,r+1))}}}catch(t){return 64}return s};try{var r=i(t);return Math.max(r,32)}catch(t){return 64}},e.buildEntityHierarchyTree=function(t){var e=this;if(null==t||!t.buffer)return[];var n=[];return t.buffer.forEach((function(t){if(!t.parent){var i=e.buildEntityHierarchyNode(t);n.push(i)}})),n.sort((function(t,e){return t.name<e.name?-1:t.name>e.name?1:t.id-e.id})),n},e.buildEntityHierarchyNode=function(t){var e,n=this,i={id:t.id,name:t.name||"Entity_"+t.id,active:!1!==t.active,enabled:!1!==t.enabled,activeInHierarchy:!1!==t.activeInHierarchy,componentCount:t.components.length,componentTypes:t.components.map((function(t){return Q(t)})),parentId:(null===(e=t.parent)||void 0===e?void 0:e.id)||null,children:[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0};(t.children&&t.children.length>0&&(i.children=t.children.map((function(t){return n.buildEntityHierarchyNode(t)}))),"function"==typeof t.getDebugInfo)&&(i=a({},i,t.getDebugInfo()));return t.components&&t.components.length>0&&(i.componentDetails=this.extractComponentDetails(t.components)),i},e.buildEntityDetailsMap=function(t){var e=this;if(null==t||!t.buffer)return{};for(var n={},i=t.buffer,r=0;r<i.length;r+=100){i.slice(r,r+100).forEach((function(t){var i,r=t.getDebugInfo?t.getDebugInfo():e.buildFallbackEntityInfo(t),s=t.getComponentCacheStats?t.getComponentCacheStats():null,o=e.extractComponentDetails(t.components);n[t.id]=a({},r,{parentName:(null===(i=t.parent)||void 0===i?void 0:i.name)||null,components:o,componentTypes:r.componentTypes||o.map((function(t){return t.typeName})),cachePerformance:s?{hitRate:s.cacheStats.hitRate,size:s.cacheStats.size,maxSize:s.cacheStats.maxSize}:null})}))}return n},e.buildFallbackEntityInfo=function(t){var e,n,i,r=Gt.scene,s=this.getSceneInfo(r);return{name:t.name||"Entity_"+t.id,id:t.id,enabled:!1!==t.enabled,active:!1!==t.active,activeInHierarchy:!1!==t.activeInHierarchy,destroyed:t.isDestroyed||!1,scene:s.name,sceneName:s.name,sceneType:s.type,componentCount:t.components.length,componentTypes:t.components.map((function(t){return Q(t)})),componentMask:(null===(e=t.componentMask)||void 0===e?void 0:e.toString())||"0",parentId:(null===(n=t.parent)||void 0===n?void 0:n.id)||null,childCount:(null===(i=t.children)||void 0===i?void 0:i.length)||0,childIds:t.children.map((function(t){return t.id}))||[],depth:t.getDepth?t.getDepth():0,tag:t.tag||0,updateOrder:t.updateOrder||0}},e.extractComponentDetails=function(t){var e=this;return t.map((function(t){var n=Q(t);if(!n||"Object"===n||"Function"===n)try{var i=Bt.instance,r=t.constructor,s=i.getTypeId(r);n=i.getTypeName(s)}catch(t){n="UnknownComponent"}var o={};try{Object.keys(t).forEach((function(n){if(!n.startsWith("_")&&"entity"!==n&&"constructor"!==n){var i=t[n];null!=i&&(o[n]=e.formatPropertyValue(i))}})),0===Object.keys(o).length&&(o._info="该组件没有公开属性",o._componentId=Q(t))}catch(e){o._error="属性提取失败",o._componentId=Q(t)}return{typeName:n,properties:o}}))},e.getComponentProperties=function(t,e){var n=this;try{var i=Gt.scene;if(!i)return{};var r=i.entities;if(null==r||!r.buffer)return{};var s=r.buffer.find((function(e){return e.id===t}));if(!s||e>=s.components.length)return{};var o=s.components[e],a={};return Object.keys(o).forEach((function(t){if(!t.startsWith("_")&&"entity"!==t){var e=o[t];null!=e&&(a[t]=n.formatPropertyValue(e))}})),a}catch(t){return{_error:"属性提取失败"}}},e.formatPropertyValue=function(t,e){return void 0===e&&(e=0),null==t?t:"object"!=typeof t?"string"==typeof t&&t.length>200?"[长字符串: "+t.length+"字符] "+t.substring(0,100)+"...":t:0===e?this.formatObjectFirstLevel(t):this.createLazyLoadPlaceholder(t)},e.formatObjectFirstLevel=function(t){var e=this;try{if(Array.isArray(t)){if(0===t.length)return[];if(t.length>10){var n=t.slice(0,3).map((function(t){return e.formatPropertyValue(t,1)}));return{_isLazyArray:!0,_arrayLength:t.length,_sample:n,_summary:"数组["+t.length+"个元素]"}}return t.map((function(t){return e.formatPropertyValue(t,1)}))}var i=Object.keys(t);if(0===i.length)return{};for(var r={},s=0,o=0,a=i;o<a.length;o++){var c=a[o];if(s>=15){r._hasMoreProperties=!0,r._totalProperties=i.length,r._hiddenCount=i.length-s;break}if(!c.startsWith("_")&&!c.startsWith("$")&&"function"!=typeof t[c])try{var u=t[c];null!=u&&(r[c]=this.formatPropertyValue(u,1),s++)}catch(t){r[c]="[访问失败: "+(t instanceof Error?t.message:String(t))+"]",s++}}return r}catch(t){return"[对象解析失败: "+(t instanceof Error?t.message:String(t))+"]"}},e.createLazyLoadPlaceholder=function(t){try{var e,n=(null===(e=t.constructor)||void 0===e?void 0:e.name)||"Object";return{_isLazyObject:!0,_typeName:n,_summary:this.getObjectSummary(t,n),_objectId:this.generateObjectId(t)}}catch(t){return{_isLazyObject:!0,_typeName:"Unknown",_summary:"无法分析的对象: "+(t instanceof Error?t.message:String(t)),_objectId:Math.random().toString(36).substr(2,9)}}},e.getObjectSummary=function(t,e){try{if((e.toLowerCase().includes("vec")||e.toLowerCase().includes("vector"))&&void 0!==t.x&&void 0!==t.y){var n=void 0!==t.z?t.z:"";return e+"("+t.x+", "+t.y+(n?", "+n:"")+")"}if(e.toLowerCase().includes("color")&&void 0!==t.r&&void 0!==t.g&&void 0!==t.b){var i=void 0!==t.a?t.a:1;return e+"("+t.r+", "+t.g+", "+t.b+", "+i+")"}if(e.toLowerCase().includes("node"))return e+": "+(t.name||t._name||"未命名");if(e.toLowerCase().includes("component")){var r,s,o=(null===(r=t.node)||void 0===r?void 0:r.name)||(null===(s=t.node)||void 0===s?void 0:s._name)||"";return e+(o?" on "+o:"")}var a=Object.keys(t);return 0===a.length?e+" (空对象)":e+" ("+a.length+"个属性)"}catch(t){return e+" (无法分析)"}},e.generateObjectId=function(t){try{return void 0!==t.id?"obj_"+t.id:void 0!==t._id?"obj_"+t._id:void 0!==t.uuid?"obj_"+t.uuid:void 0!==t._uuid?"obj_"+t._uuid:"obj_"+Math.random().toString(36).substr(2,9)}catch(t){return"obj_"+Math.random().toString(36).substr(2,9)}},e.expandLazyObject=function(t,e,n){try{var i=Gt.scene;if(!i)return null;var r=i.entities;if(null==r||!r.buffer)return null;var s=r.buffer.find((function(e){return e.id===t}));if(!s)return null;if(e>=s.components.length)return null;var o=s.components[e],a=this.getObjectByPath(o,n);return a?this.formatObjectFirstLevel(a):null}catch(t){return{error:"展开失败: "+(t instanceof Error?t.message:String(t))}}},e.getObjectByPath=function(t,e){if(!e)return t;for(var n,i=t,r=o(e.split("."));!(n=r()).done;){var s=n.value;if(null==i)return null;if(s.includes("[")&&s.includes("]")){var a=s.substring(0,s.indexOf("[")),c=parseInt(s.substring(s.indexOf("[")+1,s.indexOf("]")));if(a&&(i=i[a]),!(Array.isArray(i)&&c>=0&&c<i.length))return null;i=i[c]}else i=i[s]}return i},t}(),qt=function(){function t(){}return t.prototype.collectSystemData=function(t){var e=Gt.scene;if(!e)return{totalSystems:0,systemsInfo:[]};var n=e.entityProcessors;if(!n)return{totalSystems:0,systemsInfo:[]};var i=n.processors||[],r=new Map,s=new Map;if(t)try{r=t.getAllSystemStats(),s=t.getAllSystemData()}catch(t){}return{totalSystems:i.length,systemsInfo:i.map((function(t){var e,n=t.systemName||V(t),i=r.get(n),o=s.get(n);return{name:n,type:V(t),entityCount:(null===(e=t.entities)||void 0===e?void 0:e.length)||0,executionTime:(null==i?void 0:i.averageTime)||(null==o?void 0:o.executionTime)||0,minExecutionTime:(null==i?void 0:i.minTime)===Number.MAX_VALUE?0:(null==i?void 0:i.minTime)||0,maxExecutionTime:(null==i?void 0:i.maxTime)||0,executionTimeHistory:(null==i?void 0:i.recentTimes)||[],updateOrder:t.updateOrder||0,enabled:!1!==t.enabled,lastUpdateTime:(null==o?void 0:o.lastUpdateTime)||0}}))}},t}(),Lt=function(){function t(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.lastGCCount=0,this.gcCollections=0,this.lastMemoryCheck=0}var e=t.prototype;return e.collectPerformanceData=function(t){var e=g.deltaTime,n=1e3*e,i=e>0?Math.round(1/e):0,r=this.getECSPerformanceData(t),s=r.totalExecutionTime,o=n>0?s/n*100:0,a=0;performance.memory&&(a=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(s),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();var c=this.frameTimeHistory.filter((function(t){return t>=0}));return{frameTime:s,engineFrameTime:n,ecsPercentage:o,memoryUsage:a,fps:i,averageFrameTime:c.length>0?c.reduce((function(t,e){return t+e}),0)/c.length:s,minFrameTime:c.length>0?Math.min.apply(Math,c):s,maxFrameTime:c.length>0?Math.max.apply(Math,c):s,frameTimeHistory:[].concat(this.frameTimeHistory),systemPerformance:this.getSystemPerformance(t),systemBreakdown:r.systemBreakdown,memoryDetails:this.getMemoryDetails()}},e.getECSPerformanceData=function(t){if(!t)try{var e=Gt.Instance;if(!e||!e._performanceMonitor)return{totalExecutionTime:0,systemBreakdown:[]};t=e._performanceMonitor}catch(t){return{totalExecutionTime:0,systemBreakdown:[]}}if(!t.enabled){try{t.enabled=!0}catch(t){}return{totalExecutionTime:0,systemBreakdown:[]}}try{var n=0,i=[],r=t.getAllSystemStats();if(0===r.size)return{totalExecutionTime:0,systemBreakdown:[]};for(var s,a=o(r.entries());!(s=a()).done;){var c=s.value,u=c[0],h=c[1],l=h.recentTimes&&h.recentTimes.length>0?h.recentTimes[h.recentTimes.length-1]:h.averageTime||0;n+=l,i.push({systemName:u,executionTime:l,percentage:0})}return i.forEach((function(t){t.percentage=n>0?t.executionTime/n*100:0})),i.sort((function(t,e){return e.executionTime-t.executionTime})),{totalExecutionTime:n,systemBreakdown:i}}catch(t){return{totalExecutionTime:0,systemBreakdown:[]}}},e.getSystemPerformance=function(t){if(!t)return[];try{var e=t.getAllSystemStats(),n=t.getAllSystemData();return Array.from(e.entries()).map((function(t){var e=t[0],i=t[1],r=n.get(e);return{systemName:e,averageTime:i.averageTime||0,maxTime:i.maxTime||0,minTime:i.minTime===Number.MAX_VALUE?0:i.minTime||0,samples:i.executionCount||0,percentage:0,entityCount:(null==r?void 0:r.entityCount)||0,lastExecutionTime:(null==r?void 0:r.executionTime)||0}}))}catch(t){return[]}},e.getMemoryDetails=function(){var t={entities:0,components:0,systems:0,pooled:0,totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:this.updateGCCount()};try{if(performance.memory){var e=performance.memory;if(t.totalMemory=e.jsHeapSizeLimit||536870912,t.usedMemory=e.usedJSHeapSize||0,t.freeMemory=t.totalMemory-t.usedMemory,this.lastMemoryCheck>0)this.lastMemoryCheck-t.usedMemory>1048576&&this.gcCollections++;this.lastMemoryCheck=t.usedMemory}else t.totalMemory=536870912,t.freeMemory=536870912}catch(t){return{totalMemory:0,usedMemory:0,freeMemory:0,entityMemory:0,componentMemory:0,systemMemory:0,pooledMemory:0,gcCollections:this.gcCollections}}return t},e.updateGCCount=function(){try{return"undefined"!=typeof PerformanceObserver||performance.measureUserAgentSpecificMemory,this.gcCollections}catch(t){return this.gcCollections}},t}(),Wt=function(){function t(){}var e=t.prototype;return e.collectComponentData=function(){var t=this,e=Gt.scene;if(!e)return{componentTypes:0,componentInstances:0,componentStats:[]};var n=e.entities;if(null==n||!n.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};var i=new Map,r=0;n.buffer.forEach((function(t){t.components&&t.components.forEach((function(t){var e=Q(t),n=i.get(e)||{count:0,entities:0};n.count++,r++,i.set(e,n)}))}));var s=new Map,a=new Map;try{for(var c,u=st.getInstance(),h=u.getPoolStats(),l=u.getPoolUtilization(),d=o(h.entries());!(c=d()).done;){var f=c.value,m=f[0],p=f[1];a.set(m,p.maxSize)}for(var y,g=o(l.entries());!(y=g()).done;){var v=y.value,_=v[0],S=v[1];s.set(_,S.utilization)}}catch(t){}return{componentTypes:i.size,componentInstances:r,componentStats:Array.from(i.entries()).map((function(e){var i=e[0],r=e[1],o=a.get(i)||0,c=s.get(i)||0,u=t.getEstimatedComponentSize(i);return{typeName:i,instanceCount:r.count,memoryPerInstance:u,totalMemory:r.count*u,poolSize:o,poolUtilization:c,averagePerEntity:r.count/n.buffer.length}}))}},e.getEstimatedComponentSize=function(e){if(t.componentSizeCache.has(e))return t.componentSizeCache.get(e);var n=Gt.scene;if(!n)return 64;var i=n.entities;if(null==i||!i.buffer)return 64;var r=64;try{for(var s,a=o(i.buffer);!(s=a()).done;){var c=s.value;if(c.components){var u=c.components.find((function(t){return Q(t)===e}));if(u){r=this.calculateQuickObjectSize(u);break}}}}catch(t){r=64}return t.componentSizeCache.set(e,r),r},e.calculateQuickObjectSize=function(t){if(!t||"object"!=typeof t)return 8;var e=32,n=new WeakSet,i=function(t,e){if(void 0===e&&(e=0),!t||"object"!=typeof t||n.has(t)||e>3)return 0;n.add(t);var r=0;try{for(var s=Object.keys(t),o=0;o<Math.min(s.length,20);o++){var a=s[o];if("entity"!==a&&"_entity"!==a&&"constructor"!==a){var c=t[a];r+=2*a.length,"string"==typeof c?r+=Math.min(2*c.length,200):"number"==typeof c?r+=8:"boolean"==typeof c?r+=4:"object"==typeof c&&null!==c&&(r+=i(c,e+1))}}}catch(t){return 32}return r};return e+=i(t),Math.max(e,32)},e.calculateDetailedComponentMemory=function(t){var e=Gt.scene;if(!e)return this.getEstimatedComponentSize(t);var n=e.entities;if(null==n||!n.buffer)return this.getEstimatedComponentSize(t);try{for(var i,r=o(n.buffer);!(i=r()).done;){var s=i.value;if(s.components){var a=s.components.find((function(e){return Q(e)===t}));if(a)return this.estimateObjectSize(a)}}}catch(t){}return this.getEstimatedComponentSize(t)},e.estimateObjectSize=function(t,e,n){if(void 0===e&&(e=new WeakSet),void 0===n&&(n=0),null==t||n>10)return 0;if(e.has(t))return 0;var i=0;switch(typeof t){case"boolean":i=4;break;case"number":default:i=8;break;case"string":i=24+Math.min(2*t.length,1e3);break;case"object":if(e.add(t),Array.isArray(t)){i=40+8*t.length;for(var r=Math.min(t.length,50),s=0;s<r;s++)i+=this.estimateObjectSize(t[s],e,n+1)}else{i=32;try{for(var o=Object.getOwnPropertyNames(t),a=Math.min(o.length,30),c=0;c<a;c++){var u=o[c];if("constructor"!==u&&"__proto__"!==u&&"entity"!==u&&"_entity"!==u&&!u.startsWith("_cc_")&&!u.startsWith("__"))try{i+=16+2*u.length;var h=t[u];null!=h&&(i+=this.estimateObjectSize(h,e,n+1))}catch(t){continue}}}catch(t){i=128}}}return 8*Math.ceil(i/8)},t.clearCache=function(){t.componentSizeCache.clear()},t}();Wt.componentSizeCache=new Map;var Ut=function(){function t(){this.sceneStartTime=Date.now()}var e=t.prototype;return e.collectSceneData=function(){var t,e,n=Gt.scene;if(!n)return{currentSceneName:"No Scene",isInitialized:!1,sceneRunTime:0,sceneEntityCount:0,sceneSystemCount:0,sceneMemory:0,sceneUptime:0};var i=(Date.now()-this.sceneStartTime)/1e3,r=n.entities,s=n.entityProcessors;return{currentSceneName:n.name||"Unnamed Scene",isInitialized:n._didSceneBegin||!1,sceneRunTime:i,sceneEntityCount:(null==r||null===(t=r.buffer)||void 0===t?void 0:t.length)||0,sceneSystemCount:(null==s||null===(e=s.processors)||void 0===e?void 0:e.length)||0,sceneMemory:0,sceneUptime:i}},e.setSceneStartTime=function(t){this.sceneStartTime=t},t}(),jt=function(){function t(t,e){void 0===e&&(e=!0),this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectInterval=2e3,this.url=t,this.autoReconnect=e}var e=t.prototype;return e.setMessageHandler=function(t){this.messageHandler=t},e.connect=function(){var t=this;return new Promise((function(e,n){try{t.ws=new WebSocket(t.url),t.ws.onopen=function(n){t.handleOpen(n),e()},t.ws.onclose=function(e){t.handleClose(e)},t.ws.onerror=function(e){t.handleError(e),n(e)},t.ws.onmessage=function(e){t.handleMessage(e)}}catch(e){t.handleConnectionFailure(e),n(e)}}))},e.disconnect=function(){this.ws&&(this.autoReconnect=!1,this.ws.close(),this.ws=void 0),this.isConnected=!1},e.send=function(t){if(this.isConnected&&this.ws)try{var e="string"==typeof t?t:JSON.stringify(t);this.ws.send(e)}catch(t){}},e.getConnectionStatus=function(){return this.isConnected},e.setMaxReconnectAttempts=function(t){this.maxReconnectAttempts=t},e.setReconnectInterval=function(t){this.reconnectInterval=t},e.scheduleReconnect=function(){var t=this;this.reconnectTimer&&clearTimeout(this.reconnectTimer);var e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout((function(){t.connect().catch((function(e){t.reconnectAttempts<t.maxReconnectAttempts&&t.scheduleReconnect()}))}),e)},e.handleMessage=function(t){try{var e=JSON.parse(t.data);this.messageHandler&&this.messageHandler(e)}catch(t){}},e.handleOpen=function(t){this.isConnected=!0,this.reconnectAttempts=0,this.onOpen&&this.onOpen(t)},e.handleClose=function(t){this.isConnected=!1,this.onClose&&this.onClose(t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()},e.handleError=function(t){this.onError&&this.onError(t)},e.handleConnectionFailure=function(t){this.onError&&this.onError(t)},t}(),Ht=function(){function t(t,e){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.config=e,this.entityCollector=new Ft,this.systemCollector=new qt,this.performanceCollector=new Lt,this.componentCollector=new Wt,this.sceneCollector=new Ut,this.webSocketManager=new jt(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));var n=e.debugFrameRate||30;this.sendInterval=1e3/n,this.start()}var e=t.prototype;return e.start=function(){this.isRunning||(this.isRunning=!0,this.connectWebSocket())},e.stop=function(){this.isRunning&&(this.isRunning=!1,this.webSocketManager.disconnect())},e.updateConfig=function(t){this.config=t;var e=t.debugFrameRate||30;this.sendInterval=1e3/e,this.webSocketManager&&t.websocketUrl&&(this.webSocketManager.disconnect(),this.webSocketManager=new jt(t.websocketUrl,!1!==t.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this)),this.connectWebSocket())},e.onFrameUpdate=function(t){if(this.isRunning&&this.config.enabled){this.frameCounter++;var e=Date.now();e-this.lastSendTime>=this.sendInterval&&(this.sendDebugData(),this.lastSendTime=e)}},e.onSceneChanged=function(){this.isRunning&&this.config.enabled&&this.sendDebugData()},e.handleMessage=function(t){try{switch(t.type){case"capture_memory_snapshot":this.handleMemorySnapshotRequest();break;case"config_update":t.config&&this.updateConfig(a({},this.config,t.config));break;case"expand_lazy_object":this.handleExpandLazyObjectRequest(t);break;case"get_component_properties":this.handleGetComponentPropertiesRequest(t);break;case"get_raw_entity_list":this.handleGetRawEntityListRequest(t);break;case"get_entity_details":this.handleGetEntityDetailsRequest(t);break;case"ping":this.webSocketManager.send({type:"pong",timestamp:Date.now()})}}catch(e){t.requestId&&this.webSocketManager.send({type:"error_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleExpandLazyObjectRequest=function(t){try{var e=t.entityId,n=t.componentIndex,i=t.propertyPath,r=t.requestId;if(void 0===e||void 0===n||!i)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,error:"缺少必要参数"});var s=this.entityCollector.expandLazyObject(e,n,i);this.webSocketManager.send({type:"expand_lazy_object_response",requestId:r,data:s})}catch(e){this.webSocketManager.send({type:"expand_lazy_object_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleGetComponentPropertiesRequest=function(t){try{var e=t.entityId,n=t.componentIndex,i=t.requestId;if(void 0===e||void 0===n)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:i,error:"缺少必要参数"});var r=this.entityCollector.getComponentProperties(e,n);this.webSocketManager.send({type:"get_component_properties_response",requestId:i,data:r})}catch(e){this.webSocketManager.send({type:"get_component_properties_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleGetRawEntityListRequest=function(t){try{var e=t.requestId,n=this.entityCollector.getRawEntityList();this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e,data:n})}catch(e){this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleGetEntityDetailsRequest=function(t){try{var e=t.entityId,n=t.requestId;if(void 0===e)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:n,error:"缺少实体ID参数"});var i=this.entityCollector.getEntityDetails(e);this.webSocketManager.send({type:"get_entity_details_response",requestId:n,data:i})}catch(e){this.webSocketManager.send({type:"get_entity_details_response",requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}},e.handleMemorySnapshotRequest=function(){try{var t=this.captureMemorySnapshot();this.webSocketManager.send({type:"memory_snapshot_response",data:t})}catch(t){this.webSocketManager.send({type:"memory_snapshot_error",error:t instanceof Error?t.message:"内存快照捕获失败"})}},e.captureMemorySnapshot=function(){var t=Date.now(),e=this.entityCollector.collectEntityDataWithMemory(),n=this.collectBaseMemoryInfo(),i=Gt.scene,r=null!=i&&i.entities?this.collectComponentMemoryStats(i.entities):{totalMemory:0,componentTypes:0,totalInstances:0,breakdown:[]},s=this.collectSystemMemoryStats(),o=this.collectPoolMemoryStats(),a=this.collectPerformanceStats(),c=e.entitiesPerArchetype.reduce((function(t,e){return t+e.memory}),0);return{timestamp:t,version:"2.0",summary:{totalEntities:e.totalEntities,totalMemoryUsage:n.usedMemory,totalMemoryLimit:n.totalMemory,memoryUtilization:n.usedMemory/n.totalMemory*100,gcCollections:n.gcCollections,entityMemory:c,componentMemory:r.totalMemory,systemMemory:s.totalMemory,poolMemory:o.totalMemory},baseMemory:n,entities:{totalMemory:c,entityCount:e.totalEntities,archetypes:e.entitiesPerArchetype,largestEntities:e.topEntitiesByComponents},components:r,systems:s,pools:o,performance:a}},e.collectBaseMemoryInfo=function(){var t={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null,detailedMemory:void 0};try{var e=performance;if(e.memory){var n=e.memory;t.totalMemory=n.jsHeapSizeLimit||536870912,t.usedMemory=n.usedJSHeapSize||0,t.freeMemory=t.totalMemory-t.usedMemory,t.heapInfo={totalJSHeapSize:n.totalJSHeapSize||0,usedJSHeapSize:n.usedJSHeapSize||0,jsHeapSizeLimit:n.jsHeapSizeLimit||0}}else t.totalMemory=536870912,t.freeMemory=536870912;e.measureUserAgentSpecificMemory&&e.measureUserAgentSpecificMemory().then((function(e){t.detailedMemory=e})).catch((function(){}))}catch(t){}return t},e.collectComponentMemoryStats=function(t){for(var e,n=new Map,i=0,r=new Map,s=o(t.buffer);!(e=s()).done;){var a=e.value;if(a&&!a.destroyed&&a.components)for(var c,u=o(a.components);!(c=u()).done;){var h=Q(c.value);r.set(h,(r.get(h)||0)+1)}}for(var l,d=o(r.entries());!(l=d()).done;){var f=l.value,m=f[0],p=f[1],y=this.componentCollector.calculateDetailedComponentMemory(m),g=y*p;i+=g;for(var v,_=[],S=0,E=o(t.buffer);!(v=E()).done;){var T=v.value;if(T&&!T.destroyed&&T.components){for(var C,b=o(T.components);!(C=b()).done;){if(Q(C.value)===m&&(_.push({entityId:T.id,entityName:T.name||"Entity_"+T.id,memory:y}),++S>=100))break}if(S>=100)break}}n.set(m,{count:p,totalMemory:g,instances:_.slice(0,10)})}var M=Array.from(n.entries()).map((function(t){var e=t[0],n=t[1];return{typeName:e,instanceCount:n.count,totalMemory:n.totalMemory,averageMemory:n.totalMemory/n.count,percentage:i>0?n.totalMemory/i*100:0,largestInstances:n.instances.sort((function(t,e){return e.memory-t.memory})).slice(0,3)}})).sort((function(t,e){return e.totalMemory-t.totalMemory}));return{totalMemory:i,componentTypes:n.size,totalInstances:Array.from(n.values()).reduce((function(t,e){return t+e.count}),0),breakdown:M}},e.collectSystemMemoryStats=function(){var t=Gt.scene,e=0,n=[];try{var i=null==t?void 0:t.entityProcessors;if(i&&i.processors)for(var r,s=new Map,a=o(i.processors);!(r=a()).done;){var c=r.value,u=V(c),h=void 0;s.has(u)?h=s.get(u):(h=this.calculateQuickSystemSize(c),s.set(u,h)),e+=h,n.push({name:u,memory:h,enabled:!1!==c.enabled,updateOrder:c.updateOrder||0})}}catch(t){}return{totalMemory:e,systemCount:n.length,breakdown:n.sort((function(t,e){return e.memory-t.memory}))}},e.calculateQuickSystemSize=function(t){if(!t||"object"!=typeof t)return 64;var e=128;try{for(var n=Object.keys(t),i=0;i<Math.min(n.length,15);i++){var r=n[i];if("entities"!==r&&"scene"!==r&&"constructor"!==r){var s=t[r];e+=2*r.length,"string"==typeof s?e+=Math.min(2*s.length,100):"number"==typeof s?e+=8:"boolean"==typeof s?e+=4:Array.isArray(s)?e+=40+Math.min(8*s.length,200):"object"==typeof s&&null!==s&&(e+=64)}}}catch(t){return 128}return Math.max(e,64)},e.collectPoolMemoryStats=function(){var t=0,e=[];try{for(var n,i=o(st.getInstance().getPoolStats().entries());!(n=i()).done;){var r=n.value,s=r[0],a=r[1],c=32*a.maxSize;t+=c,e.push({typeName:s,maxSize:a.maxSize,currentSize:a.currentSize||0,estimatedMemory:c,utilization:a.currentSize?a.currentSize/a.maxSize*100:0})}}catch(t){}try{for(var u=T.getAllPoolStats(),h=0,l=Object.entries(u);h<l.length;h++){var d=l[h],f=d[0],m=d[1];t+=m.estimatedMemoryUsage,e.push({typeName:"Pool_"+f,maxSize:m.maxSize,currentSize:m.size,estimatedMemory:m.estimatedMemoryUsage,utilization:m.size/m.maxSize*100,hitRate:100*m.hitRate})}}catch(t){}return{totalMemory:t,poolCount:e.length,breakdown:e.sort((function(t,e){return e.estimatedMemory-t.estimatedMemory}))}},e.collectPerformanceStats=function(){try{var t,e=Gt.Instance._performanceMonitor;if(!e)return{enabled:!1};var n=e.getAllSystemStats(),i=e.getPerformanceWarnings();return{enabled:null!==(t=e.enabled)&&void 0!==t&&t,systemCount:n.size,warnings:i.slice(0,10),topSystems:Array.from(n.entries()).map((function(t){var e=t[0],n=t[1];return{name:e,averageTime:n.averageTime,maxTime:n.maxTime,samples:n.executionCount}})).sort((function(t,e){return e.averageTime-t.averageTime})).slice(0,5)}}catch(t){return{enabled:!1,error:t instanceof Error?t.message:String(t)}}},e.getDebugData=function(){var t=Date.now(),e=Gt.scene,n={timestamp:t,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:(null==e?void 0:e.name)||"Unknown"};if(this.config.channels.entities&&(n.entities=this.entityCollector.collectEntityData()),this.config.channels.systems){var i=Gt.Instance._performanceMonitor;n.systems=this.systemCollector.collectSystemData(i)}if(this.config.channels.performance){var r=Gt.Instance._performanceMonitor;n.performance=this.performanceCollector.collectPerformanceData(r)}return this.config.channels.components&&(n.components=this.componentCollector.collectComponentData()),this.config.channels.scenes&&(n.scenes=this.sceneCollector.collectSceneData()),n},e.connectWebSocket=function(){var t=n(l().m((function t(){return l().w((function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,t.n=1,this.webSocketManager.connect();case 1:t.n=3;break;case 2:t.p=2;case 3:return t.a(2)}}),t,this,[[0,2]])})));return function(){return t.apply(this,arguments)}}(),e.sendDebugData=function(){if(this.webSocketManager.getConnectionStatus())try{var t={type:"debug_data",data:this.getDebugData()};this.webSocketManager.send(t)}catch(t){}},t}(),Gt=function(){function t(e){var n,i,r;void 0===e&&(e={}),this._globalManagers=[],t._instance=this,this._config=a({debug:!0,enableEntitySystems:!0},e),this._timerManager=new S,t.registerGlobalManager(this._timerManager),this._performanceMonitor=E.instance,this._config.debug&&this._performanceMonitor.enable(),this._poolManager=b.getInstance(),t.entitySystemsEnabled=null===(n=this._config.enableEntitySystems)||void 0===n||n,this.debug=null===(i=this._config.debug)||void 0===i||i,null!==(r=this._config.debugConfig)&&void 0!==r&&r.enabled&&(this._debugManager=new Ht(this,this._config.debugConfig)),this.initialize()}t.getScene=function(){if(!this._instance)return null;this._instance.ensureDefaultWorld();var t=this._instance._worldManager.getWorld(this.DEFAULT_WORLD_ID);return(null==t?void 0:t.getScene(this.DEFAULT_SCENE_ID))||null},t.setScene=function(t){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");this._instance.ensureDefaultWorld();var e=this._instance._worldManager.getWorld(this.DEFAULT_WORLD_ID);return e.getScene(this.DEFAULT_SCENE_ID)&&e.removeScene(this.DEFAULT_SCENE_ID),e.createScene(this.DEFAULT_SCENE_ID,t),e.setSceneActive(this.DEFAULT_SCENE_ID,!0),this._instance.onSceneChanged(),t},t.create=function(e){if(void 0===e&&(e=!0),null==this._instance){var n="boolean"==typeof e?{debug:e,enableEntitySystems:!0}:e;this._instance=new t(n)}return this._instance},t.update=function(e){this._instance?this._instance.updateInternal(e):t._logger.warn("Core实例未创建,请先调用Core.create()")},t.registerGlobalManager=function(t){this._instance._globalManagers.push(t),t.enabled=!0},t.unregisterGlobalManager=function(t){this._instance._globalManagers.splice(this._instance._globalManagers.indexOf(t),1),t.enabled=!1},t.getGlobalManager=function(t){for(var e,n=o(this._instance._globalManagers);!(e=n()).done;){var i=e.value;if(i instanceof t)return i}return null},t.schedule=function(t,e,n,i){if(void 0===e&&(e=!1),!i)throw new Error("onTime callback is required");return this._instance._timerManager.schedule(t,e,n,i)},t.enableDebug=function(e){this._instance?(this._instance._debugManager?this._instance._debugManager.updateConfig(e):this._instance._debugManager=new Ht(this._instance,e),this._instance._config.debugConfig=e):t._logger.warn("Core实例未创建,请先调用Core.create()")},t.disableDebug=function(){this._instance&&(this._instance._debugManager&&(this._instance._debugManager.stop(),this._instance._debugManager=void 0),this._instance._config.debugConfig&&(this._instance._config.debugConfig.enabled=!1))},t.getDebugData=function(){var t;return null!==(t=this._instance)&&void 0!==t&&t._debugManager?this._instance._debugManager.getDebugData():null},t.getWorldManager=function(){if(!this._instance)throw new Error("Core实例未创建,请先调用Core.create()");return this._instance._worldManager||(this._instance._worldManager=Pt.getInstance({maxWorlds:50,autoCleanup:!0,cleanupInterval:6e4,debug:this._instance._config.debug})),this._instance._worldManager},t.enableWorldManager=function(){return this.getWorldManager()};var e=t.prototype;return e.ensureDefaultWorld=function(){this._worldManager||(this._worldManager=Pt.getInstance({maxWorlds:1,autoCleanup:!1,cleanupInterval:0,debug:this._config.debug})),this._worldManager.getWorld(t.DEFAULT_WORLD_ID)||(this._worldManager.createWorld(t.DEFAULT_WORLD_ID,{name:"DefaultWorld",maxScenes:1,autoCleanup:!1}),this._worldManager.setWorldActive(t.DEFAULT_WORLD_ID,!0))},e.onSceneChanged=function(){var e=this;g.sceneChanged();var n=t.getScene();n&&n.querySystem&&n.eventSystem&&(this._ecsAPI=Ot(n,n.querySystem,n.eventSystem)),this._debugManager&&queueMicrotask((function(){var t;null===(t=e._debugManager)||void 0===t||t.onSceneChanged()}))},e.initialize=function(){},e.updateInternal=function(e){if(!t.paused){var n=this._performanceMonitor.startMonitoring("Core.update");g.update(e),"updateFPS"in this._performanceMonitor&&"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(g.deltaTime);for(var i,r=this._performanceMonitor.startMonitoring("GlobalManagers.update"),s=o(this._globalManagers);!(i=s()).done;){var a=i.value;a.enabled&&a.update()}if(this._performanceMonitor.endMonitoring("GlobalManagers.update",r,this._globalManagers.length),this._poolManager.update(),this._worldManager){for(var c,u=this._performanceMonitor.startMonitoring("Worlds.update"),h=0,l=o(this._worldManager.getActiveWorlds());!(c=l()).done;){var d=c.value;d.updateGlobalSystems(),d.updateScenes(),h+=d.getStats().totalEntities}this._performanceMonitor.endMonitoring("Worlds.update",u,h)}this._debugManager&&this._debugManager.onFrameUpdate(e),this._performanceMonitor.endMonitoring("Core.update",n)}},s(t,null,[{key:"Instance",get:function(){return this._instance}},{key:"scene",get:function(){return this.getScene()}},{key:"ecsAPI",get:function(){var t;return(null===(t=this._instance)||void 0===t?void 0:t._ecsAPI)||null}},{key:"isDebugEnabled",get:function(){var t;return(null===(t=this._instance)||void 0===t||null===(t=t._config.debugConfig)||void 0===t?void 0:t.enabled)||!1}}])}();Gt.paused=!1,Gt.DEFAULT_WORLD_ID="__default__",Gt.DEFAULT_SCENE_ID="__main__",Gt._logger=D("Core");var Yt=function(t,e){this.func=t,this.context=e},Qt=function(){function t(){this._messageTable=new Map}var e=t.prototype;return e.addObserver=function(t,e,n){var i=this._messageTable.get(t);i||(i=[],this._messageTable.set(t,i)),this.hasObserver(t,e)||i.push(new Yt(e,n))},e.removeObserver=function(t,e){var n=this._messageTable.get(t);if(n){var i=n.findIndex((function(t){return t.func==e}));-1!=i&&n.splice(i,1)}},e.emit=function(t){var e=this._messageTable.get(t);if(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(var s,a=o(e);!(s=a()).done;){var c,u=s.value;(c=u.func).call.apply(c,[u.context].concat(i))}}},e.hasObserver=function(t,e){var n=this._messageTable.get(t);return!!n&&n.some((function(t){return t.func===e}))},e.removeAllObservers=function(t){void 0!==t?this._messageTable.delete(t):this._messageTable.clear()},e.dispose=function(){this._messageTable.clear()},e.getEventTypeCount=function(){return this._messageTable.size},e.getObserverCount=function(t){var e=this._messageTable.get(t);return e?e.length:0},t}(),Vt=function(){function t(){this._enabled=!0,this._updateOrder=0,this.id=t._idGenerator++}var e=t.prototype;return e.onAddedToEntity=function(){},e.onRemovedFromEntity=function(){},e.onEnabled=function(){},e.onDisabled=function(){},e.update=function(){},s(t,[{key:"enabled",get:function(){return this.entity?this.entity.enabled&&this._enabled:this._enabled},set:function(t){this._enabled!==t&&(this._enabled=t,this._enabled?this.onEnabled():this.onDisabled())}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(t){this._updateOrder=t}}])}();Vt._idGenerator=0;var Xt=function(){function t(){this.condition={all:[],any:[],none:[]}}t.all=function(){var e=new t;return e.all.apply(e,arguments)},t.any=function(){var e=new t;return e.any.apply(e,arguments)},t.none=function(){var e=new t;return e.none.apply(e,arguments)},t.byTag=function(e){return(new t).withTag(e)},t.byName=function(e){return(new t).withName(e)},t.byComponent=function(e){return(new t).withComponent(e)},t.complex=function(){return new t},t.empty=function(){return new t};var e=t.prototype;return e.all=function(){var t;return(t=this.condition.all).push.apply(t,arguments),this},e.any=function(){var t;return(t=this.condition.any).push.apply(t,arguments),this},e.none=function(){var t;return(t=this.condition.none).push.apply(t,arguments),this},e.exclude=function(){return this.none.apply(this,arguments)},e.one=function(){return this.any.apply(this,arguments)},e.withTag=function(t){return this.condition.tag=t,this},e.withName=function(t){return this.condition.name=t,this},e.withComponent=function(t){return this.condition.component=t,this},e.withoutTag=function(){return delete this.condition.tag,this},e.withoutName=function(){return delete this.condition.name,this},e.withoutComponent=function(){return delete this.condition.component,this},e.getCondition=function(){return{all:[].concat(this.condition.all),any:[].concat(this.condition.any),none:[].concat(this.condition.none),tag:this.condition.tag,name:this.condition.name,component:this.condition.component}},e.isEmpty=function(){return 0===this.condition.all.length&&0===this.condition.any.length&&0===this.condition.none.length&&void 0===this.condition.tag&&void 0===this.condition.name&&void 0===this.condition.component},e.reset=function(){return this.condition.all.length=0,this.condition.any.length=0,this.condition.none.length=0,delete this.condition.tag,delete this.condition.name,delete this.condition.component,this},e.clone=function(){var e,n,i,r=new t;return(e=r.condition.all).push.apply(e,this.condition.all),(n=r.condition.any).push.apply(n,this.condition.any),(i=r.condition.none).push.apply(i,this.condition.none),void 0!==this.condition.tag&&(r.condition.tag=this.condition.tag),void 0!==this.condition.name&&(r.condition.name=this.condition.name),void 0!==this.condition.component&&(r.condition.component=this.condition.component),r},e.toString=function(){var t=[];return this.condition.all.length>0&&t.push("all("+this.condition.all.map((function(t){return G(t)})).join(", ")+")"),this.condition.any.length>0&&t.push("any("+this.condition.any.map((function(t){return G(t)})).join(", ")+")"),this.condition.none.length>0&&t.push("none("+this.condition.none.map((function(t){return G(t)})).join(", ")+")"),void 0!==this.condition.tag&&t.push("tag("+this.condition.tag+")"),void 0!==this.condition.name&&t.push("name("+this.condition.name+")"),void 0!==this.condition.component&&t.push("component("+G(this.condition.component)+")"),"Matcher["+t.join(" & ")+"]"},t}(),Zt=function(){function t(t){this._updateOrder=0,this._enabled=!0,this._performanceMonitor=E.instance,this._initialized=!1,this._trackedEntities=new Set,this._scene=null,this._matcher=t||Xt.empty(),this._systemName=V(this)}var e=t.prototype;return e.setUpdateOrder=function(t){this._updateOrder=t,this.scene&&this.scene.entityProcessors&&this.scene.entityProcessors.setDirty()},e.initialize=function(){this._initialized||(this._initialized=!0,this.scene&&this.queryEntities(),this.onInitialize())},e.onInitialize=function(){},e.reset=function(){this._initialized=!1,this._trackedEntities.clear()},e.queryEntities=function(){var t;if(null===(t=this.scene)||void 0===t||!t.querySystem||!this._matcher)return[];var e=this._matcher.getCondition(),n=this.scene.querySystem,i=[];return i=this._matcher.isEmpty()?n.getAllEntities():this.isSingleCondition(e)?this.executeSingleConditionQuery(e,n):this.executeComplexQuery(e,n),this.updateEntityTracking(i),i},e.isSingleCondition=function(t){return 1===(t.all.length>0?1:0)+(t.any.length>0?1:0)+(t.none.length>0?1:0)+(void 0!==t.tag?1:0)+(void 0!==t.name?1:0)+(void 0!==t.component?1:0)},e.executeSingleConditionQuery=function(t,e){return void 0!==t.tag?e.queryByTag(t.tag).entities:void 0!==t.name?e.queryByName(t.name).entities:void 0!==t.component?e.queryByComponent(t.component).entities:t.all.length>0&&0===t.any.length&&0===t.none.length?e.queryAll.apply(e,t.all).entities:0===t.all.length&&t.any.length>0&&0===t.none.length?e.queryAny.apply(e,t.any).entities:0===t.all.length&&0===t.any.length&&t.none.length>0?e.queryNone.apply(e,t.none).entities:[]},e.executeComplexQueryWithIdSets=function(t,e){var n=null;if(void 0!==t.tag){var i=e.queryByTag(t.tag);n=this.extractEntityIds(i.entities)}if(void 0!==t.name){var r=this.extractEntityIds(e.queryByName(t.name).entities);n=n?this.intersectIdSets(n,r):r}if(void 0!==t.component){var s=this.extractEntityIds(e.queryByComponent(t.component).entities);n=n?this.intersectIdSets(n,s):s}if(t.all.length>0){var o=this.extractEntityIds(e.queryAll.apply(e,t.all).entities);n=n?this.intersectIdSets(n,o):o}if(t.any.length>0){var a=this.extractEntityIds(e.queryAny.apply(e,t.any).entities);n=n?this.intersectIdSets(n,a):a}if(t.none.length>0){n||(n=this.extractEntityIds(e.getAllEntities()));var c=e.queryAny.apply(e,t.none),u=this.extractEntityIds(c.entities);n=this.differenceIdSets(n,u)}return n?this.idSetToEntityArray(n,e.getAllEntities()):[]},e.extractEntityIds=function(t){for(var e=new Set,n=0;n<t.length;n++)e.add(t[n].id);return e},e.intersectIdSets=function(t,e){for(var n,i=t.size<=e.size?[t,e]:[e,t],r=i[0],s=i[1],a=new Set,c=o(r);!(n=c()).done;){var u=n.value;s.has(u)&&a.add(u)}return a},e.differenceIdSets=function(t,e){for(var n,i=new Set,r=o(t);!(n=r()).done;){var s=n.value;e.has(s)||i.add(s)}return i},e.idSetToEntityArray=function(t,e){for(var n,i=new Map,r=o(e);!(n=r()).done;){var s=n.value;i.set(s.id,s)}for(var a,c=[],u=o(t);!(a=u()).done;){var h=a.value,l=i.get(h);l&&c.push(l)}return c},e.executeComplexQuery=function(t,e){return this.executeComplexQueryWithIdSets(t,e)},e.update=function(){if(this._enabled&&this.onCheckProcessing()){var t=this._performanceMonitor.startMonitoring(this._systemName),e=0;try{this.onBegin();var n=this.queryEntities();e=n.length,this.process(n)}finally{this._performanceMonitor.endMonitoring(this._systemName,t,e)}}},e.lateUpdate=function(){if(this._enabled&&this.onCheckProcessing()){var t=this._performanceMonitor.startMonitoring(this._systemName+"_Late"),e=0;try{var n=this.queryEntities();e=n.length,this.lateProcess(n),this.onEnd()}finally{this._performanceMonitor.endMonitoring(this._systemName+"_Late",t,e)}}},e.onBegin=function(){},e.process=function(t){},e.lateProcess=function(t){},e.onEnd=function(){},e.onCheckProcessing=function(){return!0},e.getPerformanceData=function(){return this._performanceMonitor.getSystemData(this._systemName)},e.getPerformanceStats=function(){return this._performanceMonitor.getSystemStats(this._systemName)},e.resetPerformanceData=function(){this._performanceMonitor.resetSystem(this._systemName)},e.toString=function(){var t=this.entities.length,e=this.getPerformanceData(),n=e?" ("+e.executionTime.toFixed(2)+"ms)":"";return this._systemName+"["+t+" entities]"+n},e.updateEntityTracking=function(t){for(var e,n=new Set(t),i=o(t);!(e=i()).done;){var r=e.value;this._trackedEntities.has(r)||(this._trackedEntities.add(r),this.onAdded(r))}for(var s,a=o(this._trackedEntities);!(s=a()).done;){var c=s.value;n.has(c)||(this._trackedEntities.delete(c),this.onRemoved(c))}},e.onAdded=function(t){},e.onRemoved=function(t){},s(t,[{key:"entities",get:function(){return this.queryEntities()}},{key:"updateOrder",get:function(){return this._updateOrder},set:function(t){this.setUpdateOrder(t)}},{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled=t}},{key:"systemName",get:function(){return this._systemName}},{key:"scene",get:function(){return this._scene},set:function(t){this._scene=t}},{key:"matcher",get:function(){return this._matcher}}])}(),Jt=function(t){function e(e){return t.call(this,e)||this}return u(e,t),e.prototype.process=function(t){this.processSystem()},e}(Zt),Kt=function(t){function e(e){return t.call(this,e)||this}return u(e,t),e.prototype.process=function(t){},e}(Zt),$t=function(t){function e(e,n){var i;return(i=t.call(this,n)||this).acc=0,i.intervalRemainder=0,i.interval=e,i}u(e,t);var n=e.prototype;return n.onCheckProcessing=function(){return this.acc+=g.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)},n.getIntervalDelta=function(){return this.interval+this.intervalRemainder},e}(Zt),te=function(){function t(t){this.entityManager=t,this._allComponents=[],this._anyComponents=[],this._withoutComponents=[],this._withTags=[],this._withoutTags=[],this._activeOnly=!1,this._enabledOnly=!1,this._customPredicates=[]}var e=t.prototype;return e.withAll=function(){var t;return(t=this._allComponents).push.apply(t,arguments),this},e.withAny=function(){var t;return(t=this._anyComponents).push.apply(t,arguments),this},e.without=function(){var t;return(t=this._withoutComponents).push.apply(t,arguments),this},e.withTag=function(t){return this._withTags.push(t),this},e.withoutTag=function(t){return this._withoutTags.push(t),this},e.active=function(){return this._activeOnly=!0,this},e.enabled=function(){return this._enabledOnly=!0,this},e.where=function(t){return this._customPredicates.push(t),this},e.execute=function(){var t=this,e=[];if(this._allComponents.length>0){var n=this.entityManager.queryWithComponentIndex(this._allComponents,"AND");e=Array.from(n)}else if(this._anyComponents.length>0){var i=this.entityManager.queryWithComponentIndex(this._anyComponents,"OR");e=Array.from(i)}else e=this.entityManager.getAllEntities();return e.filter((function(e){return t.matchesEntity(e)}))},e.first=function(){var t=this;return this.entityManager.getAllEntities().find((function(e){return t.matchesEntity(e)}))||null},e.count=function(){var t=this;return this.entityManager.getAllEntities().filter((function(e){return t.matchesEntity(e)})).length},e.forEach=function(t){var e=this;this.entityManager.getAllEntities().forEach((function(n){e.matchesEntity(n)&&t(n)}))},e.matchesEntity=function(t){if(this._activeOnly&&!t.active)return!1;if(this._enabledOnly&&!t.enabled)return!1;if(this._allComponents.length>0)for(var e,n=o(this._allComponents);!(e=n()).done;){var i=e.value;if(!t.hasComponent(i))return!1}if(this._anyComponents.length>0){for(var r,s=!1,a=o(this._anyComponents);!(r=a()).done;){var c=r.value;if(t.hasComponent(c)){s=!0;break}}if(!s)return!1}if(this._withoutComponents.length>0)for(var u,h=o(this._withoutComponents);!(u=h()).done;){var l=u.value;if(t.hasComponent(l))return!1}if(this._withTags.length>0&&!this._withTags.includes(t.tag))return!1;if(this._withoutTags.length>0&&this._withoutTags.includes(t.tag))return!1;if(this._customPredicates.length>0)for(var d,f=o(this._customPredicates);!(d=f()).done;){if(!(0,d.value)(t))return!1}return!0},t}(),ee=function(){function t(){var t=this;this._entities=new Map,this._entitiesByName=new Map,this._entitiesByTag=new Map,this._destroyedEntities=new Set,this._identifierPool=new it,this._componentIndexManager=new lt,this._archetypeSystem=new dt,this._dirtyTrackingSystem=new mt,this._eventBus=new Tt(!1),$.eventBus=this._eventBus,this._eventBus.on("component:added",(function(e){var n=t._entities.get(e.entityId);n&&(t._componentIndexManager.addEntity(n),t._archetypeSystem.addEntity(n))})),this._eventBus.on("component:removed",(function(e){var n=t._entities.get(e.entityId);n&&(t._componentIndexManager.removeEntity(n),t._archetypeSystem.removeEntity(n))}))}var e=t.prototype;return e.createEntity=function(t){var e,n=this._identifierPool.checkOut();t||(t="Entity_"+n);var i=new $(t,n);return this._entities.set(n,i),this.updateNameIndex(i,!0),this.updateTagIndex(i,!0),i.components.length>0&&(this._componentIndexManager.addEntity(i),this._archetypeSystem.addEntity(i),this._dirtyTrackingSystem.markDirty(i,ut.COMPONENT_ADDED)),this._eventBus.emitEntityCreated({timestamp:Date.now(),source:"EntityManager",entityId:i.id,entityName:i.name,entityTag:null===(e=i.tag)||void 0===e?void 0:e.toString()}),i},e.createEntitiesBatch=function(t,e,n){if(void 0===e&&(e="Entity"),void 0===n&&(n=!1),t<=0)return[];for(var i=[],r=0;r<t;r++){var s=this._identifierPool.checkOut(),a=new $(e+"_"+s,s);i.push(a),this._entities.set(s,a)}for(var c=0,u=i;c<u.length;c++){var h=u[c];this.updateNameIndex(h,!0),this.updateTagIndex(h,!0),h.components.length>0&&(this._componentIndexManager.addEntity(h),this._archetypeSystem.addEntity(h),this._dirtyTrackingSystem.markDirty(h,ut.COMPONENT_ADDED))}if(!n)for(var l,d=Date.now(),f=o(i);!(l=f()).done;){var m,p=l.value;this._eventBus.emitEntityCreated({timestamp:d,source:"EntityManager",entityId:p.id,entityName:p.name,entityTag:null===(m=p.tag)||void 0===m?void 0:m.toString()})}return i},e.destroyEntity=function(t){var e,n=null;return!!(n="string"==typeof t?this.getEntityByName(t):"number"==typeof t?this._entities.get(t)||null:this._entities.get(t.id)||null)&&(this._destroyedEntities.add(n.id),this.updateNameIndex(n,!1),this.updateTagIndex(n,!1),this._componentIndexManager.removeEntity(n),this._archetypeSystem.removeEntity(n),this._dirtyTrackingSystem.markDirty(n,ut.COMPONENT_REMOVED),this._eventBus.emitEntityDestroyed({timestamp:Date.now(),source:"EntityManager",entityId:n.id,entityName:n.name,entityTag:null===(e=n.tag)||void 0===e?void 0:e.toString()}),n.destroy(),this._entities.delete(n.id),this._identifierPool.checkIn(n.id),!0)},e.getAllEntities=function(){return Array.from(this._entities.values())},e.getEntity=function(t){var e="string"==typeof t?parseInt(t):t;return this._entities.get(e)||null},e.getEntityByName=function(t){var e=this._entitiesByName.get(t);return e&&e.length>0?e[0]:null},e.getEntitiesByTag=function(t){return Array.from(this._entities.values()).filter((function(e){return e.tag===t}))},e.getEntitiesWithComponent=function(t){var e=this._componentIndexManager.query(t);return Array.from(e)},e.query=function(){return new te(this)},e.queryWithComponentIndex=function(t,e){return this._componentIndexManager.queryMultiple(t,e)},e.markEntityDirty=function(t,e){this._dirtyTrackingSystem.markDirty(t,ut.COMPONENT_MODIFIED,e)},e.getOptimizationStats=function(){return{componentIndex:this._componentIndexManager.getStats(),archetypeSystem:this._archetypeSystem.getAllArchetypes().map((function(t){return{id:t.id,componentTypes:t.componentTypes.map((function(t){return t.name})),entityCount:t.entities.length}})),dirtyTracking:this._dirtyTrackingSystem.getStats()}},e.updateNameIndex=function(t,e){if(t.name)if(e){var n=this._entitiesByName.get(t.name);n||(n=[],this._entitiesByName.set(t.name,n)),n.push(t)}else{var i=this._entitiesByName.get(t.name);if(i){var r=i.indexOf(t);-1!==r&&(i.splice(r,1),0===i.length&&this._entitiesByName.delete(t.name))}}},e.updateTagIndex=function(t,e){if(e){var n=this._entitiesByTag.get(t.tag);n||(n=[],this._entitiesByTag.set(t.tag,n)),n.push(t)}else{var i=this._entitiesByTag.get(t.tag);if(i){var r=i.indexOf(t);-1!==r&&(i.splice(r,1),0===i.length&&this._entitiesByTag.delete(t.tag))}}},s(t,[{key:"entityCount",get:function(){return this._entities.size}},{key:"activeEntityCount",get:function(){for(var t,e=0,n=o(this._entities.values());!(t=n()).done;){var i=t.value;i.active&&!i.isDestroyed&&e++}return e}},{key:"eventBus",get:function(){return this._eventBus}}])}(),ne=function(){function t(){}return t.getType=function(t){return t.constructor},t}(),ie=function(){function t(){}return t.toNumber=function(t){return null==t?0:Number(t)},t}();export{dt as ArchetypeSystem,Mt as AsyncEventHandler,M as BitMask64Utils,zt as Bits,W as COMPONENT_TYPE_NAME,w as Colors,Vt as Component,Wt as ComponentDataCollector,ht as ComponentIndex,lt as ComponentIndexManager,rt as ComponentPool,st as ComponentPoolManager,X as ComponentRegistry,ct as ComponentSparseSet,Z as ComponentStorage,Bt as ComponentTypeManager,I as ConsoleLogger,Gt as Core,Ht as DebugManager,ut as DirtyFlag,mt as DirtyTrackingSystem,j as ECSComponent,pt as ECSEventType,Dt as ECSFluentAPI,H as ECSSystem,St as EVENT_TYPES,Qt as Emitter,R as EnableSoA,$ as Entity,Ft as EntityDataCollector,et as EntityList,ee as EntityManager,nt as EntityProcessorList,te as EntityQueryBuilder,Zt as EntitySystem,Tt as EventBus,bt as EventHandler,yt as EventPriority,Et as EventTypeValidator,B as Float32,z as Float64,Yt as FuncPack,Ct as GlobalEventBus,y as GlobalManager,P as HighPrecision,it as IdentifierPool,F as Int32,$t as IntervalSystem,C as LogLevel,x as Logger,A as LoggerManager,Xt as Matcher,ie as NumberExtension,Kt as PassiveSystem,Lt as PerformanceDataCollector,E as PerformanceMonitor,v as PerformanceWarningType,T as Pool,b as PoolManager,Jt as ProcessingSystem,gt as QuerySystem,U as SYSTEM_TYPE_NAME,wt as Scene,Ut as SceneDataCollector,q as SerializeMap,L as SoAStorage,ot as SparseSet,qt as SystemDataCollector,g as Time,_ as Timer,S as TimerManager,_t as TypeSafeEventSystem,ne as TypeUtils,jt as WebSocketManager,Nt as World,Pt as WorldManager,Ot as createECSAPI,D as createLogger,Q as getComponentInstanceTypeName,G as getComponentTypeName,V as getSystemInstanceTypeName,Y as getSystemTypeName,k as resetLoggerColors,N as setGlobalLogLevel,O as setLoggerColors};
2
4
  //# sourceMappingURL=index.mjs.map