Feature/editor optimization (#251)

* refactor: 编辑器/运行时架构拆分与构建系统升级

* feat(core): 层级系统重构与UI变换矩阵修复

* refactor: 移除 ecs-components 聚合包并修复跨包组件查找问题

* fix(physics): 修复跨包组件类引用问题

* feat: 统一运行时架构与浏览器运行支持

* feat(asset): 实现浏览器运行时资产加载系统

* fix: 修复文档、CodeQL安全问题和CI类型检查错误

* fix: 修复文档、CodeQL安全问题和CI类型检查错误

* fix: 修复文档、CodeQL安全问题、CI类型检查和测试错误

* test: 补齐核心模块测试用例,修复CI构建配置

* fix: 修复测试用例中的类型错误和断言问题

* fix: 修复 turbo build:npm 任务的依赖顺序问题

* fix: 修复 CI 构建错误并优化构建性能
This commit is contained in:
YHH
2025-12-01 22:28:51 +08:00
committed by GitHub
parent 189714c727
commit b42a7b4e43
468 changed files with 18301 additions and 9075 deletions
+1 -12
View File
@@ -69,13 +69,6 @@ export class Core {
*/
private static _logger = createLogger('Core');
/**
* 实体系统启用状态
*
* 控制是否启用ECS实体系统功能。
*/
public static entitySystemsEnabled: boolean;
/**
* 调试模式标志
*
@@ -132,7 +125,6 @@ export class Core {
// 保存配置
this._config = {
debug: true,
enableEntitySystems: true,
...config
};
@@ -176,7 +168,6 @@ export class Core {
this._pluginManager.initialize(this, this._serviceContainer);
this._serviceContainer.registerInstance(PluginManager, this._pluginManager);
Core.entitySystemsEnabled = this._config.enableEntitySystems ?? true;
this.debug = this._config.debug ?? true;
// 初始化调试管理器
@@ -266,7 +257,6 @@ export class Core {
* // 方式1:使用配置对象
* Core.create({
* debug: true,
* enableEntitySystems: true,
* debugConfig: {
* enabled: true,
* websocketUrl: 'ws://localhost:9229'
@@ -281,7 +271,7 @@ export class Core {
if (this._instance == null) {
// 向后兼容:如果传入boolean,转换为配置对象
const coreConfig: ICoreConfig = typeof config === 'boolean'
? { debug: config, enableEntitySystems: true }
? { debug: config }
: config;
this._instance = new Core(coreConfig);
} else {
@@ -614,7 +604,6 @@ export class Core {
// 核心系统初始化
Core._logger.info('Core initialized', {
debug: this.debug,
entitySystemsEnabled: Core.entitySystemsEnabled,
debugEnabled: this._config.debugConfig?.enabled || false
});
}
@@ -0,0 +1,56 @@
import { Component } from '../Component';
import { ECSComponent } from '../Decorators';
import { Serializable, Serialize } from '../Serialization/SerializationDecorators';
/**
* 层级关系组件 - 用于建立实体间的父子关系
*
* 只有需要层级关系的实体才添加此组件,遵循 ECS 组合原则。
* 层级操作应通过 HierarchySystem 进行,而非直接修改此组件。
*
* @example
* ```typescript
* // 通过 HierarchySystem 设置父子关系
* const hierarchySystem = scene.getSystem(HierarchySystem);
* hierarchySystem.setParent(childEntity, parentEntity);
*
* // 查询层级信息
* const parent = hierarchySystem.getParent(entity);
* const children = hierarchySystem.getChildren(entity);
* ```
*/
@ECSComponent('Hierarchy')
@Serializable({ version: 1, typeId: 'Hierarchy' })
export class HierarchyComponent extends Component {
/**
* 父实体 ID
* null 表示根实体(无父级)
*/
@Serialize()
public parentId: number | null = null;
/**
* 子实体 ID 列表
* 顺序即为子级的排列顺序
*/
@Serialize()
public childIds: number[] = [];
/**
* 在层级中的深度
* 根实体深度为 0,由 HierarchySystem 维护
*/
public depth: number = 0;
/**
* 层级中是否激活
* 考虑所有祖先的激活状态,由 HierarchySystem 维护
*/
public bActiveInHierarchy: boolean = true;
/**
* 层级缓存是否脏
* 用于优化缓存更新
*/
public bCacheDirty: boolean = true;
}
@@ -0,0 +1 @@
export { HierarchyComponent } from './HierarchyComponent';
@@ -2,6 +2,7 @@ import { Entity } from '../../Entity';
import { Component } from '../../Component';
import { IScene } from '../../IScene';
import { ComponentType, ComponentStorageManager } from '../ComponentStorage';
import { HierarchySystem } from '../../Systems/HierarchySystem';
/**
* 实体构建器 - 提供流式API创建和配置实体
@@ -129,7 +130,8 @@ export class EntityBuilder {
*/
public withChild(childBuilder: EntityBuilder): EntityBuilder {
const child = childBuilder.build();
this.entity.addChild(child);
const hierarchySystem = this.scene.getSystem(HierarchySystem);
hierarchySystem?.setParent(child, this.entity);
return this;
}
@@ -139,9 +141,10 @@ export class EntityBuilder {
* @returns 实体构建器
*/
public withChildren(...childBuilders: EntityBuilder[]): EntityBuilder {
const hierarchySystem = this.scene.getSystem(HierarchySystem);
for (const childBuilder of childBuilders) {
const child = childBuilder.build();
this.entity.addChild(child);
hierarchySystem?.setParent(child, this.entity);
}
return this;
}
@@ -154,7 +157,8 @@ export class EntityBuilder {
public withChildFactory(childFactory: (parent: Entity) => EntityBuilder): EntityBuilder {
const childBuilder = childFactory(this.entity);
const child = childBuilder.build();
this.entity.addChild(child);
const hierarchySystem = this.scene.getSystem(HierarchySystem);
hierarchySystem?.setParent(child, this.entity);
return this;
}
@@ -167,7 +171,8 @@ export class EntityBuilder {
public withChildIf(condition: boolean, childBuilder: EntityBuilder): EntityBuilder {
if (condition) {
const child = childBuilder.build();
this.entity.addChild(child);
const hierarchySystem = this.scene.getSystem(HierarchySystem);
hierarchySystem?.setParent(child, this.entity);
}
return this;
}
+12 -299
View File
@@ -37,12 +37,14 @@ export class EntityComparer {
*
* ECS架构中的实体(Entity),作为组件的容器。
* 实体本身不包含游戏逻辑,所有功能都通过组件来实现。
* 支持父子关系,可以构建实体层次结构。
*
* 层级关系通过 HierarchyComponent 和 HierarchySystem 管理,
* 而非 Entity 内置属性,符合 ECS 组合原则。
*
* @example
* ```typescript
* // 创建实体
* const entity = new Entity("Player", 1);
* const entity = scene.createEntity("Player");
*
* // 添加组件
* const healthComponent = entity.addComponent(new HealthComponent(100));
@@ -50,12 +52,9 @@ export class EntityComparer {
* // 获取组件
* const health = entity.getComponent(HealthComponent);
*
* // 添加位置组件
* entity.addComponent(new PositionComponent(100, 200));
*
* // 添加子实体
* const weapon = new Entity("Weapon", 2);
* entity.addChild(weapon);
* // 层级关系使用 HierarchySystem
* const hierarchySystem = scene.getSystem(HierarchySystem);
* hierarchySystem.setParent(childEntity, parentEntity);
* ```
*/
export class Entity {
@@ -89,16 +88,6 @@ export class Entity {
*/
private _isDestroyed: boolean = false;
/**
* 父实体引用
*/
private _parent: Entity | null = null;
/**
* 子实体集合
*/
private _children: Entity[] = [];
/**
* 激活状态
*/
@@ -201,32 +190,6 @@ export class Entity {
this._componentCache = components;
}
/**
* 获取父实体
* @returns 父实体,如果没有父实体则返回null
*/
public get parent(): Entity | null {
return this._parent;
}
/**
* 获取子实体数组的只读副本
*
* @returns 子实体数组的副本
*/
public get children(): readonly Entity[] {
return [...this._children];
}
/**
* 获取子实体数量
*
* @returns 子实体的数量
*/
public get childCount(): number {
return this._children.length;
}
/**
* 获取活跃状态
*
@@ -239,8 +202,6 @@ export class Entity {
/**
* 设置活跃状态
*
* 设置实体的活跃状态,会影响子实体的有效活跃状态。
*
* @param value - 新的活跃状态
*/
public set active(value: boolean) {
@@ -250,19 +211,6 @@ export class Entity {
}
}
/**
* 获取实体的有效活跃状态
*
* 考虑父实体的活跃状态,只有当实体本身和所有父实体都处于活跃状态时才返回true。
*
* @returns 有效的活跃状态
*/
public get activeInHierarchy(): boolean {
if (!this._active) return false;
if (this._parent) return this._parent.activeInHierarchy;
return true;
}
/**
* 获取实体标签
*
@@ -690,185 +638,6 @@ export class Entity {
return null;
}
/**
* 添加子实体
*
* @param child - 要添加的子实体
* @returns 添加的子实体
*/
public addChild(child: Entity): Entity {
if (child === this) {
throw new Error('Entity cannot be its own child');
}
if (child._parent === this) {
return child; // 已经是子实体
}
if (child._parent) {
child._parent.removeChild(child);
}
child._parent = this;
this._children.push(child);
if (!child.scene && this.scene) {
child.scene = this.scene;
this.scene.addEntity(child);
}
return child;
}
/**
* 移除子实体
*
* @param child - 要移除的子实体
* @returns 是否成功移除
*/
public removeChild(child: Entity): boolean {
const index = this._children.indexOf(child);
if (index === -1) {
return false;
}
this._children.splice(index, 1);
child._parent = null;
return true;
}
/**
* 移除所有子实体
*/
public removeAllChildren(): void {
const childrenToRemove = [...this._children];
for (const child of childrenToRemove) {
this.removeChild(child);
}
}
/**
* 根据名称查找子实体
*
* @param name - 子实体名称
* @param recursive - 是否递归查找
* @returns 找到的子实体或null
*/
public findChild(name: string, recursive: boolean = false): Entity | null {
for (const child of this._children) {
if (child.name === name) {
return child;
}
}
if (recursive) {
for (const child of this._children) {
const found = child.findChild(name, true);
if (found) {
return found;
}
}
}
return null;
}
/**
* 根据标签查找子实体
*
* @param tag - 标签
* @param recursive - 是否递归查找
* @returns 找到的子实体数组
*/
public findChildrenByTag(tag: number, recursive: boolean = false): Entity[] {
const result: Entity[] = [];
for (const child of this._children) {
if (child.tag === tag) {
result.push(child);
}
}
if (recursive) {
for (const child of this._children) {
result.push(...child.findChildrenByTag(tag, true));
}
}
return result;
}
/**
* 获取根实体
*
* @returns 层次结构的根实体
*/
public getRoot(): Entity {
if (!this._parent) {
return this;
}
return this._parent.getRoot();
}
/**
* 检查是否是指定实体的祖先
*
* @param entity - 要检查的实体
* @returns 如果是祖先则返回true
*/
public isAncestorOf(entity: Entity): boolean {
let current = entity._parent;
while (current) {
if (current === this) {
return true;
}
current = current._parent;
}
return false;
}
/**
* 检查是否是指定实体的后代
*
* @param entity - 要检查的实体
* @returns 如果是后代则返回true
*/
public isDescendantOf(entity: Entity): boolean {
return entity.isAncestorOf(this);
}
/**
* 获取层次深度
*
* @returns 在层次结构中的深度(根实体为0)
*/
public getDepth(): number {
let depth = 0;
let current = this._parent;
while (current) {
depth++;
current = current._parent;
}
return depth;
}
/**
* 遍历所有子实体(深度优先)
*
* @param callback - 对每个子实体执行的回调函数
* @param recursive - 是否递归遍历
*/
public forEachChild(callback: (child: Entity, index: number) => void, recursive: boolean = false): void {
this._children.forEach((child, index) => {
callback(child, index);
if (recursive) {
child.forEachChild(callback, true);
}
});
}
/**
* 活跃状态改变时的回调
*/
@@ -882,8 +651,7 @@ export class Entity {
if (this.scene && this.scene.eventSystem) {
this.scene.eventSystem.emitSync('entity:activeChanged', {
entity: this,
active: this._active,
activeInHierarchy: this.activeInHierarchy
active: this._active
});
}
}
@@ -891,7 +659,8 @@ export class Entity {
/**
* 销毁实体
*
* 移除所有组件、子实体并标记为已销毁
* 移除所有组件并标记为已销毁
* 层级关系的清理由 HierarchySystem 处理。
*/
public destroy(): void {
if (this._isDestroyed) {
@@ -905,15 +674,6 @@ export class Entity {
this.scene.referenceTracker.unregisterEntityScene(this.id);
}
const childrenToDestroy = [...this._children];
for (const child of childrenToDestroy) {
child.destroy();
}
if (this._parent) {
this._parent.removeChild(this);
}
this.removeAllComponents();
if (this.scene) {
@@ -927,43 +687,6 @@ export class Entity {
}
}
/**
* 批量销毁所有子实体
*/
public destroyAllChildren(): void {
if (this._children.length === 0) return;
const scene = this.scene;
const toDestroy: Entity[] = [];
const collectChildren = (entity: Entity) => {
for (const child of entity._children) {
toDestroy.push(child);
collectChildren(child);
}
};
collectChildren(this);
for (const entity of toDestroy) {
entity.setDestroyedState(true);
}
for (const entity of toDestroy) {
entity.removeAllComponents();
}
if (scene) {
for (const entity of toDestroy) {
scene.entities.remove(entity);
scene.querySystem.removeEntity(entity);
}
scene.clearSystemEntityCaches();
}
this._children.length = 0;
}
/**
* 比较实体
*
@@ -993,31 +716,21 @@ export class Entity {
id: number;
enabled: boolean;
active: boolean;
activeInHierarchy: boolean;
destroyed: boolean;
componentCount: number;
componentTypes: string[];
componentMask: string;
parentId: number | null;
childCount: number;
childIds: number[];
depth: number;
cacheBuilt: boolean;
} {
} {
return {
name: this.name,
id: this.id,
enabled: this._enabled,
active: this._active,
activeInHierarchy: this.activeInHierarchy,
destroyed: this._isDestroyed,
componentCount: this.components.length,
componentTypes: this.components.map((c) => getComponentInstanceTypeName(c)),
componentMask: BitMask64Utils.toString(this._componentMask, 2), // 二进制表示
parentId: this._parent?.id || null,
childCount: this._children.length,
childIds: this._children.map((c) => c.id),
depth: this.getDepth(),
componentMask: BitMask64Utils.toString(this._componentMask, 2),
cacheBuilt: this._componentCache !== null
};
}
+95
View File
@@ -0,0 +1,95 @@
/**
* 实体标签常量
*
* 用于标识特殊类型的实体,如文件夹、摄像机等。
* 使用位掩码实现,支持多标签组合。
*
* @example
* ```typescript
* // 创建文件夹实体
* entity.tag = EntityTags.FOLDER;
*
* // 检查是否是文件夹
* if ((entity.tag & EntityTags.FOLDER) !== 0) {
* // 是文件夹
* }
*
* // 组合多个标签
* entity.tag = EntityTags.FOLDER | EntityTags.HIDDEN;
* ```
*/
export const EntityTags = {
/** 无标签 */
NONE: 0x0000,
/** 文件夹实体 - 用于场景层级中的组织分类 */
FOLDER: 0x1000,
/** 隐藏实体 - 在编辑器层级中不显示 */
HIDDEN: 0x2000,
/** 锁定实体 - 在编辑器中不可选择/编辑 */
LOCKED: 0x4000,
/** 编辑器专用实体 - 仅在编辑器中存在,不导出到运行时 */
EDITOR_ONLY: 0x8000,
/** 预制件实例 */
PREFAB_INSTANCE: 0x0100,
/** 预制件根节点 */
PREFAB_ROOT: 0x0200
} as const;
export type EntityTagValue = (typeof EntityTags)[keyof typeof EntityTags];
/**
* 检查实体是否具有指定标签
*
* @param entityTag - 实体的 tag 值
* @param tag - 要检查的标签
*/
export function hasEntityTag(entityTag: number, tag: EntityTagValue): boolean {
return (entityTag & tag) !== 0;
}
/**
* 添加标签到实体
*
* @param entityTag - 当前 tag 值
* @param tag - 要添加的标签
*/
export function addEntityTag(entityTag: number, tag: EntityTagValue): number {
return entityTag | tag;
}
/**
* 从实体移除标签
*
* @param entityTag - 当前 tag 值
* @param tag - 要移除的标签
*/
export function removeEntityTag(entityTag: number, tag: EntityTagValue): number {
return entityTag & ~tag;
}
/**
* 检查实体是否是文件夹
*/
export function isFolder(entityTag: number): boolean {
return hasEntityTag(entityTag, EntityTags.FOLDER);
}
/**
* 检查实体是否隐藏
*/
export function isHidden(entityTag: number): boolean {
return hasEntityTag(entityTag, EntityTags.HIDDEN);
}
/**
* 检查实体是否锁定
*/
export function isLocked(entityTag: number): boolean {
return hasEntityTag(entityTag, EntityTags.LOCKED);
}
+52 -16
View File
@@ -21,6 +21,9 @@ import {
} from './Serialization/IncrementalSerializer';
import { ComponentPoolManager } from './Core/ComponentPool';
import { PerformanceMonitor } from '../Utils/PerformanceMonitor';
import { ProfilerSDK } from '../Utils/Profiler/ProfilerSDK';
import { ProfileCategory } from '../Utils/Profiler/ProfilerTypes';
import { AutoProfiler } from '../Utils/Profiler/AutoProfiler';
import { ServiceContainer, type ServiceType, type IService } from '../Core/ServiceContainer';
import { createInstance, isInjectable, injectProperties } from '../Core/DI';
import { createLogger } from '../Utils/Logger';
@@ -334,30 +337,58 @@ export class Scene implements IScene {
* 更新场景
*/
public update() {
ComponentPoolManager.getInstance().update();
// 开始性能采样帧
ProfilerSDK.beginFrame();
const frameHandle = ProfilerSDK.beginSample('Scene.update', ProfileCategory.ECS);
this.entities.updateLists();
try {
ComponentPoolManager.getInstance().update();
const systems = this.systems;
this.entities.updateLists();
for (const system of systems) {
if (system.enabled) {
try {
system.update();
} catch (error) {
this._handleSystemError(system, 'update', error);
const systems = this.systems;
// Update 阶段
const updateHandle = ProfilerSDK.beginSample('Systems.update', ProfileCategory.ECS);
try {
for (const system of systems) {
if (system.enabled) {
const systemHandle = ProfilerSDK.beginSample(system.systemName, ProfileCategory.ECS);
try {
system.update();
} catch (error) {
this._handleSystemError(system, 'update', error);
} finally {
ProfilerSDK.endSample(systemHandle);
}
}
}
} finally {
ProfilerSDK.endSample(updateHandle);
}
}
for (const system of systems) {
if (system.enabled) {
try {
system.lateUpdate();
} catch (error) {
this._handleSystemError(system, 'lateUpdate', error);
// LateUpdate 阶段
const lateUpdateHandle = ProfilerSDK.beginSample('Systems.lateUpdate', ProfileCategory.ECS);
try {
for (const system of systems) {
if (system.enabled) {
const systemHandle = ProfilerSDK.beginSample(`${system.systemName}.late`, ProfileCategory.ECS);
try {
system.lateUpdate();
} catch (error) {
this._handleSystemError(system, 'lateUpdate', error);
} finally {
ProfilerSDK.endSample(systemHandle);
}
}
}
} finally {
ProfilerSDK.endSample(lateUpdateHandle);
}
} finally {
ProfilerSDK.endSample(frameHandle);
// 结束性能采样帧
ProfilerSDK.endFrame();
}
}
@@ -693,6 +724,11 @@ export class Scene implements IScene {
injectProperties(system, this._services);
// 调试模式下自动包装系统方法以收集性能数据(ProfilerSDK 启用时表示调试模式)
if (ProfilerSDK.isEnabled()) {
AutoProfiler.wrapInstance(system, system.systemName, ProfileCategory.ECS);
}
system.initialize();
this.logger.debug(`System ${constructor.name} registered and initialized`);
@@ -8,6 +8,8 @@ import { Entity } from '../Entity';
import { ComponentType } from '../Core/ComponentStorage';
import { ComponentSerializer, SerializedComponent } from './ComponentSerializer';
import { IScene } from '../IScene';
import { HierarchyComponent } from '../Components/HierarchyComponent';
import { HierarchySystem } from '../Systems/HierarchySystem';
/**
* 序列化后的实体数据
@@ -68,9 +70,14 @@ export class EntitySerializer {
*
* @param entity 要序列化的实体
* @param includeChildren 是否包含子实体(默认true)
* @param hierarchySystem 层级系统(可选,用于获取层级信息)
* @returns 序列化后的实体数据
*/
public static serialize(entity: Entity, includeChildren: boolean = true): SerializedEntity {
public static serialize(
entity: Entity,
includeChildren: boolean = true,
hierarchySystem?: HierarchySystem
): SerializedEntity {
const serializedComponents = ComponentSerializer.serializeComponents(
Array.from(entity.components)
);
@@ -86,15 +93,24 @@ export class EntitySerializer {
children: []
};
// 序列化父实体引用
if (entity.parent) {
serializedEntity.parentId = entity.parent.id;
// 通过 HierarchyComponent 获取层级信息
const hierarchy = entity.getComponent(HierarchyComponent);
if (hierarchy?.parentId !== null && hierarchy?.parentId !== undefined) {
serializedEntity.parentId = hierarchy.parentId;
}
// 序列化子实体
if (includeChildren) {
for (const child of entity.children) {
serializedEntity.children.push(this.serialize(child, true));
// 直接使用 HierarchyComponent.childIds 获取子实体
if (includeChildren && hierarchy && hierarchy.childIds.length > 0) {
// 获取场景引用:优先从 hierarchySystem,否则从 entity.scene
const scene = hierarchySystem?.scene ?? entity.scene;
if (scene) {
for (const childId of hierarchy.childIds) {
const child = scene.findEntityById(childId);
if (child) {
serializedEntity.children.push(this.serialize(child, true, hierarchySystem));
}
}
}
}
@@ -109,6 +125,7 @@ export class EntitySerializer {
* @param idGenerator 实体ID生成器(用于生成新ID或保持原ID)
* @param preserveIds 是否保持原始ID(默认false
* @param scene 目标场景(可选,用于设置entity.scene以支持添加组件)
* @param hierarchySystem 层级系统(可选,用于建立层级关系)
* @returns 反序列化后的实体
*/
public static deserialize(
@@ -116,12 +133,17 @@ export class EntitySerializer {
componentRegistry: Map<string, ComponentType>,
idGenerator: () => number,
preserveIds: boolean = false,
scene?: IScene
scene?: IScene,
hierarchySystem?: HierarchySystem | null,
allEntities?: Map<number, Entity>
): Entity {
// 创建实体(使用原始ID或新生成的ID)
const entityId = preserveIds ? serializedEntity.id : idGenerator();
const entity = new Entity(serializedEntity.name, entityId);
// 将实体添加到收集 Map 中(用于后续添加到场景)
allEntities?.set(entity.id, entity);
// 如果提供了scene,先设置entity.scene以支持添加组件
if (scene) {
entity.scene = scene;
@@ -143,16 +165,28 @@ export class EntitySerializer {
entity.addComponent(component);
}
// 反序列化子实体
// 重要:清除 HierarchyComponent 中的旧 ID
// 当 preserveIds=false 时,序列化的 parentId 和 childIds 是旧 ID,需要重新建立
// 通过 hierarchySystem.setParent 会正确设置新的 ID
const hierarchy = entity.getComponent(HierarchyComponent);
if (hierarchy) {
hierarchy.parentId = null;
hierarchy.childIds = [];
}
// 反序列化子实体并建立层级关系
for (const childData of serializedEntity.children) {
const childEntity = this.deserialize(
childData,
componentRegistry,
idGenerator,
preserveIds,
scene
scene,
hierarchySystem,
allEntities
);
entity.addChild(childEntity);
// 使用 HierarchySystem 建立层级关系
hierarchySystem?.setParent(childEntity, entity);
}
return entity;
@@ -163,19 +197,23 @@ export class EntitySerializer {
*
* @param entities 实体数组
* @param includeChildren 是否包含子实体
* @param hierarchySystem 层级系统(可选,用于获取层级信息)
* @returns 序列化后的实体数据数组
*/
public static serializeEntities(
entities: Entity[],
includeChildren: boolean = true
includeChildren: boolean = true,
hierarchySystem?: HierarchySystem
): SerializedEntity[] {
const result: SerializedEntity[] = [];
for (const entity of entities) {
// 只序列化顶层实体(没有父实体的实体)
// 子实体会在父实体序列化时一并处理
if (!entity.parent || !includeChildren) {
result.push(this.serialize(entity, includeChildren));
const hierarchy = entity.getComponent(HierarchyComponent);
const bHasParent = hierarchy?.parentId !== null && hierarchy?.parentId !== undefined;
if (!bHasParent || !includeChildren) {
result.push(this.serialize(entity, includeChildren, hierarchySystem));
}
}
@@ -190,6 +228,7 @@ export class EntitySerializer {
* @param idGenerator 实体ID生成器
* @param preserveIds 是否保持原始ID
* @param scene 目标场景(可选,用于设置entity.scene以支持添加组件)
* @param hierarchySystem 层级系统(可选,用于建立层级关系)
* @returns 反序列化后的实体数组
*/
public static deserializeEntities(
@@ -197,9 +236,11 @@ export class EntitySerializer {
componentRegistry: Map<string, ComponentType>,
idGenerator: () => number,
preserveIds: boolean = false,
scene?: IScene
): Entity[] {
const result: Entity[] = [];
scene?: IScene,
hierarchySystem?: HierarchySystem | null
): { rootEntities: Entity[]; allEntities: Map<number, Entity> } {
const rootEntities: Entity[] = [];
const allEntities = new Map<number, Entity>();
for (const serialized of serializedEntities) {
const entity = this.deserialize(
@@ -207,12 +248,14 @@ export class EntitySerializer {
componentRegistry,
idGenerator,
preserveIds,
scene
scene,
hierarchySystem,
allEntities
);
result.push(entity);
rootEntities.push(entity);
}
return result;
return { rootEntities, allEntities };
}
/**
@@ -11,6 +11,8 @@ import { ComponentSerializer, SerializedComponent } from './ComponentSerializer'
import { SerializedEntity } from './EntitySerializer';
import { ComponentType } from '../Core/ComponentStorage';
import { BinarySerializer } from '../../Utils/BinarySerializer';
import { HierarchyComponent } from '../Components/HierarchyComponent';
import { HierarchySystem } from '../Systems/HierarchySystem';
/**
* 变更操作类型
@@ -196,6 +198,10 @@ export class IncrementalSerializer {
for (const entity of scene.entities.buffer) {
snapshot.entityIds.add(entity.id);
// 获取层级信息
const hierarchy = entity.getComponent(HierarchyComponent);
const parentId = hierarchy?.parentId;
// 存储实体基本信息
snapshot.entities.set(entity.id, {
name: entity.name,
@@ -203,7 +209,7 @@ export class IncrementalSerializer {
active: entity.active,
enabled: entity.enabled,
updateOrder: entity.updateOrder,
...(entity.parent && { parentId: entity.parent.id })
...(parentId !== null && parentId !== undefined && { parentId })
});
// 快照组件
@@ -272,6 +278,10 @@ export class IncrementalSerializer {
for (const entity of scene.entities.buffer) {
currentEntityIds.add(entity.id);
// 获取层级信息
const hierarchy = entity.getComponent(HierarchyComponent);
const parentId = hierarchy?.parentId;
if (!baseSnapshot.entityIds.has(entity.id)) {
// 新增实体
incremental.entityChanges.push({
@@ -285,7 +295,7 @@ export class IncrementalSerializer {
active: entity.active,
enabled: entity.enabled,
updateOrder: entity.updateOrder,
...(entity.parent && { parentId: entity.parent.id }),
...(parentId !== null && parentId !== undefined && { parentId }),
components: [],
children: []
}
@@ -312,7 +322,7 @@ export class IncrementalSerializer {
oldData.active !== entity.active ||
oldData.enabled !== entity.enabled ||
oldData.updateOrder !== entity.updateOrder ||
oldData.parentId !== entity.parent?.id;
oldData.parentId !== parentId;
if (entityChanged) {
incremental.entityChanges.push({
@@ -324,7 +334,7 @@ export class IncrementalSerializer {
active: entity.active,
enabled: entity.enabled,
updateOrder: entity.updateOrder,
...(entity.parent && { parentId: entity.parent.id })
...(parentId !== null && parentId !== undefined && { parentId })
}
});
}
@@ -539,16 +549,20 @@ export class IncrementalSerializer {
if (change.entityData.enabled !== undefined) entity.enabled = change.entityData.enabled;
if (change.entityData.updateOrder !== undefined) entity.updateOrder = change.entityData.updateOrder;
if (change.entityData.parentId !== undefined) {
const newParent = scene.entities.findEntityById(change.entityData.parentId);
if (newParent && entity.parent !== newParent) {
if (entity.parent) {
entity.parent.removeChild(entity);
// 使用 HierarchySystem 更新层级关系
const hierarchySystem = scene.getSystem(HierarchySystem);
if (hierarchySystem) {
const hierarchy = entity.getComponent(HierarchyComponent);
const currentParentId = hierarchy?.parentId;
if (change.entityData.parentId !== undefined) {
const newParent = scene.entities.findEntityById(change.entityData.parentId);
if (newParent && currentParentId !== change.entityData.parentId) {
hierarchySystem.setParent(entity, newParent);
}
newParent.addChild(entity);
} else if (currentParentId !== null && currentParentId !== undefined) {
hierarchySystem.setParent(entity, null);
}
} else if (entity.parent) {
entity.parent.removeChild(entity);
}
}
@@ -11,6 +11,8 @@ import { EntitySerializer, SerializedEntity } from './EntitySerializer';
import { getComponentTypeName } from '../Decorators';
import { getSerializationMetadata } from './SerializationDecorators';
import { BinarySerializer } from '../../Utils/BinarySerializer';
import { HierarchySystem } from '../Systems/HierarchySystem';
import { HierarchyComponent } from '../Components/HierarchyComponent';
/**
* 场景序列化格式
@@ -167,8 +169,11 @@ export class SceneSerializer {
// 过滤实体和组件
const entities = this.filterEntities(scene, opts);
// 序列化实体
const serializedEntities = EntitySerializer.serializeEntities(entities, true);
// 获取层级系统用于序列化实体
const hierarchySystem = scene.getSystem(HierarchySystem);
// 序列化实体(传入 hierarchySystem 以正确序列化子实体)
const serializedEntities = EntitySerializer.serializeEntities(entities, true, hierarchySystem ?? undefined);
// 收集组件类型信息
const componentTypeRegistry = this.buildComponentTypeRegistry(entities);
@@ -258,19 +263,24 @@ export class SceneSerializer {
// ID生成器
const idGenerator = () => scene.identifierPool.checkOut();
// 获取层级系统
const hierarchySystem = scene.getSystem(HierarchySystem);
// 反序列化实体
const entities = EntitySerializer.deserializeEntities(
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
serializedScene.entities,
componentRegistry,
idGenerator,
opts.preserveIds || false,
scene
scene,
hierarchySystem
);
// 将实体添加到场景
for (const entity of entities) {
// 将所有实体添加到场景(包括子实体)
// 先添加根实体,再递归添加子实体
for (const entity of rootEntities) {
scene.addEntity(entity, true);
this.addChildrenRecursively(entity, scene);
this.addChildrenRecursively(entity, scene, hierarchySystem, allEntities);
}
// 统一清理缓存(批量操作完成后)
@@ -285,8 +295,8 @@ export class SceneSerializer {
// 调用所有组件的 onDeserialized 生命周期方法
// Call onDeserialized lifecycle method on all components
const deserializedPromises: Promise<void>[] = [];
for (const entity of entities) {
this.callOnDeserializedRecursively(entity, deserializedPromises);
for (const entity of allEntities.values()) {
this.callOnDeserializedForEntity(entity, deserializedPromises);
}
// 如果有异步的 onDeserialized,在后台执行
@@ -298,9 +308,12 @@ export class SceneSerializer {
}
/**
* 递归调用实体及其子实体所有组件的 onDeserialized 方法
* 调用实体所有组件的 onDeserialized 方法(不递归)
*/
private static callOnDeserializedRecursively(entity: Entity, promises: Promise<void>[]): void {
private static callOnDeserializedForEntity(
entity: Entity,
promises: Promise<void>[]
): void {
for (const component of entity.components) {
try {
const result = component.onDeserialized();
@@ -311,10 +324,6 @@ export class SceneSerializer {
console.error(`Error calling onDeserialized on component ${component.constructor.name}:`, error);
}
}
for (const child of entity.children) {
this.callOnDeserializedRecursively(child, promises);
}
}
/**
@@ -327,11 +336,27 @@ export class SceneSerializer {
*
* @param entity 父实体
* @param scene 目标场景
* @param hierarchySystem 层级系统
*/
private static addChildrenRecursively(entity: Entity, scene: IScene): void {
for (const child of entity.children) {
scene.addEntity(child, true); // 延迟缓存清理
this.addChildrenRecursively(child, scene); // 递归处理子实体的子实体
private static addChildrenRecursively(
entity: Entity,
scene: IScene,
hierarchySystem?: HierarchySystem | null,
childEntitiesMap?: Map<number, Entity>
): void {
const hierarchy = entity.getComponent(HierarchyComponent);
if (!hierarchy || hierarchy.childIds.length === 0) return;
// 获取子实体
// 注意:此时子实体还没有被添加到场景,所以不能用 scene.findEntityById
// 需要从 childEntitiesMap 中查找(如果提供了的话)
for (const childId of hierarchy.childIds) {
// 尝试从 map 中获取,否则从场景获取(用于已添加的情况)
const child = childEntitiesMap?.get(childId) ?? scene.findEntityById(childId);
if (child) {
scene.addEntity(child, true); // 延迟缓存清理
this.addChildrenRecursively(child, scene, hierarchySystem, childEntitiesMap);
}
}
}
@@ -0,0 +1,549 @@
import { Entity } from '../Entity';
import { EntitySystem } from './EntitySystem';
import { Matcher } from '../Utils/Matcher';
import { HierarchyComponent } from '../Components/HierarchyComponent';
/**
* 层级关系系统 - 管理实体间的父子关系
*
* 提供层级操作的统一 API,维护层级缓存(depth、activeInHierarchy)。
* 所有层级操作应通过此系统进行,而非直接修改 HierarchyComponent。
*
* @example
* ```typescript
* const hierarchySystem = scene.getSystem(HierarchySystem);
*
* // 设置父子关系
* hierarchySystem.setParent(child, parent);
*
* // 查询层级
* const parent = hierarchySystem.getParent(entity);
* const children = hierarchySystem.getChildren(entity);
* const depth = hierarchySystem.getDepth(entity);
* ```
*/
export class HierarchySystem extends EntitySystem {
private static readonly MAX_DEPTH = 32;
constructor() {
super(Matcher.empty().all(HierarchyComponent));
}
/**
* 系统优先级,确保在其他系统之前更新层级缓存
*/
public override get updateOrder(): number {
return -1000;
}
protected override process(): void {
// 更新所有脏缓存
for (const entity of this.entities) {
const hierarchy = entity.getComponent(HierarchyComponent);
if (hierarchy?.bCacheDirty) {
this.updateHierarchyCache(entity);
}
}
}
/**
* 设置实体的父级
*
* @param child - 子实体
* @param parent - 父实体,null 表示移动到根级
*/
public setParent(child: Entity, parent: Entity | null): void {
let childHierarchy = child.getComponent(HierarchyComponent);
// 如果子实体没有 HierarchyComponent,自动添加
if (!childHierarchy) {
childHierarchy = new HierarchyComponent();
child.addComponent(childHierarchy);
}
// 检查是否需要变更
const currentParentId = childHierarchy.parentId;
const newParentId = parent?.id ?? null;
if (currentParentId === newParentId) {
return;
}
// 防止循环引用
if (parent && this.isAncestorOf(child, parent)) {
throw new Error('Cannot set parent: would create circular reference');
}
// 从旧父级移除
if (currentParentId !== null) {
const oldParent = this.scene?.findEntityById(currentParentId);
if (oldParent) {
const oldParentHierarchy = oldParent.getComponent(HierarchyComponent);
if (oldParentHierarchy) {
const idx = oldParentHierarchy.childIds.indexOf(child.id);
if (idx !== -1) {
oldParentHierarchy.childIds.splice(idx, 1);
}
}
}
}
// 添加到新父级
if (parent) {
let parentHierarchy = parent.getComponent(HierarchyComponent);
if (!parentHierarchy) {
parentHierarchy = new HierarchyComponent();
parent.addComponent(parentHierarchy);
}
childHierarchy.parentId = parent.id;
parentHierarchy.childIds.push(child.id);
} else {
childHierarchy.parentId = null;
}
// 标记缓存脏
this.markCacheDirty(child);
}
/**
* 在指定位置插入子实体
*
* @param parent - 父实体
* @param child - 子实体
* @param index - 插入位置索引,-1 表示追加到末尾
*/
public insertChildAt(parent: Entity, child: Entity, index: number): void {
let childHierarchy = child.getComponent(HierarchyComponent);
let parentHierarchy = parent.getComponent(HierarchyComponent);
// 自动添加 HierarchyComponent
if (!childHierarchy) {
childHierarchy = new HierarchyComponent();
child.addComponent(childHierarchy);
}
if (!parentHierarchy) {
parentHierarchy = new HierarchyComponent();
parent.addComponent(parentHierarchy);
}
// 防止循环引用
if (this.isAncestorOf(child, parent)) {
throw new Error('Cannot set parent: would create circular reference');
}
// 从旧父级移除
if (childHierarchy.parentId !== null && childHierarchy.parentId !== parent.id) {
const oldParent = this.scene?.findEntityById(childHierarchy.parentId);
if (oldParent) {
const oldParentHierarchy = oldParent.getComponent(HierarchyComponent);
if (oldParentHierarchy) {
const idx = oldParentHierarchy.childIds.indexOf(child.id);
if (idx !== -1) {
oldParentHierarchy.childIds.splice(idx, 1);
}
}
}
}
// 设置新父级
childHierarchy.parentId = parent.id;
// 从当前父级的子列表中移除(如果已存在)
const existingIdx = parentHierarchy.childIds.indexOf(child.id);
if (existingIdx !== -1) {
parentHierarchy.childIds.splice(existingIdx, 1);
}
// 插入到指定位置
if (index < 0 || index >= parentHierarchy.childIds.length) {
parentHierarchy.childIds.push(child.id);
} else {
parentHierarchy.childIds.splice(index, 0, child.id);
}
// 标记缓存脏
this.markCacheDirty(child);
}
/**
* 移除子实体(将其移动到根级)
*/
public removeChild(parent: Entity, child: Entity): boolean {
const parentHierarchy = parent.getComponent(HierarchyComponent);
const childHierarchy = child.getComponent(HierarchyComponent);
if (!parentHierarchy || !childHierarchy) {
return false;
}
if (childHierarchy.parentId !== parent.id) {
return false;
}
const idx = parentHierarchy.childIds.indexOf(child.id);
if (idx !== -1) {
parentHierarchy.childIds.splice(idx, 1);
}
childHierarchy.parentId = null;
this.markCacheDirty(child);
return true;
}
/**
* 移除所有子实体
*/
public removeAllChildren(parent: Entity): void {
const parentHierarchy = parent.getComponent(HierarchyComponent);
if (!parentHierarchy) return;
const childIds = [...parentHierarchy.childIds];
for (const childId of childIds) {
const child = this.scene?.findEntityById(childId);
if (child) {
this.removeChild(parent, child);
}
}
}
/**
* 获取实体的父级
*/
public getParent(entity: Entity): Entity | null {
const hierarchy = entity.getComponent(HierarchyComponent);
if (!hierarchy || hierarchy.parentId === null) {
return null;
}
return this.scene?.findEntityById(hierarchy.parentId) ?? null;
}
/**
* 获取实体的子级列表
*/
public getChildren(entity: Entity): Entity[] {
const hierarchy = entity.getComponent(HierarchyComponent);
if (!hierarchy) return [];
const children: Entity[] = [];
for (const childId of hierarchy.childIds) {
const child = this.scene?.findEntityById(childId);
if (child) {
children.push(child);
}
}
return children;
}
/**
* 获取子级数量
*/
public getChildCount(entity: Entity): number {
const hierarchy = entity.getComponent(HierarchyComponent);
return hierarchy?.childIds.length ?? 0;
}
/**
* 检查实体是否有子级
*/
public hasChildren(entity: Entity): boolean {
return this.getChildCount(entity) > 0;
}
/**
* 检查 ancestor 是否是 entity 的祖先
*/
public isAncestorOf(ancestor: Entity, entity: Entity): boolean {
let current = this.getParent(entity);
let depth = 0;
while (current && depth < HierarchySystem.MAX_DEPTH) {
if (current.id === ancestor.id) {
return true;
}
current = this.getParent(current);
depth++;
}
return false;
}
/**
* 检查 descendant 是否是 entity 的后代
*/
public isDescendantOf(descendant: Entity, entity: Entity): boolean {
return this.isAncestorOf(entity, descendant);
}
/**
* 获取根实体
*/
public getRoot(entity: Entity): Entity {
let current = entity;
let parent = this.getParent(current);
let depth = 0;
while (parent && depth < HierarchySystem.MAX_DEPTH) {
current = parent;
parent = this.getParent(current);
depth++;
}
return current;
}
/**
* 获取实体在层级中的深度
*/
public getDepth(entity: Entity): number {
const hierarchy = entity.getComponent(HierarchyComponent);
if (!hierarchy) return 0;
// 如果缓存有效,直接返回
if (!hierarchy.bCacheDirty) {
return hierarchy.depth;
}
// 重新计算
let depth = 0;
let current = this.getParent(entity);
while (current && depth < HierarchySystem.MAX_DEPTH) {
depth++;
current = this.getParent(current);
}
hierarchy.depth = depth;
return depth;
}
/**
* 检查实体在层级中是否激活
*/
public isActiveInHierarchy(entity: Entity): boolean {
if (!entity.active) return false;
const hierarchy = entity.getComponent(HierarchyComponent);
if (!hierarchy) return entity.active;
// 如果缓存有效,直接返回
if (!hierarchy.bCacheDirty) {
return hierarchy.bActiveInHierarchy;
}
// 重新计算
const parent = this.getParent(entity);
if (!parent) {
hierarchy.bActiveInHierarchy = entity.active;
} else {
hierarchy.bActiveInHierarchy = entity.active && this.isActiveInHierarchy(parent);
}
return hierarchy.bActiveInHierarchy;
}
/**
* 获取所有根实体(没有父级的实体)
*/
public getRootEntities(): Entity[] {
const roots: Entity[] = [];
for (const entity of this.entities) {
const hierarchy = entity.getComponent(HierarchyComponent);
if (hierarchy && hierarchy.parentId === null) {
roots.push(entity);
}
}
return roots;
}
/**
* 根据名称查找子实体
*
* @param entity - 父实体
* @param name - 子实体名称
* @param bRecursive - 是否递归查找
*/
public findChild(entity: Entity, name: string, bRecursive: boolean = false): Entity | null {
const children = this.getChildren(entity);
for (const child of children) {
if (child.name === name) {
return child;
}
}
if (bRecursive) {
for (const child of children) {
const found = this.findChild(child, name, true);
if (found) {
return found;
}
}
}
return null;
}
/**
* 根据标签查找子实体
*
* @param entity - 父实体
* @param tag - 标签值
* @param bRecursive - 是否递归查找
*/
public findChildrenByTag(entity: Entity, tag: number, bRecursive: boolean = false): Entity[] {
const result: Entity[] = [];
const children = this.getChildren(entity);
for (const child of children) {
if ((child.tag & tag) !== 0) {
result.push(child);
}
if (bRecursive) {
result.push(...this.findChildrenByTag(child, tag, true));
}
}
return result;
}
/**
* 遍历所有子级
*
* @param entity - 父实体
* @param callback - 回调函数
* @param bRecursive - 是否递归遍历
*/
public forEachChild(
entity: Entity,
callback: (child: Entity) => void,
bRecursive: boolean = false
): void {
const children = this.getChildren(entity);
for (const child of children) {
callback(child);
if (bRecursive) {
this.forEachChild(child, callback, true);
}
}
}
/**
* 扁平化层级树(用于虚拟化渲染)
*
* @param expandedIds - 展开的实体 ID 集合
* @returns 扁平化的节点列表
*/
public flattenHierarchy(expandedIds: Set<number>): Array<{
entity: Entity;
depth: number;
bHasChildren: boolean;
bIsExpanded: boolean;
}> {
const result: Array<{
entity: Entity;
depth: number;
bHasChildren: boolean;
bIsExpanded: boolean;
}> = [];
const traverse = (entity: Entity, depth: number): void => {
const bHasChildren = this.hasChildren(entity);
const bIsExpanded = expandedIds.has(entity.id);
result.push({
entity,
depth,
bHasChildren,
bIsExpanded
});
if (bHasChildren && bIsExpanded) {
for (const child of this.getChildren(entity)) {
traverse(child, depth + 1);
}
}
};
for (const root of this.getRootEntities()) {
traverse(root, 0);
}
return result;
}
/**
* 标记缓存为脏
*/
private markCacheDirty(entity: Entity): void {
const hierarchy = entity.getComponent(HierarchyComponent);
if (!hierarchy) return;
hierarchy.bCacheDirty = true;
// 递归标记所有子级
for (const childId of hierarchy.childIds) {
const child = this.scene?.findEntityById(childId);
if (child) {
this.markCacheDirty(child);
}
}
}
/**
* 更新层级缓存
*/
private updateHierarchyCache(entity: Entity): void {
const hierarchy = entity.getComponent(HierarchyComponent);
if (!hierarchy) return;
// 计算深度
hierarchy.depth = this.getDepth(entity);
// 计算激活状态
hierarchy.bActiveInHierarchy = this.isActiveInHierarchy(entity);
// 标记缓存有效
hierarchy.bCacheDirty = false;
}
/**
* 当实体被移除时清理层级关系
*/
protected onEntityRemoved(entity: Entity): void {
const hierarchy = entity.getComponent(HierarchyComponent);
if (!hierarchy) return;
// 从父级移除
if (hierarchy.parentId !== null) {
const parent = this.scene?.findEntityById(hierarchy.parentId);
if (parent) {
const parentHierarchy = parent.getComponent(HierarchyComponent);
if (parentHierarchy) {
const idx = parentHierarchy.childIds.indexOf(entity.id);
if (idx !== -1) {
parentHierarchy.childIds.splice(idx, 1);
}
}
}
}
// 处理子级:可选择销毁或移动到根级
// 默认将子级移动到根级
for (const childId of hierarchy.childIds) {
const child = this.scene?.findEntityById(childId);
if (child) {
const childHierarchy = child.getComponent(HierarchyComponent);
if (childHierarchy) {
childHierarchy.parentId = null;
this.markCacheDirty(child);
}
}
}
}
public override dispose(): void {
// 清理资源
}
}
+1
View File
@@ -4,6 +4,7 @@ export { ProcessingSystem } from './ProcessingSystem';
export { PassiveSystem } from './PassiveSystem';
export { IntervalSystem } from './IntervalSystem';
export { WorkerEntitySystem } from './WorkerEntitySystem';
export { HierarchySystem } from './HierarchySystem';
// Worker系统相关类型导出
export type {
+3 -1
View File
@@ -8,6 +8,7 @@ import { Entity } from './Entity';
import type { Component } from './Component';
import type { ComponentType } from './Core/ComponentStorage';
import type { ComponentConstructor, ComponentInstance } from '../Types/TypeHelpers';
import { HierarchySystem } from './Systems/HierarchySystem';
/**
* 获取组件,如果不存在则抛出错误
@@ -277,7 +278,8 @@ export class TypedEntityBuilder {
* 添加子实体
*/
withChild(child: Entity): this {
this._entity.addChild(child);
const hierarchySystem = this._entity.scene?.getSystem(HierarchySystem);
hierarchySystem?.setParent(child, this._entity);
return this;
}
+2
View File
@@ -4,6 +4,7 @@ export { ECSEventType, EventPriority, EVENT_TYPES, EventTypeValidator } from './
export * from './Systems';
export * from './Utils';
export * from './Decorators';
export * from './Components';
export { Scene } from './Scene';
export { IScene, ISceneFactory, ISceneConfig } from './IScene';
export { SceneManager } from './SceneManager';
@@ -18,3 +19,4 @@ export { ReferenceTracker, getSceneByEntityId } from './Core/ReferenceTracker';
export type { EntityRefRecord } from './Core/ReferenceTracker';
export { ReactiveQuery, ReactiveQueryChangeType } from './Core/ReactiveQuery';
export type { ReactiveQueryChange, ReactiveQueryListener, ReactiveQueryConfig } from './Core/ReactiveQuery';
export * from './EntityTags';
-2
View File
@@ -264,8 +264,6 @@ export interface IECSDebugConfig {
export interface ICoreConfig {
/** 是否启用调试模式 */
debug?: boolean;
/** 是否启用实体系统 */
enableEntitySystems?: boolean;
/** 调试配置 */
debugConfig?: IECSDebugConfig;
/** WorldManager配置 */
@@ -30,6 +30,24 @@ export interface ILegacyPerformanceMonitor {
}>;
}
/**
* 热点函数项(支持递归层级)
*/
export interface IHotspotItem {
name: string;
category: string;
inclusiveTime: number;
inclusiveTimePercent: number;
exclusiveTime: number;
exclusiveTimePercent: number;
callCount: number;
avgCallTime: number;
/** 层级深度 */
depth: number;
/** 子函数 */
children?: IHotspotItem[] | undefined;
}
/**
* 高级性能数据接口
*/
@@ -63,17 +81,8 @@ export interface IAdvancedProfilerData {
percentOfFrame: number;
}>;
}>;
/** 热点函数列表 */
hotspots: Array<{
name: string;
category: string;
inclusiveTime: number;
inclusiveTimePercent: number;
exclusiveTime: number;
exclusiveTimePercent: number;
callCount: number;
avgCallTime: number;
}>;
/** 热点函数列表(支持层级) */
hotspots: IHotspotItem[];
/** 调用关系数据 */
callGraph: {
/** 当前选中的函数 */
@@ -332,16 +341,91 @@ export class AdvancedProfilerCollector {
private buildHotspots(report: ProfileReport): IAdvancedProfilerData['hotspots'] {
const totalTime = report.hotspots.reduce((sum, h) => sum + h.inclusiveTime, 0) || 1;
return report.hotspots.slice(0, 50).map(h => ({
name: h.name,
category: h.category,
inclusiveTime: h.inclusiveTime,
inclusiveTimePercent: (h.inclusiveTime / totalTime) * 100,
exclusiveTime: h.exclusiveTime,
exclusiveTimePercent: (h.exclusiveTime / totalTime) * 100,
callCount: h.callCount,
avgCallTime: h.averageTime
}));
// 使用 callGraph 构建层级结构
// 找出所有根节点(没有被任何函数调用的,或者是顶层函数)
const rootFunctions = new Set<string>();
const childFunctions = new Set<string>();
for (const [name, node] of report.callGraph) {
// 如果没有调用者,或者调用者不在 hotspots 中,则是根节点
if (node.callers.size === 0) {
rootFunctions.add(name);
} else {
// 检查是否所有调用者都在 hotspots 之外
let hasParentInHotspots = false;
for (const callerName of node.callers.keys()) {
if (report.callGraph.has(callerName)) {
hasParentInHotspots = true;
childFunctions.add(name);
break;
}
}
if (!hasParentInHotspots) {
rootFunctions.add(name);
}
}
}
// 递归构建层级热点数据
const buildHotspotItem = (
name: string,
depth: number,
visited: Set<string>
): IHotspotItem | null => {
if (visited.has(name)) return null; // 避免循环
visited.add(name);
const stats = report.hotspots.find(h => h.name === name);
const node = report.callGraph.get(name);
if (!stats && !node) return null;
const inclusiveTime = stats?.inclusiveTime || node?.totalTime || 0;
const exclusiveTime = stats?.exclusiveTime || inclusiveTime;
const callCount = stats?.callCount || node?.callCount || 1;
// 构建子节点
const children: IHotspotItem[] = [];
if (node && depth < 5) { // 限制深度避免过深
for (const [calleeName] of node.callees) {
const child = buildHotspotItem(calleeName, depth + 1, visited);
if (child) {
children.push(child);
}
}
// 按耗时排序
children.sort((a, b) => b.inclusiveTime - a.inclusiveTime);
}
return {
name,
category: stats?.category || node?.category || ProfileCategory.Custom,
inclusiveTime,
inclusiveTimePercent: (inclusiveTime / totalTime) * 100,
exclusiveTime,
exclusiveTimePercent: (exclusiveTime / totalTime) * 100,
callCount,
avgCallTime: callCount > 0 ? inclusiveTime / callCount : 0,
depth,
children: children.length > 0 ? children : undefined
};
};
// 构建根节点列表
const result: IAdvancedProfilerData['hotspots'] = [];
const visited = new Set<string>();
for (const rootName of rootFunctions) {
const item = buildHotspotItem(rootName, 0, visited);
if (item) {
result.push(item);
}
}
// 按耗时排序
result.sort((a, b) => b.inclusiveTime - a.inclusiveTime);
return result.slice(0, 50);
}
private buildHotspotsFromLegacy(
@@ -363,7 +447,8 @@ export class AdvancedProfilerCollector {
exclusiveTime: execTime,
exclusiveTimePercent: frameTime > 0 ? (execTime / frameTime) * 100 : 0,
callCount: stats?.executionCount || 1,
avgCallTime: stats?.averageTime || execTime
avgCallTime: stats?.averageTime || execTime,
depth: 0
});
}
@@ -388,15 +473,27 @@ export class AdvancedProfilerCollector {
};
}
// 计算所有调用者的总调用次数(用于计算调用者的百分比)
let totalCallerCount = 0;
for (const data of node.callers.values()) {
totalCallerCount += data.count;
}
// Calling Functions(谁调用了我)
// - totalTime: 该调用者调用当前函数时的平均耗时
// - percentOfCurrent: 该调用者的调用次数占总调用次数的百分比
const callers = Array.from(node.callers.entries())
.map(([name, data]) => ({
name,
callCount: data.count,
totalTime: data.totalTime,
percentOfCurrent: node.totalTime > 0 ? (data.totalTime / node.totalTime) * 100 : 0
percentOfCurrent: totalCallerCount > 0 ? (data.count / totalCallerCount) * 100 : 0
}))
.sort((a, b) => b.totalTime - a.totalTime);
.sort((a, b) => b.callCount - a.callCount);
// Called Functions(我调用了谁)
// - totalTime: 当前函数调用该被调用者时的平均耗时
// - percentOfCurrent: 该被调用者的耗时占当前函数耗时的百分比
const callees = Array.from(node.callees.entries())
.map(([name, data]) => ({
name,
+13 -1
View File
@@ -486,6 +486,9 @@ export class DebugManager implements IService, IUpdatable {
const { functionName, requestId } = message;
this.advancedProfilerCollector.setSelectedFunction(functionName || null);
// 立即发送更新的数据,无需等待下一帧
this.sendDebugData();
this.webSocketManager.send({
type: 'set_profiler_selected_function_response',
requestId,
@@ -995,10 +998,19 @@ export class DebugManager implements IService, IUpdatable {
try {
const debugData = this.getDebugData();
// 收集高级性能数据(包含 callGraph)
const isProfilerEnabled = ProfilerSDK.isEnabled();
const advancedProfilerData = isProfilerEnabled
? this.advancedProfilerCollector.collectAdvancedData(this.performanceMonitor)
: null;
// 包装成调试面板期望的消息格式
const message = {
type: 'debug_data',
data: debugData
data: debugData,
advancedProfiler: advancedProfilerData
};
this.webSocketManager.send(message);
} catch (error) {
@@ -3,6 +3,8 @@ import { Entity } from '../../ECS/Entity';
import { Component } from '../../ECS/Component';
import { getComponentInstanceTypeName } from '../../ECS/Decorators';
import { IScene } from '../../ECS/IScene';
import { HierarchyComponent } from '../../ECS/Components/HierarchyComponent';
import { HierarchySystem } from '../../ECS/Systems/HierarchySystem';
/**
*
@@ -75,20 +77,28 @@ export class EntityDataCollector {
const entityList = (scene as any).entities;
if (!entityList?.buffer) return [];
return entityList.buffer.map((entity: Entity) => ({
id: entity.id,
name: entity.name || `Entity_${entity.id}`,
active: entity.active !== false,
enabled: entity.enabled !== false,
activeInHierarchy: entity.activeInHierarchy !== false,
componentCount: entity.components.length,
componentTypes: entity.components.map((component: Component) => getComponentInstanceTypeName(component)),
parentId: entity.parent?.id || null,
childIds: entity.children?.map((child: Entity) => child.id) || [],
depth: entity.getDepth ? entity.getDepth() : 0,
tag: entity.tag || 0,
updateOrder: entity.updateOrder || 0
}));
const hierarchySystem = scene.getSystem(HierarchySystem);
return entityList.buffer.map((entity: Entity) => {
const hierarchy = entity.getComponent(HierarchyComponent);
const bActiveInHierarchy = hierarchySystem?.isActiveInHierarchy(entity) ?? entity.active;
const depth = hierarchySystem?.getDepth(entity) ?? 0;
return {
id: entity.id,
name: entity.name || `Entity_${entity.id}`,
active: entity.active !== false,
enabled: entity.enabled !== false,
activeInHierarchy: bActiveInHierarchy,
componentCount: entity.components.length,
componentTypes: entity.components.map((component: Component) => getComponentInstanceTypeName(component)),
parentId: hierarchy?.parentId ?? null,
childIds: hierarchy?.childIds ?? [],
depth,
tag: entity.tag || 0,
updateOrder: entity.updateOrder || 0
};
});
}
/**
@@ -200,7 +210,7 @@ export class EntityDataCollector {
pendingRemove: stats.pendingRemove || 0,
entitiesPerArchetype: archetypeData.distribution,
topEntitiesByComponents: archetypeData.topEntities,
entityHierarchy: this.buildEntityHierarchyTree(entityList),
entityHierarchy: this.buildEntityHierarchyTree(entityList, scene),
entityDetailsMap: this.buildEntityDetailsMap(entityList, scene)
};
}
@@ -534,7 +544,10 @@ export class EntityDataCollector {
}
}
private buildEntityHierarchyTree(entityList: { buffer?: Entity[] }): Array<{
private buildEntityHierarchyTree(
entityList: { buffer?: Entity[] },
scene?: IScene | null
): Array<{
id: number;
name: string;
active: boolean;
@@ -550,11 +563,14 @@ export class EntityDataCollector {
}> {
if (!entityList?.buffer) return [];
const hierarchySystem = scene?.getSystem(HierarchySystem);
const rootEntities: any[] = [];
entityList.buffer.forEach((entity: Entity) => {
if (!entity.parent) {
const hierarchyNode = this.buildEntityHierarchyNode(entity);
const hierarchy = entity.getComponent(HierarchyComponent);
const bHasNoParent = hierarchy?.parentId === null || hierarchy?.parentId === undefined;
if (bHasNoParent) {
const hierarchyNode = this.buildEntityHierarchyNode(entity, hierarchySystem);
rootEntities.push(hierarchyNode);
}
});
@@ -572,25 +588,32 @@ export class EntityDataCollector {
/**
*
*/
private buildEntityHierarchyNode(entity: Entity): any {
private buildEntityHierarchyNode(entity: Entity, hierarchySystem?: HierarchySystem | null): any {
const hierarchy = entity.getComponent(HierarchyComponent);
const bActiveInHierarchy = hierarchySystem?.isActiveInHierarchy(entity) ?? entity.active;
const depth = hierarchySystem?.getDepth(entity) ?? 0;
let node = {
id: entity.id,
name: entity.name || `Entity_${entity.id}`,
active: entity.active !== false,
enabled: entity.enabled !== false,
activeInHierarchy: entity.activeInHierarchy !== false,
activeInHierarchy: bActiveInHierarchy,
componentCount: entity.components.length,
componentTypes: entity.components.map((component: Component) => getComponentInstanceTypeName(component)),
parentId: entity.parent?.id || null,
parentId: hierarchy?.parentId ?? null,
children: [] as any[],
depth: entity.getDepth ? entity.getDepth() : 0,
depth,
tag: entity.tag || 0,
updateOrder: entity.updateOrder || 0
};
// 递归构建子实体节点
if (entity.children && entity.children.length > 0) {
node.children = entity.children.map((child: Entity) => this.buildEntityHierarchyNode(child));
if (hierarchySystem) {
const children = hierarchySystem.getChildren(entity);
if (children.length > 0) {
node.children = children.map((child: Entity) => this.buildEntityHierarchyNode(child, hierarchySystem));
}
}
// 优先使用Entity的getDebugInfo方法
@@ -616,6 +639,7 @@ export class EntityDataCollector {
private buildEntityDetailsMap(entityList: { buffer?: Entity[] }, scene?: IScene | null): Record<number, any> {
if (!entityList?.buffer) return {};
const hierarchySystem = scene?.getSystem(HierarchySystem);
const entityDetailsMap: Record<number, any> = {};
const entities = entityList.buffer;
const batchSize = 100;
@@ -626,7 +650,7 @@ export class EntityDataCollector {
batch.forEach((entity: Entity) => {
const baseDebugInfo = entity.getDebugInfo
? entity.getDebugInfo()
: this.buildFallbackEntityInfo(entity, scene);
: this.buildFallbackEntityInfo(entity, scene, hierarchySystem);
const componentCacheStats = (entity as any).getComponentCacheStats
? (entity as any).getComponentCacheStats()
@@ -634,9 +658,13 @@ export class EntityDataCollector {
const componentDetails = this.extractComponentDetails(entity.components);
// 获取父实体名称
const parent = hierarchySystem?.getParent(entity);
const parentName = parent?.name ?? null;
entityDetailsMap[entity.id] = {
...baseDebugInfo,
parentName: entity.parent?.name || null,
parentName,
components: componentDetails,
componentTypes: baseDebugInfo.componentTypes || componentDetails.map((comp) => comp.typeName),
cachePerformance: componentCacheStats
@@ -656,15 +684,22 @@ export class EntityDataCollector {
/**
*
*/
private buildFallbackEntityInfo(entity: Entity, scene?: IScene | null): any {
private buildFallbackEntityInfo(
entity: Entity,
scene?: IScene | null,
hierarchySystem?: HierarchySystem | null
): any {
const sceneInfo = this.getSceneInfo(scene);
const hierarchy = entity.getComponent(HierarchyComponent);
const bActiveInHierarchy = hierarchySystem?.isActiveInHierarchy(entity) ?? entity.active;
const depth = hierarchySystem?.getDepth(entity) ?? 0;
return {
name: entity.name || `Entity_${entity.id}`,
id: entity.id,
enabled: entity.enabled !== false,
active: entity.active !== false,
activeInHierarchy: entity.activeInHierarchy !== false,
activeInHierarchy: bActiveInHierarchy,
destroyed: entity.isDestroyed || false,
scene: sceneInfo.name,
sceneName: sceneInfo.name,
@@ -672,10 +707,10 @@ export class EntityDataCollector {
componentCount: entity.components.length,
componentTypes: entity.components.map((component: Component) => getComponentInstanceTypeName(component)),
componentMask: entity.componentMask?.toString() || '0',
parentId: entity.parent?.id || null,
childCount: entity.children?.length || 0,
childIds: entity.children.map((child: Entity) => child.id) || [],
depth: entity.getDepth ? entity.getDepth() : 0,
parentId: hierarchy?.parentId ?? null,
childCount: hierarchy?.childIds?.length ?? 0,
childIds: hierarchy?.childIds ?? [],
depth,
tag: entity.tag || 0,
updateOrder: entity.updateOrder || 0
};
@@ -0,0 +1,649 @@
/**
*
*
*
*
*
* 1. - 使 Proxy
* 2. -
* 3. - 使 @Profile()
*/
import { ProfilerSDK } from './ProfilerSDK';
import { ProfileCategory } from './ProfilerTypes';
/**
*
*/
export interface AutoProfilerConfig {
/** 是否启用自动包装 */
enabled: boolean;
/** 采样间隔(毫秒),用于采样分析器 */
sampleInterval: number;
/** 最小记录耗时(毫秒),低于此值的调用不记录 */
minDuration: number;
/** 是否追踪异步方法 */
trackAsync: boolean;
/** 排除的方法名模式 */
excludePatterns: RegExp[];
/** 最大采样缓冲区大小 */
maxBufferSize: number;
}
const DEFAULT_CONFIG: AutoProfilerConfig = {
enabled: true,
sampleInterval: 10,
minDuration: 0.1, // 0.1ms
trackAsync: true,
excludePatterns: [
/^_/, // 私有方法
/^get[A-Z]/, // getter 方法
/^set[A-Z]/, // setter 方法
/^is[A-Z]/, // 布尔检查方法
/^has[A-Z]/, // 存在检查方法
],
maxBufferSize: 10000
};
/**
*
*/
interface SampleData {
timestamp: number;
stack: string[];
duration?: number;
}
/**
*
*/
interface WrapInfo {
className: string;
methodName: string;
category: ProfileCategory;
original: Function;
}
/**
*
*/
export class AutoProfiler {
private static instance: AutoProfiler | null = null;
private config: AutoProfilerConfig;
private wrappedObjects: WeakMap<object, Map<string, WrapInfo>> = new WeakMap();
private samplingProfiler: SamplingProfiler | null = null;
private registeredClasses: Map<string, { constructor: Function; category: ProfileCategory }> = new Map();
private constructor(config?: Partial<AutoProfilerConfig>) {
this.config = { ...DEFAULT_CONFIG, ...config };
}
/**
*
*/
public static getInstance(config?: Partial<AutoProfilerConfig>): AutoProfiler {
if (!AutoProfiler.instance) {
AutoProfiler.instance = new AutoProfiler(config);
}
return AutoProfiler.instance;
}
/**
*
*/
public static resetInstance(): void {
if (AutoProfiler.instance) {
AutoProfiler.instance.dispose();
AutoProfiler.instance = null;
}
}
/**
* /
*/
public static setEnabled(enabled: boolean): void {
AutoProfiler.getInstance().setEnabled(enabled);
}
/**
*
*
*/
public static registerClass<T extends new (...args: any[]) => any>(
constructor: T,
category: ProfileCategory = ProfileCategory.Custom,
className?: string
): T {
return AutoProfiler.getInstance().registerClass(constructor, category, className);
}
/**
*
*/
public static wrapInstance<T extends object>(
instance: T,
className: string,
category: ProfileCategory = ProfileCategory.Custom
): T {
return AutoProfiler.getInstance().wrapInstance(instance, className, category);
}
/**
*
*/
public static wrapFunction<T extends (...args: any[]) => any>(
fn: T,
name: string,
category: ProfileCategory = ProfileCategory.Custom
): T {
return AutoProfiler.getInstance().wrapFunction(fn, name, category);
}
/**
*
*/
public static startSampling(): void {
AutoProfiler.getInstance().startSampling();
}
/**
*
*/
public static stopSampling(): SampleData[] {
return AutoProfiler.getInstance().stopSampling();
}
/**
*
*/
public setEnabled(enabled: boolean): void {
this.config.enabled = enabled;
if (!enabled && this.samplingProfiler) {
this.samplingProfiler.stop();
}
}
/**
*
*/
public registerClass<T extends new (...args: any[]) => any>(
constructor: T,
category: ProfileCategory = ProfileCategory.Custom,
className?: string
): T {
const name = className || constructor.name;
this.registeredClasses.set(name, { constructor, category });
// eslint-disable-next-line @typescript-eslint/no-this-alias -- Required for Proxy construct handler
const self = this;
// 创建代理类
const ProxiedClass = new Proxy(constructor, {
construct(target, args, newTarget) {
const instance = Reflect.construct(target, args, newTarget);
if (self.config.enabled) {
self.wrapInstance(instance, name, category);
}
return instance;
}
});
return ProxiedClass;
}
/**
*
*/
public wrapInstance<T extends object>(
instance: T,
className: string,
category: ProfileCategory = ProfileCategory.Custom
): T {
if (!this.config.enabled) {
return instance;
}
// 检查是否已经包装过
if (this.wrappedObjects.has(instance)) {
return instance;
}
const wrapInfoMap = new Map<string, WrapInfo>();
this.wrappedObjects.set(instance, wrapInfoMap);
// 获取所有方法(包括原型链上的)
const methodNames = this.getAllMethodNames(instance);
for (const methodName of methodNames) {
if (this.shouldExcludeMethod(methodName)) {
continue;
}
const descriptor = this.getPropertyDescriptor(instance, methodName);
if (!descriptor || typeof descriptor.value !== 'function') {
continue;
}
const original = descriptor.value as Function;
const wrapped = this.createWrappedMethod(original, className, methodName, category);
wrapInfoMap.set(methodName, {
className,
methodName,
category,
original
});
try {
(instance as any)[methodName] = wrapped;
} catch {
// 某些属性可能是只读的
}
}
return instance;
}
/**
*
*/
public wrapFunction<T extends (...args: any[]) => any>(
fn: T,
name: string,
category: ProfileCategory = ProfileCategory.Custom
): T {
if (!this.config.enabled) return fn;
// eslint-disable-next-line @typescript-eslint/no-this-alias -- Required for wrapped function closure
const self = this;
const wrapped = function(this: any, ...args: any[]): any {
const handle = ProfilerSDK.beginSample(name, category);
try {
const result = fn.apply(this, args);
// 处理 Promise
if (self.config.trackAsync && result instanceof Promise) {
return result.finally(() => {
ProfilerSDK.endSample(handle);
});
}
// 同步函数,立即结束采样
ProfilerSDK.endSample(handle);
return result;
} catch (error) {
// 发生错误时也要结束采样
ProfilerSDK.endSample(handle);
throw error;
}
} as T;
// 保留原函数的属性
Object.defineProperty(wrapped, 'name', { value: fn.name || name });
Object.defineProperty(wrapped, 'length', { value: fn.length });
return wrapped;
}
/**
*
*/
public startSampling(): void {
if (!this.samplingProfiler) {
this.samplingProfiler = new SamplingProfiler(this.config);
}
this.samplingProfiler.start();
}
/**
*
*/
public stopSampling(): SampleData[] {
if (!this.samplingProfiler) {
return [];
}
return this.samplingProfiler.stop();
}
/**
*
*/
public dispose(): void {
if (this.samplingProfiler) {
this.samplingProfiler.stop();
this.samplingProfiler = null;
}
this.registeredClasses.clear();
}
/**
*
*/
private createWrappedMethod(
original: Function,
className: string,
methodName: string,
category: ProfileCategory
): Function {
// eslint-disable-next-line @typescript-eslint/no-this-alias -- Required for wrapped method closure
const self = this;
const fullName = `${className}.${methodName}`;
const minDuration = this.config.minDuration;
return function(this: any, ...args: any[]): any {
if (!self.config.enabled || !ProfilerSDK.isEnabled()) {
return original.apply(this, args);
}
const startTime = performance.now();
const handle = ProfilerSDK.beginSample(fullName, category);
try {
const result = original.apply(this, args);
// 处理异步方法
if (self.config.trackAsync && result instanceof Promise) {
return result.then(
(value) => {
const duration = performance.now() - startTime;
if (duration >= minDuration) {
ProfilerSDK.endSample(handle);
}
return value;
},
(error) => {
ProfilerSDK.endSample(handle);
throw error;
}
);
}
// 同步方法,检查最小耗时后结束采样
const duration = performance.now() - startTime;
if (duration >= minDuration) {
ProfilerSDK.endSample(handle);
}
return result;
} catch (error) {
// 发生错误时也要结束采样
ProfilerSDK.endSample(handle);
throw error;
}
};
}
/**
*
*/
private getAllMethodNames(obj: object): string[] {
const methods = new Set<string>();
let current = obj;
while (current && current !== Object.prototype) {
for (const name of Object.getOwnPropertyNames(current)) {
if (name !== 'constructor') {
methods.add(name);
}
}
current = Object.getPrototypeOf(current);
}
return Array.from(methods);
}
/**
*
*/
private getPropertyDescriptor(obj: object, name: string): PropertyDescriptor | undefined {
let current = obj;
while (current && current !== Object.prototype) {
const descriptor = Object.getOwnPropertyDescriptor(current, name);
if (descriptor) return descriptor;
current = Object.getPrototypeOf(current);
}
return undefined;
}
/**
*
*/
private shouldExcludeMethod(methodName: string): boolean {
// 排除构造函数和内置方法
if (methodName === 'constructor' || methodName.startsWith('__')) {
return true;
}
// 检查排除模式
for (const pattern of this.config.excludePatterns) {
if (pattern.test(methodName)) {
return true;
}
}
return false;
}
}
/**
*
* 使
*/
class SamplingProfiler {
private config: AutoProfilerConfig;
private samples: SampleData[] = [];
private intervalId: number | null = null;
private isRunning = false;
constructor(config: AutoProfilerConfig) {
this.config = config;
}
/**
*
*/
public start(): void {
if (this.isRunning) return;
this.isRunning = true;
this.samples = [];
// 使用 requestAnimationFrame 或 setInterval 进行采样
const sample = () => {
if (!this.isRunning) return;
const stack = this.captureStack();
if (stack.length > 0) {
this.samples.push({
timestamp: performance.now(),
stack
});
// 限制缓冲区大小
if (this.samples.length > this.config.maxBufferSize) {
this.samples.shift();
}
}
// 继续采样
if (this.config.sampleInterval < 16) {
// 高频采样使用 setTimeout
this.intervalId = setTimeout(sample, this.config.sampleInterval) as any;
} else {
this.intervalId = setTimeout(sample, this.config.sampleInterval) as any;
}
};
sample();
}
/**
*
*/
public stop(): SampleData[] {
this.isRunning = false;
if (this.intervalId !== null) {
clearTimeout(this.intervalId);
this.intervalId = null;
}
return [...this.samples];
}
/**
*
*/
private captureStack(): string[] {
try {
// 创建 Error 对象获取调用栈
const error = new Error();
const stack = error.stack || '';
// 解析调用栈
const lines = stack.split('\n').slice(3); // 跳过 Error 和 captureStack/sample
const frames: string[] = [];
for (const line of lines) {
const frame = this.parseStackFrame(line);
if (frame && !this.isInternalFrame(frame)) {
frames.push(frame);
}
}
return frames;
} catch {
return [];
}
}
/**
*
*/
private parseStackFrame(line: string): string | null {
// Chrome/Edge 格式: " at functionName (file:line:col)"
// Firefox 格式: "functionName@file:line:col"
// Safari 格式: "functionName@file:line:col"
line = line.trim();
// Chrome 格式
let match = line.match(/at\s+(.+?)\s+\(/);
if (match && match[1]) {
return match[1];
}
// Chrome 匿名函数格式
match = line.match(/at\s+(.+)/);
if (match && match[1]) {
const name = match[1];
if (!name.includes('(')) {
return name;
}
}
// Firefox/Safari 格式
match = line.match(/^(.+?)@/);
if (match && match[1]) {
return match[1];
}
return null;
}
/**
*
*/
private isInternalFrame(frame: string): boolean {
const internalPatterns = [
'SamplingProfiler',
'AutoProfiler',
'ProfilerSDK',
'setTimeout',
'setInterval',
'requestAnimationFrame',
'<anonymous>',
'eval'
];
return internalPatterns.some(pattern => frame.includes(pattern));
}
}
/**
* @Profile
*
*
* @example
* ```typescript
* class MySystem extends System {
* @Profile()
* update() {
* // 方法执行时间会被自动记录
* }
*
* @Profile('customName', ProfileCategory.Physics)
* calculatePhysics() {
* // 使用自定义名称和分类
* }
* }
* ```
*/
export function Profile(
name?: string,
category: ProfileCategory = ProfileCategory.Custom
): MethodDecorator {
return function(
target: object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
): PropertyDescriptor {
const original = descriptor.value;
const methodName = name || `${target.constructor.name}.${String(propertyKey)}`;
descriptor.value = function(this: any, ...args: any[]): any {
if (!ProfilerSDK.isEnabled()) {
return original.apply(this, args);
}
const handle = ProfilerSDK.beginSample(methodName, category);
try {
const result = original.apply(this, args);
// 处理异步方法
if (result instanceof Promise) {
return result.finally(() => {
ProfilerSDK.endSample(handle);
});
}
// 同步方法,立即结束采样
ProfilerSDK.endSample(handle);
return result;
} catch (error) {
// 发生错误时也要结束采样
ProfilerSDK.endSample(handle);
throw error;
}
};
return descriptor;
};
}
/**
* @ProfileClass
*
*
* @example
* ```typescript
* @ProfileClass(ProfileCategory.Physics)
* class PhysicsSystem extends System {
* update() { ... } // 自动被包装
* calculate() { ... } // 自动被包装
* }
* ```
*/
export function ProfileClass(category: ProfileCategory = ProfileCategory.Custom): ClassDecorator {
return function<T extends Function>(constructor: T): T {
return AutoProfiler.registerClass(constructor as any, category) as any;
};
}
+128 -17
View File
@@ -228,6 +228,9 @@ export class ProfilerSDK {
const endTime = performance.now();
const duration = endTime - handle.startTime;
// 获取父级 handle(在删除当前 handle 之前)
const parentHandle = handle.parentId ? this.activeSamples.get(handle.parentId) : undefined;
const sample: ProfileSample = {
id: handle.id,
name: handle.name,
@@ -237,6 +240,7 @@ export class ProfilerSDK {
duration,
selfTime: duration,
parentId: handle.parentId,
parentName: parentHandle?.name,
depth: handle.depth,
callCount: 1
};
@@ -245,7 +249,7 @@ export class ProfilerSDK {
this.currentFrame.samples.push(sample);
}
this.updateCallGraph(handle.name, handle.category, duration, handle.parentId);
this.updateCallGraph(handle.name, handle.category, duration, parentHandle);
this.activeSamples.delete(handle.id);
const stackIndex = this.sampleStack.indexOf(handle);
@@ -437,6 +441,9 @@ export class ProfilerSDK {
const categoryBreakdown = this.aggregateCategoryStats(frames);
// 根据帧历史重新计算 callGraph(不使用全局累积的数据)
const callGraph = this.buildCallGraphFromFrames(frames);
const firstFrame = frames[0];
const lastFrame = frames[frames.length - 1];
@@ -450,13 +457,106 @@ export class ProfilerSDK {
p95FrameTime: sortedTimes[Math.floor(sortedTimes.length * 0.95)] || 0,
p99FrameTime: sortedTimes[Math.floor(sortedTimes.length * 0.99)] || 0,
hotspots,
callGraph: new Map(this.callGraph),
callGraph,
categoryBreakdown,
memoryTrend: frames.map((f) => f.memory),
longTasks: [...this.longTasks]
};
}
/**
*
* totalTime /
*/
private buildCallGraphFromFrames(frames: ProfileFrame[]): Map<string, CallGraphNode> {
// 临时存储累计数据
const tempData = new Map<string, {
category: ProfileCategory;
callCount: number;
totalTime: number;
callers: Map<string, { count: number; totalTime: number }>;
callees: Map<string, { count: number; totalTime: number }>;
}>();
for (const frame of frames) {
for (const sample of frame.samples) {
// 获取或创建当前函数的节点
let node = tempData.get(sample.name);
if (!node) {
node = {
category: sample.category,
callCount: 0,
totalTime: 0,
callers: new Map(),
callees: new Map()
};
tempData.set(sample.name, node);
}
node.callCount++;
node.totalTime += sample.duration;
// 如果有父级,建立调用关系
if (sample.parentName) {
// 记录当前函数被谁调用
const callerData = node.callers.get(sample.parentName) || { count: 0, totalTime: 0 };
callerData.count++;
callerData.totalTime += sample.duration;
node.callers.set(sample.parentName, callerData);
// 确保父节点存在并记录它调用了谁
let parentNode = tempData.get(sample.parentName);
if (!parentNode) {
parentNode = {
category: sample.category,
callCount: 0,
totalTime: 0,
callers: new Map(),
callees: new Map()
};
tempData.set(sample.parentName, parentNode);
}
const calleeData = parentNode.callees.get(sample.name) || { count: 0, totalTime: 0 };
calleeData.count++;
calleeData.totalTime += sample.duration;
parentNode.callees.set(sample.name, calleeData);
}
}
}
// 转换为最终结果,将 totalTime 改为平均耗时
const callGraph = new Map<string, CallGraphNode>();
for (const [name, data] of tempData) {
const avgCallers = new Map<string, { count: number; totalTime: number }>();
for (const [callerName, callerData] of data.callers) {
avgCallers.set(callerName, {
count: callerData.count,
totalTime: callerData.count > 0 ? callerData.totalTime / callerData.count : 0
});
}
const avgCallees = new Map<string, { count: number; totalTime: number }>();
for (const [calleeName, calleeData] of data.callees) {
avgCallees.set(calleeName, {
count: calleeData.count,
totalTime: calleeData.count > 0 ? calleeData.totalTime / calleeData.count : 0
});
}
callGraph.set(name, {
name,
category: data.category,
callCount: data.callCount,
totalTime: data.callCount > 0 ? data.totalTime / data.callCount : 0,
callers: avgCallers,
callees: avgCallees
});
}
return callGraph;
}
/**
*
*/
@@ -631,7 +731,7 @@ export class ProfilerSDK {
name: string,
category: ProfileCategory,
duration: number,
parentId?: string
parentHandle?: SampleHandle
): void {
let node = this.callGraph.get(name);
if (!node) {
@@ -649,22 +749,33 @@ export class ProfilerSDK {
node.callCount++;
node.totalTime += duration;
if (parentId) {
const parentHandle = this.activeSamples.get(parentId);
if (parentHandle) {
const callerData = node.callers.get(parentHandle.name) || { count: 0, totalTime: 0 };
callerData.count++;
callerData.totalTime += duration;
node.callers.set(parentHandle.name, callerData);
// 如果有父级,建立调用关系
if (parentHandle) {
// 记录当前函数被谁调用
const callerData = node.callers.get(parentHandle.name) || { count: 0, totalTime: 0 };
callerData.count++;
callerData.totalTime += duration;
node.callers.set(parentHandle.name, callerData);
const parentNode = this.callGraph.get(parentHandle.name);
if (parentNode) {
const calleeData = parentNode.callees.get(name) || { count: 0, totalTime: 0 };
calleeData.count++;
calleeData.totalTime += duration;
parentNode.callees.set(name, calleeData);
}
// 确保父节点存在
let parentNode = this.callGraph.get(parentHandle.name);
if (!parentNode) {
parentNode = {
name: parentHandle.name,
category: parentHandle.category,
callCount: 0,
totalTime: 0,
callers: new Map(),
callees: new Map()
};
this.callGraph.set(parentHandle.name, parentNode);
}
// 记录父函数调用了谁
const calleeData = parentNode.callees.get(name) || { count: 0, totalTime: 0 };
calleeData.count++;
calleeData.totalTime += duration;
parentNode.callees.set(name, calleeData);
}
}
@@ -56,6 +56,8 @@ export interface ProfileSample {
duration: number;
selfTime: number;
parentId?: string | undefined;
/** 父级采样的名称(用于构建调用图) */
parentName?: string | undefined;
depth: number;
callCount: number;
metadata?: Record<string, unknown>;
@@ -4,3 +4,5 @@
export * from './ProfilerTypes';
export { ProfilerSDK } from './ProfilerSDK';
export { AutoProfiler, Profile, ProfileClass } from './AutoProfiler';
export type { AutoProfilerConfig } from './AutoProfiler';
-465
View File
@@ -1,465 +0,0 @@
import { Core } from '../src/Core';
import { Scene } from '../src/ECS/Scene';
import { SceneManager } from '../src/ECS/SceneManager';
import { Entity } from '../src/ECS/Entity';
import { Component } from '../src/ECS/Component';
import { ITimer } from '../src/Utils/Timers/ITimer';
import { Updatable } from '../src/Core/DI';
import type { IService } from '../src/Core/ServiceContainer';
import type { IUpdatable } from '../src/Types/IUpdatable';
// 测试组件
class TestComponent extends Component {
public value: number;
constructor(...args: unknown[]) {
super();
const [value = 0] = args as [number?];
this.value = value;
}
}
// 测试场景
class TestScene extends Scene {
public initializeCalled = false;
public beginCalled = false;
public endCalled = false;
public updateCallCount = 0;
public override initialize(): void {
this.initializeCalled = true;
}
public override begin(): void {
this.beginCalled = true;
}
public override end(): void {
this.endCalled = true;
}
public override update(): void {
this.updateCallCount++;
}
}
// 测试可更新服务
@Updatable()
class TestUpdatableService implements IService, IUpdatable {
public updateCallCount = 0;
public update(): void {
this.updateCallCount++;
}
public dispose(): void {
// 清理资源
}
}
describe('Core - 核心管理系统测试', () => {
let originalConsoleWarn: typeof console.warn;
beforeEach(() => {
// 清除之前的实例
(Core as any)._instance = null;
// 注意:WorldManager不再是单例,无需reset
// 模拟console.warn以避免测试输出
originalConsoleWarn = console.warn;
console.warn = jest.fn();
});
afterEach(() => {
// 恢复console.warn
console.warn = originalConsoleWarn;
// 清理Core实例
if (Core.Instance) {
Core.destroy();
}
});
describe('实例创建和管理', () => {
test('应该能够创建Core实例', () => {
const core = Core.create(true);
expect(core).toBeDefined();
expect(core).toBeInstanceOf(Core);
expect(core.debug).toBe(true);
expect(Core.entitySystemsEnabled).toBe(true);
});
test('应该能够通过配置对象创建Core实例', () => {
const config = {
debug: false,
enableEntitySystems: false
};
const core = Core.create(config);
expect(core.debug).toBe(false);
expect(Core.entitySystemsEnabled).toBe(false);
});
test('重复调用create应该返回同一个实例', () => {
const core1 = Core.create(true);
const core2 = Core.create(false); // 不同参数
expect(core1).toBe(core2);
});
test('应该能够获取Core实例', () => {
const core = Core.create(true);
const instance = Core.Instance;
expect(instance).toBe(core);
});
test('在未创建实例时调用update应该显示警告', () => {
Core.update(0.016);
expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("Core实例未创建,请先调用Core.create()"));
});
});
// 注意:场景管理功能已移至SceneManager
// 相关测试请查看 SceneManager.test.ts
describe('更新循环 - 可更新服务', () => {
let core: Core;
let updatableService: TestUpdatableService;
beforeEach(() => {
core = Core.create(true);
updatableService = new TestUpdatableService();
Core.services.registerInstance(TestUpdatableService, updatableService);
});
test('应该能够更新可更新服务', () => {
Core.update(0.016);
expect(updatableService.updateCallCount).toBe(1);
});
test('暂停状态下不应该执行更新', () => {
Core.paused = true;
Core.update(0.016);
expect(updatableService.updateCallCount).toBe(0);
// 恢复状态
Core.paused = false;
});
test('多次更新应该累积调用', () => {
Core.update(0.016);
Core.update(0.016);
Core.update(0.016);
expect(updatableService.updateCallCount).toBe(3);
});
});
describe('服务容器集成', () => {
let core: Core;
let service1: TestUpdatableService;
beforeEach(() => {
core = Core.create(true);
service1 = new TestUpdatableService();
});
test('应该能够通过ServiceContainer注册可更新服务', () => {
Core.services.registerInstance(TestUpdatableService, service1);
// 测试更新是否被调用
Core.update(0.016);
expect(service1.updateCallCount).toBe(1);
});
test('应该能够注销服务', () => {
Core.services.registerInstance(TestUpdatableService, service1);
Core.services.unregister(TestUpdatableService);
// 测试更新不应该被调用
Core.update(0.016);
expect(service1.updateCallCount).toBe(0);
});
test('应该能够通过ServiceContainer解析服务', () => {
Core.services.registerInstance(TestUpdatableService, service1);
const retrieved = Core.services.resolve(TestUpdatableService);
expect(retrieved).toBe(service1);
});
test('解析不存在的服务应该抛出错误', () => {
expect(() => {
Core.services.resolve(TestUpdatableService);
}).toThrow();
});
});
describe('定时器系统', () => {
let core: Core;
beforeEach(() => {
core = Core.create(true);
});
test('应该能够调度定时器', () => {
let callbackExecuted = false;
let timerInstance: ITimer | null = null;
const timer = Core.schedule(0.1, false, null, (timer) => {
callbackExecuted = true;
timerInstance = timer;
});
expect(timer).toBeDefined();
// 模拟时间推进
for (let i = 0; i < 10; i++) {
Core.update(0.016); // 约160ms总计
}
expect(callbackExecuted).toBe(true);
expect(timerInstance).toBe(timer);
});
test('应该能够调度重复定时器', () => {
let callbackCount = 0;
Core.schedule(0.05, true, null, () => {
callbackCount++;
});
// 模拟足够长的时间以触发多次回调
for (let i = 0; i < 15; i++) {
Core.update(0.016); // 约240ms总计,应该触发4-5次
}
expect(callbackCount).toBeGreaterThan(1);
});
test('应该支持带上下文的定时器', () => {
const context = { value: 42 };
let receivedContext: any = null;
Core.schedule(0.05, false, context, function(this: any, timer) {
receivedContext = this;
});
// 模拟时间推进
for (let i = 0; i < 5; i++) {
Core.update(0.016);
}
expect(receivedContext).toBe(context);
});
});
describe('调试功能', () => {
test('应该能够启用调试功能', () => {
const core = Core.create(true);
const debugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:8080',
autoReconnect: true,
updateInterval: 1000,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
expect(Core.isDebugEnabled).toBe(true);
});
test('应该能够禁用调试功能', () => {
const core = Core.create(true);
const debugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:8080',
autoReconnect: true,
updateInterval: 1000,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
Core.disableDebug();
expect(Core.isDebugEnabled).toBe(false);
});
test('在未创建实例时启用调试应该显示警告', () => {
const debugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:8080',
autoReconnect: true,
updateInterval: 1000,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("Core实例未创建,请先调用Core.create()"));
});
});
// ECS API 现在由 SceneManager 管理
// 相关测试请查看 SceneManager.test.ts
describe('性能监控集成', () => {
let core: Core;
beforeEach(() => {
core = Core.create(true);
});
test('调试模式下应该启用性能监控', () => {
const performanceMonitor = (core as any)._performanceMonitor;
expect(performanceMonitor).toBeDefined();
// 性能监控器应该在调试模式下被启用
expect(performanceMonitor.isEnabled).toBe(true);
});
test('更新循环应该包含性能监控', () => {
const performanceMonitor = (core as any)._performanceMonitor;
const startMonitoringSpy = jest.spyOn(performanceMonitor, 'startMonitoring');
const endMonitoringSpy = jest.spyOn(performanceMonitor, 'endMonitoring');
Core.update(0.016);
expect(startMonitoringSpy).toHaveBeenCalled();
expect(endMonitoringSpy).toHaveBeenCalled();
});
});
describe('Core.destroy() 生命周期', () => {
// 测试服务类
class TestGameService implements IService {
public disposed = false;
public value = 'test-value';
dispose(): void {
this.disposed = true;
}
}
test('destroy 后应该清理所有服务', () => {
// 创建 Core 并注册服务
Core.create({ debug: true });
const service = new TestGameService();
Core.services.registerInstance(TestGameService, service);
// 验证服务已注册
expect(Core.services.isRegistered(TestGameService)).toBe(true);
// 销毁 Core
Core.destroy();
// 验证服务的 dispose 被调用
expect(service.disposed).toBe(true);
// 验证 Core 实例已清空
expect(Core.Instance).toBeNull();
});
test('destroy 后重新 create 应该能够成功注册服务', () => {
// 第一次:创建 Core 并注册服务
Core.create({ debug: true });
Core.services.registerSingleton(TestGameService);
// 验证服务已注册
expect(Core.services.isRegistered(TestGameService)).toBe(true);
const firstService = Core.services.resolve(TestGameService);
expect(firstService).toBeDefined();
expect(firstService.value).toBe('test-value');
// 销毁 Core
Core.destroy();
// 第二次:重新创建 Core
Core.create({ debug: true });
// 应该能够重新注册相同的服务(不应该报错或 warn)
expect(() => {
Core.services.registerSingleton(TestGameService);
}).not.toThrow();
// 验证服务重新注册成功
expect(Core.services.isRegistered(TestGameService)).toBe(true);
const secondService = Core.services.resolve(TestGameService);
expect(secondService).toBeDefined();
expect(secondService.value).toBe('test-value');
// 两次获取的应该是不同的实例
expect(secondService).not.toBe(firstService);
// 第一个实例应该已经被 dispose
expect(firstService.disposed).toBe(true);
});
test('destroy 后旧的服务引用不应该影响新的 Core 实例', () => {
// 第一次:创建 Core 并注册服务
Core.create({ debug: true });
const firstService = new TestGameService();
Core.services.registerInstance(TestGameService, firstService);
// 销毁 Core
Core.destroy();
// 验证旧服务被 dispose
expect(firstService.disposed).toBe(true);
// 第二次:重新创建 Core 并注册新的服务实例
Core.create({ debug: true });
const secondService = new TestGameService();
Core.services.registerInstance(TestGameService, secondService);
// 验证新服务注册成功
const resolved = Core.services.resolve(TestGameService);
expect(resolved).toBe(secondService);
expect(resolved).not.toBe(firstService);
// 新服务应该未被 dispose
expect(secondService.disposed).toBe(false);
});
test('多次调用 destroy 应该安全', () => {
Core.create({ debug: true });
const service = new TestGameService();
Core.services.registerInstance(TestGameService, service);
// 第一次 destroy
Core.destroy();
expect(service.disposed).toBe(true);
expect(Core.Instance).toBeNull();
// 第二次 destroy(应该安全,不抛出错误)
expect(() => {
Core.destroy();
}).not.toThrow();
expect(Core.Instance).toBeNull();
});
});
});
@@ -1,691 +0,0 @@
import {
EntityBuilder,
SceneBuilder,
ComponentBuilder,
ECSFluentAPI,
EntityBatchOperator,
createECSAPI,
initializeECS,
ECS
} from '../../../src/ECS/Core/FluentAPI';
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { QuerySystem } from '../../../src/ECS/Core/QuerySystem';
import { TypeSafeEventSystem } from '../../../src/ECS/Core/EventSystem';
import { EntitySystem } from '../../../src/ECS/Systems/EntitySystem';
import { Matcher } from '../../../src/ECS/Utils/Matcher';
// 测试组件
class TestComponent extends Component {
public value: number;
constructor(...args: unknown[]) {
super();
const [value = 0] = args as [number?];
this.value = value;
}
}
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 TestSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(TestComponent));
}
protected override process(entities: Entity[]): void {
// 测试系统
}
}
describe('FluentAPI - 流式API测试', () => {
let scene: Scene;
let querySystem: QuerySystem;
let eventSystem: TypeSafeEventSystem;
beforeEach(() => {
scene = new Scene();
querySystem = new QuerySystem();
eventSystem = new TypeSafeEventSystem();
});
describe('EntityBuilder - 实体构建器', () => {
let builder: EntityBuilder;
beforeEach(() => {
builder = new EntityBuilder(scene, scene.componentStorageManager);
});
test('应该能够创建实体构建器', () => {
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('应该能够设置实体名称', () => {
const entity = builder.named('TestEntity').build();
expect(entity.name).toBe('TestEntity');
});
test('应该能够设置实体标签', () => {
const entity = builder.tagged(42).build();
expect(entity.tag).toBe(42);
});
test('应该能够添加组件', () => {
const component = new TestComponent(100);
const entity = builder.with(component).build();
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.getComponent(TestComponent)).toBe(component);
});
test('应该能够添加多个组件', () => {
const comp1 = new TestComponent(100);
const comp2 = new PositionComponent(10, 20);
const comp3 = new VelocityComponent(1, 2);
const entity = builder.withComponents(comp1, comp2, comp3).build();
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.hasComponent(VelocityComponent)).toBe(true);
});
test('应该能够条件性添加组件', () => {
const comp1 = new TestComponent(100);
const comp2 = new PositionComponent(10, 20);
const entity = builder
.withIf(true, comp1)
.withIf(false, comp2)
.build();
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.hasComponent(PositionComponent)).toBe(false);
});
test('应该能够使用工厂函数创建组件', () => {
const entity = builder
.withFactory(() => new TestComponent(200))
.build();
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.getComponent(TestComponent)!.value).toBe(200);
});
test('应该能够配置组件属性', () => {
const entity = builder
.with(new TestComponent(100))
.configure(TestComponent, (comp) => {
comp.value = 300;
})
.build();
expect(entity.getComponent(TestComponent)!.value).toBe(300);
});
test('配置不存在的组件应该安全处理', () => {
expect(() => {
builder.configure(TestComponent, (comp) => {
comp.value = 300;
}).build();
}).not.toThrow();
});
test('应该能够设置实体启用状态', () => {
const entity1 = builder.enabled(true).build();
const entity2 = new EntityBuilder(scene, scene.componentStorageManager).enabled(false).build();
expect(entity1.enabled).toBe(true);
expect(entity2.enabled).toBe(false);
});
test('应该能够设置实体活跃状态', () => {
const entity1 = builder.active(true).build();
const entity2 = new EntityBuilder(scene, scene.componentStorageManager).active(false).build();
expect(entity1.active).toBe(true);
expect(entity2.active).toBe(false);
});
test('应该能够添加子实体', () => {
const childBuilder = new EntityBuilder(scene, scene.componentStorageManager)
.named('Child')
.with(new TestComponent(50));
const parent = builder
.named('Parent')
.withChild(childBuilder)
.build();
expect(parent.children.length).toBe(1);
expect(parent.children[0].name).toBe('Child');
});
test('应该能够添加多个子实体', () => {
const child1 = new EntityBuilder(scene, scene.componentStorageManager).named('Child1');
const child2 = new EntityBuilder(scene, scene.componentStorageManager).named('Child2');
const child3 = new EntityBuilder(scene, scene.componentStorageManager).named('Child3');
const parent = builder
.named('Parent')
.withChildren(child1, child2, child3)
.build();
expect(parent.children.length).toBe(3);
expect(parent.children[0].name).toBe('Child1');
expect(parent.children[1].name).toBe('Child2');
expect(parent.children[2].name).toBe('Child3');
});
test('应该能够使用工厂函数创建子实体', () => {
const parent = builder
.named('Parent')
.withChildFactory((parentEntity) => {
return new EntityBuilder(scene, scene.componentStorageManager)
.named(`Child_of_${parentEntity.name}`)
.with(new TestComponent(100));
})
.build();
expect(parent.children.length).toBe(1);
expect(parent.children[0].name).toBe('Child_of_Parent');
});
test('应该能够条件性添加子实体', () => {
const child1 = new EntityBuilder(scene, scene.componentStorageManager).named('Child1');
const child2 = new EntityBuilder(scene, scene.componentStorageManager).named('Child2');
const parent = builder
.named('Parent')
.withChildIf(true, child1)
.withChildIf(false, child2)
.build();
expect(parent.children.length).toBe(1);
expect(parent.children[0].name).toBe('Child1');
});
test('应该能够构建实体并添加到场景', () => {
const entity = builder
.named('SpawnedEntity')
.with(new TestComponent(100))
.spawn();
expect(entity.name).toBe('SpawnedEntity');
expect(entity.scene).toBe(scene);
});
test('应该能够克隆构建器', () => {
const originalBuilder = builder.named('Original').with(new TestComponent(100));
const clonedBuilder = originalBuilder.clone();
expect(clonedBuilder).toBeInstanceOf(EntityBuilder);
expect(clonedBuilder).not.toBe(originalBuilder);
});
test('流式调用应该工作正常', () => {
const entity = builder
.named('ComplexEntity')
.tagged(42)
.with(new TestComponent(100))
.with(new PositionComponent(10, 20))
.enabled(true)
.active(true)
.configure(TestComponent, (comp) => {
comp.value = 200;
})
.build();
expect(entity.name).toBe('ComplexEntity');
expect(entity.tag).toBe(42);
expect(entity.enabled).toBe(true);
expect(entity.active).toBe(true);
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.getComponent(TestComponent)!.value).toBe(200);
});
});
describe('SceneBuilder - 场景构建器', () => {
let builder: SceneBuilder;
beforeEach(() => {
builder = new SceneBuilder();
});
test('应该能够创建场景构建器', () => {
expect(builder).toBeInstanceOf(SceneBuilder);
});
test('应该能够设置场景名称', () => {
const scene = builder.named('TestScene').build();
expect(scene.name).toBe('TestScene');
});
test('应该能够添加实体', () => {
const entity = new Entity('TestEntity', 1);
const scene = builder.withEntity(entity).build();
expect(scene.entities.count).toBe(1);
expect(scene.findEntity('TestEntity')).toBe(entity);
});
test('应该能够使用实体构建器添加实体', () => {
const scene = builder
.withEntityBuilder((builder) => {
return builder
.named('BuilderEntity')
.with(new TestComponent(100));
})
.build();
expect(scene.entities.count).toBe(1);
expect(scene.findEntity('BuilderEntity')).not.toBeNull();
});
test('应该能够批量添加实体', () => {
const entity1 = new Entity('Entity1', 1);
const entity2 = new Entity('Entity2', 2);
const entity3 = new Entity('Entity3', 3);
const scene = builder
.withEntities(entity1, entity2, entity3)
.build();
expect(scene.entities.count).toBe(3);
});
test('应该能够添加系统', () => {
const system = new TestSystem();
const scene = builder.withSystem(system).build();
expect(scene.systems.length).toBe(1);
expect(scene.systems[0]).toBe(system);
});
test('应该能够批量添加系统', () => {
const system1 = new TestSystem();
const system2 = new TestSystem();
const scene = builder
.withSystems(system1, system2)
.build();
expect(scene.systems.length).toBe(1);
});
test('流式调用应该工作正常', () => {
const entity = new Entity('TestEntity', 1);
const system = new TestSystem();
const scene = builder
.named('ComplexScene')
.withEntity(entity)
.withSystem(system)
.withEntityBuilder((builder) => {
return builder.named('BuilderEntity');
})
.build();
expect(scene.name).toBe('ComplexScene');
expect(scene.entities.count).toBe(2);
expect(scene.systems.length).toBe(1);
});
});
describe('ComponentBuilder - 组件构建器', () => {
test('应该能够创建组件构建器', () => {
const builder = new ComponentBuilder(TestComponent, 100);
expect(builder).toBeInstanceOf(ComponentBuilder);
});
test('应该能够设置组件属性', () => {
const component = new ComponentBuilder(TestComponent, 100)
.set('value', 200)
.build();
expect(component.value).toBe(200);
});
test('应该能够使用配置函数', () => {
const component = new ComponentBuilder(PositionComponent, 10, 20)
.configure((comp) => {
comp.x = 30;
comp.y = 40;
})
.build();
expect(component.x).toBe(30);
expect(component.y).toBe(40);
});
test('应该能够条件性设置属性', () => {
const component = new ComponentBuilder(TestComponent, 100)
.setIf(true, 'value', 200)
.setIf(false, 'value', 300)
.build();
expect(component.value).toBe(200);
});
test('流式调用应该工作正常', () => {
const component = new ComponentBuilder(PositionComponent, 0, 0)
.set('x', 10)
.set('y', 20)
.setIf(true, 'x', 30)
.configure((comp) => {
comp.y = 40;
})
.build();
expect(component.x).toBe(30);
expect(component.y).toBe(40);
});
});
describe('ECSFluentAPI - 主API', () => {
let api: ECSFluentAPI;
beforeEach(() => {
api = new ECSFluentAPI(scene, querySystem, eventSystem);
});
test('应该能够创建ECS API', () => {
expect(api).toBeInstanceOf(ECSFluentAPI);
});
test('应该能够创建实体构建器', () => {
const builder = api.createEntity();
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('应该能够创建场景构建器', () => {
const builder = api.createScene();
expect(builder).toBeInstanceOf(SceneBuilder);
});
test('应该能够创建组件构建器', () => {
const builder = api.createComponent(TestComponent, 100);
expect(builder).toBeInstanceOf(ComponentBuilder);
});
test('应该能够创建查询构建器', () => {
const builder = api.query();
expect(builder).toBeDefined();
});
test('应该能够查找实体', () => {
const entity = scene.createEntity('TestEntity');
entity.addComponent(new TestComponent(100));
querySystem.setEntities([entity]);
const results = api.find(TestComponent);
expect(results.length).toBe(1);
expect(results[0]).toBe(entity);
});
test('应该能够查找第一个匹配的实体', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
entity1.addComponent(new TestComponent(100));
entity2.addComponent(new TestComponent(200));
querySystem.setEntities([entity1, entity2]);
const result = api.findFirst(TestComponent);
expect(result).not.toBeNull();
expect([entity1, entity2]).toContain(result);
});
test('查找不存在的实体应该返回null', () => {
const result = api.findFirst(TestComponent);
expect(result).toBeNull();
});
test('应该能够按名称查找实体', () => {
const entity = scene.createEntity('TestEntity');
const result = api.findByName('TestEntity');
expect(result).toBe(entity);
});
test('应该能够按标签查找实体', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
entity1.tag = 42;
entity2.tag = 42;
const results = api.findByTag(42);
expect(results.length).toBe(2);
expect(results).toContain(entity1);
expect(results).toContain(entity2);
});
test('应该能够触发同步事件', () => {
let eventReceived = false;
let eventData: any = null;
api.on('test:event', (data) => {
eventReceived = true;
eventData = data;
});
api.emit('test:event', { message: 'hello' });
expect(eventReceived).toBe(true);
expect(eventData.message).toBe('hello');
});
test('应该能够触发异步事件', async () => {
let eventReceived = false;
let eventData: any = null;
api.on('test:event', (data) => {
eventReceived = true;
eventData = data;
});
await api.emitAsync('test:event', { message: 'hello' });
expect(eventReceived).toBe(true);
expect(eventData.message).toBe('hello');
});
test('应该能够一次性监听事件', () => {
let callCount = 0;
api.once('test:event', () => {
callCount++;
});
api.emit('test:event', {});
api.emit('test:event', {});
expect(callCount).toBe(1);
});
test('应该能够移除事件监听器', () => {
let callCount = 0;
const listenerId = api.on('test:event', () => {
callCount++;
});
api.emit('test:event', {});
api.off('test:event', listenerId);
api.emit('test:event', {});
expect(callCount).toBe(1);
});
test('应该能够创建批量操作器', () => {
const entity1 = new Entity('Entity1', 1);
const entity2 = new Entity('Entity2', 2);
const batch = api.batch([entity1, entity2]);
expect(batch).toBeInstanceOf(EntityBatchOperator);
});
test('应该能够获取统计信息', () => {
const stats = api.getStats();
expect(stats).toBeDefined();
expect(stats.entityCount).toBeDefined();
expect(stats.systemCount).toBeDefined();
expect(stats.componentStats).toBeDefined();
expect(stats.queryStats).toBeDefined();
expect(stats.eventStats).toBeDefined();
});
});
describe('EntityBatchOperator - 批量操作器', () => {
let entity1: Entity;
let entity2: Entity;
let entity3: Entity;
let batchOp: EntityBatchOperator;
beforeEach(() => {
entity1 = scene.createEntity('Entity1');
entity2 = scene.createEntity('Entity2');
entity3 = scene.createEntity('Entity3');
batchOp = new EntityBatchOperator([entity1, entity2, entity3]);
});
test('应该能够创建批量操作器', () => {
expect(batchOp).toBeInstanceOf(EntityBatchOperator);
});
test('应该能够批量添加组件', () => {
const component = new TestComponent(100);
batchOp.addComponent(component);
expect(entity1.hasComponent(TestComponent)).toBe(true);
expect(entity2.hasComponent(TestComponent)).toBe(true);
expect(entity3.hasComponent(TestComponent)).toBe(true);
});
test('应该能够批量移除组件', () => {
entity1.addComponent(new TestComponent(100));
entity2.addComponent(new TestComponent(200));
entity3.addComponent(new TestComponent(300));
batchOp.removeComponent(TestComponent);
expect(entity1.hasComponent(TestComponent)).toBe(false);
expect(entity2.hasComponent(TestComponent)).toBe(false);
expect(entity3.hasComponent(TestComponent)).toBe(false);
});
test('应该能够批量设置活跃状态', () => {
batchOp.setActive(false);
expect(entity1.active).toBe(false);
expect(entity2.active).toBe(false);
expect(entity3.active).toBe(false);
});
test('应该能够批量设置标签', () => {
batchOp.setTag(42);
expect(entity1.tag).toBe(42);
expect(entity2.tag).toBe(42);
expect(entity3.tag).toBe(42);
});
test('应该能够批量执行操作', () => {
const names: string[] = [];
const indices: number[] = [];
batchOp.forEach((entity, index) => {
names.push(entity.name);
indices.push(index);
});
expect(names).toEqual(['Entity1', 'Entity2', 'Entity3']);
expect(indices).toEqual([0, 1, 2]);
});
test('应该能够过滤实体', () => {
entity1.tag = 1;
entity2.tag = 2;
entity3.tag = 1;
const filtered = batchOp.filter(entity => entity.tag === 1);
expect(filtered.count()).toBe(2);
expect(filtered.toArray()).toContain(entity1);
expect(filtered.toArray()).toContain(entity3);
});
test('应该能够获取实体数组', () => {
const entities = batchOp.toArray();
expect(entities.length).toBe(3);
expect(entities).toContain(entity1);
expect(entities).toContain(entity2);
expect(entities).toContain(entity3);
});
test('应该能够获取实体数量', () => {
expect(batchOp.count()).toBe(3);
});
test('流式调用应该工作正常', () => {
const result = batchOp
.addComponent(new TestComponent(100))
.setActive(false)
.setTag(42)
.forEach((entity) => {
entity.name = entity.name + '_Modified';
});
expect(result).toBe(batchOp);
expect(entity1.hasComponent(TestComponent)).toBe(true);
expect(entity1.active).toBe(false);
expect(entity1.tag).toBe(42);
expect(entity1.name).toBe('Entity1_Modified');
});
});
describe('工厂函数和全局API', () => {
test('createECSAPI应该创建API实例', () => {
const api = createECSAPI(scene, querySystem, eventSystem);
expect(api).toBeInstanceOf(ECSFluentAPI);
});
test('initializeECS应该初始化全局ECS', () => {
initializeECS(scene, querySystem, eventSystem);
expect(ECS).toBeInstanceOf(ECSFluentAPI);
});
test('全局ECS应该可用', () => {
initializeECS(scene, querySystem, eventSystem);
const builder = ECS.createEntity();
expect(builder).toBeInstanceOf(EntityBuilder);
});
});
});
@@ -0,0 +1,321 @@
import { EntityBuilder } from '../../../../src/ECS/Core/FluentAPI/EntityBuilder';
import { Scene } from '../../../../src/ECS/Scene';
import { Component } from '../../../../src/ECS/Component';
import { HierarchySystem } from '../../../../src/ECS/Systems/HierarchySystem';
import { ECSComponent } from '../../../../src/ECS/Decorators';
@ECSComponent('BuilderTestPosition')
class PositionComponent extends Component {
public x: number = 0;
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('BuilderTestVelocity')
class VelocityComponent extends Component {
public vx: number = 0;
public vy: number = 0;
}
@ECSComponent('BuilderTestHealth')
class HealthComponent extends Component {
public current: number = 100;
public max: number = 100;
}
// Helper function to create EntityBuilder
function createBuilder(scene: Scene): EntityBuilder {
return new EntityBuilder(scene, scene.componentStorageManager);
}
describe('EntityBuilder', () => {
let scene: Scene;
let hierarchySystem: HierarchySystem;
beforeEach(() => {
scene = new Scene({ name: 'BuilderTestScene' });
hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
});
afterEach(() => {
scene.end();
});
describe('basic building', () => {
test('should create entity with name', () => {
const builder = createBuilder(scene);
const entity = builder.named('TestEntity').build();
expect(entity.name).toBe('TestEntity');
});
test('should create entity with tag', () => {
const builder = createBuilder(scene);
const entity = builder.tagged(0x100).build();
expect(entity.tag).toBe(0x100);
});
test('should support chaining name and tag', () => {
const entity = createBuilder(scene)
.named('ChainedEntity')
.tagged(0x200)
.build();
expect(entity.name).toBe('ChainedEntity');
expect(entity.tag).toBe(0x200);
});
});
describe('component management', () => {
test('should add single component with .with()', () => {
const entity = createBuilder(scene)
.with(new PositionComponent(10, 20))
.build();
const pos = entity.getComponent(PositionComponent);
expect(pos).not.toBeNull();
expect(pos!.x).toBe(10);
expect(pos!.y).toBe(20);
});
test('should add multiple components with .withComponents()', () => {
const entity = createBuilder(scene)
.withComponents(
new PositionComponent(5, 10),
new VelocityComponent(),
new HealthComponent()
)
.build();
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.hasComponent(VelocityComponent)).toBe(true);
expect(entity.hasComponent(HealthComponent)).toBe(true);
});
test('should conditionally add component with .withIf()', () => {
const shouldAdd = true;
const shouldNotAdd = false;
const entity = createBuilder(scene)
.withIf(shouldAdd, new PositionComponent())
.withIf(shouldNotAdd, new VelocityComponent())
.build();
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.hasComponent(VelocityComponent)).toBe(false);
});
test('should add component using factory with .withFactory()', () => {
const entity = createBuilder(scene)
.withFactory(() => new PositionComponent(100, 200))
.build();
const pos = entity.getComponent(PositionComponent);
expect(pos).not.toBeNull();
expect(pos!.x).toBe(100);
expect(pos!.y).toBe(200);
});
test('should configure existing component with .configure()', () => {
const entity = createBuilder(scene)
.with(new PositionComponent(0, 0))
.configure(PositionComponent, (pos: PositionComponent) => {
pos.x = 999;
pos.y = 888;
})
.build();
const pos = entity.getComponent(PositionComponent);
expect(pos!.x).toBe(999);
expect(pos!.y).toBe(888);
});
test('.configure() should do nothing if component does not exist', () => {
const entity = createBuilder(scene)
.configure(PositionComponent, (pos: PositionComponent) => {
pos.x = 100;
})
.build();
expect(entity.hasComponent(PositionComponent)).toBe(false);
});
});
describe('entity state', () => {
test('should set enabled state', () => {
const disabledEntity = createBuilder(scene)
.enabled(false)
.build();
const enabledEntity = createBuilder(scene)
.enabled(true)
.build();
expect(disabledEntity.enabled).toBe(false);
expect(enabledEntity.enabled).toBe(true);
});
test('should set active state', () => {
const inactiveEntity = createBuilder(scene)
.active(false)
.build();
const activeEntity = createBuilder(scene)
.active(true)
.build();
expect(inactiveEntity.active).toBe(false);
expect(activeEntity.active).toBe(true);
});
});
describe('hierarchy building', () => {
test('should call withChild method', () => {
const childBuilder = createBuilder(scene).named('Child');
const builder = createBuilder(scene)
.named('Parent')
.withChild(childBuilder);
// withChild returns the builder for chaining
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('should call withChildren method', () => {
const child1Builder = createBuilder(scene).named('Child1');
const child2Builder = createBuilder(scene).named('Child2');
const builder = createBuilder(scene)
.named('Parent')
.withChildren(child1Builder, child2Builder);
// withChildren returns the builder for chaining
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('should call withChildFactory method', () => {
const builder = createBuilder(scene)
.named('Parent')
.with(new PositionComponent(100, 100))
.withChildFactory((parentEntity) => {
return createBuilder(scene)
.named('ChildFromFactory')
.with(new PositionComponent(10, 20));
});
// withChildFactory returns the builder for chaining
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('should call withChildIf method', () => {
const shouldAdd = true;
const shouldNotAdd = false;
const child1Builder = createBuilder(scene).named('Child1');
const builder1 = createBuilder(scene)
.named('Parent')
.withChildIf(shouldAdd, child1Builder);
expect(builder1).toBeInstanceOf(EntityBuilder);
const child2Builder = createBuilder(scene).named('Child2');
const builder2 = createBuilder(scene)
.named('Parent2')
.withChildIf(shouldNotAdd, child2Builder);
expect(builder2).toBeInstanceOf(EntityBuilder);
});
});
describe('spawning and cloning', () => {
test('should spawn entity to scene with .spawn()', () => {
const initialCount = scene.entities.count;
const entity = createBuilder(scene)
.named('SpawnedEntity')
.with(new PositionComponent())
.spawn();
expect(scene.entities.count).toBe(initialCount + 1);
expect(scene.findEntityById(entity.id)).toBe(entity);
});
test('.build() should not add to scene automatically', () => {
const initialCount = scene.entities.count;
createBuilder(scene)
.named('BuiltEntity')
.build();
expect(scene.entities.count).toBe(initialCount);
});
test('should clone builder', () => {
const builder = createBuilder(scene)
.named('OriginalEntity')
.tagged(0x50);
const clonedBuilder = builder.clone();
expect(clonedBuilder).not.toBe(builder);
expect(clonedBuilder).toBeInstanceOf(EntityBuilder);
});
});
describe('complex building scenarios', () => {
test('should build complete entity with all options', () => {
const entity = createBuilder(scene)
.named('CompleteEntity')
.tagged(0x100)
.with(new PositionComponent(50, 75))
.with(new VelocityComponent())
.withFactory(() => new HealthComponent())
.configure(HealthComponent, (h: HealthComponent) => {
h.current = 80;
h.max = 100;
})
.enabled(true)
.active(true)
.build();
expect(entity.name).toBe('CompleteEntity');
expect(entity.tag).toBe(0x100);
expect(entity.enabled).toBe(true);
expect(entity.active).toBe(true);
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.hasComponent(VelocityComponent)).toBe(true);
expect(entity.hasComponent(HealthComponent)).toBe(true);
const health = entity.getComponent(HealthComponent);
expect(health!.current).toBe(80);
expect(health!.max).toBe(100);
});
test('should support complex chaining', () => {
const builder = createBuilder(scene)
.named('Root')
.with(new PositionComponent(1, 1));
// Add child builder chain
const childBuilder = createBuilder(scene)
.named('Child')
.with(new PositionComponent(2, 2));
// Chain withChild
builder.withChild(childBuilder);
// Build and spawn
const root = builder.spawn();
expect(root.name).toBe('Root');
expect(root.hasComponent(PositionComponent)).toBe(true);
});
});
});
@@ -1,274 +0,0 @@
import { describe, test, expect, beforeEach } from '@jest/globals';
import { Scene } from '../../src/ECS/Scene';
import { Component } from '../../src/ECS/Component';
import { Entity } from '../../src/ECS/Entity';
import { EntityRef, ECSComponent } from '../../src/ECS/Decorators';
@ECSComponent('ParentRef')
class ParentComponent extends Component {
@EntityRef() parent: Entity | null = null;
}
@ECSComponent('TargetRef')
class TargetComponent extends Component {
@EntityRef() target: Entity | null = null;
@EntityRef() ally: Entity | null = null;
}
describe('EntityRef Integration Tests', () => {
let scene: Scene;
beforeEach(() => {
scene = new Scene({ name: 'TestScene' });
});
describe('基础功能', () => {
test('应该支持EntityRef装饰器', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(comp.parent).toBe(entity2);
});
test('Entity销毁时应该自动清理所有引用', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const comp1 = child1.addComponent(new ParentComponent());
const comp2 = child2.addComponent(new ParentComponent());
comp1.parent = parent;
comp2.parent = parent;
expect(comp1.parent).toBe(parent);
expect(comp2.parent).toBe(parent);
parent.destroy();
expect(comp1.parent).toBeNull();
expect(comp2.parent).toBeNull();
});
test('修改引用应该更新ReferenceTracker', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const entity3 = scene.createEntity('Entity3');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
comp.parent = entity3;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(0);
expect(scene.referenceTracker.getReferencesTo(entity3.id)).toHaveLength(1);
});
test('设置为null应该注销引用', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
comp.parent = null;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(0);
});
});
describe('Component生命周期', () => {
test('移除Component应该清理其所有引用注册', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
entity1.removeComponent(comp);
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(0);
});
test('移除Component应该清除entityId引用', () => {
const entity1 = scene.createEntity('Entity1');
const comp = entity1.addComponent(new ParentComponent());
expect(comp.entityId).toBe(entity1.id);
entity1.removeComponent(comp);
expect(comp.entityId).toBeNull();
});
});
describe('多属性引用', () => {
test('应该支持同一Component的多个EntityRef属性', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const entity3 = scene.createEntity('Entity3');
const comp = entity1.addComponent(new TargetComponent());
comp.target = entity2;
comp.ally = entity3;
expect(comp.target).toBe(entity2);
expect(comp.ally).toBe(entity3);
entity2.destroy();
expect(comp.target).toBeNull();
expect(comp.ally).toBe(entity3);
entity3.destroy();
expect(comp.ally).toBeNull();
});
});
describe('边界情况', () => {
test('跨Scene引用应该失败', () => {
const scene2 = new Scene({ name: 'TestScene2' });
const entity1 = scene.createEntity('Entity1');
const entity2 = scene2.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(comp.parent).toBeNull();
});
test('引用已销毁的Entity应该失败', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
entity2.destroy();
comp.parent = entity2;
expect(comp.parent).toBeNull();
});
test('重复设置相同值不应重复注册', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
comp.parent = entity2;
comp.parent = entity2;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
});
test('循环引用应该正常工作', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp1 = entity1.addComponent(new ParentComponent());
const comp2 = entity2.addComponent(new ParentComponent());
comp1.parent = entity2;
comp2.parent = entity1;
expect(comp1.parent).toBe(entity2);
expect(comp2.parent).toBe(entity1);
entity1.destroy();
expect(comp2.parent).toBeNull();
expect(entity2.isDestroyed).toBe(false);
});
});
describe('复杂场景', () => {
test('父子实体销毁应该正确清理引用', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const observer = scene.createEntity('Observer');
parent.addChild(child1);
parent.addChild(child2);
const observerComp = observer.addComponent(new TargetComponent());
observerComp.target = parent;
observerComp.ally = child1;
expect(observerComp.target).toBe(parent);
expect(observerComp.ally).toBe(child1);
parent.destroy();
expect(observerComp.target).toBeNull();
expect(observerComp.ally).toBeNull();
expect(child1.isDestroyed).toBe(true);
expect(child2.isDestroyed).toBe(true);
});
test('大量引用场景', () => {
const target = scene.createEntity('Target');
const entities: Entity[] = [];
const components: ParentComponent[] = [];
for (let i = 0; i < 100; i++) {
const entity = scene.createEntity(`Entity${i}`);
const comp = entity.addComponent(new ParentComponent());
comp.parent = target;
entities.push(entity);
components.push(comp);
}
expect(scene.referenceTracker.getReferencesTo(target.id)).toHaveLength(100);
target.destroy();
for (const comp of components) {
expect(comp.parent).toBeNull();
}
expect(scene.referenceTracker.getReferencesTo(target.id)).toHaveLength(0);
});
test('批量销毁后引用应全部清理', () => {
const entities: Entity[] = [];
const components: TargetComponent[] = [];
for (let i = 0; i < 50; i++) {
entities.push(scene.createEntity(`Entity${i}`));
}
for (let i = 0; i < 50; i++) {
const comp = entities[i].addComponent(new TargetComponent());
if (i > 0) {
comp.target = entities[i - 1];
}
if (i < 49) {
comp.ally = entities[i + 1];
}
components.push(comp);
}
scene.destroyAllEntities();
for (const comp of components) {
expect(comp.target).toBeNull();
expect(comp.ally).toBeNull();
}
});
});
describe('调试功能', () => {
test('getDebugInfo应该返回引用信息', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
const debugInfo = scene.referenceTracker.getDebugInfo();
expect(debugInfo).toHaveProperty(`entity_${entity2.id}`);
});
});
});
+237
View File
@@ -0,0 +1,237 @@
import {
EntityTags,
hasEntityTag,
addEntityTag,
removeEntityTag,
isFolder,
isHidden,
isLocked
} from '../../src/ECS/EntityTags';
describe('EntityTags', () => {
describe('tag constants', () => {
test('should have correct NONE value', () => {
expect(EntityTags.NONE).toBe(0x0000);
});
test('should have correct FOLDER value', () => {
expect(EntityTags.FOLDER).toBe(0x1000);
});
test('should have correct HIDDEN value', () => {
expect(EntityTags.HIDDEN).toBe(0x2000);
});
test('should have correct LOCKED value', () => {
expect(EntityTags.LOCKED).toBe(0x4000);
});
test('should have correct EDITOR_ONLY value', () => {
expect(EntityTags.EDITOR_ONLY).toBe(0x8000);
});
test('should have correct PREFAB_INSTANCE value', () => {
expect(EntityTags.PREFAB_INSTANCE).toBe(0x0100);
});
test('should have correct PREFAB_ROOT value', () => {
expect(EntityTags.PREFAB_ROOT).toBe(0x0200);
});
test('all tags should have unique values', () => {
const values = Object.values(EntityTags).filter((v) => typeof v === 'number');
const uniqueValues = new Set(values);
expect(uniqueValues.size).toBe(values.length);
});
});
describe('hasEntityTag', () => {
test('should return true when tag is present', () => {
const tag = EntityTags.FOLDER;
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(true);
});
test('should return false when tag is not present', () => {
const tag = EntityTags.FOLDER;
expect(hasEntityTag(tag, EntityTags.HIDDEN)).toBe(false);
});
test('should work with combined tags', () => {
const combined = EntityTags.FOLDER | EntityTags.HIDDEN | EntityTags.LOCKED;
expect(hasEntityTag(combined, EntityTags.FOLDER)).toBe(true);
expect(hasEntityTag(combined, EntityTags.HIDDEN)).toBe(true);
expect(hasEntityTag(combined, EntityTags.LOCKED)).toBe(true);
expect(hasEntityTag(combined, EntityTags.EDITOR_ONLY)).toBe(false);
});
test('should return false for NONE tag', () => {
const tag = EntityTags.NONE;
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(false);
});
});
describe('addEntityTag', () => {
test('should add tag to empty tags', () => {
const result = addEntityTag(EntityTags.NONE, EntityTags.FOLDER);
expect(result).toBe(EntityTags.FOLDER);
});
test('should add tag to existing tags', () => {
const existing = EntityTags.FOLDER as number;
const result = addEntityTag(existing, EntityTags.HIDDEN);
expect(hasEntityTag(result, EntityTags.FOLDER)).toBe(true);
expect(hasEntityTag(result, EntityTags.HIDDEN)).toBe(true);
});
test('should not change value when adding same tag', () => {
const existing = EntityTags.FOLDER as number;
const result = addEntityTag(existing, EntityTags.FOLDER);
expect(result).toBe(EntityTags.FOLDER);
});
test('should handle multiple tag additions', () => {
let tag: number = EntityTags.NONE;
tag = addEntityTag(tag, EntityTags.FOLDER);
tag = addEntityTag(tag, EntityTags.HIDDEN);
tag = addEntityTag(tag, EntityTags.LOCKED);
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(true);
expect(hasEntityTag(tag, EntityTags.HIDDEN)).toBe(true);
expect(hasEntityTag(tag, EntityTags.LOCKED)).toBe(true);
});
});
describe('removeEntityTag', () => {
test('should remove tag from combined tags', () => {
const combined = (EntityTags.FOLDER | EntityTags.HIDDEN) as number;
const result = removeEntityTag(combined, EntityTags.HIDDEN);
expect(hasEntityTag(result, EntityTags.FOLDER)).toBe(true);
expect(hasEntityTag(result, EntityTags.HIDDEN)).toBe(false);
});
test('should return same value when removing non-existent tag', () => {
const existing = EntityTags.FOLDER as number;
const result = removeEntityTag(existing, EntityTags.HIDDEN);
expect(result).toBe(EntityTags.FOLDER);
});
test('should return NONE when removing last tag', () => {
const result = removeEntityTag(EntityTags.FOLDER, EntityTags.FOLDER);
expect(result).toBe(EntityTags.NONE);
});
test('should handle multiple tag removals', () => {
let tag: number = EntityTags.FOLDER | EntityTags.HIDDEN | EntityTags.LOCKED;
tag = removeEntityTag(tag, EntityTags.FOLDER);
tag = removeEntityTag(tag, EntityTags.LOCKED);
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(false);
expect(hasEntityTag(tag, EntityTags.HIDDEN)).toBe(true);
expect(hasEntityTag(tag, EntityTags.LOCKED)).toBe(false);
});
});
describe('isFolder', () => {
test('should return true for folder tag', () => {
expect(isFolder(EntityTags.FOLDER)).toBe(true);
});
test('should return true for combined tags including folder', () => {
const combined = EntityTags.FOLDER | EntityTags.HIDDEN;
expect(isFolder(combined)).toBe(true);
});
test('should return false for non-folder tag', () => {
expect(isFolder(EntityTags.HIDDEN)).toBe(false);
expect(isFolder(EntityTags.NONE)).toBe(false);
});
});
describe('isHidden', () => {
test('should return true for hidden tag', () => {
expect(isHidden(EntityTags.HIDDEN)).toBe(true);
});
test('should return true for combined tags including hidden', () => {
const combined = EntityTags.FOLDER | EntityTags.HIDDEN;
expect(isHidden(combined)).toBe(true);
});
test('should return false for non-hidden tag', () => {
expect(isHidden(EntityTags.FOLDER)).toBe(false);
expect(isHidden(EntityTags.NONE)).toBe(false);
});
});
describe('isLocked', () => {
test('should return true for locked tag', () => {
expect(isLocked(EntityTags.LOCKED)).toBe(true);
});
test('should return true for combined tags including locked', () => {
const combined = EntityTags.FOLDER | EntityTags.LOCKED;
expect(isLocked(combined)).toBe(true);
});
test('should return false for non-locked tag', () => {
expect(isLocked(EntityTags.FOLDER)).toBe(false);
expect(isLocked(EntityTags.NONE)).toBe(false);
});
});
describe('tag combinations', () => {
test('should correctly combine and identify multiple tags', () => {
const tag = (EntityTags.FOLDER | EntityTags.HIDDEN | EntityTags.PREFAB_ROOT) as number;
expect(isFolder(tag)).toBe(true);
expect(isHidden(tag)).toBe(true);
expect(hasEntityTag(tag, EntityTags.PREFAB_ROOT)).toBe(true);
expect(isLocked(tag)).toBe(false);
});
test('should support complex add/remove operations', () => {
let tag: number = EntityTags.NONE;
// Add tags
tag = addEntityTag(tag, EntityTags.FOLDER);
tag = addEntityTag(tag, EntityTags.HIDDEN);
tag = addEntityTag(tag, EntityTags.LOCKED);
tag = addEntityTag(tag, EntityTags.EDITOR_ONLY);
expect(isFolder(tag)).toBe(true);
expect(isHidden(tag)).toBe(true);
expect(isLocked(tag)).toBe(true);
expect(hasEntityTag(tag, EntityTags.EDITOR_ONLY)).toBe(true);
// Remove some tags
tag = removeEntityTag(tag, EntityTags.HIDDEN);
tag = removeEntityTag(tag, EntityTags.LOCKED);
expect(isFolder(tag)).toBe(true);
expect(isHidden(tag)).toBe(false);
expect(isLocked(tag)).toBe(false);
expect(hasEntityTag(tag, EntityTags.EDITOR_ONLY)).toBe(true);
});
test('should work correctly with prefab tags', () => {
const prefabInstanceTag = EntityTags.PREFAB_INSTANCE as number;
const prefabRootTag = EntityTags.PREFAB_ROOT as number;
expect(hasEntityTag(prefabInstanceTag, EntityTags.PREFAB_INSTANCE)).toBe(true);
expect(hasEntityTag(prefabInstanceTag, EntityTags.PREFAB_ROOT)).toBe(false);
expect(hasEntityTag(prefabRootTag, EntityTags.PREFAB_ROOT)).toBe(true);
expect(hasEntityTag(prefabRootTag, EntityTags.PREFAB_INSTANCE)).toBe(false);
// Combine both
const combined = (prefabInstanceTag | prefabRootTag) as number;
expect(hasEntityTag(combined, EntityTags.PREFAB_INSTANCE)).toBe(true);
expect(hasEntityTag(combined, EntityTags.PREFAB_ROOT)).toBe(true);
});
});
});
+648
View File
@@ -0,0 +1,648 @@
import { Scene, Entity, HierarchyComponent, HierarchySystem } from '../../src';
describe('HierarchySystem', () => {
let scene: Scene;
let hierarchySystem: HierarchySystem;
beforeEach(() => {
scene = new Scene();
scene.initialize();
hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
});
afterEach(() => {
scene.end();
});
describe('setParent', () => {
it('should set parent-child relationship', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.getParent(child)).toBe(parent);
expect(hierarchySystem.getChildren(parent)).toContain(child);
expect(hierarchySystem.getChildCount(parent)).toBe(1);
});
it('should auto-add HierarchyComponent if not present', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
expect(parent.getComponent(HierarchyComponent)).toBeNull();
expect(child.getComponent(HierarchyComponent)).toBeNull();
hierarchySystem.setParent(child, parent);
expect(parent.getComponent(HierarchyComponent)).not.toBeNull();
expect(child.getComponent(HierarchyComponent)).not.toBeNull();
});
it('should move child to root when parent is null', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.getParent(child)).toBe(parent);
hierarchySystem.setParent(child, null);
expect(hierarchySystem.getParent(child)).toBeNull();
expect(hierarchySystem.getChildren(parent)).not.toContain(child);
});
it('should transfer child to new parent', () => {
const parent1 = scene.createEntity('Parent1');
const parent2 = scene.createEntity('Parent2');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent1);
expect(hierarchySystem.getParent(child)).toBe(parent1);
expect(hierarchySystem.getChildCount(parent1)).toBe(1);
hierarchySystem.setParent(child, parent2);
expect(hierarchySystem.getParent(child)).toBe(parent2);
expect(hierarchySystem.getChildCount(parent1)).toBe(0);
expect(hierarchySystem.getChildCount(parent2)).toBe(1);
});
it('should throw error on circular reference', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, parent);
hierarchySystem.setParent(grandchild, child);
expect(() => {
hierarchySystem.setParent(parent, grandchild);
}).toThrow('Cannot set parent: would create circular reference');
});
it('should not change if setting same parent', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
const hierarchy = child.getComponent(HierarchyComponent)!;
hierarchy.bCacheDirty = false;
hierarchySystem.setParent(child, parent);
// Should not mark dirty since parent didn't change
expect(hierarchy.bCacheDirty).toBe(false);
});
});
describe('insertChildAt', () => {
it('should insert child at specific position', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const child3 = scene.createEntity('Child3');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child3, parent);
hierarchySystem.insertChildAt(parent, child2, 1);
const children = hierarchySystem.getChildren(parent);
expect(children[0]).toBe(child1);
expect(children[1]).toBe(child2);
expect(children[2]).toBe(child3);
});
it('should append child when index is -1', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
hierarchySystem.setParent(child1, parent);
hierarchySystem.insertChildAt(parent, child2, -1);
const children = hierarchySystem.getChildren(parent);
expect(children[children.length - 1]).toBe(child2);
});
});
describe('removeChild', () => {
it('should remove child from parent', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.getChildCount(parent)).toBe(1);
const result = hierarchySystem.removeChild(parent, child);
expect(result).toBe(true);
expect(hierarchySystem.getChildCount(parent)).toBe(0);
expect(hierarchySystem.getParent(child)).toBeNull();
});
it('should return false if child is not a child of parent', () => {
const parent1 = scene.createEntity('Parent1');
const parent2 = scene.createEntity('Parent2');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent1);
const result = hierarchySystem.removeChild(parent2, child);
expect(result).toBe(false);
});
});
describe('removeAllChildren', () => {
it('should remove all children from parent', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const child3 = scene.createEntity('Child3');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
hierarchySystem.setParent(child3, parent);
expect(hierarchySystem.getChildCount(parent)).toBe(3);
hierarchySystem.removeAllChildren(parent);
expect(hierarchySystem.getChildCount(parent)).toBe(0);
expect(hierarchySystem.getParent(child1)).toBeNull();
expect(hierarchySystem.getParent(child2)).toBeNull();
expect(hierarchySystem.getParent(child3)).toBeNull();
});
});
describe('hierarchy queries', () => {
it('should check if entity has children', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
expect(hierarchySystem.hasChildren(parent)).toBe(false);
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.hasChildren(parent)).toBe(true);
});
it('should check isAncestorOf', () => {
const grandparent = scene.createEntity('Grandparent');
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(parent, grandparent);
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.isAncestorOf(grandparent, child)).toBe(true);
expect(hierarchySystem.isAncestorOf(parent, child)).toBe(true);
expect(hierarchySystem.isAncestorOf(child, grandparent)).toBe(false);
});
it('should check isDescendantOf', () => {
const grandparent = scene.createEntity('Grandparent');
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(parent, grandparent);
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.isDescendantOf(child, grandparent)).toBe(true);
expect(hierarchySystem.isDescendantOf(child, parent)).toBe(true);
expect(hierarchySystem.isDescendantOf(grandparent, child)).toBe(false);
});
it('should get root entity', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
expect(hierarchySystem.getRoot(grandchild)).toBe(root);
expect(hierarchySystem.getRoot(child)).toBe(root);
expect(hierarchySystem.getRoot(root)).toBe(root);
});
it('should get depth correctly', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
root.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
expect(hierarchySystem.getDepth(root)).toBe(0);
expect(hierarchySystem.getDepth(child)).toBe(1);
expect(hierarchySystem.getDepth(grandchild)).toBe(2);
});
});
describe('findChild', () => {
it('should find child by name', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Target');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
const found = hierarchySystem.findChild(parent, 'Target');
expect(found).toBe(child2);
});
it('should find child recursively', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Target');
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
const found = hierarchySystem.findChild(root, 'Target', true);
expect(found).toBe(grandchild);
const notFound = hierarchySystem.findChild(root, 'Target', false);
expect(notFound).toBeNull();
});
});
describe('forEachChild', () => {
it('should iterate over children', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
const visited: Entity[] = [];
hierarchySystem.forEachChild(parent, (child) => {
visited.push(child);
});
expect(visited).toContain(child1);
expect(visited).toContain(child2);
expect(visited.length).toBe(2);
});
it('should iterate recursively', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
const visited: Entity[] = [];
hierarchySystem.forEachChild(root, (entity) => {
visited.push(entity);
}, true);
expect(visited).toContain(child);
expect(visited).toContain(grandchild);
expect(visited.length).toBe(2);
});
});
describe('getRootEntities', () => {
it('should return all root entities', () => {
const root1 = scene.createEntity('Root1');
const root2 = scene.createEntity('Root2');
const child = scene.createEntity('Child');
root1.addComponent(new HierarchyComponent());
root2.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child, root1);
const roots = hierarchySystem.getRootEntities();
expect(roots).toContain(root1);
expect(roots).toContain(root2);
expect(roots).not.toContain(child);
});
});
describe('activeInHierarchy', () => {
it('should be inactive if parent is inactive', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.isActiveInHierarchy(child)).toBe(true);
parent.active = false;
// Mark cache dirty to recalculate
const childHierarchy = child.getComponent(HierarchyComponent)!;
childHierarchy.bCacheDirty = true;
expect(hierarchySystem.isActiveInHierarchy(child)).toBe(false);
});
it('should be inactive if self is inactive', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
child.active = false;
expect(hierarchySystem.isActiveInHierarchy(child)).toBe(false);
});
});
});
describe('HierarchyComponent', () => {
it('should have correct default values', () => {
const component = new HierarchyComponent();
expect(component.parentId).toBeNull();
expect(component.childIds).toEqual([]);
expect(component.depth).toBe(0);
expect(component.bActiveInHierarchy).toBe(true);
expect(component.bCacheDirty).toBe(true);
});
});
describe('HierarchySystem - Extended Tests', () => {
let scene: Scene;
let hierarchySystem: HierarchySystem;
beforeEach(() => {
scene = new Scene();
scene.initialize();
hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
});
afterEach(() => {
scene.end();
});
describe('findChildrenByTag', () => {
it('should find children by tag', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const child3 = scene.createEntity('Child3');
child1.tag = 0x01;
child2.tag = 0x02;
child3.tag = 0x01;
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
hierarchySystem.setParent(child3, parent);
const found = hierarchySystem.findChildrenByTag(parent, 0x01);
expect(found.length).toBe(2);
expect(found).toContain(child1);
expect(found).toContain(child3);
});
it('should find children by tag recursively', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
child.tag = 0x01;
grandchild.tag = 0x01;
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
const foundNonRecursive = hierarchySystem.findChildrenByTag(root, 0x01, false);
expect(foundNonRecursive.length).toBe(1);
expect(foundNonRecursive[0]).toBe(child);
const foundRecursive = hierarchySystem.findChildrenByTag(root, 0x01, true);
expect(foundRecursive.length).toBe(2);
expect(foundRecursive).toContain(child);
expect(foundRecursive).toContain(grandchild);
});
it('should return empty array when no children match tag', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
child.tag = 0x01;
hierarchySystem.setParent(child, parent);
const found = hierarchySystem.findChildrenByTag(parent, 0x02);
expect(found).toEqual([]);
});
});
describe('flattenHierarchy', () => {
it('should flatten hierarchy with expanded nodes', () => {
const root = scene.createEntity('Root');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const grandchild = scene.createEntity('Grandchild');
root.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child1, root);
hierarchySystem.setParent(child2, root);
hierarchySystem.setParent(grandchild, child1);
const expandedIds = new Set([root.id, child1.id]);
const flattened = hierarchySystem.flattenHierarchy(expandedIds);
expect(flattened.length).toBe(4);
expect(flattened[0].entity).toBe(root);
expect(flattened[0].depth).toBe(0);
expect(flattened[0].bHasChildren).toBe(true);
expect(flattened[0].bIsExpanded).toBe(true);
});
it('should not include children of collapsed nodes', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
root.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
// Root is expanded, but child is collapsed
const expandedIds = new Set([root.id]);
const flattened = hierarchySystem.flattenHierarchy(expandedIds);
expect(flattened.length).toBe(2);
expect(flattened[0].entity).toBe(root);
expect(flattened[1].entity).toBe(child);
expect(flattened[1].bHasChildren).toBe(true);
expect(flattened[1].bIsExpanded).toBe(false);
});
it('should return empty array when no root entities', () => {
const flattened = hierarchySystem.flattenHierarchy(new Set());
expect(flattened).toEqual([]);
});
});
describe('updateOrder', () => {
it('should have negative update order for early processing', () => {
expect(hierarchySystem.updateOrder).toBe(-1000);
});
});
describe('process - cache update', () => {
it('should update dirty caches during process', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
// Cache should be dirty after setParent
const childHierarchy = child.getComponent(HierarchyComponent)!;
expect(childHierarchy.bCacheDirty).toBe(true);
// Update scene to process
scene.update();
// Cache should be clean after process
expect(childHierarchy.bCacheDirty).toBe(false);
});
});
describe('insertChildAt edge cases', () => {
it('should handle circular reference prevention', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, parent);
hierarchySystem.setParent(grandchild, child);
expect(() => {
hierarchySystem.insertChildAt(grandchild, parent, 0);
}).toThrow('Cannot set parent: would create circular reference');
});
it('should move child within same parent to different position', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const child3 = scene.createEntity('Child3');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
hierarchySystem.setParent(child3, parent);
// Move child3 to position 0
hierarchySystem.insertChildAt(parent, child3, 0);
const children = hierarchySystem.getChildren(parent);
expect(children[0]).toBe(child3);
expect(children[1]).toBe(child1);
expect(children[2]).toBe(child2);
});
});
describe('removeChild edge cases', () => {
it('should return false when parent has no HierarchyComponent', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
const result = hierarchySystem.removeChild(parent, child);
expect(result).toBe(false);
});
it('should return false when child has no HierarchyComponent', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
parent.addComponent(new HierarchyComponent());
const result = hierarchySystem.removeChild(parent, child);
expect(result).toBe(false);
});
});
describe('removeAllChildren edge cases', () => {
it('should handle entity with no HierarchyComponent', () => {
const parent = scene.createEntity('Parent');
expect(() => {
hierarchySystem.removeAllChildren(parent);
}).not.toThrow();
});
});
describe('getChildren edge cases', () => {
it('should return empty array when entity has no HierarchyComponent', () => {
const entity = scene.createEntity('Entity');
const children = hierarchySystem.getChildren(entity);
expect(children).toEqual([]);
});
});
describe('getChildCount edge cases', () => {
it('should return 0 when entity has no HierarchyComponent', () => {
const entity = scene.createEntity('Entity');
expect(hierarchySystem.getChildCount(entity)).toBe(0);
});
});
describe('getDepth edge cases', () => {
it('should return 0 when entity has no HierarchyComponent', () => {
const entity = scene.createEntity('Entity');
expect(hierarchySystem.getDepth(entity)).toBe(0);
});
it('should use cached depth when cache is valid', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
parent.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child, parent);
// First call computes depth
const depth1 = hierarchySystem.getDepth(child);
expect(depth1).toBe(1);
// Mark cache as valid
const childHierarchy = child.getComponent(HierarchyComponent)!;
childHierarchy.bCacheDirty = false;
// Second call should use cache
const depth2 = hierarchySystem.getDepth(child);
expect(depth2).toBe(1);
});
});
describe('isActiveInHierarchy edge cases', () => {
it('should return entity.active when entity has no HierarchyComponent', () => {
const entity = scene.createEntity('Entity');
entity.active = true;
expect(hierarchySystem.isActiveInHierarchy(entity)).toBe(true);
entity.active = false;
expect(hierarchySystem.isActiveInHierarchy(entity)).toBe(false);
});
it('should use cached value when cache is valid', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
// First call computes activeInHierarchy
const active1 = hierarchySystem.isActiveInHierarchy(child);
expect(active1).toBe(true);
// Mark cache as valid
const childHierarchy = child.getComponent(HierarchyComponent)!;
childHierarchy.bCacheDirty = false;
// Second call should use cache
const active2 = hierarchySystem.isActiveInHierarchy(child);
expect(active2).toBe(true);
});
});
describe('dispose', () => {
it('should not throw when disposing', () => {
expect(() => {
hierarchySystem.dispose();
}).not.toThrow();
});
});
});
+197
View File
@@ -629,4 +629,201 @@ describe('Scene - 场景管理系统测试', () => {
scene2.end();
});
});
describe('扩展测试 - 补齐覆盖率', () => {
describe('实体标签查找', () => {
test('findEntitiesByTag 应该返回具有指定标签的实体', () => {
const entity1 = scene.createEntity('Entity1');
entity1.tag = 0x01;
const entity2 = scene.createEntity('Entity2');
entity2.tag = 0x02;
const entity3 = scene.createEntity('Entity3');
entity3.tag = 0x01;
const found = scene.findEntitiesByTag(0x01);
expect(found.length).toBe(2);
expect(found).toContain(entity1);
expect(found).toContain(entity3);
});
test('findEntitiesByTag 应该在没有匹配时返回空数组', () => {
scene.createEntity('Entity1');
const found = scene.findEntitiesByTag(0xFF);
expect(found).toEqual([]);
});
});
describe('批量实体操作', () => {
test('destroyEntities 应该批量销毁实体', () => {
const entities = scene.createEntities(5, 'Entity');
expect(scene.entities.count).toBe(5);
const toDestroy = entities.slice(0, 3);
scene.destroyEntities(toDestroy);
expect(scene.entities.count).toBe(2);
});
test('destroyEntities 应该处理空数组', () => {
scene.createEntities(3, 'Entity');
expect(() => {
scene.destroyEntities([]);
}).not.toThrow();
expect(scene.entities.count).toBe(3);
});
});
describe('查询方法', () => {
test('queryAny 应该返回具有任意一个组件的实体', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent());
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new VelocityComponent());
const entity3 = scene.createEntity('Entity3');
entity3.addComponent(new HealthComponent());
const result = scene.queryAny(PositionComponent, VelocityComponent);
expect(result.entities.length).toBe(2);
});
test('queryNone 应该返回不包含指定组件的实体', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent());
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new VelocityComponent());
const entity3 = scene.createEntity('Entity3');
const result = scene.queryNone(PositionComponent);
expect(result.entities.length).toBe(2);
expect(result.entities).toContain(entity2);
expect(result.entities).toContain(entity3);
});
test('query 应该创建类型安全的查询构建器', () => {
const builder = scene.query();
expect(builder).toBeDefined();
const matcher = builder.withAll(PositionComponent).buildMatcher();
expect(matcher).toBeDefined();
});
});
describe('服务容器', () => {
test('scene.services 应该返回服务容器', () => {
expect(scene.services).toBeDefined();
});
});
describe('系统错误处理', () => {
test('频繁出错的系统应该被自动禁用', () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
class ErrorProneSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(PositionComponent));
}
protected override process(): void {
throw new Error('Intentional error');
}
}
const system = new ErrorProneSystem();
scene.addEntityProcessor(system);
const entity = scene.createEntity('TestEntity');
entity.addComponent(new PositionComponent(0, 0));
// 多次更新以触发错误阈值
for (let i = 0; i < 15; i++) {
scene.update();
}
// 系统应该被禁用
expect(system.enabled).toBe(false);
consoleSpy.mockRestore();
});
});
describe('已废弃方法', () => {
test('getEntityByName 应该作为 findEntity 的别名工作', () => {
const entity = scene.createEntity('TestEntity');
const found = scene.getEntityByName('TestEntity');
expect(found).toBe(entity);
});
test('getEntitiesByTag 应该作为 findEntitiesByTag 的别名工作', () => {
const entity = scene.createEntity('Entity');
entity.tag = 0x10;
const found = scene.getEntitiesByTag(0x10);
expect(found.length).toBe(1);
expect(found[0]).toBe(entity);
});
});
describe('系统管理扩展', () => {
test('getSystem 应该返回指定类型的系统', () => {
const movementSystem = new MovementSystem();
scene.addEntityProcessor(movementSystem);
const found = scene.getSystem(MovementSystem);
expect(found).toBe(movementSystem);
});
test('getSystem 应该在系统不存在时返回 null', () => {
const found = scene.getSystem(MovementSystem);
expect(found).toBeNull();
});
test('markSystemsOrderDirty 应该标记系统顺序为脏', () => {
const system1 = new MovementSystem();
const system2 = new RenderSystem();
scene.addEntityProcessor(system1);
scene.addEntityProcessor(system2);
// 访问 systems 以清除脏标记
const _ = scene.systems;
// 标记为脏
scene.markSystemsOrderDirty();
// 再次访问应该重新构建缓存
const systems = scene.systems;
expect(systems).toBeDefined();
});
});
describe('延迟缓存清理', () => {
test('addEntity 应该支持延迟缓存清理', () => {
scene.createEntity('Entity1');
const entity2 = new Entity('Entity2', scene.identifierPool.checkOut());
// 延迟缓存清理
scene.addEntity(entity2, true);
expect(scene.entities.count).toBe(2);
});
});
});
});
@@ -0,0 +1,495 @@
import { EntitySerializer, SerializedEntity } from '../../../src/ECS/Serialization/EntitySerializer';
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { HierarchySystem } from '../../../src/ECS/Systems/HierarchySystem';
import { HierarchyComponent } from '../../../src/ECS/Components/HierarchyComponent';
import { ECSComponent } from '../../../src/ECS/Decorators';
import { ComponentRegistry, ComponentType } from '../../../src/ECS/Core/ComponentStorage';
import { Serializable, Serialize } from '../../../src/ECS/Serialization';
@ECSComponent('EntitySerTest_Position')
@Serializable({ version: 1 })
class PositionComponent extends Component {
@Serialize()
public x: number = 0;
@Serialize()
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('EntitySerTest_Velocity')
@Serializable({ version: 1 })
class VelocityComponent extends Component {
@Serialize()
public vx: number = 0;
@Serialize()
public vy: number = 0;
}
describe('EntitySerializer', () => {
let scene: Scene;
let hierarchySystem: HierarchySystem;
let componentRegistry: Map<string, ComponentType>;
beforeEach(() => {
ComponentRegistry.reset();
ComponentRegistry.register(PositionComponent);
ComponentRegistry.register(VelocityComponent);
ComponentRegistry.register(HierarchyComponent);
scene = new Scene({ name: 'EntitySerializerTestScene' });
hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
componentRegistry = ComponentRegistry.getAllComponentNames() as Map<string, ComponentType>;
});
afterEach(() => {
scene.end();
});
describe('serialize', () => {
test('should serialize basic entity properties', () => {
const entity = scene.createEntity('TestEntity');
entity.tag = 42;
entity.active = false;
entity.enabled = false;
entity.updateOrder = 10;
const serialized = EntitySerializer.serialize(entity, false);
expect(serialized.id).toBe(entity.id);
expect(serialized.name).toBe('TestEntity');
expect(serialized.tag).toBe(42);
expect(serialized.active).toBe(false);
expect(serialized.enabled).toBe(false);
expect(serialized.updateOrder).toBe(10);
});
test('should serialize entity with components', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(100, 200));
entity.addComponent(new VelocityComponent());
const serialized = EntitySerializer.serialize(entity, false);
expect(serialized.components.length).toBe(2);
});
test('should serialize entity without children when includeChildren is false', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
const serialized = EntitySerializer.serialize(parent, false, hierarchySystem);
expect(serialized.children).toEqual([]);
});
test('should serialize entity with children when includeChildren is true', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
const serialized = EntitySerializer.serialize(parent, true, hierarchySystem);
expect(serialized.children.length).toBe(2);
expect(serialized.children.some(c => c.name === 'Child1')).toBe(true);
expect(serialized.children.some(c => c.name === 'Child2')).toBe(true);
});
test('should serialize nested hierarchy', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
const serialized = EntitySerializer.serialize(root, true, hierarchySystem);
expect(serialized.children.length).toBe(1);
expect(serialized.children[0].name).toBe('Child');
expect(serialized.children[0].children.length).toBe(1);
expect(serialized.children[0].children[0].name).toBe('Grandchild');
});
test('should include parentId in serialized data', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
const serializedChild = EntitySerializer.serialize(child, false, hierarchySystem);
expect(serializedChild.parentId).toBe(parent.id);
});
});
describe('deserialize', () => {
test('should deserialize basic entity properties', () => {
const serialized: SerializedEntity = {
id: 999,
name: 'DeserializedEntity',
tag: 77,
active: false,
enabled: false,
updateOrder: 5,
components: [],
children: []
};
let nextId = 1;
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => nextId++,
false
);
expect(entity.name).toBe('DeserializedEntity');
expect(entity.tag).toBe(77);
expect(entity.active).toBe(false);
expect(entity.enabled).toBe(false);
expect(entity.updateOrder).toBe(5);
});
test('should preserve IDs when preserveIds is true', () => {
const serialized: SerializedEntity = {
id: 999,
name: 'Entity',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
};
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => 1,
true
);
expect(entity.id).toBe(999);
});
test('should generate new IDs when preserveIds is false', () => {
const serialized: SerializedEntity = {
id: 999,
name: 'Entity',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
};
let nextId = 100;
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => nextId++,
false
);
expect(entity.id).toBe(100);
});
test('should deserialize components', () => {
const serialized: SerializedEntity = {
id: 1,
name: 'Entity',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [
{ type: 'EntitySerTest_Position', version: 1, data: { x: 100, y: 200 } }
],
children: []
};
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => 1,
true,
scene
);
expect(entity.hasComponent(PositionComponent)).toBe(true);
const pos = entity.getComponent(PositionComponent)!;
expect(pos.x).toBe(100);
expect(pos.y).toBe(200);
});
test('should deserialize children with hierarchy relationships', () => {
const serialized: SerializedEntity = {
id: 1,
name: 'Parent',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: [
{
id: 2,
name: 'Child',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
}
]
};
let nextId = 10;
const allEntities = new Map<number, Entity>();
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => nextId++,
false,
scene,
hierarchySystem,
allEntities
);
expect(allEntities.size).toBe(2);
// Add deserialized entities to scene so hierarchySystem can find them
for (const [, e] of allEntities) {
scene.addEntity(e);
}
const children = hierarchySystem.getChildren(entity);
expect(children.length).toBe(1);
expect(children[0].name).toBe('Child');
});
});
describe('serializeEntities', () => {
test('should serialize multiple entities', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const serialized = EntitySerializer.serializeEntities([entity1, entity2], false);
expect(serialized.length).toBe(2);
});
test('should only serialize root entities when includeChildren is true', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, root);
const serialized = EntitySerializer.serializeEntities(
[root, child],
true,
hierarchySystem
);
// Should only have root (child is serialized inside root)
expect(serialized.length).toBe(1);
expect(serialized[0].name).toBe('Root');
expect(serialized[0].children.length).toBe(1);
});
});
describe('deserializeEntities', () => {
test('should deserialize multiple entities', () => {
const serializedEntities: SerializedEntity[] = [
{
id: 1,
name: 'Entity1',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
},
{
id: 2,
name: 'Entity2',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
}
];
let nextId = 100;
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
serializedEntities,
componentRegistry,
() => nextId++,
false,
scene
);
expect(rootEntities.length).toBe(2);
expect(allEntities.size).toBe(2);
});
test('should deserialize entities with nested hierarchy', () => {
const serializedEntities: SerializedEntity[] = [
{
id: 1,
name: 'Root',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: [
{
id: 2,
name: 'Child',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: [
{
id: 3,
name: 'Grandchild',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
}
]
}
]
}
];
let nextId = 10;
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
serializedEntities,
componentRegistry,
() => nextId++,
false,
scene,
hierarchySystem
);
expect(rootEntities.length).toBe(1);
expect(allEntities.size).toBe(3);
});
});
describe('clone', () => {
test('should clone entity with new ID', () => {
const original = scene.createEntity('Original');
original.tag = 99;
original.addComponent(new PositionComponent(50, 100));
// Use serialize + deserialize with scene for proper cloning
const serialized = EntitySerializer.serialize(original, false);
let nextId = 1000;
const cloned = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => nextId++,
false,
scene // Pass scene so components can be added
);
expect(cloned.id).not.toBe(original.id);
expect(cloned.name).toBe('Original');
expect(cloned.tag).toBe(99);
expect(cloned.hasComponent(PositionComponent)).toBe(true);
const clonedPos = cloned.getComponent(PositionComponent)!;
expect(clonedPos.x).toBe(50);
expect(clonedPos.y).toBe(100);
});
test('should clone entity basic properties without components', () => {
// Test the clone method directly with entity that has no components
const original = scene.createEntity('Original');
original.tag = 99;
original.active = false;
original.enabled = false;
original.updateOrder = 5;
let nextId = 1000;
const cloned = EntitySerializer.clone(
original,
componentRegistry,
() => nextId++
);
expect(cloned.id).not.toBe(original.id);
expect(cloned.name).toBe('Original');
expect(cloned.tag).toBe(99);
expect(cloned.active).toBe(false);
expect(cloned.enabled).toBe(false);
expect(cloned.updateOrder).toBe(5);
});
test('should clone entity with children hierarchy data', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
// Serialize with children
const serialized = EntitySerializer.serialize(parent, true, hierarchySystem);
// Verify the serialized data contains children
expect(serialized.children.length).toBe(1);
expect(serialized.children[0].name).toBe('Child');
});
});
describe('edge cases', () => {
test('should handle entity with no components', () => {
const entity = scene.createEntity('Empty');
const serialized = EntitySerializer.serialize(entity, false);
expect(serialized.components).toEqual([]);
});
test('should handle entity with no hierarchy component', () => {
const entity = new Entity('Standalone', 999);
const serialized = EntitySerializer.serialize(entity, true);
expect(serialized.children).toEqual([]);
expect(serialized.parentId).toBeUndefined();
});
test('should handle default values in serialization', () => {
const entity = scene.createEntity('Default');
const serialized = EntitySerializer.serialize(entity, false);
expect(serialized.active).toBe(true);
expect(serialized.enabled).toBe(true);
expect(serialized.updateOrder).toBe(0);
});
});
});
@@ -1,117 +0,0 @@
/**
*
*
*
*/
import { Scene } from '../../../src';
describe('父子实体序列化测试', () => {
let scene: Scene;
beforeEach(() => {
scene = new Scene({ name: 'TestScene' });
});
afterEach(() => {
scene.end();
});
test('应该正确反序列化父子实体层次结构', () => {
// 创建父实体
const parent = scene.createEntity('parent');
parent.tag = 100;
// 创建2个子实体
const child1 = scene.createEntity('child1');
child1.tag = 200;
parent.addChild(child1);
const child2 = scene.createEntity('child2');
child2.tag = 200;
parent.addChild(child2);
// 创建1个顶层实体(对照组)
const topLevel = scene.createEntity('topLevel');
topLevel.tag = 200;
// 验证序列化前的状态
expect(scene.querySystem.queryAll().entities.length).toBe(4);
expect(scene.findEntitiesByTag(100).length).toBe(1);
expect(scene.findEntitiesByTag(200).length).toBe(3);
// 序列化
const serialized = scene.serialize({ format: 'json' });
// 创建新场景并反序列化
const scene2 = new Scene({ name: 'LoadTestScene' });
scene2.deserialize(serialized as string, {
strategy: 'replace',
preserveIds: true,
});
// 验证所有实体都被正确恢复
const allEntities = scene2.querySystem.queryAll().entities;
expect(allEntities.length).toBe(4);
expect(scene2.findEntitiesByTag(100).length).toBe(1);
expect(scene2.findEntitiesByTag(200).length).toBe(3);
// 验证父子关系正确恢复
const restoredParent = scene2.findEntity('parent');
expect(restoredParent).not.toBeNull();
expect(restoredParent!.children.length).toBe(2);
const restoredChild1 = scene2.findEntity('child1');
const restoredChild2 = scene2.findEntity('child2');
expect(restoredChild1).not.toBeNull();
expect(restoredChild2).not.toBeNull();
expect(restoredChild1!.parent).toBe(restoredParent);
expect(restoredChild2!.parent).toBe(restoredParent);
scene2.end();
});
test('应该正确反序列化多层级实体层次结构', () => {
// 创建多层级实体结构:grandparent -> parent -> child
const grandparent = scene.createEntity('grandparent');
grandparent.tag = 1;
const parent = scene.createEntity('parent');
parent.tag = 2;
grandparent.addChild(parent);
const child = scene.createEntity('child');
child.tag = 3;
parent.addChild(child);
expect(scene.querySystem.queryAll().entities.length).toBe(3);
// 序列化
const serialized = scene.serialize({ format: 'json' });
// 创建新场景并反序列化
const scene2 = new Scene({ name: 'LoadTestScene' });
scene2.deserialize(serialized as string, {
strategy: 'replace',
preserveIds: true,
});
// 验证多层级结构正确恢复
expect(scene2.querySystem.queryAll().entities.length).toBe(3);
const restoredGrandparent = scene2.findEntity('grandparent');
const restoredParent = scene2.findEntity('parent');
const restoredChild = scene2.findEntity('child');
expect(restoredGrandparent).not.toBeNull();
expect(restoredParent).not.toBeNull();
expect(restoredChild).not.toBeNull();
expect(restoredParent!.parent).toBe(restoredGrandparent);
expect(restoredChild!.parent).toBe(restoredParent);
expect(restoredGrandparent!.children.length).toBe(1);
expect(restoredParent!.children.length).toBe(1);
scene2.end();
});
});
@@ -0,0 +1,439 @@
import { SceneSerializer } from '../../../src/ECS/Serialization/SceneSerializer';
import { Scene } from '../../../src/ECS/Scene';
import { Component } from '../../../src/ECS/Component';
import { HierarchySystem } from '../../../src/ECS/Systems/HierarchySystem';
import { ECSComponent } from '../../../src/ECS/Decorators';
import { ComponentRegistry, ComponentType } from '../../../src/ECS/Core/ComponentStorage';
import { Serializable, Serialize } from '../../../src/ECS/Serialization';
@ECSComponent('SceneSerTest_Position')
@Serializable({ version: 1 })
class PositionComponent extends Component {
@Serialize()
public x: number = 0;
@Serialize()
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('SceneSerTest_Velocity')
@Serializable({ version: 1 })
class VelocityComponent extends Component {
@Serialize()
public vx: number = 0;
@Serialize()
public vy: number = 0;
}
describe('SceneSerializer', () => {
let scene: Scene;
let componentRegistry: Map<string, ComponentType>;
beforeEach(() => {
ComponentRegistry.reset();
ComponentRegistry.register(PositionComponent);
ComponentRegistry.register(VelocityComponent);
scene = new Scene({ name: 'SceneSerializerTestScene' });
componentRegistry = ComponentRegistry.getAllComponentNames() as Map<string, ComponentType>;
});
afterEach(() => {
scene.end();
});
describe('serialize', () => {
test('should serialize scene to JSON string', () => {
scene.createEntity('Entity1').addComponent(new PositionComponent(10, 20));
scene.createEntity('Entity2').addComponent(new VelocityComponent());
const result = SceneSerializer.serialize(scene);
expect(typeof result).toBe('string');
const parsed = JSON.parse(result as string);
expect(parsed.name).toBe('SceneSerializerTestScene');
expect(parsed.entities.length).toBe(2);
});
test('should serialize scene to binary format', () => {
scene.createEntity('Entity');
const result = SceneSerializer.serialize(scene, { format: 'binary' });
expect(result).toBeInstanceOf(Uint8Array);
});
test('should include metadata when requested', () => {
scene.createEntity('Entity');
const result = SceneSerializer.serialize(scene, { includeMetadata: true });
const parsed = JSON.parse(result as string);
expect(parsed.metadata).toBeDefined();
expect(parsed.metadata.entityCount).toBe(1);
expect(parsed.timestamp).toBeDefined();
});
test('should pretty print JSON when requested', () => {
scene.createEntity('Entity');
const result = SceneSerializer.serialize(scene, { pretty: true });
expect(typeof result).toBe('string');
expect((result as string).includes('\n')).toBe(true);
expect((result as string).includes(' ')).toBe(true);
});
test('should serialize scene data', () => {
scene.sceneData.set('level', 5);
scene.sceneData.set('config', { difficulty: 'hard' });
const result = SceneSerializer.serialize(scene);
const parsed = JSON.parse(result as string);
expect(parsed.sceneData).toBeDefined();
expect(parsed.sceneData.level).toBe(5);
expect(parsed.sceneData.config.difficulty).toBe('hard');
});
test('should serialize with component filter', () => {
scene.createEntity('Entity1').addComponent(new PositionComponent());
scene.createEntity('Entity2').addComponent(new VelocityComponent());
const result = SceneSerializer.serialize(scene, {
components: [PositionComponent]
});
const parsed = JSON.parse(result as string);
// Only entities with PositionComponent should be included
expect(parsed.entities.length).toBe(1);
});
});
describe('deserialize', () => {
test('should deserialize scene from JSON string', () => {
scene.createEntity('Entity1').addComponent(new PositionComponent(100, 200));
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
expect(newScene.entities.count).toBe(1);
const entity = newScene.findEntity('Entity1');
expect(entity).not.toBeNull();
expect(entity!.hasComponent(PositionComponent)).toBe(true);
const pos = entity!.getComponent(PositionComponent)!;
expect(pos.x).toBe(100);
expect(pos.y).toBe(200);
newScene.end();
});
test('should deserialize scene from binary format', () => {
scene.createEntity('BinaryEntity').addComponent(new PositionComponent(50, 75));
const serialized = SceneSerializer.serialize(scene, { format: 'binary' });
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
expect(newScene.entities.count).toBe(1);
const entity = newScene.findEntity('BinaryEntity');
expect(entity).not.toBeNull();
newScene.end();
});
test('should replace existing entities with strategy replace', () => {
scene.createEntity('Original');
const serialized = SceneSerializer.serialize(scene);
const targetScene = new Scene({ name: 'Target' });
targetScene.createEntity('Existing1');
targetScene.createEntity('Existing2');
expect(targetScene.entities.count).toBe(2);
SceneSerializer.deserialize(targetScene, serialized, {
strategy: 'replace',
componentRegistry
});
expect(targetScene.entities.count).toBe(1);
expect(targetScene.findEntity('Original')).not.toBeNull();
expect(targetScene.findEntity('Existing1')).toBeNull();
targetScene.end();
});
test('should merge with existing entities with strategy merge', () => {
scene.createEntity('FromSave');
const serialized = SceneSerializer.serialize(scene);
const targetScene = new Scene({ name: 'Target' });
targetScene.createEntity('Existing');
expect(targetScene.entities.count).toBe(1);
SceneSerializer.deserialize(targetScene, serialized, {
strategy: 'merge',
componentRegistry
});
expect(targetScene.entities.count).toBe(2);
expect(targetScene.findEntity('Existing')).not.toBeNull();
expect(targetScene.findEntity('FromSave')).not.toBeNull();
targetScene.end();
});
test('should restore scene data', () => {
scene.sceneData.set('weather', 'sunny');
scene.sceneData.set('time', 12.5);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
expect(newScene.sceneData.get('weather')).toBe('sunny');
expect(newScene.sceneData.get('time')).toBe(12.5);
newScene.end();
});
test('should call migration function when versions differ', () => {
scene.createEntity('Entity');
const serialized = SceneSerializer.serialize(scene);
// Manually modify version
const parsed = JSON.parse(serialized as string);
parsed.version = 0;
const modifiedSerialized = JSON.stringify(parsed);
const migrationFn = jest.fn((oldVersion, newVersion, data) => {
expect(oldVersion).toBe(0);
return data;
});
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, modifiedSerialized, {
componentRegistry,
migration: migrationFn
});
expect(migrationFn).toHaveBeenCalled();
newScene.end();
});
test('should throw on invalid JSON', () => {
const newScene = new Scene({ name: 'NewScene' });
expect(() => {
SceneSerializer.deserialize(newScene, 'invalid json{{{', { componentRegistry });
}).toThrow();
newScene.end();
});
});
describe('validate', () => {
test('should validate correct save data', () => {
scene.createEntity('Entity');
const serialized = SceneSerializer.serialize(scene);
const result = SceneSerializer.validate(serialized as string);
expect(result.valid).toBe(true);
expect(result.version).toBe(1);
});
test('should return errors for missing version', () => {
const invalid = JSON.stringify({ entities: [], componentTypeRegistry: [] });
const result = SceneSerializer.validate(invalid);
expect(result.valid).toBe(false);
expect(result.errors).toContain('Missing version field');
});
test('should return errors for missing entities', () => {
const invalid = JSON.stringify({ version: 1, componentTypeRegistry: [] });
const result = SceneSerializer.validate(invalid);
expect(result.valid).toBe(false);
expect(result.errors).toContain('Missing or invalid entities field');
});
test('should return errors for missing componentTypeRegistry', () => {
const invalid = JSON.stringify({ version: 1, entities: [] });
const result = SceneSerializer.validate(invalid);
expect(result.valid).toBe(false);
expect(result.errors).toContain('Missing or invalid componentTypeRegistry field');
});
test('should handle JSON parse errors', () => {
const result = SceneSerializer.validate('not valid json');
expect(result.valid).toBe(false);
expect(result.errors).toBeDefined();
expect(result.errors![0]).toContain('JSON parse error');
});
});
describe('getInfo', () => {
test('should return info from save data', () => {
scene.name = 'InfoTestScene';
scene.createEntity('Entity1');
scene.createEntity('Entity2');
scene.createEntity('Entity3');
const serialized = SceneSerializer.serialize(scene);
const info = SceneSerializer.getInfo(serialized as string);
expect(info).not.toBeNull();
expect(info!.name).toBe('InfoTestScene');
expect(info!.entityCount).toBe(3);
expect(info!.version).toBe(1);
});
test('should return null for invalid data', () => {
const info = SceneSerializer.getInfo('invalid');
expect(info).toBeNull();
});
test('should include timestamp when present', () => {
scene.createEntity('Entity');
const serialized = SceneSerializer.serialize(scene, { includeMetadata: true });
const info = SceneSerializer.getInfo(serialized as string);
expect(info!.timestamp).toBeDefined();
});
});
describe('scene data serialization', () => {
test('should serialize Date objects', () => {
const date = new Date('2024-01-01T00:00:00Z');
scene.sceneData.set('createdAt', date);
const serialized = SceneSerializer.serialize(scene);
const parsed = JSON.parse(serialized as string);
expect(parsed.sceneData.createdAt.__type).toBe('Date');
});
test('should deserialize Date objects', () => {
const date = new Date('2024-01-01T00:00:00Z');
scene.sceneData.set('createdAt', date);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
const restoredDate = newScene.sceneData.get('createdAt');
expect(restoredDate).toBeInstanceOf(Date);
expect(restoredDate.getTime()).toBe(date.getTime());
newScene.end();
});
test('should serialize Map objects', () => {
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
scene.sceneData.set('mapping', map);
const serialized = SceneSerializer.serialize(scene);
const parsed = JSON.parse(serialized as string);
expect(parsed.sceneData.mapping.__type).toBe('Map');
});
test('should deserialize Map objects', () => {
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
scene.sceneData.set('mapping', map);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
const restoredMap = newScene.sceneData.get('mapping');
expect(restoredMap).toBeInstanceOf(Map);
expect(restoredMap.get('key1')).toBe('value1');
expect(restoredMap.get('key2')).toBe('value2');
newScene.end();
});
test('should serialize Set objects', () => {
const set = new Set([1, 2, 3]);
scene.sceneData.set('numbers', set);
const serialized = SceneSerializer.serialize(scene);
const parsed = JSON.parse(serialized as string);
expect(parsed.sceneData.numbers.__type).toBe('Set');
});
test('should deserialize Set objects', () => {
const set = new Set([1, 2, 3]);
scene.sceneData.set('numbers', set);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
const restoredSet = newScene.sceneData.get('numbers');
expect(restoredSet).toBeInstanceOf(Set);
expect(restoredSet.has(1)).toBe(true);
expect(restoredSet.has(2)).toBe(true);
expect(restoredSet.has(3)).toBe(true);
newScene.end();
});
});
describe('hierarchy serialization', () => {
test('should serialize and deserialize entity hierarchy', () => {
const hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
const root = scene.createEntity('Root');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
hierarchySystem.setParent(child1, root);
hierarchySystem.setParent(child2, root);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
const newHierarchySystem = new HierarchySystem();
newScene.addSystem(newHierarchySystem);
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
const newRoot = newScene.findEntity('Root');
expect(newRoot).not.toBeNull();
const children = newHierarchySystem.getChildren(newRoot!);
expect(children.length).toBe(2);
newScene.end();
});
});
});
@@ -1,629 +0,0 @@
/**
*
*/
import { Component } from '../../../src/ECS/Component';
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import {
Serializable,
Serialize,
SerializeAsMap,
SerializeAsSet,
IgnoreSerialization,
ComponentSerializer,
EntitySerializer,
SceneSerializer,
VersionMigrationManager,
MigrationBuilder
} from '../../../src/ECS/Serialization';
import { ECSComponent } from '../../../src/ECS/Decorators';
import { ComponentRegistry } from '../../../src/ECS/Core/ComponentStorage';
// 测试组件定义
@ECSComponent('Position')
@Serializable({ version: 1 })
class PositionComponent extends Component {
@Serialize()
public x: number = 0;
@Serialize()
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('Velocity')
@Serializable({ version: 1 })
class VelocityComponent extends Component {
@Serialize()
public dx: number = 0;
@Serialize()
public dy: number = 0;
}
@ECSComponent('Player')
@Serializable({ version: 1 })
class PlayerComponent extends Component {
@Serialize()
public name: string = '';
@Serialize()
public level: number = 1;
@SerializeAsMap()
public inventory: Map<string, number> = new Map();
@SerializeAsSet()
public tags: Set<string> = new Set();
@IgnoreSerialization()
public tempCache: any = null;
}
@ECSComponent('Health')
@Serializable({ version: 1 })
class HealthComponent extends Component {
@Serialize()
public current: number = 100;
@Serialize()
public max: number = 100;
}
// 非可序列化组件
class NonSerializableComponent extends Component {
public data: any = null;
}
describe('ECS Serialization System', () => {
let scene: Scene;
beforeEach(() => {
// 清空测试环境
ComponentRegistry.reset();
// 重新注册测试组件(因为reset会清空所有注册)
ComponentRegistry.register(PositionComponent);
ComponentRegistry.register(VelocityComponent);
ComponentRegistry.register(PlayerComponent);
ComponentRegistry.register(HealthComponent);
// 创建测试场景
scene = new Scene();
});
describe('Component Serialization', () => {
it('should serialize a simple component', () => {
const position = new PositionComponent(100, 200);
const serialized = ComponentSerializer.serialize(position);
expect(serialized).not.toBeNull();
expect(serialized!.type).toBe('Position');
expect(serialized!.version).toBe(1);
expect(serialized!.data.x).toBe(100);
expect(serialized!.data.y).toBe(200);
});
it('should deserialize a simple component', () => {
const serializedData = {
type: 'Position',
version: 1,
data: { x: 150, y: 250 }
};
const registry = ComponentRegistry.getAllComponentNames() as Map<string, any>;
const component = ComponentSerializer.deserialize(serializedData, registry);
expect(component).not.toBeNull();
expect(component).toBeInstanceOf(PositionComponent);
expect((component as PositionComponent).x).toBe(150);
expect((component as PositionComponent).y).toBe(250);
});
it('should serialize Map fields', () => {
const player = new PlayerComponent();
player.name = 'Hero';
player.level = 5;
player.inventory.set('sword', 1);
player.inventory.set('potion', 10);
const serialized = ComponentSerializer.serialize(player);
expect(serialized).not.toBeNull();
expect(serialized!.data.inventory).toEqual([
['sword', 1],
['potion', 10]
]);
});
it('should deserialize Map fields', () => {
const serializedData = {
type: 'Player',
version: 1,
data: {
name: 'Hero',
level: 5,
inventory: [
['sword', 1],
['potion', 10]
],
tags: ['warrior', 'hero']
}
};
const registry = ComponentRegistry.getAllComponentNames() as Map<string, any>;
const component = ComponentSerializer.deserialize(
serializedData,
registry
) as PlayerComponent;
expect(component).not.toBeNull();
expect(component.inventory.get('sword')).toBe(1);
expect(component.inventory.get('potion')).toBe(10);
expect(component.tags.has('warrior')).toBe(true);
expect(component.tags.has('hero')).toBe(true);
});
it('should ignore fields marked with @IgnoreSerialization', () => {
const player = new PlayerComponent();
player.tempCache = { foo: 'bar' };
const serialized = ComponentSerializer.serialize(player);
expect(serialized).not.toBeNull();
expect(serialized!.data.tempCache).toBeUndefined();
});
it('should return null for non-serializable components', () => {
const nonSerializable = new NonSerializableComponent();
const serialized = ComponentSerializer.serialize(nonSerializable);
expect(serialized).toBeNull();
});
});
describe('Entity Serialization', () => {
it('should serialize an entity with components', () => {
const entity = scene.createEntity('Player');
entity.addComponent(new PositionComponent(50, 100));
entity.addComponent(new VelocityComponent());
entity.tag = 10;
const serialized = EntitySerializer.serialize(entity);
expect(serialized.id).toBe(entity.id);
expect(serialized.name).toBe('Player');
expect(serialized.tag).toBe(10);
expect(serialized.components.length).toBe(2);
});
it('should serialize entity hierarchy', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
parent.addComponent(new PositionComponent(0, 0));
child.addComponent(new PositionComponent(10, 10));
parent.addChild(child);
const serialized = EntitySerializer.serialize(parent);
expect(serialized.children.length).toBe(1);
expect(serialized.children[0].id).toBe(child.id);
expect(serialized.children[0].name).toBe('Child');
});
it('should deserialize an entity', () => {
const serializedEntity = {
id: 1,
name: 'TestEntity',
tag: 5,
active: true,
enabled: true,
updateOrder: 0,
components: [
{
type: 'Position',
version: 1,
data: { x: 100, y: 200 }
}
],
children: []
};
const registry = ComponentRegistry.getAllComponentNames() as Map<string, any>;
let idCounter = 10;
const entity = EntitySerializer.deserialize(
serializedEntity,
registry,
() => idCounter++,
false,
scene
);
expect(entity.name).toBe('TestEntity');
expect(entity.tag).toBe(5);
expect(entity.components.length).toBe(1);
});
});
describe('Scene Serialization', () => {
let scene: Scene;
beforeEach(() => {
scene = new Scene({ name: 'TestScene' });
});
afterEach(() => {
scene.end();
});
it('should serialize a scene', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent(10, 20));
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new PlayerComponent());
const saveData = scene.serialize({ format: 'json', pretty: true });
expect(saveData).toBeTruthy();
expect(typeof saveData).toBe('string');
const parsed = JSON.parse(saveData as string);
expect(parsed.name).toBe('TestScene');
expect(parsed.version).toBe(1);
expect(parsed.entities.length).toBe(2);
});
it('should deserialize a scene with replace strategy', () => {
// 创建初始实体
const entity1 = scene.createEntity('Initial');
entity1.addComponent(new PositionComponent(0, 0));
// 序列化
const entity2 = scene.createEntity('ToSave');
entity2.addComponent(new PositionComponent(100, 100));
const saveData = scene.serialize();
// 清空并重新加载
scene.deserialize(saveData, {
strategy: 'replace',
// componentRegistry会自动从ComponentRegistry获取
});
expect(scene.entities.count).toBeGreaterThan(0);
});
it('should filter components during serialization', () => {
const entity = scene.createEntity('Mixed');
entity.addComponent(new PositionComponent(1, 2));
entity.addComponent(new PlayerComponent());
entity.addComponent(new HealthComponent());
const saveData = scene.serialize({
components: [PositionComponent, PlayerComponent],
format: 'json'
});
const parsed = JSON.parse(saveData as string);
expect(parsed.entities.length).toBeGreaterThan(0);
});
it('should preserve entity hierarchy', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
parent.addChild(child);
parent.addComponent(new PositionComponent(0, 0));
child.addComponent(new PositionComponent(10, 10));
const saveData = scene.serialize({ format: 'json' });
const parsed = JSON.parse(saveData as string);
// 只有父实体在顶层
expect(parsed.entities.length).toBe(1);
expect(parsed.entities[0].children.length).toBe(1);
});
it('should validate save data', () => {
const entity = scene.createEntity('Test');
entity.addComponent(new PositionComponent(5, 5));
const saveData = scene.serialize({ format: 'json' });
const validation = SceneSerializer.validate(saveData as string);
expect(validation.valid).toBe(true);
expect(validation.version).toBe(1);
});
it('should get save data info', () => {
const entity = scene.createEntity('InfoTest');
entity.addComponent(new PositionComponent(1, 1));
const saveData = scene.serialize({ format: 'json' });
const info = SceneSerializer.getInfo(saveData as string);
expect(info).not.toBeNull();
expect(info!.name).toBe('TestScene');
expect(info!.version).toBe(1);
});
});
describe('Version Migration', () => {
@ECSComponent('OldPlayer')
@Serializable({ version: 1 })
class OldPlayerV1 extends Component {
@Serialize()
public name: string = '';
@Serialize()
public hp: number = 100;
}
@ECSComponent('OldPlayer')
@Serializable({ version: 2 })
class OldPlayerV2 extends Component {
@Serialize()
public name: string = '';
@Serialize()
public health: number = 100; // 重命名了字段
@Serialize()
public maxHealth: number = 100; // 新增字段
}
beforeEach(() => {
VersionMigrationManager.clearMigrations();
});
it('should migrate component from v1 to v2', () => {
// 注册迁移
VersionMigrationManager.registerComponentMigration(
'OldPlayer',
1,
2,
(data) => {
return {
name: data.name,
health: data.hp,
maxHealth: data.hp
};
}
);
const v1Data = {
type: 'OldPlayer',
version: 1,
data: { name: 'Hero', hp: 80 }
};
const migrated = VersionMigrationManager.migrateComponent(v1Data, 2);
expect(migrated.version).toBe(2);
expect(migrated.data.health).toBe(80);
expect(migrated.data.maxHealth).toBe(80);
expect(migrated.data.hp).toBeUndefined();
});
it('should use MigrationBuilder for component migration', () => {
new MigrationBuilder()
.forComponent('Player')
.fromVersionToVersion(1, 2)
.migrate((data: any) => {
data.experience = 0;
return data;
});
expect(VersionMigrationManager.canMigrateComponent('Player', 1, 2)).toBe(true);
});
it('should check migration path availability', () => {
VersionMigrationManager.registerComponentMigration('Test', 1, 2, (d) => d);
VersionMigrationManager.registerComponentMigration('Test', 2, 3, (d) => d);
expect(VersionMigrationManager.canMigrateComponent('Test', 1, 3)).toBe(true);
expect(VersionMigrationManager.canMigrateComponent('Test', 1, 4)).toBe(false);
});
it('should get migration path', () => {
VersionMigrationManager.registerComponentMigration('PathTest', 1, 2, (d) => d);
VersionMigrationManager.registerComponentMigration('PathTest', 2, 3, (d) => d);
const path = VersionMigrationManager.getComponentMigrationPath('PathTest');
expect(path).toEqual([1, 2]);
});
});
// ComponentTypeRegistry已被移除,现在使用ComponentRegistry自动管理组件类型
describe('Integration Tests', () => {
it('should perform full save/load cycle', () => {
const scene1 = new Scene({ name: 'SaveTest' });
// 创建复杂实体
const player = scene1.createEntity('Player');
const playerComp = new PlayerComponent();
playerComp.name = 'TestHero';
playerComp.level = 10;
playerComp.inventory.set('sword', 1);
playerComp.inventory.set('shield', 1);
playerComp.tags.add('warrior');
player.addComponent(playerComp);
player.addComponent(new PositionComponent(100, 200));
player.addComponent(new HealthComponent());
// 创建子实体
const weapon = scene1.createEntity('Weapon');
weapon.addComponent(new PositionComponent(5, 0));
player.addChild(weapon);
// 序列化
const saveData = scene1.serialize();
// 新场景
const scene2 = new Scene({ name: 'LoadTest' });
// 反序列化
scene2.deserialize(saveData, {
strategy: 'replace',
// componentRegistry会自动从ComponentRegistry获取
});
// 验证
const loadedPlayer = scene2.findEntity('Player');
expect(loadedPlayer).not.toBeNull();
const loadedPlayerComp = loadedPlayer!.getComponent(PlayerComponent as any) as PlayerComponent;
expect(loadedPlayerComp).not.toBeNull();
expect(loadedPlayerComp.name).toBe('TestHero');
expect(loadedPlayerComp.level).toBe(10);
expect(loadedPlayerComp.inventory.get('sword')).toBe(1);
expect(loadedPlayerComp.tags.has('warrior')).toBe(true);
// 验证层级结构
expect(loadedPlayer!.childCount).toBe(1);
scene1.end();
scene2.end();
});
it('should serialize and deserialize scene custom data', () => {
const scene1 = new Scene({ name: 'SceneDataTest' });
// 设置场景自定义数据
scene1.sceneData.set('weather', 'rainy');
scene1.sceneData.set('timeOfDay', 14.5);
scene1.sceneData.set('difficulty', 'hard');
scene1.sceneData.set('checkpoint', { x: 100, y: 200 });
scene1.sceneData.set('tags', new Set(['action', 'adventure']));
scene1.sceneData.set('metadata', new Map([['author', 'test'], ['version', '1.0']]));
// 序列化
const saveData = scene1.serialize();
// 新场景
const scene2 = new Scene({ name: 'LoadTest' });
// 反序列化
scene2.deserialize(saveData, {
strategy: 'replace',
// componentRegistry会自动从ComponentRegistry获取
});
// 验证场景数据
expect(scene2.sceneData.get('weather')).toBe('rainy');
expect(scene2.sceneData.get('timeOfDay')).toBe(14.5);
expect(scene2.sceneData.get('difficulty')).toBe('hard');
expect(scene2.sceneData.get('checkpoint')).toEqual({ x: 100, y: 200 });
const tags = scene2.sceneData.get('tags');
expect(tags).toBeInstanceOf(Set);
expect(tags.has('action')).toBe(true);
expect(tags.has('adventure')).toBe(true);
const metadata = scene2.sceneData.get('metadata');
expect(metadata).toBeInstanceOf(Map);
expect(metadata.get('author')).toBe('test');
expect(metadata.get('version')).toBe('1.0');
scene1.end();
scene2.end();
});
it('should serialize and deserialize using binary format', () => {
const scene1 = new Scene({ name: 'BinaryTest' });
// 创建测试数据
const player = scene1.createEntity('Player');
const playerComp = new PlayerComponent();
playerComp.name = 'BinaryHero';
playerComp.level = 5;
playerComp.inventory.set('sword', 1);
player.addComponent(playerComp);
player.addComponent(new PositionComponent(100, 200));
scene1.sceneData.set('weather', 'sunny');
scene1.sceneData.set('score', 9999);
// 二进制序列化
const binaryData = scene1.serialize({ format: 'binary' });
// 验证是Uint8Array类型
expect(binaryData instanceof Uint8Array).toBe(true);
expect((binaryData as Uint8Array).length).toBeGreaterThan(0);
// 新场景反序列化二进制数据
const scene2 = new Scene({ name: 'LoadTest' });
scene2.deserialize(binaryData, {
strategy: 'replace',
// componentRegistry会自动从ComponentRegistry获取
});
// 验证数据完整性
const loadedPlayer = scene2.findEntity('Player');
expect(loadedPlayer).not.toBeNull();
const loadedPlayerComp = loadedPlayer!.getComponent(PlayerComponent as any) as PlayerComponent;
expect(loadedPlayerComp.name).toBe('BinaryHero');
expect(loadedPlayerComp.level).toBe(5);
expect(loadedPlayerComp.inventory.get('sword')).toBe(1);
const loadedPos = loadedPlayer!.getComponent(PositionComponent as any) as PositionComponent;
expect(loadedPos.x).toBe(100);
expect(loadedPos.y).toBe(200);
expect(scene2.sceneData.get('weather')).toBe('sunny');
expect(scene2.sceneData.get('score')).toBe(9999);
scene1.end();
scene2.end();
});
it('should handle complex nested data in binary format', () => {
const scene1 = new Scene({ name: 'NestedBinaryTest' });
// 复杂嵌套数据
scene1.sceneData.set('config', {
graphics: {
quality: 'high',
resolution: { width: 1920, height: 1080 }
},
audio: {
masterVolume: 0.8,
effects: new Map([['music', 0.7], ['sfx', 0.9]])
},
tags: new Set(['multiplayer', 'ranked']),
timestamp: new Date('2024-01-01')
});
// 二进制序列化
const binaryData = scene1.serialize({ format: 'binary' });
// 反序列化
const scene2 = new Scene({ name: 'LoadTest' });
scene2.deserialize(binaryData, {
// componentRegistry会自动从ComponentRegistry获取
});
const config = scene2.sceneData.get('config');
expect(config.graphics.quality).toBe('high');
expect(config.graphics.resolution.width).toBe(1920);
expect(config.audio.masterVolume).toBe(0.8);
expect(config.audio.effects.get('music')).toBe(0.7);
expect(config.tags.has('multiplayer')).toBe(true);
expect(config.timestamp).toBeInstanceOf(Date);
scene1.end();
scene2.end();
});
});
});
-145
View File
@@ -1,145 +0,0 @@
/**
* Scene查询方法测试
*/
import { Component } from '../src/ECS/Component';
import { Entity } from '../src/ECS/Entity';
import { Scene } from '../src/ECS/Scene';
import { Core } from '../src/Core';
import { ECSComponent } from '../src/ECS/Decorators';
import { EntitySystem } from '../src/ECS/Systems/EntitySystem';
@ECSComponent('Position')
class Position extends Component {
constructor(public x: number = 0, public y: number = 0) {
super();
}
}
@ECSComponent('Velocity')
class Velocity extends Component {
constructor(public dx: number = 0, public dy: number = 0) {
super();
}
}
@ECSComponent('Disabled')
class Disabled extends Component {}
describe('Scene查询方法', () => {
let scene: Scene;
beforeEach(() => {
Core.create({ debug: false, enableEntitySystems: true });
scene = new Scene();
scene.initialize();
});
afterEach(() => {
scene.end();
});
describe('基础查询方法', () => {
test('queryAll 查询拥有所有组件的实体', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
e1.addComponent(new Velocity(1, 2));
const e2 = scene.createEntity('E2');
e2.addComponent(new Position(30, 40));
const result = scene.queryAll(Position, Velocity);
expect(result.entities).toHaveLength(1);
expect(result.entities[0]).toBe(e1);
});
test('queryAny 查询拥有任意组件的实体', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
const e2 = scene.createEntity('E2');
e2.addComponent(new Velocity(1, 2));
const e3 = scene.createEntity('E3');
e3.addComponent(new Disabled());
const result = scene.queryAny(Position, Velocity);
expect(result.entities).toHaveLength(2);
});
test('queryNone 查询不包含指定组件的实体', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
const e2 = scene.createEntity('E2');
e2.addComponent(new Position(30, 40));
e2.addComponent(new Disabled());
const result = scene.queryNone(Disabled);
expect(result.entities).toHaveLength(1);
expect(result.entities[0]).toBe(e1);
});
});
describe('TypedQueryBuilder', () => {
test('scene.query() 创建类型安全的查询构建器', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
e1.addComponent(new Velocity(1, 2));
const e2 = scene.createEntity('E2');
e2.addComponent(new Position(30, 40));
e2.addComponent(new Velocity(3, 4));
e2.addComponent(new Disabled());
// 构建查询
const query = scene.query()
.withAll(Position, Velocity)
.withNone(Disabled);
const matcher = query.buildMatcher();
// 创建System使用这个matcher
class TestSystem extends EntitySystem {
public processedCount = 0;
constructor() {
super(matcher);
}
protected override process(entities: readonly Entity[]): void {
this.processedCount = entities.length;
}
}
const system = new TestSystem();
scene.addSystem(system);
scene.update();
// 应该只处理e1e2被Disabled排除)
expect(system.processedCount).toBe(1);
});
test('TypedQueryBuilder 支持复杂查询', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
e1.tag = 100;
const e2 = scene.createEntity('E2');
e2.addComponent(new Position(30, 40));
e2.tag = 200;
const query = scene.query()
.withAll(Position)
.withTag(100);
const condition = query.getCondition();
expect(condition.all).toContain(Position as any);
expect(condition.tag).toBe(100);
});
});
});
-205
View File
@@ -1,205 +0,0 @@
/**
* TypeScript类型推断测试
*
*
*/
import { Component } from '../src/ECS/Component';
import { Entity } from '../src/ECS/Entity';
import { Scene } from '../src/ECS/Scene';
import { Core } from '../src/Core';
import { ECSComponent } from '../src/ECS/Decorators';
import { requireComponent, tryGetComponent, getComponents } from '../src/ECS/TypedEntity';
// 测试组件
@ECSComponent('Position')
class Position extends Component {
constructor(public x: number = 0, public y: number = 0) {
super();
}
}
@ECSComponent('Velocity')
class Velocity extends Component {
constructor(public dx: number = 0, public dy: number = 0) {
super();
}
}
@ECSComponent('Health')
class Health extends Component {
constructor(public value: number = 100, public maxValue: number = 100) {
super();
}
}
describe('TypeScript类型推断', () => {
let scene: Scene;
let entity: Entity;
beforeEach(() => {
Core.create({ debug: false, enableEntitySystems: true });
scene = new Scene();
scene.initialize();
entity = scene.createEntity('TestEntity');
});
afterEach(() => {
scene.end();
});
describe('Entity.getComponent 类型推断', () => {
test('getComponent 应该自动推断正确的返回类型', () => {
entity.addComponent(new Position(100, 200));
// 类型推断为 Position | null
const position = entity.getComponent(Position);
// TypeScript应该知道position可能为null
expect(position).not.toBeNull();
// 在null检查后,TypeScript应该知道position是Position类型
if (position) {
expect(position.x).toBe(100);
expect(position.y).toBe(200);
// 这些操作应该有完整的类型提示
position.x += 10;
position.y += 20;
expect(position.x).toBe(110);
expect(position.y).toBe(220);
}
});
test('getComponent 返回null时类型安全', () => {
// 实体没有Velocity组件
const velocity = entity.getComponent(Velocity);
// 应该返回null
expect(velocity).toBeNull();
});
test('多个不同类型组件的类型推断', () => {
entity.addComponent(new Position(10, 20));
entity.addComponent(new Velocity(1, 2));
entity.addComponent(new Health(100));
const pos = entity.getComponent(Position);
const vel = entity.getComponent(Velocity);
const health = entity.getComponent(Health);
// 所有组件都应该被正确推断
if (pos && vel && health) {
// Position类型的字段
pos.x = 50;
pos.y = 60;
// Velocity类型的字段
vel.dx = 5;
vel.dy = 10;
// Health类型的字段
health.value = 80;
health.maxValue = 150;
expect(pos.x).toBe(50);
expect(vel.dx).toBe(5);
expect(health.value).toBe(80);
}
});
});
describe('Entity.createComponent 类型推断', () => {
test('createComponent 应该自动推断返回类型', () => {
// 应该推断为Position类型(非null
const position = entity.createComponent(Position, 100, 200);
expect(position).toBeInstanceOf(Position);
expect(position.x).toBe(100);
expect(position.y).toBe(200);
// 应该有完整的类型提示
position.x = 300;
expect(position.x).toBe(300);
});
});
describe('Entity.hasComponent 类型守卫', () => {
test('hasComponent 可以用作类型守卫', () => {
entity.addComponent(new Position(10, 20));
if (entity.hasComponent(Position)) {
// 在这个作用域内,我们知道组件存在
const pos = entity.getComponent(Position)!;
pos.x = 100;
expect(pos.x).toBe(100);
}
});
});
describe('Entity.getOrCreateComponent 类型推断', () => {
test('getOrCreateComponent 应该自动推断返回类型', () => {
// 第一次调用:创建新组件
const position1 = entity.getOrCreateComponent(Position, 50, 60);
expect(position1.x).toBe(50);
expect(position1.y).toBe(60);
// 第二次调用:返回已存在的组件
const position2 = entity.getOrCreateComponent(Position, 100, 200);
// 应该是同一个组件
expect(position2).toBe(position1);
expect(position2.x).toBe(50); // 值未改变
});
});
describe('TypedEntity工具函数类型推断', () => {
test('requireComponent 返回非空类型', () => {
entity.addComponent(new Position(100, 200));
// requireComponent 返回非null类型
const position = requireComponent(entity, Position);
// 不需要null检查
expect(position.x).toBe(100);
position.x = 300;
expect(position.x).toBe(300);
});
test('tryGetComponent 返回可选类型', () => {
entity.addComponent(new Position(50, 50));
const position = tryGetComponent(entity, Position);
// 应该返回组件
expect(position).toBeDefined();
if (position) {
expect(position.x).toBe(50);
}
// 不存在的组件返回undefined
const velocity = tryGetComponent(entity, Velocity);
expect(velocity).toBeUndefined();
});
test('getComponents 批量获取组件', () => {
entity.addComponent(new Position(10, 20));
entity.addComponent(new Velocity(1, 2));
entity.addComponent(new Health(100));
const [pos, vel, health] = getComponents(entity, Position, Velocity, Health);
// 应该推断为数组类型
expect(pos).not.toBeNull();
expect(vel).not.toBeNull();
expect(health).not.toBeNull();
if (pos && vel && health) {
expect(pos.x).toBe(10);
expect(vel.dx).toBe(1);
expect(health.value).toBe(100);
}
});
});
});
@@ -0,0 +1,410 @@
import { EntityDataCollector } from '../../../src/Utils/Debug/EntityDataCollector';
import { Scene } from '../../../src/ECS/Scene';
import { Component } from '../../../src/ECS/Component';
import { HierarchySystem } from '../../../src/ECS/Systems/HierarchySystem';
import { HierarchyComponent } from '../../../src/ECS/Components/HierarchyComponent';
import { ECSComponent } from '../../../src/ECS/Decorators';
@ECSComponent('TestPosition')
class PositionComponent extends Component {
public x: number = 0;
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('TestVelocity')
class VelocityComponent extends Component {
public vx: number = 0;
public vy: number = 0;
}
describe('EntityDataCollector', () => {
let collector: EntityDataCollector;
let scene: Scene;
beforeEach(() => {
collector = new EntityDataCollector();
scene = new Scene({ name: 'TestScene' });
});
afterEach(() => {
scene.end();
});
describe('collectEntityData', () => {
test('should return empty data when scene is null', () => {
const data = collector.collectEntityData(null);
expect(data.totalEntities).toBe(0);
expect(data.activeEntities).toBe(0);
expect(data.pendingAdd).toBe(0);
expect(data.pendingRemove).toBe(0);
expect(data.entitiesPerArchetype).toEqual([]);
expect(data.topEntitiesByComponents).toEqual([]);
});
test('should return empty data when scene is undefined', () => {
const data = collector.collectEntityData(undefined);
expect(data.totalEntities).toBe(0);
expect(data.activeEntities).toBe(0);
});
test('should collect entity data from scene', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent(10, 20));
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new VelocityComponent());
const data = collector.collectEntityData(scene);
expect(data.totalEntities).toBe(2);
expect(data.activeEntities).toBeGreaterThanOrEqual(0);
});
test('should collect archetype distribution', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent());
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new PositionComponent());
const entity3 = scene.createEntity('Entity3');
entity3.addComponent(new VelocityComponent());
const data = collector.collectEntityData(scene);
expect(data.entitiesPerArchetype.length).toBeGreaterThan(0);
});
});
describe('getRawEntityList', () => {
test('should return empty array when scene is null', () => {
const list = collector.getRawEntityList(null);
expect(list).toEqual([]);
});
test('should return raw entity list from scene', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent(10, 20));
entity1.tag = 0x01;
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new VelocityComponent());
const list = collector.getRawEntityList(scene);
expect(list.length).toBe(2);
expect(list[0].name).toBe('Entity1');
expect(list[0].componentCount).toBe(1);
expect(list[0].tag).toBe(0x01);
});
test('should include hierarchy information', () => {
const hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
const list = collector.getRawEntityList(scene);
const childInfo = list.find(e => e.name === 'Child');
expect(childInfo).toBeDefined();
expect(childInfo!.parentId).toBe(parent.id);
expect(childInfo!.depth).toBe(1);
});
});
describe('getEntityDetails', () => {
test('should return null when scene is null', () => {
const details = collector.getEntityDetails(1, null);
expect(details).toBeNull();
});
test('should return null when entity not found', () => {
const details = collector.getEntityDetails(9999, scene);
expect(details).toBeNull();
});
test('should return entity details', () => {
const entity = scene.createEntity('TestEntity');
entity.addComponent(new PositionComponent(100, 200));
entity.tag = 42;
const details = collector.getEntityDetails(entity.id, scene);
expect(details).not.toBeNull();
expect(details.componentCount).toBe(1);
expect(details.scene).toBeDefined();
});
test('should handle errors gracefully', () => {
const details = collector.getEntityDetails(-1, scene);
expect(details).toBeNull();
});
});
describe('collectEntityDataWithMemory', () => {
test('should return empty data when scene is null', () => {
const data = collector.collectEntityDataWithMemory(null);
expect(data.totalEntities).toBe(0);
expect(data.entityHierarchy).toEqual([]);
expect(data.entityDetailsMap).toEqual({});
});
test('should collect entity data with memory information', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(10, 20));
const data = collector.collectEntityDataWithMemory(scene);
expect(data.totalEntities).toBe(1);
expect(data.topEntitiesByComponents.length).toBeGreaterThan(0);
});
test('should include entity details map', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent());
const data = collector.collectEntityDataWithMemory(scene);
expect(data.entityDetailsMap).toBeDefined();
expect(data.entityDetailsMap![entity.id]).toBeDefined();
});
test('should build entity hierarchy tree', () => {
const hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
const root = scene.createEntity('Root');
root.addComponent(new HierarchyComponent());
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, root);
const data = collector.collectEntityDataWithMemory(scene);
expect(data.entityHierarchy).toBeDefined();
expect(data.entityHierarchy!.length).toBe(1);
expect(data.entityHierarchy![0].name).toBe('Root');
});
});
describe('estimateEntityMemoryUsage', () => {
test('should estimate memory for entity', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(10, 20));
const memory = collector.estimateEntityMemoryUsage(entity);
expect(memory).toBeGreaterThanOrEqual(0);
expect(typeof memory).toBe('number');
});
test('should return 0 for invalid entity', () => {
const memory = collector.estimateEntityMemoryUsage(null);
expect(memory).toBe(0);
});
test('should handle errors and return 0', () => {
const badEntity = { components: null };
const memory = collector.estimateEntityMemoryUsage(badEntity);
expect(memory).toBeGreaterThanOrEqual(0);
});
});
describe('calculateObjectSize', () => {
test('should return 0 for null/undefined', () => {
expect(collector.calculateObjectSize(null)).toBe(0);
expect(collector.calculateObjectSize(undefined)).toBe(0);
});
test('should calculate size for simple object', () => {
const obj = { x: 10, y: 20, name: 'test' };
const size = collector.calculateObjectSize(obj);
expect(size).toBeGreaterThan(0);
});
test('should respect exclude keys', () => {
const obj = { x: 10, excluded: 'large string'.repeat(100) };
const sizeWithExclude = collector.calculateObjectSize(obj, ['excluded']);
const sizeWithoutExclude = collector.calculateObjectSize(obj);
expect(sizeWithExclude).toBeLessThan(sizeWithoutExclude);
});
test('should handle nested objects with limited depth', () => {
const obj = {
level1: {
level2: {
level3: {
value: 42
}
}
}
};
const size = collector.calculateObjectSize(obj);
expect(size).toBeGreaterThan(0);
});
});
describe('extractComponentDetails', () => {
test('should extract component details', () => {
const component = new PositionComponent(100, 200);
const details = collector.extractComponentDetails([component]);
expect(details.length).toBe(1);
expect(details[0].typeName).toBe('TestPosition');
expect(details[0].properties.x).toBe(100);
expect(details[0].properties.y).toBe(200);
});
test('should handle empty components array', () => {
const details = collector.extractComponentDetails([]);
expect(details).toEqual([]);
});
test('should skip private properties', () => {
class ComponentWithPrivate extends Component {
public publicValue: number = 1;
private _privateValue: number = 2;
}
const component = new ComponentWithPrivate();
const details = collector.extractComponentDetails([component]);
expect(details[0].properties.publicValue).toBe(1);
expect(details[0].properties._privateValue).toBeUndefined();
});
});
describe('getComponentProperties', () => {
test('should return empty object when scene is null', () => {
const props = collector.getComponentProperties(1, 0, null);
expect(props).toEqual({});
});
test('should return empty object when entity not found', () => {
const props = collector.getComponentProperties(9999, 0, scene);
expect(props).toEqual({});
});
test('should return empty object when component index is out of bounds', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent());
const props = collector.getComponentProperties(entity.id, 99, scene);
expect(props).toEqual({});
});
test('should return component properties', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(50, 75));
const props = collector.getComponentProperties(entity.id, 0, scene);
expect(props.x).toBe(50);
expect(props.y).toBe(75);
});
});
describe('expandLazyObject', () => {
test('should return null when scene is null', () => {
const result = collector.expandLazyObject(1, 0, 'path', null);
expect(result).toBeNull();
});
test('should return null when entity not found', () => {
const result = collector.expandLazyObject(9999, 0, 'path', scene);
expect(result).toBeNull();
});
test('should return null when component index is out of bounds', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent());
const result = collector.expandLazyObject(entity.id, 99, '', scene);
expect(result).toBeNull();
});
test('should expand object at path', () => {
class ComponentWithNested extends Component {
public nested = { value: 42 };
}
const entity = scene.createEntity('Entity');
entity.addComponent(new ComponentWithNested());
const result = collector.expandLazyObject(entity.id, 0, 'nested', scene);
expect(result).toBeDefined();
expect(result.value).toBe(42);
});
test('should handle array index in path', () => {
class ComponentWithArray extends Component {
public items = [{ id: 1 }, { id: 2 }];
}
const entity = scene.createEntity('Entity');
entity.addComponent(new ComponentWithArray());
const result = collector.expandLazyObject(entity.id, 0, 'items[1]', scene);
expect(result).toBeDefined();
expect(result.id).toBe(2);
});
});
describe('edge cases', () => {
test('should handle scene without entities buffer', () => {
const mockScene = {
entities: null,
getSystem: () => null
};
const data = collector.collectEntityData(mockScene as any);
expect(data.totalEntities).toBe(0);
});
test('should handle entity with long string properties', () => {
class ComponentWithLongString extends Component {
public longText = 'x'.repeat(300);
}
const entity = scene.createEntity('Entity');
entity.addComponent(new ComponentWithLongString());
const details = collector.extractComponentDetails(entity.components);
expect(details[0].properties.longText).toContain('[长字符串:');
});
test('should handle entity with large arrays', () => {
class ComponentWithLargeArray extends Component {
public items = Array.from({ length: 20 }, (_, i) => i);
}
const entity = scene.createEntity('Entity');
entity.addComponent(new ComponentWithLargeArray());
const details = collector.extractComponentDetails(entity.components);
expect(details[0].properties.items).toBeDefined();
expect(details[0].properties.items._isLazyArray).toBe(true);
expect(details[0].properties.items._arrayLength).toBe(20);
});
});
});
@@ -0,0 +1,417 @@
import { AutoProfiler, Profile, ProfileClass } from '../../../src/Utils/Profiler/AutoProfiler';
import { ProfilerSDK } from '../../../src/Utils/Profiler/ProfilerSDK';
import { ProfileCategory } from '../../../src/Utils/Profiler/ProfilerTypes';
describe('AutoProfiler', () => {
beforeEach(() => {
AutoProfiler.resetInstance();
ProfilerSDK.reset();
ProfilerSDK.setEnabled(true);
});
afterEach(() => {
AutoProfiler.resetInstance();
ProfilerSDK.reset();
});
describe('getInstance', () => {
test('should return singleton instance', () => {
const instance1 = AutoProfiler.getInstance();
const instance2 = AutoProfiler.getInstance();
expect(instance1).toBe(instance2);
});
test('should accept custom config', () => {
const instance = AutoProfiler.getInstance({ minDuration: 1.0 });
expect(instance).toBeDefined();
});
});
describe('resetInstance', () => {
test('should reset the singleton instance', () => {
const instance1 = AutoProfiler.getInstance();
AutoProfiler.resetInstance();
const instance2 = AutoProfiler.getInstance();
expect(instance1).not.toBe(instance2);
});
});
describe('setEnabled', () => {
test('should enable/disable auto profiling', () => {
AutoProfiler.setEnabled(false);
const instance = AutoProfiler.getInstance();
expect(instance).toBeDefined();
AutoProfiler.setEnabled(true);
expect(instance).toBeDefined();
});
});
describe('wrapFunction', () => {
test('should wrap a synchronous function', () => {
ProfilerSDK.beginFrame();
const originalFn = (a: number, b: number) => a + b;
const wrappedFn = AutoProfiler.wrapFunction(originalFn, 'add', ProfileCategory.Custom);
const result = wrappedFn(2, 3);
expect(result).toBe(5);
ProfilerSDK.endFrame();
});
test('should preserve function behavior', () => {
const originalFn = (x: number) => x * 2;
const wrappedFn = AutoProfiler.wrapFunction(originalFn, 'double', ProfileCategory.Script);
ProfilerSDK.beginFrame();
expect(wrappedFn(5)).toBe(10);
expect(wrappedFn(0)).toBe(0);
expect(wrappedFn(-3)).toBe(-6);
ProfilerSDK.endFrame();
});
test('should handle async functions', async () => {
const asyncFn = async (x: number) => {
await new Promise((resolve) => setTimeout(resolve, 1));
return x * 2;
};
const wrappedFn = AutoProfiler.wrapFunction(asyncFn, 'asyncDouble', ProfileCategory.Script);
ProfilerSDK.beginFrame();
const result = await wrappedFn(5);
expect(result).toBe(10);
ProfilerSDK.endFrame();
});
test('should handle function that throws error', () => {
const errorFn = () => {
throw new Error('Test error');
};
const wrappedFn = AutoProfiler.wrapFunction(errorFn, 'errorFn', ProfileCategory.Script);
ProfilerSDK.beginFrame();
expect(() => wrappedFn()).toThrow('Test error');
ProfilerSDK.endFrame();
});
test('should return original function when disabled', () => {
AutoProfiler.setEnabled(false);
const originalFn = (x: number) => x + 1;
const wrappedFn = AutoProfiler.wrapFunction(originalFn, 'increment', ProfileCategory.Script);
expect(wrappedFn(5)).toBe(6);
});
});
describe('wrapInstance', () => {
test('should wrap all methods of an object', () => {
class Calculator {
add(a: number, b: number): number {
return a + b;
}
subtract(a: number, b: number): number {
return a - b;
}
}
const calc = new Calculator();
AutoProfiler.wrapInstance(calc, 'Calculator', ProfileCategory.Script);
ProfilerSDK.beginFrame();
expect(calc.add(5, 3)).toBe(8);
expect(calc.subtract(5, 3)).toBe(2);
ProfilerSDK.endFrame();
});
test('should not wrap already wrapped objects', () => {
class MyClass {
getValue(): number {
return 42;
}
}
const obj = new MyClass();
AutoProfiler.wrapInstance(obj, 'MyClass', ProfileCategory.Custom);
AutoProfiler.wrapInstance(obj, 'MyClass', ProfileCategory.Custom);
ProfilerSDK.beginFrame();
expect(obj.getValue()).toBe(42);
ProfilerSDK.endFrame();
});
test('should return object unchanged when disabled', () => {
AutoProfiler.setEnabled(false);
class MyClass {
getValue(): number {
return 42;
}
}
const obj = new MyClass();
const wrapped = AutoProfiler.wrapInstance(obj, 'MyClass', ProfileCategory.Custom);
expect(wrapped).toBe(obj);
});
test('should exclude methods matching exclude patterns', () => {
class MyClass {
getValue(): number {
return 42;
}
_privateMethod(): number {
return 1;
}
getName(): string {
return 'test';
}
isValid(): boolean {
return true;
}
hasData(): boolean {
return true;
}
}
const obj = new MyClass();
AutoProfiler.wrapInstance(obj, 'MyClass', ProfileCategory.Custom);
ProfilerSDK.beginFrame();
expect(obj.getValue()).toBe(42);
expect(obj._privateMethod()).toBe(1);
expect(obj.getName()).toBe('test');
expect(obj.isValid()).toBe(true);
expect(obj.hasData()).toBe(true);
ProfilerSDK.endFrame();
});
});
describe('registerClass', () => {
test('should register a class for auto profiling', () => {
class MySystem {
update(): void {
// Do something
}
}
const RegisteredClass = AutoProfiler.registerClass(MySystem, ProfileCategory.ECS);
ProfilerSDK.beginFrame();
const instance = new RegisteredClass();
instance.update();
ProfilerSDK.endFrame();
expect(instance).toBeInstanceOf(MySystem);
});
test('should accept custom class name', () => {
class MySystem {
process(): number {
return 1;
}
}
const RegisteredClass = AutoProfiler.registerClass(MySystem, ProfileCategory.ECS, 'CustomSystem');
ProfilerSDK.beginFrame();
const instance = new RegisteredClass();
expect(instance.process()).toBe(1);
ProfilerSDK.endFrame();
});
});
describe('sampling profiler', () => {
test('should start and stop sampling', () => {
AutoProfiler.startSampling();
const samples = AutoProfiler.stopSampling();
expect(Array.isArray(samples)).toBe(true);
});
test('should return empty array when sampling was never started', () => {
const samples = AutoProfiler.stopSampling();
expect(samples).toEqual([]);
});
test('should collect samples during execution', async () => {
AutoProfiler.startSampling();
// Do some work
for (let i = 0; i < 100; i++) {
Math.sqrt(i);
}
// Wait a bit for samples to accumulate
await new Promise((resolve) => setTimeout(resolve, 50));
const samples = AutoProfiler.stopSampling();
expect(Array.isArray(samples)).toBe(true);
});
});
describe('dispose', () => {
test('should clean up resources', () => {
const instance = AutoProfiler.getInstance();
instance.startSampling();
instance.dispose();
// After dispose, stopping sampling should return empty array
const samples = instance.stopSampling();
expect(samples).toEqual([]);
});
});
describe('minDuration filtering', () => {
test('should respect minDuration setting', () => {
AutoProfiler.resetInstance();
const instance = AutoProfiler.getInstance({ minDuration: 1000 });
const quickFn = () => 1;
const wrappedFn = instance.wrapFunction(quickFn, 'quickFn', ProfileCategory.Script);
ProfilerSDK.beginFrame();
expect(wrappedFn()).toBe(1);
ProfilerSDK.endFrame();
});
});
});
describe('@Profile decorator', () => {
beforeEach(() => {
ProfilerSDK.reset();
ProfilerSDK.setEnabled(true);
});
afterEach(() => {
ProfilerSDK.reset();
});
test('should profile decorated methods', () => {
class TestClass {
@Profile()
calculate(): number {
return 42;
}
}
const instance = new TestClass();
ProfilerSDK.beginFrame();
const result = instance.calculate();
ProfilerSDK.endFrame();
expect(result).toBe(42);
});
test('should use custom name when provided', () => {
class TestClass {
@Profile('CustomMethodName', ProfileCategory.Physics)
compute(): number {
return 100;
}
}
const instance = new TestClass();
ProfilerSDK.beginFrame();
expect(instance.compute()).toBe(100);
ProfilerSDK.endFrame();
});
test('should handle async methods', async () => {
class TestClass {
@Profile()
async asyncMethod(): Promise<number> {
await new Promise((resolve) => setTimeout(resolve, 1));
return 99;
}
}
const instance = new TestClass();
ProfilerSDK.beginFrame();
const result = await instance.asyncMethod();
ProfilerSDK.endFrame();
expect(result).toBe(99);
});
test('should handle method that throws error', () => {
class TestClass {
@Profile()
throwingMethod(): void {
throw new Error('Decorated error');
}
}
const instance = new TestClass();
ProfilerSDK.beginFrame();
expect(() => instance.throwingMethod()).toThrow('Decorated error');
ProfilerSDK.endFrame();
});
test('should skip profiling when ProfilerSDK is disabled', () => {
ProfilerSDK.setEnabled(false);
class TestClass {
@Profile()
simpleMethod(): number {
return 1;
}
}
const instance = new TestClass();
expect(instance.simpleMethod()).toBe(1);
});
});
describe('@ProfileClass decorator', () => {
beforeEach(() => {
AutoProfiler.resetInstance();
ProfilerSDK.reset();
ProfilerSDK.setEnabled(true);
});
afterEach(() => {
AutoProfiler.resetInstance();
ProfilerSDK.reset();
});
test('should profile all methods of decorated class', () => {
@ProfileClass(ProfileCategory.ECS)
class GameSystem {
update(): void {
// Update logic
}
render(): number {
return 1;
}
}
ProfilerSDK.beginFrame();
const system = new GameSystem();
system.update();
expect(system.render()).toBe(1);
ProfilerSDK.endFrame();
});
test('should use default category when not specified', () => {
@ProfileClass()
class DefaultSystem {
process(): boolean {
return true;
}
}
ProfilerSDK.beginFrame();
const system = new DefaultSystem();
expect(system.process()).toBe(true);
ProfilerSDK.endFrame();
});
});