Open feresr opened 4 years ago
investigate: using std::list
instead of std::vector
might help here
Iterator Invalidation Deleting or Inserting an element in List does not invalidate any iterator because during insertion and deletion no element is moved from its position only a couple pointers are changed. Whereas, in vector insertion and deletion can invalidate the iterators.
Try having a look at Entt! From their README:
EnTT
is a header-only, tiny and easy to use library for game programming and much more written in modern C++, mainly known for its innovative entity-component-system (ECS) model. Among others, it's used in Minecraft by Mojang and the ArcGIS Runtime SDKs by Esri.
They might already have a solution for this.
I'm sure they do! 🙂 My goal with this small project was to learn CPP fundamentals so I try to keep the use of libraries to a minimum
Oh I wasn't saying that you use the library here. I was saying that you could see how they solved this issue. Or even create an issue in their repository asking the same question
Sorry for the misunderstanding, yeah that's a good idea!
I am also interested in potential solutions!
I found this article that tackles the problem. Not entirely convinced that the trade-offs are worth, but the solution is interesting: https://austinmorlan.com/posts/entity_component_system/
I think the problem you raise here comes from that redxdev ECS implementation is "wrong".
Entities should be unique identifiers (hash, integer, but not a pointer nor a class)
"Entity: An entity represents a general-purpose object. In a game engine context, for example, every coarse game object is represented as an entity. Usually, it only consists of a unique id. Implementations typically use a plain integer for this." Source: https://en.wikipedia.org/wiki/Entity_component_system
IMHO… The vector of entities you are concerned about (not been contigous) is not the root flaw you should be concerned about. That's the vector of components, which are sparsed among instances of entities.
Optimizing the components vector/vectors (continuity) to optimize CPU cache usage is the key element of the ECS performance benefits, from what I understood from my readings on the topic.
P.S.: This been said, you did a pretty good work and thumbs up for sharing it!
World::entities
is a vector of pointers, those pointers could be scattered in memory. Iterating over them might result in poor usage of CPU caches.I tried changing
std::vector<Entity*> entities;
tostd::vector<Entity> entities;
but other problems arose. (Namely some systems might keep a pointer to a specific entity, the pointer becomes a dangling pointer when adding/removing items to the vector invalidates them)I think my own inexperience with CPP is showing here, I'll revisit this when I feel more comfortable with it