summary refs log tree commit diff stats
path: root/src/entity_manager.h
blob: 9068fe3edb835ee37af8abaae106ee1bf717a5ab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#ifndef ENTITY_MANAGER_H_C5832F11
#define ENTITY_MANAGER_H_C5832F11

#include <map>
#include <vector>
#include <typeindex>
#include <set>
#include <stdexcept>
#include "component.h"
#include "algorithms.h"

class EntityManager {
private:

  struct EntityData {
    std::map<std::type_index, std::unique_ptr<Component>> components;
  };

  using database_type = std::vector<EntityData>;

public:

  using id_type = database_type::size_type;

private:

  database_type entities;
  std::vector<bool> slotAvailable;
  std::map<std::set<std::type_index>, std::set<id_type>> cachedComponents;

  id_type nextEntityID = 0;

  template <class T, class... R>
  std::set<id_type> getEntitiesWithComponentsHelper(
    std::set<std::type_index>& componentTypes)
  {
    componentTypes.insert(typeid(T));

    return getEntitiesWithComponents<R...>(componentTypes);
  }

  template <class... R>
  std::set<id_type> getEntitiesWithComponents(
    std::set<std::type_index>& componentTypes)
  {
    return getEntitiesWithComponentsHelper<R...>(componentTypes);
  }

public:

  EntityManager() = default;

  EntityManager(const EntityManager& copy) = delete;

  id_type emplaceEntity()
  {
    if (nextEntityID >= entities.size())
    {
      // If the database is saturated, add a new element for the new entity.
      entities.emplace_back();
      slotAvailable.push_back(false);

      return nextEntityID++;
    } else {
      // If there is an available slot in the database, use it.
      id_type id = nextEntityID++;
      slotAvailable[id] = false;

      // Fast forward the next available slot pointer to an available slot.
      while ((nextEntityID < entities.size()) && !slotAvailable[nextEntityID])
      {
        nextEntityID++;
      }

      return id;
    }
  }

  void deleteEntity(id_type entity)
  {
    if ((entity >= entities.size()) || slotAvailable[entity])
    {
      throw std::invalid_argument("Cannot delete non-existent entity");
    }

    // Uncache components
    for (auto& cache : cachedComponents)
    {
      cache.second.erase(entity);
    }

    // Destroy the data
    entities[entity].components.clear();

    // Mark the slot as available
    slotAvailable[entity] = true;

    if (entity < nextEntityID)
    {
      nextEntityID = entity;
    }
  }

  template <class T, class... Args>
  T& emplaceComponent(id_type entity, Args&&... args)
  {
    if ((entity >= entities.size()) || slotAvailable[entity])
    {
      throw std::invalid_argument("Cannot delete non-existent entity");
    }

    EntityData& data = entities[entity];
    std::type_index componentType = typeid(T);

    if (data.components.count(componentType))
    {
      throw std::invalid_argument("Cannot emplace already-existent component");
    }

    // Initialize the component
    std::unique_ptr<T> ptr(new T(std::forward<Args>(args)...));
    T& component = *ptr;
    data.components[componentType] = std::move(ptr);

    // Invalidate related caches
    erase_if(
      cachedComponents,
      [&componentType] (
        std::pair<const std::set<std::type_index>, std::set<id_type>>& cache) {
          return cache.first.count(componentType) == 1;
        });

    return component;
  }

  template <class T>
  void removeComponent(id_type entity)
  {
    if ((entity >= entities.size()) || slotAvailable[entity])
    {
      throw std::invalid_argument("Cannot delete non-existent entity");
    }

    EntityData& data = entities[entity];
    std::type_index componentType = typeid(T);

    if (!data.components.count(componentType))
    {
      throw std::invalid_argument("Cannot delete non-existent component");
    }

    // Destroy the component
    data.components.erase(componentType);

    // Uncache the component
    for (auto& cache : cachedComponents)
    {
      if (cache.first.count(componentType) == 1)
      {
        cache.second.erase(entity);
      }
    }
  }

  template <class T>
  T& getComponent(id_type entity)
  {
    if ((entity >= entities.size()) || slotAvailable[entity])
    {
      throw std::invalid_argument("Cannot delete non-existent entity");
    }

    EntityData& data = entities[entity];
    std::type_index componentType = typeid(T);

    if (!data.components.count(componentType))
    {
      throw std::invalid_argument("Cannot get non-existent component");
    }

    return *dynamic_cast<T*>(data.components[componentType].get());
  }

  template <class... R>
  std::set<id_type> getEntitiesWithComponents()
  {
    std::set<std::type_index> componentTypes;

    return getEntitiesWithComponentsHelper<R...>(componentTypes);
  }
};

template <>
std::set<EntityManager::id_type> EntityManager::getEntitiesWithComponents<>(
  std::set<std::type_index>& componentTypes);

#endif /* end of include guard: ENTITY_MANAGER_H_C5832F11 */