entity systems games design massively multiplayer programming

Entity System 1: Java/Android

Please note: the design described in this blog post has been much improved and updated and put up – with full source – on

On the wiki linked above, there is now a wholly new Entity System design, based on this one, but much improved. There’s a brief post about it here, recommended instead of this ES design:

I’ve been writing about Entity Systems sporadically for the last few years. Recently, I finally had the time and the excuse to build one of my own (i.e. not owned by an employer). If you haven’t read the main series of ES posts, you should do that first. There are many things in the world masquerading under the Entity/Component banner – and even more that just coincidentally share the name, but describe something else completely. It’s worth understanding which variant I’m talking about before you read about what I’ve done :).

Why build an Entity System?

At a generic level, this is covered in the other posts. But it’s taken years for me to have the time/inclination to write a new one from scratch outside of my day-job. What happened?

  1. I left my iPhone in America, and it took 2 months to get it back
  2. Google gave me a free Nexus One, in the hope I’d write something for it (ha! Their cunning plan worked…)
  3. The Android marketplace is such a miserable morasss of third-rate crap that eventually I was compelled to write my own Android game … just so that I would have something to play (there are very few games on the Android store that are even worth the time it takes to download them)

I’ve been making games for a long time. I know how much effort will go into it, how much time, and how much slog there is before it becomes worth it. Writing a game on your own often means putting in 90% of the effort to get 10% of the reward.

Enter … the Entity System. If I were to pick a game-design that mostly used data-driven game features, I could implement it around an ES, and massively reduce the amount of planning needed to get the game running. I could maybe have a working game after a mere 20% of the effort. Hmm…

Building the ES for Android

Android runs something that’s *almost* Java (although more on that later – Android’s version of Java is very slow at some of the core libraries, and it really shouldn’t be). Technically, Android supports all the core data structures from Java (Collections), and the templating system (Generics).

If I were writing an ES in C++, I’d do it using templates without pausing to think; I wondered how well the same might work with Generics, given that Generics is *not* a complete templating system, although it provides quite a lot.

Getting started: early ES decisions

How to design/implement this thing? Well, we know one thing for sure:

Entities have a single name/label/global-ID. Entities MUST NOT contain ANY DATA: these are NOT objects, this is NOT OOP!

There you go, the Entity class wrote itself:
public class Entity
public int id;
This immediately raised some concerns for me, being the seasoned coder I am (ha!). How the heck was I going to write any code that dealt with these things if I didn’t have references to them? Obviously, sometimes you do have references, but other times you expect to follow refs from within the objects you have, to get to the objects you need. That wouldn’t be happening here, since there are no inter-object refs.

public class BaseEntitySystem implements EntitySystem
/** I’m too lazy to write a "safe" method to get a globally-unique ID; for now,
I just return 1 the first time I’m called, 2 the second time, etc… */
protected int getNextAvailableID();

/** Whenever you create an entity, you’d better invoke this method too!*/
public void registerEntity( Entity e );

/** The method to solve my fears above */
public Entity getEntity( int id )

* Merely removes the entity from the store. It becomes a GC candidate
* almost immediately (since all other refs are transient)
public void killEntity( Entity e )

…but, again, being a Veteran coder, the survivor of many painful battles on the field of programming … I didn’t trust myself in the slightest to “always remember” to invoke registerEntity. Quick trick: give the Entity class a static reference to a default EntitySystem, and have each EntitySystem check if that reference is null when starting; if so, set itself as the “default”.

public class Entity

public static EntitySystem defaultEntitySystem;

public Entity( int i )
id = i;

if( defaultEntitySystem == null )
throw new IllegalArgumentException( "There is no global EntitySystem; create a new EntitySystem before creating Entity’s" );

defaultEntitySystem.registerEntity( this );


public class BaseEntitySystem implements EntitySystem

public BaseEntitySystem()
if( Entity.defaultEntitySystem == null )
slog( "Setting myself as default entity system (Entity.default… is currently null) self = " + this );
Entity.defaultEntitySystem = this;


W00t! I can create Entity’s, and I can find them later on. Awesome. What about those Components, then?

Getting started: Components in Java

I’ve done ES in C++ before, with real templates, so I wasn’t really thinking at this point … I just ran with what seemed natural based on prior experience. The thought process (had there been one) would have been something like this:

  1. This is java, I use Eclipse: I absolutely *must* have the IDE know what data/fields exist in each component so that Content-Assist/Autocomplete works 100%. Otherwise I will gouge my own eyes out having to remember, and doubly so each time the app compiles but dies at runtime because of a typo in a field-name.
    • Requirement: each unique Component must be defined as a java Class, with each of the fields being a public member of that class
    • Requirement: to access a Component of a given Entity, you must invoke a method which returns something that is typed (as in language typing) to the correct Class

I made a Component class, and had all Components extend it; there is a particular reason for this, but it doesn’t matter right now – essentially, it lets you define shared behaviour for all Component subclasses, and just saves you time on typing.

My first real Component:

(NB: I defined this *inside* another class, because I couldn’t be bothered having N source files for the (large number of) N Components I was bound to create. Hence the “static”):
public class MyEntitySystemExperiment

static class Position extends Component
float x, y;
int width, height;
float rotationDegrees;

@Override public String toString()
return "("+super.toString()+" @ ("+x+","+y+") * rot."+rotationDegrees+")";


Great. I have a component. Now comes the largest single piece of work in the entire implementation of the ES: writing the methods to:

  1. Add a component to an Entity
  2. Fetch a component from an Entity
  3. Remove a component from an Entity

Fetching a Component from an Entity

This is the win/lose point: if this works well, our ES will be nice and easy to use. The other two methods (add and remove) are simply twiddling bits of data. This one is the challenge: can you make it *easy* to write code that uses the ES, and for that code to be clearly *understandable*?

public class EntitySystemSimple extends BaseEntitySystem
HashMap<Class, HashMap<Entity, ? extends Component>> componentStores;

public <T> T getComponent( Entity e, Class<T> exampleClass )
HashMap<Entity, ? extends Component> store = componentStores.get( exampleClass );

T result = (T) store.get( e );
if( result == null )
throw new IllegalArgumentException( "GET FAIL: "+e+" does not
possess Component of class\n missing: "+exampleClass );

return result;


Boom! It works.

Let’s just stop briefly and I’ll explain why. Reading Java generics code from cold (just like reading C++ templates) often takes a lot of hard thinking.

Looking at the “result” of this method, we want it to be (enforced by the compiler):

  1. “an instance of a class that extends Component”
  2. “an instance of the particular class/Component that we requested – not just any old subclass”

/** based on comments at end of blog post, think this is correct,
but not checked */
public <T extends Component> T getComponent( Entity e, Class<T> exampleClass )

It causes you to write application code that looks something like this:

public void doSomethingWithAnEntity( int globalId )
// remember, we NEVER hold refs to Entity objects for long
Entity e = entitySystem.get( globalId );

Position position = entitySystem.getComponent( e, Position.class );
position.x = 5;

…and what’s important is that the “type” of the “Position position = …” line is already hard-typed to “Position”. So, the content-assist will *auto-complete* anything put after a dot on the end of that line, e.g.:

entitySystem.getComponent( e, Position.class ).AUTO_COMPLETE

…so you can instead write your method much quicker, and yet very clearly, as:

public void doSomethingWithAnEntity( int globalId )
// remember, we NEVER hold refs to Entity objects for long
Entity e = entitySystem.get( globalId );

entitySystem.getComponent( e, Position.class ).x = 5;
entitySystem.getComponent( e, Damage.class ).hitpoints = 145;
entitySystem.getComponent( e, Renderable.class ).foregroundColour =;

Time-out: HashMap

HashMap is the “correct” class to use in Java for this setup: it’s the exact equivalent of Hashtable / Dictionary / etc in other languages. We need to map (somewhere, somehow) from one thing (an entity) to another thing (a component).

NB: this does not mean that you have to use HashMap as your data-store for the ES; I positively encourage you to consider other options. I used it here as the most obvious, simplest possible structure that would do the job. If you think back to my posts on Entity Systems for MMO development, I’ve often suggested that the data store could *and should* be any of many different things. In particular, SQL databases make for an excellent data-store (and remember you can get in-memory SQL implementations that do away with all the expensive write-to-disk stuff).

Unfortunately … Android seems to only partially support HashMap. You can use the class, but it runs an order of magnitude slower than you expect for a normal JVM (compared to the speed with which it runs other methods). It seems to have problems with the hashcode methods, but also even with basic iteration over the Map contents. Odd. Later on, I had to do some tricks to speed up the ES, just because of this problem.

Fetching a Component from an Entity: Redux

The examples I gave above for accessing components were lean and clear on the right hand side (thanks to autocomplete and strong typing), but terrible on the left-hand-side. By the magic of OOP, I’m going to clean up the LHS. BUT (and this is a big “but”) … make sure you fully understand what I’m doing here. With what I’m about to do, it would be very easy to fall into one of the traps of ES development: slipping back into OOP techniques.

Looking at the example:

entitySystem.getComponent( e, Position.class ).x = 5;
entitySystem.getComponent( e, Damage.class ).hitpoints = 145;
entitySystem.getComponent( e, Renderable.class ).foregroundColour =;

… applying OOP mindset, we see that the first argument is redundant; the Entity already knows about the EntitySystem to which it’s registered.

Also, we know that the Entity class will never have any methods or data other than the ID. If that’s the case, the only thing we’d ever “get” from an Entity is a Component. So, we can add this to Entity:

public class Entity

/** Gets a filtered view of the entity’s data, only returning the subset that
* corresponds to a particular one of its components */
public <T extends Component> T getAs( Class<T> type )
return source.getComponent( this, type );


…which converts our usage example to:

e.getAs( Position.class ).x = 5;
e.getAs( Damage.class ).hitpoints = 145;
e.getAs( Renderable.class ).foregroundColour =;

Using the ES with Systems

Recap: right now, we can:

  1. Create entities
  2. Add components to entities
  3. Read/Write the data inside each component, on a per-entity basis
  4. Fetch entities by globally unique ID

One last thing is needed before the ES can work: we need a way to fetch Entities “by component”.


public class MyEntitySystemExperiment

public void runLoop()
while( true )
// move all the entities
positionSystem.move( MOVEABLE_ENTITIES );

// check for collisions
collisionDetectionSystem.process( MOVEABLE_ENTITIES );

// render all the visible entities
renderingSystem.render( RENDERABLE_ENTITIES );


We need a way to provide the arguments that are capitalized above. We know that these should be plain-old lists of entities. We know they have to come from the EntitySystem. Finally, we know that the only defining characteristic of these lists is that everything in the list has *at least* a particular Component.

(respectively, in the example above, the lists contain: “all entities that are moveable”, “all entities that are moveable AND all entities that are barriers to movement (e.g. solid walls)”, and “all entities that should be displayed on-screen”)

So, one more method for the EntitySystem interface:

public interface EntitySystem

public List<Entity> getAllEntitiesPossessing( Class… requiredComponents );


“Class…” is just a convenience; in many cases, you’ll be insisting on a single Component. In many other cases, you’ll be insisting on a set of components. Java varargs provide the minor convenience of doing both of those in one method, while retaining type-safety.

The implementation of this method is obvious: it iterates over every entity that’s been registered, and checks it against ALL the required components. If it possesses all of them, it goes into the output list.


That’s it. So easy! Obviously, there’s more to it – the other methods you need to create should be mostly self-evident – but this should be enough to get you started.

Now, I’m not sure where to go from here. I’ve got a working Java ES. I’ve got some performance improvements and feature improvements. But … in practice, hardly anyone writes games in Java (except Android programmers, and there aren’t many of those), so … is it worth it?

Alternatively, I might just run through some of the practical pros and cons I encountered when actually using the ES in writing the game-logic. There’s some interesting things that came up which most people encounter sooner or later when doing their first ES, and which might be worth looking at in more detail.

One last thought…

Did it work? Did this ES allow me to write a decent Android game?

Yep. I wrote a space-invaders / bullet-hell game with it. It worked fine on Android phones for a hundred-odd enemies and bullets on screen. On Android, thanks to the crappy JVM, it started to chug after that (dropped below 30 FPS), so I had to make some substantial performance improvements, and now it’s happily rendering 300 things all flying around at 20-30 FPS. The game is far from finished, but it’s playable and fun for a minute or so – a definite achievement considering how little of it I’ve written so far.


NB: it’s got some way to go before I’ll be happy releasing it. But, given a few more spare evenings, I hope to get this up on the Android Market as a free download in the near future.

I’m pleasantly surprised that the Android phones can handle something as high-level as an ES, in a pure, unoptimized “simplest possible” implementation.

Did this post help you?

You can say “thank you” by giving me your email address, and letting me contact you next time I make a game of my own:

[smlsubform emailtxt=”” showname=” mailinglist=”pif-entity-systems”]

177 replies on “Entity System 1: Java/Android”

2nd HashMap

Sorry for the double post please edit them. It didn’t let me add multiple “less-than, more-than signs”


Two quick solutions … one is to change the methods and store the int in the hashmap as key instead (which is a PITA in Java but works fine)…

…the other is java-specific (but holds true for MOST OOP languages): in your Entity class, you override the two methods:
(boolean) equals( Object o );
(int) hashCode();

(I may have the names wrong). The first one is what Java uses to test for “equality” in a collection – if you set that to return true IFF the two objects are both Entity instances *and* have the same integer value inside them, it will work fine.

However, the second one is a performance optimization that you nearly always want to do: specifically for hashmaps, you can control the hash that is generated on a per-object basis. Gross simplification, but: … to make java’s HashMap class work at peak performance, you should have objects that are the same according to equals have the same hashCode too (google for how HashMap’s work, independent of language, if interested to know “why”).

(int) hashCode
return this.entityIntegerValue; //whatever the internal int var is called

…which should be extremely fast, and yet correct.

Thank you for fast replying. I red about equals and hashCode but I never had the chance to override them so I will try it now :D

To get the whole process straight….there is the initialization process( adding entities, components), then systems Updates all Entities which contain the required Components. This Update method takes every Entity containing the required Components and for each Entity change the data in the corresponding Component. Is this right?

As a suggestion maybe it is good for everybody if you can post the whole Entity System process as a short story/description better than I wrote above.

I’m wondering about the implementation of
List getAllEntitiesPossessing( Class… requiredComponents ).

The way I have it setup right now is exactly like you describe: An entity list is returned, which I use to call getComponent to retrieve the actual components. Ideally I would like getAllEntitiesPossessing to return a list of lists (like you commented somewhere above), but I fail at Generics I think.

My only real attempt has been to return List<List>, but this requires casting on the calling end. Is there a smart way to return a typesafe list with mixed Components which DOESNT require casting? I imagine returning the components instead of the entites would be more in line with the ideas described here, and would also improve performance, so perhaps I should just deal with the cast and move forward?


this is getting into the next-level of “slightly more advanced” ES design, which I’ve talked about in theory, but not gone into much detail. If I can get more people contributing to the Entity Systems wiki, this is where we’ll go next.

(at this point, you’re getting into the kind of thing we were doing on commercial / AAA games – cleverer design around performance, efficiency, etc)

I *do not* have a pithy description for you – I find it takes me a lot of time to come up with derscriptions/blogposts that are clear on this topic (so little is defined, so little shared vocabulary, so many wasys to confuse / get the wrong idea)

The best I can say is:

– in C (and anything C-derived), my preferred route was to work with ( lists-of ( structs-of-structs ) )

– each Component is (essentially) a struct
– for a given System, you know you want, perhaps, the Position, Velocity, Destroyable, and Human components
– so … you make a struct of: mySpecialStruct { P, V, D, H }
– …and now you can pass a list of that mySpecialStruct from the ESManager back to the System – with no typecasting – and with no indirection / entity-ID-de-referencing

Problem is: I’m sure I’ve seen good ways of doing that “make a mySpecialStruct” with C++ templates, but I can’t remember exactly what/how :(.

The alternative is to – essentially – create miniature “monolithic GameObject” classes (which, remember, is the nightmare we’re trying to escape), just to avoid the typecasting etc.

NB: I believe that is *not* necessarily a failure, to go down that route: some systems will never need changing (i.e. anything that’s pretty generic already, like a movement system). It’s still a failure for other systems (e.g. AI, that’s very sensitive to the invention of “new” components …. or e.g. anything that runs game-logic (death, damage, etc), for the same reason).

If you can preserve *some* runtime binding of that mySpecialStruct’s contents, you could evade those problems above. Which is what I remember trying to do with C++ templates before. But I’m not a templates expert – if you can find someone who is, they might be able to provide a perfect solution.

So if I get your drift, using Java, I should spend some time figuring out how to create generic “container”-classes I can pass to the getAllEntities method, to ensure type safety.

I will do some thinking and get back with a post if I can develop something useful.

For java, just swallow the cast for now. Until you need / think of smoething better.

OR … make a custom List class, which you use just for passing things in to the Systems. A class which acts like the Facade / Flyweight pattern, e.g.:

public getCurrent( T ); // for the current index, gets the component of type T
public void advance(); // jumps to the next index; all future calls to getCurrent will access the components of the *next* entity

Tell me if I’m on to something here or if I am missing the point completly (this is a as-it.-comes-to-me-with-no-regards-to-maintainability-implementation):

class TwoContainer{
public T one;
public X two;

public List<TwoContainer> getAllEntitiesPossessing(Class class1, Class class2) {
TwoContainer container;
List<TwoContainer> returnList = new ArrayList<TwoContainer>();
Component fetchedComponent;

for(Entity e : entities){
container = new TwoContainer();

if((fetchedComponent = getComponent(e, class1)) != null){ = (T)fetchedComponent;

if((fetchedComponent = getComponent(e, class2)) != null){
container.two = (X)fetchedComponent;


return returnList;

Hmm, all my typesafety got eaten by the replay parser. Let me clarify with (T, X)

public (T extends Component, X extends Component) List getAllEntitiesPossessing(Class(T) class1, Class(X) class2) {
TwoContainer(T,X) container;
List returnList = new ArrayList();
Component fetchedComponent;

for(Entity e : entities){
container = new TwoContainer(T, X)();

if((fetchedComponent = getComponent(e, class1)) != null){ = (T)fetchedComponent;

if((fetchedComponent = getComponent(e, class2)) != null){
container.two = (X)fetchedComponent;


return returnList;

What I’m thinking is this: Have some monster getAllEntitiesPossessing method that takes and have overloaded methods for fewer classes, aka

getAllEntitiesPossessing(Class(T) class){
return getAllEntitiesPossessing(Class(T) class, null…)

Not maintainable?

OR, realize that you posted a sweet solution. Thanks! I’ll use the list approach, that will work well. Feel free to remove the above mess. Talk about going about this the wrong way!

Adam, thank you for your detailed blog series, and for being active in the comments. It was tremendously enlightening, and for better or (probably) worse), I’d like to share what I came up with after your indirect help.

Using Processing, I cobbled together a working entity component system that uses the id of each entity to grab a specific object from that system’s vector array. Because my power over Generics is weak, I settled short of the promised land, but this method seems like it will work for small, contained projects.

Thanks again. Naturally, critical feedback is welcome from anyone who cares to dive in.


Cool. Could you add a page to the wiki, with a brief writeup of this approach, and with a link to your source project at the end? Also very helpful if you could write a brief overview of the source code in a way that makes it easy for people to port it to other languages.

c.f. == complete “perfect” example of a writeup page

NB: the three most important bits for a minimal writeup are:
– the first para of the page (the bit that explains verbally *only* whatever is special/different/unique about your approach – in this case, it could be as simple as saying “it’s like the RDBMS-Inspired approach, except that each system holds the components of its kind, instead of the entitymanager holding all components of all kinds” … but better worded than that :))
– the “Implementation > Concepts” section: c.f. the example, it not only lists the words being used, but it gives the *type* of each (e.g. in some implementations, Entity is not an integer. So it helps a lot to state this up-front)
– …and, finally of course: the link to your sourcecode project :)

Hi, First of all great articles…

I’ve been using an entity system created by me for some time now, and since I’m doing another (improved) ES I have a couple of questions about the render part of the ES.

Example 1:
A tank is composed of tracks, body and turret, in my ES the render would take care of rendering the entire tank, having no need for child entities.

Now making the new ES, I come to the conclusion that,perhaps, I need a tree structure in entities.

Example 2:
A ship with 3 cannons, its the ship entity that has 3 children entities, one for each cannon, this is a tree concept while doing the render, in the sense that, when the ship moves the cannons should move as well.

How do I implement this? And Do I need this at all?

Should the ship be a complete entity?
Should I have entity trees?
Should I have a tree concept for the render components?

Also regarding the render components, are they data as well? or should they be seen as different since they are the view in the model view controller pattern?

Or am I just making a big mess out of this?

Thanks in advance…

ES aren’t well-suited to tree structures, although for small-scale situations, they work fine.

The problems come when you have e.g. a 50-node deep Scene Graph: you can’t iterate over components any more, your fundamental algorithms aren’t iterators – they’re tree-traversers.

In general, my advice would be to run through your data twice: once in a non-ES fashion, which pre-processes data and stores it back in the ES components, then once in an ES fashion, that uses the pre-processed data.

e.g. for rendering a scene graph, have a “pre-render” stage where you traverse your graph, writing-out the absolute coordinates of every node … then you can process the list of nodes in an ES fashion, iterating over each one and processing it without having to refer to its parent, it’s parent’s parent, … etc

…but there are obvious performance issues with running through your data twice, and in the long run you’d want to think carefully about how that interacts with your hardware.

NB: that said, many projects find that this kind of dual-run approach fits well within the performance of the hardware available. I’d perhaps try it this way to start, and see what happens.

Hello adam, I am really interested in networking using ES. How would this work? Can you describe a little how the server will implement ES?

In your code, you store components into a hash map with the following specification:


However, adding objects to collections defined with bounded wild cards is not allowed in Java. Moreover, since you already know that your collection will only contain classes derived from the Component class, why not make it just:


Note that in order to maintain the easy code completion feature in Eclipse, you do still need the getComponent method to have the signature you specified above.

In a networking environment, the server will implement ES with clients as Entities?

How many threads will run?

I’m thinking about a thread that will manage the game logic and other threads for listening client messages. The messages from the clients will be some events for the game logic.

Is this right? How it’s done for maximizing potential in MMOs?

These blog posts are really about using an ES to write a game. What you’re talking about is how to write low-level networking code, which is a different problem. I probably wouldn’t use an ES for that – I’d just use straight imperative code with a little OOP mixed in.

If you definitely wanted to use an ES for network code, I’m not sure how I’d do it.

So networking is a question I’m curious about, too, albeit at a much higher level than Alex. The commercial entity system I’m familiar with embraces message-passing, and has messages between systems (and between scripts attached to entities); it also uses the same messaging system to replicate data between instances of entities on separate computers. However, I thought I’d read you arguing against using message passing / event-driven systems with entities (although I can’t find that in your blog at the moment). How would you network an entity system?

One core aspect of the ES is that everything is merely simple data – its very easy to write generic code that will serialize, compress, transfer etc your game data around, at the granularity of components.

Can you give me some references, books about low level networking coding?
Sorry if this is off topic but I really want to find more information about this subject
and I didn’t found many articles. Thanks in advance!!!

Hi Adam,
The articles are great. I am looking forward for the next article – hopefully you will give us some more information about AAA performance and use cases.

Meanwhile, I’m wondering about the implementation of a collision detection system.
We will need a:
collisionDetectionComponent (x,y, deltaX, deltaY, velocity, radius etc)

Let’s say that we have 1000 entities, all of them are bind to collisionDetectionComponents.
Assuming that we need to perform a simple sphere test, how would you suggest of checking if there was any collision between the objects?

IMO, since the entities are stored in a list, we will need to check them against each other (1000*1000) – which is bad.

Another suggestion is that the collisionDetectionSystem will have a 2-3D array/hash table for the X.Y,Z and on-top have linked list to hold more then 1 entity on the same X,Y,Z (array[x][y][z]->entitiy_1->entitiy_2)
Now, we can check for collision only on specific areas and reduce the amount of checks.

Any idea?


Hey there,

this is a great article. I tried this myself and it didn’t work “out of the blog” for me.
I had to cange to After that it worked for me. I might have done something wrong, because I’m not that fit with Java Genereics as well.
By the way, one can put java primitive types into collections. Just write HashMap . You can then write map.put(42, new Component) since Java 5 the compiler supports Auto-boxing and will create the Integer-Wrapper for you.

What I didn’t quite understand is the big picture. Imagine a network packet comes in, is unmarshalled and then I know, what should happen, e.g. Player moved. Will the network system itself get the Position-Property of the player and change the values or does it forward the incoming message to something like a Position-Service (which then changes the property.)? After that I need to tell other entities about the new Position of the player.

@Simon – sorry, wordpress deletes code. It’s crap. Blame WP! (I’ve tried a few plugins, but all so far caused conflicts or bugs elsewhere :( :( )

you may need to apply the corrections listed higher-up in the comments. I can’t remember if I edited and added them all :(.

No, you NEVER “need to tell other entities”. You just wait. They will automatically “discover” this fact the next time they iterate over the entire list of components (usually: once per gametick).

If you need the object to *animate* into position, then *some* additional work will need to be done. e.g. you might have a “interpolatingmovement” component, where you set fields saying what the new position is, how long it should take to get to that position, etc, and maybe do NOT update the position at all.

Instead, you have a system that checks these interpolationmovement comps each tick, moves things a little, and if an interpolation is complete … deletes that component (or zeroes it).

PS: if you’ve made this, please add it to on the page “RDBMS with code in systems”. Ideally, if you can create a (free) github account for it, then include that link on the page.

(someone will ned to change the names of some classes / methods – I came up with better names after writing this blog post. But if you’ve already got a working verison, that’s easy for someone else to do in github)

Thank you for your fast reply.
I didn’t think of the gametick. But what about the server side of a multiplayer or even massive multiplayer game? I once read that “event based” is the way to go. However, this was written by a former Sun programmer, who worked on *Project Darkstar*, which is now know as *Red Dwarf Server*. It’s entirely event-based and one was encouraged not to programm in the “old gameloop”-fashion.
So the servers have their own gameloop / tick-mechanism? I hope it’s not getting too off-topic, but I’m really interested in the server architecture und implementation. I’m doing some research on locationbased mobile games at my university and, to be honest, a server with an own gameloop might solve some problems i encountered.

Event based game logic on any non-trivial scale is generally a stupid idea coming from people with little or no experience of building real systems. Or from people who are used to having insane amounts of spare processors (far too expensive for a game company to afford).

Because modern computers can’t do event-based processing. They can only fake it, and for non-trivial examples, the fakery breaks down, and the performance crashes to the floor.

It’s also the most natural approach for OOP. Which is why you see it come up again and again from people who haven’t been taught better (or haven’t yet learned the hard way). I learned the hard way – I made awesome small games with it, then tried to scale up, got badly burned, and gradually realised quite how stupid I’d been.

Just to be clear: I’m talking purely in the context of computer games, and the main game. Things that have to operate with millions of objects being updated with complex CPU processing hundreds of times per second.

There’s plenty of industries where their data / interactivity rate is orders of magnitude slower than games, and they can get away with things like event processing.

Even games industry uses it – e.g the networking layers ride on the back of special hardware in the PC, or code in the OS kernel, that’s there to provide a faked version. But the networking layers typically run very simple code at a much slower rate than the main game – and they have special hardware / OS support to help them.

(But even so, I’m making a gross generalization here. My point is: you should be asusming a game-loop until you’ve got a damn good reason to do otherwise)

Would it be a better idea to let Systems call the appropiate components from EntityManager? Leaving System such as render() without parameters, except for systems that need delta time.

– Multiple component request can be made through one method call.
– No need to make sure the correct components are being inserted through parameter. (or create definition of names for a family of components)

– System now know about EntityManager.

Instead of this:
mPhysicSystem.processMovable(mEntityManager.getEntitiesOf(ENTITIES_MOVABLE), dt);
You get this

Any thoughts?

I don’t think there’s anything intrinsically wrong with systems knowing about the entity manager – so long as they’re mostly delegating to it the work of retrieving the sets of components they need from memory / wherever.

In my examples I didn’t pay much attention to the call semantics of systems – I kind of waved my hands and said “however you like”, so long as you don’t mess up any of the core rules around e.g. Don’t put logic inside compOnents

Adam, thank you for such extensive writeup on such a paradigm shift. I’ve ported a ES implementation really close to your thinking to C#, which can be found here(work-in-progress):

Also, an example of game using this can be found here:

So far, so good, but now I’ve stumbled upon a tricky topic: how can I bridge the ES with existing engines that take care of rendering, physics etc.

These tasks require complex objects(like a Body to physics) and from what I read here, should be in systems(so, a temporary system state which is generated from the “true” state of primitive component attributes)

I think these complex attributes can be initialized on systems and could be a analogue to temporary tables, a state that won’t be persisted but it is generated based on the “true” state(components). So I thought about a special component that would be populated with these complex objects by the system, to keep the entity reference and easy value lookup(also, we could write systems based on the existence of this component, which means some complex property is already initialized and ready to process). These special components would not be persisted, they are generated in game because of the primitive components…


Ok, I’ve added it to the wiki.

My question doesn’t concern specifically physics stuff, that was an example. It is about the “glue” needed between ES and another engine(frequently OOP), hence the complex component objects.

These kinds of issues are generally quite small/obvious/simple with other systems; Physics is a special case – and makes a great case-study/example – because it’s so processor intensive and yet so common, with the same data structures/algorithms used in almost every game.

So … I think it’s a good one to discuss and work on.

Briefly, on your example, everthying you say makes sense – there’s nothing new there, AFAICS? I hope it’s obvious that many components don’t usually get persisted (for instance, not least: player-inputs from tick to tick :)).

More extreme example: in network code, lots gets serialized that normally you wouldn’t persist, and lots gets ignored that’s critical, locally.

…but with Physics, there are important questions of: efficiency, integration with 3rd party physics libs, etc. I’ve used a few physics engines, but I’m by no means an expert on them, and I’d really like to throw the question out to people who are :)

Adam, I need to integrate the ES with a rendering engine that has at its core a messaging system: it acummulating messages and sending them at once. (and it has a number of messages that he can send each frame).
Some messages can be sent lots of times to an object, if the message is a component, it would be strange.
Messages are used to tell something about the engine (triggers for example notifies objects using messages)
If we put components as messages, are we coupling both systems too much? Do you have any advice about integrating ES with external engines that work on a evented way?

In practical terms, you literally *cannot* send messages to entities. The nearest you can do is send messages to one of the “systems” that is processing entities each loop, and have it batch up a whole chunk of incoming messages, then apply them to its own entities on the next cycle.

Although … without knowing the details, my gut feel is that a rendering-engine based on messaging system sounds like a nightmare anyway :)

I know there’s been so much time since the last update on this thread however this thread made be so frenetic an excited that I just want to spend some time around this model.

I was wondering if, for example, a Command Pattern would fit in here lets say for ease of networking (and not only).. For example, if I want to make a level of abstraction on the way that entities take actions and not to differ from input actions or network actions, would it be correct to create a stack that groups the actions that need to be executed tick after tick and in the specific systems we just create those actions and add them to that stack?

Don’t know if I made myself clear but basically I’m wondering how I can add that level of abstraction so that we can simplify how the systems interact with the “outer” world.

Best regards, João Gonçalves

Great article but i have some problems with this design :

You said that components can’t communicate between them, ok because there are only data but what about systems ?

Imagine you have a physic system that uses Box2D engine to process physic and if you need to disable a contact with the presolve callback of Box2D, how we can do that without using an event or notification system ?

My solution is to have a Box2D physic system that sends events with a contact as parameter of event and others systems which register to this event when needed.

Is that correct ? Thank you

Yes you can do that.

Although you’re probably better off creating temporary components that will be picked up by other systems when they scan the complete entity/component store looking for things to operate on

@Joao – one of the long term advantages of entities is that they make it a LOT easier to write generic code for memory management, network synchronisation, etc.

This is by no means unique to an ES – it happens with all coding approaches that provide a strongly enforced set of rules on object creation and class design. ES happens to be one of the easier ones for doing this stuff – simPly because the component approach is VERY strongly enforced, de facto.

I know this article’s rather old, but it seems to be the most relevant for my question. I’ve read through all your articles on Entity-Component design (as well as any others I could find), and I’ve been trying to implement an ES in C++ for a game idea I’ve had.

You mention that if you were working in C++ you would use templates. And for the life of me I can’t figure out what that would actually look like. I know enough about templates to see the benefit, but I’m just not seeing how an ES would work like that. Do you have any examples of an ES implemented in C++? The Entity Manager is where I’m having the real problem, but anything would be greatly appreciated.

And great job on the articles! I just wish there was more information on Entity-Component design in general (everything I’ve found either redirects here, or has a not-quite-right ES design).

@seth – I’ve made a couple of half-hearted attempts last year at doing a pure C++ version based on template metaprogramming, but I’m too out of practice with templates, and I wasn’t happy with any of them.

In theory, it ought to work well. The problem is that I haven’t written any C++ in a long time, and I’m very rusty. In practice, when I struggled and went looking for 2nd opinions, most of the hardcore C++ people I know haven’t adopted ES’s yet and won’t focus on the problem – they instead try to sell me on other, “more C++ style” solutions. Which is usually missing the point, sadly. In practice, C++ coding with the current free IDE’s I have access to makes my head hurt (Eclipse C++ support is (to put it nicely) “weak”, and let’s not even mention Xcode). I actually find it easier to write C++ on paper and then b*tch-slap the IDE into accepting it, than to write it with the IDE’s ‘help’ :(.

So … sorry!

I suggest you try tweeting at some well known tech / games people who tweet about C++ programming – there are interesting problems here, and they might find it fun to have a go with.

Comments are closed.