@esengine/ecs-framework 2.1.24 → 2.1.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +2 -0
- package/index.cjs.map +1 -0
- package/index.d.ts +353 -3
- package/index.mjs +2 -0
- package/index.mjs.map +1 -0
- package/package.json +9 -9
- package/index.js +0 -2
- package/index.js.map +0 -1
- package/index.umd.js +0 -2
- package/index.umd.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@esengine/ecs-framework",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.26",
|
|
4
4
|
"description": "用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架",
|
|
5
|
-
"main": "index.
|
|
6
|
-
"module": "index.
|
|
5
|
+
"main": "index.cjs",
|
|
6
|
+
"module": "index.mjs",
|
|
7
7
|
"types": "index.d.ts",
|
|
8
|
-
"type": "module",
|
|
9
8
|
"exports": {
|
|
10
9
|
".": {
|
|
11
|
-
"import": "./index.
|
|
10
|
+
"import": "./index.mjs",
|
|
11
|
+
"require": "./index.cjs",
|
|
12
12
|
"types": "./index.d.ts"
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
15
|
"files": [
|
|
16
|
-
"index.
|
|
17
|
-
"index.
|
|
18
|
-
"index.
|
|
19
|
-
"index.
|
|
16
|
+
"index.mjs",
|
|
17
|
+
"index.mjs.map",
|
|
18
|
+
"index.cjs",
|
|
19
|
+
"index.cjs.map",
|
|
20
20
|
"index.d.ts",
|
|
21
21
|
"README.md",
|
|
22
22
|
"LICENSE",
|
package/index.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
class t{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 e{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}}e.deltaTime=0,e.unscaledDeltaTime=0,e.totalTime=0,e.unscaledTotalTime=0,e.timeScale=1,e.frameCount=0;class s{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+=e.deltaTime,this._isDone}initialize(t,e,s,n){this._timeInSeconds=t,this._repeats=e,this.context=s,this._onTime=n.bind(s)}unload(){this.context=null,this._onTime=null}}class n extends t{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,i){let o=new s;return o.initialize(t,e,n,i),this._timers.push(o),o}}var i,o,r,a,c,h,m;!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"}(i||(i={}));class l{static get instance(){return l._instance||(l._instance=new l),l._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,s=0){if(!this._isEnabled||0===e)return;const n=performance.now(),i=n-e,o={name:t,executionTime:i,entityCount:s,averageTimePerEntity:s>0?i/s:0,lastUpdateTime:n};this._systemData.set(t,o),this.updateStats(t,i)}updateStats(t,e){let s=this._systemStats.get(t);s||(s={totalTime:0,averageTime:0,minTime:Number.MAX_VALUE,maxTime:0,executionCount:0,recentTimes:[],standardDeviation:0,percentile95:0,percentile99:0},this._systemStats.set(t,s)),s.totalTime+=e,s.executionCount++,s.averageTime=s.totalTime/s.executionCount,s.minTime=Math.min(s.minTime,e),s.maxTime=Math.max(s.maxTime,e),s.recentTimes.push(e),s.recentTimes.length>this._maxRecentSamples&&s.recentTimes.shift(),this.calculateAdvancedStats(s)}calculateAdvancedStats(t){if(0===t.recentTimes.length)return;const e=t.recentTimes.reduce(((t,e)=>t+e),0)/t.recentTimes.length,s=t.recentTimes.reduce(((t,s)=>t+Math.pow(s-e,2)),0)/t.recentTimes.length;t.standardDeviation=Math.sqrt(s);const n=[...t.recentTimes].sort(((t,e)=>t-e)),i=n.length;t.percentile95=n[Math.floor(.95*i)]||0,t.percentile99=n[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[s,n]of e){const e=this._systemData.get(s);t.push(`System: ${s}`),t.push(` Current: ${e?.executionTime.toFixed(2)}ms (${e?.entityCount} entities)`),t.push(` Average: ${n.averageTime.toFixed(2)}ms`),t.push(` Min/Max: ${n.minTime.toFixed(2)}ms / ${n.maxTime.toFixed(2)}ms`),t.push(` Total: ${n.totalTime.toFixed(2)}ms (${n.executionCount} calls)`),e?.averageTimePerEntity&&e.averageTimePerEntity>0&&t.push(` Per Entity: ${e.averageTimePerEntity.toFixed(4)}ms`),t.push("")}const s=Array.from(this._systemData.values()).reduce(((t,e)=>t+e.executionTime),0);return t.push(`Total Frame Time: ${s.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[s,n]of this._systemData.entries())n.executionTime>t&&e.push(`${s}: ${n.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 u{constructor(t,e=100,s=1024){this._objects=[],this._createFn=t,this._maxSize=e,this._objectSize=s,this._stats={size:0,maxSize:e,totalCreated:0,totalObtained:0,totalReleased:0,hitRate:0,estimatedMemoryUsage:0}}static getPool(t,e=100,s=1024){let n=this._pools.get(t);return n||(n=new u((()=>new t),e,s),this._pools.set(t,n)),n}obtain(){if(this._stats.totalObtained++,this._objects.length>0){const t=this._objects.pop();return this._stats.size--,this._updateHitRate(),this._updateMemoryUsage(),t}const t=this._createFn();return this._stats.totalCreated++,this._updateHitRate(),t}free(t){this._objects.length<this._maxSize&&(t.reset(),this._objects.push(t),this._stats.size++,this._stats.totalReleased++,this._updateMemoryUsage())}warmUp(t){const e=Math.min(t,this._maxSize);for(;this._objects.length<e;){const t=this._createFn();this._stats.totalCreated++,this._objects.push(t),this._stats.size++}this._updateMemoryUsage()}clear(){this._objects.length=0,this._stats.size=0,this._updateMemoryUsage()}get size(){return this._objects.length}get maxSize(){return this._maxSize}set maxSize(t){for(this._maxSize=t,this._stats.maxSize=t;this._objects.length>this._maxSize;)this._objects.pop(),this._stats.size--;this._updateMemoryUsage()}getStats(){return{...this._stats}}resetStats(){this._stats.totalCreated=0,this._stats.totalObtained=0,this._stats.totalReleased=0,this._stats.hitRate=0}_updateHitRate(){if(this._stats.totalObtained>0){const t=this._stats.totalObtained-this._stats.totalCreated;this._stats.hitRate=t/this._stats.totalObtained}}_updateMemoryUsage(){this._stats.estimatedMemoryUsage=this._stats.size*this._objectSize}static obtain(t){return this.getPool(t).obtain()}static free(t,e){this.getPool(t).free(e)}static warmUp(t,e){this.getPool(t).warmUp(e)}static clearPool(t){const e=this._pools.get(t);e&&e.clear()}static clearAllPools(){for(const t of this._pools.values())t.clear();this._pools.clear()}static getStats(){const t={};for(const[e,s]of this._pools.entries()){t[e.name||"Unknown"]=s.getStats()}return t}static getTotalMemoryUsage(){let t=0;for(const e of this._pools.values())t+=e.getStats().estimatedMemoryUsage;return t}static getPerformanceReport(){const t=this.getStats(),e=[];e.push("=== Object Pool Performance Report ==="),e.push(`Total Memory Usage: ${(this.getTotalMemoryUsage()/1024/1024).toFixed(2)} MB`),e.push("");for(const[s,n]of Object.entries(t))e.push(`${s}:`),e.push(` Size: ${n.size}/${n.maxSize}`),e.push(` Hit Rate: ${(100*n.hitRate).toFixed(1)}%`),e.push(` Total Created: ${n.totalCreated}`),e.push(` Total Obtained: ${n.totalObtained}`),e.push(` Memory: ${(n.estimatedMemoryUsage/1024).toFixed(1)} KB`),e.push("");return e.join("\n")}}u._pools=new Map;class p{constructor(t,e,s=[10,50,200],n=1024){this.pools=[],this.totalObtained=0,this.totalReleased=0,this.createFn=t,this.resetFn=e,this.tierSizes=s;for(const e of s)this.pools.push(new u(t,e,n))}obtain(){this.totalObtained++;for(const t of this.pools)if(t.size>0)return t.obtain();return this.createFn()}release(t){this.totalReleased++,this.resetFn(t);for(const e of this.pools)if(e.size<e.maxSize)return void e.free(t)}warmUp(t){let e=t;for(const t of this.pools){const s=Math.min(e,t.maxSize);if(t.warmUp(s),e-=s,e<=0)break}}clear(){for(const t of this.pools)t.clear()}getStats(){let t=0,e=0,s=0;const n=[];for(const i of this.pools){const o=i.getStats();n.push(o),t+=o.size,e+=o.maxSize,s+=o.estimatedMemoryUsage}return{totalSize:t,totalMaxSize:e,totalMemoryUsage:s,tierStats:n,hitRate:this.totalObtained>0?(this.totalObtained-this.getTotalCreated())/this.totalObtained:0}}getTotalCreated(){return this.pools.reduce(((t,e)=>t+e.getStats().totalCreated),0)}}class d{constructor(){this.pools=new Map,this.autoCompactInterval=6e4,this.lastCompactTime=0}static getInstance(){return d.instance||(d.instance=new d),d.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)}compactAllPools(){for(const t of this.pools.values())t instanceof u&&t.resetStats()}getAllStats(){const t=new Map;for(const[e,s]of this.pools.entries())(s instanceof u||s instanceof p)&&t.set(e,s.getStats());return t}generateReport(){const t=[];t.push("=== Pool Manager Report ===");let e=0;for(const[s,n]of this.pools.entries())if(t.push(`\n${s}:`),n instanceof u){const s=n.getStats();t.push(" Type: Standard Pool"),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`),e+=s.estimatedMemoryUsage}else if(n instanceof p){const s=n.getStats();t.push(" Type: Tiered Pool"),t.push(` Total Size: ${s.totalSize}/${s.totalMaxSize}`),t.push(` Hit Rate: ${(100*s.hitRate).toFixed(1)}%`),t.push(` Memory: ${(s.totalMemoryUsage/1024).toFixed(1)} KB`),e+=s.totalMemoryUsage}return t.push(`\nTotal Memory Usage: ${(e/1024/1024).toFixed(2)} MB`),t.join("\n")}}class y{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),e}static getBitMask(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return BigInt(1)<<BigInt(e)}static getBitIndex(t){const e=this.componentTypes.get(t);if(void 0===e)throw new Error(`Component type ${t.name} is not registered`);return e}static isRegistered(t){return this.componentTypes.has(t)}static getAllRegisteredTypes(){return new Map(this.componentTypes)}}y.componentTypes=new Map,y.nextBitIndex=0,y.maxComponents=64;class g{constructor(t){this.components=[],this.entityToIndex=new Map,this.indexToEntity=[],this.freeIndices=[],this._size=0,this.componentType=t,y.isRegistered(t)||y.register(t)}addComponent(t,e){if(this.entityToIndex.has(t))throw new Error(`Entity ${t} already has component ${this.componentType.name}`);let s;this.freeIndices.length>0?(s=this.freeIndices.pop(),this.components[s]=e,this.indexToEntity[s]=t):(s=this.components.length,this.components.push(e),this.indexToEntity.push(t)),this.entityToIndex.set(t,s),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 s=this.components[e];return this.entityToIndex.delete(t),this.components[e]=null,this.freeIndices.push(e),this._size--,s}forEach(t){for(let e=0;e<this.components.length;e++){const s=this.components[e];s&&t(s,this.indexToEntity[e],e)}}getDenseArray(){const t=[],e=[];for(let s=0;s<this.components.length;s++){const n=this.components[s];n&&(t.push(n),e.push(this.indexToEntity[s]))}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=[],s=new Map;let n=0;for(let i=0;i<this.components.length;i++){const o=this.components[i];o&&(t[n]=o,e[n]=this.indexToEntity[i],s.set(this.indexToEntity[i],n),n++)}this.components=t,this.indexToEntity=e,this.entityToIndex=s,this.freeIndices.length=0}getStats(){const t=this.components.length,e=this._size,s=this.freeIndices.length;return{totalSlots:t,usedSlots:e,freeSlots:s,fragmentation:t>0?s/t:0}}}class f{constructor(){this.storages=new Map}getStorage(t){let e=this.storages.get(t);return e||(e=new g(t),this.storages.set(t,e)),e}addComponent(t,e){const s=e.constructor;this.getStorage(s).addComponent(t,e)}getComponent(t,e){const s=this.storages.get(e);return s?s.getComponent(t):null}hasComponent(t,e){const s=this.storages.get(e);return!!s&&s.hasComponent(t)}removeComponent(t,e){const s=this.storages.get(e);return s?s.removeComponent(t):null}removeAllComponents(t){for(const e of this.storages.values())e.removeComponent(t)}getComponentMask(t){let e=BigInt(0);for(const[s,n]of this.storages.entries())n.hasComponent(t)&&(e|=y.getBitMask(s));return e}compactAll(){for(const t of this.storages.values())t.compact()}getAllStats(){const t=new Map;for(const[e,s]of this.storages.entries()){const n=e.name||"Unknown";t.set(n,s.getStats())}return t}clear(){for(const t of this.storages.values())t.clear();this.storages.clear()}}class _{compare(t,e){let s=t.updateOrder-e.updateOrder;return 0==s&&(s=t.id-e.id),s}}class T{constructor(t={maxSize:16,ttl:5e3,enableLRU:!0}){this.cache=new Map,this.accessOrder=[],this.config=t}get(t){const e=this.cache.get(t);return e?Date.now()-e.lastAccessed>this.config.ttl?(this.cache.delete(t),this.removeFromAccessOrder(t),null):(e.lastAccessed=Date.now(),e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.component):null}set(t,e){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLeastRecentlyUsed();const s={component:e,lastAccessed:Date.now(),accessCount:1};this.cache.set(t,s),this.config.enableLRU&&this.updateAccessOrder(t)}delete(t){const e=this.cache.delete(t);return e&&this.removeFromAccessOrder(t),e}clear(){this.cache.clear(),this.accessOrder.length=0}has(t){return this.cache.has(t)}evictLeastRecentlyUsed(){if(this.accessOrder.length>0){const t=this.accessOrder[0];this.cache.delete(t),this.accessOrder.shift()}}updateAccessOrder(t){this.removeFromAccessOrder(t),this.accessOrder.push(t)}removeFromAccessOrder(t){const e=this.accessOrder.indexOf(t);-1!==e&&this.accessOrder.splice(e,1)}getStats(){let t=0,e=0;for(const s of this.cache.values())t+=s.accessCount,e++;return{size:this.cache.size,maxSize:this.config.maxSize,hitRate:t>0?e/t:0,averageAccessCount:this.cache.size>0?t/this.cache.size:0}}}class E{constructor(t,e){this.components=[],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=BigInt(0),this._componentTypeToIndex=new Map,this._componentAccessStats=new Map,this.name=t,this.id=e,this._componentCache=new T}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 s=new t(...e);return this.addComponent(s)}addComponentInternal(t){const e=t.constructor;y.isRegistered(e)||y.register(e),t.entity=this;const s=this.components.length;return this.components.push(t),this._componentTypeToIndex.set(e,s),this._componentMask|=y.getBitMask(e),this._componentCache.set(e,t),this._componentAccessStats.set(e,{accessCount:0,lastAccessed:Date.now(),cacheHits:0,cacheMisses:0}),t}addComponent(t){const e=t.constructor;if(this.hasComponent(e))throw new Error(`Entity ${this.name} already has component ${e.name}`);if(this.addComponentInternal(t),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.addComponent(this.id,t),t.onAddedToEntity(),E.eventBus&&E.eventBus.emitComponentAdded({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),this.scene&&this.scene.entityProcessors)for(const t of this.scene.entityProcessors.processors)t.onChanged(this);return t}getComponent(t){if(this.updateComponentAccessStats(t),!y.isRegistered(t))return this.recordCacheMiss(t),null;const e=y.getBitMask(t);if((this._componentMask&e)===BigInt(0))return this.recordCacheMiss(t),null;const s=this._componentCache.get(t);if(s)return this.recordCacheHit(t),s;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 this._componentCache.set(t,e),this.recordCacheHit(t),e}if(this.scene&&this.scene.componentStorageManager){const e=this.scene.componentStorageManager.getComponent(this.id,t);if(e)return this._componentCache.set(t,e),this.rebuildComponentIndex(),this.recordCacheHit(t),e}for(let e=0;e<this.components.length;e++){const s=this.components[e];if(s instanceof t)return this._componentTypeToIndex.set(t,e),this._componentCache.set(t,s),this.recordCacheHit(t),s}return this.recordCacheMiss(t),null}updateComponentAccessStats(t){let e=this._componentAccessStats.get(t);e||(e={accessCount:0,lastAccessed:Date.now(),cacheHits:0,cacheMisses:0},this._componentAccessStats.set(t,e)),e.accessCount++,e.lastAccessed=Date.now()}recordCacheHit(t){const e=this._componentAccessStats.get(t);e&&e.cacheHits++}recordCacheMiss(t){const e=this._componentAccessStats.get(t);e&&e.cacheMisses++}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(!y.isRegistered(t))return!1;const e=y.getBitMask(t);return(this._componentMask&e)!==BigInt(0)}getOrCreateComponent(t,...e){let s=this.getComponent(t);return s||(s=this.createComponent(t,...e)),s}removeComponent(t){const e=t.constructor,s=this.components.indexOf(t);if(-1!==s&&(this.components.splice(s,1),this.rebuildComponentIndex()),this._componentCache.delete(e),this._componentAccessStats.delete(e),y.isRegistered(e)&&(this._componentMask&=~y.getBitMask(e)),this.scene&&this.scene.componentStorageManager&&this.scene.componentStorageManager.removeComponent(this.id,e),t.onRemovedFromEntity(),E.eventBus&&E.eventBus.emitComponentRemoved({timestamp:Date.now(),source:"Entity",entityId:this.id,entityName:this.name,entityTag:this.tag?.toString(),componentType:e.name,component:t}),t.entity=null,this.scene&&this.scene.entityProcessors)for(const t of this.scene.entityProcessors.processors)t.onChanged(this)}removeComponentByType(t){const e=this.getComponent(t);return e?(this.removeComponent(e),e):null}removeAllComponents(){const t=[...this.components];this._componentCache.clear(),this._componentTypeToIndex.clear(),this._componentAccessStats.clear(),this._componentMask=BigInt(0);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}if(this.components.length=0,this.scene&&this.scene.entityProcessors)for(const t of this.scene.entityProcessors.processors)t.onChanged(this)}addComponents(t){const e=[];for(const s of t)try{e.push(this.addComponent(s))}catch(t){console.warn(`添加组件失败 ${s.constructor.name}:`,t)}return e}removeComponentsByTypes(t){const e=[];for(const s of t)e.push(this.removeComponentByType(s));return e}getComponentCacheStats(){const t=new Map;for(const[e,s]of this._componentAccessStats){const n=s.cacheHits+s.cacheMisses;t.set(e.name,{...s,hitRate:n>0?s.cacheHits/n:0})}return{cacheStats:this._componentCache.getStats(),accessStats:t,indexMappingSize:this._componentTypeToIndex.size,totalComponents:this.components.length}}warmUpComponentCache(){for(let t=0;t<this.components.length;t++){const e=this.components[t],s=e.constructor;this._componentTypeToIndex.set(s,t),this._componentCache.set(s,e)}}cleanupComponentCache(){const t=Date.now();for(const[e,s]of this._componentAccessStats)t-s.lastAccessed>3e4&&s.accessCount<5&&this._componentCache.delete(e)}getComponents(t){const e=[];for(const s of this.components)s instanceof t&&e.push(s);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 s=e.findChild(t,!0);if(s)return s}return null}findChildrenByTag(t,e=!1){const s=[];for(const e of this._children)e.tag===t&&s.push(e);if(e)for(const e of this._children)s.push(...e.findChildrenByTag(t,!0));return s}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(((s,n)=>{t(s,n),e&&s.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.entities&&this.scene.entities.remove(this)}compareTo(t){return _.prototype.compare(this,t)}toString(){return`Entity[${this.name}:${this.id}]`}getDebugInfo(){const t=this.getComponentCacheStats(),e=Array.from(t.accessStats.entries()).map((([t,e])=>({componentType:t,accessCount:e.accessCount,cacheHits:e.cacheHits,cacheMisses:e.cacheMisses,hitRate:e.hitRate,lastAccessed:new Date(e.lastAccessed).toISOString()})));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=>t.constructor.name)),componentMask:this._componentMask.toString(2),parentId:this._parent?.id||null,childCount:this._children.length,childIds:this._children.map((t=>t.id)),depth:this.getDepth(),componentCache:t.cacheStats,componentAccessStats:e,indexMappingSize:t.indexMappingSize}}}E.entityComparer=new _,E.eventBus=null;class S{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))}removeAllEntities(){for(let t=this.buffer.length-1;t>=0;t--)this.buffer[t].destroy();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 s of this.buffer)s.tag===t&&e.push(s);return e}findEntitiesWithComponent(t){const e=[];for(const s of this.buffer)s.hasComponent(t)&&e.push(s);return e}forEach(t){for(const e of this.buffer)t(e)}forEachWhere(t,e){for(const s of this.buffer)t(s)&&e(s)}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 s=e.indexOf(t);-1!==s&&(e.splice(s,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 C{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();for(const t of this._processors)t.initialize()}end(){}update(){this.sortProcessors();for(const t of this._processors)t.update()}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}}class M{constructor(){this._nextAvailableId=0,this._ids=[]}checkOut(){return this._ids.length>0?this._ids.pop():this._nextAvailableId++}checkIn(t){this._ids.push(t)}}class b{constructor(t,e,s=1e3){this.pool=[],this.createFn=t,this.resetFn=e,this.maxSize=s}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 I{constructor(){this.pools=new Map}static getInstance(){return I.instance||(I.instance=new I),I.instance}registerPool(t,e,s,n){this.pools.set(t,new b(e,s,n))}acquireComponent(t){const e=this.pools.get(t);return e?e.acquire():null}releaseComponent(t,e){const s=this.pools.get(t);s&&s.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()}getPoolStats(){const t=new Map;for(const[e,s]of this.pools)t.set(e,{available:s.getAvailableCount(),maxSize:s.getMaxSize()});return t}getPoolUtilization(){const t=new Map;for(const[e,s]of this.pools){const n=s.getAvailableCount(),i=s.getMaxSize(),o=i-n,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 s=e.getAvailableCount(),n=e.getMaxSize();return n>0?(n-s)/n*100:0}}class v{constructor(){this.maskCache=new Map,this.componentTypeMap=new Map,this.nextComponentId=0}static getInstance(){return v.instance||(v.instance=new v),v.instance}registerComponentType(t){return this.componentTypeMap.has(t)||this.componentTypeMap.set(t,this.nextComponentId++),this.componentTypeMap.get(t)}getComponentTypeId(t){return this.componentTypeMap.get(t)}createSingleComponentMask(t){const e=`single:${t}`;if(this.maskCache.has(e))return this.maskCache.get(e);const s=this.getComponentTypeId(t);if(void 0===s)throw new Error(`Component type not registered: ${t}`);const n=1n<<BigInt(s);return this.maskCache.set(e,n),n}createCombinedMask(t){const e=`combined:${[...t].sort().join(",")}`;if(this.maskCache.has(e))return this.maskCache.get(e);let s=0n;for(const e of t){const t=this.getComponentTypeId(e);if(void 0===t)throw new Error(`Component type not registered: ${e}`);s|=1n<<BigInt(t)}return this.maskCache.set(e,s),s}maskContainsComponent(t,e){return 0n!==(t&this.createSingleComponentMask(e))}maskContainsAllComponents(t,e){const s=this.createCombinedMask(e);return(t&s)===s}maskContainsAnyComponent(t,e){return 0n!==(t&this.createCombinedMask(e))}addComponentToMask(t,e){return t|this.createSingleComponentMask(e)}removeComponentFromMask(t,e){return t&~this.createSingleComponentMask(e)}precomputeCommonMasks(t){for(const e of t)this.createCombinedMask(e)}getCacheStats(){return{size:this.maskCache.size,componentTypes:this.componentTypeMap.size}}clearCache(){this.maskCache.clear()}reset(){this.maskCache.clear(),this.componentTypeMap.clear(),this.nextComponentId=0}maskToComponentNames(t){const e=[];for(const[s,n]of this.componentTypeMap){0n!==(t&1n<<BigInt(n))&&e.push(s)}return e}getComponentCount(t){let e=0,s=t;for(;0n!==s;)0n!=(1n&s)&&e++,s>>=1n;return e}}!function(t){t.ADD_ENTITY="add_entity",t.REMOVE_ENTITY="remove_entity",t.UPDATE_ENTITY="update_entity"}(o||(o={}));class w{constructor(){this.pendingOperations=[],this.isProcessing=!1,this.batchSize=1e3,this.flushTimeout=null,this.flushDelay=16}addOperation(t){this.pendingOperations.push(t),this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}addEntities(t){for(const e of t)this.pendingOperations.push({type:o.ADD_ENTITY,entity:e});this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}removeEntities(t){for(const e of t)this.pendingOperations.push({type:o.REMOVE_ENTITY,entity:e});this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}updateEntities(t){for(const e of t)this.pendingOperations.push({type:o.UPDATE_ENTITY,entity:e.entity,oldMask:e.oldMask,newMask:e.newMask});this.pendingOperations.length>=this.batchSize?this.flush():this.scheduleFlush()}scheduleFlush(){this.flushTimeout||(this.flushTimeout=setTimeout((()=>{this.flush()}),this.flushDelay))}flush(){if(!this.isProcessing&&0!==this.pendingOperations.length){this.isProcessing=!0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null);try{this.processBatch()}finally{this.isProcessing=!1}}}processBatch(){const t=this.pendingOperations;this.pendingOperations=[];const e=[],s=[],n=[];for(const i of t)switch(i.type){case o.ADD_ENTITY:e.push(i.entity);break;case o.REMOVE_ENTITY:s.push(i.entity);break;case o.UPDATE_ENTITY:void 0!==i.oldMask&&void 0!==i.newMask&&n.push({entity:i.entity,oldMask:i.oldMask,newMask:i.newMask})}e.length>0&&this.processBatchAdd(e),s.length>0&&this.processBatchRemove(s),n.length>0&&this.processBatchUpdate(n)}processBatchAdd(t){this.onBatchAdd&&this.onBatchAdd(t)}processBatchRemove(t){this.onBatchRemove&&this.onBatchRemove(t)}processBatchUpdate(t){this.onBatchUpdate&&this.onBatchUpdate(t)}setBatchSize(t){this.batchSize=Math.max(1,t)}setFlushDelay(t){this.flushDelay=Math.max(0,t)}getPendingCount(){return this.pendingOperations.length}clear(){this.pendingOperations.length=0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null)}hasPendingOperations(){return this.pendingOperations.length>0}}!function(t){t.HASH="hash",t.BITMAP="bitmap",t.SORTED="sorted"}(r||(r={}));class x{constructor(){this.type=r.HASH,this._componentToEntities=new Map,this._entityToComponents=new Map,this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now()}addEntity(t){const e=t.components,s=new Set;for(const n of e){const e=n.constructor;s.add(e);let i=this._componentToEntities.get(e);i||(i=new Set,this._componentToEntities.set(e,i)),i.add(t)}this._entityToComponents.set(t,s),this._lastUpdated=Date.now()}removeEntity(t){const e=this._entityToComponents.get(t);if(e){for(const s of e){const e=this._componentToEntities.get(s);e&&(e.delete(t),0===e.size&&this._componentToEntities.delete(s))}this._entityToComponents.delete(t),this._lastUpdated=Date.now()}}query(t){const e=performance.now(),s=new Set(this._componentToEntities.get(t)||[]);return this._queryCount++,this._totalQueryTime+=performance.now()-e,s}queryMultiple(t,e){const s=performance.now();if(0===t.length)return new Set;if(1===t.length)return this.query(t[0]);let n;if("AND"===e){let e,i=1/0;for(const n of t){const t=this._componentToEntities.get(n);if(!t||0===t.size)return this._queryCount++,this._totalQueryTime+=performance.now()-s,new Set;t.size<i&&(i=t.size,e=t)}if(n=new Set,e)for(const s of e){let e=!0;for(const n of t){const t=this._componentToEntities.get(n);if(!t||!t.has(s)){e=!1;break}}e&&n.add(s)}}else{n=new Set;for(const e of t){const t=this._componentToEntities.get(e);if(t)for(const e of t)n.add(e)}}return this._queryCount++,this._totalQueryTime+=performance.now()-s,n}clear(){this._componentToEntities.clear(),this._entityToComponents.clear(),this._lastUpdated=Date.now()}getStats(){let t=0;t+=64*this._componentToEntities.size,t+=64*this._entityToComponents.size;for(const e of this._componentToEntities.values())t+=8*e.size;for(const e of this._entityToComponents.values())t+=8*e.size;return{type:this.type,size:this._componentToEntities.size,memoryUsage:t,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}}}class D{constructor(){this.type=r.BITMAP,this._componentTypeToBit=new Map,this._entityToBitmap=new Map,this._bitToEntities=new Map,this._nextBit=0,this._queryCount=0,this._totalQueryTime=0,this._lastUpdated=Date.now()}addEntity(t){let e=0;for(const s of t.components){const n=s.constructor;let i=this._componentTypeToBit.get(n);void 0===i&&(i=this._nextBit++,this._componentTypeToBit.set(n,i)),e|=1<<i;let o=this._bitToEntities.get(1<<i);o||(o=new Set,this._bitToEntities.set(1<<i,o)),o.add(t)}this._entityToBitmap.set(t,e),this._lastUpdated=Date.now()}removeEntity(t){const e=this._entityToBitmap.get(t);if(void 0!==e){for(const[s,n]of this._bitToEntities)0!==(e&s)&&(n.delete(t),0===n.size&&this._bitToEntities.delete(s));this._entityToBitmap.delete(t),this._lastUpdated=Date.now()}}query(t){const e=performance.now(),s=this._componentTypeToBit.get(t);if(void 0===s)return this._queryCount++,this._totalQueryTime+=performance.now()-e,new Set;const n=new Set(this._bitToEntities.get(1<<s)||[]);return this._queryCount++,this._totalQueryTime+=performance.now()-e,n}queryMultiple(t,e){const s=performance.now();if(0===t.length)return new Set;let n=0;const i=[];for(const e of t){const t=this._componentTypeToBit.get(e);void 0!==t&&(n|=1<<t,i.push(1<<t))}const o=new Set;if("AND"===e)for(const[t,e]of this._entityToBitmap)(e&n)===n&&o.add(t);else for(const t of i){const e=this._bitToEntities.get(t);if(e)for(const t of e)o.add(t)}return this._queryCount++,this._totalQueryTime+=performance.now()-s,o}clear(){this._componentTypeToBit.clear(),this._entityToBitmap.clear(),this._bitToEntities.clear(),this._nextBit=0,this._lastUpdated=Date.now()}getStats(){let t=0;t+=12*this._componentTypeToBit.size,t+=12*this._entityToBitmap.size,t+=64*this._bitToEntities.size;for(const e of this._bitToEntities.values())t+=8*e.size;return{type:this.type,size:this._componentTypeToBit.size,memoryUsage:t,queryCount:this._queryCount,avgQueryTime:this._queryCount>0?this._totalQueryTime/this._queryCount:0,lastUpdated:this._lastUpdated}}}class A{constructor(t=r.HASH){this._indexHistory=new Map,this._autoOptimize=!0,this._optimizationThreshold=1e3,this._activeIndex=this.createIndex(t)}addEntity(t){this._activeIndex.addEntity(t),this.checkOptimization()}removeEntity(t){this._activeIndex.removeEntity(t)}query(t){return this._activeIndex.query(t)}queryMultiple(t,e){return this._activeIndex.queryMultiple(t,e)}switchIndexType(t){if(t===this._activeIndex.type)return;this._indexHistory.set(this._activeIndex.type,this._activeIndex.getStats());const e=this._activeIndex;this._activeIndex=this.createIndex(t),e.clear()}setAutoOptimize(t){this._autoOptimize=t}getStats(){return this._activeIndex.getStats()}getAllStats(){const t=this._activeIndex.getStats();return new Map([...this._indexHistory,[t.type,t]])}clear(){this._activeIndex.clear()}createIndex(t){switch(t){case r.HASH:return new x;case r.BITMAP:return new D;case r.SORTED:default:return new x}}checkOptimization(){if(!this._autoOptimize)return;const t=this._activeIndex.getStats();t.queryCount<this._optimizationThreshold||(t.avgQueryTime>1&&t.type!==r.HASH?this.switchIndexType(r.HASH):t.memoryUsage>10485760&&t.type!==r.BITMAP&&this.switchIndexType(r.BITMAP))}}class O{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),s=this.generateArchetypeId(e);let n=this._archetypes.get(s);n||(n=this.createArchetype(e)),n.entities.push(t),n.updatedAt=Date.now(),this._entityToArchetype.set(t,n),this.updateComponentIndexes(n,e,!0),this.invalidateQueryCache()}removeEntity(t){const e=this._entityToArchetype.get(t);if(!e)return;const s=e.entities.indexOf(t);-1!==s&&(e.entities.splice(s,1),e.updatedAt=Date.now()),this._entityToArchetype.delete(t),this.invalidateQueryCache()}queryArchetypes(t,e="AND"){const s=performance.now(),n=`${e}:${t.map((t=>t.name)).sort().join(",")}`,i=this._queryCache.get(n);if(i&&Date.now()-i.timestamp<this._cacheTimeout)return{...i.result,executionTime:performance.now()-s,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 s of t){const t=this._componentToArchetypes.get(s);if(t)for(const s of t)e.add(s)}for(const t of e)o.push(t),r+=t.entities.length}const a={archetypes:o,totalEntities:r,executionTime:performance.now()-s,fromCache:!1};return this._queryCache.set(n,{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=>t.name)).sort().join("|")}createArchetype(t){const e=this.generateArchetypeId(t),s={id:e,componentTypes:[...t],entities:[],createdAt:Date.now(),updatedAt:Date.now()};return this._archetypes.set(e,s),s}archetypeContainsAllComponents(t,e){for(const s of e)if(!t.componentTypes.includes(s))return!1;return!0}updateComponentIndexes(t,e,s){for(const n of e){let e=this._componentToArchetypes.get(n);e||(e=new Set,this._componentToArchetypes.set(n,e)),s?e.add(t):(e.delete(t),0===e.size&&this._componentToArchetypes.delete(n))}}invalidateQueryCache(){this._queryCache.clear()}}!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"}(a||(a={}));class N{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,s=[]){this._stats.totalMarkings++;let n=this._dirtyEntities.get(t);n||(n={entity:t,flags:0,modifiedComponents:new Set,timestamp:performance.now(),frameNumber:this._currentFrame},this._dirtyEntities.set(t,n)),n.flags|=e,n.timestamp=performance.now(),n.frameNumber=this._currentFrame;for(const t of s)n.modifiedComponents.add(t);this.notifyListeners(n,e)}isDirty(t,e=a.ALL){const s=this._dirtyEntities.get(t);return!!s&&0!==(s.flags&e)}clearDirty(t,e=a.ALL){const s=this._dirtyEntities.get(t);s&&(e===a.ALL?this._dirtyEntities.delete(t):(s.flags&=~e,0===s.flags&&this._dirtyEntities.delete(t)),this._stats.totalCleanups++)}getDirtyEntities(t=a.ALL){const e=[];for(const s of this._dirtyEntities.values())0!==(s.flags&t)&&e.push(s);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 s=this._processingQueue.shift();this.processEntity(s),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){console.error("脏数据监听器错误:",t)}this.clearDirty(t.entity)}notifyListeners(t,e){for(const s of this._listeners)if(0!==(e&s.flags))try{s.callback(t)}catch(t){console.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}}!function(t){t.ALL="all",t.ANY="any",t.NONE="none"}(c||(c={}));class R{constructor(){this.entities=[],this.indexDirty=!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=I.getInstance(),this.bitMaskOptimizer=v.getInstance(),this.indexUpdateBatcher=new w,this.componentIndexManager=new A(r.HASH),this.archetypeSystem=new O,this.dirtyTrackingSystem=new N,this.indexUpdateBatcher.onBatchAdd=t=>{for(const e of t)this.addEntityToIndexes(e)},this.indexUpdateBatcher.onBatchRemove=t=>{for(const e of t)this.removeEntityFromIndexes(e)},this.indexUpdateBatcher.onBatchUpdate=t=>{for(const e of t)this.removeEntityFromIndexes(e.entity),this.addEntityToIndexes(e.entity)}}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,a.COMPONENT_ADDED),e||this.clearQueryCache())}addEntities(t){if(0===t.length)return;const e=new Set(this.entities.map((t=>t.id)));let s=0;for(const n of t)e.has(n.id)||(this.entities.push(n),this.addEntityToIndexes(n),e.add(n.id),s++);s>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,a.COMPONENT_REMOVED),this.clearQueryCache())}addEntityToIndexes(t){const e=t.componentMask;let s=this.entityIndex.byMask.get(e);s||(s=new Set,this.entityIndex.byMask.set(e,s)),s.add(t);const n=t.components;for(let e=0;e<n.length;e++){const s=n[e].constructor;let i=this.entityIndex.byComponentType.get(s);i||(i=new Set,this.entityIndex.byComponentType.set(s,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,s=this.entityIndex.byMask.get(e);s&&(s.delete(t),0===s.size&&this.entityIndex.byMask.delete(e));for(const e of t.components){const s=e.constructor,n=this.entityIndex.byComponentType.get(s);n&&(n.delete(t),0===n.size&&this.entityIndex.byComponentType.delete(s))}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();for(const t of this.entities)this.addEntityToIndexes(t);this.indexDirty=!1}queryAll(...t){const e=performance.now();this.queryStats.totalQueries++;const s=`all:${t.map((t=>t.name)).sort().join(",")}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};let i;const o=this.archetypeSystem.queryArchetypes(t,"AND");if(o.archetypes.length>0){this.queryStats.archetypeHits++,i=[];for(const t of o.archetypes)i.push(...t.entities)}else 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)}return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryMultipleComponents(t){let e=null,s=1/0;for(const n of t){const t=this.entityIndex.byComponentType.get(n);if(!t||0===t.size)return[];t.size<s&&(s=t.size,e=t)}if(!e)return this.queryStats.linearScans++,this.queryByLinearScan(t);const n=this.createComponentMask(t),i=[];for(const t of e)(t.componentMask&n)===n&&i.push(t);return i}queryByLinearScan(t){const e=this.createComponentMask(t);return this.entities.filter((t=>(t.componentMask&e)===e))}queryAny(...t){const e=performance.now();this.queryStats.totalQueries++;const s=`any:${t.map((t=>t.name)).sort().join(",")}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.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(s,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryNone(...t){const e=performance.now();this.queryStats.totalQueries++;const s=`none:${t.map((t=>t.name)).sort().join(",")}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};const i=this.createComponentMask(t),o=this.entities.filter((t=>(t.componentMask&i)===BigInt(0)));return this.addToCache(s,o),{entities:o,count:o.length,executionTime:performance.now()-e,fromCache:!1}}queryByTag(t){const e=performance.now();this.queryStats.totalQueries++;const s=`tag:${t}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byTag.get(t)||[]);return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByName(t){const e=performance.now();this.queryStats.totalQueries++;const s=`name:${t}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byName.get(t)||[]);return this.addToCache(s,i),{entities:i,count:i.length,executionTime:performance.now()-e,fromCache:!1}}queryByComponent(t){const e=performance.now();this.queryStats.totalQueries++;const s=`component:${t.name}`,n=this.getFromCache(s);if(n)return this.queryStats.cacheHits++,{entities:n,count:n.length,executionTime:performance.now()-e,fromCache:!0};this.queryStats.indexHits++;const i=Array.from(this.entityIndex.byComponentType.get(t)||[]);return this.addToCache(s,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,s]of this.queryCache.entries())t-s.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 s=0;s<e&&s<t.length;s++)this.queryCache.delete(t[s][0])}}clearQueryCache(){this.queryCache.clear()}clearCache(){this.clearQueryCache()}batchUpdateComponents(t){const e=[];for(const s of t){const t=this.entities.find((t=>t.id===s.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,a.COMPONENT_MODIFIED,[]);this.clearQueryCache()}createComponentMask(t){const e=t.map((t=>t.name));for(const t of e)this.bitMaskOptimizer.registerComponentType(t);return this.bitMaskOptimizer.createCombinedMask(e)}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=>t.name)),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%"}}}switchComponentIndexType(t){this.componentIndexManager.switchIndexType(t)}configureDirtyTracking(t,e){this.dirtyTrackingSystem.configureBatchProcessing(t,e)}optimizePerformance(){this.dirtyTrackingSystem.processDirtyEntities(),this.cleanupCache();const t=this.componentIndexManager.getStats();t.avgQueryTime>2&&t.type!==r.HASH?this.switchComponentIndexType(r.HASH):t.memoryUsage>52428800&&t.type!==r.BITMAP&&this.switchComponentIndexType(r.BITMAP)}beginFrame(){this.dirtyTrackingSystem.beginFrame()}endFrame(){this.dirtyTrackingSystem.endFrame()}markEntityDirty(t,e){this.queryStats.dirtyChecks++,this.dirtyTrackingSystem.markDirty(t,a.COMPONENT_MODIFIED,e),this.clearQueryCache()}getEntityArchetype(t){return this.archetypeSystem.getEntityArchetype(t)}}class B{constructor(t){this.conditions=[],this.querySystem=t}withAll(...t){return this.conditions.push({type:c.ALL,componentTypes:t,mask:this.createComponentMask(t)}),this}withAny(...t){return this.conditions.push({type:c.ANY,componentTypes:t,mask:this.createComponentMask(t)}),this}without(...t){return this.conditions.push({type:c.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 c.ALL:return this.querySystem.queryAll(...t.componentTypes);case c.ANY:return this.querySystem.queryAny(...t.componentTypes);case c.NONE:return this.querySystem.queryNone(...t.componentTypes)}}return{entities:[],count:0,executionTime:performance.now()-t,fromCache:!1}}createComponentMask(t){let e=BigInt(0);for(const s of t)try{e|=y.getBitMask(s)}catch(t){console.warn(`组件类型 ${s.name} 未注册,跳过`)}return e}reset(){return this.conditions=[],this}}class k{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,s={}){return this.addListener(t,e,s)}once(t,e,s={}){return this.addListener(t,e,{...s,once:!0})}onAsync(t,e,s={}){return this.addListener(t,e,{...s,async:!0})}off(t,e){const s=this.listeners.get(t);if(!s)return!1;const n=s.findIndex((t=>t.id===e));return-1!==n&&(s.splice(n,1),0===s.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 s=this.batchConfigs.get(t);s?.enabled?this.addToBatch(t,e):await this.executeEvent(t,e)}emitSync(t,e){if(!this.isEnabled)return;const s=this.listeners.get(t);if(!s||0===s.length)return;const n=performance.now(),i=[],o=this.sortListenersByPriority(s);for(const s of o)if(!s.config.async)try{s.config.context?s.handler.call(s.config.context,e):s.handler(e),s.config.once&&i.push(s.id)}catch(e){console.error(`事件处理器执行错误 ${t}:`,e)}this.removeListeners(t,i),this.updateStats(t,performance.now()-n)}setBatchConfig(t,e){this.batchConfigs.set(t,e)}flushBatch(t){const e=this.batchQueue.get(t);if(!e||0===e.length)return;const s=this.batchTimers.get(t);s&&(clearTimeout(s),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,s){let n=this.listeners.get(t);if(n||(n=[],this.listeners.set(t,n)),n.length>=this.maxListeners)return console.warn(`事件类型 ${t} 的监听器数量超过最大限制 (${this.maxListeners})`),"";const i="listener_"+this.nextListenerId++,o={handler:e,config:{priority:0,...s},id:i};return n.push(o),this.stats.has(t)||this.stats.set(t,this.createEmptyStats(t)),i}async executeEvent(t,e){const s=this.listeners.get(t);if(!s||0===s.length)return;const n=performance.now(),i=[],o=this.sortListenersByPriority(s),r=o.filter((t=>!t.config.async)),a=o.filter((t=>t.config.async));for(const s of r)try{s.config.context?s.handler.call(s.config.context,e):s.handler(e),s.config.once&&i.push(s.id)}catch(e){console.error(`同步事件处理器执行错误 ${t}:`,e)}const c=a.map((async s=>{try{s.config.context?await s.handler.call(s.config.context,e):await s.handler(e),s.config.once&&i.push(s.id)}catch(e){console.error(`异步事件处理器执行错误 ${t}:`,e)}}));await Promise.all(c),this.removeListeners(t,i),this.updateStats(t,performance.now()-n)}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 s=this.listeners.get(t);if(s){for(const t of e){const e=s.findIndex((e=>e.id===t));-1!==e&&s.splice(e,1)}0===s.length&&(this.listeners.delete(t),this.stats.delete(t))}}addToBatch(t,e){let s=this.batchQueue.get(t);s||(s=[],this.batchQueue.set(t,s)),s.push(e);const n=this.batchConfigs.get(t);if(s.length>=n.batchSize)this.flushBatch(t);else if(!this.batchTimers.has(t)){const e=setTimeout((()=>{this.flushBatch(t)}),n.delay);this.batchTimers.set(t,e)}}async processBatch(t,e){const s={type:t,events:e,count:e.length,timestamp:Date.now()};await this.executeEvent(`${t}:batch`,s)}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 s=this.stats.get(t);s||(s=this.createEmptyStats(t),this.stats.set(t,s)),s.triggerCount++,s.totalExecutionTime+=e,s.averageExecutionTime=s.totalExecutionTime/s.triggerCount,s.lastTriggerTime=Date.now(),s.listenerCount=this.getListenerCount(t)}createEmptyStats(t){return{eventType:t,listenerCount:0,triggerCount:0,totalExecutionTime:0,averageExecutionTime:0,lastTriggerTime:0}}}class P{get systems(){return this.entityProcessors.processors}constructor(){this.name="",this._didSceneBegin=!1,this.entities=new S(this),this.entityProcessors=new C,this.identifierPool=new M,this.componentStorageManager=new f,this.querySystem=new R,this.eventSystem=new k,this.initialize()}initialize(){}onStart(){}unload(){}begin(){null!=this.entityProcessors&&this.entityProcessors.begin(),this._didSceneBegin=!0,this.onStart()}end(){this._didSceneBegin=!1,this.entities.removeAllEntities(),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 E(t,this.identifierPool.checkOut());return 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 s=[];for(let n=0;n<t;n++){const t=new E(`${e}_${n}`,this.identifierPool.checkOut());t.scene=this,s.push(t)}for(const t of s)this.entities.add(t);return this.querySystem.addEntitiesUnchecked(s),this.eventSystem.emitSync("entities:batch_added",{entities:s,scene:this,count:t}),s}createEntitiesOld(t,e="Entity"){const s=[];for(let n=0;n<t;n++){const t=new E(`${e}_${n}`,this.identifierPool.checkOut());s.push(t),this.addEntity(t,!0)}return this.querySystem.clearCache(),s}destroyAllEntities(){for(let t=0;t<this.entities.count;t++)this.entities.buffer[t].destroy()}findEntity(t){return this.entities.findEntity(t)}findEntityById(t){return this.entities.findEntityById(t)}findEntitiesByTag(t){const e=[];for(const s of this.entities.buffer)s.tag===t&&e.push(s);return e}getEntityByName(t){return this.findEntity(t)}getEntitiesByTag(t){return this.findEntitiesByTag(t)}addEntityProcessor(t){return t.scene=this,this.entityProcessors.add(t),t.setUpdateOrder(this.entityProcessors.count-1),t}addSystem(t){return this.addEntityProcessor(t)}removeEntityProcessor(t){this.entityProcessors.remove(t)}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.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=>t.constructor.name))}))),processors:this.entityProcessors.processors.map((t=>({name:t.constructor.name,updateOrder:t.updateOrder,entityCount:t._entities?.length||0}))),componentStats:this.componentStorageManager.getAllStats()}}}class z{constructor(t,e){this.scene=t,this.storageManager=e,this.entity=new E("",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 s=this.entity.getComponent(t);return s&&e(s),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 z(this.scene,this.storageManager);return t.entity=this.entity,t}}class q{constructor(){this.scene=new P}named(t){return this.scene.name=t,this}withEntity(t){return this.scene.addEntity(t),this}withEntityBuilder(t){const e=t(new z(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 H{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,s){return t&&(this.component[e]=s),this}build(){return this.component}}class U{constructor(t,e,s){this.scene=t,this.querySystem=e,this.eventSystem=s}createEntity(){return new z(this.scene,this.scene.componentStorageManager)}createScene(){return new q}createComponent(t,...e){return new H(t,...e)}query(){return new B(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.getEntityByName(t)}findByTag(t){return this.scene.getEntitiesByTag(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 F(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()}}}class F{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 F(this.entities.filter(t))}toArray(){return this.entities.slice()}count(){return this.entities.length}}function L(t,e,s){return new U(t,e,s)}class ${collectEntityData(){const t=K.scene;if(!t)return this.getEmptyEntityDebugData();const e=t.entities;if(!e)return this.getEmptyEntityDebugData();let s;try{s=e.getStats?e.getStats():this.calculateFallbackEntityStats(e)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const n=this.collectArchetypeData(t);return{totalEntities:s.totalEntities,activeEntities:s.activeEntities,pendingAdd:s.pendingAdd||0,pendingRemove:s.pendingRemove||0,entitiesPerArchetype:n.distribution,topEntitiesByComponents:n.topEntities,entityHierarchy:[],entityDetailsMap:{}}}getRawEntityList(){const t=K.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=>t.constructor.name)),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=K.scene;if(!e)return null;const s=e.entities;if(!s?.buffer)return null;const n=s.buffer.find((e=>e.id===t));if(!n)return null;const i=n.getDebugInfo?n.getDebugInfo():this.buildFallbackEntityInfo(n),o=this.extractComponentDetails(n.components),r=this.getSceneInfo(e);return{...i,scene:r.name,sceneName:r.name,sceneType:r.type,parentName:n.parent?.name||null,components:o||[],componentCount:n.components?.length||0,componentTypes:n.components?.map((t=>t.constructor.name))||[]}}catch(t){return{error:`获取实体详情失败: ${t instanceof Error?t.message:String(t)}`,scene:"获取失败",components:[],componentCount:0,componentTypes:[]}}}getSceneInfo(t){let e="当前场景",s="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,s=t.constructor.name;else if(t._name&&"string"==typeof t._name&&t._name.trim())e=t._name.trim();else{const n=Object.getPrototypeOf(t)?.constructor?.name;n&&"Object"!==n&&(e=n,s=n)}}catch(t){e="场景名获取失败"}return{name:e,type:s}}collectEntityDataWithMemory(){const t=K.scene;if(!t)return this.getEmptyEntityDebugData();const e=t.entities;if(!e)return this.getEmptyEntityDebugData();let s;try{s=e.getStats?e.getStats():this.calculateFallbackEntityStats(e)}catch(t){return{totalEntities:0,activeEntities:0,pendingAdd:0,pendingRemove:0,entitiesPerArchetype:[],topEntitiesByComponents:[],entityHierarchy:[],entityDetailsMap:{}}}const n=this.collectArchetypeDataWithMemory(t);return{totalEntities:s.totalEntities,activeEntities:s.activeEntities,pendingAdd:s.pendingAdd||0,pendingRemove:s.pendingRemove||0,entitiesPerArchetype:n.distribution,topEntitiesByComponents:n.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 s=t.components?.map((t=>t.constructor.name))||[],n=s.length>0?s.sort().join(", "):"无组件",i=e.get(n);i?i.count++:e.set(n,{count:1,componentTypes:s})})),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(),s=[],n=[];return e.forEach((t=>{const e=t.componentTypes?.map((t=>t.name)).join(",")||"Unknown",i=t.entities?.length||0;s.push({signature:e,count:i,memory:0}),t.entities&&t.entities.slice(0,5).forEach((t=>{n.push({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:0})}))})),s.sort(((t,e)=>e.count-t.count)),n.sort(((t,e)=>e.componentCount-t.componentCount)),{distribution:s,topEntities:n}}extractArchetypeStatisticsWithMemory(t){const e=t.getAllArchetypes(),s=[],n=[];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 s=0;for(let n=0;n<e;n++)s+=this.estimateEntityMemoryUsage(t.entities[n]);o=s/e*i}s.push({signature:e,count:i,memory:o}),t.entities&&t.entities.slice(0,5).forEach((t=>{n.push({id:t.id.toString(),name:t.name||`Entity_${t.id}`,componentCount:t.components?.length||0,memory:this.estimateEntityMemoryUsage(t)})}))})),s.sort(((t,e)=>e.count-t.count)),n.sort(((t,e)=>e.componentCount-t.componentCount)),{distribution:s,topEntities:n}}getArchetypeDistribution(t){const e=new Map;return t&&t.entities&&t.entities.forEach((t=>{const s=t.componentMask?.toString()||"0",n=e.get(s);e.set(s,(n||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 s=t.components?.map((t=>t.constructor.name))||[],n=s.length>0?s.sort().join(", "):"无组件",i=e.get(n);let o=this.estimateEntityMemoryUsage(t);(isNaN(o)||o<0)&&(o=0),i?(i.count++,i.memory+=o):e.set(n,{count:1,memory:o,componentTypes:s})})),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||[],s=e.filter((t=>t.enabled&&!t._isDestroyed));return{totalEntities:e.length,activeEntities:s.length,pendingAdd:0,pendingRemove:0,averageComponentsPerEntity:s.length>0?e.reduce(((t,e)=>t+(e.components?.length||0)),0)/s.length:0}}estimateEntityMemoryUsage(t){try{let e=0;const s=this.calculateObjectSize(t,["components","children","parent"]);return!isNaN(s)&&s>0&&(e+=s),t.components&&Array.isArray(t.components)&&t.components.forEach((t=>{const s=this.calculateObjectSize(t,["entity"]);!isNaN(s)&&s>0&&(e+=s)})),isNaN(e)||e<0?0:e}catch(t){return 0}}calculateObjectSize(t,e=[]){if(!t||"object"!=typeof t)return 0;const s=new WeakSet,n=(t,i=0)=>{if(!t||"object"!=typeof t||i>=2)return 0;if(s.has(t))return 0;s.add(t);let o=32;try{const s=Object.keys(t),r=Math.min(s.length,20);for(let a=0;a<r;a++){const r=s[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+=n(c,i+1))}}catch(t){return 64}return o};try{const e=n(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 s=this.buildEntityHierarchyNode(t);e.push(s)}})),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=>t.constructor.name)),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 s=t.getDebugInfo();e={...e,...s}}return t.components&&t.components.length>0&&(e.componentDetails=this.extractComponentDetails(t.components)),e}buildEntityDetailsMap(t){if(!t?.buffer)return{};const e={},s=t.buffer;for(let t=0;t<s.length;t+=100){s.slice(t,t+100).forEach((t=>{const s=t.getDebugInfo?t.getDebugInfo():this.buildFallbackEntityInfo(t),n=t.getComponentCacheStats?t.getComponentCacheStats():null,i=this.extractComponentDetails(t.components);e[t.id]={...s,parentName:t.parent?.name||null,components:i,componentTypes:s.componentTypes||i.map((t=>t.typeName)),cachePerformance:n?{hitRate:n.cacheStats.hitRate,size:n.cacheStats.size,maxSize:n.cacheStats.maxSize}:null}}))}return e}buildFallbackEntityInfo(t){const e=K.scene,s=this.getSceneInfo(e);return{name:t.name||`Entity_${t.id}`,id:t.id,enabled:!1!==t.enabled,active:!1!==t.active,activeInHierarchy:!1!==t.activeInHierarchy,destroyed:t.isDestroyed||!1,scene:s.name,sceneName:s.name,sceneType:s.type,componentCount:t.components.length,componentTypes:t.components.map((t=>t.constructor.name)),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=t.constructor.name;if(!e||"Object"===e||"Function"===e)try{const{ComponentTypeManager:s}=require("../../ECS/Utils/ComponentTypeManager"),n=s.instance,i=t.constructor,o=n.getTypeId(i);e=n.getTypeName(o)}catch(t){e="UnknownComponent"}const s={};try{Object.keys(t).forEach((e=>{if(!e.startsWith("_")&&"entity"!==e&&"constructor"!==e){const n=t[e];null!=n&&(s[e]=this.formatPropertyValue(n))}})),0===Object.keys(s).length&&(s._info="该组件没有公开属性",s._componentId=t.constructor.name)}catch(e){s._error="属性提取失败",s._componentId=t.constructor.name}return{typeName:e,properties:s}}))}getComponentProperties(t,e){try{const s=K.scene;if(!s)return{};const n=s.entities;if(!n?.buffer)return{};const i=n.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 s={};let n=0;const i=15;for(const o of e){if(n>=i){s._hasMoreProperties=!0,s._totalProperties=e.length,s._hiddenCount=e.length-n;break}if(!o.startsWith("_")&&!o.startsWith("$")&&"function"!=typeof t[o])try{const e=t[o];null!=e&&(s[o]=this.formatPropertyValue(e,1),n++)}catch(t){s[o]=`[访问失败: ${t instanceof Error?t.message:String(t)}]`,n++}}return s}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 s=void 0!==t.z?t.z:"";return`${e}(${t.x}, ${t.y}${s?", "+s:""})`}if(e.toLowerCase().includes("color")&&void 0!==t.r&&void 0!==t.g&&void 0!==t.b){const s=void 0!==t.a?t.a:1;return`${e}(${t.r}, ${t.g}, ${t.b}, ${s})`}if(e.toLowerCase().includes("node")){return`${e}: ${t.name||t._name||"未命名"}`}if(e.toLowerCase().includes("component")){const s=t.node?.name||t.node?._name||"";return`${e}${s?` on ${s}`:""}`}const s=Object.keys(t);return 0===s.length?`${e} (空对象)`:`${e} (${s.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,s){try{const n=K.scene;if(!n)return null;const i=n.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,s);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 s=e.split(".");let n=t;for(const t of s){if(null==n)return null;if(t.includes("[")&&t.includes("]")){const e=t.substring(0,t.indexOf("[")),s=parseInt(t.substring(t.indexOf("[")+1,t.indexOf("]")));if(e&&(n=n[e]),!(Array.isArray(n)&&s>=0&&s<n.length))return null;n=n[s]}else n=n[t]}return n}}class j{collectSystemData(t){const e=K.scene;if(!e)return{totalSystems:0,systemsInfo:[]};const s=e.entityProcessors;if(!s)return{totalSystems:0,systemsInfo:[]};const n=s.processors||[];let i=new Map,o=new Map;if(t)try{i=t.getAllSystemStats(),o=t.getAllSystemData()}catch(t){}return{totalSystems:n.length,systemsInfo:n.map((t=>{const e=t.systemName||t.constructor.name,s=i.get(e),n=o.get(e);return{name:e,type:t.constructor.name,entityCount:t.entities?.length||0,executionTime:s?.averageTime||n?.executionTime||0,minExecutionTime:s?.minTime===Number.MAX_VALUE?0:s?.minTime||0,maxExecutionTime:s?.maxTime||0,executionTimeHistory:s?.recentTimes||[],updateOrder:t.updateOrder||0,enabled:!1!==t.enabled,lastUpdateTime:n?.lastUpdateTime||0}}))}}}class Y{constructor(){this.frameTimeHistory=[],this.maxHistoryLength=60,this.lastGCCount=0,this.gcCollections=0,this.lastMemoryCheck=0}collectPerformanceData(t){const s=e.deltaTime,n=1e3*s,i=s>0?Math.round(1/s):0,o=this.getECSPerformanceData(t),r=o.totalExecutionTime,a=n>0?r/n*100:0;let c=0;performance.memory&&(c=performance.memory.usedJSHeapSize/1024/1024),this.frameTimeHistory.push(r),this.frameTimeHistory.length>this.maxHistoryLength&&this.frameTimeHistory.shift();const h=this.frameTimeHistory.filter((t=>t>=0));return{frameTime:r,engineFrameTime:n,ecsPercentage:a,memoryUsage:c,fps:i,averageFrameTime:h.length>0?h.reduce(((t,e)=>t+e),0)/h.length:r,minFrameTime:h.length>0?Math.min(...h):r,maxFrameTime:h.length>0?Math.max(...h):r,frameTimeHistory:[...this.frameTimeHistory],systemPerformance:this.getSystemPerformance(t),systemBreakdown:o.systemBreakdown,memoryDetails:this.getMemoryDetails()}}getECSPerformanceData(t){if(!t)try{const{Core:e}=require("../../Core"),s=e.Instance;if(!s||!s._performanceMonitor)return{totalExecutionTime:0,systemBreakdown:[]};t=s._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 s=[],n=t.getAllSystemStats();if(0===n.size)return{totalExecutionTime:0,systemBreakdown:[]};for(const[t,i]of n.entries()){const n=i.recentTimes&&i.recentTimes.length>0?i.recentTimes[i.recentTimes.length-1]:i.averageTime||0;e+=n,s.push({systemName:t,executionTime:n,percentage:0})}return s.forEach((t=>{t.percentage=e>0?t.executionTime/e*100:0})),s.sort(((t,e)=>e.executionTime-t.executionTime)),{totalExecutionTime:e,systemBreakdown:s}}catch(t){return{totalExecutionTime:0,systemBreakdown:[]}}}getSystemPerformance(t){if(!t)return[];try{const e=t.getAllSystemStats(),s=t.getAllSystemData();return Array.from(e.entries()).map((([t,e])=>{const n=s.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:n?.entityCount||0,lastExecutionTime:n?.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 G{collectComponentData(){const t=K.scene;if(!t)return{componentTypes:0,componentInstances:0,componentStats:[]};const e=t.entities;if(!e?.buffer)return{componentTypes:0,componentInstances:0,componentStats:[]};const s=new Map;let n=0;e.buffer.forEach((t=>{t.components&&t.components.forEach((t=>{const e=t.constructor.name,i=s.get(e)||{count:0,entities:0};i.count++,n++,s.set(e,i)}))}));let i=new Map,o=new Map;try{const{ComponentPoolManager:t}=require("../../ECS/Core/ComponentPool"),e=t.getInstance(),s=e.getPoolStats(),n=e.getPoolUtilization();for(const[t,e]of s.entries())o.set(t,e.maxSize);for(const[t,e]of n.entries())i.set(t,e.utilization)}catch(t){}return{componentTypes:s.size,componentInstances:n,componentStats:Array.from(s.entries()).map((([t,s])=>{const n=o.get(t)||0,r=i.get(t)||0,a=this.getEstimatedComponentSize(t);return{typeName:t,instanceCount:s.count,memoryPerInstance:a,totalMemory:s.count*a,poolSize:n,poolUtilization:r,averagePerEntity:s.count/e.buffer.length}}))}}getEstimatedComponentSize(t){if(G.componentSizeCache.has(t))return G.componentSizeCache.get(t);const e=K.scene;if(!e)return 64;const s=e.entities;if(!s?.buffer)return 64;let n=64;try{for(const e of s.buffer)if(e.components){const s=e.components.find((e=>e.constructor.name===t));if(s){n=this.calculateQuickObjectSize(s);break}}}catch(t){n=64}return G.componentSizeCache.set(t,n),n}calculateQuickObjectSize(t){if(!t||"object"!=typeof t)return 8;let e=32;const s=new WeakSet,n=(t,e=0)=>{if(!t||"object"!=typeof t||s.has(t)||e>3)return 0;s.add(t);let i=0;try{const s=Object.keys(t);for(let o=0;o<Math.min(s.length,20);o++){const r=s[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+=n(a,e+1))}}catch(t){return 32}return i};return e+=n(t),Math.max(e,32)}calculateDetailedComponentMemory(t){const e=K.scene;if(!e)return this.getEstimatedComponentSize(t);const s=e.entities;if(!s?.buffer)return this.getEstimatedComponentSize(t);try{for(const e of s.buffer)if(e.components){const s=e.components.find((e=>e.constructor.name===t));if(s)return this.estimateObjectSize(s)}}catch(t){}return this.getEstimatedComponentSize(t)}estimateObjectSize(t,e=new WeakSet,s=0){if(null==t||s>10)return 0;if(e.has(t))return 0;let n=0;switch(typeof t){case"boolean":n=4;break;case"number":default:n=8;break;case"string":n=24+Math.min(2*t.length,1e3);break;case"object":if(e.add(t),Array.isArray(t)){n=40+8*t.length;const i=Math.min(t.length,50);for(let o=0;o<i;o++)n+=this.estimateObjectSize(t[o],e,s+1)}else{n=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{n+=16+2*o.length;const i=t[o];null!=i&&(n+=this.estimateObjectSize(i,e,s+1))}catch(t){continue}}}catch(t){n=128}}}return 8*Math.ceil(n/8)}static clearCache(){G.componentSizeCache.clear()}}G.componentSizeCache=new Map;class Q{constructor(){this.sceneStartTime=Date.now()}collectSceneData(){const t=K.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,s=t.entities,n=t.entityProcessors;return{currentSceneName:t.name||"Unnamed Scene",isInitialized:t._didSceneBegin||!1,sceneRunTime:e,sceneEntityCount:s?.buffer?.length||0,sceneSystemCount:n?.processors?.length||0,sceneMemory:0,sceneUptime:e}}setSceneStartTime(t){this.sceneStartTime=t}}class W{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 V{constructor(t,e){this.frameCounter=0,this.lastSendTime=0,this.isRunning=!1,this.config=e,this.entityCollector=new $,this.systemCollector=new j,this.performanceCollector=new Y,this.componentCollector=new G,this.sceneCollector=new Q,this.webSocketManager=new W(e.websocketUrl,!1!==e.autoReconnect),this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));const s=e.debugFrameRate||30;this.sendInterval=1e3/s,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 W(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:s,propertyPath:n,requestId:i}=t;if(void 0===e||void 0===s||!n)return void this.webSocketManager.send({type:"expand_lazy_object_response",requestId:i,error:"缺少必要参数"});const o=this.entityCollector.expandLazyObject(e,s,n);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:s,requestId:n}=t;if(void 0===e||void 0===s)return void this.webSocketManager.send({type:"get_component_properties_response",requestId:n,error:"缺少必要参数"});const i=this.entityCollector.getComponentProperties(e,s);this.webSocketManager.send({type:"get_component_properties_response",requestId:n,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,s=this.entityCollector.getRawEntityList();this.webSocketManager.send({type:"get_raw_entity_list_response",requestId:e,data:s})}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:s}=t;if(void 0===e)return void this.webSocketManager.send({type:"get_entity_details_response",requestId:s,error:"缺少实体ID参数"});const n=this.entityCollector.getEntityDetails(e);this.webSocketManager.send({type:"get_entity_details_response",requestId:s,data:n})}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(),s=this.collectBaseMemoryInfo(),n=this.collectComponentMemoryStats(K.scene?.entities),i=this.collectSystemMemoryStats(),o=this.collectPoolMemoryStats(),r=this.collectPerformanceStats(),a=e.entitiesPerArchetype.reduce(((t,e)=>t+e.memory),0);return{timestamp:t,version:"2.0",summary:{totalEntities:e.totalEntities,totalMemoryUsage:s.usedMemory,totalMemoryLimit:s.totalMemory,memoryUtilization:s.usedMemory/s.totalMemory*100,gcCollections:s.gcCollections,entityMemory:a,componentMemory:n.totalMemory,systemMemory:i.totalMemory,poolMemory:o.totalMemory},baseMemory:s,entities:{totalMemory:a,entityCount:e.totalEntities,archetypes:e.entitiesPerArchetype,largestEntities:e.topEntitiesByComponents},components:n,systems:i,pools:o,performance:r}}collectBaseMemoryInfo(){const t={totalMemory:0,usedMemory:0,freeMemory:0,gcCollections:0,heapInfo:null};try{if(performance.memory){const e=performance.memory;t.totalMemory=e.jsHeapSizeLimit||536870912,t.usedMemory=e.usedJSHeapSize||0,t.freeMemory=t.totalMemory-t.usedMemory,t.heapInfo={totalJSHeapSize:e.totalJSHeapSize||0,usedJSHeapSize:e.usedJSHeapSize||0,jsHeapSizeLimit:e.jsHeapSizeLimit||0}}else t.totalMemory=536870912,t.freeMemory=536870912;performance.measureUserAgentSpecificMemory&&performance.measureUserAgentSpecificMemory().then((e=>{t.detailedMemory=e})).catch((()=>{}))}catch(t){}return t}collectComponentMemoryStats(t){const e=new Map;let s=0;const n=new Map;for(const e of t.buffer)if(e&&!e.destroyed&&e.components)for(const t of e.components){const e=t.constructor.name;n.set(e,(n.get(e)||0)+1)}for(const[i,o]of n.entries()){const n=this.componentCollector.calculateDetailedComponentMemory(i),r=n*o;s+=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(t.constructor.name===i&&(a.push({entityId:e.id,entityName:e.name||`Entity_${e.id}`,memory:n}),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:s>0?e.totalMemory/s*100:0,largestInstances:e.instances.sort(((t,e)=>e.memory-t.memory)).slice(0,3)}))).sort(((t,e)=>e.totalMemory-t.totalMemory));return{totalMemory:s,componentTypes:e.size,totalInstances:Array.from(e.values()).reduce(((t,e)=>t+e.count),0),breakdown:i}}collectSystemMemoryStats(){const t=K.scene;let e=0;const s=[];try{const n=t.entityProcessors;if(n&&n.processors){const t=new Map;for(const i of n.processors){const n=i.constructor.name;let o;t.has(n)?o=t.get(n):(o=this.calculateQuickSystemSize(i),t.set(n,o)),e+=o,s.push({name:n,memory:o,enabled:!1!==i.enabled,updateOrder:i.updateOrder||0})}}}catch(t){}return{totalMemory:e,systemCount:s.length,breakdown:s.sort(((t,e)=>e.memory-t.memory))}}calculateQuickSystemSize(t){if(!t||"object"!=typeof t)return 64;let e=128;try{const s=Object.keys(t);for(let n=0;n<Math.min(s.length,15);n++){const i=s[n];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{ComponentPoolManager:s}=require("../../ECS/Core/ComponentPool"),n=s.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{Pool:s}=require("../../Utils/Pool"),n=s.getStats();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=K.Instance._performanceMonitor;if(!t)return{enabled:!1};const e=t.getAllSystemStats(),s=t.getPerformanceWarnings();return{enabled:t.enabled,systemCount:e.size,warnings:s.slice(0,10),topSystems:Array.from(e.entries()).map((t=>{const[e,s]=t;return{name:e,averageTime:s.averageTime,maxTime:s.maxTime,samples:s.executionCount}})).sort(((t,e)=>e.averageTime-t.averageTime)).slice(0,5)}}catch(t){return{enabled:!1,error:t.message}}}getMemorySizeCategory(t){return t<1024?"< 1KB":t<10240?"1-10KB":t<102400?"10-100KB":t<1048576?"100KB-1MB":"> 1MB"}getDebugData(){const t=Date.now(),e=K.scene,s={timestamp:t,frameworkVersion:"1.0.0",isRunning:this.isRunning,frameworkLoaded:!0,currentScene:e?.name||"Unknown"};if(this.config.channels.entities&&(s.entities=this.entityCollector.collectEntityData()),this.config.channels.systems){const t=K.Instance._performanceMonitor;s.systems=this.systemCollector.collectSystemData(t)}if(this.config.channels.performance){const t=K.Instance._performanceMonitor;s.performance=this.performanceCollector.collectPerformanceData(t)}return this.config.channels.components&&(s.components=this.componentCollector.collectComponentData()),this.config.channels.scenes&&(s.scenes=this.sceneCollector.collectSceneData()),s}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 K{constructor(t={}){this._nextScene=null,this._globalManagers=[],K._instance=this,this._config={debug:!0,enableEntitySystems:!0,...t},this._timerManager=new n,K.registerGlobalManager(this._timerManager),this._performanceMonitor=l.instance,this._config.debug&&this._performanceMonitor.enable(),this._poolManager=d.getInstance(),K.entitySystemsEnabled=this._config.enableEntitySystems||!0,this.debug=this._config.debug||!0,this._config.debugConfig?.enabled&&(this._debugManager=new V(this,this._config.debugConfig)),this.initialize()}static get Instance(){return this._instance}static get scene(){return this._instance&&this._instance._scene||null}static set scene(t){if(t){if(!t)throw new Error("场景不能为空");null==this._instance._scene?(this._instance._scene=t,this._instance.onSceneChanged(),this._instance._scene.begin()):this._instance._nextScene=t}}static create(t=!0){if(null==this._instance){const e="boolean"==typeof t?{debug:t,enableEntitySystems:!0}:t;this._instance=new K(e)}return this._instance}static update(t){this._instance?this._instance.updateInternal(t):console.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,s=null,n){return this._instance._timerManager.schedule(t,e,s,n)}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 V(this._instance,t),this._instance._config.debugConfig=t):console.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}onSceneChanged(){if(e.sceneChanged(),this._scene&&void 0!==this._scene.querySystem){const t=this._scene;this._ecsAPI=L(t,t.querySystem,t.eventSystem)}this._debugManager&&this._debugManager.onSceneChanged()}initialize(){}updateInternal(t){if(K.paused)return;const s=this._performanceMonitor.startMonitoring("Core.update");e.update(t),"function"==typeof this._performanceMonitor.updateFPS&&this._performanceMonitor.updateFPS(e.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(),null!=this._nextScene&&(null!=this._scene&&this._scene.end(),this._scene=this._nextScene,this._nextScene=null,this.onSceneChanged(),this._scene.begin()),null!=this._scene&&this._scene.update){const t=this._performanceMonitor.startMonitoring("Scene.update");this._scene.update();const e=this._scene.entities?.count||0;this._performanceMonitor.endMonitoring("Scene.update",t,e)}this._debugManager&&this._debugManager.onFrameUpdate(t),this._performanceMonitor.endMonitoring("Core.update",s)}}K.paused=!1;class J{constructor(t,e){this.func=t,this.context=e}}class X{constructor(){this._messageTable=new Map}addObserver(t,e,s){let n=this._messageTable.get(t);n||(n=[],this._messageTable.set(t,n)),this.hasObserver(t,e)||n.push(new J(e,s))}removeObserver(t,e){let s=this._messageTable.get(t);if(s){let t=s.findIndex((t=>t.func==e));-1!=t&&s.splice(t,1)}}emit(t,...e){let s=this._messageTable.get(t);if(s)for(let t of s)t.func.call(t.context,...e)}hasObserver(t,e){let s=this._messageTable.get(t);return!!s&&s.some((t=>t.func===e))}}class Z{constructor(){this._enabled=!0,this._updateOrder=0,this.id=Z._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(){}}Z._idGenerator=0,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"}(h||(h={})),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"}(m||(m={}));const tt={ENTITY:{CREATED:h.ENTITY_CREATED,DESTROYED:h.ENTITY_DESTROYED,ENABLED:h.ENTITY_ENABLED,DISABLED:h.ENTITY_DISABLED,TAG_ADDED:h.ENTITY_TAG_ADDED,TAG_REMOVED:h.ENTITY_TAG_REMOVED,NAME_CHANGED:h.ENTITY_NAME_CHANGED},COMPONENT:{ADDED:h.COMPONENT_ADDED,REMOVED:h.COMPONENT_REMOVED,MODIFIED:h.COMPONENT_MODIFIED,ENABLED:h.COMPONENT_ENABLED,DISABLED:h.COMPONENT_DISABLED},SYSTEM:{ADDED:h.SYSTEM_ADDED,REMOVED:h.SYSTEM_REMOVED,ENABLED:h.SYSTEM_ENABLED,DISABLED:h.SYSTEM_DISABLED,PROCESSING_START:h.SYSTEM_PROCESSING_START,PROCESSING_END:h.SYSTEM_PROCESSING_END,ERROR:h.SYSTEM_ERROR},PERFORMANCE:{WARNING:h.PERFORMANCE_WARNING,CRITICAL:h.PERFORMANCE_CRITICAL,MEMORY_HIGH:h.MEMORY_USAGE_HIGH,FRAME_DROP:h.FRAME_RATE_DROP}};class et{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)}}et.validTypes=new Set([...Object.values(h),...Object.values(tt.ENTITY),...Object.values(tt.COMPONENT),...Object.values(tt.SYSTEM),...Object.values(tt.PERFORMANCE)]);class st{constructor(t=0n){this._value=0n,this._value=t}set(t){if(t<0)throw new Error("Bit index cannot be negative");this._value|=1n<<BigInt(t)}clear(t){if(t<0)throw new Error("Bit index cannot be negative");this._value&=~(1n<<BigInt(t))}get(t){return!(t<0)&&0n!=(this._value&1n<<BigInt(t))}containsAll(t){return(this._value&t._value)===t._value}intersects(t){return 0n!==(this._value&t._value)}excludes(t){return!this.intersects(t)}clearAll(){this._value=0n}isEmpty(){return 0n===this._value}cardinality(){let t=0,e=this._value;for(;e>0n;)1n&e&&t++,e>>=1n;return t}and(t){return new st(this._value&t._value)}or(t){return new st(this._value|t._value)}xor(t){return new st(this._value^t._value)}not(t=64){const e=(1n<<BigInt(t))-1n;return new st(~this._value&e)}copyFrom(t){this._value=t._value}clone(){return new st(this._value)}getValue(){return this._value}setValue(t){this._value=t}toString(){const t=[];let e=0,s=this._value;for(;s>0n;)1n&s&&t.push(e.toString()),s>>=1n,e++;return`Bits[${t.join(", ")}]`}toBinaryString(t=64){let e="";for(let s=t-1;s>=0;s--)e+=this.get(s)?"1":"0",s%8==0&&s>0&&(e+=" ");return e}toHexString(){return"0x"+this._value.toString(16).toUpperCase()}static fromBinaryString(t){const e=t.replace(/\s/g,""),s=BigInt("0b"+e);return new st(s)}static fromHexString(t){const e=t.replace(/^0x/i,""),s=BigInt("0x"+e);return new st(s)}equals(t){return this._value===t._value}getHighestBitIndex(){if(0n===this._value)return-1;let t=0,e=this._value;for(;e>1n;)e>>=1n,t++;return t}getLowestBitIndex(){if(0n===this._value)return-1;let t=0,e=this._value;for(;0n==(1n&e);)e>>=1n,t++;return t}}class nt{static get instance(){return nt._instance||(nt._instance=new nt),nt._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,t.name)),e}getTypeName(t){return this._typeNames.get(t)||"Unknown"}createBits(...t){const e=new st;for(const s of t){const t=this.getTypeId(s);e.set(t)}return e}getEntityBits(t){const e=new st;for(const s of t){const t=this.getTypeId(s.constructor);e.set(t)}return e}reset(){this._componentTypes.clear(),this._typeNames.clear(),this._nextTypeId=0}get registeredTypeCount(){return this._componentTypes.size}}class it{constructor(){this.allSet=[],this.exclusionSet=[],this.oneSet=[],this._isDirty=!0}static empty(){return new it}getAllSet(){return this.allSet}getExclusionSet(){return this.exclusionSet}getOneSet(){return this.oneSet}isInterestedEntity(t){const e=this.getEntityBits(t);return this.isInterested(e)}isInterested(t){return this.updateBitsIfDirty(),!(this._allBits&&!t.containsAll(this._allBits))&&((!this._exclusionBits||!t.intersects(this._exclusionBits))&&!(this._oneBits&&!t.intersects(this._oneBits)))}all(...t){return this.allSet.push(...t),this._isDirty=!0,this}exclude(...t){return this.exclusionSet.push(...t),this._isDirty=!0,this}one(...t){return this.oneSet.push(...t),this._isDirty=!0,this}getEntityBits(t){const e=t.components;return nt.instance.getEntityBits(e)}updateBitsIfDirty(){if(!this._isDirty)return;const t=nt.instance;this.allSet.length>0?this._allBits=t.createBits(...this.allSet):this._allBits=void 0,this.exclusionSet.length>0?this._exclusionBits=t.createBits(...this.exclusionSet):this._exclusionBits=void 0,this.oneSet.length>0?this._oneBits=t.createBits(...this.oneSet):this._oneBits=void 0,this._isDirty=!1}toString(){const t=[];return this.allSet.length>0&&t.push(`all: [${this.allSet.map((t=>t.name)).join(", ")}]`),this.exclusionSet.length>0&&t.push(`exclude: [${this.exclusionSet.map((t=>t.name)).join(", ")}]`),this.oneSet.length>0&&t.push(`one: [${this.oneSet.map((t=>t.name)).join(", ")}]`),`Matcher(${t.join(", ")})`}}class ot{get entities(){return this._entities}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._entities=[],this._updateOrder=0,this._enabled=!0,this._performanceMonitor=l.instance,this._matcher=t||it.empty(),this._systemName=this.constructor.name}get scene(){return this._scene}set scene(t){this._scene=t,this._entities=[]}get matcher(){return this._matcher}setUpdateOrder(t){this._updateOrder=t,this.scene.entityProcessors.setDirty()}initialize(){if(this.scene?.entities?.buffer)for(const t of this.scene.entities.buffer)this.onChanged(t)}onChanged(t){const e=this._entities.includes(t),s=this._matcher.isInterestedEntity(t);s&&!e?this.add(t):!s&&e&&this.remove(t)}add(t){this._entities.includes(t)||(this._entities.push(t),this.onAdded(t))}onAdded(t){}remove(t){const e=this._entities.indexOf(t);-1!==e&&(this._entities.splice(e,1),this.onRemoved(t))}onRemoved(t){}update(){if(!this._enabled||!this.checkProcessing())return;const t=this._performanceMonitor.startMonitoring(this._systemName);try{this.begin(),this.process(this._entities)}finally{this._performanceMonitor.endMonitoring(this._systemName,t,this._entities.length)}}lateUpdate(){if(!this._enabled||!this.checkProcessing())return;const t=this._performanceMonitor.startMonitoring(`${this._systemName}_Late`);try{this.lateProcess(this._entities),this.end()}finally{this._performanceMonitor.endMonitoring(`${this._systemName}_Late`,t,this._entities.length)}}begin(){}process(t){}lateProcess(t){}end(){}checkProcessing(){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(),s=e?` (${e.executionTime.toFixed(2)}ms)`:"";return`${this._systemName}[${t} entities]${s}`}}class rt extends ot{onChanged(t){}process(t){this.processSystem()}}class at extends ot{onChanged(t){}process(t){}}class ct extends ot{constructor(t,e){super(t),this.acc=0,this.intervalRemainder=0,this.interval=e}checkProcessing(){return this.acc+=e.deltaTime,this.acc>=this.interval&&(this.intervalRemainder=this.acc-this.interval,this.acc=0,!0)}getIntervalDelta(){return this.interval+this.intervalRemainder}}class ht{constructor(t=!1){this.eventIdCounter=0,this.isDebugMode=!1,this.eventSystem=new k,this.isDebugMode=t}emit(t,e){this.validateEventType(t);const s=this.enhanceEventData(t,e);this.isDebugMode&&console.log(`[EventBus] 发射事件: ${t}`,s),this.eventSystem.emitSync(t,s)}async emitAsync(t,e){this.validateEventType(t);const s=this.enhanceEventData(t,e);this.isDebugMode&&console.log(`[EventBus] 发射异步事件: ${t}`,s),await this.eventSystem.emit(t,s)}on(t,e,s={}){this.validateEventType(t);const n={once:s.once||!1,priority:s.priority||m.NORMAL,async:s.async||!1,context:s.context};return this.isDebugMode&&console.log(`[EventBus] 添加监听器: ${t}`,n),this.eventSystem.on(t,e,n)}once(t,e,s={}){return this.on(t,e,{...s,once:!0})}onAsync(t,e,s={}){return this.on(t,e,{...s,async:!0})}off(t,e){return this.isDebugMode&&console.log(`[EventBus] 移除监听器: ${e} 事件: ${t}`),this.eventSystem.off(t,e)}offAll(t){this.isDebugMode&&console.log(`[EventBus] 移除所有监听器: ${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,s)=>{t.set(s,this.convertEventStats(e))})),t}return this.convertEventStats(e)}clear(){this.isDebugMode&&console.log("[EventBus] 清空所有监听器"),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,s){this.eventSystem.setBatchConfig(t,{batchSize:e,delay:s,enabled:!0})}flushBatch(t){this.eventSystem.flushBatch(t)}resetStats(t){this.eventSystem.resetStats(t)}emitEntityCreated(t){this.emit(h.ENTITY_CREATED,t)}emitEntityDestroyed(t){this.emit(h.ENTITY_DESTROYED,t)}emitComponentAdded(t){this.emit(h.COMPONENT_ADDED,t)}emitComponentRemoved(t){this.emit(h.COMPONENT_REMOVED,t)}emitSystemAdded(t){this.emit(h.SYSTEM_ADDED,t)}emitSystemRemoved(t){this.emit(h.SYSTEM_REMOVED,t)}emitSceneChanged(t){this.emit(h.SCENE_ACTIVATED,t)}emitPerformanceWarning(t){this.emit(h.PERFORMANCE_WARNING,t)}onEntityCreated(t,e){return this.on(h.ENTITY_CREATED,t,e)}onComponentAdded(t,e){return this.on(h.COMPONENT_ADDED,t,e)}onSystemError(t,e){return this.on(h.SYSTEM_ERROR,t,e)}onPerformanceWarning(t,e){return this.on(h.PERFORMANCE_WARNING,t,e)}validateEventType(t){et.isValid(t)||(this.isDebugMode&&console.warn(`[EventBus] 未知事件类型: ${t}`),this.isDebugMode&&et.addCustomType(t))}enhanceEventData(t,e){const s=e;return s.timestamp||(s.timestamp=Date.now()),s.eventId||(s.eventId=`${t}_${++this.eventIdCounter}`),s.source||(s.source="EventBus"),s}convertEventStats(t){return{eventType:t.eventType,listenerCount:t.listenerCount,triggerCount:t.triggerCount,totalExecutionTime:t.totalExecutionTime,averageExecutionTime:t.averageExecutionTime,lastTriggerTime:t.lastTriggerTime}}}class mt{static getInstance(t=!1){return this.instance||(this.instance=new ht(t)),this.instance}static reset(t=!1){return this.instance&&this.instance.clear(),this.instance=new ht(t),this.instance}}function lt(t,e={}){return function(s,n,i){const o=i.value,r=s.constructor.prototype.initEventListeners||function(){};return s.constructor.prototype.initEventListeners=function(){r.call(this);mt.getInstance().on(t,o.bind(this),e)},i}}function ut(t,e={}){return function(s,n,i){const o=i.value,r=s.constructor.prototype.initEventListeners||function(){};return s.constructor.prototype.initEventListeners=function(){r.call(this);mt.getInstance().onAsync(t,o.bind(this),e)},i}}class pt{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 s of this._anyComponents)if(t.hasComponent(s)){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 dt{constructor(){this._entities=new Map,this._entitiesByName=new Map,this._entitiesByTag=new Map,this._destroyedEntities=new Set,this._identifierPool=new M,this._componentIndexManager=new A(r.HASH),this._archetypeSystem=new O,this._dirtyTrackingSystem=new N,this._eventBus=new ht(!1),E.eventBus=this._eventBus}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=`Entity_${Date.now()}`){const e=this._identifierPool.checkOut(),s=new E(t,e);return this._entities.set(e,s),this.updateNameIndex(s,!0),this.updateTagIndex(s,!0),this._componentIndexManager.addEntity(s),this._archetypeSystem.addEntity(s),this._dirtyTrackingSystem.markDirty(s,a.COMPONENT_ADDED),this._eventBus.emitEntityCreated({timestamp:Date.now(),source:"EntityManager",entityId:s.id,entityName:s.name,entityTag:s.tag?.toString()}),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,a.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[...this._entitiesByTag.get(t)||[]]}getEntitiesWithComponent(t){const e=this._componentIndexManager.query(t);return Array.from(e)}query(){return new pt(this)}queryWithComponentIndex(t,e){return this._componentIndexManager.queryMultiple(t,e)}markEntityDirty(t,e){this._dirtyTrackingSystem.markDirty(t,a.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 s=e.indexOf(t);-1!==s&&(e.splice(s,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 s=e.indexOf(t);-1!==s&&(e.splice(s,1),0===e.length&&this._entitiesByTag.delete(t.tag))}}}}class yt{static getType(t){return t.constructor}}class gt{static toNumber(t){return null==t?0:Number(t)}}export{O as ArchetypeSystem,ut as AsyncEventHandler,v as BitMaskOptimizer,D as BitmapComponentIndex,st as Bits,Z as Component,G as ComponentDataCollector,A as ComponentIndexManager,b as ComponentPool,I as ComponentPoolManager,g as ComponentStorage,nt as ComponentTypeManager,K as Core,V as DebugManager,a as DirtyFlag,N as DirtyTrackingSystem,h as ECSEventType,U as ECSFluentAPI,tt as EVENT_TYPES,X as Emitter,E as Entity,$ as EntityDataCollector,S as EntityList,dt as EntityManager,C as EntityProcessorList,pt as EntityQueryBuilder,ot as EntitySystem,ht as EventBus,lt as EventHandler,m as EventPriority,et as EventTypeValidator,J as FuncPack,mt as GlobalEventBus,t as GlobalManager,x as HashComponentIndex,M as IdentifierPool,r as IndexType,w as IndexUpdateBatcher,ct as IntervalSystem,it as Matcher,gt as NumberExtension,at as PassiveSystem,Y as PerformanceDataCollector,l as PerformanceMonitor,i as PerformanceWarningType,u as Pool,d as PoolManager,rt as ProcessingSystem,R as QuerySystem,P as Scene,Q as SceneDataCollector,j as SystemDataCollector,p as TieredObjectPool,e as Time,s as Timer,n as TimerManager,k as TypeSafeEventSystem,yt as TypeUtils,W as WebSocketManager,L as createECSAPI};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|