I've been looking into building an entity-component-system. Basically, an entity is just an id wrapped around a struct, components are data belonging to that entity(and reference said id), and systems are the code. Entities and components are all stored inside arrays, to allow fast iteration over each.
For example, an entity could have a Mass, Position and Velocity component. A GravitySystem would take in these three components, calculate some velocity (based off of the Mass) and add it to the Position component.
My problem is, what happens when an entity is removed from the middle of an array? One option is to have the last element of the array swap positions with the entity that was just removed, so that the array stays neatly packed. The downside is that I lose the ability to reference each element by same index number, ie Entity ID 5 is at index 5, and each component belonging to that entity is also located at index 5 within their own arrays.
A solution would be to just ask if entity[i] is "active" before each iteration. Something like,
void gravitySystem(entityList[], massList[], velocityList[], positionList[])
{
for(int i = 0; i < 100; ++i) {
if(entityList[i].isAlive == 1) {
velocityList[i] += 9.81 * massList[i];
positionList[i] += velocityList[i];
}
else {
printf("The entity is dead, Jim.\n");
}
}
}
My problem with this solution is that if I were to have a huge list of entities, say 4M, going through this loop, then the if(entityList[i].isAlive==1) statement would have an impact on performance. Is there another solution that would remove this bottleneck? Perhaps one that would keep the array nice and packed without "holes" in it?