Building Games in ECS with Entity Relationships

  • What are Entity Relationships
  • Querying for Relationships

So what are Entity Relationships?

entity.add<MeleeUnit>() [live demo]
entity.set<Position>({10, 20}) [live demo]
  1. Relationships let you add a pair of two things to an entity
entity.add<Likes, Dogs>() [live demo]
entity.add< relation<Likes, Dogs> >();
player_1.add<Attacks>(player_2) [live demo]
Earth.add(ChildOf, Sun); Moon.add(ChildOf, Earth) [live demo]
entity.set<Eats>(Apples, {10}) [live demo]
entity.add<MeleeUnit>();
entity.add<MeleeUnit>(); // already present, do nothing
animation.set<Start, Position>({0, 0}); animation.set<Stop, Position>({10, 20}) [live demo]
inventory.set<Item>(Coins, {30}); inventory.set<Item>(WoodenSword, {2}) [live demo]
child.add(ChildOf, parent_a); child.add(ChildOf, parent_b) [live demo]
enum Color {
Red, Green, Blue
};
// Add (Color, Red)
entity.add(Color::Red);
// Replace (Color, Red) with (Color, Green)
entity.add(Color::Green);
entity.add(Color::Red); entity.add(Color::Green) [live demo]
  1. Relationships lets you add a pair of two things to an entity
  2. Relationship pairs can contain regular entities
  3. Each relationship pair corresponds with a unique component id
  4. Relationships make it possible to add a component multiple times
  5. Exclusive relationships swap out old instances with new instances

ECS Queries

Position, Velocity
Evaluation of query “Position, Velocity” [live demo]

Relationship queries

SpaceShip, Position, (DockedTo, Earth)
Evaluation of query “SpaceShip, Position, (DockedTo, Earth)” [live demo]

Wildcard Queries

SpaceShip, Position, (DockedTo, *)
Evaluation of query “SpaceShip, Position, (DockedTo, *)” [live demo]
map<component_id, set<table_id>> id_index
tables = id_index[ SpaceShip ]
id_index[ Position ].has(table.id)
tables = id_index[ pair(DockedTo, Earth) ]
tables = id_index[ pair(DockedTo, Wildcard) ]

Querying the Graph

  1. Allow the nodes in a query to match on different entities
  2. Allow the entity matched by a node to be determined at evaluation time
Position, Velocity, TimeScale(Game)
Position($This), Velocity($This), TimeScale(Game)
SpaceShip, (DockedTo, $Planet), Planet($Planet)
Evaluation of query “SpaceShip, (DockedTo, $Planet), Planet($Planet)” [live demo]
SpaceShip, 
(Faction, $SpaceShipFaction),
(DockedTo, $Planet),
Planet($Planet),
RuledBy($Planet, $PlanetFaction),
AlliedWith($SpaceShipFaction, $PlanetFaction)
Query evaluation graph [live demo]

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store