Jump to content

  • Log In with Google      Sign In   
  • Create Account

Composition heavy OOP vs pure entity component systems?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
31 replies to this topic

#21 dublindan   Members   -  Reputation: 457

Like
0Likes
Like

Posted 22 August 2012 - 04:37 AM

On the topic of is-a vs has-a:


With the traditional inheritance-based approach, every entity must have at least one is-a relationship and zero or more has-a relationships.

So, if a Tank is composed of a Vehicle and a Cannon, is a Tank a Vehicle that has a Cannon, or is it a Cannon that has a Vehicle? Obviously the former, in this case, so lets go down to the next level.

A Vehicle is composed of a Chasis, some Wheels and an Engine. Is a Vehicle a Chasis that has Wheels and an Engine? Is it an Engine that has a Chasis and Wheels? Again, the former makes most sense, but at what point does a Chasis stop being a Vehicle? If it has no Wheels and no Engine (and so is basically a stationary frame), its hardly a Vehicle any more: "A vehicle is a mechanical means of conveyance, a carriage or transport."

So you could encode some rules into your class that ensures that a Vehicle always has an Engine and Wheels. But what if we want a Plane? A Boat? A HotAirBalloon?

Through the use of additional layers of abstraction and complicated inheritance hierarchies it is possible to come up with a structure that allows this kind of flexibility (A Vehilce is a Chasis that has a PropulsionSystem, A PropulsionSystem is a... whatever, through additional layers in the hierarchy, eventually we can encode what we need), but at the cost of significant complexity (and complexity = bugs, often!) and work and god forbid something needs to change later!

The alternative is to introduce an abstract "is a" which we will call an entity. An entity consists of (is composed of, has a) a number of components. Components are generally self contained.

So a Tank is an entity and that entity consists of a Chasis, an Engine, Wheels (or Tracks), a Cannon...
A Plane is an entity which consists of a Chasis, JetEngine, Wings....
A HotAirBalloon is an entity which consists of a Basket and a Balloon...

The rules of what makes a Vehicle a vehicle or a Tank a tank (or a Tank a Vehicle) are now longer hard coded into a class, but instead is now coded into the constructor function of that entity: make_tank(...) contains all the code to make sure that the entity it creates adheres to the interface required for a tank or a vehicle or a weapon or whatever else that entity should be. It is this interface which defines the is-a relationship. Duck typing, if you will.

The concept could be expanded to allow entities to be derived: a Tank is a Vehicle entity with a Cannon component (and its basically a union of the set of components that make up a Vehicle and the set of components that make up a Cannon - each component could itself be treated as an entity which contains only itself in its set, so if later Cannon consists of a Turret and FiringMechanism, the definition of Tank need not change). But you should also be able to swap components out: A Tank = Vehicle ∪ Cannon ∪ Tracks ∩ Wheels.

Finally, the concept could be extended to allow interfaces (similar to Java interfaces, but that are implemented by the union of the components in the set that makes up the entity - again, duck typing). That is, IVehicle is an interface through which you can interact with vehicles. It doesn't care how the vehicle is a vehicle as long as it acts like one (ie it has the IVehicle interface). It could meet this interface by composing the Engine and Wheel and Chasis components or through Basket and Balloon or whatever you want.

I feel that is a is an abstract concept that describes the union of all the has a parts - a set of interfaces (a Tank is a IVehicle and a IWeapon for example) that describes what the set of components (ie entity) represents and I feel this is more true to real life than inheritance hierarchies, which don't seem very natural (from a real live POV) to me at all.

Sponsor:

#22 CC Ricers   Members   -  Reputation: 733

Like
0Likes
Like

Posted 22 August 2012 - 08:43 AM

So, if a Tank is composed of a Vehicle and a Cannon, is a Tank a Vehicle that has a Cannon, or is it a Cannon that has a Vehicle? Obviously the former, in this case, so lets go down to the next level.

A Vehicle is composed of a Chasis, some Wheels and an Engine. Is a Vehicle a Chasis that has Wheels and an Engine? Is it an Engine that has a Chasis and Wheels? Again, the former makes most sense, but at what point does a Chasis stop being a Vehicle? If it has no Wheels and no Engine (and so is basically a stationary frame), its hardly a Vehicle any more: "A vehicle is a mechanical means of conveyance, a carriage or transport."

So you could encode some rules into your class that ensures that a Vehicle always has an Engine and Wheels. But what if we want a Plane? A Boat? A HotAirBalloon?


LorenzoGatti has a point, that the Tank and Cannon example may not be a very good one here. In most cases having a distinct Cannon class is not necessary. For most use cases in games, you are breaking down the object into more parts than you need to.

In a typical shooter or RTS game, there are no fundamental differences between a cannon and a machine gun. Both of them are types of weapons, and they mainly differ in their range, damage inflicted, and firing rate. You do not need to have a separate MachineGun class to make a weapon that has these properties differ from a Cannon class. I would just have a Weapon class (for the lack of a better word) and the stats that distinguish one weapon from another would come from an external model/data structure.

Maybe you have a case for overriding some of the behavior by the way they can be controlled and what terrain it can move over, but you may be able to extract some of this information as well. Planes can pitch and roll, regular tanks can't. Maybe apply special movement constraints in the vehicle class, then you can make a cool futuristic hover-tank that only flies for a short time. In the end I would just have a Vehicle class that would optionally contain one or more Weapons. Most games do not care about the inner workings of wheels or a vehicle chassis. If you want to give a plane a different appearance from a boat, then supply it on the view side. Tell a Vehicle object it needs to load "airplane.obj" in a structure reserved for the visual assets of the vehicle. The same goes with collision shapes. Don't try to use specialized classes to model real life, when their behaviors are very similar in the game. Instead, make components as generic as possible and provide the differences through a view and model-like design.

Edited by CC Ricers, 22 August 2012 - 08:46 AM.

My development blog: Electronic Meteor

#23 dublindan   Members   -  Reputation: 457

Like
0Likes
Like

Posted 22 August 2012 - 10:04 AM

LorenzoGatti has a point, that the Tank and Cannon example may not be a very good one here. In most cases having a distinct Cannon class is not necessary. For most use cases in games, you are breaking down the object into more parts than you need to.


Sure - you can always simplify and flatten things down if you like. I mean, on the other extreme, you could represent all Actors as the same class, have a bunch of flags represent the different things your Actor might want to do (canShoot, canFly, canCarryPerson, isPerson) and handle all the code in one place but vary the models or sprites or whatever visual data you have. Obviously a balance between the two extremes needs to be found and the question one needs to ask is what level of flexibility do you need and what data do each of your game systems need. If you have vehicles that drive with reasonably accurate physics (so any game where driving is a big focus), your physics engine might indeed simulate wheels and your game logic might indeed have an engine that handles how it drives (or at the least is a pure data container with all the properties representing the engine: power, weight, whatever) - the point, as I see it, of component entity systems is that the components can be simple data containers if that's all you need, or they can have systems with complex logic associated and components in themselves are extremely cheap (eg they could be allocated from a memory pool, they could be cache line aligned, the processing loop could prefetch...).

But that's besides the point I was implying in my previous post - obviously the example was a contrived one. The real point wasn't even specific to game programming, but rather that in my opinion composition is much more natural to inheritance in that with real world objects, entities can often be classified as many things (I'm a living thing, I'm human, I'm a programmer, whatever...) that are dependant on the entities state (either internal or external) and that entities are composed of many things. Also often removal of some of these things does not cause the entity to lose a is-a relationship, removal of other things might (but exactly which things may not be well defined - if I kept removing parts of my body, when do I stop being human?). Then I went and mentioned some ideas which could be used to take the concept even further.

I think that this idea is just as applicable in software outside of games too.

But obviously, as you imply, a balance must be struck to find the level of abstraction that best fits the problem space - but isn't this always the case, regardless of how the problem is being modeled (OO or otherwise)?

Edited by dublindan, 22 August 2012 - 10:07 AM.


#24 LorenzoGatti   Crossbones+   -  Reputation: 2762

Like
0Likes
Like

Posted 23 August 2012 - 08:14 AM

The real point wasn't even specific to game programming, but rather that in my opinion composition is much more natural to inheritance in that with real world objects, entities can often be classified as many things (I'm a living thing, I'm human, I'm a programmer, whatever...) that are dependant on the entities state (either internal or external) and that entities are composed of many things. Also often removal of some of these things does not cause the entity to lose a is-a relationship, removal of other things might (but exactly which things may not be well defined - if I kept removing parts of my body, when do I stop being human?).

Don't be too philosophical: classification of objects and relations are only important in software design if they are actually used.
For example, a game might want separate classes for Vehicle and Bullet (or VehicleCollection and BulletCollection in certain types of entity architecture) because they actually have very little in common (different AI needs, different collision detection, different lifetime and number of class instances, separate updates at different points of each frame...) but not for Howitzer and MachineGun because the distinction cannot possibly matter, ever, because all code works with generic Weapon entities.
Removing pieces of objects is also utterly uninteresting from a software design viewpoint, not only because we never ask whether the mutilated object "is-a" something, but more importantly because the altered entity is either in a valid state or corrupt, according to the invariants and expectations that the code contains; nothing uncertain or ambiguous can happen.
Produci, consuma, crepa

#25 dublindan   Members   -  Reputation: 457

Like
0Likes
Like

Posted 23 August 2012 - 11:39 AM

Don't be too philosophical: classification of objects and relations are only important in software design if they are actually used.

I was merely pointing out how composition has a better real world analogue than inheritance. An analogy to explain how is-a isn't as clear cut as it first seems. In most software, you are unlikely to require the flexibility of adding or removing components at runtime, but I feel that in games, having the ability to do so should you want to is a huge bonus and allows you to do cool things that would otherwise be hard. Ideally, the development kit would be able to bake entities that do not use the flexibility so you don't pay for it if its not used, but I see that as an optimisation (which should be done later). I think it rarely makes sense to hard code limitations into the very design.

Howitzer and MachineGun because the distinction cannot possibly matter, ever, because all code works with generic Weapon entities.

Sure - I would see them as being the one Gun or Weapon component and the differences between them are defined purely in a data-driven way: their attributes have different values. Data-driven design is certainly a very good thing.

Removing pieces of objects is also utterly uninteresting from a software design viewpoint, not only because we never ask whether the mutilated object "is-a" something

Sure - but I often see it driving a design. Often people start with "Well, X is-a Y, so I'll derive X from Y and..." while I think this is the wrong approach. Instead, I feel is-a is only useful in the sense of "does it provide the interface I need?" - think of it like duck typing. So, instead of trying to figure out if something is a type of something else or if it has a something else instead and then building an inheritance hierarchy from this, I feel a better approach is to compose all components rather than inheriting from them.

I used to like hardcore OO a number of years ago, but these days I find it has too many limitations, both in design (as I've been trying to articulate in this thread) and technically: eg, OO and concurrency/parallelism, OO and cache/memory friendliness etc. Therefore I nowadays prefer a functional-programming approach, though I still code in a style that I would consider somewhat OO - except that my entities are now compositions of components with little or no inheritance in sight - functional programming makes it easy to compose both data and functions. When I program in C++, I obviously do use classes and even inheritance, but I still like to design my programs with functional programming in mind and I find that it not only simplifies the design and makes it more flexible (in real life that flexibility often gets traded off for performance later when its apparent that having two components instead of one is 1) not required and 2) a performance issue), but it also makes it easier to support concurrency safely and to solve cache/memory issues - hell, that was one of the big goals of component entity systems after all.

but more importantly because the altered entity is either in a valid state or corrupt, according to the invariants and expectations that the code contains; nothing uncertain or ambiguous can happen.

Sure. This is a very important point, regardless of the design.

#26 Gabriel Grom   Members   -  Reputation: 108

Like
0Likes
Like

Posted 24 August 2012 - 11:42 AM

I would like to say this is a great topic so far, with lots and lots of info contained and a lot of opinions. I was wondering if this is a good example of what would be a good entity architecture so that I see if I should go ahead with it or not: http://obviam.net/index.php/design-in-game-entities-object-composition-strategies-part-1/
http://obviam.net/index.php/design-in-game-entities-object-composition-strategies-part-2-the-state-pattern/

#27 BeerNutts   Crossbones+   -  Reputation: 2999

Like
0Likes
Like

Posted 24 August 2012 - 12:52 PM

I would like to say this is a great topic so far, with lots and lots of info contained and a lot of opinions. I was wondering if this is a good example of what would be a good entity architecture so that I see if I should go ahead with it or not: http://obviam.net/in...ategies-part-1/
http://obviam.net/in...-state-pattern/


Gabriel, that's kind of the beginning of the idea of Composition, but it's only partial IMO. It limits some because, what if you have a droid that you can ride on? Is it a droid? or a vehicle?

Using a true entity/component system, it can be both easily. Instead of having a is-a droid relation ship, and it would go into the droid list, you have a generic entity, built with a graphics component, physics component, droid component, and weapon component.

Then you have systems that act on these components. ie, the droid system handle entities with the droid component, and it handles the AI and movement (depending if droid component was built with wheels or track, or nothing), as well as attempting to shoot it's weapon.

If you add a vehicle component, then the vehicle system can work on that entity, and allows a player to ride on the droid, and shoot from the back of the droid.

That's the general idea. My dev journal has some articles about it, and there's plenty of other data too.
My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

#28 Gabriel Grom   Members   -  Reputation: 108

Like
0Likes
Like

Posted 24 August 2012 - 02:36 PM


I would like to say this is a great topic so far, with lots and lots of info contained and a lot of opinions. I was wondering if this is a good example of what would be a good entity architecture so that I see if I should go ahead with it or not: http://obviam.net/in...ategies-part-1/
http://obviam.net/in...-state-pattern/


Gabriel, that's kind of the beginning of the idea of Composition, but it's only partial IMO. It limits some because, what if you have a droid that you can ride on? Is it a droid? or a vehicle?

Using a true entity/component system, it can be both easily. Instead of having a is-a droid relation ship, and it would go into the droid list, you have a generic entity, built with a graphics component, physics component, droid component, and weapon component.

Then you have systems that act on these components. ie, the droid system handle entities with the droid component, and it handles the AI and movement (depending if droid component was built with wheels or track, or nothing), as well as attempting to shoot it's weapon.

If you add a vehicle component, then the vehicle system can work on that entity, and allows a player to ride on the droid, and shoot from the back of the droid.

That's the general idea. My dev journal has some articles about it, and there's plenty of other data too.


Hey BeerNutts!

You make a good point. I might be missing the actual point though, but wouldn't just adding a Riding component solve the problem?

The reason why I feel the need to have predefined entities, and also to have tightly coupled components, such as for example the texture and rendering component, or the collision and movement component, like some people here mentioned is because of the two concepts I'm having trouble with, which are the layering of the game that Hodgman and Ryuu talked about, as well as inter component communication.

Also I'm having trouble with how I will differentiate between entities, such as player and AI or vehicle and person.

Things like updating the components also come to mind. Should I make a system for each type of component that updates the components of the same type, in which case should l iterate the types in order? For example iterate over the physics components and update them first, after which I iterate over the rendering components?

What I mean by that, and most of the above is, let's say that there is a vehicle or droid which players can ride. How will I be able to differentiate the players from the other vehicle components such as the collision component? If things are made as generic as you say, and perhaps here I misunderstood you, in that I understood you said that we should make the entities only have a reference to the generic Component class, rather than manually hardcode that a vehicle will have armor, characters, wheels so as to gain maximum flexibility.

If it is hardcoded, then the vehicle will be able to directly manage the characters' updates. What I have in mind is, that when a character is added to a vehicle, the player's control, or that of the AI is stripped, and given to the vehicle, which in turn has a controller, player or AI. I would have addCharacter() method in the vehicle entity or in the Riding component which will do what I just described.

If however, the vehicle only knows generic components, and vehicle is generic in its self, then how will I be able to know that the component being added is a character, and how will I know that the vehicle has a Riding component? Don't get me wrong, I'm not asking how to do those things, but the solution I am imagining in my head entails a lot of boilerplate and messy code, which is essentially a massive Component class to accommodate for every possible action or scenario in the game.

public void addComponent(Component Receiving, Component Attaching)
{
......
	if(Receiving.has(RidingComponent)
	   if(Attaching.is(CharacterComponent)
		   RidingComponent.addComponent(Attaching, type CharacterComponenet);
.........
}

And that's just a small snippet of the method, where other lines would test for rendering, collision, animation, etc...

My opinion is that for small-medium sized games, something akin to say.. the size of Warcraft 2 or Red Alert like game, over-engineering by going completely generic and flexible at the cost of code complexity does not really pay off.

Then again I've never done a component system before.

Edited by Gabriel Grom, 24 August 2012 - 02:39 PM.


#29 nox_pp   Members   -  Reputation: 490

Like
0Likes
Like

Posted 26 August 2012 - 05:52 AM

If however, the vehicle only knows generic components, and vehicle is generic in its self, then how will I be able to know that the component being added is a character, and how will I know that the vehicle has a Riding component? Don't get me wrong, I'm not asking how to do those things, but the solution I am imagining in my head entails a lot of boilerplate and messy code, which is essentially a massive Component class to accommodate for every possible action or scenario in the game.


If components know about their owners, then you can move their dependency tests to be inside of them. Say with a method, Component::Attach(Entity), that tests the entity to which this component is being attached for dependencies and does whatever other magic it wants to do. If components do not know about their owners, you can move that logic to be external from the Component class with a free function, like AddCharacter(Entity), that executes your dependency tests and such. Alternatively, you could go more data driven, and define the relationships between components in some softer format, like ComponentAttacher::DefineConstraint(Component receiving, Component attaching, function constraint), and then make all of your connections through ComponentAttacher.

No matter what though, such logic definitely does not go in the base component.

Between Scylla and Charybdis: First Look <-- The game I'm working on

 

Object-Oriented Programming Sucks <-- The kind of thing I say


#30 Hodgman   Moderators   -  Reputation: 31799

Like
1Likes
Like

Posted 26 August 2012 - 06:28 AM

public void addComponent(Component Receiving, Component Attaching)
{
......
	if(Receiving.has(RidingComponent)
	   if(Attaching.is(CharacterComponent)
		   RidingComponent.addComponent(Attaching, type CharacterComponenet);
.........
}

I personally group "component/entity" designs into two categories -- those that try and perform "magic" linking of components to each other, and those that require the entity creator to manually connect components to each other.
class MyEntity
{
  ComponentA a = new ComponentA();
  ComponentB b = new ComponentB();
  ComponentC c = new ComponentC();
  void Init_1()
  {
	a.InspectParentToPerformMagicLinking( this );//uses reflection to look at my members
	b.InspectParentToPerformMagicLinking( this );//  to automatically make any required connections
	c.InspectParentToPerformMagicLinking( this );//  without my explicit knowledge of how this works
  }
  void Init_2()
  {
	a.ExplictlyLinkYouToC( c );//I, the entity author, know that A needs a C.
	b.ExplicitlyLinkYouToA( a );//  and that B needs an A.
  }
};
IMHO, the first option violates too much of my deeply ingrained engineering intuition to be considered. Explicitly plugging things in seems superior in almost every way to me... Ideally these explicit links, and the entity data-structures themselves should be loaded from data/scripts, but can be hard-coded as above.

Also I'm having trouble with how I will differentiate between entities, such as player and AI or vehicle and person.

If you need to differentiate between them, don't put them all in some generic collection (also don't inherit them from a common base if they don't need it). Am I right in paraphrasing that this is the same as: "I've inherited vastly different classes from a common base, but now I can't use them for different purposes"? If so, it's the same flaw that entity inheritance-trees had.
Put vehicles in a vehicle-list, and players in a player-list, if needed.

we should make the entities only have a reference to the generic Component class

I've seen designs such as this, but IMHO it's a harmful idea. Imagine replacing all of your floats, ints, Arrays, etc, with object... and then having to use casts absolutely everywhere. It defeats the purpose of having a type system.

If it is hardcoded, then the vehicle will be able to directly manage the characters' updates. What I have in mind is, that when a character is added to a vehicle, the player's control, or that of the AI is stripped, and given to the vehicle, which in turn has a controller, player or AI. I would have addCharacter() method in the vehicle entity or in the Riding component which will do what I just described

N.B. as well as "hard-coding" these kinds of specific relationships in your C++/C#/Java etc codebase, it can also be "soft-coded" in your scripting language or data files. IMHO, this is much better than creating an over-engineered framework.

Edited by Hodgman, 26 August 2012 - 06:35 AM.


#31 Midori Ryuu   Members   -  Reputation: 177

Like
0Likes
Like

Posted 10 September 2012 - 11:02 AM

Hey all~ I am back after a somewhat long absence, as I've been busy acclimating into my new job. I wanted to update you guys who took the time to help me with what happened! (And I might hope for a little feedback for how right (or how less wrong) I did things.)

So, after some more search, I fell upon the Apollo entity framework. It is built by the same folks who has made the Artemis entity framework, but is more 'object-oriented' in its thinking. I fiddle around with it in the past couple of weeks, and I must say I really do prefer it a lot over Artemis, which I wasn't planning on using.

This on the other, I loved! I'm not using the platform in its entirety (yet), and I have made some modifications of my own to suit my programming taste (to the builders, etc..)

I have made a small, small demo where I integrated it with LibGDX and Box2D, and I have the code up on Github for those who want to make me feel bad by telling me how bad it is. Posted Image

My architecture is essentially having the Apollo world contain the Box2D world (though I keep a separate reference for the Box2D world for convenience).

I have a Renderable component, along with a collidable component. The collision component depends on the Renderable component, but for the time being only, and only for practicing/experimenting with things, but they should be completely independent, and only separately depend on the Transform component which holds the position.

I have a collision detection listener which doesn't itself act on the bodies, but triggers a flag in the Collidable component and forwards it the needed information to handle the collision (the other body, its type, etc..)

I haven't used the event listeners built into Apollo, so I cant' say anything about that, though I might use it later on. Sorry about that, Gabriel, but I hope I can still answer some of your questions in the code.

I'm using builders like Apollo recommends, though I have modified those to take several parameters. This broke the methods related to builders (which was rather convenient) but it's nothing fatal. (To those who made Apollo, my sincerest apologies for butchering your framework!!)

So yeah, that's pretty much it! Don't judge too harshly.~

I wonder if I should start my own game dev diary.. But I don't want to infect people with bad code. xD

Edited by Midori Ryuu, 10 September 2012 - 11:03 AM.


#32 Mito   Members   -  Reputation: 855

Like
1Likes
Like

Posted 10 September 2012 - 01:08 PM

I wonder if I should start my own game dev diary.. But I don't want to infect people with bad code. xD


well, i think you SHOULD start one. this way you will learn much more. don't be shy. there's no such thing as bad code, only code that has not been polished yet Posted Image




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS