Search code examples
c++game-enginegame-physicsentity-component-system

Entity Component System and multiple components sharing common base type


I'm trying to implement a simple ECS for my game engine. I know that my implementation is not strictly ECS, but I'm refactoring my code to be more component-based. So far I have the following classes:

Entity: it is a container of components, and since I want my entity to have multiple components of the same type, it stores them in a std::map<ComponentID,std::vector<std::unique_ptr<Component>>>. Each component has a unique ID (an unsigned int), that I get from a simple template trick I learned on the web:

A function called GetUniqueComponentID:

using ComponentID = unsigned int;

inline ComponentID GetUniqueComponentID()
{
    static ComponentID id = 0;

    return id++;
}

contains a counter that simply generates incrementing numbers. I call this function from a function template called GetComponentID:

template <typename T>
ComponentID GetComponentID()
{
    static ComponentID id = GetUniqueComponentID();

    return id;
}

this template instantiates a different function for each component that I add to my entity, so code that needs to retrieve a component can index the map using GetComponentId<Component_type>, with the concrete component type as the template argument for the function.

The entity class has methods like AddComponent and GetComponent that respectively create a component and add it to the entity, and retrieve a component (if present):

class Entity
{
public:
    Entity();
    ~Entity();
    template <typename T, typename... TArgs>
    T &AddComponent(TArgs&&... args);
    template <typename T>
    bool HasComponent();
    //template <typename T>
    //T &GetComponent();
    template <typename T> 
    std::vector<T*> GetComponents();
    bool IsAlive() { return mIsAlive; }
    void Destroy() { mIsAlive = false; }
private:
    //std::map<ComponentID, std::unique_ptr<Component>> mComponents;              // single component per type
    std::map<ComponentID, std::vector<std::unique_ptr<Component>>> mComponents;   // multiple components per type
    bool mIsAlive = true;
};


template <typename T, typename... TArgs>
T &Entity::AddComponent(TArgs&&... args)
{
    T *c = new T(std::forward<TArgs>(args)...);
    std::unique_ptr<Component> component(c);
    component->SetEntity(this);
    mComponents[GetComponentID<T>()].push_back(std::move(component));
    return *c;
}

template <typename T>
bool Entity::HasComponent()  // use bitset (faster)
{
    std::map<ComponentID, std::vector<std::unique_ptr<Component>>>::iterator it = mComponents.find(GetComponentID<T>());
    if (it != mComponents.end())
        return true;
    return false;
}

template <typename T>
std::vector<T*> Entity::GetComponents()
{
    std::vector<T*> components;
    for (std::unique_ptr<Component> &component : mComponents[GetComponentID<T>()])
        components.push_back(static_cast<T*>(component.get()));

    return components;
}

Since I want to store multiple components of the same type, I store them in a std::map<ComponentID,std::vector<std::unique_ptr<Component>>>.

Now my question is:

I need to create a component hierarchy for a type of component: I have a ForceGenerator component that is the (abstract) base class for all kinds of concrete ForceGenerators (Springs, Gravity and so on). So I need to create the concrete components, but I need to use them polymorphically through a pointer to the base class: my physics subsystem needs only be concerned with pointers to the base ForceGenerator, calling its Update() method that takes care of updating forces.

I can't use the current approach, since I call AddComponent with a different type each time I create a specific ForceGenerator component, while I need to store them in the same array (mapped to the component ID of the base ForceGenerator).

How could I solve this problem?


Solution

  • You could use default template arguments like this:

    class Entity
    {
    template <typename T,typename StoreAs=T, typename... TArgs>
        T &Entity::AddComponent(TArgs&&... args);
    };
    template <typename T,typename StoreAs, typename... TArgs>
    T &Entity::AddComponent(TArgs&&... args)
    {
         T *c = new T(std::forward<TArgs>(args)...);
         std::unique_ptr<Component> component(c);
         component->SetEntity(this);
         mComponents[GetComponentID<StoreAs()].push_back(std::move(component));
         return *c;
    }
    

    is called like

     entity.AddComponent<T>(...)//Will instatiate AddComponent<T,T,...>
     entity.AddComponent<T,U>(...)//Will instatiate AddComponent<T,U,...>
    

    You might even go step further and use some SFINAE to only enable this function when the component can be stored as that type: (Might or might not actually improve the error message)

    template <typename T,typename StoreAs, typename... TArgs>
    std::enable_if_t<std::is_base_of_v<StoreAs,T>,T&> //Return type is `T&`
    Entity::AddComponent(TArgs&&... args)
    {
         T *c = new T(std::forward<TArgs>(args)...);
         std::unique_ptr<Component> component(c);
         component->SetEntity(this);
         mComponents[GetComponentID<StoreAs>()].push_back(std::move(component));
         return *c;
    }
    

    I assume that Component is a base class for all components. If you have a finite,known set of components, you can store them in std::variant<List types here> instead of unique pointers.

    EDIT: Apparently clang complains: "template parameter redefines default argument". Gcc didn't mind, but just to be correct, put the StoreAs initialization StoreAs=T only in Entity class, not to the implementation. I edited the source code.