实体组件系统和共享通用基本类型的多个组件 [英] Entity Component System and multiple components sharing common base type

查看:116
本文介绍了实体组件系统和共享通用基本类型的多个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的游戏引擎实现一个简单的ECS.我知道我的实现并不严格是ECS,但是我正在重构我的代码以使其更加基于组件.到目前为止,我有以下课程:

Entity:它是一个组件容器,并且由于我希望我的实体具有多个相同类型的组件,因此将它们存储在一个 std::map<ComponentID,std::vector<std::unique_ptr<Component>>>.每个组件都有一个唯一的ID(一个无符号的int),该ID是从我在网络上学到的一个简单的模板技巧获得的:

一个名为GetUniqueComponentID的函数:

using ComponentID = unsigned int;

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

    return id++;
}

包含一个计数器,该计数器仅生成递增的数字. 我从名为GetComponentID的函数模板中调用此函数:

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

    return id;
}

此模板为我添加到实体中的每个组件实例化了一个不同的函数,因此需要检索组件的代码可以使用GetComponentId<Component_type>索引地图,并使用具体的组件类型作为该函数的模板参数./p>

实体类具有AddComponent和GetComponent之类的方法,它们分别创建一个组件并将其添加到实体中,并检索一个组件(如果存在):

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;
}

由于我要存储相同类型的多个组件,因此将它们存储在std::map<ComponentID,std::vector<std::unique_ptr<Component>>>中.

现在我的问题是:

我需要为一种类型的组件创建一个组件层次结构:我有一个ForceGenerator组件,它是所有具体的ForceGenerator(弹簧,重力等)的(抽象)基类.因此,我需要创建具体的组件,但是我需要通过指向基类的指针来多态使用它们:我的物理子系统只需要关心指向基力生成器的指针,调用其Update()方法即可处理更新力

我无法使用当前方法,因为每次创建特定的ForceGenerator组件时我都会用不同的类型调用AddComponent,而我需要将它们存储在同一数组中(映射到基本ForceGenerator的组件ID) .

我该如何解决这个问题?

解决方案

您可以使用以下默认模板参数:

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;
}

被称为

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

您甚至可以更进一步,仅在可以将组件存储为该类型时才使用一些SFINAE来启用此功能:(可能或可能实际上并未改善错误消息)

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;
}

我认为Component是所有组件的基类.如果您有一组有限的已知组件,则可以将它们存储在std::variant<List types here>中,而不是唯一的指针中.

显然clang抱怨:模板参数重新定义了默认参数". Gcc并不介意,只是为了正确,只将StoreAs初始化StoreAs=T放在Entity类中,而不放在实现中.我编辑了源代码.

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?

解决方案

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.

这篇关于实体组件系统和共享通用基本类型的多个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆