Does an Entity Component System require Trait Objects?

For an ECS, where entities contain different instantiations of components, should I just accept that the component collection needs to contain Box<dyn Component> ?

Don't see a way to avoid that since entities can contain Transform components, Renderer components, etc. etc.

In an ECS, the entities themselves don't usually contain the components - the entity should effectively just be an ID number, which you use to index into the collections of components.

// Psuedo-code - obviously it's more complex than this!

struct Entity(usize);

struct Components {
    transforms: Vec<Transform>,
    renderers: Vec<Renderers>,
}

The benefit of this is that iterating over a particular type of component (a very common operation) becomes extremely fast and benefits from CPU cache locality.

1 Like

Thanks! Having a bit of trouble following your example though...

If one entity has Transform+Renderer, and the next has just Transform, and the one after that has Transform+Renderer again - won't it be problematic since renderers[1] is missing?

There are many ways to avoid this. Vectors may actually contains Option<Component> for later iteration, or there may be additional indirection table. For some usages keeping components in HashMaps may be beneficial.

There are actually many ways to implement ECS, good place to start may be to check Specs - even if not code (which itself is pretty good piece of art), even reading docs you may reason about architecture a bit.

4 Likes

Seems like specs really does a lot of the heavy lifting... will think about building on that :slight_smile:

Yep, I was definitely oversimplifying! This page from the Specs docs goes into the various ways that they allow you to store your components - worth a look for some info on the tradeoffs of the different container types.

1 Like

Heh, wow - I was way out of the loop!

I was thinking Entity-Component-System as like the last time I built something in Unity (~2-3 years ago), which had entities, and components, and systems - and did allow composition of components, but it structured the relationships more like inheritance (which is where I made a wrong turn in my thinking above) - and it turns out was not truly a ECS.

And now they've got a modern ECS architecture which uses the ideas y'all mention above (re-organizing it so that entities are simply indexes into the component collections, and that components are grouped into archetypes, etc.)

Cool stuff!