entities
entities
- 2014-03-11
- mikzzz
Entities
An entityx::Entity is a convenience class wrapping an opaque uint64_t value allocated by the entityx::EntityManager. Each entity has a set of components associated with it that can be added, queried or retrieved directly.
Creating an entity is as simple as:
#include <entityx/entityx.h>
entityx::EntityX ex;
entityx::Entity entity = ex.entities.create();
And destroying an entity is done with:
entity.destroy();
Implementation details
Each entityx::Entity is a convenience class wrapping an entityx::Entity::Id.
An entityx::Entity handle can be invalidated with invalidate(). This does not affect the underlying entity.
When an entity is destroyed the manager adds its ID to a free list and invalidates the entityx::Entity handle.
When an entity is created IDs are recycled from the free list first, before allocating new ones.
An entityx::Entity ID contains an index and a version. When an entity is destroyed, the version associated with the index is incremented, invalidating all previous entities referencing the previous ID.
To improve cache coherence, components are constructed in contiguous memory ranges by using entityx::EntityManager::assign
Components (entity data)
The general idea with the EntityX interpretation of ECS is to have as little logic in components as possible. All logic should be contained in Systems.
To that end Components are typically POD types consisting of self-contained sets of related data. Components can be any user defined struct/class.
Creating components
As an example, position and direction information might be represented as:
struct Position {
Position(float x = 0.0f, float y = 0.0f) : x(x), y(y) {}
float x, y;
};
struct Direction {
Direction(float x = 0.0f, float y = 0.0f) : x(x), y(y) {}
float x, y;
};
Assigning components to entities
To associate a component with a previously created entity call entityx::Entity::assign
// Assign a Position with x=1.0f and y=2.0f to “entity”
entity.assign
Querying entities and their components
To query all entities with a set of components assigned you can use two methods. Both methods will return only those entities that have all of the specified components associated with them.
entityx::EntityManager::each(f) provides functional-style iteration over entity components:
entities.each<Position, Direction>([](Entity entity, Position &position, Direction &direction) {
// Do things with entity, position and direction.
});
For iterator-style traversal of components, use entityx::EntityManager::entities_with_components():
ComponentHandle
ComponentHandle
for (Entity entity : entities.entities_with_components(position, direction)) {
// Do things with entity, position and direction.
}
To retrieve a component associated with an entity use entityx::Entity::component
ComponentHandle
if (position) {
// Do stuff with position
}
Component dependencies
In the case where a component has dependencies on other components, a helper class exists that will automatically create these dependencies.
eg. The following will also add Position and Direction components when a Physics component is added to an entity.
#include “entityx/deps/Dependencies.h”
system_manager->add<entityx::deps::Dependency<Physics, Position, Direction>>();
Implementation notes
Components must provide a no-argument constructor.
The default implementation can handle up to 64 components in total. This can be extended by changing the entityx::EntityManager::MAX_COMPONENTS constant.
Each type of component is allocated in (mostly) contiguous blocks to improve cache coherency.
Systems (implementing behavior)
Systems implement behavior using one or more components. Implementations are subclasses of System
A basic movement system might be implemented with something like the following:
struct MovementSystem : public System
void update(entityx::EntityManager &es, entityx::EventManager &events, TimeDelta dt) override {
es.each<Position, Direction>([dt](Entity entity, Position &position, Direction &direction) {
position.x += direction.x * dt;
position.y += direction.y * dt;
});
};
};
Events (communicating between systems)
Events are objects emitted by systems, typically when some condition is met. Listeners subscribe to an event type and will receive a callback for each event object emitted. An entityx::EventManager coordinates subscription and delivery of events between subscribers and emitters. Typically subscribers will be other systems, but need not be. Events are not part of the original ECS pattern, but they are an efficient alternative to component flags for sending infrequent data.
As an example, we might want to implement a very basic collision system using our Position data from above.
Creating event types
First, we define the event type, which for our example is simply the two entities that collided:
struct Collision {
Collision(entityx::Entity left, entityx::Entity right) : left(left), right(right) {}
entityx::Entity left, right;
};
Emitting events
Next we implement our collision system, which emits Collision objects via an entityx::EventManager instance whenever two entities collide.
class CollisionSystem : public System
public:
void update(entityx::EntityManager &es, entityx::EventManager &events, TimeDelta dt) override {
ComponentHandle
for (Entity left_entity : es.entities_with_components(left_position)) {
for (Entity right_entity : es.entities_with_components(right_position)) {
if (collide(left_position, right_position)) {
events.emit
}
}
}
};
};
Subscribing to events
Objects interested in receiving collision information can subscribe to Collision events by first subclassing the CRTP class Receiver
struct DebugSystem : public System
void configure(entityx::EventManager &event_manager) {
event_manager.subscribe
}
void update(entityx::EntityManager &entities, entityx::EventManager &events, TimeDelta dt) {}
void receive(const Collision &collision) {
LOG(DEBUG) << “entities collided: “ << collision.left << “ and “ << collision.right << endl;
}
};
Builtin events
Several events are emitted by EntityX itself:
EntityCreatedEvent - emitted when a new entityx::Entity has been created.
entityx::Entity entity - Newly created entityx::Entity.
EntityDestroyedEvent - emitted when an entityx::Entity is about to be destroyed.
entityx::Entity entity - entityx::Entity about to be destroyed.
ComponentAddedEvent
entityx::Entity entity - entityx::Entity that component was added to.
ComponentHandle
ComponentRemovedEvent
entityx::Entity entity - entityx::Entity that component was removed from.
ComponentHandle
Implementation notes
There can be more than one subscriber for an event; each one will be called.
Event objects are destroyed after delivery, so references should not be retained.
A single class can receive any number of types of events by implementing a receive(const EventType &) method for each event type.
Any class implementing Receiver can receive events, but typical usage is to make Systems also be Receivers.
When an Entity is destroyed it will cause all of its components to be removed. This triggers ComponentRemovedEvents to be triggered for each of its components. These events are triggered before the EntityDestroyedEvent.
Manager (tying it all together)
Managing systems, components and entities can be streamlined by using the “quick start” class EntityX. It simply provides pre-initialized EventManager, EntityManager and SystemManager instances.
To use it, subclass EntityX:
class Level : public EntityX {
public:
explicit Level(filename string) {
systems.add
systems.add
systems.add
systems.configure();
level.load(filename);
for (auto e : level.entity_data()) {
entityx::Entity entity = entities.create();
entity.assign<Position>(rand() % 100, rand() % 100);
entity.assign<Direction>((rand() % 10) - 5, (rand() % 10) - 5);
}
}
void update(TimeDelta dt) {
systems.update
systems.update
systems.update
}
Level level;
};
You can then step the entities explicitly inside your own game loop:
while (true) {
level.update(0.1);
}