{"id":6006,"date":"2017-11-23T16:10:00","date_gmt":"2017-11-23T16:10:00","guid":{"rendered":"http:\/\/www.gamasutra.com\/view\/news\/310237"},"modified":"2017-11-23T16:10:00","modified_gmt":"2017-11-23T16:10:00","slug":"blog-creating-an-awesome-game-design-pattern-in-c","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2017\/11\/23\/blog-creating-an-awesome-game-design-pattern-in-c\/","title":{"rendered":"Blog: Creating an awesome game design pattern in C++"},"content":{"rendered":"<p><strong><em><small>The following blog post, unless otherwise noted, was written by a member of Gamasutra\u2019s community.<br \/>The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company.<\/small><\/em><\/strong><\/p>\n<hr \/>\n<p>Hi Folks.<\/p>\n<p>This is actually my first post on gamasutra\u00a0\ud83d\ude42 I am here pretty much every day and checkout cool posts, today is gonna be the day I add one by myself \ud83d\ude42 You will find the origial post here.<\/p>\n<p>In this article I want to talk about the Entity-Component-System (<strong>ECS<\/strong>). You can find a lot of information about the matter in the internet so I am not going to deep into explanation here, but talking more about my own implementation.<\/p>\n<p>First things first. You will find the full source code of my ECS in my <a href=\"https:\/\/github.com\/tobias-stein\/EntityComponentSystem\" id=\"ecsSrc\" rel=\"noopener\" target=\"_blank\">github<\/a>\u00a0repository.<\/p>\n<p>An Entity-Component-System\u00a0\u2013 mostly encountered in video games \u2013 is a design pattern which allows you great flexibility in designing your overall software architecture<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[1]<\/sup><\/a>. Big companies like Unity, Epic or Crytek in-cooperate this pattern into their frameworks to provide a very rich tool for developers to build their software with. You can checkout these posts to follow a broad discussion about the matter<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[2,3,4,5]<\/sup><\/a>.<\/p>\n<p>If you have read the articles I mentioned above you will notice they all share the same goal: distributing different concerns and tasks between Entities, Components and Systems. These are the three big players in this pattern and are fairly loose coupled. <strong>Entities<\/strong> are mainly used to provide a unique identifier, make the environment aware of the existence of a single individual and function as a sort of root object that bundles a set of components. <strong>Components<\/strong> are nothing more than container objects that do not possess any complex logic. Ideally they are simple plain old data objects (POD\u2019s). Each type of a component can be attached to an entity to provide some sort of a property. Let&#8217;s say for example a \u201cHealth-Component\u201d can be attached to an entity to make it mortal by giving it <em>health<\/em>, which is not more than an integer or floating point value in memory.<\/p>\n<p>Up to this point most of the articles I came across agree about the purpose and use of entity and component objects, but for systems opinions differ. Some people suggest that systems are only aware of components. Furthermore some say for each type of component there should be a system, e.g. for \u201cCollision-Components\u201d there is a \u201cCollision-System\u201d, for \u201cHealth-Components\u201d there is a \u201cHealth-System\u201d etc. This approach is kind of rigid and does not consider the interplay of different components. A less restrictive approach is to let different systems deal with all components they should be concerned with. For instance a \u201cPhysics-Systems\u201d should be aware of \u201cCollision-Components\u201d and \u201cRigidbody-Components\u201d, as both probably contain necessary information regarding physics simulation. In my humble opinion <strong>systems<\/strong> are &#8220;closed environments&#8221;. That is, they do not take ownership of entities nor components. They do access them through independent manager objects, which in turn will take care of the\u00a0entities and components life-cycle.<\/p>\n<p>This raises an interesting question: how do entities, components and systems communicate with each other, if they are more or less independent of each other? Depending on the implementation the answer differs. As for the implementation I am going to show you, the answer is event sourcing<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[6]<\/sup><\/a>. Events are distributed through an \u201cEvent-Manager\u201d and everyone who is interested in events can listen to what the manager has to say. If an entity or system or even a component has an important state change to communicate, e.g. &#8220;position changed&#8221; or &#8220;player died&#8221;, it can tell the \u201cEvent-Manager\u201d. He will broadcast the event and all subscriber for this event will get notified. This way everything can be interconnected.<\/p>\n<p>Well I guess the introduction above got longer than I was actually planning to, but here we are \ud83d\ude42 Before we are going to dive deeper into the <a href=\"https:\/\/github.com\/tobias-stein\/EntityComponentSystem\" id=\"ecsSrc\" rel=\"noopener\" target=\"_blank\">code<\/a>, which is C++11 by the way, I will outline the main features of my architecture:<\/p>\n<ul>\n<li><strong>memory efficiency<\/strong> &#8211; to allow a quick creation and removal of entity, component and system objects as well as events I could not rely on standard new\/delete managed heap-memory. The solution for this was of course a custom memory allocator.<\/li>\n<li><strong>logging<\/strong> &#8211; to see what is going on I used log4cplus<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[7]<\/sup><\/a>\u00a0for logging.<\/li>\n<li><strong>scalable\u00a0<\/strong>&#8211; it is easy to implement new types of entities, components, systems and events without any preset upper limit except your system&#8217;s memory<\/li>\n<li><strong>flexible<\/strong>\u00a0&#8211; no dependencies exist between entities, components and systems (entities and components sure do have a sort of dependency, but do not contain any pointer logic of each other)<\/li>\n<li><strong>simple object lookup\/access<\/strong>\u00a0&#8211; easy retrieval of entity objects and there components through an <em>EntityId<\/em> or a component-iterator to iterate over all components of a certain type<\/li>\n<li><strong>flow control<\/strong>\u00a0&#8211; systems have priorities and can depend on each other, therefore a topological order for their execution can be established<\/li>\n<li><strong>easy to use<\/strong> &#8211; the library can be easily in cooperate into other software; only one include.<\/li>\n<\/ul>\n<p>The following figure depicts the overall architecture of my Entity-Component-System:<\/p>\n<p><img decoding=\"async\" alt=\"ECS_Overview\" class=\"alignnone size-full wp-image-777\" src=\"https:\/\/www.sickgamedev.win\/wp-content\/uploads\/2017\/11\/blog-creating-an-awesome-game-design-pattern-in-c.png\" \/> Figure-01: ECS Architecture Overview (<strong><em>ECS.dll<\/em><\/strong>).<\/p>\n<p>As you can see there are four different colored areas in this picture. Each area defines a modular piece of the architecture. At the very bottom &#8211; actually in the picture above at the very top; it should be upside down &#8211; we got the memory management and the logging stuff (yellow area). This first-tier modules are dealing with very low-level tasks. They are used by the second-tier modules in the Entity-Component-System (blue area) and the event sourcing (red area). These guys mainly deal with object management tasks. Sitting on top is the third-tier module, the ECS_Engine (green area). This high-level global engine object orchestrates all second-tier modules and takes care of the initialization and destruction. All right, this was a short and very abstract overview now let&#8217;s get more into the details.<\/p>\n<h4>Memory Manager<\/h4>\n<p>Let&#8217;s start with the <a href=\"https:\/\/github.com\/tobias-stein\/EntityComponentSystem\/tree\/master\/EntityComponentSystem\/include\/ECS\/Memory\" rel=\"noopener\" target=\"_blank\">Memory-Manager<\/a>. It&#8217;s implementation is based on an article<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[8]<\/sup><\/a> I have found on <em><a href=\"https:\/\/www.gamedev.net\/\" rel=\"noopener\" target=\"_blank\">gamedev.net<\/a><\/em>. The idea is to keep heap-memory allocations and releases to an absolute minimum. Therefore only at application start a big chuck of system-memory is allocated with <a href=\"http:\/\/en.cppreference.com\/w\/cpp\/memory\/c\/malloc\" rel=\"noopener\" target=\"_blank\"><em>malloc<\/em><\/a>. This memory now will be managed by one or more custom allocator. There are many types of allocators<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[9]<\/sup><\/a>\u00a0( linear, stack, free list&#8230;) and each one of them has it&#8217;s pro&#8217;s and con&#8217;s (which I am not going to discuss here). But even if they internally work in a different way they all share a common public interface:<\/p>\n<pre>\n<code class=\"language-cpp\">class Allocator\n{ public: virtual void* allocate(size_t size) = 0; virtual void free(void* p) = 0;\n};<\/code>\n<\/pre>\n<p>The code snippet above is not complete, but outlines the two major public methods each concrete allocator must provide:<\/p>\n<ol>\n<li><strong>allocate<\/strong> &#8211; which allocates a certain amount of bytes and returns the memory-address to this chunk and<\/li>\n<li><strong>free<\/strong> &#8211; to de-allocates a previously allocated chuck of memory given it&#8217;s address.<\/li>\n<\/ol>\n<p>Now with that said, we can do cool stuff like chaining-up multiple allocators like that:<\/p>\n<p><img decoding=\"async\" alt=\"CustomMemoryMgr\" class=\"alignnone size-full wp-image-871\" src=\"https:\/\/www.sickgamedev.win\/wp-content\/uploads\/2017\/11\/blog-creating-an-awesome-game-design-pattern-in-c-1.png\" \/> Figure-02: Custom allocator managed memory.<\/p>\n<p>As you can see, one allocator can get it&#8217;s chunk of memory &#8211; that it is going to manage &#8211; from another (parent) allocator, which in turn could get it&#8217;s memory from another allocator and so on. That way you can establish different memory management strategies. For the implementation of my ECS I provide a root stack-allocator that get&#8217;s an initial allocated chuck of 1GB system-memory. Second-tier modules will allocate as much memory as they need from this root allocator and only will free it when the application get&#8217;s terminated.<\/p>\n<p><img decoding=\"async\" alt=\"MemoryMgr\" class=\"alignnone size-full wp-image-872\" src=\"https:\/\/www.sickgamedev.win\/wp-content\/uploads\/2017\/11\/blog-creating-an-awesome-game-design-pattern-in-c-2.png\" \/> Figure-03: Possible distribution of global memory.<\/p>\n<p><a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#fig01\">Figure-03<\/a> shows how the global memory could be distributed among the second-tier modules: &#8220;<em>Global-Memory-User A&#8221;<\/em> could be the Entity-Manager, &#8220;<em>Global-Memory-User B&#8221;<\/em> the Component-Manager and <em>&#8220;Global-Memory-User C&#8221;<\/em> the System-Manager.<\/p>\n<h4>Logging<\/h4>\n<p>I am not going to talk too much about logging as I simply used\u00a0log4cplus<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[7]<\/sup><\/a>\u00a0doing this job for me. All I did was defining a <a href=\"https:\/\/github.com\/tobias-stein\/EntityComponentSystem\/blob\/master\/EntityComponentSystem\/include\/ECS\/Log\/Logger.h\" rel=\"noopener\" target=\"_blank\">Logger<\/a> base class hosting a <em>log4cplus::Logger<\/em> object and a few wrapper methods forwarding simple log calls like &#8220;LogInfo()&#8221;, &#8220;LogWarning()&#8221;, etc.<\/p>\n<h4>Entity-Manager, IEntity, Entity and Co.<\/h4>\n<p>Okay now let&#8217;s talk about the real meat of my architecture; the blue area in <a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#fig01\">Figure-01<\/a>. You may have noticed the similar setup between all manager objects and their concerning classes. Have a look at the <em><a href=\"https:\/\/github.com\/tobias-stein\/EntityComponentSystem\/blob\/master\/EntityComponentSystem\/include\/ECS\/EntityManager.h\" rel=\"noopener\" target=\"_blank\">EntityManager<\/a><\/em>, <a href=\"https:\/\/github.com\/tobias-stein\/EntityComponentSystem\/blob\/master\/EntityComponentSystem\/include\/ECS\/IEntity.h\" rel=\"noopener\" target=\"_blank\"><em>IEntity<\/em><\/a> and <em><a href=\"https:\/\/github.com\/tobias-stein\/EntityComponentSystem\/blob\/master\/EntityComponentSystem\/include\/ECS\/Entity.h\" rel=\"noopener\" target=\"_blank\">Entity<\/a><\/em> classes for example. The <em>EntityManger<\/em> class is supposed to manage <u>all<\/u> entity objects during application run-time. This includes tasks like creating, deleting and accessing existing entity objects. <em>IEntity<\/em> is an interface class and provides the very basic traits of an entity object, such as an object-identifier and (static-)type-identifier. It&#8217;s static because it won&#8217;t change after program initialization. This type-identifier is also consistent over multiple application runs and may only change, if source code was modified.<\/p>\n<pre>\n<code class=\"language-cpp\">class IEntity\n{ \/\/ code not complete!\nEntityId m_Id; public: IEntity(); virtual ~IEntity(); virtual const EntityTypeId GetStaticEntityTypeID() const = 0; inline const EntityId GetEntityID() const { return this-&gt;m_Id; }\n};<\/code>\n<\/pre>\n<p>The type-identifier is an integer value and varies for each concrete entity class. This allows us to check the type of an <em>IEntity<\/em> object at run-time. Last but not least comes the <em>Entity<\/em> template class.<\/p>\n<pre>\n<code class=\"language-cpp\">template&lt;class T&gt;\nclass Entity : public IEntity\n{ \/\/ code not complete! void operator delete(void*) = delete; void operator delete[](void*) = delete; public: static const EntityTypeId STATIC_ENTITY_TYPE_ID; Entity() {} virtual ~Entity() {} virtual const EntityTypeId GetStaticEntityTypeID() const override { return STATIC_ENTITY_TYPE_ID; }\n}; \/\/ constant initialization of entity type identifier\ntemplate&lt;class T&gt;\nconst EntityTypeId Entity&lt;T&gt;::STATIC_ENTITY_TYPE_ID = util::Internal::FamilyTypeID::Get();<\/code>\n<\/pre>\n<p>This class&#8217;s soul purpose is the initialization of the unique type-identifier of a concrete entity class. I made use of two facts here: first constant initialization<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[10]<\/sup><\/a>\u00a0of static variables and second the nature of how template classes work. Each Version of the template class <em>Entity<\/em> will have its own static variable <em>STATIC_ENTITY_TYPE_ID<\/em>. Which in turn will be guaranteed to be initialized before any dynamic initialization happens. The term &#8220;<em>util::Internal::FamilyTypeID::Get()<\/em>&#8221; is used to implement a sort of type counter mechanism. It internally increments a counter every time it gets called with a different <em>T<\/em>, but always returns the same value when called with the same\u00a0<em>T<\/em> again. I am not sure if that patter has a special name, but it is pretty cool \ud83d\ude42 At this point I also got ride of the delete and delete[] operator. This way I made sure nobody would accidentally call these guys. This also &#8211; as long as your compiler is smart enough &#8211; would give you a warning when trying to use the new or new[] operator of entity objects as their counterparts are gone. These operators are not intended to be used since the <em>EntityManager<\/em>\u00a0class will take care of all this. Alright, let&#8217;s summarize what we just learned. The manager class provides basic functionality such as creating, deleting and accessing objects. The interface class functions as the very root base class and provides an unique object-identifier and type-identifier. The template class ensures the correct initialization of the type-identifier and removes the delete\/delete[] operator. This very same pattern of a manager, interface and template class is used for components, systems and events as well. The only, but important, thing these groups differ, is the way manger classes store and access their objects.<\/p>\n<p>Let&#8217;s have a look at the EntityManager\u00a0class first. <a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#fig01\">Figure-04<\/a> shows the overall structure of how things are stored.\u00a0<\/p>\n<p><img decoding=\"async\" alt=\"EntityMgr\" class=\"aligncenter size-full wp-image-1013\" src=\"https:\/\/www.sickgamedev.win\/wp-content\/uploads\/2017\/11\/blog-creating-an-awesome-game-design-pattern-in-c-3.png\" \/><\/p>\n<dl class=\"wp-caption aligncenter\" id=\"attachment_1003\">\n<dd class=\"wp-caption-dd\">Figure-04: Abstract view of EntityManager class and it&#8217;s object storage.<\/dd>\n<\/dl>\n<p>When creating a new entity object one would use the <em>EntityManager::CreateEntity&lt;<strong><span>T<\/span><\/strong>&gt;(args&#8230;)<\/em> method. This public method first takes a template parameter which is the type of the concrete entity to be created. Secondly this method takes in an optional amount of parameters (can be empty) which are forwarded to the constructor of <strong><span>T<\/span><\/strong>. Forwarding\u00a0 these parameters happens through a variadic template<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[11]<\/sup><\/a>. During creation the following things happen internally &#8230;<\/p>\n<ol>\n<li>The <em>ObjectPool<a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[12]<\/sup><\/a><\/em> for entity objects of type <strong><span>T<\/span><\/strong><span><span>\u00a0<\/span><\/span>will be acquired, if this pool does not exists a new one will be created<\/li>\n<li>New memory will be allocated from this pool; just enough to store the <span><strong>T<\/strong><\/span> object<\/li>\n<li>Before actually calling the constructor of <strong><span>T<\/span><\/strong>, a new <em>EntityId<\/em> is acquired from the manager. This id will be stored along with the before allocated memory into a look-up table, this way we can look-up the entity instance later with that id<\/li>\n<li>Next the C++ in-placement new operator<em><a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#refs\"><sup>[13]<\/sup><\/a><\/em>\u00a0is called with the forwarded <em>args&#8230;<\/em>\u00a0as input to create a new instance of <span><strong>T<\/strong><\/span><\/li>\n<li>finally the method returns the entity&#8217;s identifier.<\/li>\n<\/ol>\n<p>After a new instance of an entity object got created you can get access to it via it&#8217;s unique <strong>object<\/strong> identifier (<em>EntityId<\/em>) and <em>EntityManager::GetEntity(EntityId id)<\/em>. To destroy an instance of an entity object one must call the <em>EntityManager::DestroyEntity(EntityId id)<\/em> method.<\/p>\n<p>The ComponentManager\u00a0class works in the same way plus one extension. Besides the object pools for storing all sorts of components it must provide an additional mechanism for linking components to their owning entity objects. This constraint results in a second look-up step: first we check if there is an entry for a given <em>EntityId<\/em>, if there is one we will check if this entity has a certain type of component attached by looking it up in a component-list.<\/p>\n<p><img decoding=\"async\" alt=\"CompMgr\" class=\"alignnone size-full wp-image-1012\" src=\"https:\/\/www.sickgamedev.win\/wp-content\/uploads\/2017\/11\/blog-creating-an-awesome-game-design-pattern-in-c-4.png\" \/> Figure-05: Component-Manager object storage overview.<\/p>\n<p>Using the <em>ComponentManager::CreateComponent(EntityId id, args&#8230;)<\/em> method allows us to add a certain component to an entity. With <em>ComponentManager::GetComponent(EntityId id)<\/em> <span>we can access the entity&#8217;s components, where T specifies what type of component we want to access. If the component is not present <em>nullptr<\/em> is returned. To remove a component from an entity one would use the <em>ComponentManager::RemoveComponent(EntityId id)\u00a0<\/em>method. But wait there is more. Another way of accessing components is using the <em>ComponentIterator<\/em>. This way you can iterate over all existing components of a certain type T. This might be handy if a system like the &#8220;Physics-System&#8221; wants to apply gravity to all &#8220;Rigidbody-Components&#8221;.<\/span><\/p>\n<p>The SystemManager class does not have any fancy extras for storing and accessing systems. A simple map is used to store a system along with it&#8217;s type-identifier as the key.<\/p>\n<p>The EventManager\u00a0class uses a linear-allocator that manages a chunk of memory. This memory is used as an event buffer. Events are stored into that buffer and dispatched later. Dispatching the event will clear the buffer so new events can be stored. This happens at least once every frame.<\/p>\n<p><img decoding=\"async\" alt=\"ECS_Access\" class=\"alignnone size-full wp-image-1016\" src=\"https:\/\/www.sickgamedev.win\/wp-content\/uploads\/2017\/11\/blog-creating-an-awesome-game-design-pattern-in-c-5.png\" \/> Figure-06: Recap ECS architecture overview<\/p>\n<p>I hope at this point you got a somewhat idea how things work in my ECS. If not, no worries, have a look at <a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#fig01\">Figure-06<\/a> and let&#8217;s recap. You can see the <em>EntityId<\/em> is quite important as you will use it to access a concrete entity object instance and all it&#8217;s components. All components know their owner, that is, having a component object at hand you can easily get the entity by asking the EntityManager class with the given owner-id of that component. To pass an entity around you would never use it&#8217;s pointer directly, but you can use events in combination with the\u00a0<em>EntityId<\/em>. You could create a concrete event, let&#8217;s say &#8220;<em>EntityDied<\/em>&#8221; for example, and this event (which must be a plain old data object) has a member of type\u00a0<em>EntityId<\/em>. Now to notify all event listeners (<em>IEventListener<\/em>) &#8211; which could be Entities, Components or Systems &#8211; we use <em>EventManager::SendEvent(entityId)<\/em>. The event receiver on the other side now can use the provided <em>EntityId<\/em> and ask the EntityManager class to get the entity object or the ComponentManager class to get a certain component of that entity. The reason for that detour is simple, at any point while running the application an entity or one of it&#8217;s components could be deleted by some logic. Because you won&#8217;t clutter your code by extra clean-up stuff you rely on this <em>EntityId<\/em>. If the manager returns <em>nullptr<\/em> for that <em>EntityId<\/em>, you will know that an entity or component does no longer exists. The red square btw. is corresponding to the one in <a href=\"https:\/\/www.gamasutra.com\/blogs\/TobiasStein\/20171122\/310172\/The_EntityComponentSystem__An_awesome_gamedesign_pattern_in_C_Part_1.php?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+GamasutraNews+%28Gamasutra+News%29&amp;utm_content=Google+UK#fig01\">Figure-01<\/a> and marks the boundaries of the ECS.<\/p>\n<h4>\u00a0<\/h4>\n<h4>The Engine object<\/h4>\n<p>To make things a little bit more comfortable I created an engine object. The engine object ensures an easy integration and usage in client software. On client side one only has to include the \u201cECS\/ECS.h\u201d header and call the <em>ECS::Initialize()<\/em> method. Now a static global engine object will be initialized (<em>ECS::ECS_Engine<\/em>) and can be used at client side to get access to all the manager classes. Furthermore it provides\u00a0 a <em>SendEvent<\/em> method for broadcasting events and an Update method, which will automatically dispatch all events and update all systems. The <em>ECS::Terminate()<\/em> should be called before exiting the main program. This will ensure that all acquired resources will be freed.\u00a0The code snippet bellow demonstrates the very basic usage of the ECS&#8217;s global engine object.<\/p>\n<pre>\n<code class=\"language-cpp\">#include &lt;ECS\/ECS.h&gt; int main(int argc,char* argv[])\n{ \/\/ initialize global 'ECS_Engine' object ECS::Initialize(); const float DELTA_TIME_STEP = 1.0f \/ 60.0f; \/\/ 60hz bool bQuit = false; \/\/ run main loop until quit while(bQuit == false) { \/\/ Update all Systems, dispatch all buffered events, \/\/ remove destroyed components and entities ... ECS::ECS_Engine-&gt;(DELTA_TIME_STEP); \/* ECS::ECS_Engine-&gt;GetEntityManager()-&gt;...; ECS::ECS_Engine-&gt;GetComponentManager()-&gt;...; ECS::ECS_Engine-&gt;GetSystemManager()-&gt;...; ECS::ECS_Engine-&gt;SendEvent&lt;T&gt;(...); *\/ \/\/ more logic ... } \/\/ destroy global 'ECS_Engine' object ECS::Terminate(); return 0;\n}<\/code>\n<\/pre>\n<h4>Conclusion<\/h4>\n<p>The Entity-Component-System described in this article is fully functional and ready to use. But as usual there are certainly a few thinks to improve. The following list outlines just a few ideas that I came up with:<\/p>\n<ul>\n<li>Make it thread-safe,<\/li>\n<li>Run each system or a group of systems in threats w.r.t. to their topological order,<\/li>\n<li>Refactor event-sourcing and memory management and include them as modules,<\/li>\n<li>serialization,<\/li>\n<li>profiling<\/li>\n<li>&#8230;<\/li>\n<\/ul>\n<p>I hope this article was helpful and you enjoyed reading it as much as I did writing it \ud83d\ude42 If you want to see my ECS in action check out this demo:<\/p>\n<p>[embedded content]<\/p>\n<p>The <em>BountyHunter<\/em> demo makes heavily use of the ECS and demonstrates the strength of this pattern. If you want to know how?, have a look at this <a href=\"https:\/\/tsprojectsblog.wordpress.com\/2017\/11\/16\/the-bountyhunter-game\/\">post<\/a>.<\/p>\n<p>So far \u2026<\/p>\n<p>Cheer\u2019s, Tob\u2019s.<\/p>\n<hr \/>\n<h4>References<\/h4>\n<p><sup>[1]<\/sup><a href=\"https:\/\/en.wikipedia.org\/wiki\/Entity%E2%80%93component%E2%80%93system\" id=\"refs\" rel=\"noopener\" target=\"_blank\">https:\/\/en.wikipedia.org\/wiki\/Entity-component-system<\/a> <sup>[2]<\/sup><a href=\"http:\/\/gameprogrammingpatterns.com\/component.html\" id=\"refs\" rel=\"noopener\" target=\"_blank\">http:\/\/gameprogrammingpatterns.com\/component.html<\/a> <sup>[3]<\/sup><a href=\"https:\/\/www.gamedev.net\/articles\/programming\/general-and-gameplay-programming\/understanding-component-entity-systems-r3013\/\" id=\"refs\" rel=\"noopener\" target=\"_blank\">https:\/\/www.gamedev.net\/articles\/programming\/general-and-gameplay-programming\/understanding-component-entity-systems-r3013\/<\/a><br \/><sup>[4]<\/sup><a href=\"https:\/\/github.com\/junkdog\/artemis-odb\/wiki\/Introduction-to-Entity-Systems\" id=\"refs\" rel=\"noopener\" target=\"_blank\">https:\/\/github.com\/junkdog\/artemis-odb\/wiki\/Introduction-to-Entity-Systems<\/a> <sup>[5]<\/sup><a href=\"http:\/\/scottbilas.com\/files\/2002\/gdc_san_jose\/game_objects_slides.pdf\" id=\"refs\" rel=\"noopener\" target=\"_blank\">http:\/\/scottbilas.com\/files\/2002\/gdc_san_jose\/game_objects_slides.pdf<\/a> <sup>[6]<\/sup><a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/architecture\/patterns\/event-sourcing\" id=\"refs\" rel=\"noopener\" target=\"_blank\">https:\/\/docs.microsoft.com\/en-us\/azure\/architecture\/patterns\/event-sourcing<\/a> <sup>[7]<\/sup><a href=\"https:\/\/sourceforge.net\/p\/log4cplus\/wiki\/Home\/\" id=\"refs\" rel=\"noopener\" target=\"_blank\">https:\/\/sourceforge.net\/p\/log4cplus\/wiki\/Home\/<\/a> <sup>[8]<\/sup><a href=\"https:\/\/www.gamedev.net\/articles\/programming\/general-and-gameplay-programming\/c-custom-memory-allocation-r3010\/\" id=\"refs\" rel=\"noopener\" target=\"_blank\">https:\/\/www.gamedev.net\/articles\/programming\/general-and-gameplay-programming\/c-custom-memory-allocation-r3010\/<\/a><br \/><sup>[9]<\/sup><a href=\"https:\/\/www.gamedev.net\/articles\/programming\/general-and-gameplay-programming\/c-custom-memory-allocation-r3010\/\" id=\"refs\" rel=\"noopener\" target=\"_blank\">https:\/\/github.com\/mtrebi\/memory-allocatorshttps:\/\/www.gamedev.net\/articles\/programming\/general-and-gameplay-programming\/c-custom-memory-allocation-r3010\/<\/a> <sup>[10]<\/sup><a href=\"http:\/\/en.cppreference.com\/w\/cpp\/language\/constant_initialization\" rel=\"noopener\" target=\"_blank\">http:\/\/en.cppreference.com\/w\/cpp\/language\/constant_initialization<\/a> <sup>[11]<\/sup><a href=\"https:\/\/en.wikipedia.org\/wiki\/Variadic_template\" rel=\"noopener\" target=\"_blank\">https:\/\/en.wikipedia.org\/wiki\/Variadic_template<\/a><br \/><sup>[12]<\/sup><a href=\"http:\/\/gameprogrammingpatterns.com\/object-pool.html\" rel=\"noopener\" target=\"_blank\">http:\/\/gameprogrammingpatterns.com\/object-pool.html<\/a> <sup>[13]<\/sup><a href=\"http:\/\/en.cppreference.com\/w\/cpp\/language\/new\" rel=\"noopener\" target=\"_blank\">http:\/\/en.cppreference.com\/w\/cpp\/language\/new<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The following blog post, unless otherwise noted, was written by a member of Gamasutra\u2019s community.The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company. Hi Folks. This is actually my first post on gamasutra\u00a0\ud83d\ude42 I am here pretty much every day and checkout cool posts, today is gonna [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":6007,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[20],"tags":[],"class_list":["post-6006","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/6006","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=6006"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/6006\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/6007"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=6006"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=6006"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=6006"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}