Files
oops-plugin-framework/assets/core/gui/layer/LayerManager.ts
dgflash 3a2db77647 1. 核心入口 — ECS.ts
ecs 命名空间:统一导出所有 API,业务只需 import { ecs } from './ECS'
核心类型别名:ecs.Entity / ecs.Comp / ecs.RootSystem / ecs.ComblockSystem
接口再导出:ecs.IComp / ecs.IMatcher / ecs.IEntityEnterSystem / ecs.IEntityRemoveSystem / ecs.ISystemFirstUpdate / ecs.ISystemUpdate
实体工厂:ecs.getEntity(ctor, world?) — 创建或从对象池获取实体
动态查询:ecs.query(matcher, world?) — 按匹配器查询实体
过滤器工厂:ecs.allOf() / ecs.anyOf() / ecs.onlyOf() / ecs.excludeOf() — 组合匹配规则
单例组件:ecs.getSingleton() / ecs.addSingleton() — 全局唯一组件访问
子模块门面:ecs.world / ecs.pool / ecs.system / ecs.storage / ecs.network / ecs.serialize / ecs.entityRef
2. 驱动器 — ECSDriver.ts
封装默认世界的 init / execute / destroy 生命周期
add(system) — 向默认世界添加业务系统
init() — 初始化 ECS(并入 @ecs.register 注册的系统、拓扑排序、init)
execute(dt) — 驱动默认世界一帧
destroy() — 清理所有子系统
3. 实体 — ECSEntity.ts
组件容器:位掩码 mask + 按 tid 索引的密集数组,get/has 为 O(1)
双重重载 add():
add(组件类) — 从对象池取实例或恢复软移除缓存
add(组件实例) — 挂载外部实例(如 cc.Component),设 canRecycle=false
remove(ctor, isRecycle?):
isRecycle=true(默认):reset + 回池/释放 SoA 槽位
isRecycle=false:软移除,数据暂存 compTid2Obj,下次 add 同 tid 恢复
父子层级:addChild / removeChild,带循环引用检测
destroy():断开父子 → 移除全部组件 → 清理软移除缓存 → 回收实体 + 释放 eid
forEachComponent(cb):遍历当前挂载的所有组件
4. 组件 — ECSComp.ts
抽象基类,子类须实现 reset() 方法
canRecycle — 是否可回收(外部创建的组件设 false)
ent — 拥有该组件的实体引用
变更检测:markDirty() / isChangedSince(sinceEpoch) / lastWriteEpoch — 基于 epoch 的帧级脏标记
5. 位掩码 — ECSMask.ts
基于 Uint32Array 的位运算,支持 set / has / delete / and / or / bitCount
对象池复用,clearPool() 清理
6. 注册系统 — ECSRegister.ts + ECSTypeRegistry.ts
@ecs.register('Name') 类装饰器:自动识别注册类型
组件:分配 tid,写入 compCtors 表
实体:记录 ctor → name 映射
系统:注册到全局表或指定世界
ECSTypeRegistry:全局类型注册表(跨世界共享),记录组件/实体/系统元数据
7. 查询 — ECSMatcher.ts + ECSGroup.ts
四种规则:AllOf / AnyOf / OnlyOf / ExcludeOf,规则间为"与"关系
flyweight 缓存:相同组合共享同一 Matcher 实例
小规则优化:tid 数 ≤ 4 时直接 mask.has,否则分配 ECSMask
ECSGroup:SparseSet 实现,O(1) 增删(swap-pop),稳定快照遍历
进入/离开追踪:watchEntityEnterAndRemove 供系统帧内查询变化
8. 系统 — ECSComblockSystem.ts + ECSRootSystem.ts
ComblockSystem:业务系统基类
生命周期:init → entityEnter → firstUpdate → update → entityRemove → onDestroy
filter() — 声明实体匹配规则
interval — 执行间隔(0=每帧,>0=固定间隔)
被动系统:isPassiveSystem() 返回 true 时不参与每帧 update
构造时探测子类钩子,选定 execute 变体(零开销分支)
RootSystem:根系统,一世界一个
init() — 并入 @ecs.register 系统 + 拓扑排序 + 绑定世界 + init
execute(dt) — 切换当前世界 → 递增 epoch → tick 各系统 → flush 命令缓冲
9. 系统调度 — SystemScheduler.ts
声明式执行顺序:@ecs.system.executeBefore / @ecs.system.executeAfter / @ecs.system.inSet
拓扑排序(Kahn 算法):无约束系统保持原始顺序,循环依赖抛 CycleDependencyError
集合机制:inSet('名') 把系统加入虚拟分组,其他系统用 executeAfter('set:名') 批量依赖
10. 世界 — ECSWorld.ts + ECSWorldManager.ts
ECSWorld:运行期数据容器
entities — 活动实体表(eid → 实体)
groups — 响应式查询分组
singletons — 单例组件表
refs — @entityRef 引用追踪
commands — 延迟结构变更命令队列
epoch — 世代号(每帧递增,变更检测用)
getEntity(ctor) — 创建/从池获取实体
assignEid(entity, eid) — 反序列化时保持 eid 一致
ECSWorldManager(ecs.world):多世界管理
get(name?) / default() / current — 获取/切换世界
use(world) — 切换当前世界,返回切换前的世界
inWorld(world, fn) — 在指定世界中执行,自动还原
createSystems(world, ...ctors) — 批量装配系统并 init
defer(fn) / flushCommands() — 延迟结构变更
11. 命令缓冲 — ECSCommandBuffer.ts
延迟结构变更队列,帧末由 RootSystem.execute 统一 flush
push(fn) 入队,flush() 先快照再执行(避免本帧新入队命令在本帧执行)
12. 对象池 — ECSPoolManager.ts + ECSDynamicPool.ts
ecs.pool:统一管理实体/组件动态对象池
getPool(name, factory) — 获取或创建池
clearAll() / clearPools() — 清空池缓存(不触碰存活数据)
getAllMetrics() — 获取各池统计信息(命中/未命中/缓存/创建数)
13. 实体引用 — ECSEntityRef.ts + ECSReferenceTracker.ts
@ecs.entityRef() 属性装饰器:标记组件属性为实体引用
目标实体销毁时自动置 null,避免悬空引用
组件回收时 clearComponentEntityRefs 清理所有引用
14. SoA 列存储 — StorageSoA.ts + StorageDecorators.ts
@ecs.storage.enableSoA 类装饰器:为组件启用 SoA 列存储(默认 AoS,opt-in)
字段装饰器:float64 / float32 / int32 / uint32 / int16 / uint16 / int8 / uint8
数值字段按列存入 TypedArray,按 eid 分配槽位
acquire 返回 Proxy 视图:SoA 字段读写直接落到 TypedArray,非 SoA 字段走后备实例
槽位超出容量时 2 倍扩容,释放时入空闲栈
自注册机制:模块加载时注册到核心,删除 storage/ 目录后基础 ECS 仍可运行
15. 网络同步 — NetworkSync.ts + SyncDecorators.ts + SyncCodec.ts + ByteBuffer.ts
@ecs.network.sync(类型) 字段装饰器:标记组件字段参与网络同步
ecs.network.net 门面:
encodeWorld(op?) — 编码当前世界为紧凑二进制(Full 全量 / Delta 增量)
applyToWorld(bytes, onMissing?) — 将二进制同步数据应用到世界
track(entity, markAll?) — 为实体初始化变更追踪器
clearDirty() — 清除所有脏标记
SyncCodec:实体/组件级编解码器
ByteWriter / ByteReader:二进制读写缓冲(变长整数等)
ChangeTracker:字段级脏标记追踪
16. 序列化 — Serialization.ts + Incremental.ts
@ecs.serialize() 字段装饰器:标记组件需要持久化的字段
全量序列化:
ecs.serialize.serializeWorld(pretty?) — 序列化当前世界为 JSON
ecs.serialize.deserializeWorld(json) — 从 JSON 反序列化到当前世界
增量序列化:
ecs.serialize.snapshot() — 对当前世界拍快照(基线)
ecs.serialize.computeDelta(base) — 计算相对基线的增量(added / removed / changed)
ecs.serialize.applyDelta(delta) — 将增量应用到当前世界
保留实体层级(parentEid),两阶段重建(先建实体+组件,再重建父子)
17. 监控日志 — ECSMonitorLogger.ts
零入侵监控模块,通过控制台命令触发
注册全局命令:
ecsLog() — 打印所有监控表格
ecsWorldSummary() — 各世界实体/系统/组件缓存统计
ecsSummary() — 总体统计(所有世界合计)
ecsEntityPools() — 实体池明细(命中/未命中/缓存)
ecsCompPools() — 组件池明细(按 M/B/V/VC 分类排序)
ecsEntityCaches() — 实体软移除组件缓存明细
ecsHelp() — 显示帮助信息
2026-06-12 21:52:47 +08:00

374 lines
12 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Camera, Node, warn } from 'cc';
import { gui } from '../Gui';
import { LayerDialog } from './LayerDialog';
import type { UIConfigMap, Uiid } from './LayerEnum';
import { LayerCustomType, LayerTypeCls } from './LayerEnum';
import { LayerGame } from './LayerGame';
import { LayerHelper } from './LayerHelper';
import { LayerNotify } from './LayerNotify';
import { LayerPopUp } from './LayerPopup';
import { LayerUI } from './LayerUI';
import type { UIParam } from './LayerUIElement';
import { LayerUIElement } from './LayerUIElement';
import type { UIConfig } from './UIConfig';
import { ScreenAdapter } from './ScreenAdapter';
/** 界面层级管理器 */
export class LayerManager {
/** 界面根节点 */
root!: Node;
/** 界面摄像机 */
camera!: Camera;
/** 游戏界面特效层 */
game!: LayerGame;
/** 新手引导层 */
guide!: Node;
/** 屏幕适配器 */
adapter: ScreenAdapter = new ScreenAdapter();
/** 消息提示控制器请使用show方法来显示 */
private notify!: LayerNotify;
/** 界面层集合 - 无自定义类型 */
private uiLayers: Map<string, LayerUI> = new Map();
/** 界面层组件集合 */
private clsLayers: Map<string, any> = new Map();
constructor() {
this.clsLayers.set(LayerTypeCls.UI, LayerUI);
this.clsLayers.set(LayerTypeCls.PopUp, LayerPopUp);
this.clsLayers.set(LayerTypeCls.Dialog, LayerDialog);
this.clsLayers.set(LayerTypeCls.Notify, LayerNotify);
this.clsLayers.set(LayerTypeCls.Game, LayerGame);
this.clsLayers.set(LayerTypeCls.Node, null);
}
/**
* 注册自定义界面层对象
* @param type 自定义界面层类型
* @param cls 自定义界面层对象
*/
registerLayerCls(type: string, cls: any) {
if (this.clsLayers.has(type)) {
console.error('已存在自定义界面层类型', type);
return;
}
this.clsLayers.set(type, cls);
}
/**
* 初始化界面层
* @param root 界面根节点
*/
private initLayer(root: Node, config: any) {
if (config == null) {
console.error('请升级到最新版本框架,界面层级管理修改为数据驱动。参考模板项目中的config.json配置文件');
return;
}
this.root = root;
this.adapter.init(this.root);
this.camera = this.root.getComponentInChildren(Camera)!;
// 创建界面层
for (let i = 0; i < config.length; i++) {
const data = config[i];
let layer: Node = null!;
if (data.type == LayerTypeCls.Node) {
switch (data.name) {
case LayerCustomType.Guide:
this.guide = this.create_node(data.name);
layer = this.guide;
break;
}
}
else {
const cls = this.clsLayers.get(data.type);
if (cls) {
layer = new cls(data.name);
}
else {
console.error('未识别的界面层类型', data.type);
}
}
root.addChild(layer);
if (layer instanceof LayerUI)
this.uiLayers.set(data.name, layer);
else if (layer instanceof LayerNotify)
this.notify = layer;
else if (layer instanceof LayerGame)
this.game = layer;
}
}
/**
* 初始化所有UI的配置对象
* @param configs 配置对象
*/
init(configs: UIConfigMap): void {
gui.internal.initConfigs(configs);
}
/**
* 设置窗口打开失败回调
* @param callback 回调方法
*/
setOpenFailure(callback: Function) {
this.uiLayers.forEach((layer: LayerUI) => {
layer.onOpenFailure = callback;
});
}
/**
* 渐隐飘过提示
* @param content 文本表示
* @param useI18n 是否使用多语言
* @example
* oops.gui.toast("提示内容");
*/
toast(content: string, useI18n = false) {
this.notify.toast(content, useI18n);
}
/** 打开等待提示 */
waitOpen() {
this.notify.waitOpen();
}
/** 关闭等待提示 */
waitClose() {
this.notify.waitClose();
}
/** 获取界面信息 */
private getInfo(uiid: Uiid): { key: string; config: UIConfig } {
let key = '';
let config: UIConfig = null!;
// 界面配置
if (typeof uiid === 'object') {
key = uiid.bundle + '_' + uiid.prefab;
config = gui.internal.getConfig(key);
if (config == null) {
config = uiid;
gui.internal.setConfig(key, uiid);
}
}
// 界面对象 - 配合gui.register使用
else if (uiid instanceof Function) {
//@ts-ignore
key = uiid[gui.internal.GUI_KEY];
config = gui.internal.getConfig(key);
}
// 界面唯一标记
else {
key = uiid.toString();
config = gui.internal.getConfig(key);
if (config == null) {
console.error(`打开编号为【${uiid}】的界面失败,配置信息不存在`);
}
}
return { key, config };
}
/**
* 同步打开一个窗口
* @param uiid 窗口唯一编号
* @param param 窗口参数
* @example
var uic: UICallbacks = {
onAdded: (node: Node, params: any) => {
var comp = node.getComponent(LoadingViewComp) as ecs.Comp;
}
onRemoved:(node: Node | null, params: any) => {
}
};
oops.gui.open(UIID.Loading);
*/
open(uiid: Uiid, param?: UIParam): Promise<Node> {
const info = this.getInfo(uiid);
// 配置不存在时直接拒绝,避免 Promise 永久挂起
if (info.config == null) {
const error = `打开编号为【${uiid}】的界面失败,配置信息不存在`;
console.error(error);
return Promise.reject(new Error(error));
}
const layer = this.uiLayers.get(info.config.layer);
if (!layer) {
const error = `打开编号为【${uiid}】的界面失败,界面层【${info.config.layer}】不存在`;
console.error(error);
return Promise.reject(new Error(error));
}
return layer.add(info.key, info.config, param);
}
/** 显示指定界面 */
show(uiid: Uiid) {
const info = this.getInfo(uiid);
const layer = this.uiLayers.get(info.config.layer);
if (layer) {
layer.show(info.config.prefab);
}
else {
console.error(`打开编号为【${uiid}】的界面失败,界面层不存在`);
}
}
/**
* 移除指定标识的窗口
* @param uiid 窗口唯一标识
* @example
* oops.gui.remove(UIID.Loading);
*/
remove(uiid: Uiid) {
const info = this.getInfo(uiid);
const layer = this.uiLayers.get(info.config.layer);
if (layer) {
layer.remove(info.config.prefab);
}
else {
console.error(`移除编号为【${uiid}】的界面失败,界面层不存在`);
}
}
/**
* 清理指定界面的缓存
* @param uiid 窗口唯一标识
* @example
* oops.gui.removeCache(UIID.Loading);
*/
removeCache(uiid: Uiid) {
const info = this.getInfo(uiid);
const layer = this.uiLayers.get(info.config.layer);
if (layer) {
layer.removeCache(info.config.prefab);
}
else {
console.error(`移除编号为【${uiid}】的界面失败,界面层不存在`);
}
}
/**
* 通过界面节点移除
* @param node 窗口节点
* @example
* oops.gui.removeByNode(cc.Node);
*/
removeByNode(node: Node) {
if (node instanceof Node) {
const comp = node.getComponent(LayerUIElement);
if (comp && comp.state) {
// 释放显示的界面
if (node.parent) {
const uiid = gui.internal.getConfig(comp.state.uiid);
this.remove(uiid);
}
// 释放缓存中的界面
else {
const layer = this.uiLayers.get(comp.state.config.layer);
if (layer) {
// @ts-ignore 注:不对外使用
layer.removeCache(comp.state.config.prefab);
}
}
}
else {
warn('当前删除的 Node 不是通过界面管理器添加的');
node.destroy();
}
}
}
/**
* 场景替换
* @param removeUiId 移除场景编号
* @param openUiid 新打开场景编号
* @param param 新打开场景参数
*/
async replace(removeUiId: Uiid, openUiid: Uiid, param?: UIParam): Promise<Node> {
const node = await this.open(openUiid, param);
this.remove(removeUiId);
return node;
}
/**
* 缓存中是否存在指定标识的窗口
* @param uiid 窗口唯一标识
* @example
* oops.gui.has(UIID.Loading);
*/
has(uiid: Uiid): boolean {
const info = this.getInfo(uiid);
let result = false;
const layer = this.uiLayers.get(info.config.layer);
if (layer) {
result = layer.has(info.config.prefab);
}
else {
console.error(`验证编号为【${uiid}】的界面失败,界面层不存在`);
}
return result;
}
/**
* 界面缓存中是否存在指定标识的窗口(用于 destroy: false 的界面)
* @param uiid 窗口唯一标识
* @example
* oops.gui.isCached(UIID.Loading);
*/
hasCache(uiid: Uiid): boolean {
const info = this.getInfo(uiid);
let result = false;
const layer = this.uiLayers.get(info.config.layer);
if (layer) {
result = layer.hasCache(info.config.prefab);
}
else {
console.error(`验证编号为【${uiid}】的界面缓存失败,界面层不存在`);
}
return result;
}
/**
* 缓存中是否存在指定标识的窗口
* @param uiid 窗口唯一标识
* @example
* oops.gui.has(UIID.Loading);
*/
get(uiid: Uiid): Node {
const info = this.getInfo(uiid);
let result: Node = null!;
const layer = this.uiLayers.get(info.config.layer);
if (layer) {
result = layer.get(info.config.prefab);
}
else {
console.error(`获取编号为【${uiid}】的界面失败,界面层不存在`);
}
return result;
}
/**
* 清除所有窗口
* @param isDestroy 移除后是否释放
* @example
* oops.gui.clear();
*/
clear(isDestroy = true) {
this.uiLayers.forEach((layer: LayerUI) => {
layer.clear(isDestroy);
});
}
private create_node(name: string) {
const node = new Node(name);
LayerHelper.setFullScreen(node);
return node;
}
}