Jump to content
  • Advertisement
Sign in to follow this  
cooky

Object / Entity management

This topic is 2562 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm new, so hello to you guys. (And I'm not a native speaker, so please forgive little grammar mistakes. But you can correct me if you want to. ;) )

So here is my question:
I want to make a 3rd person RPG game. So my problem is actually not very specific, I know how to use C++, OpenGL, GLSL. I can render objects and load Wavefront .obj files. I know how to render lights etc. But I can't manage all those little pieces properly. So I'm currently looking for a nice way to manage my game objects. My first idea was a deep inheritance hierarchy. But that didn't work well, I had to use multiple virtual inheritance everywhere and the code seemed just bloated. Then I read about this "component based game design". Ok, that sounded really neat, but I'm not really sure how to implement it. My first intention was a entity class with a std::map<ComponentType, std::unique_ptr<Component>>. But that seems to slow down the creation of entities with a short lifetime. On top of that I'm not sure how to manage the communication between the components. I've searched a lot about this component model, but I couldn't find any neat implementation of this. Now I'm stuck here, I don't really know how to continue, but I also don't want to go back to a deep object hierarchy. Does anyone know a nice open source implementation of a component based entity model? Or did anyone solve this problem in a completely different manner? I'm currently open for more or less any new idea / impulse on this. ^^

One more question, I don't want to open another thread: How are bounding boxes / spheres / whatever (for collision detection) usually implemented in a game? Does the game generate that or is that loaded from the model file and the artists make them manually?)

Many questions in my first post, but I'm hoping for good answers, thanks a lot for any advices. :)

Share this post


Link to post
Share on other sites
Advertisement
Here's one place to start:
http://entity-systems.wikidot.com/

However, I too have started looking into Entity/Component based programming, and even begun programming one. My initial steps were to take a "Component contains data and logic" approach, and pass data to and from the different Components/Entities via a messaging system. My messaging system allows a component to register for certain events, and they can set events in the system or just their entity.

I may be looking into moving to more of a "Components contain only data, Systems do all the logic" approach, as it seems to be more efficient. In this case, the Components only contain the data about that component type, and the systems do the logic on the different component types. So, you'd have a Rendering System, Physics System, Input System, Player System, Enemy System, Weapons System, etc. And the Components would be of a Physical Component, Graphics Component, Vitals Component, Camera Component, Weaponry, etc.

Share this post


Link to post
Share on other sites
{1} I know how to {omissis}... But I can't manage all those little pieces properly.
{2} I'm currently looking for a nice way to manage my game objects. My first idea was a deep inheritance hierarchy. But that didn't work well
{3} I read about this "component based game design" ... I'm not sure how to manage the communication between the components.
{4} I couldn't find any neat implementation of this.
{5} How are bounding boxes / spheres / whatever (for collision detection) usually implemented in a game?
Hello cooky, welcome to gamedev.net. I understand the following might sound a bit harsh, it really isn't meant to be but I think it's better to go to the point.
  1. If you can manage all those things in a stand-alone system but not together, odds are it might be too soon for you to get your hands dirty in difficult problems. In particular, the break even point for the system you're looking for is very far from the initial implementation. If your needs are simple, I suggest to hardcode everything (yes, that's bad but it's also the only way to get the experience). One of the main troubles in writing generic systems is to avoid polluting them with application-level requirements.
  2. Yes, I guess I know what you're referring to. To my experience however, you can indeed get a lot of mileage out of those systems. If you have those ready to go, I suggest to stick with them.
  3. I've heard some people uses "signals" whatever they are supposed to be other people seem to call them "messages". For the time being, I'm using inheritance based on the Observer/Listener pattern. I plan for an explicit inter-object synchronization system in the future but that is unlikely to see the light soon. I'd be extremely careful on a truly arbitrary object dispatch: even with my current, simplified approach, component inter-communication is already the most CPU intensive process of gameplay management.
  4. Of course not. As I previously stated, the need for those systems arise in complex products. Therefore, it is very likely most people will want to protect their IP by trade secret. I'd be quite cautious with the above provided link, from a quick glance, it appears its scope is limited.
  5. They are built by the artist and encoded in the asset. Eventually, simplified collision meshes will be used. It is still possible to build AABB /Sphere/kDOP automatically, sometimes even with reasonable quality (UnrealED can do this for you if memory serves). It is at least partially manual work. It is done at preprocessing.


My initial steps were to take a "Component contains data and logic"

How does that compares to an object?

I may be looking into moving to more of a "Components contain only data, Systems do all the logic" approach, as it seems to be more efficient.
Don't. There's no way IMHO to make this transition for all entities. Sure, you can do it for some components (it's very recommended). It's not a "this" or "that" problem. Use the proper tool.

Share this post


Link to post
Share on other sites
In particular, the break even point for the system you're looking for is very far from the initial implementation.
Well, the implementation isn't really a problem, I already implemented a kind of component system. The problem is that I'm not happy with that implementation due to various reasons I mentioned in my first post. And if I add a message / event system, the performance to create one entity grows just more.
Example, how I wanted to do a simple map format:

Entity Flowerpot
{
GraphicsComponent (...)
PhysicsCompoent(...)
}

So my parser reads this and creates a new factory for a "Flowerpot". And then:

Flowerpot
{
(position, rotation)
(position, rotation)
(position, rotation)
}

So my parser parses this and the factory creates a new flowerpot in each position. But this just feels so bad, since each flowerpot needs to be created as a new raw entity, then you add the GraphicsComponent, then the PhysicsComponent.

So this is a pretty simple example, but I hope you see my point. Object creation is just soo inefficient, for each object a new std::map needs to be created, and if a entity has like ~15 components, you need to insert 15 things in that std::map. I think if the file is long, that would take forever.

Thanks for your help so far! :)

Share this post


Link to post
Share on other sites

[quote name='BeerNutts' timestamp='1323038649' post='4890512']My initial steps were to take a "Component contains data and logic"

How does that compares to an object?
[/quote]
I'm not sure I understand what you are asking. I believe I'm doing the standard Component-based entity system, where i build an entity out of components: A short example list of entities and components:
Entity list:
Bullet components: Physics, Graphics, Timer, Value
Enemy components: Physics, Graphics, Timer, Enemy, Health
Wall components: Physics, Graphics
Player components: Physics, Graphics, Timer, Input, Camera, Player, Health

Component list:
Physics: Handles world position, movements, and collision
Graphics: Handles object graphical representation (typically a sprite), and drawing it
Timer: Sends specific event after a specific time (can handle multiple events/times)
Value: Holds a integer value to represent certain stats (Bullet Damage, Armor Value, HealthBox Value, etc.)
Enemy: Handles the logic controlling an enemy, typically based on a timer and location of the player
Health: Handles the health of the entity; it gets notified when it's entity collides with a bullet.
Input: Handles all input from user, and sends signals for the given inputs
Camera: Describes the location of the camera in world coordinates.
Player: Handles all logic associated with the player; get messages from Input component


I may be looking into moving to more of a "Components contain only data, Systems do all the logic" approach, as it seems to be more efficient.
Don't. There's no way IMHO to make this transition for all entities. Sure, you can do it for some components (it's very recommended). It's not a "this" or "that" problem. Use the proper tool.
[/quote]


Maybe, but I'm just not sure the efficiency of all the events going on, and I figured it could be cleaned up by having the systems operate on the Components data only. We'll see.

Share this post


Link to post
Share on other sites

[quote name='Krohm' timestamp='1323073379' post='4890639']In particular, the break even point for the system you're looking for is very far from the initial implementation.
Well, the implementation isn't really a problem, I already implemented a kind of component system. The problem is that I'm not happy with that implementation due to various reasons I mentioned in my first post. And if I add a message / event system, the performance to create one entity grows just more.
Example, how I wanted to do a simple map format:

Entity Flowerpot
{
GraphicsComponent (...)
PhysicsCompoent(...)
}

So my parser reads this and creates a new factory for a "Flowerpot". And then:

Flowerpot
{
(position, rotation)
(position, rotation)
(position, rotation)
}

So my parser parses this and the factory creates a new flowerpot in each position. But this just feels so bad, since each flowerpot needs to be created as a new raw entity, then you add the GraphicsComponent, then the PhysicsComponent.

So this is a pretty simple example, but I hope you see my point. Object creation is just soo inefficient, for each object a new std::map needs to be created, and if a entity has like ~15 components, you need to insert 15 things in that std::map. I think if the file is long, that would take forever.

Thanks for your help so far! :)
[/quote]
I don't think it will take as long as you suspect; in fact, I don't think you'll notice any slowdown at all during the creation phase.

However, other people have created systems where the components are linked to an entity only based on a unique ID (integrer). So, an entity is only a uniqueue ID, and the components each have an OwnerEntity member which contains that ID value. That removes the entities from "containing" the components, and you just have a pool of components. This could be one giant pool of all components, or each component could be in it's own component-type's pool.

But, I still contend, I highly doubt you'll see any performance hit for creating many entities with many components in general.

Share this post


Link to post
Share on other sites

I don't think it will take as long as you suspect; in fact, I don't think you'll notice any slowdown at all during the creation phase.
Agreed.
Well, the implementation isn't really a problem, I already implemented a kind of component system. The problem is that I'm not happy with that implementation due to various reasons I mentioned in my first post. And if I add a message / event system, the performance to create one entity grows just more.
Then implementation is a problem. Anyway... for your parser, I strongly suggest to use either JSON or XML. I'm currently towards JSON.
What's the problem in creating raw entities and then adding components to them?
While I can see the overhead involved in multiple allocations, you must be doing things really wrong to find a performance problem into that as you're going through native C++.
I do that for about a thousands entities in my system... on a virtual machine which is at least 100X slower than C++. Performance has proven to be surprisingly good, even with the current message dispatch system (which is a linear scan).



Anyway, if you are sure you have a performance problem, preallocate everything and exploit definitions. If you know a flower pot is a graphical model component and a physical bounding box, create a single map for all the istances, then for each instance, preallocate a two-slot array. Of course that will take some care in the moment you attach a particle system to a flower pot.

Share this post


Link to post
Share on other sites

[quote name='Krohm' timestamp='1323073379' post='4890639']In particular, the break even point for the system you're looking for is very far from the initial implementation.
Well, the implementation isn't really a problem, I already implemented a kind of component system. The problem is that I'm not happy with that implementation due to various reasons I mentioned in my first post. And if I add a message / event system, the performance to create one entity grows just more.
...
So this is a pretty simple example, but I hope you see my point. Object creation is just soo inefficient, for each object a new std::map needs to be created, and if a entity has like ~15 components, you need to insert 15 things in that std::map. I think if the file is long, that would take forever.[/quote]


This is why a lot of games that leverage component-based design use a concept called "templates"; not to be confused with C++ templates.

Essentially, these templates are a high-level description of what components and their "base values" are to be assigned to entity archetypes. As an example, lets assume I want to create 1 or 5000 big bad orcs, the process is the same. I simply invoke the entity system by asking it to create that many entities providing it the ARCHETYPE_ORC template id. The entity framework when the game starts reads a list of archetypes and parses these so that later on when I need a specific entity of an archetype, it doesn't need to parse any files, the definition is already in memory. This speeds up the creation of entities considerably. You could obviously take this to the next step and prepare a small pool of these objects that are prefabricated and ready to use too (except for setting instance specific attributes).

Entity creation is probably one of the most expensive operations depending on how you implement it and how well you plan out being able to reuse entities and their components throughout a game level's life cycle. But I wouldn't focus as much on performance as I would on trying to get something "working". It's hard to get caught up in the performance side of things, but reality is in game programming, hardware is always a bottleneck for most games and so there will be lots of tuning needed later on, save all of it for that point :).

Share this post


Link to post
Share on other sites

However, other people have created systems where the components are linked to an entity only based on a unique ID (integrer). So, an entity is only a uniqueue ID, and the components each have an OwnerEntity member which contains that ID value. That removes the entities from "containing" the components, and you just have a pool of components. This could be one giant pool of all components, or each component could be in it's own component-type's pool.

But, I still contend, I highly doubt you'll see any performance hit for creating many entities with many components in general.


To elaborate and give some background for Cooky, the entity framework I designed is much like what BeerNutts describes. The EntitySystem class essentially manages a 32-bit unique number that begins at 1 when the game loads and this value increases with time as new entities are created. A simple interface of the system looks like this:


class EntitySystem
{
public:
EntitySystem(EventSystem* eventSystem);
~EntitySystem();

// Create a raw entity by getting an ID for a unique string name tag.
TEntityId createEntityByName(const std::string& name);

// Create an entity by providing an archetype template and name tag.
TEntityId createEntityByArchetype(const std::string& name, TEntityArcheTypeId typeId);

// Lookup an entity id by name tag
TEntityId getEntityIdByName(const std::string& name);

// Removes an entity by unique name tag and adds the entity to the remove pool.
// Entities are not deallocated until the game loop ticks the update method.
bool deleteEntityByName(const std::string& name);

// Removes an entity by entity id and adds it to the remove pool.
// Entities are not deallocated until the game loop ticks the update method.
bool deleteEntity(TEntityId entityId);

// Starts the entity framework.
// Loads all prefabricated templates and hooks into event framework
bool startup();

// Unloads the templates, detaches from event framework
void shutdown();

// Tick function used by the game engine
void update(double timeSinceLastFrame);

private:
// type declarations
typedef std::deque<TEntityId> TEntityIdQueue
typedef std::map<TEntityArcheTypeId, EntityArcheType*> TArcheTypeMap;

// variables
TEntityId mNextEntityId;
TEntityIdQueue mReusePool;
TEntityIdQueue mDeleteQueue;
TArcheTypeMap mArcheTypes;
};


There are a lot of other methods on my entity system class, but these are ultimately the basic ones. As you can see, entities in my framework have both a string name and an ID. The string name is used inside the editor tool so that designers can easily assign familiar names to objects in the scene so that they can easily reference "MainExteriorDoor" versus "MainInteriorDoor" rather than using the ID.

The one thing to note is that the entity system above is not the same as the World, which I have often seen considered one in the same. In my design, I can create multitudes of entities, creating components for those various entities but they have yet to be rendered in the game world or even updated. All entities are created in an inactive status. Entities are not considered active until I pass the entity id to the addToWorld method on the world manager class. When this occurs, an event fires that notifies all component systems that the entity is being added. This is when those component systems move the components for that entity id from the inactive list to the active list. I have a few more lists managed by each component system that take care of performance based tweaks such as updating objects that are a certain distance away from the camera that aren't being rendered presently but that we don't want to remove from memory just yet because the player may move and those entities may come back into view. That list is updated every 30-60 frames and another list is an object pool of deleted components where I maintain a varying number of allocated components for use later on since memory allocations can be expensive. But keep in mind, these last two lists are somewhat performance tuning decisions I have made in my own engine based on my game and it's mechanics. At the end, when the world manager class's removeFromWorld method is called, an event fires and the components of that entity are then moved from the active or update slower lists to the inactive list. This way an entity can be reactivated later if it is never deleted. If the delete entity method above is invoked, then the component systems are informed and the components are then moved to the delete queue where they'll be returned to the object pool at the start of the next game loop.

Hope that helps give you some ideas.
Chris

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • 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!