Jump to content
  • Advertisement

Tobs

Member
  • Content Count

    3
  • Joined

  • Last visited

Community Reputation

4 Neutral

1 Follower

About Tobs

  • Rank
    Newbie

Personal Information

  • Interests
    Programming

Recent Profile Visitors

The recent visitors block is disabled and is not being shown to other users.

  1. Hey Spool, glad you like my post and thanks for the feedback. I kinda have no time as I am busy with other projects at the moment. But I just quickly updated my blog post and added a few thoughts about systems. You'll find it further down at the "MORE ABOUT SYSTEMS" part. I hope this will help you a bit. So far ... Cheers, Tobs.
  2. Hey Folks Welcome to part two of the series "The Entity-Component-System". As always you can checkout the original post here. In my last post (The Entity-Component-System - An awesome game-design pattern in C++ (Part 1)), I talked about the Entity-Component-System (ECS) design pattern and my own implementation. Now I want to show you how to actually use it to build a game with it. If you not already have seen it, check out what kinda game I built with the help of my ECS. I will admit this does not look much, but if you ever had build your own game without help of a big and fancy game engine, like Unity or Unreal, you might give me some credit here So for the purpose of demonstrating my ECS I simply just need that much. If you still have not figured out what this game (BountyHunter) is about, let me help you out with the following picture: Figure-01: BountyHunter objective and rules. The picture on the left may look familiar as it is a more abstract view of the game you saw in the video clip. Focus is laid on game entities. On the right hand side you will find the game objective and rules. This should be pretty much self-explanatory. As you can see we got a bunch of entity types living in this game world and now you may wonder what they are actually made of? Well components of course. While some types of components are common for all this entities a few are unique for others. Check out the next picture. Figure-02: Entity and their components. By looking at this picture you can easily see the relation between entities and their components (this is not a complete depiction!). All game entities have the Transform-Component in common. Because game entities must be somewhere located in the world they have a transform, which describes the entities position, rotation and scale. This might be the one and only component attached to an entity. The camera object for instance does require more components especially not a Material-Component as it will be never visible to the player (this might not be true if you would use it for post-effects). The Bounty and Collector entity objects on the other hand do have a visual appearance and therefore need a Material-Component to get displayed. They also can collide with other objects in the game world and therefore have a Collision-Component attached, which describes their physical form. The Bounty entity has one more component attached to it; the Lifetime-Component. This component states the remaining life-time of a Bounty object, when it’s life-time is elapsed the bounty will fade away. So what’s next? Having all these different entities with their individual gathering of components does not complete the game. We also need someone who knows how to drive each one of them. I am talking about the systems of course. Systems are great. You can use systems to split up your entire game-logic into much smaller pieces. Each piece dealing with a different aspect of the game. There could or actually should be an Input-System, which is handling all the player input. Or a Render-System that brings all the shapes and color onto screen. A Respawn-System to respawn dead game objects. I guess you got the idea. The following picture shows a complete class-diagram of all the concrete entity, component and system types in BountyHunter. Figure-03: BountyHunter ECS class-diagram. Now we got entities, components and system (ECS), but wait there is more.. events! To let systems and entities communicate with each other I provided a collection of 38 different events: GameInitializedEvent GameRestartedEvent GameStartedEvent GamePausedEvent GameResumedEvent GameoverEvent GameQuitEvent PauseGameEvent ResumeGameEvent RestartGameEvent QuitGameEvent LeftButtonDownEvent LeftButtonUpEvent LeftButtonPressedEvent RightButtonDownEvent RightButtonUpEvent RightButtonPressedEvent KeyDownEvent KeyUpEvent KeyPressedEvent ToggleFullscreenEvent EnterFullscreenModeEvent StashFull EnterWindowModeEvent GameObjectCreated GameObjectDestroyed PlayerLeft GameObjectSpawned GameObjectKilled CameraCreated, CameraDestroyed ToggleDebugDrawEvent WindowMinimizedEvent WindowRestoredEvent WindowResizedEvent PlayerJoined CollisionBeginEvent CollisionEndEvent And there is still more , what else did I need to make BountyHunter: general application framework – SDL2 for getting the player input and setting up the basic application window. graphics – I used a custom OpenGL renderer to make rendering into that application window possible. math – for solid linear algebra I used glm. collision detection – for collision detection I used box2d physics. Finite-State-Machine – used for simple AI and game states. Obviously I am not going to talk about all these mechanics as they are worth their own post, which I might do at a later point But, if your are enthusiastic to get to know anyway I won’t stop you and leave you with this link. Looking at all the features I mentioned above you may realize that they are a good start for your own small game engine. Here are a few more things I got on my todo-list, but actually did not implement just because I wanted to get things done. Editor – an editor managing entities, components, systems and more Savegame – persist entities and their components into a database using some ORM library (e.g. codesynthesis) Replays – recoding events at run-time and replay them at a later point GUI – using a GUI framework (e.g. librocket) to build an interactive game-menu Resource-Manager – synchronous and asynchronous loading of assets (textures, fonts, models etc.) through a custom resource manager Networking – send events across the network and setup a multiplayer mode I will leave these todo’s up to you as a challenge to proof that you are an awesome programmer Finally let me provide you some code, which demonstrates the usage of the my ECS. Remember the Bounty game entity? Bounties are the small yellow, big red and all in between squares spawning somewhere randomly in the center of the world. The following snipped shows the code of the class declaration of the Bounty entity. // Bounty.h class Bounty : public GameObject<Bounty> { private: // cache components TransformComponent* m_ThisTransform; RigidbodyComponent* m_ThisRigidbody; CollisionComponent2D* m_ThisCollision; MaterialComponent* m_ThisMaterial; LifetimeComponent* m_ThisLifetime; // bounty class property float m_Value; public: Bounty(GameObjectId spawnId); virtual ~Bounty(); virtual void OnEnable() override; virtual void OnDisable() override; inline float GetBounty() const { return this->m_Value; } // called OnEnable, sets new randomly sampled bounty value void ShuffleBounty(); }; The code is pretty much straight forward. I’ve created a new game entity by deriving from GameObject<T> (which is derived from ECS::Entity<T>), with the class (Bounty) itself as T. Now the ECS is aware of that concrete entity type and a unique (static-)type-identifier will be created. We will also get access to the convenient methods AddComponent<U>, GetComponent<U>, RemoveComponent<U>. Besides the components, which I show you in a second, there is another property; the bounty value. I am not sure why I did not put that property into a separate component, for instance a BountyComponentcomponent, because that would be the right way. Instead I just put the bounty value property as member into the Bounty class, shame on me. But hey, this only shows you the great flexibility of this pattern, right? Right, the components … // Bounty.cpp Bounty::Bounty(GameObjectId spawnId) { Shape shape = ShapeGenerator::CreateShape<QuadShape>(); AddComponent<ShapeComponent>(shape); AddComponent<RespawnComponent>(BOUNTY_RESPAWNTIME, spawnId, true); // cache this components this->m_ThisTransform = GetComponent<TransformComponent>(); this->m_ThisMaterial = AddComponent<MaterialComponent>(MaterialGenerator::CreateMaterial<defaultmaterial>()); this->m_ThisRigidbody = AddComponent<RigidbodyComponent>(0.0f, 0.0f, 0.0f, 0.0f, 0.0001f); this->m_ThisCollision = AddComponent<CollisionComponent2d>(shape, this->m_ThisTransform->AsTransform()->GetScale(), CollisionCategory::Bounty_Category, CollisionMask::Bounty_Collision); this->m_ThisLifetime = AddComponent<LifetimeComponent>(BOUNTY_MIN_LIFETIME, BOUNTY_MAX_LIFETIME); } // other implementations ... I’ve used the constructor to attach all the components required by the Bountyentity. Note that this approach creates a prefabricate of an object and is not flexible, that is, you will always get a Bounty object with the same components attached to it. Where this is a good enough solution for this game it might be not in a more complex one. In such a case you would provide a factory that produces custom tailored entity objects. As you can see in the code above there are quite a few components attached to the Bounty entity. We got a ShapeComponent and MaterialComponent for the visual appearance. A RigidbodyComponent and CollisionComponent2D for physical behavior and collision response. A RespawnComponent for giving Bounty the ability to get respawned after death. Last but not least there is a LifetimeComponent that will bind the existents of the entity on a certain amount of time. The TransformComponent is automatically attached to any entity that is derived from GameObject<T>. That’s it. We’ve just added a new entity to the game. Now you probably want to see how to make use of all this components. Let me give you two examples. First the RigidbodyComponent. This component contains information about some physical traits, e.g. friction, density or linear damping. Furthermore it functions as an adapter class which is used to in-cooperate the box2d physics into the game. The RigidbodyComponent is rather important as it is used to synchronize the physics simulated body’s transform (owned by box2d) and the the entities TransformComponent (owned by the game). The PhysicsSystem is responsable for this synchronization process. // PhysicsEngine.h class PhysicsSystem : public ECS::System<PhysicsSystem>, public b2ContactListener { public: PhysicsSystem(); virtual ~PhysicsSystem(); virtual void PreUpdate(float dt) override; virtual void Update(float dt) override; virtual void PostUpdate(float dt) override; // Hook-in callbacks provided by box2d physics to inform about collisions virtual void BeginContact(b2Contact* contact) override; virtual void EndContact(b2Contact* contact) override; }; // class PhysicsSystem // PhysicsEngine.cpp void PhysicsSystem::PreUpdate(float dt) { // Sync physics rigidbody transformation and TransformComponent for (auto RB = ECS::ECS_Engine->GetComponentManager()->begin<RigidbodyComponent>(); RB != ECS::ECS_Engine->GetComponentManager()->end<RigidbodyComponent>(); ++RB) { if ((RB->m_Box2DBody->IsAwake() == true) && (RB->m_Box2DBody->IsActive() == true)) { TransformComponent* TFC = ECS::ECS_Engine->GetComponentManager()->GetComponent<TransformComponent>(RB->GetOwner()); const b2Vec2& pos = RB->m_Box2DBody->GetPosition(); const float rot = RB->m_Box2DBody->GetAngle(); TFC->SetTransform(glm::translate(glm::mat4(1.0f), Position(pos.x, pos.y, 0.0f)) * glm::yawPitchRoll(0.0f, 0.0f, rot) * glm::scale(TFC->AsTransform()->GetScale())); } } } // other implementations ... From the implementation above you may have noticed the three different update functions. When systems get updated, first all PreUpdate methods of all systems are called, then Update and last the PostUpdate methods. Since the PhysicsSystem is called before any other TransformComponent concerned system, the code above ensures a synchronized transform. Here you can also see the ComponentIterator in action. Rather than asking every entity in the world, if it has a RigidbodyComponent, we ask the ComponentManager to give us a ComponentIterator for type RigidbodyComponent. Having the RigidbodyComponent we easily can retrieve the entity’s id and ask the ComponentManager once more to give us the TransformComponent for that id as well, too easy. Let’s check out that second example I’ve promised. The RespawnComponent is used for entities which are intended to be respawned after they died. This component provides five properties which can be used to configure the entity’s respawn behavior. You can decide to automatically respawn an entity when it dies, how much time must pass until it get’s respawned and a spawn location and orientation. The actual respawn logic is implemented in the RespawnSystem. // RespawnSystem.h class RespawnSystem : public ECS::System<RespawnSystem>, protected ECS::Event::IEventListener { private: // ... other stuff Spawns m_Spawns; RespawnQueue m_RespawnQueue; // Event callbacks void OnGameObjectKilled(const GameObjectKilled* event); public: RespawnSystem(); virtual ~RespawnSystem(); virtual void Update(float dt) override; // more ... }; // class RespawnSystem // RespawnSystem.cpp // note: the following is only pseudo code! voidRespawnSystem::OnGameObjectKilled(const GameObjectKilled * event) { // check if entity has respawn ability RespawnComponent* entityRespawnComponent = ECS::ECS_Engine->GetComponentManager()->GetComponent<RespawnComponent>(event->m_EntityID); if(entityRespawnComponent == nullptr || (entityRespawnComponent->IsActive() == false) || (entityRespawnComponent->m_AutoRespawn == false)) return; AddToRespawnQeueue(event->m_EntityID, entityRespawnComponent); } void RespawnSystem::Update(float dt) { foreach(spawnable in this->m_RespawnQueue) { spawnable.m_RemainingDeathTime -= dt; if(spawnable.m_RemainingDeathTime <= 0.0f) { DoSpawn(spawnable); RemoveFromSpawnQueue(spawnable); } } } The code above is not complete, but grasps the important lines of code. The RespawnSystem is holding and updating a queue of EntityId’s along with their RespawnComponent’s. New entries are enqueued when the systems receives a GameObjectKilled event. The system will check if the killed entity has the respawn ability, that is, if there is a RespawnComponent attached. If true, then the entity get’s enqueued for respawning, else it is ignored. In the RespawnSystem’s update method, which is called each frame, the system will decrease the initial respawn-time of the queued entitys’ RespawnComponents‘ (not sure if I got the single quotes right here?). If a respawn-time drops below zero, the entity will be respawned and removed from the respawn queue. I know this was a quick tour, but I hope I could give you a rough idea how things work in the ECS world. Before ending this post I want to share some more of my own experiences with you. Working with my ECS was much a pleasure. It is so surprisingly easy to add new stuff to the game even third-party libraries. I simply added new components and systems, which would link the new feature into my game. I never got the feeling being at a dead end. Having the entire game logic split up into multiple systems is intuitive and comes for free using an ECS. The code looks much cleaner and becomes more maintainable as all this pointer-spaghetti-dependency-confusion is gone. Event sourcing is very powerful and helpful for inter system/entity/… communication, but it is also a double bleeding edge and can cause you some trouble eventually. I am speaking of event raise conditions. If you have ever worked with Unity’s or Unreal Engine’s editor you will be glad to have them. Such editors definitely boost your productivity as your are able to create new ECS objects in much less time than hacking all these line of code by hand. But once you have setup a rich foundation of entity, component, system and event objects it is almost child’s play to plug them together and build something cool out of them. I guess I could go on and talk a while longer about how cool ECS’s are, but I will stop here. Thanks for swinging by and making it this far Cheers, Tobs.
  3. Article was originally posted here. In this article I want to talk about the Entity-Component-System (ECS). 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. First things first. You will find the full source code of my ECS in my github repository. An Entity-Component-System – mostly encountered in video games – is a design pattern which allows you great flexibility in designing your overall software architecture[1]. 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[2,3,4,5]. 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. Entities 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. Components are nothing more than container objects that do not possess any complex logic. Ideally they are simple plain old data objects (POD’s). Each type of a component can be attached to an entity to provide some sort of a property. Let’s say for example a “Health-Component” can be attached to an entity to make it mortal by giving it health, which is not more than an integer or floating point value in memory. 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 “Collision-Components” there is a “Collision-System”, for “Health-Components” there is a “Health-System” 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 “Physics-Systems” should be aware of “Collision-Components” and “Rigidbody-Components”, as both probably contain necessary information regarding physics simulation. In my humble opinion systems are “closed environments”. 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 entities and components life-cycle. 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[6]. Events are distributed through an “Event-Manager” 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. “position changed” or “player died”, it can tell the “Event-Manager”. He will broadcast the event and all subscriber for this event will get notified. This way everything can be interconnected. Well I guess the introduction above got longer than I was actually planning to, but here we are Before we are going to dive deeper into the code, which is C++11 by the way, I will outline the main features of my architecture: memory efficiency – 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. logging – to see what is going on I used log4cplus[7] for logging. scalable – it is easy to implement new types of entities, components, systems and events without any preset upper limit except your system’s memory flexible – 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) simple object lookup/access – easy retrieval of entity objects and there components through an EntityId or a component-iterator to iterate over all components of a certain type flow control – systems have priorities and can depend on each other, therefore a topological order for their execution can be established easy to use – the library can be easily in cooperate into other software; only one include. The following figure depicts the overall architecture of my Entity-Component-System: Figure-01: ECS Architecture Overview (ECS.dll). 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 – actually in the picture above at the very top; it should be upside down – 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’s get more into the details. Memory Manager Let’s start with the Memory-Manager. It’s implementation is based on an article[8] I have found on gamedev.net. 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 malloc. This memory now will be managed by one or more custom allocator. There are many types of allocators[9] ( linear, stack, free list…) and each one of them has it’s pro’s and con’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: class Allocator { public: virtual void* allocate(size_t size) = 0; virtual void free(void* p) = 0; }; The code snippet above is not complete, but outlines the two major public methods each concrete allocator must provide: allocate – which allocates a certain amount of bytes and returns the memory-address to this chunk and free – to de-allocates a previously allocated chuck of memory given it’s address. Now with that said, we can do cool stuff like chaining-up multiple allocators like that: Figure-02: Custom allocator managed memory. As you can see, one allocator can get it’s chunk of memory – that it is going to manage – from another (parent) allocator, which in turn could get it’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’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’s terminated. Figure-03: Possible distribution of global memory. Figure-03 shows how the global memory could be distributed among the second-tier modules: “Global-Memory-User A” could be the Entity-Manager, “Global-Memory-User B” the Component-Manager and “Global-Memory-User C”the System-Manager. Logging I am not going to talk too much about logging as I simply used log4cplus[7] doing this job for me. All I did was defining a Logger base class hosting a log4cplus::Logger object and a few wrapper methods forwarding simple log calls like “LogInfo()”, “LogWarning()”, etc. Entity Manager, IEntity, Entity<T> and Co. Okay now let’s talk about the real meat of my architecture; the blue area in Figure-01. You may have noticed the similar setup between all manager objects and their concerning classes. Have a look at the EntityManager, IEntity and Entity<T> classes for example. The EntityManger class is supposed to manage all entity objects during application run-time. This includes tasks like creating, deleting and accessing existing entity objects. IEntity is an interface class and provides the very basic traits of an entity object, such as an object-identifier and (static-)type-identifier. It’s static because it won’t change after program initialization. This type-identifier is also consistent over multiple application runs and may only change, if source code was modified. class IEntity { // code not complete! EntityId m_Id; public: IEntity(); virtual ~IEntity(); virtual const EntityTypeId GetStaticEntityTypeID() const = 0; inline const EntityId GetEntityID() const { return this->m_Id; } }; The type-identifier is an integer value and varies for each concrete entity class. This allows us to check the type of an IEntity object at run-time. Last but not least comes the Entity<T> template class. template<class T> class Entity : public IEntity { // 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; } }; // constant initialization of entity type identifier template const EntityTypeId Entity::STATIC_ENTITY_TYPE_ID = util::Internal::FamilyTypeID::Get(); This class’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[10] of static variables and second the nature of how template classes work. Each Version of the template class Entity<T> will have its own static variable STATIC_ENTITY_TYPE_ID. Which in turn will be guaranteed to be initialized before any dynamic initialization happens. The term “util::Internal::FamilyTypeID::Get()” is used to implement a sort of type counter mechanism. It internally increments a counter every time it gets called with a different T, but always returns the same value when called with the same Tagain. I am not sure if that patter has a special name, but it is pretty cool 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 – as long as your compiler is smart enough – 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 EntityManager class will take care of all this. Alright, let’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. Let’s have a look at the EntityManager class first. Figure-04 shows the overall structure of how things are stored. Figure-04: Abstract view of EntityManager class and it’s object storage. When creating a new entity object one would use the EntityManager::CreateEntity<T>(args…) 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 T. Forwarding these parameters happens through a variadic template[11]. During creation the following things happen internally … The ObjectPool[12] for entity objects of type T will be acquired, if this pool does not exists a new one will be created New memory will be allocated from this pool; just enough to store the Tobject Before actually calling the constructor of T, a new EntityId 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 Next the C++ in-placement new operator[13] is called with the forwarded args… as input to create a new instance of T finally the method returns the entity’s identifier. After a new instance of an entity object got created you can get access to it via it’s unique object identifier (EntityId) and EntityManager::GetEntity(EntityId id). To destroy an instance of an entity object one must call the EntityManager::DestroyEntity(EntityId id) method. The ComponentManager class 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 EntityId, 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. Figure-05: Component-Manager object storage overview. Using the ComponentManager::CreateComponent<T>(EntityId id, args…) method allows us to add a certain component to an entity. With ComponentManager::GetComponent<T>(EntityId id) we can access the entity’s components, where T specifies what type of component we want to access. If the component is not present nullptr is returned. To remove a component from an entity one would use the ComponentManager::RemoveComponent<T>(EntityId id) method. But wait there is more. Another way of accessing components is using the ComponentIterator<T>. This way you can iterate over all existing components of a certain type T. This might be handy if a system like the “Physics-System” wants to apply gravity to all “Rigidbody-Components”. 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’s type-identifier as the key. The EventManager class 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. Figure-06: Recap ECS architecture overview I hope at this point you got a somewhat idea how things work in my ECS. If not, no worries, have a look at Figure-06 and let’s recap. You can see the EntityId is quite important as you will use it to access a concrete entity object instance and all it’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’s pointer directly, but you can use events in combination with the EntityId. You could create a concrete event, let’s say “EntityDied” for example, and this event (which must be a plain old data object) has a member of type EntityId. Now to notify all event listeners (IEventListener) – which could be Entities, Components or Systems – we use EventManager::SendEvent<EntityDied>(entityId). The event receiver on the other side now can use the provided EntityId 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’s components could be deleted by some logic. Because you won’t clutter your code by extra clean-up stuff you rely on this EntityId. If the manager returns nullptr for that EntityId, you will know that an entity or component does no longer exists. The red square btw. is corresponding to the one in Figure-01 and marks the boundaries of the ECS. The Engine Object 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 “ECS/ECS.h” header and call the ECS::Initialize()method. Now a static global engine object will be initialized (ECS::ECS_Engine) and can be used at client side to get access to all the manager classes. Furthermore it provides a SendEvent<T> method for broadcasting events and an Update method, which will automatically dispatch all events and update all systems. The ECS::Terminate() should be called before exiting the main program. This will ensure that all acquired resources will be freed. The code snippet bellow demonstrates the very basic usage of the ECS’s global engine object. #include <ECS/ECS.h> int main(int argc,char* argv[]) { // 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->(DELTA_TIME_STEP); /* ECS::ECS_Engine->GetEntityManager()->...; ECS::ECS_Engine->GetComponentManager()->...; ECS::ECS_Engine->GetSystemManager()->...; ECS::ECS_Engine->SendEvent<T>(...); */ // more logic ... } // destroy global 'ECS_Engine' object ECS::Terminate(); return 0; } CONCLUSION 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: Make it thread-safe, Run each system or a group of systems in threats w.r.t. to their topological order, Refactor event-sourcing and memory management and include them as modules, serialization, profiling … I hope this article was helpful and you enjoyed reading it as much as I did writing it If you want to see my ECS in action check out this demo: The BountyHunter demo makes heavily use of the ECS and demonstrates the strength of this pattern. If you want to know how?, have a look at part two. References [1] https://en.wikipedia.org/wiki/Entity-component-system [2] http://gameprogrammingpatterns.com/component.html [3] https://www.gamedev.net/articles/programming/general-and-gameplay-programming/understanding-component-entity-systems-r3013/ [4] https://github.com/junkdog/artemis-odb/wiki/Introduction-to-Entity-Systems [5] http://scottbilas.com/files/2002/gdc_san_jose/game_objects_slides.pdf [6] https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing [7] https://sourceforge.net/p/log4cplus/wiki/Home/ [8] https://www.gamedev.net/articles/programming/general-and-gameplay-programming/c-custom-memory-allocation-r3010/ [9] https://github.com/mtrebi/memory-allocators https://www.gamedev.net/articles/programming/general-and-gameplay-programming/c-custom-memory-allocation-r3010/ [10] http://en.cppreference.com/w/cpp/language/constant_initialization [11] https://en.wikipedia.org/wiki/Variadic_template [12] http://gameprogrammingpatterns.com/object-pool.html [13] http://en.cppreference.com/w/cpp/language/new
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!