Files
esengine/packages/core/src/ECS/Systems/EntityCache.ts

167 lines
3.7 KiB
TypeScript
Raw Normal View History

import { Entity } from '../Entity';
/**
*
*
* EntitySystem
* 使
*
* @example
* ```typescript
* const cache = new EntityCache();
* cache.setPersistent(entities);
* const cached = cache.getPersistent();
* cache.invalidate();
* ```
*/
export class EntityCache {
/**
*
*
* update周期内使用
*/
private _frameCache: readonly Entity[] | null = null;
/**
*
*
* 使
*/
private _persistentCache: readonly Entity[] | null = null;
/**
*
*
*
*/
private _trackedEntities: Set<Entity> = new Set();
/**
*
*/
public getFrame(): readonly Entity[] | null {
return this._frameCache;
}
/**
*
*
* @param entities
*/
public setFrame(entities: readonly Entity[]): void {
this._frameCache = entities;
}
/**
*
*/
public getPersistent(): readonly Entity[] | null {
return this._persistentCache;
}
/**
*
*
* @param entities
*/
public setPersistent(entities: readonly Entity[]): void {
this._persistentCache = entities;
}
/**
*
*/
public getTracked(): ReadonlySet<Entity> {
return this._trackedEntities;
}
/**
*
*
* @param entity
*/
public addTracked(entity: Entity): void {
this._trackedEntities.add(entity);
}
/**
*
*
* @param entity
*/
public removeTracked(entity: Entity): void {
this._trackedEntities.delete(entity);
}
/**
*
*
* @param entity
*/
public isTracked(entity: Entity): boolean {
return this._trackedEntities.has(entity);
}
/**
* 使
*
*
*/
public invalidate(): void {
this._persistentCache = null;
}
/**
*
*
*
*/
public clearFrame(): void {
this._frameCache = null;
}
/**
*
*
*
*/
public clearAll(): void {
this._frameCache = null;
this._persistentCache = null;
this._trackedEntities.clear();
}
/**
*
*/
public hasPersistent(): boolean {
return this._persistentCache !== null;
}
/**
*
*/
public hasFrame(): boolean {
return this._frameCache !== null;
}
/**
*
*/
public getStats(): {
hasFrame: boolean;
hasPersistent: boolean;
trackedCount: number;
frameEntityCount: number;
persistentEntityCount: number;
} {
return {
hasFrame: this._frameCache !== null,
hasPersistent: this._persistentCache !== null,
trackedCount: this._trackedEntities.size,
frameEntityCount: this._frameCache?.length ?? 0,
persistentEntityCount: this._persistentCache?.length ?? 0
};
}
}