Files
esengine/packages/core/src/ECS/Scene.ts

435 lines
12 KiB
TypeScript
Raw Normal View History

import { Entity } from './Entity';
import { EntityList } from './Utils/EntityList';
import { EntityProcessorList } from './Utils/EntityProcessorList';
import { IdentifierPool } from './Utils/IdentifierPool';
import { EntitySystem } from './Systems/EntitySystem';
import { ComponentStorageManager } from './Core/ComponentStorage';
import { QuerySystem } from './Core/QuerySystem';
import { TypeSafeEventSystem } from './Core/EventSystem';
import { EventBus } from './Core/EventBus';
2025-08-12 09:39:07 +08:00
import { IScene, ISceneConfig } from './IScene';
import { getComponentInstanceTypeName, getSystemInstanceTypeName } from './Decorators';
/**
2025-08-12 09:39:07 +08:00
*
*
2025-08-12 09:39:07 +08:00
* IScene接口
* 使
*/
2025-08-12 09:39:07 +08:00
export class Scene implements IScene {
/**
*
*
*
*/
public name: string = "";
/**
*
*
*
*/
public readonly entities: EntityList;
/**
*
*
*
*/
public readonly entityProcessors: EntityProcessorList;
/**
* ID池
*
*
*/
public readonly identifierPool: IdentifierPool;
/**
*
*
*
*/
public readonly componentStorageManager: ComponentStorageManager;
/**
*
*
*
*/
public readonly querySystem: QuerySystem;
/**
*
*
*
*/
public readonly eventSystem: TypeSafeEventSystem;
/**
*
*/
private _didSceneBegin: boolean = false;
/**
*
*/
public get systems(): EntitySystem[] {
return this.entityProcessors.processors;
}
2025-08-12 09:39:07 +08:00
/**
*
*/
2025-08-12 09:39:07 +08:00
constructor(config?: ISceneConfig) {
this.entities = new EntityList(this);
this.entityProcessors = new EntityProcessorList();
this.identifierPool = new IdentifierPool();
this.componentStorageManager = new ComponentStorageManager();
this.querySystem = new QuerySystem();
this.eventSystem = new TypeSafeEventSystem();
2025-08-12 09:39:07 +08:00
// 应用配置
if (config?.name) {
this.name = config.name;
}
2025-09-26 09:38:51 +08:00
// 配置实体直接更新选项
if (config?.enableEntityDirectUpdate !== undefined) {
this.entities.setEnableEntityDirectUpdate(config.enableEntityDirectUpdate);
}
if (!Entity.eventBus) {
Entity.eventBus = new EventBus(false);
}
if (Entity.eventBus) {
2025-08-12 09:39:07 +08:00
Entity.eventBus.onComponentAdded((data: unknown) => {
this.eventSystem.emitSync('component:added', data);
});
}
}
/**
*
*
*
*/
public initialize(): void {
}
/**
*
*
*
*/
public onStart(): void {
}
/**
*
*
*
*/
public unload(): void {
}
/**
*
*
* onStart方法
*/
public begin() {
// 启动实体处理器
if (this.entityProcessors != null)
this.entityProcessors.begin();
// 标记场景已开始运行并调用onStart方法
this._didSceneBegin = true;
this.onStart();
}
/**
*
*
* unload方法
*/
public end() {
// 标记场景已结束运行
this._didSceneBegin = false;
// 移除所有实体
this.entities.removeAllEntities();
// 清理查询系统中的实体引用和缓存
this.querySystem.setEntities([]);
// 清空组件存储
this.componentStorageManager.clear();
// 结束实体处理器
if (this.entityProcessors)
this.entityProcessors.end();
// 调用卸载方法
this.unload();
}
/**
2025-09-26 09:38:51 +08:00
*
*/
public update() {
// 更新实体列表
this.entities.updateLists();
// 更新实体处理器
if (this.entityProcessors != null)
this.entityProcessors.update();
2025-09-26 09:38:51 +08:00
// 更新实体
this.entities.update();
2025-09-26 09:38:51 +08:00
// 更新实体处理器后处理
if (this.entityProcessors != null)
this.entityProcessors.lateUpdate();
}
/**
*
* @param name
*/
public createEntity(name: string) {
let entity = new Entity(name, this.identifierPool.checkOut());
this.eventSystem.emitSync('entity:created', { entityName: name, entity, scene: this });
return this.addEntity(entity);
}
/**
* EntitySystem的实体缓存
*
*/
public clearSystemEntityCaches(): void {
for (const system of this.entityProcessors.processors) {
system.clearEntityCache();
}
}
/**
*
* @param entity
* @param deferCacheClear
*/
public addEntity(entity: Entity, deferCacheClear: boolean = false) {
this.entities.add(entity);
entity.scene = this;
// 将实体添加到查询系统(可延迟缓存清理)
this.querySystem.addEntity(entity, deferCacheClear);
// 清除系统缓存以确保系统能及时发现新实体
if (!deferCacheClear) {
this.clearSystemEntityCaches();
}
// 触发实体添加事件
this.eventSystem.emitSync('entity:added', { entity, scene: this });
return entity;
}
/**
*
* @param count
* @param namePrefix
* @returns
*/
public createEntities(count: number, namePrefix: string = "Entity"): Entity[] {
const entities: Entity[] = [];
// 批量创建实体对象,不立即添加到系统
for (let i = 0; i < count; i++) {
const entity = new Entity(`${namePrefix}_${i}`, this.identifierPool.checkOut());
entity.scene = this;
entities.push(entity);
}
// 批量添加到实体列表
for (const entity of entities) {
this.entities.add(entity);
}
// 批量添加到查询系统(无重复检查,性能最优)
this.querySystem.addEntitiesUnchecked(entities);
// 批量触发事件(可选,减少事件开销)
this.eventSystem.emitSync('entities:batch_added', { entities, scene: this, count });
return entities;
}
/**
*
*/
public destroyAllEntities() {
this.entities.removeAllEntities();
// 清理查询系统中的实体引用和缓存
this.querySystem.setEntities([]);
}
/**
*
* @param name
*/
public findEntity(name: string): Entity | null {
return this.entities.findEntity(name);
}
/**
* ID查找实体
* @param id ID
*/
public findEntityById(id: number): Entity | null {
return this.entities.findEntityById(id);
}
/**
*
* @param tag
*/
public findEntitiesByTag(tag: number): Entity[] {
const result: Entity[] = [];
for (const entity of this.entities.buffer) {
if (entity.tag === tag) {
result.push(entity);
}
}
return result;
}
/**
*
* @param name
*/
public getEntityByName(name: string): Entity | null {
return this.findEntity(name);
}
/**
*
* @param tag
*/
public getEntitiesByTag(tag: number): Entity[] {
return this.findEntitiesByTag(tag);
}
/**
* EntitySystem处理器
* @param processor
*/
public addEntityProcessor(processor: EntitySystem) {
if (this.entityProcessors.processors.includes(processor)) {
return processor;
}
processor.scene = this;
this.entityProcessors.add(processor);
processor.initialize();
processor.setUpdateOrder(this.entityProcessors.count - 1);
return processor;
}
/**
* addEntityProcessor的别名
* @param system
*/
public addSystem(system: EntitySystem) {
return this.addEntityProcessor(system);
}
/**
* EntitySystem处理器
* @param processor
*/
public removeEntityProcessor(processor: EntitySystem) {
this.entityProcessors.remove(processor);
processor.reset();
2025-09-24 18:14:22 +08:00
}
/**
* removeEntityProcessor的别名
* @param system
*/
public removeSystem(system: EntitySystem) {
this.removeEntityProcessor(system);
}
/**
* EntitySystem处理器
* @param type
*/
public getEntityProcessor<T extends EntitySystem>(type: new (...args: unknown[]) => T): T | null {
return this.entityProcessors.getProcessor(type);
}
/**
*
*/
public getStats(): {
entityCount: number;
processorCount: number;
componentStorageStats: Map<string, any>;
} {
return {
entityCount: this.entities.count,
processorCount: this.entityProcessors.count,
componentStorageStats: this.componentStorageManager.getAllStats()
};
}
/**
*
*/
public getDebugInfo(): {
name: string;
entityCount: number;
processorCount: number;
isRunning: boolean;
entities: Array<{
name: string;
id: number;
componentCount: number;
componentTypes: string[];
}>;
processors: Array<{
name: string;
updateOrder: number;
entityCount: number;
}>;
componentStats: Map<string, any>;
} {
return {
name: this.name || this.constructor.name,
entityCount: this.entities.count,
processorCount: this.entityProcessors.count,
isRunning: this._didSceneBegin,
entities: this.entities.buffer.map(entity => ({
name: entity.name,
id: entity.id,
componentCount: entity.components.length,
componentTypes: entity.components.map(c => getComponentInstanceTypeName(c))
})),
processors: this.entityProcessors.processors.map(processor => ({
name: getSystemInstanceTypeName(processor),
updateOrder: processor.updateOrder,
entityCount: (processor as any)._entities?.length || 0
})),
componentStats: this.componentStorageManager.getAllStats()
};
}
2020-06-08 11:49:45 +08:00
}