ECS架构核心是实体为纯ID、组件为POD数据、系统为无状态函数;Entity是uint32_t包装,Component用连续vector存储并按ID对齐,System直接遍历对应数组执行逻辑,World统一管理生命周期与调度。
用C++实现一个简单的ECS(Entity-Component-System)架构,核心是把数据(Component)和逻辑(System)彻底分离,实体(Entity)只作为ID存在。不依赖复杂模板或宏,也能写出清晰、可扩展、缓存友好的基础版本。
Entity 就是一个无符号整数(如 uint32_t),用于唯一标识一个游戏对象。它本身不包含任何成员变量,也不继承任何类——避免虚函数开销和内存碎片。
可以加一层简单包装防止误用:
struct Entity {
uint32_t id;
explicit Entity(uint32_t i) : id(i) {}
bool operator==(const Entity& other) const { return id == other.id; }
};
Component 是 POD(Plain Old Data)类型:只有 public 成员变量,没有虚函数、构造/析构逻辑、指针或 STL 容器(避免非连续内存)。例如:
struct Position {
float x = 0.f, y = 0.f;
};
struct Velocity {
float dx = 0.f, dy = 0.f;
};
struct Renderable {
const char* texture_name = nullptr;
};
关键点:
System 不持有 Entity 或 Component 实例,只在运行时按需访问组件数组。例如移动系统:
struct MovementSystem {
std::vector& positions;
std::vector& velocities;
void update(float dt) {
size_t n = std::min(positions.size(), velocities.size());
for (size_t i = 0; i < n; ++i) {
positions[i].x += velocities[i].dx * dt;
positions[i].y += velocities[i].dy * dt;
}
}};
实际中可用标签(Tag)或位掩码(Archetype)加速查询,但最简版直接遍历对齐数组即可。
系统之间无依赖顺序,靠手动调用顺序控制(如先 update Input → Movement → Collision → Render)。
World 是 ECS 的调度中心,负责:
简易 registry 示例(不依赖 type_index):
templatestruct ComponentStorage { std::vector data; std::vector alive; // 标记该槽是否有效 void grow_to(size_t n) { if (data.size() < n) { data.resize(n); alive.resize(n, false); } } T& get(Entity e) { return data[e.id]; } void set(Entity e, const T& v) { grow_to(e.id + 1); data[e.id] = v; alive[e.id] = true; }};
struct World { ComponentStorage
positions; ComponentStorage velocities; // ... 其他组件 Entity create_entity() { // 简单线性分配(生产环境建议 freelist) return Entity(next_id++); } void update(float dt) { movement_system.update(dt); // ... }private: uint32_t next_id = 0; MovementSystem movement_system{positions.data, velocities.data}; };
基本上就这些。不需要反射、不强制用宏、不绑定特定框架——C++11 起就能写。重点是守住“组件即数据、系统即函数、实体即ID”的边
界,后续再按需加入 archetype、事件总线、多线程任务调度等增强特性。