@esengine/ecs-framework
Version:
用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架
2,072 lines (2,056 loc) • 519 kB
TypeScript
/**
* @esengine/ecs-framework v2.7.1
* TypeScript definitions
*/
/**
* TypeScript类型工具集
*
* 提供高级类型推断和类型安全的工具类型
*/
/**
* 组件类型提取器
* 从组件构造函数中提取实例类型
*/
type ComponentInstance<T> = T extends new (...args: any[]) => infer R ? R : never;
/**
* 组件构造函数类型
*
* 使用 Component 作为默认类型,与 ComponentType 保持一致。
* 这确保类型兼容性,因为所有实际组件都继承自 Component 类。
*/
type ComponentConstructor<T extends Component = Component> = new (...args: any[]) => T;
/**
* 组件类型的通用约束
*
* 用于确保类型参数是有效的组件构造函数
*/
type AnyComponentConstructor = ComponentConstructor<any>;
/**
* 多组件类型提取
* 从组件构造函数数组中提取所有实例类型的联合
*/
type ExtractComponents<T extends readonly ComponentConstructor[]> = {
[K in keyof T]: ComponentInstance<T[K]>;
};
/**
* 组件类型映射
* 将组件构造函数数组转换为实例类型的元组
*/
type ComponentTypeMap<T extends readonly ComponentConstructor[]> = {
[K in keyof T]: T[K] extends ComponentConstructor<infer C> ? C : never;
};
/**
* 实体with组件的类型
* 表示一个实体确定拥有某些组件
*/
type EntityWithComponents<T extends readonly ComponentConstructor[]> = {
readonly id: number;
readonly name: string;
/**
* 类型安全的组件获取
* 确保返回非空的组件实例
*/
getComponent<C extends ComponentConstructor>(componentType: C): ComponentInstance<C>;
/**
* 检查是否拥有组件
*/
hasComponent<C extends ComponentConstructor>(componentType: C): boolean;
/**
* 获取所有组件
*/
readonly components: ComponentTypeMap<T>;
};
/**
* 查询结果类型
* 根据查询条件推断实体必定拥有的组件
*/
type QueryResult$1<All extends readonly ComponentConstructor[] = [], Any extends readonly ComponentConstructor[] = [], None extends readonly ComponentConstructor[] = []> = {
/**
* 实体列表,确保拥有All中的所有组件
*/
readonly entities: ReadonlyArray<EntityWithComponents<All>>;
/**
* 实体数量
*/
readonly length: number;
/**
* 遍历实体
*/
forEach(callback: (entity: EntityWithComponents<All>, index: number) => void): void;
/**
* 映射转换
*/
map<R>(callback: (entity: EntityWithComponents<All>, index: number) => R): R[];
/**
* 过滤实体
*/
filter(predicate: (entity: EntityWithComponents<All>, index: number) => boolean): QueryResult$1<All, Any, None>;
};
/**
* System处理的实体类型
* 根据Matcher推断System处理的实体类型
*/
type SystemEntityType<M> = M extends {
getCondition(): {
all: infer All extends readonly ComponentConstructor[];
};
} ? EntityWithComponents<All> : never;
/**
* 组件字段类型提取
* 提取组件中所有可序列化的字段
*/
type SerializableFields<T> = {
[K in keyof T]: T[K] extends Function ? never : K;
}[keyof T];
/**
* 只读组件类型
* 将组件的所有字段转为只读
*/
type ReadonlyComponent<T extends IComponent> = {
readonly [K in keyof T]: T[K];
};
/**
* 部分组件类型
* 用于组件更新操作
*/
type PartialComponent<T extends IComponent> = {
[K in SerializableFields<T>]?: T[K];
};
/**
* 组件类型约束
* 确保类型参数是有效的组件
*/
type ValidComponent<T> = T extends Component ? T : never;
/**
* 组件数组约束
* 确保数组中的所有元素都是组件构造函数
*/
type ValidComponentArray<T extends readonly any[]> = T extends readonly ComponentConstructor[] ? T : never;
/**
* 事件处理器类型
* 提供类型安全的事件处理
*/
type TypedEventHandler<T> = (data: T) => void | Promise<void>;
/**
* 系统生命周期钩子类型
*/
type SystemLifecycleHooks<T extends readonly ComponentConstructor[]> = {
/**
* 实体添加到系统时调用
*/
onAdded?: (entity: EntityWithComponents<T>) => void;
/**
* 实体从系统移除时调用
*/
onRemoved?: (entity: EntityWithComponents<T>) => void;
/**
* 系统初始化时调用
*/
onInitialize?: () => void;
/**
* 系统销毁时调用
*/
onDestroy?: () => void;
};
/**
* Fluent API构建器类型
*/
type TypeSafeBuilder<T> = {
/**
* 完成构建
*/
build(): T;
};
/**
* 实体查询条件类型
*/
type TypedQueryCondition<All extends readonly ComponentConstructor[] = [], Any extends readonly ComponentConstructor[] = [], None extends readonly ComponentConstructor[] = []> = {
all: All;
any: Any;
none: None;
tag?: number;
name?: string;
};
/**
* 组件类型守卫
*/
declare function isComponentType<T extends Component>(value: any): value is ComponentConstructor<T>;
/**
* 类型安全的组件数组守卫
*/
declare function isComponentArray(value: any[]): value is ComponentConstructor[];
/**
* 提取组件类型名称(编译时)
*/
type ComponentTypeName<T extends ComponentConstructor> = T extends {
prototype: {
constructor: {
name: infer N;
};
};
} ? N : string;
/**
* 多组件类型名称联合
*/
type ComponentTypeNames<T extends readonly ComponentConstructor[]> = {
[K in keyof T]: ComponentTypeName<T[K]>;
}[number];
/**
* 深度只读类型
*/
type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};
/**
* 深度可选类型
*/
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
};
/**
* 排除方法的类型
*/
type DataOnly<T> = {
[K in keyof T as T[K] extends Function ? never : K]: T[K];
};
/**
* 可序列化的组件数据
*/
type SerializableComponent<T extends IComponent> = DeepPartial<DataOnly<T>>;
/**
* 可更新接口
*
* 实现此接口的服务将在每帧被Core自动调用update方法
*/
type IUpdatable = {
/**
* 每帧更新方法
*
* @param deltaTime - 帧时间间隔(秒),可选参数
*/
update(deltaTime?: number): void;
};
/**
* @zh 全局类型声明 - 用于减少 as any 的使用
* @en Global type declarations - to reduce as any usage
*/
/**
* @zh 小游戏平台基础 API 接口
* @en Base interface for mini-game platform APIs
*/
interface IMiniGamePlatformAPI {
getSystemInfo?: (options?: {
success?: (res: unknown) => void;
}) => void;
getSystemInfoSync?: () => Record<string, unknown>;
createCanvas?: () => HTMLCanvasElement;
createImage?: () => HTMLImageElement;
}
/**
* @zh 微信小游戏 API
* @en WeChat Mini Game API
*/
interface IWeChatMiniGameAPI extends IMiniGamePlatformAPI {
env?: {
USER_DATA_PATH?: string;
};
getFileSystemManager?: () => unknown;
createInnerAudioContext?: () => unknown;
}
/**
* @zh 字节跳动小游戏 API
* @en ByteDance Mini Game API
*/
type IByteDanceMiniGameAPI = IMiniGamePlatformAPI;
/**
* @zh 支付宝小游戏 API
* @en Alipay Mini Game API
*/
type IAlipayMiniGameAPI = IMiniGamePlatformAPI;
/**
* @zh 百度小游戏 API
* @en Baidu Mini Game API
*/
type IBaiduMiniGameAPI = IMiniGamePlatformAPI;
/**
* @zh 扩展的 globalThis 类型,包含小游戏平台
* @en Extended globalThis type with mini-game platforms
*/
interface IGlobalThisWithMiniGame {
wx?: IWeChatMiniGameAPI;
tt?: IByteDanceMiniGameAPI;
my?: IAlipayMiniGameAPI;
swan?: IBaiduMiniGameAPI;
}
/**
* @zh Chrome 内存信息接口
* @en Chrome memory info interface
*/
interface IChromeMemoryInfo {
jsHeapSizeLimit: number;
totalJSHeapSize: number;
usedJSHeapSize: number;
}
/**
* @zh 扩展的 Performance 接口,包含 Chrome 特有 API
* @en Extended Performance interface with Chrome-specific APIs
*/
interface IPerformanceWithMemory extends Performance {
memory?: IChromeMemoryInfo;
measureUserAgentSpecificMemory?: () => Promise<{
bytes: number;
breakdown: Array<{
bytes: number;
types: string[];
attribution: Array<{
scope: string;
container?: unknown;
}>;
}>;
}>;
}
/**
* @zh SoA 组件类型元数据接口
* @en SoA component type metadata interface
*
* @zh 用于 SoA 存储装饰器附加的元数据
* @en Used for metadata attached by SoA storage decorators
*/
interface IComponentTypeMetadata {
__enableSoA?: boolean;
__float64Fields?: Set<string>;
__float32Fields?: Set<string>;
__int32Fields?: Set<string>;
__uint32Fields?: Set<string>;
__int16Fields?: Set<string>;
__uint16Fields?: Set<string>;
__int8Fields?: Set<string>;
__uint8Fields?: Set<string>;
__uint8ClampedFields?: Set<string>;
__highPrecisionFields?: Set<string>;
__serializeMapFields?: Set<string>;
__serializeSetFields?: Set<string>;
__serializeArrayFields?: Set<string>;
__deepCopyFields?: Set<string>;
}
/**
* @zh 带元数据的组件构造函数类型
* @en Component constructor type with metadata
*/
type ComponentTypeWithMetadata<T> = (new () => T) & IComponentTypeMetadata;
/**
* @zh 获取全局小游戏平台对象
* @en Get global mini-game platform objects
*/
declare function getGlobalWithMiniGame(): IGlobalThisWithMiniGame;
/**
* @zh 获取带内存 API 的 performance 对象
* @en Get performance object with memory API
*/
declare function getPerformanceWithMemory(): IPerformanceWithMemory;
/**
* 框架核心类型定义
*/
/**
* 组件接口
*
* 定义组件的基本契约。
* 在 ECS 架构中,组件应该是纯数据容器,不包含业务逻辑。
*/
type IComponent = {
/** 组件唯一标识符 */
readonly id: number;
/** 组件所属的实体ID */
entityId: number | null;
/**
* 最后写入的 epoch
*
* 用于帧级变更检测,记录组件最后一次被修改时的 epoch。
*
* Last write epoch for frame-level change detection.
*/
readonly lastWriteEpoch: number;
/**
* 标记组件为已修改
*
* Mark component as modified with current epoch.
*/
markDirty(epoch: number): void;
/** 组件添加到实体时的回调 */
onAddedToEntity(): void;
/** 组件从实体移除时的回调 */
onRemovedFromEntity(): void;
/** 组件反序列化后的回调 */
onDeserialized(): void | Promise<void>;
};
/**
* 系统基础接口
*
* 为现有的EntitySystem类提供类型定义
*/
type ISystemBase = {
/** 系统名称 */
readonly systemName: string;
/** 更新顺序/优先级 */
updateOrder: number;
/** 系统启用状态 */
enabled: boolean;
/** 系统初始化 */
initialize(): void;
/** 更新系统(主要处理阶段) */
update(): void;
/** 延迟更新系统 */
lateUpdate?(): void;
};
/**
* 事件总线接口
* 提供类型安全的事件发布订阅机制
*/
type IEventBus = {
/**
* 发射事件
* @param eventType 事件类型
* @param data 事件数据
*/
emit<T>(eventType: string, data: T): void;
/**
* 异步发射事件
* @param eventType 事件类型
* @param data 事件数据
*/
emitAsync<T>(eventType: string, data: T): Promise<void>;
/**
* 监听事件
* @param eventType 事件类型
* @param handler 事件处理器
* @param config 监听器配置
* @returns 监听器ID
*/
on<T>(eventType: string, handler: (data: T) => void, config?: IEventListenerConfig): string;
/**
* 监听事件(一次性)
* @param eventType 事件类型
* @param handler 事件处理器
* @param config 监听器配置
* @returns 监听器ID
*/
once<T>(eventType: string, handler: (data: T) => void, config?: IEventListenerConfig): string;
/**
* 异步监听事件
* @param eventType 事件类型
* @param handler 异步事件处理器
* @param config 监听器配置
* @returns 监听器ID
*/
onAsync<T>(eventType: string, handler: (data: T) => Promise<void>, config?: IEventListenerConfig): string;
/**
* 移除事件监听器
* @param eventType 事件类型
* @param listenerId 监听器ID
*/
off(eventType: string, listenerId: string): boolean;
/**
* 移除指定事件类型的所有监听器
* @param eventType 事件类型
*/
offAll(eventType: string): void;
/**
* 检查是否有指定事件的监听器
* @param eventType 事件类型
*/
hasListeners(eventType: string): boolean;
/**
* 获取事件统计信息
* @param eventType 事件类型(可选)
*/
getStats(eventType?: string): IEventStats | Map<string, IEventStats>;
/**
* 清空所有监听器
*/
clear(): void;
};
/**
* 事件监听器配置接口
*/
type IEventListenerConfig = {
/** 是否只执行一次 */
once?: boolean;
/** 优先级(数字越大优先级越高) */
priority?: number;
/** 是否异步执行 */
async?: boolean;
/** 事件处理函数的 this 绑定对象 */
thisArg?: object;
};
/**
* 事件统计信息接口
*/
type IEventStats = {
/** 事件类型 */
eventType: string;
/** 监听器数量 */
listenerCount: number;
/** 触发次数 */
triggerCount: number;
/** 总执行时间(毫秒) */
totalExecutionTime: number;
/** 平均执行时间(毫秒) */
averageExecutionTime: number;
/** 最后触发时间 */
lastTriggerTime: number;
};
/**
* 事件数据基类接口
*/
type IEventData = {
/** 事件时间戳 */
timestamp: number;
/** 事件来源 */
source?: string;
/** 事件ID */
eventId?: string;
};
/**
* 实体事件数据接口
*/
interface IEntityEventData extends IEventData {
/** 实体ID */
entityId: number;
/** 实体名称 */
entityName?: string;
/** 实体标签 */
entityTag?: string;
}
/**
* 组件事件数据接口
*/
interface IComponentEventData extends IEntityEventData {
/** 组件类型名称 */
componentType: string;
/** 组件实例 */
component?: IComponent;
}
/**
* 系统事件数据接口
*/
interface ISystemEventData extends IEventData {
/** 系统名称 */
systemName: string;
/** 系统类型 */
systemType: string;
}
/**
* 场景事件数据接口
*/
interface ISceneEventData extends IEventData {
/** 场景名称 */
sceneName: string;
/** 前一个场景名称 */
previousSceneName?: string;
}
/**
* 性能事件数据接口
*/
interface IPerformanceEventData extends IEventData {
/** 操作类型 */
operation: string;
/** 执行时间(毫秒) */
executionTime: number;
/** 内存使用量 */
memoryUsage?: number;
/** 额外数据 */
metadata?: Record<string, unknown>;
}
/**
* ECS调试配置接口
*/
type IECSDebugConfig = {
/** 是否启用调试 */
enabled: boolean;
/** WebSocket服务器URL */
websocketUrl: string;
/** 是否自动重连 */
autoReconnect?: boolean;
/** 数据更新间隔(毫秒)- 已弃用,使用debugFrameRate替代 */
updateInterval?: number;
/** 调试数据发送帧率 (60fps, 30fps, 15fps) */
debugFrameRate?: 60 | 30 | 15;
/** 数据通道配置 */
channels: {
entities: boolean;
systems: boolean;
performance: boolean;
components: boolean;
scenes: boolean;
};
};
/**
* @zh 运行时环境类型
* @en Runtime environment type
*/
type RuntimeEnvironment = 'server' | 'client' | 'standalone';
/**
* Core配置接口
*/
type ICoreConfig = {
/** 是否启用调试模式 */
debug?: boolean;
/** 调试配置 */
debugConfig?: IECSDebugConfig;
/** WorldManager配置 */
worldManagerConfig?: IWorldManagerConfig;
/**
* @zh 运行时环境
* @en Runtime environment
*
* @zh 设置后所有 Scene 默认继承此环境。服务端框架应设置为 'server',客户端应用设置为 'client'。
* @en All Scenes inherit this environment by default. Server frameworks should set 'server', client apps should set 'client'.
*
* @default 'standalone'
*/
runtimeEnvironment?: RuntimeEnvironment;
};
/**
* ECS调试数据接口
*/
type IECSDebugData = {
/** 时间戳 */
timestamp: number;
/** 框架版本 */
frameworkVersion?: string;
/** 是否正在运行 */
isRunning: boolean;
/** 框架是否已加载 */
frameworkLoaded: boolean;
/** 当前场景名称 */
currentScene: string;
/** 实体数据 */
entities?: IEntityDebugData;
/** 系统数据 */
systems?: ISystemDebugData;
/** 性能数据 */
performance?: IPerformanceDebugData;
/** 组件数据 */
components?: IComponentDebugData;
/** 场景数据 */
scenes?: ISceneDebugData;
};
/**
* 实体层次结构节点接口
*/
type IEntityHierarchyNode = {
id: number;
name: string;
active: boolean;
enabled: boolean;
activeInHierarchy: boolean;
componentCount: number;
componentTypes: string[];
parentId: number | null;
children: IEntityHierarchyNode[];
depth: number;
tag: number;
updateOrder: number;
};
/**
* 实体调试数据接口
*/
type IEntityDebugData = {
/** 总实体数 */
totalEntities: number;
/** 激活实体数 */
activeEntities: number;
/** 待添加实体数 */
pendingAdd: number;
/** 待移除实体数 */
pendingRemove: number;
/** 按Archetype分组的实体分布 */
entitiesPerArchetype: Array<{
signature: string;
count: number;
memory: number;
}>;
/** 组件数量最多的前几个实体 */
topEntitiesByComponents: Array<{
id: string;
name: string;
componentCount: number;
memory: number;
}>;
/** 实体详情列表 */
entityDetails?: Array<{
id: string | number;
name?: string;
tag?: string;
enabled: boolean;
componentCount: number;
components: string[];
}>;
/** 实体层次结构(根实体) */
entityHierarchy?: Array<{
id: number;
name: string;
active: boolean;
enabled: boolean;
activeInHierarchy: boolean;
componentCount: number;
componentTypes: string[];
parentId: number | null;
children: IEntityHierarchyNode[];
depth: number;
tag: number;
updateOrder: number;
}>;
/** 实体详细信息映射 */
entityDetailsMap?: Record<number, {
id: number;
name: string;
active: boolean;
enabled: boolean;
activeInHierarchy: boolean;
destroyed: boolean;
tag: number;
updateOrder: number;
componentMask: string;
parentId: number | null;
parentName: string | null;
childCount: number;
childIds: number[];
depth: number;
components: Array<{
typeName: string;
properties: Record<string, unknown>;
}>;
componentCount: number;
componentTypes: string[];
}>;
};
/**
* 系统调试数据接口
*/
type ISystemDebugData = {
/** 总系统数 */
totalSystems: number;
/** 系统信息列表 */
systemsInfo: Array<{
name: string;
type: string;
entityCount: number;
executionTime?: number;
averageExecutionTime?: number;
minExecutionTime?: number;
maxExecutionTime?: number;
executionTimeHistory?: number[];
memoryUsage?: number;
updateOrder: number;
enabled: boolean;
lastUpdateTime?: number;
}>;
};
/**
* 性能调试数据接口
*/
type IPerformanceDebugData = {
/** ECS框架执行时间(毫秒) */
frameTime: number;
/** 引擎总帧时间(毫秒) */
engineFrameTime?: number;
/** ECS占总帧时间百分比 */
ecsPercentage?: number;
/** 内存使用量(MB) */
memoryUsage: number;
/** FPS */
fps: number;
/** 平均ECS执行时间(毫秒) */
averageFrameTime: number;
/** 最小ECS执行时间(毫秒) */
minFrameTime: number;
/** 最大ECS执行时间(毫秒) */
maxFrameTime: number;
/** ECS执行时间历史记录 */
frameTimeHistory: number[];
/** 系统性能详情 */
systemPerformance: Array<{
systemName: string;
averageTime: number;
maxTime: number;
minTime: number;
samples: number;
percentage?: number;
}>;
/** 系统占比分析数据 */
systemBreakdown?: Array<{
systemName: string;
executionTime: number;
percentage: number;
}>;
/** 内存分配详情 */
memoryDetails?: {
entities: number;
components: number;
systems: number;
pooled: number;
totalMemory: number;
usedMemory: number;
freeMemory: number;
gcCollections: number;
};
};
/**
* 组件调试数据接口
*/
type IComponentDebugData = {
/** 组件类型数 */
componentTypes: number;
/** 组件实例总数 */
componentInstances: number;
/** 组件分布统计 */
componentStats: Array<{
typeName: string;
instanceCount: number;
memoryPerInstance: number;
totalMemory: number;
poolSize: number;
poolUtilization: number;
averagePerEntity?: number;
}>;
};
/**
* 场景调试数据接口
*/
type ISceneDebugData = {
/** 当前场景名称 */
currentSceneName: string;
/** 场景是否已初始化 */
isInitialized: boolean;
/** 场景运行时间(秒) */
sceneRunTime: number;
/** 场景实体数 */
sceneEntityCount: number;
/** 场景系统数 */
sceneSystemCount: number;
/** 场景启动时间 */
sceneUptime: number;
};
/**
* @zh 游戏组件基类
* @en Base class for game components
*
* @zh ECS架构中的组件(Component)应该是纯数据容器。
* 所有游戏逻辑应该在 EntitySystem 中实现,而不是在组件内部。
* @en Components in ECS architecture should be pure data containers.
* All game logic should be implemented in EntitySystem, not inside components.
*
* @zh **重要:所有 Component 子类都必须使用 @ECSComponent 装饰器!**
* @zh 该装饰器用于注册组件类型名称,是序列化、网络同步等功能正常工作的前提。
* @en **IMPORTANT: All Component subclasses MUST use the @ECSComponent decorator!**
* @en This decorator registers the component type name, which is required for serialization, network sync, etc.
*
* @example
* @zh 正确做法:使用 @ECSComponent 装饰器
* @en Correct: Use @ECSComponent decorator
* ```typescript
* @ECSComponent('HealthComponent')
* class HealthComponent extends Component {
* public health: number = 100;
* public maxHealth: number = 100;
* }
* ```
*
* @example
* @zh 推荐做法:在 System 中处理逻辑
* @en Recommended: Handle logic in System
* ```typescript
* class HealthSystem extends EntitySystem {
* process(entities: Entity[]): void {
* for (const entity of entities) {
* const health = entity.getComponent(HealthComponent);
* if (health && health.health <= 0) {
* entity.destroy();
* }
* }
* }
* }
* ```
*/
declare abstract class Component implements IComponent {
/**
* @zh 组件ID生成器,用于为每个组件分配唯一的ID
* @en Component ID generator, used to assign unique IDs to each component
*/
private static _idGenerator;
/**
* @zh 组件唯一标识符,在整个游戏生命周期中唯一
* @en Unique identifier for the component, unique throughout the game lifecycle
*/
readonly id: number;
/**
* @zh 所属实体ID
* @en Owner entity ID
*
* @zh 存储实体ID而非引用,避免循环引用,符合ECS数据导向设计
* @en Stores entity ID instead of reference to avoid circular references, following ECS data-oriented design
*/
entityId: number | null;
/**
* @zh 最后写入的 epoch,用于帧级变更检测
* @en Last write epoch, used for frame-level change detection
*
* @zh 记录组件最后一次被修改时的 epoch,0 表示从未被标记为已修改
* @en Records the epoch when component was last modified, 0 means never marked as modified
*/
private _lastWriteEpoch;
/**
* @zh 获取最后写入的 epoch
* @en Get last write epoch
*/
get lastWriteEpoch(): number;
/**
* @zh 创建组件实例,自动分配唯一ID
* @en Create component instance, automatically assigns unique ID
*/
constructor();
/**
* @zh 标记组件为已修改
* @en Mark component as modified
*
* @zh 调用此方法会更新组件的 lastWriteEpoch 为当前帧的 epoch。
* 系统可以通过比较 lastWriteEpoch 和上次检查的 epoch 来判断组件是否发生变更。
* @en Calling this method updates the component's lastWriteEpoch to the current frame's epoch.
* Systems can compare lastWriteEpoch with their last checked epoch to detect changes.
*
* @param epoch - @zh 当前帧的 epoch @en Current frame's epoch
*
* @example
* ```typescript
* // @zh 在修改组件数据后调用 | @en Call after modifying component data
* velocity.x = 10;
* velocity.markDirty(scene.epochManager.current);
* ```
*/
markDirty(epoch: number): void;
/**
* @zh 组件添加到实体时的回调
* @en Callback when component is added to an entity
*
* @zh 当组件被添加到实体时调用,可以在此方法中进行初始化操作。
* 这是一个生命周期钩子,用于组件的初始化逻辑。
* 虽然保留此方法,但建议将复杂的初始化逻辑放在 System 中处理。
* @en Called when component is added to an entity, can perform initialization here.
* This is a lifecycle hook for component initialization logic.
* While this method is available, complex initialization logic should be handled in System.
*/
onAddedToEntity(): void;
/**
* @zh 组件从实体移除时的回调
* @en Callback when component is removed from an entity
*
* @zh 当组件从实体中移除时调用,可以在此方法中进行清理操作。
* 这是一个生命周期钩子,用于组件的清理逻辑。
* 虽然保留此方法,但建议将复杂的清理逻辑放在 System 中处理。
* @en Called when component is removed from an entity, can perform cleanup here.
* This is a lifecycle hook for component cleanup logic.
* While this method is available, complex cleanup logic should be handled in System.
*/
onRemovedFromEntity(): void;
/**
* @zh 组件反序列化后的回调
* @en Callback after component deserialization
*
* @zh 当组件从场景文件加载或快照恢复后调用,可以在此方法中恢复运行时数据。
* 这是一个生命周期钩子,用于恢复无法序列化的运行时数据。
* 例如:从图片路径重新加载图片尺寸信息,重建缓存等。
* @en Called after component is loaded from scene file or restored from snapshot.
* This is a lifecycle hook for restoring runtime data that cannot be serialized.
* For example: reloading image dimensions from image path, rebuilding caches, etc.
*
* @example
* ```typescript
* class TilemapComponent extends Component {
* public tilesetImage: string = '';
* private _tilesetData: TilesetData | undefined;
*
* public async onDeserialized(): Promise<void> {
* if (this.tilesetImage) {
* // @zh 重新加载 tileset 图片并恢复运行时数据
* // @en Reload tileset image and restore runtime data
* const img = await loadImage(this.tilesetImage);
* this.setTilesetInfo(img.width, img.height, ...);
* }
* }
* }
* ```
*/
onDeserialized(): void | Promise<void>;
}
/**
* 基础 64 位段结构
* [低32位,高32位]
*/
type BitMask64Segment = [number, number];
/**
* 位掩码数据结构
* 基础模式(64位):使用 base[lo , hi] 存储 64 位,segments 为空
* 扩展模式(128+位):base[lo , hi] 作为第一段,segments 存储额外的 64 位段
* segments[0] 对应 bit 64-127,segments[1] 对应 bit 128-191,以此类推
*/
type BitMask64Data = {
base: BitMask64Segment;
/** 扩展段数组,每个元素是一个 64 位段,用于超过 64 位的场景 */
segments?: BitMask64Segment[];
};
declare class BitMask64Utils {
/** 零掩码常量,所有位都为0 */
static readonly ZERO: Readonly<BitMask64Data>;
/**
* 根据位索引创建64位掩码
* @param bitIndex 位索引,范围 [0, 63]
* @returns 包含指定位设置为1的掩码
* @throws 当位索引超出范围时抛出错误
*/
static create(bitIndex: number): BitMask64Data;
/**
* 从32位数字创建64位掩码
* @param value 32位数字值
* @returns 低32位为输入值、高32位为0的掩码
*/
static fromNumber(value: number): BitMask64Data;
/**
* 检查掩码是否包含任意指定的位
* @param mask 要检查的掩码
* @param bits 指定的位模式
* @returns 如果掩码包含bits中的任意位则返回true
*/
static hasAny(mask: BitMask64Data, bits: BitMask64Data): boolean;
/**
* 检查掩码是否包含所有指定的位
* @param mask 要检查的掩码
* @param bits 指定的位模式
* @returns 如果掩码包含bits中的所有位则返回true
*/
static hasAll(mask: BitMask64Data, bits: BitMask64Data): boolean;
/**
* 检查掩码是否不包含任何指定的位
* @param mask 要检查的掩码
* @param bits 指定的位模式
* @returns 如果掩码不包含bits中的任何位则返回true
*/
static hasNone(mask: BitMask64Data, bits: BitMask64Data): boolean;
/**
* 检查掩码是否为零
* @param mask 要检查的掩码
* @returns 如果掩码所有位都为0则返回true
*/
static isZero(mask: BitMask64Data): boolean;
/**
* 检查两个掩码是否相等
* @param a 第一个掩码
* @param b 第二个掩码
* @returns 如果两个掩码完全相等则返回true
*/
static equals(a: BitMask64Data, b: BitMask64Data): boolean;
/**
* 设置掩码中指定位为1,必要时自动扩展
* @param mask 要修改的掩码(原地修改)
* @param bitIndex 位索引,不小于零
* @throws 当位索引超出范围时抛出错误
*/
static setBit(mask: BitMask64Data, bitIndex: number): void;
/**
* 获取掩码中指定位,如果位超出当前掩码的区段长度,则直接返回0
* @param mask 掩码
* @param bitIndex 位索引,不小于零
*/
static getBit(mask: BitMask64Data, bitIndex: number): boolean;
/**
* 清除掩码中指定位为0,如果位超出当前掩码的区段长度,则什么也不做
* @param mask 要修改的掩码(原地修改)
* @param bitIndex 位索引,不小于0
*/
static clearBit(mask: BitMask64Data, bitIndex: number): void;
/**
* 对目标掩码执行按位或操作
* @param target 目标掩码(原地修改)
* @param other 用于按位或的掩码
*/
static orInPlace(target: BitMask64Data, other: BitMask64Data): void;
/**
* 对目标掩码执行按位与操作
* @param target 目标掩码(原地修改)
* @param other 用于按位与的掩码
*/
static andInPlace(target: BitMask64Data, other: BitMask64Data): void;
/**
* 对目标掩码执行按位异或操作
* @param target 目标掩码(原地修改)
* @param other 用于按位异或的掩码
*/
static xorInPlace(target: BitMask64Data, other: BitMask64Data): void;
/**
* 清除掩码的所有位为0
* @param mask 要清除的掩码(原地修改)
*/
static clear(mask: BitMask64Data): void;
/**
* 将源掩码的值复制到目标掩码,如果source包含扩展段,则target也会至少扩展到source扩展段的长度
* @param source 源掩码
* @param target 目标掩码(原地修改)
*/
static copy(source: BitMask64Data, target: BitMask64Data): void;
/**
* 创建掩码的深拷贝
* @param mask 要拷贝的掩码
* @returns 新的掩码对象,内容与源掩码相同
*/
static clone(mask: BitMask64Data): BitMask64Data;
/**
* 将掩码转换为字符串表示,每个区段之间将使用空格分割。
* @param mask 要转换的掩码
* @param radix 进制,支持2(二进制)或16(十六进制),默认为2,其他的值被视为2
* @param printHead 打印头
* @returns 掩码的字符串表示,二进制不带前缀,十六进制带0x前缀
*/
static toString(mask: BitMask64Data, radix?: 2 | 16, printHead?: boolean): string;
/**
* 计算掩码中设置为1的位数
* @param mask 要计算的掩码
* @returns 掩码中1的位数
*/
static popCount(mask: BitMask64Data): number;
/**
* 获取包含目标位的BitMask64Segment
* @param mask 要操作的掩码
* @param bitIndex 目标位
* @param createNewSegment 如果bitIndex超过了当前范围,是否自动补充扩展区域,默认为真
* @private
*/
private static getSegmentByBitIndex;
}
/**
* SoA存储器支持的TypedArray类型
*/
type SupportedTypedArray = Float32Array | Float64Array | Int32Array | Uint32Array | Int16Array | Uint16Array | Int8Array | Uint8Array | Uint8ClampedArray;
/**
* @zh SoA 字段统计信息
* @en SoA field statistics
*/
interface ISoAFieldStats {
size: number;
capacity: number;
type: string;
memory: number;
}
/**
* @zh SoA 存储统计信息
* @en SoA storage statistics
*/
interface ISoAStorageStats {
size: number;
capacity: number;
totalSlots: number;
usedSlots: number;
freeSlots: number;
fragmentation: number;
memoryUsage: number;
fieldStats: Map<string, ISoAFieldStats>;
}
/**
* @zh 启用 SoA 优化装饰器 - 默认关闭,只在大规模批量操作场景下建议开启
* @en Enable SoA optimization decorator - disabled by default, recommended only for large-scale batch operations
*/
declare function EnableSoA<T extends ComponentType>(target: T): T;
/**
* @zh 64位浮点数装饰器 - 标记字段使用 Float64Array 存储(更高精度但更多内存)
* @en Float64 decorator - marks field to use Float64Array storage (higher precision but more memory)
*/
declare function Float64(target: object, propertyKey: string | symbol): void;
/**
* @zh 32位浮点数装饰器 - 标记字段使用 Float32Array 存储(默认类型,平衡性能和精度)
* @en Float32 decorator - marks field to use Float32Array storage (default, balanced performance and precision)
*/
declare function Float32(target: object, propertyKey: string | symbol): void;
/**
* @zh 32位整数装饰器 - 标记字段使用 Int32Array 存储(适用于整数值)
* @en Int32 decorator - marks field to use Int32Array storage (for integer values)
*/
declare function Int32(target: object, propertyKey: string | symbol): void;
/**
* @zh 32位无符号整数装饰器 - 标记字段使用 Uint32Array 存储
* @en Uint32 decorator - marks field to use Uint32Array storage
*/
declare function Uint32(target: object, propertyKey: string | symbol): void;
/**
* @zh 16位整数装饰器 - 标记字段使用 Int16Array 存储
* @en Int16 decorator - marks field to use Int16Array storage
*/
declare function Int16(target: object, propertyKey: string | symbol): void;
/**
* @zh 16位无符号整数装饰器 - 标记字段使用 Uint16Array 存储
* @en Uint16 decorator - marks field to use Uint16Array storage
*/
declare function Uint16(target: object, propertyKey: string | symbol): void;
/**
* @zh 8位整数装饰器 - 标记字段使用 Int8Array 存储
* @en Int8 decorator - marks field to use Int8Array storage
*/
declare function Int8(target: object, propertyKey: string | symbol): void;
/**
* @zh 8位无符号整数装饰器 - 标记字段使用 Uint8Array 存储
* @en Uint8 decorator - marks field to use Uint8Array storage
*/
declare function Uint8(target: object, propertyKey: string | symbol): void;
/**
* @zh 8位夹紧整数装饰器 - 标记字段使用 Uint8ClampedArray 存储(适用于颜色值)
* @en Uint8Clamped decorator - marks field to use Uint8ClampedArray storage (for color values)
*/
declare function Uint8Clamped(target: object, propertyKey: string | symbol): void;
/**
* @zh 序列化 Map 装饰器 - 标记 Map 字段需要序列化/反序列化存储
* @en SerializeMap decorator - marks Map field for serialization/deserialization
*/
declare function SerializeMap(target: object, propertyKey: string | symbol): void;
/**
* @zh 序列化 Set 装饰器 - 标记 Set 字段需要序列化/反序列化存储
* @en SerializeSet decorator - marks Set field for serialization/deserialization
*/
declare function SerializeSet(target: object, propertyKey: string | symbol): void;
/**
* @zh 序列化 Array 装饰器 - 标记 Array 字段需要序列化/反序列化存储
* @en SerializeArray decorator - marks Array field for serialization/deserialization
*/
declare function SerializeArray(target: object, propertyKey: string | symbol): void;
/**
* @zh 深拷贝装饰器 - 标记字段需要深拷贝处理(适用于嵌套对象)
* @en DeepCopy decorator - marks field for deep copy handling (for nested objects)
*/
declare function DeepCopy(target: object, propertyKey: string | symbol): void;
/**
* SoA存储器(需要装饰器启用)
* 使用Structure of Arrays存储模式,在大规模批量操作时提供优异性能
*/
declare class SoAStorage<T extends Component> {
private fields;
private stringFields;
private serializedFields;
private complexFields;
private entityToIndex;
private indexToEntity;
private freeIndices;
private _size;
private _capacity;
readonly type: ComponentType<T>;
private fieldTypes;
private serializeMapFields;
private serializeSetFields;
private serializeArrayFields;
constructor(componentType: ComponentType<T>);
private initializeFields;
addComponent(entityId: number, component: T): void;
private updateComponentAtIndex;
getComponent(entityId: number): T | null;
/**
* 创建组件的 Proxy 视图
* 读写操作直接映射到底层 TypedArray,无数据复制
*/
private createProxyView;
/**
* @zh 获取组件的快照副本(用于序列化等需要独立副本的场景)
* @en Get a snapshot copy of the component (for serialization scenarios)
*/
getComponentSnapshot(entityId: number): T | null;
private getFieldType;
hasComponent(entityId: number): boolean;
removeComponent(entityId: number): T | null;
private resize;
getActiveIndices(): number[];
getFieldArray(fieldName: string): SupportedTypedArray | null;
getTypedFieldArray<K extends keyof T>(fieldName: K): SupportedTypedArray | null;
getEntityIndex(entityId: number): number | undefined;
getEntityIdByIndex(index: number): number | undefined;
size(): number;
clear(): void;
compact(): void;
/**
* @zh 获取 SoA 存储统计信息
* @en Get SoA storage statistics
*/
getStats(): ISoAStorageStats;
/**
* 执行向量化批量操作
* @param operation 操作函数,接收字段数组和活跃索引
*/
performVectorizedOperation(operation: (fieldArrays: Map<string, SupportedTypedArray>, activeIndices: number[]) => void): void;
}
/**
* Component Type Utilities
* 组件类型工具函数
*
* This module contains low-level utilities for component type handling.
* It has NO dependencies on other ECS modules to avoid circular imports.
*
* 此模块包含组件类型处理的底层工具函数。
* 它不依赖其他 ECS 模块,以避免循环导入。
*/
/**
* 组件类型定义
* Component type definition
*
* 注意:构造函数参数使用 any[] 是必要的,因为组件可以有各种不同签名的构造函数
* Note: Constructor args use any[] because components can have various constructor signatures
*/
type ComponentType<T extends Component = Component> = new (...args: any[]) => T;
/**
* 存储组件类型名称的 Symbol 键
* Symbol key for storing component type name
*/
declare const COMPONENT_TYPE_NAME: unique symbol;
/**
* 存储组件依赖的 Symbol 键
* Symbol key for storing component dependencies
*/
declare const COMPONENT_DEPENDENCIES: unique symbol;
/**
* 存储组件编辑器选项的 Symbol 键
* Symbol key for storing component editor options
*/
declare const COMPONENT_EDITOR_OPTIONS: unique symbol;
/**
* 组件编辑器选项
* Component editor options
*/
type ComponentEditorOptions = {
/**
* 是否在 Inspector 中隐藏此组件
* Whether to hide this component in Inspector
*
* @default false
*/
hideInInspector?: boolean;
/**
* 组件分类(用于 Inspector 中的分组显示)
* Component category (for grouping in Inspector)
*/
category?: string;
/**
* 组件图标(用于 Inspector 中的显示)
* Component icon (for display in Inspector)
*/
icon?: string;
};
/**
* 检查组件是否使用了 @ECSComponent 装饰器
* Check if component has @ECSComponent decorator
*
* @param componentType 组件构造函数
* @returns 是否有装饰器
*/
declare function hasECSComponentDecorator(componentType: ComponentType): boolean;
/**
* 获取组件类型的名称,优先使用装饰器指定的名称
* Get component type name, preferring decorator-specified name
*
* @param componentType 组件构造函数
* @returns 组件类型名称
*/
declare function getComponentTypeName(componentType: ComponentType): string;
/**
* 从组件实例获取类型名称
* Get type name from component instance
*
* @param component 组件实例
* @returns 组件类型名称
*/
declare function getComponentInstanceTypeName(component: Component): string;
/**
* 获取组件的依赖列表
* Get component dependencies
*
* @param componentType 组件构造函数
* @returns 依赖的组件名称列表
*/
declare function getComponentDependencies(componentType: ComponentType): string[] | undefined;
/**
* 获取组件的编辑器选项
* Get component editor options
*
* @param componentType 组件构造函数
* @returns 编辑器选项
*/
declare function getComponentEditorOptions(componentType: ComponentType): ComponentEditorOptions | undefined;
/**
* 从组件实例获取编辑器选项
* Get editor options from component instance
*
* @param component 组件实例
* @returns 编辑器选项
*/
declare function getComponentInstanceEditorOptions(component: Component): ComponentEditorOptions | undefined;
/**
* 检查组件是否应该在 Inspector 中隐藏
* Check if component should be hidden in Inspector
*
* @param componentType 组件构造函数
* @returns 是否隐藏
*/
declare function isComponentHiddenInInspector(componentType: ComponentType): boolean;
/**
* 从组件实例检查是否应该在 Inspector 中隐藏
* Check if component instance should be hidden in Inspector
*
* @param component 组件实例
* @returns 是否隐藏
*/
declare function isComponentInstanceHiddenInInspector(component: Component): boolean;
/**
* 服务基础接口
* 所有通过 ServiceContainer 管理的服务都应该实现此接口
*/
type IService = {
/**
* 释放服务占用的资源
* 当服务被注销或容器被清空时调用
*/
dispose(): void;
};
/**
* 服务类型
*
* 支持任意构造函数签名,以便与依赖注入装饰器配合使用
* 使用 any[] 以允许任意参数类型的构造函数
*/
type ServiceType<T extends IService> = new (...args: any[]) => T;
/**
* 服务标识符
*
* 支持类构造函数或 Symbol 作为服务标识符
*/
type ServiceIdentifier<T extends IService = IService> = ServiceType<T> | symbol;
/**
* 服务生命周期
*/
declare enum ServiceLifetime {
/**
* 单例模式 - 整个应用生命周期内只有一个实例
*/
Singleton = "singleton",
/**
* 瞬时模式 - 每次请求都创建新实例
*/
Transient = "transient"
}
/**
* 服务容器
*
* 负责管理所有服务的注册、解析和生命周期。
* 支持依赖注入和服务定位模式。
*
* 特点:
* - 单例和瞬时两种生命周期
* - 支持工厂函数注册
* - 支持实例注册
* - 类型安全的服务解析
*
* @example
* ```typescript
* const container = new ServiceContainer();
*
* // 注册单例服务
* container.registerSingleton(TimerManager);
*
* // 注册工厂函数
* container.registerSingleton(Logger, (c) => createLogger('App'));
*
* // 注册实例
* container.registerInstance(Config, new Config());
*
* // 解析服务
* const timer = container.resolve(TimerManager);
* ```
*/
declare class ServiceContainer {
/**
* 服务注册表
*/
private _services;
/**
* 正在解析的服务栈(用于循环依赖检测)
*/
private _resolving;
/**
* 可更新的服务列表
*
* 自动收集所有使用@Updatable装饰器标记的服务,供Core统一更新
* 按优先级排序(数值越小越先执行)
*/
private _updatableServices;
/**
* 注册单例服务
*
* @param type - 服务类型
* @param factory - 可选的工厂函数
*
* @example
* ```typescript
* // 直接注册类型
* container.registerSingleton(TimerManager);
*
* // 使用工厂函数
* container.registerSingleton(Logger, (c) => {
* return createLogger('App');
* });
* ```
*/
registerSingleton<T extends IService>(type: ServiceType<T>, factory?: (container: ServiceContainer) => T): void;
/**
* 注册瞬时服务
*
* 每次解析都会创建新实例。
*
* @param type - 服务类型
* @param factory - 可选的工厂函数
*
* @example
* ```typescript
* // 每次解析都创建新实例
* container.registerTransient(Command);
* ```
*/
registerTransient<T extends IService>(type: ServiceType<T>, factory?: (container: ServiceContainer) => T): void;
/**
* 注册服务实例
*
* 直接注册已创建的实例,自动视为单例。
*
* @param identifier - 服务标识符(构造函数或 Symbol)
* @param instance - 服务实例
*
* @example
* ```typescript
* const config = new Config();
* container.registerInstance(Config, config);
*
* // 使用 Symbol 作为标识符(适用于接口)
* const IFileSystem = Symbol('IFileSystem');
* container.registerInstance(IFileSystem, new TauriFileSystem());
* ```
*/
registerInstance<T extends IService>(identifier: ServiceIdentifier<T>, instance: T): void;
/**
* 解析服务
*
* @param identifier - 服务标识符(构造函数或 Symbol)
* @returns 服务实例
* @throws 如果服务未注册或存在循环依赖
*
* @example
* ```typescript
* const timer = container.resolve(TimerManager);
*
* // 使用 Symbol
* const fileSystem = container.resolve(IFileSystem);
* ```
*/
resolve<T extends IService>(identifier: ServiceIdentifier<T>): T;
/**
* 尝试解析服务
*
* 如果服务未注册,返回null而不是抛出异常。
*
* @param identifier - 服务标识符(构造函数或 Symbol)
* @returns 服务实例或null
*
* @example
* ```typescript
* const timer = container.tryResolve(TimerManager);
* if (timer) {
* timer.schedule(...);
* }
* ```
*/
tryResolve<T extends IService>(identifier: ServiceIdentifier<T>): T | null;
/**
* 检查服务是否已注册
*
* @param identifier - 服务标识符(构造函数或 Symbol)
* @returns 是否已注册
*/
isRegistered<T extends IService>(identifier: ServiceIdentifier<T>): boolean;
/**
* 注销服务
*
* @param identifier - 服务标识符(构造函数或 Symbol)
* @returns 是否成功注销
*/
unregister<T extends IService>(identifier: ServiceIdentifier<T>): boolean;
/**
* 清空所有服务
*/
clear(): void;
/**
* 获取所有已注册的服务标识符
*
* @returns 服务标识符数组
*/
getRegisteredServices(): ServiceIdentifier[];
/**
* 更新所有使用@Updatable装饰器标记的服务
*
* 此方法会按优先级顺序遍历所有可更新的服务并调用它们的update方法。
* 所有服务在注册时已经由@Updatable装饰器验证过必须实现IUpdatable接口。
* 通常在Core的主更新循环中调用。
*
* @param deltaTime - 可选的帧时间间隔(秒)
*
* @example
* ```typescript
* // 在Core的update方法中
* this._serviceContainer.updateAll(deltaTime);
* ```
*/
updateAll(deltaTime?: number): void;
/**
* 获取所有可更新的服务数量
*
* @returns 可更新服务的数量
*/
getUpdatableCount(): number;
/**
* 获取所有已实例化的服务实例
*
* @returns 所有服务实例的数组
*/
getAll(): IService[];
}
/**
* 性能监控数据
*/
type PerformanceData = {
/** 系统名称 */
name: string;
/** 执行时间(毫秒) */
executionTime: number;
/** 处理的实体数量 */
entityCount: number;
/** 平均每个实体的处理时间 */
averageTimePerEntity: number;
/** 最后更新时间戳 */
lastUpdateTime: number;
/** 内存使用量(字节) */
memoryUsage?: number;
/** CPU使用率(百分比) */
cpuUsage?: number;
};
/**
* 性能统计信息
*/
type PerformanceStats = {
/** 总执行时间 */
totalTime: number;
/** 平均执行时间 */
averageTime: number;
/** 最小执行时间 */
minTime: number;
/** 最大执行时间 */
maxTime: number;
/** 执行次数 */
executionCount: number;
/** 最近的执行时间列表 */
recentTimes: number[];
/** 标准差 */
standardDeviation: number;
/** 95百分位数 */
percentile95: number;
/** 99百分位数 */
percentile99: number;
};
/**
* 性能警告类型
*/
declare enum PerformanceWarningType {
HIGH_EXECUTION_TIME = "high_execution_time",
HIGH_MEMORY_USAGE = "high_memory_usage",
HIGH_CPU_USAGE = "high_cpu_usage",
FREQUENT_GC = "frequent_gc",
LOW_FPS = "low_fps",
HIGH_ENTITY_COUNT = "high_entity_count"
}
/**
* 性能警告
*/
type PerformanceWarning = {
type: PerformanceWarningType;
systemName: string;
message: string;
severity: 'low' | 'medium' | 'high' | 'critical';
timestamp: number;
value: number;
threshold: number;
suggestion?: string;
};
/**
* 性能阈值配置
*/
type PerformanceThresholds = {
/** 执行时间阈值(毫秒) */
executionTime: {
warning: number;
critical: number;
};
/** 内存使用阈值(MB) */
memoryUsage: {
warning: number;
critical: number;
};
/** CPU使用率阈值(百分比) */
cpuUsage: {
warning: number;
critical: number;
};
/** FPS阈值 */
fps: {
warning: number;
critical: number;
};
/** 实体数量阈值 */
entityCount: {
warning: number;
critical: number;
};
};
/**
* 高性能监控器
* 用于监控ECS系统的性能表现,提供详细的分析和优化建议
*/
declare class PerformanceMonitor implements IService {
private _systemData;
private _systemStats;
private _isEnabled;
private _maxRecentSamples;
constructor();
/**
* @zh 更新FPS统计(可选功能,子类可重写)
* @en Update FPS statistics (optional, can be overridden by subclasses)
*
* @param _deltaTime - @zh 帧时间间隔(秒)@en Frame delta time in seconds
*/
updateFPS(_deltaTime: number): void;
/**
* 启用性能监控
*/
enable(): void;
/**
* 禁用性能监控
*/
disable(): void;
/**
* 检查是否启用了性能监控
*/
get isEnabled(): boolean;
/**
* 开始监控系统性能
* @param systemName 系统名称
* @returns 开始时间戳
*/
startMonitoring(_systemName: string): number;
/**
* 结束监控并记录性能数据
* @param systemName 系统名称
* @param startTime 开始时间戳
* @param entityCount 处理的实体数量
*/
endMonitoring(systemName: string, startTime: number, entityCount?: number): void;
/**
* 更新系统统计信息
* @param systemName 系统名称
* @param executionTime 执行时间
*/
private updateStats;
/**
* 计算高级统计信息
* @param stats 统计信息对象
*/
private calculateAdvancedStats;
/**
* 获取系统的当前性能数据
* @param systemName 系统名称
* @returns 性能数据或undefined
*/
getSystemData(systemName: string): PerformanceData | undefined;
/**
* 获取系统的统计信息
* @param systemName 系统名称
* @returns 统计信息或undefined
*/
getSystemStats(systemName: string): PerformanceStats | undefined;
/**
* 获取所有系统的性能数据
* @returns 所有系统的性能数据
*/
getAllSystemData(): Map<string, PerformanceData>;
/**
* 获取所有系统的统计信息
* @returns 所有系统的统计信息
*/
getAllSystemStats(): Map<string, PerformanceStats>;
/**
* 获取性能报告
* @returns 格式化的性能报告字符串
*/
getPerformanceReport(): string;
/**
* 重置所有性能数据
*/
reset(): void;
/**
* 重置指定系统的性能数据
* @param systemName 系统名称
*/
resetSystem(systemName: string): void;
/**
* 获取性能警告
* @param thresholdMs 警告阈值(毫秒)
* @returns 超过阈值的系统列表
*/
getPerformanceWarnings(thresholdMs?: number): string[];
/**
* 设置最大保留样本数
* @param maxSamples 最大样本数
*/
setMaxRecentSamples(maxSamples: number): void;
/**
* 释放资源
*/
dispose(): void;
}
/**
* 查询条件类型
*/
type QueryCondition$1 = {
all: ComponentType[];
any: ComponentType[];
none: ComponentType[];
tag?: number;
name?: string;
component?: ComponentType;
matchNothing?: boolean;
};
/**
* 实体匹配条件描述符
*
* 用于描述实体查询条件,不执行实际查询
*
* @example
* ```typescript
* const matcher = Matcher.all(Position, Velocity)
* .any(Health, Shield)
* .none(Dead);
*
* // 获取查询条件
* const condition = matcher.getCondition();
* ```
*/
declare class Matcher {
private readonly condition;
private constructor();
/**
* 创建匹配器,要求所有指定的组件
* @param types 组件类型
*/
static all(...types: ComponentType[]): Matcher;
/**
* 创建匹配器,要求至少一个指定的组件
* @param types 组件类型
*/
static any(...types: ComponentType[]): Matcher;
/**
* 创建匹配器,排除指定的组件
* @param types 组件类型
*/
static none(...types: ComponentType[]): Matcher;
/**
* 创建按标签查询的匙配器
* @param tag 标签值
*/
static byTag(tag: number): Matcher;
/**
* 创建按名称查询的匙配器
* @param name 实体名称
*/
static byName(name: string): Matcher;
/**
* 创建单组件查询的匙配器
* @param componentType 组件类型
*/
static byComponent(componentType: ComponentType): Matcher;
/**
* 创建复杂查询构建器
*/
static complex(): Matcher;
/**
* 创建空匙配器
*/
static empty(): Matcher;
/**
* 创建不匹配任何实体的匹配器
* 用于只需要 onBegin/onEnd 生命周期方法但不需要处理实体的系统
*
* @example
* ```typescript
* // 创建一个只在帧开始时执行的系统
* class FrameBeginSystem extends EntitySystem {
* constructor() {
* super(Matcher.nothing());
* }
*
* protected onBegin(): void {
* // 每帧开始时执行
* }
*
* protected process(entities: readonly Entity[]): void {
* // 永远不会被调用,因为没有实体匹配
* }
* }
* ```
*/
static nothing(): Matcher;
/**
* 必须包含所有指定组件
* @param types 组件类型
*/
all(...types: ComponentType[]): Matcher;
/**
* 必须包含至少一个指定组件
* @param types 组件类型
*/
any(...types: ComponentType[]): Matcher;
/**
* 不能包含任何指定组件
* @param types 组件类型
*/
none(...types: ComponentType[]): Matcher;
/**
* 排除指定组件(别名方法)
* @param types 组件类型
*/
exclude(...types: ComponentType[]): Matcher;
/**
* 至少包含其中之一(别名方法)
* @param types 组件类型
*/
one(...types: ComponentType[]): Matcher;
/**
* 按标签查询
* @param tag 标签值
*/
withTag(tag: number): Matcher;
/**
* 按名称查询
* @param name 实体名称
*/
withName(name: string): Matcher;
/**
* 单组件查询
* @param componentType 组件类型
*/
withComponent(componentType: ComponentType): Matcher;
/**
* 移除标签条件
*/
withoutTag(): Matcher;
/**
* 移除名称条件
*/
withoutName(): Matcher;
/**
* 移除单组件条件
*/
withoutComponent(): Matcher;
/**
* 获取查询条件(只读)
*/
getCondition(): Readonly<QueryCondition$1>;
/**
* 检查是否为空条件
* 注意:matchNothing 不算空条件,因为它是明确的"不匹配任何实体"语义
*/
isEmpty(): boolean;
/**
* 检查是否为"不匹配任何实体"的匹配器
*/
isNothing(): boolean;
/**
* 重置所有条件
*/
reset(): Matcher;
/**
* 克隆匹配器
*/
clone(): Matcher;
/**
* 字符串表示
*/
toString(): string;
}
/**
* 高性能实体列表管理器
* 管理场景中的所有实体,支持快速查找和批量操作
*/
declare class EntityList {
buffer: Entity[];
private _scene;
private _idToEntity;
private _nameToEntities;
private _entitiesToAdd;
private _entitiesToRemove;
get count(): number;
constructor(scene: any);
/**
* 添加实体
* @param entity 要添加的实体
*/
add(entity: Entity): void;
/**
* 立即添加实体
* @param entity 要添加的实体
*/
private addImmediate;
/**
* 移除实体
* @param entity 要移除的实体
*/
remove(entity: Entity): void;
/**
* 立即移除实体
* @param entity 要移除的实体
*/
private removeImmediate;
/**
* 移除所有实体
* Remove all entities
*
* 包括 buffer 中的实体和待添加队列中的实体。
* Includes entities in buffer and entities in pending add queue.
*/
removeAllEntities(): void;
/**
* 更新实体列表,处理延迟操作
*/
updateLists(): void;
/**
* 更新实体列表
*
* 处理延迟操作(添加/删除实体)
*/
update(): void;
/**
* 根据名称查找实体(使用索引,O(1)复杂度)
* @param name 实体名称
* @returns 找到的第一个实体或null
*/
findEntity(name: string): Entity | null;
/**
* 根据名称查找所有实体
* @param name 实体名称
* @returns 找到的所有实体数组
*/
findEntitiesByName(name: string): E