Refactoring Game Entities with Components
Up until fairly recent years, game programmers have consistently used a deep class hierarchy to represent game entities. The tide is beginning to shift from this use of deep hierarchies to a variety of methods that compose a game entity object as an aggregation of components. This article explains what this means, and explores some of the benefits and practical considerations of such an approach. I will describe my personal experience in implementing this system on a large code base, including how to sell the idea to other programmers and management.
GAME ENTITIES
Different games have different requirements as to what is needed in a game entity, but in most games the concept of a game entity is quite similar. A game entity is some object that exists in the game world, usually the object is visible to the player, and usually it can move around.
Some example entities:
- Missile
- Car
- Tank
- Grenade
- Gun
- Hero
- Pedestrian
- Alien
- Jetpack
- Med-kit
- Rock
Entities can usually do various things. Here are some of the things you might want the entities to do
- Run a script
- Move
- React as a rigid body
- Emit Particles
- Play located audio
- Be packed up by the player
- Be worn by the player
- Explode
- React to magnets
- Be targeted by the player
- Follow a path
- Animate
TRADITIONAL DEEP HIERARCHIES
The traditional way of representing a set of game entities like this is to perform an object-oriented decomposition of the set of entities we want to represent. This usually starts out with good intentions, but is frequently modified as the game development progresses - particularly if a game engine is re-used for a different game. We usually end up with something like figure 1, but with a far greater number of nodes in the class hierarchy.
As development progresses, we usually need to add various points of functionality to the entities. The objects must either encapsulate the functionality themselves, or be derived from an object that includes that functionality. Often, the functionality is added to the class hierarchy at some level near the root, such as the CEntity class. This has the benefit of the functionality being available to all derived classes, but has the downside of the associated overhead also being carried by those classes.
Even fairly simple objects such as rocks or grenades can end up with a large amount of additional functionality (and associated member variables, and possibly unnecessary execution of member functions). Often, the traditional game object hierarchy ends up creating the type of object known as "the blob". The blob is a classic "anti-pattern" which manifests as a huge single class (or a specific branch of a class hierarchy) with a large amount of complex interwoven functionality.
While the blob anti-pattern often shows up near the root of the object hierarchy, it will also show up in leaf nodes. The most likely candidate for this is the class representing the player character. Since the game is usually programmed around a single character, then the object representing that character often has a very large amount of functionality. Frequently this is implemented as a large number of member functions in a class such as CPlayer.
The result of implementing functionality near the root of the hierarchy is an overburdening of the leaf objects with unneeded functionality. However, the opposite method of implementing the functionality in the leaf nodes can also have unfortunate consequence. Functionality now becomes compartmentalized, so that only the objects specifically programmed for that particular functionality can use it. Programmers often duplicate code to mirror functionality already implemented in a different object. Eventually messy re-factoring is required by re-structuring the class hierarchy to move and combine functionality.
Take for example the functionality of having an object react under physics as a rigid body. Not every object needs to be able to do this. As you can see in figure 1, we just have the CRock and the CGrenade classes derived from CRigid. What happens when we want to apply this functionality to the vehicles? You have to move the CRigid class further up the hierarchy, making it more and more like the root-heavy blob pattern we saw before, with all the functionality bunched in a narrow chain of classes from which most other entity classes are derived.
AN AGGREGATION OF COMPONENTS
The component approach, which is gaining more acceptance in current game development, is one of separating the functionality into individual components that are mostly independent of one another. The traditional object hierarchy is dispensed with, and an object is now created as an aggregation (a collection) of independent components.
Each object now only has the functionality that it needs. Any distinct new functionality is implemented by adding a component.
A system of forming an object from aggregating components can be implemented in one of three ways, which may be viewed as separate stages in moving from a blob object hierarchy to a composite object.
OBJECT AS ORGANIZED BLOB
A common way of re-factoring a blob object is to break out the functionality of that object into sub-objects, which are then referenced by the first object. Eventually the parent blob object can mostly be replaced by a series of pointers to other objects, and the blob object's member functions become interface functions for the functions of those sub-objects.
This may actually be a reasonable solution if the amount of functionality in your game objects is reasonably small, or if time is limited. You can implement arbitrary object aggregation simply by allowing some of the sub-objects to be absent (by having a NULL pointer to them). Assuming there are not too many sub-objects, then this still allows you the advantage of having lightweight pseudo-composite objects without having to implement a framework for managing the components of that object.
The downside is that this is still essentially a blob. All the functionality is still encapsulated within one large object. It is unlikely you will fully factor the blob into purely sub-objects, so you will still be left with some significant overhead, which will weight down your lightweight objects. You still have the overhead of constantly checking all the NULL pointers to see if they need updating.
OBJECT AS COMPONENT CONTAINER
The next stage is to factor out each of the components (the "sub-objects" in the previous example) into objects that share a common base class, so we can store a list of components inside of an object.
This is an intermediate solution, as we still have the root "object" that represents the game entity. However, it may be a reasonable solution, or indeed the only practical solution, if a large part of the code base requires this notion of a game object as a concrete object.
Your game object then becomes an interface object that acts as a bridge between the legacy code in your game, and the new system of composite objects. As time permits, you will eventually remove the notion of game entity as being a monolithic object, and instead address the object more and more directly via its components. Eventually you may be able to transition to a pure aggregation.
OBJECT AS A PURE AGGREGATION
In this final arrangement, an object is simply the sum of its parts. Figure 2 shows a scheme where each game entity is comprised of a collection of components. There is no "game entity object" as such. Each column in the diagram represents a list of identical components, each row can be though of as representing an objects. The components themselves can be treated as being independent of the objects they make up.
PRACTICAL EXPERIENCE
I first implemented a system of object composition from components when working at Neversoft, on the Tony Hawk series of games. Our game object system had developed over the course of three successive games until we had a game object hierarchy that resembled the blob anti-pattern I described earlier. It suffered from all the same problems: the objects tended to be heavyweight. Objects had unnecessary data and functionality. Sometimes the unnecessary functionality slowed down the game. Functionality was sometimes duplicated in different branches of the tree.
I had heard about this new-fangled "component based objects" system on the sweng-gamedev mailing list, and decided it sounded like a very good idea. I set to re-organizing the code-base and two years later, it was done.
Why so long? Well, firstly we were churning out Tony Hawk games at the rate of one per year, so there was little time between games to devote to re-factoring. Secondly, I miscalculated the scale of the problem. A three-year old code-base contains a lot of code. A lot of that code became somewhat inflexible over the years. Since the code relied on the game objects being game objects, and very particular game objects at that, it proved to be a lot of work to make everything work as components.
EXPECT RESISTANCE
The first problem I encountered was in trying to explain the system to other programmers. If you are not particularly familiar with the idea of object composition and aggregation, then it can strike you as pointless, needlessly complex, and unnecessary extra work. Programmers who have worked with the traditional system of object hierarchies for many years become very used to working that way. They even become very good at working that way, and manage to work around the problems as they arise.
Selling the idea to management is also a difficult. You need to be able to explain in plain words exactly how this is going to help get the game done faster. Something along the lines of:
"Whenever we add new stuff to the game now, it takes a long time to do, and there are lots of bugs. If we do this new component object thing, it will let us add new stuff a lot quicker, and have fewer bugs."
My approach was to introduce it in a stealth manner. I first discussed the idea with a couple of programmers individually, and eventually convinced them it was a good idea. I then implemented the basic framework for generic components, and implemented one small aspect of game object functionality as a component.
I then presented this to the rest of the programmers. There was some confusion and resistance, but since it was implemented and working there was not much argument.
SLOW PROGRESS
Once the framework was established, the conversion from static hierarchy to object composition happened slowly. It is thankless work, since you spend hours and days re-factoring code into something that seems functionally no different to the code it replaces. In addition, we were doing this while still implementing new features for the next iteration of the game.
At an early point, we hit the problem of re-factoring our largest class, the skater class. Since it contained a vast amount of functionality, it was almost impossible to re-factor a piece at a time. In addition, it could not really be re-factored until the other object systems in the game conformed to the component way of doing things. These in turn could not be cleanly refactored as components unless the skater was also a component.
The solution here was to create a "blob component." This was a single huge component, which encapsulated much of the functionality of the skater class. A few other blob components were required in other places, and we eventually shoehorned the entire object system into a collection of components. Once this was in place, the blob components could gradually be refactored into more atomic components.
RESULTS
The first results of this re-factoring were barely tangible. But over time the code became cleaner and easier to maintain as functionality was encapsulated in discreet components. Programmers began to create new types of object in less time simply by combining a few components and adding a new one.
We created a system of data-driven object creation, so that entirely new types of object could be created by the designers. This proved invaluable in the speedy creation and configuration of new types of objects.
Eventually the programmers came (at different rates) to embrace the component system, and became very adept at adding new functionality via components. The common interface and the strict encapsulation led to a reduction in bugs, and code that that was easier to read, maintain and re-use.
IMPLEMENTATION DETAILS
Giving each component a common interface means deriving from a base class with virtual functions. This introduces some additional overhead. Do not let this turn you against the idea, as the additional overhead is small, compared to the savings due to simplification of objects.
Since each component has a common interface, it is very easy to add additional debug member functions to each component. That made it a relatively simple matter to add an object inspector that could dump the contents of the components of a composite object in a human readable manner. Later this would evolve into a sophisticated remote debugging tool that was always up to date with all possible types of game object. This is something that would have been very tiresome to implement and maintain with the traditional hierarchy.
Ideally, components should not know about each other. However, in a practical world, there are always going to be dependencies between specific components. Performance issues also dictate that components should be able to quickly access other components. Initially we had all component references going through the component manager, however when this started using up over 5% of our CPU time, we allowed the components to store pointers to one another, and call member functions in other components directly.
The order of composition of the components in an object can be important. In our initial system, we stored the components as a list inside a container object. Each component had an update function, which was called as we iterated over the list of components for each object.
Since the object creation was data driven, it could create problems if the list of components is in an unexpected order. If one object updates physics before animation, and the other updates animation before physics, then they might get out of sync with each other. Dependencies such as this need to be identified, and then enforced in code.
CONCLUSIONS
Moving from blob style object hierarchies to composite objects made from a collection of components was one of the best decisions I made. The initial results were disappointing as it took a long time to re-factor existing code. However, the end results were well worth it, with lightweight, flexible, robust and re-usable code.
Resources
Scott Bilas: GDC 2002 Presentation: A Data-Driven Game Object System
http://scottbilas.com/files/2002/gdc_san_jose/game_objects_slides.pdf
Bjarne Rene: Component Based Object Management. Game Programming Gems 5, 2005, page 25.
Kyle Wilson: Game Object Structure: Inheritence vs Aggregation, 2002, http://gamearchitect.net/Articles/GameObjects1.html
Jerarquia de entidades vs Agregación de componentes…
Interesante articulo que nos habla acerca de estas dos tipos de arquitecturas y de como, en un caso real, se paso de una jerarquia de entidades a un sistema de componentes….
This sounds cool, could provide a little code?
It’s hard to get an idea of exactly how it works. Is each component object a pointer in each class, that’s filled in if used, but otherwise null?
If so this seems it would be difficult to add new component types, but I’m probably missing something :D
[...] link happily stabs away at one of my own phobias for the future. Another piece on component programming, which to me sounds great but I’m never sure how these people are implementing it. I have half an [...]
I can’t show the code I was using, as it’s proprietary Neversoft code. But I think Bjarne Rene’s article has code.
[...] wzorca fasady w silniku gry. W pewnym momencie pojawiły się linki do dwóch prezentacji (1, 2) i artykułu. Prezentują one zupełnie inny niż powszechnie znany sposób tworzenia i zarządzania obiektami w [...]
[...] other developers to adopt component-based systems in their own code. Mick West of Neversoft has a great post on his blog detailing how he worked over two years to refactor the codebase used in the Tony Hawk series of [...]
It’s a pitty there are no examples in articles focusing on this subject (not to mention that it’s hard to find such articles). It would be nice to see some code or maybe a bit of pseudocode to know where to start from. I learn mostly by practice, so never really liked to read about stuff without seeing some real world use for it. Anyway the article is great, gave me a spark, now to find something to keep the fire burning…
Hi, I’ve made a working example of the gpg6-code, you can find it here:
http://www.unseen-academy.de/componentSystem.html
or here:
http://www.mcshaffry.com/GameCode/thread.php?threadid=732
regards
Hi,
I’ve also implemented a component object based system, based on the article from GPG6, in C#. At the moment it is focused on use in conjunction with XNA, but the implementation itself should be usable for other needs.
It is open-source, and available at http://codeplex.com/elephant
However, it is in a beta-stage and while it is certainly working, it is in need of quite a bit of refactoring here and there.
To me the component system seems like an anti-pattern too.
Its a solution to a problem that you cannot fix, if you want your design to change in runtime your better of using a scripting language.
It’s not one problem, there is a large number of overlapping factors that are addressed by the component system. Like anything, there is a trade-off between any systems you choose. The component system works very well for large complex games (and game logic engines) that have a lot of programmers working on them over a number of years. It has been used very successfully in many major games.
For little games, a traditional hierarchy can work just fine. In games where performance is not a problem, then you can code the whole thing in a script language.
The component system of object composition is just another tool in your programmer toolbox.
How can one be certain a component will work for every object without having overlapping functionality? There are an infinite amount of objects.
I’m not saying the component system hasnt been implemented in games succesfully but I doubt reusability which it is all about.
Why do you think people use it then?
Because they think people use it ;)
We are talking specifically about game objects here. For that use it worked very well for me. It provided both encapsulation and flexibility, which greatly increased productivity. “Reusibility” is not what it was all about.
It does depend on your application though.
[...] 16, 2007 in Articles Evolve your Heirachy by Mick West. Interesting article on using a composite design pattern for game objects to keep a [...]
[...] entity. Data lives in either the entity, its components, or both, depending on the exact design. Evolve Your Heirarchy [sic] is a good article on what it’s about and why you should do [...]
[...] December 2007 – You may also want to take a look at Mick West’s introduction to entity systems for game development, it’s a shorter read than my posts, but narrower in [...]
Thanks for the nicely-written explanation – I especially like the way you hand to us on a plate ready-made convincing arguments for production staff :).
I only very recently found this post, by which time I’d already started writing a longer series of posts on entity system design, development, and usage – otherwise I would have just pointed to your post for the first part and skipped straight ahead to the details of using them :).
Our main driver for using a component system was to avoid the deep inheritance hierarchies we’d all been involved with from various other games we’d worked on. The component system as described in GPG 5 could support dynamic adding/removal of components, but our game design never called for it so we didn’t use that capability. All our object types were set up in a separate object template editor, so no code changes were needed if we wanted to add new capabilities (which were already coded up as a component) to an object type. A good example of this would be making an object pick-up-able :-) Once the pick-up component was added to the object, it was possible to pick it up and drop it as needed.
I am not a great believer in code reuse (always sounds great in theory), but one very nice feature of a component system (if done right) is that the engine, editors and tools become general purpose enough to give a strong foundation to a new game whether it re-uses a lot of the old components or not. Our game editor had ui-hooks for each component type in case they needed something more than the base datatype edit fields allowed for. This made it really easy to get new functionality out to the designers.
Bjarne, thanks for that info. The tools aspect of it was something that we experienced at Neversoft as well – once you’ve written something for one component, it works for all of them. This was particularly useful for debugging.
Hi,
I’m glad you wrote this post. I have found people can be resistant to ideas like this. I think that inheritance is great for polymorphism but should rarely be used for reuse. Components should be used instead. Lowly coupled easily testable invariant components. Bjarne Stroustrup, Hurb Sutter ect… have been saying this for years. Yet programmers who haven’t come across this concept seem to have a hard time understanding it.
I’m not sure data-driven component systems are always the best solution although they are a useful tool. The problem I see with making all component structures datadriven (and I have done this in the past) is that its hard to debug.
Codewise I generally prefer simply written classes like:
class Player : public IOnUpdate, public IOnDamaged, public IOnDraw
{
…
virtual void OnDraw(…);
private:
PhysicsSphere mPhysics;
Movement mController;
Appearance mAppearance;
Attachment mAttachments;
…
}
You could register these to a list, like C#’s control system however I much prefer not doing that and just calling the components at the appropriate time: ie:
void OnUpdate(…)
{
mPhysics.OnUpdate(…);
mController.OnUpdate(…);
…
}
Also the components would also use the necessary interfaces like IOnUpdate. Now that’s yet another reason to avoid writing singletons. If you’ve got a specialzed manager for say draw for example (maybe it culls invisible objects) then you can simply make it an aggregate of Player and now player gets the same culling power that its the general Draw manager gets.
Further advantages of components are that you can easily move these around. Maybe you need to move the attachment manager into appearance because of the skeleton lives there. Well now you can. Maybe you decide that Player shouldn’t be responsible for drawing itself, or that you want to make the player server only. Its very simple to change with components.
One further advantage of breaking things into tiny tiny pieces that not many people seem to cover is merging. If everything is in the same file(s) then the chance of merge errors increases dramatically.
Anyway great stuff on the article. I hope that people will listen and learn from your experience so less people have to spend time digging themselves out of blobs.
SomeCoder, I think you will get a lot of the benefits from the way you are doing it – aggregation of components without going to data driven composition. I think the choice depends on the type and size of your project, and the number of people working on it.
I did not have a specific problem with debugging data-driven components. But we did develop some additional debugging tools to allow visualization of the aggregate objects. This eventually made it easier to debug.
I agree. I have had some benefit from using data driven components however I don’t think they are need in all cases. The extra leg work to develop debugging tools is sometimes overkill for particular problems. It all depends on how much time you have and the needs of the problem. I’m a big fan of data-driven stuff.
One thing I’ve done in the past with datadriven component systems is to have them register themselves for the services it needs. For example, not every component needs to be updated, or drawn, or etc… There where also versions of the interfaces that would automatically register so that it was very easy to add additional functionality. There was no base component class that anything needed. Any component could add componentmanagers for the types of subcomponents they wanted (ie onRenderManager, scheduler ect…). There where things like, debugI, drawI and datadrivenI. In effect any class could get component traits if it wished.
The idea being, things only use and have what they need and nothing more. Or to put it another way, they picked and choose what they wanted.
Anyway if you don’t do this, you risk ending in the same situation, with a huge component class to inherit from. Alternatively, you start using abstraction breaking techniques like dynamic_cast (*cough* I feel sick already).
This was a big win for that project because every system was independent. I could easily add/replace/remove/move ect… the rendermanager code, only affecting the systems that where using it.
There is one question. How the program stores references to game objects, created in component style? Suppose we have Combat AI System. Is it holds a lot of pointers to particular components of each object (Position, Script, Movement, etc.)? Doesn’t it look weird? :) May be it’s better to hold references to some GameObject class (which can give us such pointers to object’s components)?
You can do both. The AI system can hold a list of all AI components, and the object manager can hold pointers to each collection of components that make up an object. This could be a GameObject class. See “OBJECT AS COMPONENT CONTAINER” above.
In the diagram above, the two types of container are represented by the horizontal and vertical arrows.
If the AI system needs to hold reference to only one component of an object (AI component in your example) – it’s ok. But in some cases we may need references to several components of each object (like in my example above). Holding several references to each object in one system – it’s not ok, don’t you think? :) How do you handle with this?
It’s an optimization.
Say you had a sparesely used lightweight component, like a CTargetableComponent, and you wanted to find the objects that are targetable, then you could do:
for each object
if object has CTargetableComponent
object.TargetableComponent->target(...)
but that’s hugely slow, as you have to check every object, and iterate over the list of components to see if it has a targetable component. You could speed it up a bit by hard-wiring the component into the object, but it’s much easier, faster and more flexible to do:
for each TargetableComponent in Manager
TargetableComponent->target(...)
Multiple references to the same object raise problems, but they are well understood (reference counting, deferred destruction).
[...] was orginally a test of proof of my implementation of a Component based Entity-system and the integration of the great Farseer Physics Engine. I orginally wanted to extend the FlyWeight [...]
[...] entities. Mick West talks about creating game entities as components in his blog post “Evolve Your Hierarchy” – I think he is right and that Scala’s language support for this (especially in the [...]
[...] For more info on component or entity frameworks see this excellent post: Evolve Your Hierarchy. [...]
I would be very pleased if someone could show me a example code of that component scheme, with primary methods and loops that a implementation would have. Since I have no experience in a larger scale project it would be very interessting to see that.
Thanks in advice
Rikardo
See comments 8 & 9, above – they have links to some source code.
Thanks I missed those when I took a fast look!
Have I got it wrong if I think you would take use of multiple inheritance to create each object. Say like this:
class CPlayer : public Component, public Graphics, public Physics …
{
…
};
Yes, you have it wrong :)
There is no CPlayer class, there are only components, and collections of components which are aggregated at run time.
pPlayer = new CCollection
pPlayer->Add(new CGraphics)
pPlayer->Add(new CPhysics)
pPlayer->Add(new CStickyNature)
Damn! Thanks for the quick answers!
The first thought that strikes me is that does it really work? Or actually how can it work :P
I’am a really newbie in this area and tries to build a little bit larger system that could atleast show some cool results in front of my eyes.
Its hard when you don’t know how to grip the ACTUAL problem. But as I believe it is for me to first of all describe HOW to explain each object in a programmable way. As objects with position moving and colliding under the laws of physic.
I want to learn about what I would call (since I don’t have any better word) “Game Engine Theory” including the most necessary parts Input, Graphics and Physics.
Thanks!
Rikardo
It feels that I lack the knowledge to put everything into a whole nice system. This is one way to approach the situation but almost everytime someone shows someting like you just did, I directly think: Aha! OK, but how does it really end up as a whole system. It irritates myself :D
There are several ways you can arrange it. What I do is have a CComponent base type which has a position and some flags. Then derived from that is a CCollection type, and all the other components (CBounceAround, CSprite, CText, CModel).
Hence the components form a tree structure. There is a root collection, and that contains various components, most of which are collections, which themselves contain other components and collections.
Rendering traverses the tree, calling the components Render() function with their relative position. Generally the position of complex objects is stored in the parent collection, and the mover component updates that position.
It’s a little difficult to understand until you actually do it. It can take a while before it becomes useful.
But still physics and graphics should be separated but I guess they are when building the components of different parts?
Yes, physics and graphics should be separate. But it depends on your situation – like, how many different entities are there going to be? When I implemented my first system I was refactoring an existing “Blob” system. But building something from scratch depends on what you eventual goals are.
The coupling between components can be a problem. You will invariably need some, and there are various ways of doing it.
Say this situation
Collection* Player = new Collection();
Player -> Add(Movable);
Player -> Add(Graphics);
Player -> Add(Boundary);
// This would not exist as a callable method?
// How would you resolve this to be able to reload another model for example.
Player -> LoadModel("model.dat");
And a render method would lie inside the graphics component, but how could you reach this?
You would have some kind of factory object that created composite objects – either from code, or data driven, or from script.
For rendering, you could either have ALL components have a virtual Render() method, and iterate over all of them. Or you could have the renderable components register with a manager. Or each component type can have its own manager.
The Player example above is a little simplistic. Who manages the “Player” pointer? Do you even need one. There are several ways of doing this – the component pattern is only part of a larger picture.
As for getting the model component, various ways, depending on implementation
Player->GetComponent<CModel>()->LoadModel(“model.dat”);
Player->GetComponent(TYPE_CMODEL)->LoadModel(“model.dat”);
Player->mp_model->LoadModel(“model.dat”);
ModelManager->GetModel(Player)->LoadModel()
Scripted:
FireEvent(event=”loadmodel”, target=”Player1″, params={model=”model.dat”, wait=false})
player_table.model_comp:Load(“model.dat”)
I’ve seen this type of implementation in Torque X
do you have a code for this type of implementation for XNA?
[...] [2] Mick West: Evolve your Hierachy (sic!) http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
[...] I did a lot more work on both the level editor and object editor, and they’re really coming along. In fact, they’re both in a usable state, and all the work hence forth will be polish and new features. I spent a lot of time updating and robustifying the underlying architecture, and I’m happy with what I’ve got now. The GUI flow is a lot more straightforward and easy to extend. The graphics library is more flexible. It’s now cache and streaming friendly, which will come in handy down the line. The component system is just lovely. It was worth taking the time to wrap my head around the concept (thank you MickWest!). [...]
[...] a series of these classes to make whatever is needed. It’s nothing revolutionary like a component system or anything but it definitely works. Until next time « Game State [...]
[...] almost entirely data driven. In fact once I had almost finished to redesign I stumbled upon some articles about data-driven game systems and entity systems and I rewrote about a third of the code [...]
[...] in general because there’s already some great articles out there on the subject such as this one by Mick West. My implentation of a component system differs a little from what’s described in [...]
[...] Evolve Your Hierarchy : Refactoring Game Entities With Components 2. Game Programming Gems 6 , Section 4.6 : Game Object Component System 3. A Data-Driven Game [...]
[...] 1. http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
I’m trying to understand the semantics behind the different components. Say that you had implemented a new extendable entity system, the most beutiful you could imagine.
1. How would you have divided the responsibilities between the different components?
2. What guidelines/rules would you instruct to new programmers so that the system could be kept as clean as possible when it’s added with many new components?
Thanks
Beware of striving for beauty over pragmatism.
Your questions are a little broad, and really the only answer I can give us “it depends”. What is your actual goal here? Where are you now, and where are you going?
My goal is a simple 2d prototype (platforms, player, some enemies, some gui), an environment to learn thinking about entities as components.
But what is a component, really? (i.e. “separtion of concerns”)
Is is a pure data structure without functions, which is operated on by subsystems, or is the componentes themself the subsystems.
I do realize that there is multiple ways to approach the problem, my objective is finding the right metaphor to work under so it is consistent.
… I’m looking for a definition, which explains the perspective/angle/paradigm/mindset/mental model in how to think about the components, the rules of conduct and semantics in naming them.
A component is still just an object containing data, with methods that act on that data. It’s just more atomic, and the components are used in aggregate to create entities (which would normally be complex objects)
I’d recommend you look at done of the implementations discussed in the comments.
Hi Mick,
I’d be interested to hear what you think of Adam Martin’s (incomplete!) series of articles which describes a different kind of entity system. http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/
This concept does not consider an entity or a component to be an instance of a class but, rather, pure data similar to a database table. It also relies heavily on a FlyWeight implementation (at least, that’s what I think).
I’ve used your concept of component systems (OOP components) in several projects, but Adam’s way of looking at it has really intrigued me. It would be great to hear your thoughts on analysis and comparison of the two, etc.
My article is a fairly simple description, and leaves open a lot of the implementation issues.
You can abstract things a lot, but there can be performance issues. What Adam seems to be describing is the “Object as Pure Aggregation” method, which is shown in the the diagram above. The method of aggregating (saying which components belong to which entities – or more abstractly how entity-like output arises from discreet components) is an implementation issue. Adam suggests using a Database – but I’m not sure if he’s actually done this.
Great write-up, super useful for communicating similar ideas to other people on the team. Thanks!
errata: “This may actually be a reasonably solution” -> “This may actually be a reasonable solution”
Thanks Andrei, I fixed the typo.
Great article Mick.
While reading your article though, a question kept popping up in my head which I don’t seem to be able to shake off.
Take a light or a camera for instance. Beyond the very essence of their nature, i.e. as objects that illuminate or capture the scene, either of them may have or have not a Position, Render, Physics or Script component and so on, so they clearly must have their place in such a system, either as entities or as components, so my question is how do you go about incorporating these objects into such a system? Are lights and cameras components too? So a scriptable camera consists of two components, the CameraComponent and the ScriptComponent? What about a particle emitter? Or a physical joint?
Generally speaking, what’s the rule of thumb for recognizing components?
Thanks in advance.
Ash, that sounds about right. A fairly simple thing such as a camera could be a single component, but would likely be at least a CameraComponent that specifies the view vector and FOV, and some ScriptComponent or AttachComponent that governs how it moves.
When creating components, or functionality for an existing component, consider if it can be split into sub components that might be useful in another composite object. All the things you mention could be components.
I’m a fan of this appraoch. I despise it when I look at someone elses code and I have to work my way up six or seven inheirtance levels just to find the meat and potatoes of some procedure. There’s nothing more confusing about joining a project than learning what class in the heirarchy does exactly what, especially when they’re horribly mislabelled classes which are doing things the name suggests they shouldn’t be doing and no one’s bothered to update it.
I’ve tried my hand at this design before and the real difficulty I’ve always run into is enforcing a particular order that components should be in the container class. The method I’ve employed before is to have each component maintain it’s own list of dependencies which are checked when the component is added to an object or component collection. The problem inherent with this is that it’s very easy to create cyclic dependencies, especially later on in the project when you have potentially thousands of components.
There’s no easy solution, but the traditional approach simply doesn’t cut the mustard these days in my opinion, and something new like the composite design is definitely an improvement.
Truly fascinating!!!
[...] more capable of handling new things. For instance, enemies are now based on components as per an article on Cowboy Programming, making it super easy to create new enemy behaviors (and combinations of existing behaviors). It [...]
Incredible! Do you have an example running? because i have several problems trying it.
thanks
jhon
[...] http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
[...] Engine: Case Study: The Age Of Mythology Doug Church – Object Systems Mick West – Refactoring Game Entities with Components Kyle Wilson has a blog with a bunch of strong posts about engine design. Be sure to check out the [...]
[...] the ground will have a render part and a physics part. My system is similar to the one mentioned in this article. Components should be highly reusable. For example, I might write an AI part, let’s say for [...]
[...] would have pretty much all part types except AI. My system is similar to the one mentioned in this article. Components should be highly reusable. For example, I might write an AI part, let’s say for [...]
[...] Evolve Your Hierarchy ( 2007 ) By Mick West http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
[...] on structuring your game code. The first was the Guerilla Guide to Game Code, and the second was Evolve Your Hierarchy, by Mick [...]
[...] Evolve Your Hierarchy, one of the classic texts on the subject by Mick West [...]
[...] Inspired by this article, I got thinking about the overall effectiveness of my programming methods. [...]
[...] on January 10, 2011 by Rohin Knight I recently learnt about component based game engines at http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/. But I was unsure how I should implement [...]
[...] architecture, and get a very flexible code. To learn more about this model, I invite you to read Evolve Your Hierarchy by Mick [...]
[...] many have proposed a component based system. Before continuing, I recommend reading Evolve Your Hierarchy, a good introduction to the [...]
You mention using a factory method to create entities. I’ve gotten used to inheritance and I like each entity having it’s own class. However, I want to switch to components.
Should I use a single factory class with different methods for each entity, or should I use separate classes for each entity, and use the class constructor to create the entity?
A factory will encapsulate better, avoiding duplication.
[...] Evolve Your Hierarchy [...]
[...] many have proposed a component based system. Before continuing, I recommend reading Evolve Your Hierarchy, a good introduction to the [...]
[...] This link gives a great introduction to an entity component system. [...]
[...] got an article from a friend that will help with solidifying my engine architecture. I have a programming [...]
[...] http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
[...] Share this on:Facebook Twitter Delicious Digg Google Reddit Stumbleupon Email ← Indexes.js – When you need to find certain [...]
[...] Mick West’s blog post on the component system at Neversoft in the Tony Hawks games is an excellent introduction to entities and components. It’s where I first found out about components. [...]
[...] Note: If you don’t have at least a vague concept of component-entity design, read this article first. [...]
[...] Cowboy Programming discusses these benefits in illustrated detail while Lambdor discusses some problems he found. [...]
[...] I used as reference: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ http://gameprogrammingpatterns.com/component.html [...]
[...] Evolve Your Hierarchy (Cowboy Programming) – A detailed review of components vs OO hierarchies. [...]
[...] mess. I fell into the classic deep hierarchy problem and, after some research, I began working on a component-based entity system. In the near future I will be posting a series of coding posts about the [...]
[...] hierarchical classes with inheritance. It has been used for some years in the game industry (Here one of the most cited article on the subject on CowboyProgramming blog) , but it has recently become a big trend over amateur/indie game development. Even so, it’s hard [...]
[...] Evolve Your Hierarchy (Cowboy Programming) – A detailed review of components vs OO hierarchies. [...]
[...] Dokuro2 is a game engine that I am writing in SFML to allow me to create games in it more easily. It is has a component based entity design, which I think has many advantages over the usual inheritance based entity design. I read this article and it converted me http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ =) [...]
[...] for avoiding using deep inheritance hierachies when classifying game objects123, and I won’t reiterate that argument here. Suffice it to say, using only [...]
[...] a great differentiator from other engines. Instead of long chains of inheritance it's built on a "Entity Component System" where sprites (called Entities) are manipulated by adding reusable Components to [...]
[...] min) Read up on component based (as opposed to hierarchy based) engine design (1, 2, 3, [...]
[...] Evolve your hierarchy – Cowboy Programming – http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
[...] leer más sobre este sistema en la siguiente página: Refactoring Game Entities with Components. Donde se explica más en detalle como funciona este sistema. También en la siguiente [...]
[...] Components for game entities [...]
[...] many have proposed a component based system. Before continuing, I recommend reading Evolve Your Hierarchy, a good introduction to the [...]
[...] System, a sort of Architectural Pattern to develop game logic (read an excellent introduction here.) Nevertheless, before even starting to think how to apply it in a functional context, I’ve [...]
[...] http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ http://gameprogrammingpatterns.com/component.html [...]
[...] recently came across an article, which simply explains what we might want some of our game entities to do, these are summarized [...]
[...] of supporting multiple-inheritance with dynamic type casting in an engine that makes heavy use of component-based design are relatively [...]
[...] http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
[...] It’s really easy to use, though it might be confusing at first because it’s a modular game engine that uses entities and components. I suggest you read this article if you don’t have any experience with it: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
[...] attempting to framework my fixture item courses comparable to how it is finished in this article. just one method to carry out this tactic is discussed in this StackOverflow [...]
[...] It’s really easy to use, though it might be confusing at first because it’s a modular game engine that uses entities and components. I suggest you read this article if you don’t have any experience with it: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
[...] Um artigo que tenta mostrar as vantagens de usar agregação ao invés de herança: (link) [...]
[...] mentioned in an article by Cowboy Programming here it has marginal gains early into a project but reaps high development gains later [...]
[...] C++ version. I’ll go into more specifics on it later, but for further reading on the concept try here, or even search for “Component Based Architecture”. Share this:TwitterFacebookLike [...]
[...] bug, repetir” cuando se trata de programas inútiles como el mío. Tomemos como ejemplo el modelo de programación de Entidades y Componentes. El artículo que enlazo (nota: si están en esto del desarrollo de juegos deberían darle una [...]
[...] http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ [...]
[...] Evolve Your Hierarchy [...]
[...] Cow boy programming : Evolve your hierarchy Si vous avez aimé, partagez ! [...]
[...] West. Evolve Your Hierarchy. http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/, January [...]
[...] West. Evolve Your Hierarchy. http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/, January [...]
[...] If you are thinking of taking a more modular approach, Mike West discusses this in his post “Evolve Your Hierarchy”. Or alternatively if you are planning on making a larger application and need more structure and [...]
Have you used or considered Component / Entity System frameworks to build games? Interested in your feedback and experience….
Yes, I have built a system from scratch in Java, and now use it every day as a built-in feature of Unity. Their embrace of this philosophy has radically simplified development for me. Mick West (co-founder of Neversoft) got me started on the journey wi…