Files
DX12/docs/架构分析/Entity组件分析.md
2026-03-19 18:27:49 +08:00

59 lines
1.5 KiB
Markdown
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.
# Entity 组件分析
## 组件职责
`Entity.*` 负责:
- 分配与回收 `entity_id`
- 维护实体到 `transform/script` 句柄的绑定;
- 提供 `is_alive` 存活判定。
## 核心存储
位于 `Entity.cpp` 的静态容器:
- `transforms`:实体索引 -> 变换组件句柄
- `scripts`:实体索引 -> 脚本组件句柄
- `generations`:实体索引 -> 当前代数
- `free_ids`:可复用实体 ID 队列
## 创建流程
入口:`game_entity::create(entity_info info)`
主要步骤:
1. 校验 `info.transform`Transform 为必需组件;
2. 分配 `entity_id`
- 回收路径:从 `free_ids` 取旧 id`new_generation`
- 新建路径:追加新索引并扩展并行数组;
3. 创建 Transform 组件(强制);
4. 若传入脚本工厂,则创建 Script 组件(可选);
5. 返回 `entity` 轻句柄。
## 删除流程
入口:`game_entity::remove(entity_id id)`
步骤:
1. 校验实体存活;
2. 若存在脚本组件,先删脚本并清空句柄槽;
3. 删除 Transform 并清空句柄槽;
4. 把 id 放入 `free_ids`,等待复用。
## 存活判定规则
`is_alive(id)` 依赖两项:
- `generations[index] == id::generation(id)`
- `transforms[index].is_valid()`
这让“旧代数句柄”天然失效,避免悬挂句柄误访问。
## 设计特点
- Entity 层是组件索引空间的“主时钟”;
- Transform 与实体强 1:1 绑定;
- Script 按需挂载,存在即可访问,不存在则为空句柄。