• Create Account

# Demise of the "game entity".

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.

19 replies to this topic

### #1Krohm  Crossbones+   -  Reputation: 2396

Like
0Likes
Like

Posted 12 July 2011 - 01:54 AM

Surfing the net I stumbled on The Game Entity – Part I, A Retrospect. The post itself is quite open but a comment is fairly interesting, let me quote:

By Nicolas MERCIER
There is so much wrong in the concept of "entities" today ... [a] C++ object representing the state of an object in the world That object has an "update" method, that updates this entity and eventually recursively updates all entities/components lower in the "entity tree".

He goes describing the issues associated with that approach involving 1) parallelization, 2) self-documentation, 3) deep inheritance trees 4) constraints (update THAT before THIS).
He proposes, as solution
1,2,4) group updates by object type and update type (DOD like) 3) component model.

Ok, this makes a lot of sense. I was thinking about using interfaces so the inheritance tree would have been low but as interfaces come with no implementations I guess it's just better to switch to component-based anyway (there would have been a code of redundant code). And I was already going to pool those objects by type.
However, there are still some thinks I cannot quite figure out.

a) I don't see any way to avoid using Update, nor propagation.
This is mostly referring to script-driven entities. The current "core entities" as I call them, are updated with a proper call and do not propagate in general, albeit some modify the values of certain other entities (in a way similar to multithreading or "volatile" values) because of the way they were implemented. But for script entities, I see no way to avoid this, besides forbidding. Maybe I can intercept all the calls and short-circuit them so each entity could be updated only once per frame, but I'm not sure.

b) I'm not quite sure what this "update type" thing even means.
Again, put in scripts. Can a scripted object register an update type? How? How they are pooled? Where? When to refresh? What?

c) Constraints.
The way I was going to deal with them was... uhm, fairly ugly I guess. It revolved around an object database driven by strings, a getNamedObject call and casting like crazy (or build the objects using an helper script to connect them together). The script execution model was simply "no order guaranteed" so checking a condition could take a few frames. I don't think I'm going to have this problem anyway in the near future.

By Nicolas MERCIER
to sum up, can we get away from that entity tree concept NOW? =)

Which I guess it's ok as I never got the idea that entities should have been put in trees (I guess it's similar to my scene graph misunderstanding) but there's another thing which I cannot quite understand.

It comes from "Hodgman" and since it seems likely he's the same "Hodgman" here I'd like to ask to elaborate on:

By Brook Hodgman
...the very notion of a 'game entity' itself is fading as well. Having a single way to describe anything ("everything is an entity!") seems like a "well, we've always done it that way" design choice, instead of an actual requirement.

I understand the sentiment behind the second statement as I'm having the very same problem (is a game entity collidable? visualized? has logic? is live/nonstatic?). So the whole point here is to have a family of entities instead to compose?

Since I'm going to tear apart the "entity" system yet another time, I suppose it would be a good time to think about "doing it right", so I'd like to hear anything that might come useful.

### #2Hodgman  Moderators   -  Reputation: 19247

Like
3Likes
Like

Posted 12 July 2011 - 03:47 AM

I understand the sentiment behind the second statement as I'm having the very same problem (is a game entity collidable? visualized? has logic? is live/nonstatic?). So the whole point here is to have a family of entities instead to compose?

Yes. Imagine if all the standard-library objects had a common base type -- i.e. std::string, std::iostream and std::vector were all "entities"...
Why? Why would you do such a thing! They're completely different types that can be composed to make more complex types. There's no requirement for having an Entity* which might point to either a string or an iostream.

Likewise, if I've got some objects called "game rule", "animation controller" and "AI path-finder", there's absolutely no need to try and force them all into some kind of common interface. They're all completely different types that can be composed to make more complex types. I don't need a base-class or an interface or whatever, here.

a) I don't see any way to avoid using Update, nor propagation.

Firstly, the "virtual void Update" pattern is absolutely terrible for performance. You go through completely unknown objects one by one, executing unpredictable code and accessing unpredictable data for each one. You might update an AI character, then a projectile, then the weather, then another projectile, etc...

Imagine if other software worked like this! A bank that randomly walked through it's accounts checking each one if they've got new transactions... A calculator that checks if '7' was pressed, then updates part of the LCD, then checks if a square-root needs to be computed, then checks if '8' was pressed, etc... That is not a performant design.

Secondly, not everything needs to be "updated" every frame. E.g. a game-rule entity might only need to execute some code whenever a particular event happens -- this code can be triggered by that event, instead of polling for the event each frame, just because we like Update functions.

A breakable object might only need to execute some code when it's bumped into -- instead of checking for collisions every frame in it's Update function, the physics sub-system can instead produce an array of collision events during it's processing, then another sub-system can iterate over these results and calling the "Breakable::Bump" function if required. No collisions generated means no updates of breakables (as opposed to checking each one each frame).

b) I'm not quite sure what this "update type" thing even means.

This often means grouping by type, which addresses some of the performance problems of "virtual void Entity::Update". Instead of the update method being unpredictable, you group your objects by type and just have "void T::Update". You iterate through all your Foo objects, calling Foo::Update, then your Bar objects, calling Bar::Update, etc... Also, instead of having "T::Update", you can instead write "TSystem::UpdateMany", as usually you can write much better code when you're performing an operation on a large number of inputs/outputs, instead of writing code that only operates on a single item at a time (and then running it many, many times).

c) Constraints.

Once your code is split up into a directed graph of jobs that need to be done (e.g. "simulate physics", "break bumped breakables", etc...) you can plot the data-dependencies between the jobs (e.g. "breaking bumped breakables" consumes the collision list, which is produced by "simulate physics") and then either manually or automatically create a dependency graph for your jobs, and execute them in the appropriate order.

### #3Sappharos  Members   -  Reputation: 140

Like
0Likes
Like

Posted 12 July 2011 - 05:27 AM

Imagine if all the standard-library objects had a common base type -- i.e. std::string, std::iostream and std::vector were all "entities"...
Why? Why would you do such a thing! They're completely different types that can be composed to make more complex types. There's no requirement for having an Entity* which might point to either a string or an iostream.

I don't know much so I may be missing the point of the conversation here, but surely the purpose of an entity object is to serve as a base class so that all objects in the game can be held in the same container? Otherwise you have a list of trees, a list of monsters, a list of players, a list of particle systems etc., all with similar interfaces, but which need to be accessed seperately...

### #4Hodgman  Moderators   -  Reputation: 19247

Like
0Likes
Like

Posted 12 July 2011 - 05:51 AM

surely the purpose of an entity object is to serve as a base class so that all objects in the game can be held in the same container? Otherwise you have a list of trees, a list of monsters, a list of players, a list of particle systems etc., all with similar interfaces, but which need to be accessed seperately...

Yes, that is the purpose, but it's an anti-pattern.
Does a tree really have the same interface as a monster? Do you really have a requirement to access both player data and particle-system data at the same time? Surely you want your particle-systems to be accessed separately than players? Can a player be safely substituted by a tree and have all player-related algorithms still function? This is just a horrible abuse of object oriented design done out of laziness, and as mentioned earlier, it's a great way to absolutely destroy the performance of your game, while not actually satisfying any real requirements.

### #5Sappharos  Members   -  Reputation: 140

Like
0Likes
Like

Posted 12 July 2011 - 06:22 AM

Yes, that is the purpose, but it's an anti-pattern.
Does a tree really have the same interface as a monster? Do you really have a requirement to access both player data and particle-system data at the same time?

Yes, sometimes. Admittedly this system can get awkward, but without a common interface, what would prevent code like this from occurring?:

for (std::list<Tree>::iterator it = trees.begin(); it != trees.end(); ++it)
it->UpdateAnimation(dt);
for (std::list<Monster>::iterator it = monsters.begin(); it != monsters.end(); ++it)
it->UpdateAnimation(dt);
for (std::list<Player>::iterator it = players.begin(); it != players.end(); ++it)
it->UpdateAnimation(dt);
for (std::list<ParticleSystem>::iterator it = particleSystems.begin(); it != particleSystems.end(); ++it)
it->UpdateAnimation(dt);


Sure, everything would be stored in some form of scene graph rather than a list, but you get the idea. As soon as you add a new type of object you have to add special-case lines all over the code for purposes like this. I'm not arguing, just trying to understand.

### #6PrestoChung  Members   -  Reputation: 163

Like
0Likes
Like

Posted 12 July 2011 - 06:27 AM

I don't know if what MERCIER describes with update() is just a general example? I suppose if you didn't care about cache coherency this is how you would do it? It really seems wrong-headed to me and ignores data-oriented design principles.

### #7Hodgman  Moderators   -  Reputation: 19247

Like
2Likes
Like

Posted 12 July 2011 - 06:34 AM

Admittedly this system can get awkward, but without a common interface, what would prevent code like this from occurring? As soon as you add a new type of object you have to add special-case lines all over the code for purposes like this.

The same UpdateAnimation method shouldn't belong to trees, monsters, players and particle systems (separation of concerns). If that functionality is re-used by many different classes, then it should be packaged up into it's own class.
For example, if a monster needed a dynamically-sized vector, you don't go adding a push_back method to the monster -- you add a std::vector as a member variable of monster, and use it's push_back method.
Likewise, if both players and monsters need an "animation", then you add an animation as a member variable of player and monster.

All the animation objects for a scene can be kept track of seperately of the objects that own them (e.g. following the law of demeter, you should be able to update a player/monster's animation without even #includeing player.h or monster.h). If you add a new "Spaceship" class that also needs an animation, there's no need to give it an UpdateAnimation function, or to write a new loop like you've done. You just give it an animation member object, which is kept track of (and updated by) the animation-manager.

e.g.
class Player {
Animation* anim;
Player( AnimManager& am ) : anim( am.Create() ) {}
};
...
void AnimManager::UpdateAnimations()
{
for (std::vector<Animation>::iterator it = animations.begin(); it != animations.end(); ++it)
it->UpdateAnimation();
}
You don't need a common interface at all -- all you need to do is pull that duplicated logic out into it's own class, following the single responsibility principle.

Sure, everything would be stored in some form of scene graph rather than a list...

Once you've pulled all the animation data out into it's own isolated class, there's no reason to go putting it into some kind of 'scene graph'!! Just put it in an array, and put spatial objects in the spatial graph!

Does a tree really have the same interface as a monster? Do you really have a requirement to access both player data and particle-system data at the same time?

Yes, sometimes.

That was a rhetorical question. If you break your classes up properly so they're not overflowing with different responsibilities, the answer is 'no'.
There might be some member variable of a player, which is the same type as a member variable in a particle-system (e.g. maybe they both have world-transformations) -- but this is not a part of the player and particle-system interfaces, this is the interface of one of the objects they've been composed out of.

So if you had an algorithm that operated on world-transformations, then as is, yes, you might have a need to iterate over both players and particle systems.

If you instead break that common interface out into it's own class (i.e. the world-transform class), then now your algorithm can iterate over a collection of world-transforms without caring if they belong to a player or a particle-system, without inheritance and without interfaces... and with much better performance...

### #8Antheus  Members   -  Reputation: 2381

Like
3Likes
Like

Posted 12 July 2011 - 07:27 AM

C++...

A thought experiment. Let's make "an entity" in JavaScript.
function Car(...) {
this.speed = 10;
this.position = [0,0,100];
}

var entity = new Car();
all_entities.push(entity);


Given entity, how do we know it's a car, that it's updatable and that it has speed? How to update the position? We don't have inheritance, interfaces, introspection (well), .... We have blobs.

But what we need to do is update all cars or perhaps update all entities with certain attribute or all with position. We lack a facility that would allow us to query such things. The simplest way is to do it manually:
var with_speed = [];
var with_position = [];

function Car(...) {
this.speed = 10;
this.position = [0,0,100];
with_speed.push(this);
with_position.push(this);
}
10 lines of code. And I think it might even work.

How do we update? JS lacks set intersection, but let's pretend there is. To update "physics", one might do something like this:
var s_and_p = set_intersect(with_speed, with_position);
for (e in s_and_p) {
e.position.x += e.speed;
}
Voila...

function Kettle {
this.position = [100, 100, -1];
with_position.push(this);
}
Won't move, doesn't have speed.

And then... well, that is it. Really, this is all there is to the magic of entities. No joke. It's just that C++ is horribly complicated when attempting to explain something absurdly trivial. Above, there is nothing saying our entities cannot be JSON objects. Or copy-pasted. Or renamed. Or changed during run-time (as long as registeration is respected).

We have sets of data, intersections of which form our "entities".

And system described above would likely work just find for reasonable number of entities and properties. C++ implementation of above design just allows some further optimizations. But at very core, it's just set algebra, so learning SQL is a good idea. Not for syntax, but for concepts.

The "radical departure from OO" is quite trivial. We have plain state that is dumb. Then we have smart methods which know about *all state* and make the best of it. In OO, each instance knows about itself and is oblivious to everything else. Here, the caller specifies what they are interested in and what they need, select that subset and manipulate it (see above, we care about speed and position, nothing else, even though we could ask for more).

### #9PrestoChung  Members   -  Reputation: 163

Like
0Likes
Like

Posted 12 July 2011 - 08:00 AM

That's a very intelligible example Antheus though I don't know Java.
The only thing though, it seems your with_speed and with_position are going to have pointers to all different places in memory, not a contiguous allocation? Many cache misses?

### #10Antheus  Members   -  Reputation: 2381

Like
2Likes
Like

Posted 12 July 2011 - 08:10 AM

That's a very intelligible example Antheus though I don't know Java.

Well, good news then. It's JavaScript.

The only thing though, it seems your with_speed and with_position are going to have pointers to all different places in memory, not a contiguous allocation? Many cache misses?

Oh forget about that. Really. You're not working for DICE or Intel, so just ignore that for now. And it's JavaScript, so it's 10,000 times slower than C++ code could be. Yet I'm willing to bet it would work just find for reasonable number of entities.

Understand the design and the idea behind it first, especially why and how it departs from typical OO.

And it's JavaScript. Write a few more classes, then run it in browser. No IDE or anything needed, see how many entities you can get before things become a problem. 3 or 4 years ago, before all these fancy browsers I managed to replicated Dune 2 in browser. It was just barely doable for 4096 tile map and 250 units. Today it would probably fly at 60FPS. More if using Canvas or WebGL or such.

The whole "entity" doesn't even have a name, it's just how everyone in dynamic languages programs. This is why it's important to notice the "10 lines only" argument.

The original question was about design first and it didn't mention any performance mentrics, so it's not useful part of discussion. However, if you want to run 1000 entities with 20,000 properties at 60Hz on a 3GHz CPU, then one simply writes a benchmark and tunes until that is achieved. If memory optimization helps with that, fine, otherwise it's not important.

### #11frob  Moderators   -  Reputation: 11522

Like
2Likes
Like

Posted 12 July 2011 - 12:15 PM

It will be interesting to see where he takes his articles.

The concept of a game entity is such a vague and nebulous term it could mean many different things. It would be foolish in the extreme to have many hundred million pieces of data placed into a common pool that is constantly polled for no reason. Nobody does that in the real world, nor would they.

Many systems do have "entities" which are composed of various parts. Unity3D does this very nicely, and it is similar to examples I have seen in the regular work environment. Again, they aren't blindly running all processing work on every piece of data, but intelligently selecting what to run and then those items in turn pruning down to only processing the data that actually needs it.

It is common to have a set of management classes which are always updated, and then they coordinate the work within that subsystem.

For example, you have a particle system, and it determines what work needs to take place within that system. You don't have every particle mixed in with AI processing and with network updates, but a single system that runs it's portion of work only as needed. Similarly you have a networking system which is always updated, and determines what work needs to take place, if any. Same for the AI system, perhaps updating only a few of its AI actors as needed; the system is always updated, but the individual AI actors do not necessarily need to be polled every update.

Even with a single large tree, that is still something that can be made trivially parallel by maintaining an 'old' and 'new' value (often with three rather than two), which large systems will likely do anyway since since rendering and updating are typically decoupled. Rendering is an interpolation between two states. With subsystems instead of a giant tree the parallelization concerns are also unfounded, since each of those subsystems can be updated in parallel, and often the individual parts within them can be updated in parallel.

Hopefully the rest of his articles are carefully considered.
Check out my personal indie blog at bryanwagstaff.com.

### #12Krohm  Crossbones+   -  Reputation: 2396

Like
0Likes
Like

Posted 13 July 2011 - 02:32 AM

Thank you very much for your replies.
Perhaps I need to make clear that scripts are involved in some parts of the discussion. That is, I am not, in general, talking about code that gets executed natively that the application knows about.

To be completely honest, I don't think I am going to drop my generic Object class. While I understand the point in not allowing a particle system to stay together with AI controllers, it seems to deliver some added value to me. For example, I like very much Object::finalize and Object::hashCode. The 'game entity' would have been something definitely higher-level. I think having a common base class is not really bad by itself. Sure abusing it is another business.

What I can see from the examples is that there's a recurrent theme about behavior you know about classes you know. Let's call those "core" objects/classes/interfaces. Pooling in the right place is relatively easy for those objects, sure we can update it with no trouble.
The problem arises from the others, let's call them "user entities". They are, W.R.T. the core class definition, different/unknown in behavior and need to execute code which is likely to be different, the component model cleans up a lot here but in general to make the system flexible, I'll need to have some kind of listeners to events.
For example, when CD code determines two thingies collided, it will issue a Bump call, from now on, I have no guarantee what's going on. Sure, the call is now Bump, and not Update, and called from a more specific context, and thus hopefully not abused. Yet it likely involves updating something and this may have the same issues associated with Update, albeit on a smaller scale, or perhaps not? Am I missing something here? Perhaps I am thinking too generic?

When I wrote about constraints, I meant inter-object constraints. To satisfy those, I was planning to let the script provide the required "sync" code, or perhaps I should allow them to register "update groups"? I wonder if I need to keep track of update status on a per-object, per-tick basis.
After all, if the script can define a function, it can probably call it as well.

Inter-task constraints don't worry me much. Ok, they do but I'm positive I'll figure them somehow.

I understand the point about composition and I'm glad to read that my approach about a family of well-known sub-entities instead of a single generic entity was correct. I personally don't think that involves a big departure from OO (we're basically taking advantage from the implementation provided by a specific derived class exposing a certain interface in a way or the other, some kind of manual devirtualization).
Still an update call, perhaps event-based, needs to be here. Similarly, some kind of propagation must go on albeit hopefully for a reason. Ok, I'll smartly update the classes I know about but I had the impression the original concept involved sub-types in the same pool... perhaps I am taking the linked post too seriously, I'll surely want to still think at this for a while.

### #13frob  Moderators   -  Reputation: 11522

Like
0Likes
Like

Posted 13 July 2011 - 11:10 AM

What I can see from the examples is that there's a recurrent theme about behavior you know about classes you know. Let's call those "core" objects/classes/interfaces. Pooling in the right place is relatively easy for those objects, sure we can update it with no trouble.
The problem arises from the others, let's call them "user entities". They are, W.R.T. the core class definition, different/unknown in behavior and need to execute code which is likely to be different, the component model cleans up a lot here but in general to make the system flexible, I'll need to have some kind of listeners to events.
For example, when CD code determines two thingies collided, it will issue a Bump call, from now on, I have no guarantee what's going on. Sure, the call is now Bump, and not Update, and called from a more specific context, and thus hopefully not abused. Yet it likely involves updating something and this may have the same issues associated with Update, albeit on a smaller scale, or perhaps not? Am I missing something here? Perhaps I am thinking too generic?
When I wrote about constraints, I meant inter-object constraints. To satisfy those, I was planning to let the script provide the required "sync" code, or perhaps I should allow them to register "update groups"? I wonder if I need to keep track of update status on a per-object, per-tick basis.
After all, if the script can define a function, it can probably call it as well.

Go look at Unity3D. It does a very good job of this, and mirrors the same style I've seen in several professional game engines I've worked with.

You should never ever be in a position where "I have no guarantee what's going on". The person who wrote that system should absolutely know what's going on. Even on a huge project with hundreds of developers, you personally may not know what every system does, but when you get the right people from the right teams together you can know exactly what everything is doing.

Yes, it looks like you are being too generic. Game objects are put together through composition (even when they come through scripts) and properly designed composition can intelligently process events and prune them down. Each layer can select its subordinates that need the message or prune it out, relatively few items actually get processed during an update. If a function needs to be called it can register to be called, but that is something to avoid for the reasons mentioned above: Don't run code if you don't have to.

The constraints you mentioned are generally non-issues with that sort of system when it is designed well. Most notably they have decoupled rendering and processing: they don't update the 'live' variables, they are given a copy of the previous frame's values and the end result becomes the next frame's values. This can be made trivially parallel through proper design and composition, with each layer generating new tasks that are independent of the others. Tasks can be run in parallel or serial order with a proper design. Ordering of items such that object A must be updated before object B is an obvious design flaw; if you require additional ordering something is wrong. (Often you have a pre-update, update, and post-update cycle; similarly there is a pre-render, render, and post-render cycle. More than that indicates too much interdependence.)
Check out my personal indie blog at bryanwagstaff.com.

### #14Krohm  Crossbones+   -  Reputation: 2396

Like
0Likes
Like

Posted 15 July 2011 - 01:04 AM

To be completely honest, I was thinking about going for direct variable access for the time being as I do not plan to have any support for parallel processing mid-term.

### #15Krohm  Crossbones+   -  Reputation: 2396

Like
0Likes
Like

Posted 15 July 2011 - 12:31 PM

I've fiddled a bit with Unity today and while I still don't understand quite well how the system works in general, I think I am having a sufficient understanding of how the scripting is supposed to work. This is my biggest concern as I really don't want to have anything system-specific in source.

Everything in Unity is an Object. It appears that object creation is tracked and drives appropriate behavior, very much like I'm doing for my "core classes". Their Object is therefore much higher level than mine to start with. Interestingly, each Object has a name, some editor-oriented data and the ability to be kept on level load. This is something that has kept me thinking for a while right now and I'll have to consider this simple solution as it really makes sense.

From there, the next step is the GameObject. This is where things start to be really different from the approach I was thinking about: the GameObject appears to contain an handle (possibly null) for everything I might want to put into it. This in my opinion somewhat clashes with what we have discussed so far, to use a family of basic components instead of a "game entity", by defining a GameObject that way, I cannot reasonably tell how this will be used. Nonetheless, routines in GameObject might act differently according to what references are valid or not. is a "Base class for everything attached to GameObjects".
I wonder why they did it that way.
By sure, I don't want to have a thing like that, with different management depending on the inner fields.
I was thinking about working more with composition, independently resolving events for each sub-object, then dispatching callbacks to those base objects, which would then forward them to the containing objects by using Java-like listeners.
I can see some advantages by considering the aggregated information emerging from component interactions, but I cannot tell if this translates in real world benefit without more experimentation.

Behaviour is the same as component but can be disable ("Enabled Behaviours are Updated, disabled Behaviours are not." What about events?). From there, they derive MonoBehaviour, which defines a boatload of event listener calls which I'll have to consider. But, we also get Update, FixedUpdate and LateUpdate. Whoops. I was completely sold on that "no generic update/tick call" right now.

Summing up, I would say I don't see a "silver bullet" solution. My plan is therefore to just try an iteration and see what happens, hopefully just getting the rid of interface-inheritance should save me some problems although listeners would still be needed to connect the well-known component events to the object managing it. I'll need to consider the details.

### #16Antheus  Members   -  Reputation: 2381

Like
2Likes
Like

Posted 17 July 2011 - 01:46 PM

Summing up, I would say I don't see a "silver bullet" solution. My plan is therefore to just try an iteration and see what happens, hopefully just getting the rid of interface-inheritance should save me some problems although listeners would still be needed to connect the well-known component events to the object managing it. I'll need to consider the details.

The missing piece is that you're still unable to differentiate between language-specific parts and the design.

C# simply requires certain constructs, such as inheritance from common class. The "many callbacks in one class" is also just because of language, it could be done differently.

Behaviour is the same as component but can be disable ("Enabled Behaviours are Updated, disabled Behaviours are not." What about events?). From there, they derive MonoBehaviour, which defines a boatload of event listener calls which I'll have to consider. But, we also get Update, FixedUpdate and LateUpdate. Whoops. I was completely sold on that "no generic update/tick call" right now.

They are stages or phases. They work something like this:
- ...
- update AI (for anything with AI component)
- update rigid body physics (for anything with rigid body)
- fixup (sometimes a constraint needs to be set after previous two phases)
- ...
- ...
The fact they derive from MonoBehavior or anything similar is, again, because of language.

Design benefit of the above is, if you have a Pot of Petunias that was intended as decoration, you can, at any point, just add AI component and it will have a deep conversation with a whale. With inheritance, you'd be stuck with StaticObject<-PotOfPetunias. To make it AI, you'd suddenly have to change it to inherit from Object<-Actor<-NPC<-PotOfPetunias. But oops, now it would automatically become RigidBody/QuestGiver/InventoryHolder/CombatTarget, because that is what an NPC is as well.

Component is a "Base class for everything attached to GameObjects".

It's irrelevant tag required by language. Everything is a component, so it doesn't even need to be mentioned.

Type identity of a "Car" is just a bag of components, it is not "Car derives from Component derives from GameObject derives from Object". Car is a car with several properties. The properties define what "type" it is. If it has rigid body component, then it's part of physical world and can collide, crash, jump. If not, then it it's just decoration.

### #17Mike2343  Members   -  Reputation: 468

Like
1Likes
Like

Posted 17 July 2011 - 02:32 PM

Something you may wish to look into is Component based entities/systems. Looking at my post history (I've not checked it in a year so I may be wrong) you can find several threads on this site that are great discussions on the subject.

Myself, I use entities as a compilation of components. Each entity is basically an array of components with functions to add/remove them easily. But it could be just as easily a struct © and an array, or a std::map<std::string, std::vector<ComponentBase*>> (Note: I use smart pointers but for ease of reading I will just use raw pointers here, and in this case its a weak pointer).

Then each Manager class (using manager here since its a common term, I am personally not a fan of it and in my code use the term System, but it's really just semantics) has a smart pointer array of all its appropriate components. Then each manager makes intelligent decisions on which component to update, etc.

We've been using this technique for a few years now and it allows us to rapidly prototype new projects in just hours verses days/weeks it used to take.

### #18Krohm  Crossbones+   -  Reputation: 2396

Like
0Likes
Like

Posted 18 July 2011 - 12:41 AM

The missing piece is that you're still unable to differentiate between language-specific parts and the design.

Admittedly, I am not. What I don't get is the following: couldn't they just do this?

// particularly lazy on public/private/protected, not being formal here
class Object { // Everything inherits from Object. Like in Java. Not really defined in code, provided by library.
String name;
// note this is potentially empty
};

// Base class for anything going through the physics system. Does nothing by itself.
// Again, this is provided by the library. Automatic "extends Object"
class Collidable {
class CollisionListener {
virtual void OnTouch(const Collidable &other) = 0;
};
CollisionListener *notify;
/* etc */
};

/* "Core class" with special management. Everything inheriting from there will be pooled by the physics management system
and updated accordingly. Inheriting from this class is highly discouraged but possible, as I don't have any way to prevent this.
This inherits from Collidable mostly because of syntactic sugar than anything else. */
class RigidBody extends Collidable { /* center of mass, transform... */ };

class SomeGameObject implements Collidable::CollisionListener { // auto inheritance from Object, multiple interface-only inheritance
RigidBody inner;
SomeGameObject() {    inner.notify = this;    }
void OnTouch(const Collidable &other) { /* not really relevant */ }
};

This way, I don't need to say much on inheritance (used for listeners, but not for object composition). Aggregating the behaviors happens by overriding and pooling the appropriate event calls. Each class has the chance to aggregate the objects as they want and I don't need any container struct. This way I never do this:
void MangleGameObject(Object &object) {
if(object.inventory) MangleInventory(object.inventory);
if(object.collidable) MangleCollidable(object.collidable);
if(object.visualization) MangleVis(object.visualization);
}

In general I can see this is probably going to be more manageable due to its centralized approach and allow higher tuning. I still cannot quite get in the line of thinking.
For example, why couldn't them just pull out the component they need to work on using for example GetComponent (which seems to do some reflective magic)?
Because that's what we are saying: a GameObject might have a transform... or perhaps not. So why to put a transform variable there explicitly in the first place?
I suppose I am not well aware of the language limitations you're referring to. Why not to just let derived objects do whatever they want, declare whatever they want and then using listeners? Or inspeciton/reflection? You wrote exactly this: it could have been done differently. So, is there a reason to do it this way?

I also require inheritance for a common class because this is how the system pools the "core classes" up to now. If I instance a DigitalButtonBinding("w"), the system will silently create the special behavior associated to keyboard mangling. If some object wants to mangle keyboard it just has to new it and listen/check its status. I don't need to put an handle in some base class to let this happen.

Thank you very much for the petunias example. It's good to have a "real" example to think at. I think there would be no problem using the above method, it seems to retain the benefits of component model. Sure it would be slightly more verbose because of the need to define ad-hoc listeners. At this point I cannot estimate if this is a problem for me.

They are stages or phases....The fact they derive from MonoBehavior or anything similar is, again, because of language.

Ok, so that would be the "Update by type" approach referred above. So what happens is that the objects will "evolve" naturally. Ok, but those Update calls are here for something, to provide the logic that is non-core.
The point I was trying to make here is that: Update exists. Why? Because events are dispatched in nontrivial order. Neither those calls. But they hold an interesting property: they are called before or after a certain phase. And they do what? They "propagate" the update somehow sure it's not called Update but this takes me to the starting line (a) I don't see any way to avoid using Update, nor propagation.

Myself, I use entities as a compilation of components. Each entity is basically an array of components with functions to add/remove them easily.
...
Then each Manager class (using manager here since its a common term, I am personally not a fan of it and in my code use the term System, but it's really just semantics) has a smart pointer array of all its appropriate components. Then each manager makes intelligent decisions on which component to update, etc.

Thank you, this is exactly the point. If we put every component in an array of ComponentBase* nobody has knowledge of who will contain what until runtime. Which means I don't need to say "those objects might hold a camera... or perhaps not". I mean, it's a question of style here. If we can retain all the benefits of component models by ... not explicitly naming components at all, why to worry about each of them explicitly in the first place? Just let the user to declare the classes he wants, slapping in the components he wants and we are done.

But unity is good stuff and if they didn't do that way, I'd say there's a reason to. Which is the language-specific issue we are talking about? I don't know.

Is this correct?

### #19JarkkoL  Members   -  Reputation: 153

Like
0Likes
Like

Posted 18 July 2011 - 07:37 AM

I have taken a bit similar approach as Mike. My entity class is lightweight and has 5 pointers to different types of components: graphics, audio, physics, animation & controller (ai/script), i.e. one component for each type of sub-engine. I didn't want to generalize these components though to keep the design simple & efficient and to have custom class interface for each type of component. It's up to each sub-engine how they deal with these components as well, e.g. physics engine can also contain an internal list of simulated entities and efficiently update only physics components or entity properties as required by the simulation. The entity class is needed for composing different entities in a level from the components, so for example when an entity is deleted, it deletes its components, which in turn may inform the associated sub-engines about the deletion. Or in editor you can tweak properties of a component that's assigned to the entity.

Cheers, Jarkko

### #20ddn3  Members   -  Reputation: 1005

Like
0Likes
Like

Posted 20 July 2011 - 01:06 PM

Logical game entities don't live in low level game code anymore, usually they've been moved over into some scripting framework. The entities inside the engine themselves are not much more than collections of interfaces into owned subsystems objects, centralized to simplify dispatching of events or methods. The more advance systems I've seen implement something like the COM protocol where they bind to objects interfaces, usually to get around the slow event dispatch problem. As for the update function, in modern game architectures the subsystems are responsible for updating their respective owned objects not the entry itself. This allows for better cache coherence and parallazation.

The game entity itself is still very pertinent but lives mostly inside its own special built framework, managed by a scripting core. All this of course is just generalization, plenty of exceptions and there is nothing stopping you from putting your game entity inside straight C++..

-ddn

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