@esengine/ecs-framework 2.0.6 → 2.0.8

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.
Files changed (124) hide show
  1. package/bin/Core.js +21 -17
  2. package/bin/Core.js.map +1 -1
  3. package/bin/ECS/Component.js +5 -1
  4. package/bin/ECS/Component.js.map +1 -1
  5. package/bin/ECS/Components/IUpdatable.js +7 -2
  6. package/bin/ECS/Components/IUpdatable.js.map +1 -1
  7. package/bin/ECS/Components/SceneComponent.js +5 -1
  8. package/bin/ECS/Components/SceneComponent.js.map +1 -1
  9. package/bin/ECS/Core/BitMaskOptimizer.d.ts +75 -0
  10. package/bin/ECS/Core/BitMaskOptimizer.d.ts.map +1 -0
  11. package/bin/ECS/Core/BitMaskOptimizer.js +165 -0
  12. package/bin/ECS/Core/BitMaskOptimizer.js.map +1 -0
  13. package/bin/ECS/Core/ComponentPool.d.ts +72 -0
  14. package/bin/ECS/Core/ComponentPool.d.ts.map +1 -0
  15. package/bin/ECS/Core/ComponentPool.js +128 -0
  16. package/bin/ECS/Core/ComponentPool.js.map +1 -0
  17. package/bin/ECS/Core/ComponentStorage.js +9 -3
  18. package/bin/ECS/Core/ComponentStorage.js.map +1 -1
  19. package/bin/ECS/Core/EventSystem.js +12 -6
  20. package/bin/ECS/Core/EventSystem.js.map +1 -1
  21. package/bin/ECS/Core/FluentAPI.js +24 -17
  22. package/bin/ECS/Core/FluentAPI.js.map +1 -1
  23. package/bin/ECS/Core/IndexUpdateBatcher.d.ts +100 -0
  24. package/bin/ECS/Core/IndexUpdateBatcher.d.ts.map +1 -0
  25. package/bin/ECS/Core/IndexUpdateBatcher.js +223 -0
  26. package/bin/ECS/Core/IndexUpdateBatcher.js.map +1 -0
  27. package/bin/ECS/Core/QuerySystem.d.ts +292 -444
  28. package/bin/ECS/Core/QuerySystem.d.ts.map +1 -1
  29. package/bin/ECS/Core/QuerySystem.js +661 -1075
  30. package/bin/ECS/Core/QuerySystem.js.map +1 -1
  31. package/bin/ECS/CoreEvents.js +5 -2
  32. package/bin/ECS/CoreEvents.js.map +1 -1
  33. package/bin/ECS/Entity.js +17 -12
  34. package/bin/ECS/Entity.js.map +1 -1
  35. package/bin/ECS/Scene.d.ts +18 -2
  36. package/bin/ECS/Scene.d.ts.map +1 -1
  37. package/bin/ECS/Scene.js +67 -19
  38. package/bin/ECS/Scene.js.map +1 -1
  39. package/bin/ECS/Systems/EntitySystem.js +9 -5
  40. package/bin/ECS/Systems/EntitySystem.js.map +1 -1
  41. package/bin/ECS/Systems/IntervalSystem.js +8 -4
  42. package/bin/ECS/Systems/IntervalSystem.js.map +1 -1
  43. package/bin/ECS/Systems/PassiveSystem.js +6 -2
  44. package/bin/ECS/Systems/PassiveSystem.js.map +1 -1
  45. package/bin/ECS/Systems/ProcessingSystem.js +6 -2
  46. package/bin/ECS/Systems/ProcessingSystem.js.map +1 -1
  47. package/bin/ECS/Systems/index.js +11 -4
  48. package/bin/ECS/Systems/index.js.map +1 -1
  49. package/bin/ECS/Utils/Bits.js +5 -1
  50. package/bin/ECS/Utils/Bits.js.map +1 -1
  51. package/bin/ECS/Utils/ComponentTypeManager.js +8 -4
  52. package/bin/ECS/Utils/ComponentTypeManager.js.map +1 -1
  53. package/bin/ECS/Utils/EntityList.js +5 -1
  54. package/bin/ECS/Utils/EntityList.js.map +1 -1
  55. package/bin/ECS/Utils/EntityProcessorList.js +5 -1
  56. package/bin/ECS/Utils/EntityProcessorList.js.map +1 -1
  57. package/bin/ECS/Utils/IdentifierPool.js +5 -1
  58. package/bin/ECS/Utils/IdentifierPool.js.map +1 -1
  59. package/bin/ECS/Utils/Matcher.js +8 -4
  60. package/bin/ECS/Utils/Matcher.js.map +1 -1
  61. package/bin/ECS/Utils/index.js +15 -6
  62. package/bin/ECS/Utils/index.js.map +1 -1
  63. package/bin/ECS/index.js +27 -6
  64. package/bin/ECS/index.js.map +1 -1
  65. package/bin/Testing/Performance/benchmark.d.ts +6 -0
  66. package/bin/Testing/Performance/benchmark.d.ts.map +1 -0
  67. package/bin/Testing/Performance/benchmark.js +639 -0
  68. package/bin/Testing/Performance/benchmark.js.map +1 -0
  69. package/bin/Testing/Unit/bitmask-optimizer.test.d.ts +2 -0
  70. package/bin/Testing/Unit/bitmask-optimizer.test.d.ts.map +1 -0
  71. package/bin/Testing/Unit/bitmask-optimizer.test.js +164 -0
  72. package/bin/Testing/Unit/bitmask-optimizer.test.js.map +1 -0
  73. package/bin/Testing/Unit/component-pool.test.d.ts +5 -0
  74. package/bin/Testing/Unit/component-pool.test.d.ts.map +1 -0
  75. package/bin/Testing/Unit/component-pool.test.js +149 -0
  76. package/bin/Testing/Unit/component-pool.test.js.map +1 -0
  77. package/bin/Testing/test-runner.d.ts +51 -0
  78. package/bin/Testing/test-runner.d.ts.map +1 -0
  79. package/bin/Testing/test-runner.js +159 -0
  80. package/bin/Testing/test-runner.js.map +1 -0
  81. package/bin/Types/index.js +7 -4
  82. package/bin/Types/index.js.map +1 -1
  83. package/bin/Utils/Emitter.js +7 -2
  84. package/bin/Utils/Emitter.js.map +1 -1
  85. package/bin/Utils/Extensions/NumberExtension.js +5 -1
  86. package/bin/Utils/Extensions/NumberExtension.js.map +1 -1
  87. package/bin/Utils/Extensions/TypeUtils.js +5 -1
  88. package/bin/Utils/Extensions/TypeUtils.js.map +1 -1
  89. package/bin/Utils/Extensions/index.js +7 -2
  90. package/bin/Utils/Extensions/index.js.map +1 -1
  91. package/bin/Utils/GlobalManager.js +5 -1
  92. package/bin/Utils/GlobalManager.js.map +1 -1
  93. package/bin/Utils/PerformanceMonitor.js +7 -3
  94. package/bin/Utils/PerformanceMonitor.js.map +1 -1
  95. package/bin/Utils/Pool.js +9 -3
  96. package/bin/Utils/Pool.js.map +1 -1
  97. package/bin/Utils/Time.js +5 -1
  98. package/bin/Utils/Time.js.map +1 -1
  99. package/bin/Utils/Timers/ITimer.js +2 -1
  100. package/bin/Utils/Timers/Timer.js +7 -3
  101. package/bin/Utils/Timers/Timer.js.map +1 -1
  102. package/bin/Utils/Timers/TimerManager.js +8 -4
  103. package/bin/Utils/Timers/TimerManager.js.map +1 -1
  104. package/bin/Utils/WasmCore.d.ts +234 -0
  105. package/bin/Utils/WasmCore.d.ts.map +1 -0
  106. package/bin/Utils/WasmCore.js +634 -0
  107. package/bin/Utils/WasmCore.js.map +1 -0
  108. package/bin/Utils/index.d.ts +10 -0
  109. package/bin/Utils/index.d.ts.map +1 -1
  110. package/bin/Utils/index.js +36 -5
  111. package/bin/Utils/index.js.map +1 -1
  112. package/bin/index.d.ts +1 -2
  113. package/bin/index.d.ts.map +1 -1
  114. package/bin/index.js +42 -14
  115. package/bin/index.js.map +1 -1
  116. package/package.json +58 -74
  117. package/bin/Utils/AccelerationProvider.d.ts +0 -192
  118. package/bin/Utils/AccelerationProvider.d.ts.map +0 -1
  119. package/bin/Utils/AccelerationProvider.js +0 -261
  120. package/bin/Utils/AccelerationProvider.js.map +0 -1
  121. package/bin/Utils/WasmBridge.d.ts +0 -152
  122. package/bin/Utils/WasmBridge.d.ts.map +0 -1
  123. package/bin/Utils/WasmBridge.js +0 -336
  124. package/bin/Utils/WasmBridge.js.map +0 -1
@@ -0,0 +1,639 @@
1
+ "use strict";
2
+ /**
3
+ * ECS框架性能基准测试
4
+ * 测试框架在不同场景下的性能表现
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ const Scene_1 = require("../../ECS/Scene");
41
+ const Component_1 = require("../../ECS/Component");
42
+ console.log('🚀 ECS框架性能基准测试');
43
+ console.log('============================================================');
44
+ console.log('测试目标: 评估ECS框架在不同场景下的性能表现');
45
+ console.log('============================================================');
46
+ /**
47
+ * 位置组件
48
+ */
49
+ class PositionComponent extends Component_1.Component {
50
+ constructor(x = 0, y = 0) {
51
+ super();
52
+ this.x = 0;
53
+ this.y = 0;
54
+ this.x = x;
55
+ this.y = y;
56
+ }
57
+ }
58
+ /**
59
+ * 速度组件
60
+ */
61
+ class VelocityComponent extends Component_1.Component {
62
+ constructor(vx = 0, vy = 0) {
63
+ super();
64
+ this.vx = 0;
65
+ this.vy = 0;
66
+ this.vx = vx;
67
+ this.vy = vy;
68
+ }
69
+ }
70
+ /**
71
+ * 生命值组件
72
+ */
73
+ class HealthComponent extends Component_1.Component {
74
+ constructor(health = 100) {
75
+ super();
76
+ this.health = 100;
77
+ this.maxHealth = 100;
78
+ this.health = health;
79
+ this.maxHealth = health;
80
+ }
81
+ }
82
+ /**
83
+ * 渲染组件
84
+ */
85
+ class RenderComponent extends Component_1.Component {
86
+ constructor(sprite = '') {
87
+ super();
88
+ this.sprite = '';
89
+ this.visible = true;
90
+ this.sprite = sprite;
91
+ }
92
+ }
93
+ /**
94
+ * AI组件
95
+ */
96
+ class AIComponent extends Component_1.Component {
97
+ constructor(state = 'idle') {
98
+ super();
99
+ this.state = 'idle';
100
+ this.target = null;
101
+ this.state = state;
102
+ }
103
+ }
104
+ /**
105
+ * 测试配置
106
+ */
107
+ const TEST_CONFIG = {
108
+ entityCounts: [1000, 5000, 10000, 25000, 50000, 100000, 200000, 500000],
109
+ queryIterations: 1000,
110
+ updateIterations: 100
111
+ };
112
+ /**
113
+ * 测试创建实体的性能
114
+ */
115
+ function testEntityCreation(scene, count) {
116
+ const startTime = performance.now();
117
+ let entityCreationTime = 0;
118
+ let componentAdditionTime = 0;
119
+ let tagAssignmentTime = 0;
120
+ // 批量创建实体(不添加组件)
121
+ const entityStart = performance.now();
122
+ const entities = scene.createEntities(count, "Entity");
123
+ entityCreationTime = performance.now() - entityStart;
124
+ // 批量添加组件
125
+ const componentStart = performance.now();
126
+ for (let i = 0; i < entities.length; i++) {
127
+ const entity = entities[i];
128
+ // 所有实体都有位置组件
129
+ entity.addComponent(new PositionComponent(Math.random() * 1000, Math.random() * 1000));
130
+ // 70%的实体有速度组件
131
+ if (Math.random() < 0.7) {
132
+ entity.addComponent(new VelocityComponent((Math.random() - 0.5) * 10, (Math.random() - 0.5) * 10));
133
+ }
134
+ // 50%的实体有生命值组件
135
+ if (Math.random() < 0.5) {
136
+ entity.addComponent(new HealthComponent(Math.floor(Math.random() * 100) + 50));
137
+ }
138
+ // 30%的实体有渲染组件
139
+ if (Math.random() < 0.3) {
140
+ entity.addComponent(new RenderComponent(`sprite_${i % 10}`));
141
+ }
142
+ // 20%的实体有AI组件
143
+ if (Math.random() < 0.2) {
144
+ entity.addComponent(new AIComponent(['idle', 'patrol', 'chase'][Math.floor(Math.random() * 3)]));
145
+ }
146
+ }
147
+ componentAdditionTime = performance.now() - componentStart;
148
+ // 批量设置标签
149
+ const tagStart = performance.now();
150
+ for (const entity of entities) {
151
+ entity.tag = Math.floor(Math.random() * 10);
152
+ }
153
+ tagAssignmentTime = performance.now() - tagStart;
154
+ const totalTime = performance.now() - startTime;
155
+ return {
156
+ totalTime,
157
+ averageTime: totalTime / count,
158
+ entitiesPerSecond: count / (totalTime / 1000),
159
+ breakdown: {
160
+ entityCreation: entityCreationTime,
161
+ componentAddition: componentAdditionTime,
162
+ tagAssignment: tagAssignmentTime
163
+ }
164
+ };
165
+ }
166
+ /**
167
+ * 创建测试实体
168
+ */
169
+ function createTestEntities(scene, count) {
170
+ const entities = [];
171
+ for (let i = 0; i < count; i++) {
172
+ const entity = scene.createEntity(`Entity_${i}`);
173
+ // 所有实体都有位置组件
174
+ entity.addComponent(new PositionComponent(Math.random() * 1000, Math.random() * 1000));
175
+ // 70%的实体有速度组件
176
+ if (Math.random() < 0.7) {
177
+ entity.addComponent(new VelocityComponent((Math.random() - 0.5) * 10, (Math.random() - 0.5) * 10));
178
+ }
179
+ // 50%的实体有生命值组件
180
+ if (Math.random() < 0.5) {
181
+ entity.addComponent(new HealthComponent(Math.floor(Math.random() * 100) + 50));
182
+ }
183
+ // 30%的实体有渲染组件
184
+ if (Math.random() < 0.3) {
185
+ entity.addComponent(new RenderComponent(`sprite_${i % 10}`));
186
+ }
187
+ // 20%的实体有AI组件
188
+ if (Math.random() < 0.2) {
189
+ entity.addComponent(new AIComponent(['idle', 'patrol', 'chase'][Math.floor(Math.random() * 3)]));
190
+ }
191
+ // 设置随机标签
192
+ entity.tag = Math.floor(Math.random() * 10);
193
+ entities.push(entity);
194
+ }
195
+ return entities;
196
+ }
197
+ /**
198
+ * 测试单组件查询性能
199
+ */
200
+ function testSingleComponentQuery(scene, iterations) {
201
+ const startTime = performance.now();
202
+ for (let i = 0; i < iterations; i++) {
203
+ scene.querySystem.queryAll(PositionComponent);
204
+ }
205
+ return performance.now() - startTime;
206
+ }
207
+ /**
208
+ * 测试多组件查询性能
209
+ */
210
+ function testMultiComponentQuery(scene, iterations) {
211
+ const startTime = performance.now();
212
+ for (let i = 0; i < iterations; i++) {
213
+ scene.querySystem.queryAll(PositionComponent, VelocityComponent);
214
+ }
215
+ return performance.now() - startTime;
216
+ }
217
+ /**
218
+ * 测试复杂查询性能
219
+ */
220
+ function testComplexQuery(scene, iterations) {
221
+ const startTime = performance.now();
222
+ for (let i = 0; i < iterations; i++) {
223
+ scene.querySystem.queryAll(PositionComponent, VelocityComponent, HealthComponent);
224
+ }
225
+ return performance.now() - startTime;
226
+ }
227
+ /**
228
+ * 测试标签查询性能
229
+ */
230
+ function testTagQuery(scene, iterations) {
231
+ const startTime = performance.now();
232
+ // 优化:预先获取所有标签查询结果,然后重复使用
233
+ // 这更符合实际游戏中的使用模式
234
+ const tags = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
235
+ for (let i = 0; i < iterations; i++) {
236
+ // 批量查询所有标签
237
+ for (const tag of tags) {
238
+ scene.querySystem.queryByTag(tag);
239
+ }
240
+ }
241
+ return performance.now() - startTime;
242
+ }
243
+ /**
244
+ * 测试单个标签查询性能
245
+ */
246
+ function testSingleTagQuery(scene, iterations) {
247
+ const startTime = performance.now();
248
+ // 只查询标签0,测试单个标签的查询性能和缓存效果
249
+ for (let i = 0; i < iterations; i++) {
250
+ scene.querySystem.queryByTag(0);
251
+ }
252
+ return performance.now() - startTime;
253
+ }
254
+ /**
255
+ * 测试实体更新性能
256
+ */
257
+ function testEntityUpdate(scene, iterations) {
258
+ const entities = scene.querySystem.queryAll(PositionComponent, VelocityComponent).entities;
259
+ const startTime = performance.now();
260
+ for (let i = 0; i < iterations; i++) {
261
+ for (const entity of entities) {
262
+ const pos = entity.getComponent(PositionComponent);
263
+ const vel = entity.getComponent(VelocityComponent);
264
+ if (pos && vel) {
265
+ pos.x += vel.vx;
266
+ pos.y += vel.vy;
267
+ }
268
+ }
269
+ }
270
+ return performance.now() - startTime;
271
+ }
272
+ /**
273
+ * 获取内存使用情况
274
+ */
275
+ function getMemoryUsage() {
276
+ if (typeof process !== 'undefined' && process.memoryUsage) {
277
+ return process.memoryUsage().heapUsed / 1024 / 1024; // MB
278
+ }
279
+ return 0;
280
+ }
281
+ /**
282
+ * 运行性能测试
283
+ */
284
+ function runPerformanceTest(scene, entityCount, config) {
285
+ console.log(`\n📊 测试 ${entityCount.toLocaleString()} 个实体...`);
286
+ // 测试实体创建性能
287
+ const startMemory = getMemoryUsage();
288
+ console.log(` 🔧 测试实体创建性能...`);
289
+ const creationStats = testEntityCreation(scene, entityCount);
290
+ const endMemory = getMemoryUsage();
291
+ console.log(` 📈 实体创建性能分析:`);
292
+ console.log(` 总时间: ${creationStats.totalTime.toFixed(2)}ms`);
293
+ console.log(` 平均时间: ${creationStats.averageTime.toFixed(4)}ms/实体`);
294
+ console.log(` 创建速度: ${creationStats.entitiesPerSecond.toFixed(0)} 实体/秒`);
295
+ console.log(` 时间分解:`);
296
+ console.log(` - 实体创建: ${creationStats.breakdown.entityCreation.toFixed(2)}ms (${(creationStats.breakdown.entityCreation / creationStats.totalTime * 100).toFixed(1)}%)`);
297
+ console.log(` - 组件添加: ${creationStats.breakdown.componentAddition.toFixed(2)}ms (${(creationStats.breakdown.componentAddition / creationStats.totalTime * 100).toFixed(1)}%)`);
298
+ console.log(` - 标签分配: ${creationStats.breakdown.tagAssignment.toFixed(2)}ms (${(creationStats.breakdown.tagAssignment / creationStats.totalTime * 100).toFixed(1)}%)`);
299
+ console.log(` 内存使用: ${(endMemory - startMemory).toFixed(1)}MB`);
300
+ // 运行测试
301
+ console.log(` 🔍 执行查询测试...`);
302
+ const singleQuery = testSingleComponentQuery(scene, config.queryIterations);
303
+ const multiQuery = testMultiComponentQuery(scene, config.queryIterations);
304
+ const complexQuery = testComplexQuery(scene, config.queryIterations);
305
+ const tagQuery = testTagQuery(scene, config.queryIterations);
306
+ const singleTagQuery = testSingleTagQuery(scene, config.queryIterations);
307
+ console.log(` ⚡ 执行更新测试...`);
308
+ const entityUpdate = testEntityUpdate(scene, config.updateIterations);
309
+ console.log(` ✅ 测试完成`);
310
+ return {
311
+ entityCount,
312
+ singleQuery,
313
+ multiQuery,
314
+ complexQuery,
315
+ tagQuery,
316
+ singleTagQuery,
317
+ entityUpdate,
318
+ memoryUsage: endMemory - startMemory
319
+ };
320
+ }
321
+ /**
322
+ * 显示系统信息
323
+ */
324
+ function displaySystemInfo(scene) {
325
+ const status = scene.querySystem.getAccelerationStatus();
326
+ const stats = scene.querySystem.getStats();
327
+ console.log('\n🔍 系统信息:');
328
+ console.log(` 当前提供者: ${status.currentProvider}`);
329
+ console.log(` WebAssembly: ${status.wasmEnabled ? '已启用' : '未启用'}`);
330
+ console.log(` 可用提供者: ${status.availableProviders.join(', ')}`);
331
+ console.log(` 索引统计:`);
332
+ console.log(` 组件掩码索引: ${stats.indexStats.maskIndexSize}`);
333
+ console.log(` 组件类型索引: ${stats.indexStats.componentIndexSize}`);
334
+ console.log(` 标签索引: ${stats.indexStats.tagIndexSize}`);
335
+ console.log(` 名称索引: ${stats.indexStats.nameIndexSize}`);
336
+ if (status.performanceInfo?.cacheStats) {
337
+ console.log(` 查询缓存:`);
338
+ console.log(` 缓存大小: ${status.performanceInfo.cacheStats.size}`);
339
+ console.log(` 命中率: ${status.performanceInfo.cacheStats.hitRate}`);
340
+ }
341
+ }
342
+ /**
343
+ * 显示性能结果
344
+ */
345
+ function displayResults(results, scene) {
346
+ console.log('\n📈 ECS框架性能测试结果');
347
+ console.log('='.repeat(130));
348
+ console.log('| 实体数量 | 单组件查询 | 双组件查询 | 三组件查询 | 多标签查询 | 单标签查询 | 实体更新 | 内存使用 |');
349
+ console.log('|' + '-'.repeat(128) + '|');
350
+ for (const result of results) {
351
+ const entityCount = result.entityCount.toLocaleString().padStart(9);
352
+ const singleQuery = `${result.singleQuery.toFixed(2)}ms`.padStart(10);
353
+ const multiQuery = `${result.multiQuery.toFixed(2)}ms`.padStart(10);
354
+ const complexQuery = `${result.complexQuery.toFixed(2)}ms`.padStart(10);
355
+ const tagQuery = `${result.tagQuery.toFixed(2)}ms`.padStart(10);
356
+ const singleTagQuery = `${result.singleTagQuery.toFixed(2)}ms`.padStart(10);
357
+ const entityUpdate = `${result.entityUpdate.toFixed(2)}ms`.padStart(9);
358
+ const memoryUsage = `${result.memoryUsage.toFixed(1)}MB`.padStart(9);
359
+ console.log(`| ${entityCount} | ${singleQuery} | ${multiQuery} | ${complexQuery} | ${tagQuery} | ${singleTagQuery} | ${entityUpdate} | ${memoryUsage} |`);
360
+ }
361
+ console.log('|' + '-'.repeat(128) + '|');
362
+ // 计算性能指标
363
+ const maxEntities = Math.max(...results.map(r => r.entityCount));
364
+ const maxResult = results.find(r => r.entityCount === maxEntities);
365
+ console.log(`\n🎯 性能峰值 (${maxEntities.toLocaleString()} 个实体):`);
366
+ console.log(` 单组件查询: ${(TEST_CONFIG.queryIterations / maxResult.singleQuery * 1000).toFixed(0)} 次/秒`);
367
+ console.log(` 双组件查询: ${(TEST_CONFIG.queryIterations / maxResult.multiQuery * 1000).toFixed(0)} 次/秒`);
368
+ console.log(` 三组件查询: ${(TEST_CONFIG.queryIterations / maxResult.complexQuery * 1000).toFixed(0)} 次/秒`);
369
+ console.log(` 多标签查询: ${(TEST_CONFIG.queryIterations * 10 / maxResult.tagQuery * 1000).toFixed(0)} 次/秒`);
370
+ console.log(` 单标签查询: ${(TEST_CONFIG.queryIterations / maxResult.singleTagQuery * 1000).toFixed(0)} 次/秒`);
371
+ console.log(` 实体更新: ${(maxResult.entityCount * TEST_CONFIG.updateIterations / maxResult.entityUpdate * 1000).toFixed(0)} 个/秒`);
372
+ console.log(` 内存效率: ${(maxResult.entityCount / (maxResult.memoryUsage || 1)).toFixed(0)} 实体/MB`);
373
+ // 性能评级
374
+ const avgQueryTime = (maxResult.singleQuery + maxResult.multiQuery + maxResult.complexQuery + maxResult.singleTagQuery) / 4;
375
+ let rating = '';
376
+ if (avgQueryTime < 50)
377
+ rating = '🚀 优秀';
378
+ else if (avgQueryTime < 100)
379
+ rating = '✅ 良好';
380
+ else if (avgQueryTime < 200)
381
+ rating = '⚠️ 一般';
382
+ else
383
+ rating = '❌ 需要优化';
384
+ console.log(`\n📊 性能评级: ${rating}`);
385
+ console.log(` 平均查询时间: ${avgQueryTime.toFixed(2)}ms`);
386
+ // 显示查询统计信息
387
+ const queryStats = scene.querySystem.getStats().queryStats;
388
+ console.log(`\n🔍 查询统计:`);
389
+ console.log(` 总查询次数: ${queryStats.totalQueries.toLocaleString()}`);
390
+ console.log(` 缓存命中: ${queryStats.cacheHits.toLocaleString()}`);
391
+ console.log(` 索引命中: ${queryStats.indexHits.toLocaleString()}`);
392
+ console.log(` 线性扫描: ${queryStats.linearScans.toLocaleString()}`);
393
+ console.log(` 缓存命中率: ${queryStats.cacheHitRate}`);
394
+ // 标签查询性能分析
395
+ console.log(`\n🏷️ 标签查询分析:`);
396
+ const tagQueryRatio = maxResult.tagQuery / maxResult.singleTagQuery;
397
+ console.log(` 多标签查询 vs 单标签查询: ${tagQueryRatio.toFixed(2)}x (预期约10x)`);
398
+ if (tagQueryRatio > 15) {
399
+ console.log(` ⚠️ 多标签查询性能异常,可能存在缓存问题`);
400
+ }
401
+ else if (tagQueryRatio < 5) {
402
+ console.log(` ✅ 标签查询缓存效果良好`);
403
+ }
404
+ else {
405
+ console.log(` 📊 标签查询性能正常`);
406
+ }
407
+ // 性能改进分析
408
+ const improvement = calculatePerformanceImprovement(results);
409
+ if (improvement) {
410
+ console.log(`\n📈 性能改进分析:`);
411
+ console.log(` 双组件查询改进: ${improvement.multiQuery}x`);
412
+ console.log(` 三组件查询改进: ${improvement.complexQuery}x`);
413
+ console.log(` 整体查询改进: ${improvement.overall}x`);
414
+ }
415
+ // 扩展性分析
416
+ console.log(`\n📊 扩展性分析:`);
417
+ analyzeScalability(results);
418
+ }
419
+ /**
420
+ * 计算性能改进(与优化前对比)
421
+ */
422
+ function calculatePerformanceImprovement(results) {
423
+ // 基于50,000实体的结果进行分析
424
+ const maxResult = results.find(r => r.entityCount === 50000);
425
+ if (!maxResult)
426
+ return null;
427
+ // 优化前的基准时间(基于之前的测试结果)
428
+ const baselineMultiQuery = 1270.54; // ms
429
+ const baselineComplexQuery = 981.76; // ms
430
+ const multiImprovement = (baselineMultiQuery / maxResult.multiQuery).toFixed(2);
431
+ const complexImprovement = (baselineComplexQuery / maxResult.complexQuery).toFixed(2);
432
+ const overallImprovement = ((baselineMultiQuery + baselineComplexQuery) /
433
+ (maxResult.multiQuery + maxResult.complexQuery)).toFixed(2);
434
+ return {
435
+ multiQuery: multiImprovement,
436
+ complexQuery: complexImprovement,
437
+ overall: overallImprovement
438
+ };
439
+ }
440
+ /**
441
+ * 分析系统扩展性
442
+ */
443
+ function analyzeScalability(results) {
444
+ if (results.length < 2)
445
+ return;
446
+ // 分析查询时间随实体数量的变化趋势
447
+ const first = results[0];
448
+ const last = results[results.length - 1];
449
+ const entityRatio = last.entityCount / first.entityCount;
450
+ const singleQueryRatio = last.singleQuery / first.singleQuery;
451
+ const multiQueryRatio = last.multiQuery / first.multiQuery;
452
+ const complexQueryRatio = last.complexQuery / first.complexQuery;
453
+ console.log(` 实体数量增长: ${entityRatio.toFixed(1)}x (${first.entityCount.toLocaleString()} → ${last.entityCount.toLocaleString()})`);
454
+ console.log(` 单组件查询时间增长: ${singleQueryRatio.toFixed(2)}x`);
455
+ console.log(` 双组件查询时间增长: ${multiQueryRatio.toFixed(2)}x`);
456
+ console.log(` 三组件查询时间增长: ${complexQueryRatio.toFixed(2)}x`);
457
+ // 计算复杂度
458
+ const avgComplexity = (singleQueryRatio + multiQueryRatio + complexQueryRatio) / 3;
459
+ let complexityRating = '';
460
+ if (avgComplexity < entityRatio * 0.1)
461
+ complexityRating = '🚀 近似O(1) - 优秀';
462
+ else if (avgComplexity < entityRatio * 0.5)
463
+ complexityRating = '✅ 亚线性 - 良好';
464
+ else if (avgComplexity < entityRatio)
465
+ complexityRating = '⚠️ 接近线性 - 一般';
466
+ else
467
+ complexityRating = '❌ 超线性 - 需要优化';
468
+ console.log(` 时间复杂度评估: ${complexityRating}`);
469
+ // 内存效率分析
470
+ const memoryEfficiencyFirst = first.entityCount / first.memoryUsage;
471
+ const memoryEfficiencyLast = last.entityCount / last.memoryUsage;
472
+ const memoryEfficiencyRatio = memoryEfficiencyLast / memoryEfficiencyFirst;
473
+ console.log(` 内存效率变化: ${memoryEfficiencyRatio.toFixed(2)}x (${memoryEfficiencyFirst.toFixed(0)} → ${memoryEfficiencyLast.toFixed(0)} 实体/MB)`);
474
+ }
475
+ /**
476
+ * 专门测试实体创建性能
477
+ */
478
+ async function runEntityCreationBenchmark() {
479
+ console.log('\n🚀 实体创建性能基准测试');
480
+ console.log('='.repeat(60));
481
+ const testCounts = [1000, 5000, 10000, 50000, 100000];
482
+ for (const count of testCounts) {
483
+ console.log(`\n📊 测试创建 ${count.toLocaleString()} 个实体:`);
484
+ // 创建新场景
485
+ const scene = new Scene_1.Scene();
486
+ // 测试创建性能
487
+ const stats = testEntityCreation(scene, count);
488
+ console.log(` 总时间: ${stats.totalTime.toFixed(2)}ms`);
489
+ console.log(` 平均时间: ${stats.averageTime.toFixed(4)}ms/实体`);
490
+ console.log(` 创建速度: ${stats.entitiesPerSecond.toFixed(0)} 实体/秒`);
491
+ console.log(` 时间分解:`);
492
+ console.log(` - 实体创建: ${stats.breakdown.entityCreation.toFixed(2)}ms (${(stats.breakdown.entityCreation / stats.totalTime * 100).toFixed(1)}%)`);
493
+ console.log(` - 组件添加: ${stats.breakdown.componentAddition.toFixed(2)}ms (${(stats.breakdown.componentAddition / stats.totalTime * 100).toFixed(1)}%)`);
494
+ console.log(` - 标签分配: ${stats.breakdown.tagAssignment.toFixed(2)}ms (${(stats.breakdown.tagAssignment / stats.totalTime * 100).toFixed(1)}%)`);
495
+ // 分析性能瓶颈
496
+ const { entityCreation, componentAddition, tagAssignment } = stats.breakdown;
497
+ const total = stats.totalTime;
498
+ console.log(` 性能瓶颈分析:`);
499
+ if (componentAddition / total > 0.5) {
500
+ console.log(` ⚠️ 组件添加是主要瓶颈 (${(componentAddition / total * 100).toFixed(1)}%)`);
501
+ }
502
+ if (entityCreation / total > 0.3) {
503
+ console.log(` ⚠️ 实体创建开销较高 (${(entityCreation / total * 100).toFixed(1)}%)`);
504
+ }
505
+ if (tagAssignment / total > 0.1) {
506
+ console.log(` ⚠️ 标签分配开销异常 (${(tagAssignment / total * 100).toFixed(1)}%)`);
507
+ }
508
+ // 分析组件添加性能(仅对较小的测试集)
509
+ if (count <= 10000) {
510
+ analyzeComponentAdditionPerformance(new Scene_1.Scene(), Math.min(count, 5000));
511
+ }
512
+ // 清理场景
513
+ scene.end();
514
+ }
515
+ console.log('\n📈 实体创建性能总结:');
516
+ console.log(' 主要性能瓶颈通常在组件添加阶段');
517
+ console.log(' 建议优化方向:');
518
+ console.log(' 1. 减少组件注册开销');
519
+ console.log(' 2. 优化位掩码计算');
520
+ console.log(' 3. 减少内存分配次数');
521
+ console.log(' 4. 使用对象池复用组件实例');
522
+ }
523
+ /**
524
+ * 测试组件添加性能的详细分析
525
+ */
526
+ function analyzeComponentAdditionPerformance(scene, count) {
527
+ console.log(`\n🔬 组件添加性能详细分析 (${count.toLocaleString()} 个实体):`);
528
+ // 创建实体但不添加组件
529
+ const entities = scene.createEntities(count, "TestEntity");
530
+ // 分别测试每种组件的添加性能
531
+ const componentTests = [
532
+ {
533
+ name: "PositionComponent",
534
+ create: () => new PositionComponent(Math.random() * 1000, Math.random() * 1000),
535
+ probability: 1.0
536
+ },
537
+ {
538
+ name: "VelocityComponent",
539
+ create: () => new VelocityComponent((Math.random() - 0.5) * 10, (Math.random() - 0.5) * 10),
540
+ probability: 0.7
541
+ },
542
+ {
543
+ name: "HealthComponent",
544
+ create: () => new HealthComponent(Math.floor(Math.random() * 100) + 50),
545
+ probability: 0.5
546
+ },
547
+ {
548
+ name: "RenderComponent",
549
+ create: () => new RenderComponent(`sprite_${Math.floor(Math.random() * 10)}`),
550
+ probability: 0.3
551
+ },
552
+ {
553
+ name: "AIComponent",
554
+ create: () => new AIComponent(['idle', 'patrol', 'chase'][Math.floor(Math.random() * 3)]),
555
+ probability: 0.2
556
+ }
557
+ ];
558
+ for (const test of componentTests) {
559
+ const startTime = performance.now();
560
+ let addedCount = 0;
561
+ for (const entity of entities) {
562
+ if (Math.random() < test.probability) {
563
+ entity.addComponent(test.create());
564
+ addedCount++;
565
+ }
566
+ }
567
+ const endTime = performance.now();
568
+ const totalTime = endTime - startTime;
569
+ console.log(` ${test.name}:`);
570
+ console.log(` 添加数量: ${addedCount.toLocaleString()}`);
571
+ console.log(` 总时间: ${totalTime.toFixed(2)}ms`);
572
+ console.log(` 平均时间: ${(totalTime / addedCount).toFixed(4)}ms/组件`);
573
+ console.log(` 添加速度: ${(addedCount / (totalTime / 1000)).toFixed(0)} 组件/秒`);
574
+ }
575
+ }
576
+ /**
577
+ * 主测试函数
578
+ */
579
+ async function runBenchmarks() {
580
+ console.log('🎯 ECS框架性能基准测试');
581
+ console.log('='.repeat(60));
582
+ // 先运行实体创建性能测试
583
+ await runEntityCreationBenchmark();
584
+ // 然后运行完整的框架测试
585
+ console.log('\n🚀 完整框架性能测试');
586
+ console.log('='.repeat(60));
587
+ console.log(`\n⚙️ 测试配置:`);
588
+ console.log(` 实体数量: ${TEST_CONFIG.entityCounts.map(n => n.toLocaleString()).join(', ')}`);
589
+ console.log(` 查询迭代: ${TEST_CONFIG.queryIterations.toLocaleString()}`);
590
+ console.log(` 更新迭代: ${TEST_CONFIG.updateIterations.toLocaleString()}`);
591
+ console.log(` 预计测试时间: ${(TEST_CONFIG.entityCounts.length * 2).toFixed(0)}-${(TEST_CONFIG.entityCounts.length * 5).toFixed(0)} 分钟`);
592
+ console.log('\n🔧 初始化ECS框架...');
593
+ // 初始化WebAssembly模块
594
+ try {
595
+ const { ecsCore } = await Promise.resolve().then(() => __importStar(require('../../Utils/WasmCore')));
596
+ await ecsCore.initialize();
597
+ console.log(`✅ WebAssembly模块: ${ecsCore.isUsingWasm() ? '已加载' : '未加载'}`);
598
+ }
599
+ catch (error) {
600
+ console.log('⚠️ WebAssembly模块加载失败,使用JavaScript实现');
601
+ }
602
+ const scene = new Scene_1.Scene();
603
+ // 等待初始化完成
604
+ await new Promise(resolve => setTimeout(resolve, 1000));
605
+ displaySystemInfo(scene);
606
+ const results = [];
607
+ const totalTests = TEST_CONFIG.entityCounts.length;
608
+ // 运行不同规模的测试
609
+ for (let i = 0; i < TEST_CONFIG.entityCounts.length; i++) {
610
+ const entityCount = TEST_CONFIG.entityCounts[i];
611
+ console.log(`\n🔄 进度: ${i + 1}/${totalTests} (${((i + 1) / totalTests * 100).toFixed(1)}%)`);
612
+ const result = runPerformanceTest(scene, entityCount, TEST_CONFIG);
613
+ results.push(result);
614
+ // 清理场景,准备下一轮测试
615
+ console.log(` 🧹 清理内存...`);
616
+ scene.end();
617
+ scene.begin();
618
+ // 强制垃圾回收
619
+ if (typeof global !== 'undefined' && global.gc) {
620
+ global.gc();
621
+ }
622
+ // 大规模测试间隔稍作休息
623
+ if (entityCount >= 100000) {
624
+ console.log(` ⏱️ 等待系统稳定...`);
625
+ await new Promise(resolve => setTimeout(resolve, 2000));
626
+ }
627
+ }
628
+ displayResults(results, scene);
629
+ scene.end();
630
+ console.log('\n✅ 性能测试完成!');
631
+ console.log(`📊 总测试时间: ${((Date.now() - startTime) / 1000 / 60).toFixed(1)} 分钟`);
632
+ }
633
+ // 记录开始时间
634
+ const startTime = Date.now();
635
+ // 运行测试
636
+ runBenchmarks().catch(error => {
637
+ console.error('❌ 测试失败:', error);
638
+ });
639
+ //# sourceMappingURL=benchmark.js.map