Skip to content

Instantly share code, notes, and snippets.

@sjgriffiths
Last active January 10, 2018 02:35
Show Gist options
  • Save sjgriffiths/5c09caaa20d54a3a55c4906c05a82bba to your computer and use it in GitHub Desktop.
Save sjgriffiths/5c09caaa20d54a3a55c4906c05a82bba to your computer and use it in GitHub Desktop.
Game entity manager (C++)
/**
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);
}
}
/**
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