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

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
});
}

View File

@@ -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;
}

View File

@@ -0,0 +1 @@
export { HierarchyComponent } from './HierarchyComponent';

View File

@@ -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;
}

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
};
}

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);
}

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`);

View File

@@ -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 };
}
/**

View File

@@ -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);
}
}

View File

@@ -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);
}
}
}

View File

@@ -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 {
// 清理资源
}
}

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 {

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;
}

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';

View File

@@ -264,8 +264,6 @@ export interface IECSDebugConfig {
export interface ICoreConfig {
/** 是否启用调试模式 */
debug?: boolean;
/** 是否启用实体系统 */
enableEntitySystems?: boolean;
/** 调试配置 */
debugConfig?: IECSDebugConfig;
/** WorldManager配置 */

View File

@@ -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,

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) {

View File

@@ -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
};

View File

@@ -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;
};
}

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);
}
}

View File

@@ -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>;

View File

@@ -4,3 +4,5 @@
export * from './ProfilerTypes';
export { ProfilerSDK } from './ProfilerSDK';
export { AutoProfiler, Profile, ProfileClass } from './AutoProfiler';
export type { AutoProfilerConfig } from './AutoProfiler';