Class: Baku::EntityManager

Inherits:
Object
  • Object
show all
Defined in:
lib/baku/entity_manager.rb

Overview

The EntityManager stores entities in such a way that they can be retrieved efficiently by either ComponentMask or tag. Before storing any entities, the ComponentMasks that we wish to match on should be registered. This step is performed transparently by the World whenever a System is added.

Instance Method Summary collapse

Constructor Details

#initializeEntityManager

Returns a new instance of EntityManager.



7
8
9
10
# File 'lib/baku/entity_manager.rb', line 7

def initialize
  @entities_by_component_mask = {}
  @entities_by_tag = {}
end

Instance Method Details

#add_entity(entity) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/baku/entity_manager.rb', line 21

def add_entity(entity)
  add_entity_to_matching_component_lists(entity)
  
  entity.add_event_listener(:component_added,
                            method(:on_entity_component_added))
  entity.add_event_listener(:component_removed,
                            method(:on_entity_component_removed))

  entity.tags.each do |tag|
    @entities_by_tag[tag] ||= []
    @entities_by_tag[tag] << entity
  end
end

#disposeObject



12
13
14
15
# File 'lib/baku/entity_manager.rb', line 12

def dispose
  @entities_by_component_mask.clear
  @entities_by_tag.clear
end

#get_entities(component_mask) ⇒ Object



52
53
54
# File 'lib/baku/entity_manager.rb', line 52

def get_entities(component_mask)
  @entities_by_component_mask[component_mask] || []
end

#get_entities_by_tag(tag) ⇒ Object



56
57
58
# File 'lib/baku/entity_manager.rb', line 56

def get_entities_by_tag(tag)
  @entities_by_tag[tag] || []
end

#register_component_mask(component_mask) ⇒ Object



17
18
19
# File 'lib/baku/entity_manager.rb', line 17

def register_component_mask(component_mask)
  @entities_by_component_mask[component_mask] = []
end

#remove_entity(entity) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/baku/entity_manager.rb', line 35

def remove_entity(entity)
  entity.tags.each do |tag|
    @entities_by_tag[tag].delete(entity)
  end
  
  entity.remove_event_listener(:component_added,
                               method(:on_entity_component_added))
  entity.remove_event_listener(:component_removed,
                               method(:on_entity_component_removed))

  @entities_by_component_mask.each do |component_mask, entities|
    if component_mask.matches?(entity.component_mask)
      entities.delete(entity)
    end
  end
end