Entity Systems

Entity Systems

3f51727357dd2eeb7fbb59993e0fca29?s=128

Jason Frame

February 12, 2013
Tweet

Transcript

  1. Entity Systems Jason Frame | http://(twitter|github).com/jaz303 Saturday, 1 June 13

  2. Entity Systems • Origins in MMORPGs • Collection of architecture

    patterns used to organise a game “world” • No fixed definition Saturday, 1 June 13
  3. Entity Systems • Decrease Coupling • Increase (runtime) flexibility •

    Separate data from behaviour Saturday, 1 June 13
  4. Traditional Inheritance Player() Player Class Saturday, 1 June 13

  5. Traditional Inheritance Player(sprite) Player Class Saturday, 1 June 13

  6. Traditional Inheritance Player(sprite,position,direction,speed) Player Class Saturday, 1 June 13

  7. Traditional Inheritance Player(sprite,position,direction,speed,health) Player Class Saturday, 1 June 13

  8. Traditional Inheritance Player(sprite,position,direction,speed,health) Item(sprite,position,weight) Add Items Saturday, 1 June 13

  9. Traditional Inheritance GameObject(sprite,position) Player(direction,speed,health) Item(weight) Refactor Saturday, 1 June 13

  10. Traditional Inheritance GameObject(sprite,position) Player(direction,speed,health) Item(weight) Enemy(direction,speed,health,treasure) Add Enemies Saturday, 1

    June 13
  11. Traditional Inheritance GameObject(sprite,position) LivingEntity(direction,speed,health) Player() Enemy(treasure) Item(weight) Refactor Saturday, 1

    June 13
  12. Traditional Inheritance GameObject(sprite,position) LivingEntity(direction,speed,health) Player() Enemy(treasure) Item(weight) Trigger(position) Triggers Saturday,

    1 June 13
  13. Traditional Inheritance GameObject(position) RenderableGameObject(sprite) LivingEntity(direction,speed,health) Player() Enemy(treasure) Item(weight) Trigger() Refactor

    Saturday, 1 June 13
  14. Traditional Inheritance GameObject(position) RenderableGameObject(sprite) PhysicsObject(direction,speed,mass) LivingEntity(health) Player() Enemy(treasure) Item(weight) Trigger()

    Add Physics Saturday, 1 June 13
  15. Traditional Inheritance GameObject(position) RenderableGameObject(sprite) PhysicsObject(direction,speed,mass) LivingEntity(health) Player() Enemy(treasure) Item(weight) Chest(treasure)

    Trigger() “I need that chest to drop treasure” Saturday, 1 June 13
  16. Traditional Inheritance GameObject(position) RenderableGameObject(sprite) PhysicsObject(direction,speed,mass) LivingEntity(health) Player() Enemy(treasure) Item(weight) Chest(treasure)

    Trigger() “I need that chest to drop treasure” Saturday, 1 June 13
  17. Traditional Inheritance GameObject(position) RenderableGameObject(sprite) PhysicsObject(direction,speed,mass) LivingEntity(health) Player() Enemy(treasure) Item(weight) Trigger()

    “I need that trigger to move” Saturday, 1 June 13
  18. Traditional Inheritance GameObject(position) PhysicsObject(direction,speed,mass) RenderableGameObject(sprite) LivingEntity(health) Player() Enemy(treasure) Item(weight) Trigger()

    “I need that trigger to move” Saturday, 1 June 13
  19. Traditional Inheritance GameObject(position,isMoveable,direction,speed,mass) RenderableGameObject(sprite) LivingEntity(health) Player() Enemy(treasure) Item(weight) Trigger() “I

    need that trigger to move” - Refactor! Saturday, 1 June 13
  20. Traditional Inheritance GameObject(position,isMoveable,direction,speed,mass) RenderableGameObject(sprite) LivingEntity(health) Player() Enemy(treasure) Item(weight) Trigger() “I

    need that trigger to look like a spotlight” Saturday, 1 June 13
  21. Traditional Inheritance GameObject(position,isMoveable,direction,speed,mass,isDrawable,sprite) LivingEntity(health) Player() Enemy(treasure) Item(weight) Trigger() “I need

    that trigger to look like a spotlight” Saturday, 1 June 13
  22. Traditional Inheritance • Elaborate object hierarchies are inflexible • Functionality

    gradually bubbles to the top • Wasted memory • Increased complexity Saturday, 1 June 13
  23. Composition Implement each facet of an entity in its own

    class: Saturday, 1 June 13
  24. Composition class GameObject { public Health health = null; public

    Physics physics = null; public Position position = null; public Inventory inventory = null; } player = new GameObject(); player.health = new PlayerHealth(100); player.physics = new DefaultPhysics(); player.position = new Position(mkvec2(0,0)); Implement each facet of an entity in its own class: Saturday, 1 June 13
  25. Mixins function GameObject() { } GameObject.prototype = { addPhysics: function(props)

    { props = props || {}; this.x = props.x || 0.0; this.y = props.y || 0.0; this.vx = props.vx || 0.0; this.vy = props.vy || 0.0; this.inverseMass = 1 / (props.mass || 1); this.distanceFrom = function(rhs) { // calculate distance from rhs and return } } } Great for dynamic languages! Saturday, 1 June 13
  26. Mixins var obj = new GameObject(); obj.addPhysics({x: 0, y: 0,

    }); Great for dynamic languages! Saturday, 1 June 13
  27. Mixins - Pros • No longer carrying around a bunch

    of extra cruft on objects that don't need it • Can craft any type of object on the fly • Don't need concrete classes for each combination Saturday, 1 June 13
  28. Mixins - Cons • In the absence of a powerful

    type system still need to check what we're dealing with: function gameUpdate(delta) { allGameObjects.forEach(function(obj) { if (object.hasPhysics) { // do stuff } if (object.hasAI) { // do stuff } }); } Saturday, 1 June 13
  29. The Problem • Fundamental mismatch • Object bigotry? • Not

    every object needs a bit of everything • Is there a better way of thinking about this? Saturday, 1 June 13
  30. Autopoietic (Social) Systems • Infinitely chaotic environment • Systems operate

    on environment • Systems extract information from environment • Systems are operationally closed Saturday, 1 June 13
  31. Systems • Implement one single game task • Maintains a

    collection of components • Acceptance check • update(delta) method • e.g. Physics, rendering, AI etc. Saturday, 1 June 13
  32. Entities • Represents any game object • e.g. player, door,

    trigger, monster, gun-turret • Just a (unique) integer ID Saturday, 1 June 13
  33. Components • Describes a single facet of a single entity

    • Usually a map of key/value pairs • Max of one component of each type per entity • Data only - no behaviour/logic Saturday, 1 June 13
  34. Components positionComponent = {x:0, y:0} physicsComponent = {vx:0, vy:0, inverseMass:1}

    healthComponent = {health:100} Saturday, 1 June 13
  35. Entities & Components positionComponent {x:0, y:0} physicsComponent {vx:0, vy:0, inverseMass:1}

    healthComponent {health:100} •Entity is bag of components •Entity uses ID as primary key to look up components EID 1 => Still just data! Saturday, 1 June 13
  36. World • Container • Query methods • Lifecycle methods •

    Message bus Saturday, 1 June 13
  37. What is an Entity System? Replace object-centric approach with data-centric

    approach Saturday, 1 June 13
  38. Entity System Benefits • Flexible component composition • Tooling •

    Serialisation • Parallelism • Runtime modification Saturday, 1 June 13
  39. Runtime Modification • Remove item’s Position component • Add CarriedItem

    component to item Pick Up Item Saturday, 1 June 13
  40. Runtime Modification • Remove Health component • Remove Inventory component

    • Change Animation component to Death animation • Create new entity with existing Inventory/Position components Entity Death Saturday, 1 June 13
  41. Example - Bootstrapping world = new World(); world.addSystem(new PlayerInputSystem(world)); world.addSystem(new

    PhysicsSystem(world)); world.addSystem(new RenderingSystem(world)); Saturday, 1 June 13
  42. Example - Entity Creation entityId = world.createEntity(); world.addComponent(entityId, { type:'physics',

    x:0, y:0, vx: 0, vy: 0, mass: 1 }); world.addComponent(entityId, { type: 'playerInput' }); world.addComponent(entityId, { type: 'render', sprite: 'paddle' }); Saturday, 1 June 13
  43. Example - Add Entity to World world.addEntity(entityId); Saturday, 1 June

    13
  44. Example - World Lifecycle Events • Adding entity to world

    triggers lifecycle event • Inform all systems of new entity • Other lifecycle events: delete entity, change entity, enable/disable entity Saturday, 1 June 13
  45. Example - Game Update setInterval(function() { world.update(40); }, 40); Saturday,

    1 June 13
  46. Example - Game Update world.update = function(delta) { this._systems.forEach(function(system) {

    system.update(delta); }); } Saturday, 1 June 13
  47. Example - Physics System function update(delta) { this._entities.forEach(function(entity) { var

    physics = this._manager.getComponent( entity, 'physics'); physics.x += physics.vx * delta / 1000; physics.y += physics.vy * delta / 1000; physics.vx *= physics.damping; physics.vy *= physics.damping; }); // resolve collisions } Saturday, 1 June 13
  48. Inter-System Communication • `PhysicsSystem` detects car hits wall at speed;

    `DamageSystem` must react • `DamageSystem` detect character is dead. `InventorySystem` should drop treasure and `AnimationSystem` should play death animation Saturday, 1 June 13
  49. Inter-System Communication • Systems neither know about nor understand other

    systems • Decouple systems • Message passing Saturday, 1 June 13
  50. Example - Inter-system Communication function PhysicsSystem() { var self =

    this; this.update = function(delta) { var collisions = []; // do physics mojo... // ... // ... collisions.forEach(function(c) { // `c` is collision event object self.emit('collision', c); }); } } Saturday, 1 June 13
  51. Example - Inter-system Communication function DamageSystem(world) { var self =

    this; world.on('collision', function(collisionEvent) { if (collisionEvent.speed > DAMAGE_THRESHOLD) { var cmp = self._manager.getComponent( collisionEvent.entity, 'health'); cmp.health -= 10; if (cmp <= 0) { self.emit('entityDead', { ... }); } } }); } Saturday, 1 June 13
  52. Revisiting Entities • Entities as IDs is a throwback to

    statically- typed languages • In Javascript, we can make entity an object •Do not allow logic to seep in Saturday, 1 June 13
  53. Entities as Objects function Entity(id, manager) { this.id = id;

    this._manager = manager; } Entity.prototype.addComponent = function(name, cmp) { this[name] = cmp; // notify observers } entity.addComponent('physics', ...); // check for component if ('physics' in entity) { Saturday, 1 June 13
  54. Entities as Objects entity.hasComponent(); entity.removeComponent(); entity.removeAllComponents(); Helper methods: Saturday, 1

    June 13
  55. Entities as Objects entity.getHealth(); entity.attackCreature(jason); entity.setCombatBehaviour(Behaviour.FLEE); DON’T DO THIS: Saturday,

    1 June 13
  56. Attribute/Behaviour Systems • Again, entity is just an ID •

    No systems or components • Instead, attributes and behaviours Saturday, 1 June 13
  57. Attribute Observable key/value pair Saturday, 1 June 13

  58. Attribute function makeAttribute(name, type, value) { var observers = [];

    function notify(ov, nv) { for (var i = observers.length - 1; i >= 0; --i) { observers[i].onMessage({ type: ‘attributeChange’, attribute: attr, oldValue: ov, newValue: nv }); } } var attr = { name: name, type: type, get: function() { return value; }, set: function(v) { var oldValue = value; value = v; notify(oldValue, value); }, addObserver: function(b) { observers.push(b); }, removeObserver: function(b) { observers.splice(observers.indexOf(b), 1); }, }; return attr; } Saturday, 1 June 13
  59. Behaviour • Object that responds to a 2 methods •

    onUpdate(delta) • onMessage(message) • May have private internal state Saturday, 1 June 13
  60. Game Update Loop function update(delta) { var behaviour = rootBehaviour;

    while (behaviour) { behaviour.update(delta); behaviour = behaviour.next; } } Saturday, 1 June 13
  61. Managing Determinism • Synchronisation Points • Queues • Asynchronous/synchronous events

    Saturday, 1 June 13
  62. Optimisation Saturday, 1 June 13

  63. Optimisation - Caching function PhysicsSystem() { this._entities = {}; this.update

    = function() { for (var entityId in this._entities) { var physicsComponent = this._entities[entityId].getComponent('physics'); // integrate position } // resolve collisions } this.entityAdded = function(entity) { this._entities[entity.id] = entity; } // entityRemoved // entityChanged } Saturday, 1 June 13
  64. Optimisation - Caching function PhysicsSystem() { this._entities = {}; this.update

    = function() { for (var entityId in this._entities) { var physicsComponent = this._entities[entityId]; // integrate position } // resolve collisions } this.entityAdded = function(entity) { // store the physics component directly this._entities[entity.id] = entity.getComponent('physics'); } // entityRemoved // entityChanged } Saturday, 1 June 13
  65. Optimisation - Component Querying function systemAcceptsEntity(entity) { return entity.hasComponent('physics') &&

    entity.hasComponent('render') && entity.hasComponent('damage'); } Method call + hash lookup for each test Saturday, 1 June 13
  66. Optimisation - Component Querying Components = { PHYSICS: 1, DAMAGE:

    2, RENDER: 4, ... }; entity = world.createEntity(); entity.addComponent(Components.PHYSICS,{ ... }); entity.addComponent(Components.RENDER, { ... }); function Entity() { this._components = {}; this._componentMask = 0; } Entity.prototype.addComponent = function(type, props) { this._components[type] = props; this._componentMask |= type; } Idea: represent each type of component with a single bit. Saturday, 1 June 13
  67. Optimisation - Component Querying Entity.prototype.hasComponent = function(mask) { return (this._componentMask

    & mask) == mask; } // check for a single component entity.hasComponent(Components.PHYSICS); // check for multiple components entity.hasComponent(Components.PHYSICS | Components.DAMAGE | Components.RENDER); Idea: represent each type of component with a single bit. Saturday, 1 June 13
  68. Optimisation - Bit mask limitations • Limited by the number

    of bits in the underlying data type • In Javascript, bitwise operations operate on 32 bits • 32 bits => 32 components max • Array/object abstraction? Saturday, 1 June 13
  69. Optimisation - Event Handling Events = { COLLISION_DETECTED: 1, PLAYER_DIED:

    2, SOUND_EMITTED: 4 ... } Saturday, 1 June 13
  70. Optimisation - Event Handling • Introduce event categories • Each

    event belongs to single category • Split up the bitfield • Each category gets unique bit • Each system specifies its category mask • Use remaining bits for Event ID Saturday, 1 June 13
  71. Optimisation - Event Handling Role <-- Category ---> <--------- Event

    -----------> Bit 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 In Javascript, 16 bits for category + 16 bits for event number == 16 * (2^16) == 1M event types Saturday, 1 June 13
  72. Optimisation - Exploit V8 • Assemble objects in deterministic order

    Saturday, 1 June 13
  73. Entity Systems - Drawbacks • Overhead • Hierarchical data problem

    • “Framework” required Saturday, 1 June 13
  74. Beyond Games • Simulations/data visualisations • Chris Granger’s Light Table

    project uses a component-entity system behind the scenes • Useful anywhere custom objects must be composed dynamically at runtime Saturday, 1 June 13
  75. Thank you! Saturday, 1 June 13