Compare commits

..

22 Commits

Author SHA1 Message Date
YHH
a572c80967 v2.2.4 2025-10-14 21:22:07 +08:00
YHH
a09e8261db Merge pull request #118 from esengine/issue-117-统一组件注册系统,移除ComponentTypeManager重复实现
移除了功能重复的ComponentTypeManager
2025-10-14 18:24:17 +08:00
YHH
62e8ebe926 移除了功能重复的ComponentTypeManager 2025-10-14 18:19:08 +08:00
YHH
96e0a9126f Merge pull request #116 from esengine/issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query
使用ComponentRegistry来确保与Entity.componentMask使用相同的bitIndex
2025-10-14 17:56:26 +08:00
YHH
4afb195814 Merge remote-tracking branch 'origin/master' into issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query 2025-10-14 17:51:59 +08:00
YHH
7da5366bca 修复querysystem循环依赖的问题 2025-10-14 17:50:32 +08:00
YHH
d979c38615 使用ComponentRegistry来确保与Entity.componentMask使用相同的bitIndex 2025-10-14 17:34:15 +08:00
YHH
7def06126b Merge pull request #115 from esengine/issue-114-reactive-query_文档
新增实体查询系统文档
2025-10-14 13:39:23 +08:00
YHH
9f600f88b0 新增实体查询系统文档 2025-10-14 13:33:12 +08:00
YHH
e3c4d5f0c0 Merge pull request #105 from esengine/issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query
响应式查询
2025-10-14 12:29:54 +08:00
YHH
b97f3a8431 移除了 EntitySystem.update() 中的冗余 invalidate() 调用 2025-10-14 12:08:08 +08:00
YHH
3b917a06af 修复响应式查询缓存失效和测试隔离问题 2025-10-14 11:48:04 +08:00
YHH
360106fb92 优化ReactiveQuery: 添加公共API、修复内存泄漏、提升通知性能 2025-10-13 23:55:43 +08:00
YHH
507ed5005f Merge remote-tracking branch 'origin/master' into issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query 2025-10-13 23:36:12 +08:00
YHH
8bea5d5e68 Merge remote-tracking branch 'origin/master' into issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query 2025-10-13 23:29:56 +08:00
YHH
99076adb72 Merge pull request #113 from esengine/issue-112-优化_DebugManager_使用_DI_避免依赖问题
使用DI避免依赖问题
2025-10-13 23:21:10 +08:00
YHH
d1a6230b23 新增调试配置服务用于DI 2025-10-13 23:17:10 +08:00
YHH
cfe3916934 使用DI避免依赖问题 2025-10-13 22:56:49 +08:00
YHH
d798995876 Merge pull request #111 from esengine/issue-110-_Inject_装饰器在_Cocos_Creator_环境中不执行
扩展 InjectableMetadata 接口支持属性注入,实现 @InjectProperty 装饰器
2025-10-12 23:44:22 +08:00
YHH
43e6b7bf88 扩展 InjectableMetadata 接口支持属性注入,实现 @InjectProperty 装饰器 2025-10-12 23:39:32 +08:00
YHH
942043f0b0 报告响应式查询的数量而不是传统缓存 2025-10-11 18:44:55 +08:00
YHH
23d81bca35 响应式查询 2025-10-11 18:31:20 +08:00
30 changed files with 2910 additions and 327 deletions

View File

@@ -66,6 +66,7 @@ export default defineConfig({
items: [
{ text: '实体类 (Entity)', link: '/guide/entity' },
{ text: '组件系统 (Component)', link: '/guide/component' },
{ text: '实体查询系统', link: '/guide/entity-query' },
{
text: '系统架构 (System)',
link: '/guide/system',

501
docs/guide/entity-query.md Normal file
View File

@@ -0,0 +1,501 @@
# 实体查询系统
实体查询是 ECS 架构的核心功能之一。本指南将介绍如何使用 Matcher 和 QuerySystem 来查询和筛选实体。
## 核心概念
### Matcher - 查询条件描述符
Matcher 是一个链式 API,用于描述实体查询条件。它本身不执行查询,而是作为条件传递给 EntitySystem 或 QuerySystem。
### QuerySystem - 查询执行引擎
QuerySystem 负责实际执行查询,内部使用响应式查询机制自动优化性能。
## 在 EntitySystem 中使用 Matcher
这是最常见的使用方式。EntitySystem 通过 Matcher 自动筛选和处理符合条件的实体。
### 基础用法
```typescript
import { EntitySystem, Matcher, Entity, Component } from '@esengine/ecs-framework';
class PositionComponent extends Component {
public x: number = 0;
public y: number = 0;
}
class VelocityComponent extends Component {
public vx: number = 0;
public vy: number = 0;
}
class MovementSystem extends EntitySystem {
constructor() {
// 方式1: 使用 Matcher.empty().all()
super(Matcher.empty().all(PositionComponent, VelocityComponent));
// 方式2: 直接使用 Matcher.all() (等价)
// super(Matcher.all(PositionComponent, VelocityComponent));
}
protected process(entities: readonly Entity[]): void {
for (const entity of entities) {
const pos = entity.getComponent(PositionComponent)!;
const vel = entity.getComponent(VelocityComponent)!;
pos.x += vel.vx;
pos.y += vel.vy;
}
}
}
// 添加到场景
scene.addEntityProcessor(new MovementSystem());
```
### Matcher 链式 API
#### all() - 必须包含所有组件
```typescript
class HealthSystem extends EntitySystem {
constructor() {
// 实体必须同时拥有 Health 和 Position 组件
super(Matcher.empty().all(HealthComponent, PositionComponent));
}
protected process(entities: readonly Entity[]): void {
// 只处理同时拥有两个组件的实体
}
}
```
#### any() - 至少包含一个组件
```typescript
class DamageableSystem extends EntitySystem {
constructor() {
// 实体至少拥有 Health 或 Shield 其中之一
super(Matcher.any(HealthComponent, ShieldComponent));
}
protected process(entities: readonly Entity[]): void {
// 处理拥有生命值或护盾的实体
}
}
```
#### none() - 不能包含指定组件
```typescript
class AliveEntitySystem extends EntitySystem {
constructor() {
// 实体不能拥有 DeadTag 组件
super(Matcher.all(HealthComponent).none(DeadTag));
}
protected process(entities: readonly Entity[]): void {
// 只处理活着的实体
}
}
```
#### 组合条件
```typescript
class CombatSystem extends EntitySystem {
constructor() {
super(
Matcher.empty()
.all(PositionComponent, HealthComponent) // 必须有位置和生命
.any(WeaponComponent, MagicComponent) // 至少有武器或魔法
.none(DeadTag, FrozenTag) // 不能是死亡或冰冻状态
);
}
protected process(entities: readonly Entity[]): void {
// 处理可以战斗的活着的实体
}
}
```
### 按标签查询
```typescript
class PlayerSystem extends EntitySystem {
constructor() {
// 查询特定标签的实体
super(Matcher.empty().withTag(Tags.PLAYER));
}
protected process(entities: readonly Entity[]): void {
// 只处理玩家实体
}
}
```
### 按名称查询
```typescript
class BossSystem extends EntitySystem {
constructor() {
// 查询特定名称的实体
super(Matcher.empty().withName('Boss'));
}
protected process(entities: readonly Entity[]): void {
// 只处理名为 'Boss' 的实体
}
}
```
## 直接使用 QuerySystem
如果不需要创建系统,可以直接使用 Scene 的 querySystem 进行查询。
### 基础查询方法
```typescript
// 获取场景的查询系统
const querySystem = scene.querySystem;
// 查询拥有所有指定组件的实体
const result1 = querySystem.queryAll(PositionComponent, VelocityComponent);
console.log(`找到 ${result1.count} 个移动实体`);
console.log(`查询耗时: ${result1.executionTime.toFixed(2)}ms`);
// 查询拥有任意指定组件的实体
const result2 = querySystem.queryAny(WeaponComponent, MagicComponent);
console.log(`找到 ${result2.count} 个战斗单位`);
// 查询不包含指定组件的实体
const result3 = querySystem.queryNone(DeadTag);
console.log(`找到 ${result3.count} 个活着的实体`);
```
### 按标签查询
```typescript
const playerResult = querySystem.queryByTag(Tags.PLAYER);
for (const player of playerResult.entities) {
console.log('玩家:', player.name);
}
```
### 按名称查询
```typescript
const bossResult = querySystem.queryByName('Boss');
if (bossResult.count > 0) {
const boss = bossResult.entities[0];
console.log('找到Boss:', boss);
}
```
### 按单个组件查询
```typescript
const healthResult = querySystem.queryByComponent(HealthComponent);
console.log(`${healthResult.count} 个实体拥有生命值`);
```
## 性能优化
### 自动缓存
QuerySystem 内部使用响应式查询自动缓存结果,相同的查询条件会直接使用缓存:
```typescript
// 第一次查询,执行实际查询
const result1 = querySystem.queryAll(PositionComponent);
console.log('fromCache:', result1.fromCache); // false
// 第二次相同查询,使用缓存
const result2 = querySystem.queryAll(PositionComponent);
console.log('fromCache:', result2.fromCache); // true
```
### 实体变化自动更新
当实体添加/移除组件时,查询缓存会自动更新:
```typescript
// 查询拥有武器的实体
const before = querySystem.queryAll(WeaponComponent);
console.log('之前:', before.count); // 假设为 5
// 给实体添加武器
const enemy = scene.createEntity('Enemy');
enemy.addComponent(new WeaponComponent());
// 再次查询,自动包含新实体
const after = querySystem.queryAll(WeaponComponent);
console.log('之后:', after.count); // 现在是 6
```
### 查询性能统计
```typescript
const stats = querySystem.getStats();
console.log('总查询次数:', stats.queryStats.totalQueries);
console.log('缓存命中率:', stats.queryStats.cacheHitRate);
console.log('缓存大小:', stats.cacheStats.size);
```
## 实际应用场景
### 场景1: 物理系统
```typescript
class PhysicsSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(TransformComponent, RigidbodyComponent));
}
protected process(entities: readonly Entity[]): void {
for (const entity of entities) {
const transform = entity.getComponent(TransformComponent)!;
const rigidbody = entity.getComponent(RigidbodyComponent)!;
// 应用重力
rigidbody.velocity.y -= 9.8 * Time.deltaTime;
// 更新位置
transform.position.x += rigidbody.velocity.x * Time.deltaTime;
transform.position.y += rigidbody.velocity.y * Time.deltaTime;
}
}
}
```
### 场景2: 渲染系统
```typescript
class RenderSystem extends EntitySystem {
constructor() {
super(
Matcher.empty()
.all(TransformComponent, SpriteComponent)
.none(InvisibleTag) // 排除不可见实体
);
}
protected process(entities: readonly Entity[]): void {
// 按 z-order 排序
const sorted = entities.slice().sort((a, b) => {
const zA = a.getComponent(TransformComponent)!.z;
const zB = b.getComponent(TransformComponent)!.z;
return zA - zB;
});
// 渲染实体
for (const entity of sorted) {
const transform = entity.getComponent(TransformComponent)!;
const sprite = entity.getComponent(SpriteComponent)!;
renderer.drawSprite(sprite.texture, transform.position);
}
}
}
```
### 场景3: 碰撞检测
```typescript
class CollisionSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(TransformComponent, ColliderComponent));
}
protected process(entities: readonly Entity[]): void {
// 简单的 O(n²) 碰撞检测
for (let i = 0; i < entities.length; i++) {
for (let j = i + 1; j < entities.length; j++) {
this.checkCollision(entities[i], entities[j]);
}
}
}
private checkCollision(a: Entity, b: Entity): void {
const transA = a.getComponent(TransformComponent)!;
const transB = b.getComponent(TransformComponent)!;
const colliderA = a.getComponent(ColliderComponent)!;
const colliderB = b.getComponent(ColliderComponent)!;
if (this.isOverlapping(transA, colliderA, transB, colliderB)) {
// 触发碰撞事件
scene.eventSystem.emit('collision', { entityA: a, entityB: b });
}
}
private isOverlapping(...args: any[]): boolean {
// 碰撞检测逻辑
return false;
}
}
```
### 场景4: 一次性查询
```typescript
// 在系统外部执行一次性查询
class GameManager {
private scene: Scene;
public countEnemies(): number {
const result = this.scene.querySystem.queryByTag(Tags.ENEMY);
return result.count;
}
public findNearestEnemy(playerPos: Vector2): Entity | null {
const enemies = this.scene.querySystem.queryByTag(Tags.ENEMY);
let nearest: Entity | null = null;
let minDistance = Infinity;
for (const enemy of enemies.entities) {
const transform = enemy.getComponent(TransformComponent);
if (!transform) continue;
const distance = Vector2.distance(playerPos, transform.position);
if (distance < minDistance) {
minDistance = distance;
nearest = enemy;
}
}
return nearest;
}
}
```
## 最佳实践
### 1. 优先使用 EntitySystem
```typescript
// 推荐: 使用 EntitySystem
class GoodSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(HealthComponent));
}
protected process(entities: readonly Entity[]): void {
// 自动获得符合条件的实体,每帧自动更新
}
}
// 不推荐: 在 update 中手动查询
class BadSystem extends EntitySystem {
constructor() {
super(Matcher.empty());
}
protected process(entities: readonly Entity[]): void {
// 每帧手动查询,浪费性能
const result = this.scene!.querySystem.queryAll(HealthComponent);
for (const entity of result.entities) {
// ...
}
}
}
```
### 2. 合理使用 none() 排除条件
```typescript
// 排除已死亡的敌人
class EnemyAISystem extends EntitySystem {
constructor() {
super(
Matcher.empty()
.all(EnemyTag, AIComponent)
.none(DeadTag) // 不处理死亡的敌人
);
}
}
```
### 3. 使用标签优化查询
```typescript
// 不好: 查询所有实体再过滤
const allEntities = scene.querySystem.getAllEntities();
const players = allEntities.filter(e => e.hasComponent(PlayerTag));
// 好: 直接按标签查询
const players = scene.querySystem.queryByTag(Tags.PLAYER).entities;
```
### 4. 避免过于复杂的查询条件
```typescript
// 不推荐: 过于复杂
super(
Matcher.empty()
.all(A, B, C, D)
.any(E, F, G)
.none(H, I, J)
);
// 推荐: 拆分成多个简单系统
class SystemAB extends EntitySystem {
constructor() {
super(Matcher.empty().all(A, B));
}
}
class SystemCD extends EntitySystem {
constructor() {
super(Matcher.empty().all(C, D));
}
}
```
## 注意事项
### 1. 查询结果是只读的
```typescript
const result = querySystem.queryAll(PositionComponent);
// 不要修改返回的数组
result.entities.push(someEntity); // 错误!
// 如果需要修改,先复制
const mutableArray = [...result.entities];
mutableArray.push(someEntity); // 正确
```
### 2. 组件添加/移除后的查询时机
```typescript
// 创建实体并添加组件
const entity = scene.createEntity('Player');
entity.addComponent(new PositionComponent());
// 立即查询可能获取到新实体
const result = scene.querySystem.queryAll(PositionComponent);
// result.entities 包含新创建的实体
```
### 3. Matcher 是不可变的
```typescript
const matcher = Matcher.empty().all(PositionComponent);
// 链式调用返回新的 Matcher 实例
const matcher2 = matcher.any(VelocityComponent);
// matcher 本身不变
console.log(matcher === matcher2); // false
```
## 相关 API
- [Matcher](../api/classes/Matcher.md) - 查询条件描述符 API 参考
- [QuerySystem](../api/classes/QuerySystem.md) - 查询系统 API 参考
- [EntitySystem](../api/classes/EntitySystem.md) - 实体系统 API 参考
- [Entity](../api/classes/Entity.md) - 实体 API 参考

2
package-lock.json generated
View File

@@ -15530,7 +15530,7 @@
},
"packages/core": {
"name": "@esengine/ecs-framework",
"version": "2.2.3",
"version": "2.2.4",
"license": "MIT",
"dependencies": {
"@msgpack/msgpack": "^3.0.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/ecs-framework",
"version": "2.2.3",
"version": "2.2.4",
"description": "用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架",
"main": "bin/index.js",
"types": "bin/index.d.ts",

View File

@@ -13,6 +13,8 @@ import { ServiceContainer } from './Core/ServiceContainer';
import { PluginManager } from './Core/PluginManager';
import { IPlugin } from './Core/Plugin';
import { WorldManager } from './ECS/WorldManager';
import { DebugConfigService } from './Utils/Debug/DebugConfigService';
import { createInstance } from './Core/DI/Decorators';
/**
* 游戏引擎核心类
@@ -202,14 +204,15 @@ export class Core {
// 初始化调试管理器
if (this._config.debugConfig?.enabled) {
// 使用DI容器创建DebugManager前两个参数从容器解析config手动传入
const config = this._config.debugConfig;
this._debugManager = new DebugManager(
this._serviceContainer.resolve(SceneManager),
this._serviceContainer.resolve(PerformanceMonitor),
config
const configService = new DebugConfigService();
configService.setConfig(this._config.debugConfig);
this._serviceContainer.registerInstance(DebugConfigService, configService);
this._serviceContainer.registerSingleton(DebugManager, (c) =>
createInstance(DebugManager, c)
);
this._serviceContainer.registerInstance(DebugManager, this._debugManager);
this._debugManager = this._serviceContainer.resolve(DebugManager);
}
this.initialize();
@@ -476,13 +479,15 @@ export class Core {
if (this._instance._debugManager) {
this._instance._debugManager.updateConfig(config);
} else {
// 使用DI容器创建DebugManager
this._instance._debugManager = new DebugManager(
this._instance._serviceContainer.resolve(SceneManager),
this._instance._serviceContainer.resolve(PerformanceMonitor),
config
const configService = new DebugConfigService();
configService.setConfig(config);
this._instance._serviceContainer.registerInstance(DebugConfigService, configService);
this._instance._serviceContainer.registerSingleton(DebugManager, (c) =>
createInstance(DebugManager, c)
);
this._instance._serviceContainer.registerInstance(DebugManager, this._instance._debugManager);
this._instance._debugManager = this._instance._serviceContainer.resolve(DebugManager);
}
// 更新Core配置
@@ -659,11 +664,6 @@ export class Core {
// 更新额外的 WorldManager
this._worldManager.updateAll();
// 更新调试管理器基于FPS的数据发送
if (this._debugManager) {
this._debugManager.onFrameUpdate(deltaTime);
}
// 结束性能监控
this._performanceMonitor.endMonitoring('Core.update', frameStartTime);
}

View File

@@ -35,6 +35,12 @@ export interface InjectableMetadata {
* 依赖列表
*/
dependencies: Array<ServiceType<any> | string | symbol>;
/**
* 属性注入映射
* key: 属性名, value: 服务类型
*/
properties?: Map<string | symbol, ServiceType<any>>;
}
/**
@@ -77,10 +83,12 @@ export interface UpdatableMetadata {
*/
export function Injectable(): ClassDecorator {
return function <T extends Function>(target: T): T {
// 标记为可注入
const existing = injectableMetadata.get(target);
injectableMetadata.set(target, {
injectable: true,
dependencies: []
dependencies: [],
properties: existing?.properties
});
return target;
@@ -142,20 +150,7 @@ export function Updatable(priority: number = 0): ClassDecorator {
*
* 标记构造函数参数需要注入的服务类型
*
* @param serviceType 服务类型标识符类、字符串或Symbol
*
* @example
* ```typescript
* @Injectable()
* class MySystem extends EntitySystem {
* constructor(
* @Inject(TimeService) private timeService: TimeService,
* @Inject(PhysicsService) private physics: PhysicsService
* ) {
* super();
* }
* }
* ```
* @param serviceType 服务类型标识符
*/
export function Inject(serviceType: ServiceType<any> | string | symbol): ParameterDecorator {
return function (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) {
@@ -171,6 +166,35 @@ export function Inject(serviceType: ServiceType<any> | string | symbol): Paramet
};
}
/**
* @InjectProperty() 装饰器
*
* 通过属性装饰器注入依赖
*
* 注入时机在构造函数执行后、onInitialize() 调用前完成
*
* @param serviceType 服务类型
*/
export function InjectProperty(serviceType: ServiceType<any>): PropertyDecorator {
return function (target: any, propertyKey: string | symbol) {
let metadata = injectableMetadata.get(target.constructor);
if (!metadata) {
metadata = {
injectable: true,
dependencies: []
};
injectableMetadata.set(target.constructor, metadata);
}
if (!metadata.properties) {
metadata.properties = new Map();
}
metadata.properties.set(propertyKey, serviceType);
};
}
/**
* 检查类是否标记为可注入
*
@@ -252,6 +276,29 @@ export function createInstance<T>(
return new constructor(...dependencies);
}
/**
* 为实例注入属性依赖
*
* @param instance 目标实例
* @param container 服务容器
*/
export function injectProperties<T>(instance: T, container: ServiceContainer): void {
const constructor = (instance as any).constructor;
const metadata = getInjectableMetadata(constructor);
if (!metadata?.properties || metadata.properties.size === 0) {
return;
}
for (const [propertyKey, serviceType] of metadata.properties) {
const service = container.resolve(serviceType);
if (service !== null) {
(instance as any)[propertyKey] = service;
}
}
}
/**
* 检查类是否标记为可更新
*

View File

@@ -7,6 +7,7 @@
export {
Injectable,
Inject,
InjectProperty,
Updatable,
isInjectable,
getInjectableMetadata,
@@ -14,6 +15,7 @@ export {
isUpdatable,
getUpdatableMetadata,
createInstance,
injectProperties,
registerInjectable
} from './Decorators';

View File

@@ -1,6 +1,6 @@
import { Entity } from '../Entity';
import { ComponentType } from './ComponentStorage';
import { BitMask64Data, BitMask64Utils, ComponentTypeManager } from "../Utils";
import { ComponentType, ComponentRegistry } from './ComponentStorage';
import { BitMask64Data, BitMask64Utils } from "../Utils";
import { BitMaskHashMap } from "../Utils/BitMaskHashMap";
/**
@@ -266,10 +266,18 @@ export class ArchetypeSystem {
/**
* 生成原型ID
* 使用ComponentRegistry确保与Entity.componentMask使用相同的bitIndex
*/
private generateArchetypeId(componentTypes: ComponentType[]): ArchetypeId {
let entityBits = ComponentTypeManager.instance.getEntityBits(componentTypes);
return entityBits.getValue();
let mask = BitMask64Utils.clone(BitMask64Utils.ZERO);
for (const type of componentTypes) {
if (!ComponentRegistry.isRegistered(type)) {
ComponentRegistry.register(type);
}
const bitMask = ComponentRegistry.getBitMask(type);
BitMask64Utils.orInPlace(mask, bitMask);
}
return mask;
}
/**

View File

@@ -5,40 +5,10 @@ import { BitMask64Utils, BitMask64Data } from '../Utils/BigIntCompatibility';
import { createLogger } from '../../Utils/Logger';
import { getComponentTypeName } from '../Decorators';
import { Archetype, ArchetypeSystem } from './ArchetypeSystem';
import { ComponentTypeManager } from "../Utils";
import { ReactiveQuery, ReactiveQueryConfig } from './ReactiveQuery';
import { QueryCondition, QueryConditionType, QueryResult } from './QueryTypes';
/**
* 查询条件类型
*/
export enum QueryConditionType {
/** 必须包含所有指定组件 */
ALL = 'all',
/** 必须包含任意一个指定组件 */
ANY = 'any',
/** 不能包含任何指定组件 */
NONE = 'none'
}
/**
* 查询条件接口
*/
export interface QueryCondition {
type: QueryConditionType;
componentTypes: ComponentType[];
mask: BitMask64Data;
}
/**
* 实体查询结果接口
*/
export interface QueryResult {
entities: readonly Entity[];
count: number;
/** 查询执行时间(毫秒) */
executionTime: number;
/** 是否来自缓存 */
fromCache: boolean;
}
export { QueryCondition, QueryConditionType, QueryResult };
/**
* 实体索引结构
@@ -124,15 +94,16 @@ export class QuerySystem {
/**
* 设置实体列表并重建索引
*
*
* 当实体集合发生大规模变化时调用此方法。
* 系统将重新构建所有索引以确保查询性能。
*
*
* @param entities 新的实体列表
*/
public setEntities(entities: Entity[]): void {
this.entities = entities;
this.clearQueryCache();
this.clearReactiveQueries();
this.rebuildIndexes();
}
@@ -152,12 +123,14 @@ export class QuerySystem {
this.archetypeSystem.addEntity(entity);
// 通知响应式查询
this.notifyReactiveQueriesEntityAdded(entity);
// 只有在非延迟模式下才立即清理缓存
if (!deferCacheClear) {
this.clearQueryCache();
}
// 更新版本号
this._version++;
}
@@ -235,14 +208,24 @@ export class QuerySystem {
public removeEntity(entity: Entity): void {
const index = this.entities.indexOf(entity);
if (index !== -1) {
const componentTypes: ComponentType[] = [];
for (const component of entity.components) {
componentTypes.push(component.constructor as ComponentType);
}
this.entities.splice(index, 1);
this.removeEntityFromIndexes(entity);
this.archetypeSystem.removeEntity(entity);
if (componentTypes.length > 0) {
this.notifyReactiveQueriesEntityRemoved(entity, componentTypes);
} else {
this.notifyReactiveQueriesEntityRemovedFallback(entity);
}
this.clearQueryCache();
// 更新版本号
this._version++;
}
}
@@ -270,6 +253,9 @@ export class QuerySystem {
// 重新添加实体到索引(基于新的组件状态)
this.addEntityToIndexes(entity);
// 通知响应式查询
this.notifyReactiveQueriesEntityChanged(entity);
// 清理查询缓存,因为实体组件状态已改变
this.clearQueryCache();
@@ -357,13 +343,13 @@ export class QuerySystem {
/**
* 查询包含所有指定组件的实体
*
*
* 返回同时包含所有指定组件类型的实体列表。
* 系统会自动选择最高效的查询策略,包括索引查找和缓存机制
*
* 内部使用响应式查询作为智能缓存,自动跟踪实体变化,性能更优
*
* @param componentTypes 要查询的组件类型列表
* @returns 查询结果,包含匹配的实体和性能信息
*
*
* @example
* ```typescript
* // 查询同时具有位置和速度组件的实体
@@ -375,38 +361,20 @@ export class QuerySystem {
const startTime = performance.now();
this.queryStats.totalQueries++;
// 生成缓存
const cacheKey = this.generateCacheKey('all', componentTypes);
// 使用内部响应式查询作为智能缓存
const reactiveQuery = this.getOrCreateReactiveQuery(QueryConditionType.ALL, componentTypes);
// 检查缓存
const cached = this.getFromCache(cacheKey);
if (cached) {
this.queryStats.cacheHits++;
return {
entities: cached,
count: cached.length,
executionTime: performance.now() - startTime,
fromCache: true
};
}
// 从响应式查询获取结果(永远是最新的)
const entities = reactiveQuery.getEntities();
this.queryStats.archetypeHits++;
const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'AND');
const entities: Entity[] = [];
for (const archetype of archetypeResult.archetypes) {
for (const entity of archetype.entities) {
entities.push(entity);
}
}
this.addToCache(cacheKey, entities);
// 统计为缓存命中(响应式查询本质上是永不过期的智能缓存)
this.queryStats.cacheHits++;
return {
entities,
count: entities.length,
executionTime: performance.now() - startTime,
fromCache: false
fromCache: true
};
}
@@ -436,13 +404,13 @@ export class QuerySystem {
/**
* 查询包含任意指定组件的实体
*
*
* 返回包含任意一个指定组件类型的实体列表。
* 使用集合合并算法确保高效的查询性能
*
* 内部使用响应式查询作为智能缓存,自动跟踪实体变化,性能更优
*
* @param componentTypes 要查询的组件类型列表
* @returns 查询结果,包含匹配的实体和性能信息
*
*
* @example
* ```typescript
* // 查询具有武器或护甲组件的实体
@@ -454,52 +422,32 @@ export class QuerySystem {
const startTime = performance.now();
this.queryStats.totalQueries++;
const cacheKey = this.generateCacheKey('any', componentTypes);
// 使用内部响应式查询作为智能缓存
const reactiveQuery = this.getOrCreateReactiveQuery(QueryConditionType.ANY, componentTypes);
// 检查缓存
const cached = this.getFromCache(cacheKey);
if (cached) {
this.queryStats.cacheHits++;
return {
entities: cached,
count: cached.length,
executionTime: performance.now() - startTime,
fromCache: true
};
}
// 从响应式查询获取结果(永远是最新的)
const entities = reactiveQuery.getEntities();
this.queryStats.archetypeHits++;
const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'OR');
const entities = this.acquireResultArray();
for (const archetype of archetypeResult.archetypes) {
for (const entity of archetype.entities) {
entities.push(entity);
}
}
const frozenEntities = [...entities];
this.releaseResultArray(entities);
this.addToCache(cacheKey, frozenEntities);
// 统计为缓存命中(响应式查询本质上是永不过期的智能缓存)
this.queryStats.cacheHits++;
return {
entities: frozenEntities,
count: frozenEntities.length,
entities,
count: entities.length,
executionTime: performance.now() - startTime,
fromCache: false
fromCache: true
};
}
/**
* 查询不包含任何指定组件的实体
*
*
* 返回不包含任何指定组件类型的实体列表。
* 适用于排除特定类型实体的查询场景
*
* 内部使用响应式查询作为智能缓存,自动跟踪实体变化,性能更优
*
* @param componentTypes 要排除的组件类型列表
* @returns 查询结果,包含匹配的实体和性能信息
*
*
* @example
* ```typescript
* // 查询不具有AI和玩家控制组件的实体如静态物体
@@ -511,32 +459,20 @@ export class QuerySystem {
const startTime = performance.now();
this.queryStats.totalQueries++;
const cacheKey = this.generateCacheKey('none', componentTypes);
// 使用内部响应式查询作为智能缓存
const reactiveQuery = this.getOrCreateReactiveQuery(QueryConditionType.NONE, componentTypes);
// 检查缓存
const cached = this.getFromCache(cacheKey);
if (cached) {
this.queryStats.cacheHits++;
return {
entities: cached,
count: cached.length,
executionTime: performance.now() - startTime,
fromCache: true
};
}
// 从响应式查询获取结果(永远是最新的)
const entities = reactiveQuery.getEntities();
const mask = this.createComponentMask(componentTypes);
const entities = this.entities.filter(entity =>
BitMask64Utils.hasNone(entity.componentMask, mask)
);
this.addToCache(cacheKey, entities);
// 统计为缓存命中(响应式查询本质上是永不过期的智能缓存)
this.queryStats.cacheHits++;
return {
entities,
count: entities.length,
executionTime: performance.now() - startTime,
fromCache: false
fromCache: true
};
}
@@ -759,6 +695,20 @@ export class QuerySystem {
this.componentMaskCache.clear();
}
/**
* 清除所有响应式查询
*
* 销毁所有响应式查询实例并清理索引
* 通常在setEntities时调用以确保缓存一致性
*/
private clearReactiveQueries(): void {
for (const query of this._reactiveQueries.values()) {
query.dispose();
}
this._reactiveQueries.clear();
this._reactiveQueriesByComponent.clear();
}
/**
* 高效的缓存键生成
*/
@@ -782,11 +732,111 @@ export class QuerySystem {
/**
* 清理查询缓存
*
*
* 用于外部调用清理缓存,通常在批量操作后使用。
* 注意:此方法也会清理响应式查询缓存
*/
public clearCache(): void {
this.clearQueryCache();
this.clearReactiveQueries();
}
/**
* 创建响应式查询
*
* 响应式查询会自动跟踪实体/组件的变化,并通过事件通知订阅者。
* 适合需要实时响应实体变化的场景(如UI更新、AI系统等)。
*
* @param componentTypes 查询的组件类型列表
* @param config 可选的查询配置
* @returns 响应式查询实例
*
* @example
* ```typescript
* const query = querySystem.createReactiveQuery([Position, Velocity], {
* enableBatchMode: true,
* batchDelay: 16
* });
*
* query.subscribe((change) => {
* if (change.type === ReactiveQueryChangeType.ADDED) {
* console.log('新实体:', change.entity);
* }
* });
* ```
*/
public createReactiveQuery(
componentTypes: ComponentType[],
config?: ReactiveQueryConfig
): ReactiveQuery {
if (!componentTypes || componentTypes.length === 0) {
throw new Error('组件类型列表不能为空');
}
const mask = this.createComponentMask(componentTypes);
const condition: QueryCondition = {
type: QueryConditionType.ALL,
componentTypes,
mask
};
const query = new ReactiveQuery(condition, config);
const initialEntities = this.executeTraditionalQuery(
QueryConditionType.ALL,
componentTypes
);
query.initializeWith(initialEntities);
const cacheKey = this.generateCacheKey('all', componentTypes);
this._reactiveQueries.set(cacheKey, query);
for (const type of componentTypes) {
let queries = this._reactiveQueriesByComponent.get(type);
if (!queries) {
queries = new Set();
this._reactiveQueriesByComponent.set(type, queries);
}
queries.add(query);
}
return query;
}
/**
* 销毁响应式查询
*
* 清理查询占用的资源,包括监听器和实体引用。
* 销毁后的查询不应再被使用。
*
* @param query 要销毁的响应式查询
*
* @example
* ```typescript
* const query = querySystem.createReactiveQuery([Position, Velocity]);
* // ... 使用查询
* querySystem.destroyReactiveQuery(query);
* ```
*/
public destroyReactiveQuery(query: ReactiveQuery): void {
if (!query) {
return;
}
const cacheKey = query.id;
this._reactiveQueries.delete(cacheKey);
for (const type of query.condition.componentTypes) {
const queries = this._reactiveQueriesByComponent.get(type);
if (queries) {
queries.delete(query);
if (queries.size === 0) {
this._reactiveQueriesByComponent.delete(type);
}
}
}
query.dispose();
}
/**
@@ -794,6 +844,7 @@ export class QuerySystem {
*
* 根据组件类型列表生成对应的位掩码。
* 使用缓存避免重复计算。
* 注意:必须使用ComponentRegistry来确保与Entity.componentMask使用相同的bitIndex
*
* @param componentTypes 组件类型列表
* @returns 生成的位掩码
@@ -810,10 +861,20 @@ export class QuerySystem {
return cached;
}
let mask = ComponentTypeManager.instance.getEntityBits(componentTypes);
// 使用ComponentRegistry而不是ComponentTypeManager,确保bitIndex一致
let mask = BitMask64Utils.clone(BitMask64Utils.ZERO);
for (const type of componentTypes) {
// 确保组件已注册
if (!ComponentRegistry.isRegistered(type)) {
ComponentRegistry.register(type);
}
const bitMask = ComponentRegistry.getBitMask(type);
BitMask64Utils.orInPlace(mask, bitMask);
}
// 缓存结果
this.componentMaskCache.set(cacheKey, mask.getValue());
return mask.getValue();
this.componentMaskCache.set(cacheKey, mask);
return mask;
}
/**
@@ -882,7 +943,7 @@ export class QuerySystem {
}))
},
cacheStats: {
size: this.queryCache.size,
size: this._reactiveQueries.size,
hitRate: this.queryStats.totalQueries > 0 ?
(this.queryStats.cacheHits / this.queryStats.totalQueries * 100).toFixed(2) + '%' : '0%'
}
@@ -891,12 +952,230 @@ export class QuerySystem {
/**
* 获取实体所属的原型信息
*
*
* @param entity 要查询的实体
*/
public getEntityArchetype(entity: Entity): Archetype | undefined {
return this.archetypeSystem.getEntityArchetype(entity);
}
// ============================================================
// 响应式查询支持(内部智能缓存)
// ============================================================
/**
* 响应式查询集合(内部使用,作为智能缓存)
* 传统查询API(queryAll/queryAny/queryNone)内部自动使用响应式查询优化性能
*/
private _reactiveQueries: Map<string, ReactiveQuery> = new Map();
/**
* 按组件类型索引的响应式查询
* 用于快速定位哪些查询关心某个组件类型
*/
private _reactiveQueriesByComponent: Map<ComponentType, Set<ReactiveQuery>> = new Map();
/**
* 获取或创建内部响应式查询(作为智能缓存)
*
* @param queryType 查询类型
* @param componentTypes 组件类型列表
* @returns 响应式查询实例
*/
private getOrCreateReactiveQuery(
queryType: QueryConditionType,
componentTypes: ComponentType[]
): ReactiveQuery {
// 生成缓存键(与传统缓存键格式一致)
const cacheKey = this.generateCacheKey(queryType, componentTypes);
// 检查是否已存在响应式查询
let reactiveQuery = this._reactiveQueries.get(cacheKey);
if (!reactiveQuery) {
// 创建查询条件
const mask = this.createComponentMask(componentTypes);
const condition: QueryCondition = {
type: queryType,
componentTypes,
mask
};
// 创建响应式查询(禁用批量模式,保持实时性)
reactiveQuery = new ReactiveQuery(condition, {
enableBatchMode: false,
debug: false
});
// 初始化查询结果(使用传统方式获取初始数据)
const initialEntities = this.executeTraditionalQuery(queryType, componentTypes);
reactiveQuery.initializeWith(initialEntities);
// 注册响应式查询
this._reactiveQueries.set(cacheKey, reactiveQuery);
// 为每个组件类型注册索引
for (const type of componentTypes) {
let queries = this._reactiveQueriesByComponent.get(type);
if (!queries) {
queries = new Set();
this._reactiveQueriesByComponent.set(type, queries);
}
queries.add(reactiveQuery);
}
this._logger.debug(`创建内部响应式查询缓存: ${cacheKey}`);
}
return reactiveQuery;
}
/**
* 执行传统查询(内部使用,用于响应式查询初始化)
*
* @param queryType 查询类型
* @param componentTypes 组件类型列表
* @returns 匹配的实体列表
*/
private executeTraditionalQuery(
queryType: QueryConditionType,
componentTypes: ComponentType[]
): Entity[] {
switch (queryType) {
case QueryConditionType.ALL: {
const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'AND');
const entities: Entity[] = [];
for (const archetype of archetypeResult.archetypes) {
for (const entity of archetype.entities) {
entities.push(entity);
}
}
return entities;
}
case QueryConditionType.ANY: {
const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'OR');
const entities: Entity[] = [];
for (const archetype of archetypeResult.archetypes) {
for (const entity of archetype.entities) {
entities.push(entity);
}
}
return entities;
}
case QueryConditionType.NONE: {
const mask = this.createComponentMask(componentTypes);
return this.entities.filter(entity =>
BitMask64Utils.hasNone(entity.componentMask, mask)
);
}
default:
return [];
}
}
/**
* 通知所有响应式查询实体已添加
*
* 使用组件类型索引,只通知关心该实体组件的查询
*
* @param entity 添加的实体
*/
private notifyReactiveQueriesEntityAdded(entity: Entity): void {
if (this._reactiveQueries.size === 0) return;
const notified = new Set<ReactiveQuery>();
for (const component of entity.components) {
const componentType = component.constructor as ComponentType;
const queries = this._reactiveQueriesByComponent.get(componentType);
if (queries) {
for (const query of queries) {
if (!notified.has(query)) {
query.notifyEntityAdded(entity);
notified.add(query);
}
}
}
}
}
/**
* 通知响应式查询实体已移除
*
* 使用组件类型索引,只通知关心该实体组件的查询
*
* @param entity 移除的实体
* @param componentTypes 实体移除前的组件类型列表
*/
private notifyReactiveQueriesEntityRemoved(entity: Entity, componentTypes: ComponentType[]): void {
if (this._reactiveQueries.size === 0) return;
const notified = new Set<ReactiveQuery>();
for (const componentType of componentTypes) {
const queries = this._reactiveQueriesByComponent.get(componentType);
if (queries) {
for (const query of queries) {
if (!notified.has(query)) {
query.notifyEntityRemoved(entity);
notified.add(query);
}
}
}
}
}
/**
* 通知响应式查询实体已移除(后备方案)
*
* 当实体已经清空组件时使用,通知所有查询
*
* @param entity 移除的实体
*/
private notifyReactiveQueriesEntityRemovedFallback(entity: Entity): void {
if (this._reactiveQueries.size === 0) return;
for (const query of this._reactiveQueries.values()) {
query.notifyEntityRemoved(entity);
}
}
/**
* 通知响应式查询实体已变化
*
* 使用混合策略:
* 1. 首先通知关心实体当前组件的查询
* 2. 然后通知所有其他查询(包括那些可能因为组件移除而不再匹配的查询)
*
* @param entity 变化的实体
*/
private notifyReactiveQueriesEntityChanged(entity: Entity): void {
if (this._reactiveQueries.size === 0) {
return;
}
const notified = new Set<ReactiveQuery>();
for (const component of entity.components) {
const componentType = component.constructor as ComponentType;
const queries = this._reactiveQueriesByComponent.get(componentType);
if (queries) {
for (const query of queries) {
if (!notified.has(query)) {
query.notifyEntityChanged(entity);
notified.add(query);
}
}
}
}
for (const query of this._reactiveQueries.values()) {
if (!notified.has(query)) {
query.notifyEntityChanged(entity);
}
}
}
}
/**

View File

@@ -0,0 +1,36 @@
import { ComponentType } from './ComponentStorage';
import { BitMask64Data } from '../Utils/BigIntCompatibility';
import { Entity } from '../Entity';
/**
* 查询条件类型
*/
export enum QueryConditionType {
/** 必须包含所有指定组件 */
ALL = 'all',
/** 必须包含任意一个指定组件 */
ANY = 'any',
/** 不能包含任何指定组件 */
NONE = 'none'
}
/**
* 查询条件接口
*/
export interface QueryCondition {
type: QueryConditionType;
componentTypes: ComponentType[];
mask: BitMask64Data;
}
/**
* 实体查询结果接口
*/
export interface QueryResult {
entities: readonly Entity[];
count: number;
/** 查询执行时间(毫秒) */
executionTime: number;
/** 是否来自缓存 */
fromCache: boolean;
}

View File

@@ -0,0 +1,475 @@
import { Entity } from '../Entity';
import { QueryCondition, QueryConditionType } from './QueryTypes';
import { BitMask64Utils } from '../Utils/BigIntCompatibility';
import { createLogger } from '../../Utils/Logger';
const logger = createLogger('ReactiveQuery');
/**
* 响应式查询变化类型
*/
export enum ReactiveQueryChangeType {
/** 实体添加到查询结果 */
ADDED = 'added',
/** 实体从查询结果移除 */
REMOVED = 'removed',
/** 查询结果批量更新 */
BATCH_UPDATE = 'batch_update'
}
/**
* 响应式查询变化事件
*/
export interface ReactiveQueryChange {
/** 变化类型 */
type: ReactiveQueryChangeType;
/** 变化的实体 */
entity?: Entity;
/** 批量变化的实体 */
entities?: readonly Entity[];
/** 新增的实体列表(仅batch_update时有效) */
added?: readonly Entity[];
/** 移除的实体列表(仅batch_update时有效) */
removed?: readonly Entity[];
}
/**
* 响应式查询监听器
*/
export type ReactiveQueryListener = (change: ReactiveQueryChange) => void;
/**
* 响应式查询配置
*/
export interface ReactiveQueryConfig {
/** 是否启用批量模式(减少通知频率) */
enableBatchMode?: boolean;
/** 批量模式的延迟时间(毫秒) */
batchDelay?: number;
/** 调试模式 */
debug?: boolean;
}
/**
* 响应式查询类
*
* 提供基于事件驱动的实体查询机制,只在实体/组件真正变化时触发通知。
*
* 核心特性:
* - Event-driven: 基于事件的增量更新
* - 精确通知: 只通知真正匹配的变化
* - 性能优化: 避免每帧重复查询
*
* @example
* ```typescript
* // 创建响应式查询
* const query = new ReactiveQuery(querySystem, {
* type: QueryConditionType.ALL,
* componentTypes: [Position, Velocity],
* mask: createMask([Position, Velocity])
* });
*
* // 订阅变化
* query.subscribe((change) => {
* if (change.type === ReactiveQueryChangeType.ADDED) {
* console.log('新实体:', change.entity);
* }
* });
*
* // 获取当前结果
* const entities = query.getEntities();
* ```
*/
export class ReactiveQuery {
/** 当前查询结果 */
private _entities: Entity[] = [];
/** 实体ID集合,用于快速查找 */
private _entityIdSet: Set<number> = new Set();
/** 查询条件 */
private readonly _condition: QueryCondition;
/** 监听器列表 */
private _listeners: ReactiveQueryListener[] = [];
/** 配置 */
private readonly _config: ReactiveQueryConfig;
/** 批量变化缓存 */
private _batchChanges: {
added: Entity[];
removed: Entity[];
timer: ReturnType<typeof setTimeout> | null;
};
/** 查询ID(用于调试) */
private readonly _id: string;
/** 是否已激活 */
private _active: boolean = true;
constructor(condition: QueryCondition, config: ReactiveQueryConfig = {}) {
this._condition = condition;
this._config = {
enableBatchMode: config.enableBatchMode ?? true,
batchDelay: config.batchDelay ?? 16, // 默认一帧
debug: config.debug ?? false
};
this._id = this.generateQueryId();
this._batchChanges = {
added: [],
removed: [],
timer: null
};
if (this._config.debug) {
logger.debug(`创建ReactiveQuery: ${this._id}`);
}
}
/**
* 生成查询ID
*/
private generateQueryId(): string {
const typeStr = this._condition.type;
const componentsStr = this._condition.componentTypes
.map(t => t.name)
.sort()
.join(',');
return `${typeStr}:${componentsStr}`;
}
/**
* 订阅查询变化
*
* @param listener 监听器函数
* @returns 取消订阅的函数
*/
public subscribe(listener: ReactiveQueryListener): () => void {
if (!this._active) {
throw new Error(`Cannot subscribe to disposed ReactiveQuery ${this._id}`);
}
if (typeof listener !== 'function') {
throw new TypeError('Listener must be a function');
}
this._listeners.push(listener);
if (this._config.debug) {
logger.debug(`订阅ReactiveQuery: ${this._id}, 监听器数量: ${this._listeners.length}`);
}
return () => {
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
};
}
/**
* 取消所有订阅
*/
public unsubscribeAll(): void {
this._listeners.length = 0;
}
/**
* 获取当前查询结果
*/
public getEntities(): readonly Entity[] {
return this._entities;
}
/**
* 获取查询结果数量
*/
public get count(): number {
return this._entities.length;
}
/**
* 检查实体是否匹配查询条件
*
* @param entity 要检查的实体
* @returns 是否匹配
*/
public matches(entity: Entity): boolean {
const entityMask = entity.componentMask;
switch (this._condition.type) {
case QueryConditionType.ALL:
return BitMask64Utils.hasAll(entityMask, this._condition.mask);
case QueryConditionType.ANY:
return BitMask64Utils.hasAny(entityMask, this._condition.mask);
case QueryConditionType.NONE:
return BitMask64Utils.hasNone(entityMask, this._condition.mask);
default:
return false;
}
}
/**
* 通知实体添加
*
* 当Scene中添加实体时调用
*
* @param entity 添加的实体
*/
public notifyEntityAdded(entity: Entity): void {
if (!this._active) return;
// 检查实体是否匹配查询条件
if (!this.matches(entity)) {
return;
}
// 检查是否已存在
if (this._entityIdSet.has(entity.id)) {
return;
}
// 添加到结果集
this._entities.push(entity);
this._entityIdSet.add(entity.id);
// 通知监听器
if (this._config.enableBatchMode) {
this.addToBatch('added', entity);
} else {
this.notifyListeners({
type: ReactiveQueryChangeType.ADDED,
entity
});
}
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 实体添加 ${entity.name}(${entity.id})`);
}
}
/**
* 通知实体移除
*
* 当Scene中移除实体时调用
*
* @param entity 移除的实体
*/
public notifyEntityRemoved(entity: Entity): void {
if (!this._active) return;
// 检查是否在结果集中
if (!this._entityIdSet.has(entity.id)) {
return;
}
// 从结果集移除
const index = this._entities.indexOf(entity);
if (index !== -1) {
this._entities.splice(index, 1);
}
this._entityIdSet.delete(entity.id);
// 通知监听器
if (this._config.enableBatchMode) {
this.addToBatch('removed', entity);
} else {
this.notifyListeners({
type: ReactiveQueryChangeType.REMOVED,
entity
});
}
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 实体移除 ${entity.name}(${entity.id})`);
}
}
/**
* 通知实体组件变化
*
* 当实体的组件发生变化时调用
*
* @param entity 变化的实体
*/
public notifyEntityChanged(entity: Entity): void {
if (!this._active) return;
const wasMatching = this._entityIdSet.has(entity.id);
const isMatching = this.matches(entity);
if (wasMatching && !isMatching) {
// 实体不再匹配,从结果集移除
this.notifyEntityRemoved(entity);
} else if (!wasMatching && isMatching) {
// 实体现在匹配,添加到结果集
this.notifyEntityAdded(entity);
}
}
/**
* 批量初始化查询结果
*
* @param entities 初始实体列表
*/
public initializeWith(entities: readonly Entity[]): void {
// 清空现有结果
this._entities.length = 0;
this._entityIdSet.clear();
// 筛选匹配的实体
for (const entity of entities) {
if (this.matches(entity)) {
this._entities.push(entity);
this._entityIdSet.add(entity.id);
}
}
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 初始化 ${this._entities.length} 个实体`);
}
}
/**
* 添加到批量变化缓存
*/
private addToBatch(type: 'added' | 'removed', entity: Entity): void {
if (type === 'added') {
this._batchChanges.added.push(entity);
} else {
this._batchChanges.removed.push(entity);
}
// 启动批量通知定时器
if (this._batchChanges.timer === null) {
this._batchChanges.timer = setTimeout(() => {
this.flushBatchChanges();
}, this._config.batchDelay);
}
}
/**
* 刷新批量变化
*/
private flushBatchChanges(): void {
if (this._batchChanges.added.length === 0 && this._batchChanges.removed.length === 0) {
this._batchChanges.timer = null;
return;
}
const added = [...this._batchChanges.added];
const removed = [...this._batchChanges.removed];
// 清空缓存
this._batchChanges.added.length = 0;
this._batchChanges.removed.length = 0;
this._batchChanges.timer = null;
// 通知监听器
this.notifyListeners({
type: ReactiveQueryChangeType.BATCH_UPDATE,
added,
removed,
entities: this._entities
});
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 批量更新 +${added.length} -${removed.length}`);
}
}
/**
* 通知所有监听器
*/
private notifyListeners(change: ReactiveQueryChange): void {
const listeners = [...this._listeners];
for (const listener of listeners) {
try {
listener(change);
} catch (error) {
logger.error(`ReactiveQuery ${this._id}: 监听器执行出错`, error);
}
}
}
/**
* 暂停响应式查询
*
* 暂停后不再响应实体变化,但可以继续获取当前结果
*/
public pause(): void {
this._active = false;
// 清空批量变化缓存
if (this._batchChanges.timer !== null) {
clearTimeout(this._batchChanges.timer);
this._batchChanges.timer = null;
}
this._batchChanges.added.length = 0;
this._batchChanges.removed.length = 0;
}
/**
* 恢复响应式查询
*/
public resume(): void {
this._active = true;
}
/**
* 销毁响应式查询
*
* 释放所有资源,清空监听器和结果集
*/
public dispose(): void {
if (this._batchChanges.timer !== null) {
clearTimeout(this._batchChanges.timer);
this._batchChanges.timer = null;
}
this._batchChanges.added.length = 0;
this._batchChanges.removed.length = 0;
this._active = false;
this.unsubscribeAll();
this._entities.length = 0;
this._entityIdSet.clear();
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 已销毁`);
}
}
/**
* 获取查询条件
*/
public get condition(): QueryCondition {
return this._condition;
}
/**
* 获取查询ID
*/
public get id(): string {
return this._id;
}
/**
* 检查是否激活
*/
public get active(): boolean {
return this._active;
}
/**
* 获取监听器数量
*/
public get listenerCount(): number {
return this._listeners.length;
}
}

View File

@@ -75,7 +75,7 @@ export interface SystemMetadata {
* @ECSSystem('Physics', { updateOrder: 10 })
* class PhysicsSystem extends EntitySystem {
* constructor(@Inject(CollisionSystem) private collision: CollisionSystem) {
* super(Matcher.of(Transform, RigidBody));
* super(Matcher.empty().all(Transform, RigidBody));
* }
* }
* ```

View File

@@ -15,7 +15,7 @@ import { IncrementalSerializer, IncrementalSnapshot, IncrementalSerializationOpt
import { ComponentPoolManager } from './Core/ComponentPool';
import { PerformanceMonitor } from '../Utils/PerformanceMonitor';
import { ServiceContainer, type ServiceType } from '../Core/ServiceContainer';
import { createInstance, isInjectable } from '../Core/DI';
import { createInstance, isInjectable, injectProperties } from '../Core/DI';
import { isUpdatable, getUpdatableMetadata } from '../Core/DI/Decorators';
import { createLogger } from '../Utils/Logger';
@@ -527,7 +527,7 @@ export class Scene implements IScene {
* @Injectable()
* class PhysicsSystem extends EntitySystem {
* constructor(@Inject(CollisionSystem) private collision: CollisionSystem) {
* super(Matcher.of(Transform));
* super(Matcher.empty().all(Transform));
* }
* }
* scene.addEntityProcessor(PhysicsSystem);
@@ -547,7 +547,9 @@ export class Scene implements IScene {
constructor = systemTypeOrInstance;
if (this._services.isRegistered(constructor)) {
return this._services.resolve(constructor) as T;
const existingSystem = this._services.resolve(constructor) as T;
this.logger.debug(`System ${constructor.name} already registered, returning existing instance`);
return existingSystem;
}
if (isInjectable(constructor)) {
@@ -560,7 +562,17 @@ export class Scene implements IScene {
constructor = system.constructor;
if (this._services.isRegistered(constructor)) {
return system;
const existingSystem = this._services.resolve(constructor);
if (existingSystem === system) {
this.logger.debug(`System ${constructor.name} instance already registered, returning it`);
return system;
} else {
this.logger.warn(
`Attempting to register a different instance of ${constructor.name}, ` +
`but type is already registered. Returning existing instance.`
);
return existingSystem as T;
}
}
}
@@ -578,8 +590,12 @@ export class Scene implements IScene {
this._services.registerInstance(constructor, system);
injectProperties(system, this._services);
system.initialize();
this.logger.debug(`System ${constructor.name} registered and initialized`);
return system;
}
@@ -597,7 +613,7 @@ export class Scene implements IScene {
* @Injectable()
* @ECSSystem('Collision', { updateOrder: 5 })
* class CollisionSystem extends EntitySystem implements IService {
* constructor() { super(Matcher.of(Collider)); }
* constructor() { super(Matcher.empty().all(Collider)); }
* dispose() {}
* }
*
@@ -605,7 +621,7 @@ export class Scene implements IScene {
* @ECSSystem('Physics', { updateOrder: 10 })
* class PhysicsSystem extends EntitySystem implements IService {
* constructor(@Inject(CollisionSystem) private collision: CollisionSystem) {
* super(Matcher.of(Transform, RigidBody));
* super(Matcher.empty().all(Transform, RigidBody));
* }
* dispose() {}
* }

View File

@@ -36,7 +36,7 @@ interface EventListenerRecord {
* // 传统方式
* class MovementSystem extends EntitySystem {
* constructor() {
* super(Matcher.of(Transform, Velocity));
* super(Matcher.empty().all(Transform, Velocity));
* }
*
* protected process(entities: readonly Entity[]): void {
@@ -51,7 +51,7 @@ interface EventListenerRecord {
* // 类型安全方式
* class MovementSystem extends EntitySystem<[typeof Transform, typeof Velocity]> {
* constructor() {
* super(Matcher.of(Transform, Velocity));
* super(Matcher.empty().all(Transform, Velocity));
* }
*
* protected process(entities: readonly Entity[]): void {
@@ -555,6 +555,7 @@ export abstract class EntitySystem<
try {
this.onBegin();
// 查询实体并存储到帧缓存中
// 响应式查询会自动维护最新的实体列表updateEntityTracking会在检测到变化时invalidate
this._entityCache.frame = this.queryEntities();
entityCount = this._entityCache.frame.length;

View File

@@ -1,101 +0,0 @@
import { Bits } from './Bits';
import { getComponentTypeName } from '../Decorators';
import { ComponentType } from "../../Types";
/**
* 组件类型管理器
* 负责管理组件类型的注册和ID分配
* 支持无限数量的组件类型(通过自动扩展 BitMask
*/
export class ComponentTypeManager {
private static _instance: ComponentTypeManager;
private _componentTypes = new Map<Function, number>();
private _typeNames = new Map<number, string>();
private _nextTypeId = 0;
/**
* 获取单例实例
*/
public static get instance(): ComponentTypeManager {
if (!ComponentTypeManager._instance) {
ComponentTypeManager._instance = new ComponentTypeManager();
}
return ComponentTypeManager._instance;
}
private constructor() {}
/**
* 获取组件类型的ID
* @param componentType 组件类型构造函数
* @returns 组件类型ID
*/
public getTypeId(componentType: ComponentType): number {
let typeId = this._componentTypes.get(componentType);
if (typeId === undefined) {
typeId = this._nextTypeId++;
this._componentTypes.set(componentType, typeId);
this._typeNames.set(typeId, getComponentTypeName(componentType));
}
return typeId;
}
/**
* 获取组件类型名称
* @param typeId 组件类型ID
* @returns 组件类型名称
*/
public getTypeName(typeId: number): string {
return this._typeNames.get(typeId) || 'Unknown';
}
/**
* 创建包含指定组件类型的Bits对象
* @param componentTypes 组件类型构造函数数组
* @returns Bits对象
*/
public createBits(...componentTypes: ComponentType[]): Bits {
const bits = new Bits();
for (const componentType of componentTypes) {
const typeId = this.getTypeId(componentType);
bits.set(typeId);
}
return bits;
}
/**
* 获取实体的组件位掩码
* @param components 组件数组
* @returns Bits对象
*/
public getEntityBits(components: ComponentType[]): Bits {
const bits = new Bits();
for (const component of components) {
const typeId = this.getTypeId(component);
bits.set(typeId);
}
return bits;
}
/**
* 重置管理器(主要用于测试)
*/
public reset(): void {
this._componentTypes.clear();
this._typeNames.clear();
this._nextTypeId = 0;
}
/**
* 获取已注册的组件类型数量
*/
public get registeredTypeCount(): number {
return this._componentTypes.size;
}
}

View File

@@ -4,7 +4,6 @@ export { EntityProcessorList } from './EntityProcessorList';
export { IdentifierPool } from './IdentifierPool';
export { Matcher } from './Matcher';
export { Bits } from './Bits';
export { ComponentTypeManager } from './ComponentTypeManager';
export { BitMask64Utils, BitMask64Data } from './BigIntCompatibility';
export { SparseSet } from './SparseSet';
export { ComponentSparseSet } from './ComponentSparseSet';

View File

@@ -15,4 +15,6 @@ export * from './Core/Storage';
export * from './Core/StorageDecorators';
export * from './Serialization';
export { ReferenceTracker, getSceneByEntityId } from './Core/ReferenceTracker';
export type { EntityRefRecord } from './Core/ReferenceTracker';
export type { EntityRefRecord } from './Core/ReferenceTracker';
export { ReactiveQuery, ReactiveQueryChangeType } from './Core/ReactiveQuery';
export type { ReactiveQueryChange, ReactiveQueryListener, ReactiveQueryConfig } from './Core/ReactiveQuery';

View File

@@ -0,0 +1,45 @@
import { IECSDebugConfig } from '../../Types';
import { Injectable } from '../../Core/DI/Decorators';
import type { IService } from '../../Core/ServiceContainer';
/**
* 调试配置服务
*
* 管理调试系统的配置信息
*/
@Injectable()
export class DebugConfigService implements IService {
private _config: IECSDebugConfig;
constructor() {
this._config = {
enabled: false,
websocketUrl: '',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
}
public setConfig(config: IECSDebugConfig): void {
this._config = config;
}
public getConfig(): IECSDebugConfig {
return this._config;
}
public isEnabled(): boolean {
return this._config.enabled;
}
dispose(): void {
// 清理资源
}
}

View File

@@ -10,17 +10,20 @@ import { ComponentPoolManager } from '../../ECS/Core/ComponentPool';
import { Pool } from '../../Utils/Pool';
import { getComponentInstanceTypeName, getSystemInstanceTypeName } from '../../ECS/Decorators';
import type { IService } from '../../Core/ServiceContainer';
import type { IUpdatable } from '../../Types/IUpdatable';
import { SceneManager } from '../../ECS/SceneManager';
import { PerformanceMonitor } from '../PerformanceMonitor';
import { Injectable, Inject, Updatable } from '../../Core/DI/Decorators';
import { DebugConfigService } from './DebugConfigService';
/**
* 调试管理器
*
* 整合所有调试数据收集器,负责收集和发送调试数据
*
* 通过构造函数接收SceneManager和PerformanceMonitor避免直接依赖Core实例
*/
export class DebugManager implements IService {
@Injectable()
@Updatable()
export class DebugManager implements IService, IUpdatable {
private config: IECSDebugConfig;
private webSocketManager: WebSocketManager;
private entityCollector: EntityDataCollector;
@@ -36,18 +39,12 @@ export class DebugManager implements IService {
private sendInterval: number;
private isRunning: boolean = false;
/**
* 构造调试管理器
* @param sceneManager 场景管理器
* @param performanceMonitor 性能监控器
* @param config 调试配置
*/
constructor(
sceneManager: SceneManager,
performanceMonitor: PerformanceMonitor,
config: IECSDebugConfig
@Inject(SceneManager) sceneManager: SceneManager,
@Inject(PerformanceMonitor) performanceMonitor: PerformanceMonitor,
@Inject(DebugConfigService) configService: DebugConfigService
) {
this.config = config;
this.config = configService.getConfig();
this.sceneManager = sceneManager;
this.performanceMonitor = performanceMonitor;
@@ -60,15 +57,15 @@ export class DebugManager implements IService {
// 初始化WebSocket管理器
this.webSocketManager = new WebSocketManager(
config.websocketUrl,
config.autoReconnect !== false
this.config.websocketUrl,
this.config.autoReconnect !== false
);
// 设置消息处理回调
this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));
// 计算发送间隔(基于帧率)
const debugFrameRate = config.debugFrameRate || 30;
const debugFrameRate = this.config.debugFrameRate || 30;
this.sendInterval = 1000 / debugFrameRate;
this.start();
@@ -116,16 +113,12 @@ export class DebugManager implements IService {
}
}
/**
* 帧更新回调
*/
public onFrameUpdate(deltaTime: number): void {
public update(deltaTime?: number): void {
if (!this.isRunning || !this.config.enabled) return;
this.frameCounter++;
const currentTime = Date.now();
// 基于配置的帧率发送数据
if (currentTime - this.lastSendTime >= this.sendInterval) {
this.sendDebugData();
this.lastSendTime = currentTime;

View File

@@ -1,7 +1,6 @@
import { IEntityDebugData } from '../../Types';
import { Entity } from '../../ECS/Entity';
import { Component } from '../../ECS/Component';
import { ComponentTypeManager } from '../../ECS/Utils/ComponentTypeManager';
import { getComponentInstanceTypeName, getSystemInstanceTypeName } from '../../ECS/Decorators';
import { IScene } from '../../ECS/IScene';
@@ -722,20 +721,7 @@ export class EntityDataCollector {
properties: Record<string, any>;
}> {
return components.map((component: Component) => {
let typeName = getComponentInstanceTypeName(component);
if (!typeName || typeName === 'Object' || typeName === 'Function') {
try {
const typeManager = ComponentTypeManager.instance;
const componentType = component.constructor as any;
const typeId = typeManager.getTypeId(componentType);
typeName = typeManager.getTypeName(typeId);
} catch (error) {
typeName = 'UnknownComponent';
}
}
// 提取实际的组件属性
const typeName = getComponentInstanceTypeName(component);
const properties: Record<string, any> = {};
try {

View File

@@ -4,4 +4,5 @@ export { PerformanceDataCollector } from './PerformanceDataCollector';
export { ComponentDataCollector } from './ComponentDataCollector';
export { SceneDataCollector } from './SceneDataCollector';
export { WebSocketManager } from './WebSocketManager';
export { DebugManager } from './DebugManager';
export { DebugManager } from './DebugManager';
export { DebugConfigService } from './DebugConfigService';

View File

@@ -0,0 +1,668 @@
import { Core } from '../src/Core';
import { Scene } from '../src/ECS/Scene';
import { DebugManager } from '../src/Utils/Debug/DebugManager';
import { DebugConfigService } from '../src/Utils/Debug/DebugConfigService';
import { IECSDebugConfig } from '../src/Types';
import { createLogger } from '../src/Utils/Logger';
const logger = createLogger('DebugManagerTest');
class TestScene extends Scene {
public initializeCalled = false;
public override initialize(): void {
this.initializeCalled = true;
}
public override begin(): void {
}
public override end(): void {
}
}
describe('DebugManager DI Architecture Tests', () => {
let originalConsoleWarn: typeof console.warn;
let originalConsoleError: typeof console.error;
beforeEach(() => {
(Core as any)._instance = null;
originalConsoleWarn = console.warn;
originalConsoleError = console.error;
console.warn = jest.fn();
console.error = jest.fn();
});
afterEach(() => {
console.warn = originalConsoleWarn;
console.error = originalConsoleError;
if (Core.Instance) {
Core.destroy();
}
});
describe('DebugConfigService - Configuration Service', () => {
test('should create with default configuration', () => {
const configService = new DebugConfigService();
const config = configService.getConfig();
expect(config).toBeDefined();
expect(config.enabled).toBe(false);
expect(config.websocketUrl).toBe('');
expect(config.debugFrameRate).toBe(30);
expect(config.autoReconnect).toBe(true);
expect(config.channels).toBeDefined();
});
test('should set and get configuration', () => {
const configService = new DebugConfigService();
const newConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 60,
autoReconnect: false,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
configService.setConfig(newConfig);
const retrievedConfig = configService.getConfig();
expect(retrievedConfig).toEqual(newConfig);
expect(retrievedConfig.enabled).toBe(true);
expect(retrievedConfig.websocketUrl).toBe('ws://localhost:9229');
expect(retrievedConfig.debugFrameRate).toBe(60);
});
test('should return correct enabled status', () => {
const configService = new DebugConfigService();
expect(configService.isEnabled()).toBe(false);
configService.setConfig({
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
});
expect(configService.isEnabled()).toBe(true);
});
test('should implement dispose method', () => {
const configService = new DebugConfigService();
expect(() => configService.dispose()).not.toThrow();
});
});
describe('DebugManager - DI Initialization', () => {
test('should initialize DebugManager through DI when debug config is enabled', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({
debug: true,
debugConfig: debugConfig
});
expect((core as any)._debugManager).toBeDefined();
expect((core as any)._debugManager).toBeInstanceOf(DebugManager);
});
test('should not create DebugManager when debug config is disabled', () => {
const core = Core.create({
debug: true,
debugConfig: {
enabled: false,
websocketUrl: '',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
}
});
expect((core as any)._debugManager).toBeUndefined();
});
test('should not create DebugManager when no debug config provided', () => {
const core = Core.create({ debug: true });
expect((core as any)._debugManager).toBeUndefined();
});
test('should register DebugConfigService in ServiceContainer', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({
debug: true,
debugConfig: debugConfig
});
const configService = Core.services.resolve(DebugConfigService);
expect(configService).toBeDefined();
expect(configService).toBeInstanceOf(DebugConfigService);
});
test('should inject all dependencies correctly', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({
debug: true,
debugConfig: debugConfig
});
const debugManager = (core as any)._debugManager as DebugManager;
expect(debugManager).toBeDefined();
const sceneManager = (debugManager as any).sceneManager;
const performanceMonitor = (debugManager as any).performanceMonitor;
const config = (debugManager as any).config;
expect(sceneManager).toBeDefined();
expect(performanceMonitor).toBeDefined();
expect(config).toBeDefined();
expect(config.enabled).toBe(true);
expect(config.websocketUrl).toBe('ws://localhost:9229');
});
});
describe('Core.enableDebug - Runtime Activation', () => {
test('should enable debug at runtime', () => {
const core = Core.create({ debug: true });
expect(Core.isDebugEnabled).toBe(false);
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
expect(Core.isDebugEnabled).toBe(true);
expect((core as any)._debugManager).toBeDefined();
});
test('should create DebugConfigService when enabling debug at runtime', () => {
Core.create({ debug: true });
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
const configService = Core.services.resolve(DebugConfigService);
expect(configService).toBeDefined();
expect(configService.getConfig()).toEqual(debugConfig);
});
test('should update existing DebugManager config when already enabled', () => {
const initialConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: initialConfig });
const updatedConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:8080',
debugFrameRate: 60,
autoReconnect: false,
channels: {
entities: false,
systems: true,
performance: true,
components: false,
scenes: true
}
};
Core.enableDebug(updatedConfig);
expect(Core.isDebugEnabled).toBe(true);
const debugManager = (Core.Instance as any)._debugManager;
expect(debugManager).toBeDefined();
});
test('should show warning when enabling debug without Core instance', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining('Core实例未创建请先调用Core.create()')
);
});
});
describe('Core.disableDebug', () => {
test('should disable debug functionality', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
expect(Core.isDebugEnabled).toBe(true);
Core.disableDebug();
expect(Core.isDebugEnabled).toBe(false);
expect((Core.Instance as any)._debugManager).toBeUndefined();
});
test('should handle disabling when Core instance does not exist', () => {
expect(() => Core.disableDebug()).not.toThrow();
});
test('should handle disabling when debug was never enabled', () => {
Core.create({ debug: true });
expect(() => Core.disableDebug()).not.toThrow();
});
});
describe('DebugManager - Auto Update Integration', () => {
test('should be registered as updatable service', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const serviceContainer = (Core.Instance as any)._serviceContainer;
const updatableCount = serviceContainer.getUpdatableCount();
expect(updatableCount).toBeGreaterThan(0);
});
test('should be updated during Core.update cycle', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const updateSpy = jest.spyOn(debugManager, 'update');
Core.update(0.016);
expect(updateSpy).toHaveBeenCalledWith(0.016);
});
});
describe('DebugManager - Scene Integration', () => {
test('should respond to scene changes', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const sceneChangeSpy = jest.spyOn(debugManager, 'onSceneChanged');
const testScene = new TestScene();
Core.setScene(testScene);
expect(sceneChangeSpy).toHaveBeenCalled();
});
test('should collect debug data from current scene', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const testScene = new TestScene();
Core.setScene(testScene);
const debugData = Core.getDebugData();
expect(debugData).toBeDefined();
expect(debugData).toHaveProperty('timestamp');
expect(debugData).toHaveProperty('frameworkVersion');
expect(debugData).toHaveProperty('currentScene');
});
});
describe('DebugManager - Configuration Management', () => {
test('should use correct debug frame rate', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 60,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const sendInterval = (debugManager as any).sendInterval;
expect(sendInterval).toBe(1000 / 60);
});
test('should handle channel configuration correctly', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: false,
performance: false,
components: true,
scenes: false
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const testScene = new TestScene();
Core.setScene(testScene);
const debugData = Core.getDebugData() as any;
expect(debugData.entities).toBeDefined();
expect(debugData.components).toBeDefined();
expect(debugData.systems).toBeUndefined();
expect(debugData.performance).toBeUndefined();
expect(debugData.scenes).toBeUndefined();
});
});
describe('DebugManager - Lifecycle', () => {
test('should start automatically on creation', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const isRunning = (debugManager as any).isRunning;
expect(isRunning).toBe(true);
});
test('should stop when disabling debug', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (Core.Instance as any)._debugManager as DebugManager;
const stopSpy = jest.spyOn(debugManager, 'stop');
Core.disableDebug();
expect(stopSpy).toHaveBeenCalled();
});
test('should dispose properly on Core.destroy', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (Core.Instance as any)._debugManager as DebugManager;
const stopSpy = jest.spyOn(debugManager, 'stop');
Core.destroy();
expect(stopSpy).toHaveBeenCalled();
});
});
describe('DebugManager - Pure DI Architecture Validation', () => {
test('should resolve all dependencies through ServiceContainer', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const debugConfigService = Core.services.resolve(DebugConfigService);
expect(debugConfigService).toBeDefined();
const config = debugConfigService.getConfig();
expect(config).toEqual(debugConfig);
});
test('should not have mixed DI patterns', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const sceneManager = (debugManager as any).sceneManager;
const performanceMonitor = (debugManager as any).performanceMonitor;
const config = (debugManager as any).config;
expect(sceneManager).toBeDefined();
expect(performanceMonitor).toBeDefined();
expect(config).toBeDefined();
expect(config.enabled).toBe(true);
});
test('should use factory pattern for registration', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const debugManager1 = (Core.Instance as any)._debugManager;
const debugManager2 = Core.services.resolve(DebugManager);
expect(debugManager1).toBe(debugManager2);
});
});
});

View File

@@ -0,0 +1,94 @@
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { EntitySystem } from '../../../src/ECS/Systems/EntitySystem';
import { Matcher } from '../../../src/ECS/Utils/Matcher';
import { ComponentRegistry } from '../../../src/ECS/Core/ComponentStorage';
// 简单的测试组件
class HealthComponent extends Component {
public health: number;
constructor(...args: unknown[]) {
super();
const [health = 100] = args as [number?];
this.health = health;
}
}
// 简单的测试系统
class HealthSystem extends EntitySystem {
public onAddedEntities: Entity[] = [];
constructor() {
super(Matcher.empty().all(HealthComponent));
}
protected override onAdded(entity: Entity): void {
console.log('[HealthSystem] onAdded called:', { id: entity.id, name: entity.name });
this.onAddedEntities.push(entity);
}
}
describe('MinimalSystemInit - 最小化系统初始化测试', () => {
let scene: Scene;
beforeEach(() => {
ComponentRegistry.reset();
scene = new Scene();
});
afterEach(() => {
if (scene) {
scene.end();
}
});
test('先创建实体和组件,再添加系统 - 应该触发onAdded', () => {
console.log('\\n=== Test 1: 先创建实体再添加系统 ===');
// 1. 创建实体并添加组件
const entity = scene.createEntity('TestEntity');
entity.addComponent(new HealthComponent(100));
console.log('[Test] Entity created with HealthComponent');
console.log('[Test] ComponentRegistry registered types:', ComponentRegistry.getRegisteredCount());
// 2. 验证QuerySystem能查询到实体
const queryResult = scene.querySystem.queryAll(HealthComponent);
console.log('[Test] QuerySystem result:', { count: queryResult.count });
// 3. 添加系统
const system = new HealthSystem();
console.log('[Test] Adding system to scene...');
scene.addEntityProcessor(system);
console.log('[Test] System added, onAddedEntities.length =', system.onAddedEntities.length);
// 4. 验证
expect(system.onAddedEntities).toHaveLength(1);
});
test('先添加系统,再创建实体和组件 - 应该在update时触发onAdded', () => {
console.log('\\n=== Test 2: 先添加系统再创建实体 ===');
// 1. 先添加系统
const system = new HealthSystem();
scene.addEntityProcessor(system);
console.log('[Test] System added, onAddedEntities.length =', system.onAddedEntities.length);
// 2. 创建实体并添加组件
const entity = scene.createEntity('TestEntity');
entity.addComponent(new HealthComponent(100));
console.log('[Test] Entity created with HealthComponent');
// 3. 调用update触发系统查询
console.log('[Test] Calling scene.update()...');
scene.update();
console.log('[Test] After update, onAddedEntities.length =', system.onAddedEntities.length);
// 4. 验证
expect(system.onAddedEntities).toHaveLength(1);
});
});

View File

@@ -0,0 +1,160 @@
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { EntitySystem } from '../../../src/ECS/Systems/EntitySystem';
import { Matcher } from '../../../src/ECS/Utils/Matcher';
import { ComponentRegistry } from '../../../src/ECS/Core/ComponentStorage';
// 测试组件
class PositionComponent extends Component {
public x: number;
public y: number;
constructor(...args: unknown[]) {
super();
const [x = 0, y = 0] = args as [number?, number?];
this.x = x;
this.y = y;
}
}
class VelocityComponent extends Component {
public vx: number;
public vy: number;
constructor(...args: unknown[]) {
super();
const [vx = 0, vy = 0] = args as [number?, number?];
this.vx = vx;
this.vy = vy;
}
}
class HealthComponent extends Component {
public health: number;
constructor(...args: unknown[]) {
super();
const [health = 100] = args as [number?];
this.health = health;
}
}
// 测试系统
class MovementSystem extends EntitySystem {
public onAddedEntities: Entity[] = [];
constructor() {
super(Matcher.empty().all(PositionComponent, VelocityComponent));
}
protected override onAdded(entity: Entity): void {
console.log('[MovementSystem] onAdded:', { id: entity.id, name: entity.name });
this.onAddedEntities.push(entity);
}
}
class HealthSystem extends EntitySystem {
public onAddedEntities: Entity[] = [];
constructor() {
super(Matcher.empty().all(HealthComponent));
}
protected override onAdded(entity: Entity): void {
console.log('[HealthSystem] onAdded:', { id: entity.id, name: entity.name });
this.onAddedEntities.push(entity);
}
}
describe('MultiSystemInit - 多系统初始化测试', () => {
let scene: Scene;
beforeEach(() => {
ComponentRegistry.reset();
scene = new Scene();
});
afterEach(() => {
if (scene) {
scene.end();
}
});
test('多个系统同时响应同一实体 - 复现失败场景', () => {
console.log('\\n=== Test: 多个系统同时响应同一实体 ===');
// 1. 创建实体并添加所有组件
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(0, 0));
entity.addComponent(new VelocityComponent(1, 1));
entity.addComponent(new HealthComponent(100));
console.log('[Test] Entity created with Position, Velocity, Health');
console.log('[Test] ComponentRegistry registered types:', ComponentRegistry.getRegisteredCount());
// 2. 验证QuerySystem能查询到实体
const movementQuery = scene.querySystem.queryAll(PositionComponent, VelocityComponent);
const healthQuery = scene.querySystem.queryAll(HealthComponent);
console.log('[Test] MovementQuery result:', { count: movementQuery.count });
console.log('[Test] HealthQuery result:', { count: healthQuery.count });
// 3. 添加两个系统
console.log('[Test] Adding MovementSystem...');
const movementSystem = new MovementSystem();
scene.addEntityProcessor(movementSystem);
console.log('[Test] MovementSystem added, onAddedEntities.length =', movementSystem.onAddedEntities.length);
console.log('[Test] Adding HealthSystem...');
const healthSystem = new HealthSystem();
scene.addEntityProcessor(healthSystem);
console.log('[Test] HealthSystem added, onAddedEntities.length =', healthSystem.onAddedEntities.length);
// 4. 验证
console.log('[Test] Final check:');
console.log(' MovementSystem.onAddedEntities.length =', movementSystem.onAddedEntities.length);
console.log(' HealthSystem.onAddedEntities.length =', healthSystem.onAddedEntities.length);
expect(movementSystem.onAddedEntities).toHaveLength(1);
expect(healthSystem.onAddedEntities).toHaveLength(1);
});
test('不同系统匹配不同实体 - 复现失败场景', () => {
console.log('\\n=== Test: 不同系统匹配不同实体 ===');
// 1. 创建两个实体
const movingEntity = scene.createEntity('Moving');
movingEntity.addComponent(new PositionComponent(0, 0));
movingEntity.addComponent(new VelocityComponent(1, 1));
const healthEntity = scene.createEntity('Health');
healthEntity.addComponent(new HealthComponent(100));
console.log('[Test] Two entities created');
// 2. 验证QuerySystem
const movementQuery = scene.querySystem.queryAll(PositionComponent, VelocityComponent);
const healthQuery = scene.querySystem.queryAll(HealthComponent);
console.log('[Test] MovementQuery result:', { count: movementQuery.count });
console.log('[Test] HealthQuery result:', { count: healthQuery.count });
// 3. 添加系统
console.log('[Test] Adding systems...');
const movementSystem = new MovementSystem();
const healthSystem = new HealthSystem();
scene.addEntityProcessor(movementSystem);
scene.addEntityProcessor(healthSystem);
console.log('[Test] Systems added');
console.log(' MovementSystem.onAddedEntities.length =', movementSystem.onAddedEntities.length);
console.log(' HealthSystem.onAddedEntities.length =', healthSystem.onAddedEntities.length);
// 4. 验证
expect(movementSystem.onAddedEntities).toHaveLength(1);
expect(movementSystem.onAddedEntities[0]).toBe(movingEntity);
expect(healthSystem.onAddedEntities).toHaveLength(1);
expect(healthSystem.onAddedEntities[0]).toBe(healthEntity);
});
});

View File

@@ -449,22 +449,24 @@ describe('QuerySystem - 查询系统测试', () => {
expect(parseFloat(stats.cacheStats.hitRate)).toBeLessThanOrEqual(100);
});
test('缓存命中率应该在重复查询时提高', () => {
test('缓存命中率应该在重复查询时保持高命中率', () => {
entities[0].addComponent(new PositionComponent(10, 20));
entities[1].addComponent(new PositionComponent(30, 40));
// 第一次查询(缓存未命中)
// 第一次查询(创建响应式查询缓存)
querySystem.queryAll(PositionComponent);
let stats = querySystem.getStats();
const initialHitRate = parseFloat(stats.cacheStats.hitRate);
// 重复查询应该命中缓存
// 重复查询(应该持续命中响应式查询缓存)
for (let i = 0; i < 10; i++) {
querySystem.queryAll(PositionComponent);
}
stats = querySystem.getStats();
expect(parseFloat(stats.cacheStats.hitRate)).toBeGreaterThan(initialHitRate);
// 响应式查询永远100%命中,这是期望的优化效果
expect(parseFloat(stats.cacheStats.hitRate)).toBeGreaterThanOrEqual(initialHitRate);
expect(parseFloat(stats.cacheStats.hitRate)).toBe(100);
});
test('应该能够清理查询缓存', () => {

View File

@@ -3,7 +3,6 @@ import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { EntitySystem } from '../../../src/ECS/Systems/EntitySystem';
import { Matcher } from '../../../src/ECS/Utils/Matcher';
import { ComponentTypeManager } from '../../../src/ECS/Utils/ComponentTypeManager';
/**
* System初始化测试套件
@@ -205,11 +204,16 @@ describe('SystemInitialization - 系统初始化测试', () => {
let scene: Scene;
beforeEach(() => {
ComponentTypeManager.instance.reset();
scene = new Scene();
scene.name = 'InitializationTestScene';
});
afterEach(() => {
if (scene) {
scene.end();
}
});
describe('初始化时序', () => {
test('先添加实体再添加系统 - 系统应该正确初始化', () => {
const player = scene.createEntity('Player');

View File

@@ -3,7 +3,7 @@ import { EntitySystem } from '../../src/ECS/Systems/EntitySystem';
import { Entity } from '../../src/ECS/Entity';
import { Component } from '../../src/ECS/Component';
import { Matcher } from '../../src/ECS/Utils/Matcher';
import { Injectable, Inject } from '../../src/Core/DI';
import { Injectable, Inject, InjectProperty } from '../../src/Core/DI';
import { Core } from '../../src/Core';
import type { IService } from '../../src/Core/ServiceContainer';
import { ECSSystem } from '../../src/ECS/Decorators';
@@ -423,4 +423,170 @@ describe('EntitySystem - 依赖注入测试', () => {
expect(transform.y).toBeCloseTo(0.8, 1);
});
});
describe('属性注入 @InjectProperty', () => {
test('应该支持单个属性注入', () => {
@Injectable()
@ECSSystem('Config')
class GameConfig extends EntitySystem implements IService {
public bulletDamage = 10;
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Combat')
class CombatSystem extends EntitySystem implements IService {
@InjectProperty(GameConfig)
gameConfig!: GameConfig;
constructor() {
super(Matcher.empty().all(Health));
}
protected override onInitialize(): void {
expect(this.gameConfig).toBeInstanceOf(GameConfig);
expect(this.gameConfig.bulletDamage).toBe(10);
}
override dispose() {}
}
scene.addEntityProcessor(GameConfig);
scene.addEntityProcessor(CombatSystem);
});
test('应该支持多个属性注入', () => {
@Injectable()
@ECSSystem('Time')
class TimeService extends EntitySystem implements IService {
public deltaTime = 0.016;
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Collision')
class CollisionSystem extends EntitySystem implements IService {
public checkCount = 0;
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Physics')
class PhysicsSystem extends EntitySystem implements IService {
@InjectProperty(TimeService)
time!: TimeService;
@InjectProperty(CollisionSystem)
collision!: CollisionSystem;
constructor() {
super(Matcher.empty());
}
protected override onInitialize(): void {
expect(this.time).toBeInstanceOf(TimeService);
expect(this.collision).toBeInstanceOf(CollisionSystem);
expect(this.time.deltaTime).toBe(0.016);
}
override dispose() {}
}
scene.registerSystems([TimeService, CollisionSystem, PhysicsSystem]);
});
test('属性注入应该在onInitialize之前完成', () => {
@Injectable()
@ECSSystem('Service')
class TestService extends EntitySystem implements IService {
public value = 42;
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Consumer')
class ConsumerSystem extends EntitySystem implements IService {
@InjectProperty(TestService)
service!: TestService;
private initializeValue = 0;
constructor() {
super(Matcher.empty());
}
protected override onInitialize(): void {
this.initializeValue = this.service.value;
}
public getInitializeValue(): number {
return this.initializeValue;
}
override dispose() {}
}
scene.addEntityProcessor(TestService);
const consumer = scene.addEntityProcessor(ConsumerSystem);
expect(consumer.getInitializeValue()).toBe(42);
});
test('属性注入可以与构造函数注入混合使用', () => {
@Injectable()
@ECSSystem('A')
class ServiceA extends EntitySystem implements IService {
public valueA = 'A';
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('B')
class ServiceB extends EntitySystem implements IService {
public valueB = 'B';
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Mixed')
class MixedSystem extends EntitySystem implements IService {
@InjectProperty(ServiceB)
serviceB!: ServiceB;
constructor(@Inject(ServiceA) public serviceA: ServiceA) {
super(Matcher.empty());
}
protected override onInitialize(): void {
expect(this.serviceA).toBeInstanceOf(ServiceA);
expect(this.serviceB).toBeInstanceOf(ServiceB);
expect(this.serviceA.valueA).toBe('A');
expect(this.serviceB.valueB).toBe('B');
}
override dispose() {}
}
scene.registerSystems([ServiceA, ServiceB, MixedSystem]);
});
});
});

View File

@@ -0,0 +1,109 @@
import { describe, it, expect, beforeEach } from '@jest/globals';
import { Scene, Entity, Component, EntitySystem, Matcher, ECSComponent } from '../src';
@ECSComponent('TestTransform')
class TestTransform extends Component {
constructor(public x: number = 0, public y: number = 0) {
super();
}
}
@ECSComponent('TestRenderable')
class TestRenderable extends Component {
constructor(public sprite: string = 'default') {
super();
}
}
class TestRenderSystem extends EntitySystem {
public entitiesFound: Entity[] = [];
constructor() {
super(Matcher.all(TestTransform, TestRenderable));
}
protected override process(entities: readonly Entity[]): void {
this.entitiesFound = Array.from(entities);
console.log(`TestRenderSystem.process: 找到 ${entities.length} 个实体`);
}
protected override onAdded(entity: Entity): void {
console.log(`TestRenderSystem.onAdded: 实体 ${entity.name}(${entity.id}) 被添加`);
}
}
describe('响应式查询调试', () => {
let scene: Scene;
let system: TestRenderSystem;
beforeEach(() => {
scene = new Scene();
system = new TestRenderSystem();
scene.addEntityProcessor(system);
scene.begin();
});
it('应该在实体添加组件后能被System发现', () => {
console.log('\n=== 测试开始 ===');
// 1. 创建实体(此时没有组件)
console.log('\n步骤1: 创建实体');
const entity = scene.createEntity('TestEntity');
console.log(`实体已创建: ${entity.name}(${entity.id})`);
console.log(`QuerySystem中的实体数量: ${scene.querySystem.getAllEntities().length}`);
// 2. 添加组件
console.log('\n步骤2: 添加 TestTransform 组件');
entity.addComponent(new TestTransform(100, 200));
console.log(`实体组件数量: ${entity.components.length}`);
console.log('\n步骤3: 添加 TestRenderable 组件');
entity.addComponent(new TestRenderable('test-sprite'));
console.log(`实体组件数量: ${entity.components.length}`);
// 3. 触发系统更新
console.log('\n步骤4: 更新Scene');
scene.update();
// 4. 检查System是否找到了实体
console.log(`\nSystem找到的实体数量: ${system.entitiesFound.length}`);
if (system.entitiesFound.length > 0) {
console.log(`找到的实体: ${system.entitiesFound.map(e => `${e.name}(${e.id})`).join(', ')}`);
}
// 5. 直接查询QuerySystem
console.log('\n步骤5: 直接查询QuerySystem');
const queryResult = scene.querySystem.queryAll(TestTransform, TestRenderable);
console.log(`QuerySystem.queryAll 返回: ${queryResult.entities.length} 个实体`);
console.log('\n=== 测试结束 ===\n');
expect(system.entitiesFound.length).toBe(1);
expect(system.entitiesFound[0]).toBe(entity);
expect(queryResult.entities.length).toBe(1);
expect(queryResult.entities[0]).toBe(entity);
});
it('应该测试响应式查询的内部状态', () => {
console.log('\n=== 响应式查询内部状态测试 ===');
// 创建实体并添加组件
const entity = scene.createEntity('TestEntity');
entity.addComponent(new TestTransform(100, 200));
entity.addComponent(new TestRenderable('test-sprite'));
// 获取QuerySystem的内部状态
const querySystem = scene.querySystem as any;
console.log(`\n响应式查询数量: ${querySystem._reactiveQueries.size}`);
console.log(`组件索引数量: ${querySystem._reactiveQueriesByComponent.size}`);
// 检查响应式查询
for (const [key, query] of querySystem._reactiveQueries) {
console.log(`\n查询: ${key}`);
console.log(` 实体数量: ${(query as any)._entities.length}`);
console.log(` 实体ID集合: ${Array.from((query as any)._entityIdSet).join(', ')}`);
}
console.log('\n=== 测试结束 ===\n');
});
});

View File

@@ -0,0 +1,89 @@
import { describe, it, expect } from '@jest/globals';
import { Scene, Entity, Component, EntitySystem, Matcher, ECSComponent } from '../src';
@ECSComponent('TestTransform')
class TestTransform extends Component {
constructor(public x: number = 0, public y: number = 0) {
super();
}
}
@ECSComponent('TestRenderable')
class TestRenderable extends Component {
constructor(public sprite: string = 'default') {
super();
}
}
class TestRenderSystem extends EntitySystem {
public entitiesFound: Entity[] = [];
constructor() {
super(Matcher.all(TestTransform, TestRenderable));
}
protected override process(entities: readonly Entity[]): void {
this.entitiesFound = Array.from(entities);
console.log(`TestRenderSystem.process: 找到 ${entities.length} 个实体`);
}
protected override onAdded(entity: Entity): void {
console.log(`TestRenderSystem.onAdded: 实体 ${entity.name}(${entity.id}) 被添加`);
}
}
class TestGameScene extends Scene {
private renderSystem: TestRenderSystem | null = null;
public override initialize(): void {
super.initialize();
console.log('\n=== Scene.initialize() 开始 ===');
// 1. 先添加System这是GameScene的做法
console.log('步骤1: 添加RenderSystem');
this.renderSystem = new TestRenderSystem();
this.addEntityProcessor(this.renderSystem);
// 2. 然后创建实体这是GameScene的做法
console.log('\n步骤2: 创建实体');
const entity = this.createEntity('Player');
console.log(`实体已创建: ${entity.name}(${entity.id})`);
console.log('\n步骤3: 添加组件');
entity.addComponent(new TestTransform(100, 200));
entity.addComponent(new TestRenderable('player-sprite'));
console.log(`实体组件数量: ${entity.components.length}`);
console.log('=== Scene.initialize() 结束 ===\n');
}
public getRenderSystem(): TestRenderSystem | null {
return this.renderSystem;
}
}
describe('响应式查询时序测试模拟GameScene', () => {
it('应该在Scene.initialize()中先添加System再创建实体时正常工作', () => {
console.log('\n\n========== 测试开始 ==========');
const scene = new TestGameScene();
console.log('\n调用scene.initialize()');
scene.initialize();
console.log('\n调用Scene.begin()');
scene.begin();
console.log('\n第一次Scene.update()');
scene.update();
const renderSystem = scene.getRenderSystem();
expect(renderSystem).not.toBeNull();
console.log(`\nRenderSystem找到的实体数量: ${renderSystem!.entitiesFound.length}`);
expect(renderSystem!.entitiesFound.length).toBe(1);
console.log('========== 测试结束 ==========\n\n');
});
});

View File

@@ -60,15 +60,15 @@ afterEach(() => {
const { Core } = require('../src/Core');
const { WorldManager } = require('../src/ECS/WorldManager');
// 重置 Core 和 WorldManager 单例
// 销毁 Core 和 WorldManager 单例
if (Core._instance) {
Core.reset();
Core.destroy();
}
if (WorldManager._instance) {
if (WorldManager._instance.destroy) {
WorldManager._instance.destroy();
}
WorldManager.reset();
WorldManager._instance = null;
}
} catch (error) {
// 忽略清理错误