I wonder how to implement in C ++ the fastest version of the system of entity components (ECS from now on).
First of all, regarding terminology:
- A scene is a container for entities (and systems in some implementations).
- The component is a simple data warehouse (e.g. position, collision column, image for rendering, etc.).
- a The system executes logic for components that meet the requirements of the System (this may be physics, player input, simple rendering, etc.).
- An Entity Contains Several Components to Compose the Final Behavior
I have listed all the projects that we came up with below.
1. The "naive" way
The scene contains all unordered entities.
As a system update, each system must scroll through all the objects and check whether each Entity contains all the necessary components, and then perform an update for these objects.
Obviously, this method is not very effective when there are a large number of systems and / or many objects.
2. Using "bitmask enumerations" and mapping
Each component contains a type identifier in the form of a bitmask (for example, 1u << 5 / binary [0...]100000 ). Each Entity can then compile all component identifiers of the component (provided that all type identifiers are unique within Entity), so it looks something like this:
1u << 5 | 1u << 3 | 1u << 1 binary [0...]101010
The scene contains some kind of map where Systems can easily search for suitable objects:
MovementSystem::update() { for (auto& kv : parent_scene_) {
Pros :
- Faster than the naive way
vs
- Systems must search for relevant objects every time they are updated.
- The bitmask (enumeration) is limited by the number of bits (32 for
uint32_t , at least 64 for unsigned long long ), and in some cases you may need more components than the bitmask allows.
3. Use without systems
This method is described by Danvil in the answer below .
Pros
- Completely gets rid of bitmasks.
- Most likely faster than design # 2.
vs
- It relies on
dynamic_cast to search for a component, while design # 2 can directly search for a component, and then static_cast it static_cast .
4. Use of spare kits
This method is described in skypjack in the answer below . He explained his approach in detail, so I suggest you read his answer.
user1795160
source share