Last active
January 10, 2018 02:35
-
-
Save sjgriffiths/5c09caaa20d54a3a55c4906c05a82bba to your computer and use it in GitHub Desktop.
Game entity manager (C++)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
EntityManager.cpp | |
Implements the EntityManager class, representing | |
a collection of Entities responsible for their | |
instantiation. | |
@author Sam Griffiths | |
www.computist.xyz | |
*/ | |
#include "EntityManager.h" | |
#include <algorithm> | |
EntityID EntityManager::instantiate(std::string name) | |
{ | |
//Add to collection and log in lookup | |
std::shared_ptr<Entity> e = std::make_shared<Entity>(name); | |
entityLookup.insert({ e->id(), entities.size() }); | |
entities.push_back(e); | |
return e->id(); | |
} | |
std::weak_ptr<Entity> EntityManager::get(EntityID id) | |
{ | |
auto it = entityLookup.find(id); | |
if (it != entityLookup.end()) | |
return std::weak_ptr<Entity>(entities[it->second]); | |
else | |
return std::weak_ptr<Entity>(); | |
} | |
void EntityManager::remove(EntityID id) | |
{ | |
auto it = entityLookup.find(id); | |
if (it != entityLookup.end()) | |
{ | |
EntityCollectionIndex i = it->second; | |
EntityID back = entities.back()->id(); | |
//Swap and pop | |
std::swap(entities[i], entities.back()); | |
entities.pop_back(); | |
entityLookup[back] = i; | |
entityLookup.erase(id); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
EntityManager.h | |
Declares the EntityManager class, representing | |
a collection of Entities responsible for their | |
instantiation. | |
@author Sam Griffiths | |
www.computist.xyz | |
*/ | |
#pragma once | |
#include <memory> | |
#include <vector> | |
#include <unordered_map> | |
#include "Entity.h" | |
typedef std::vector<std::shared_ptr<Entity>> EntityCollection; | |
typedef EntityCollection::size_type EntityCollectionIndex; | |
class EntityManager | |
{ | |
private: | |
EntityCollection entities; | |
std::unordered_map<EntityID, EntityCollectionIndex> entityLookup; | |
public: | |
//Creates a new Entity, returning its allocated ID | |
EntityID instantiate(std::string name); | |
//Gets a pointer to the Entity of the given ID | |
std::weak_ptr<Entity> get(EntityID id); | |
//Deletes the Entity of the given ID | |
void remove(EntityID id); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment