How to do simulation with many entities?
-
Let's say I want to implement a nature simulation kind of thing - a world where there is grass, herbivores, carnivores etc., all interacting based on their respective behavior patterns. I think I understand how I would use scenes and nodes to do this, but now, let's assume I want to have a huge amounts of these entities and I don't need to show them all at once. Basically, I want to do a simulation in the background and based on certain rules, I want to pick some of these entities that will also be visible.
How would you do this? What would you use to represent the entities that are just a few data fields and an associated behavior? How to make them as lightweight as possible for this to be efficient, but still be able to save them easily, for example? And how would you switch for a specific entity (for example one particular wolf) from the "simulated-in-the-background-but-not-displayed" to the "visible-on-the-screen" state?
Thanks for any advice.
-
For the entities that are simulated but not visible, I would use a custom class that extends
RefCounted
as lightweight representations. Let's call itEntityRef
with each contain:- A unique ID
- The entity type (tree, herbivore, carnivore)
- Any data fields needed for the behavior (location, hunger level, etc.)
I would store all these RefCounteds in an Array or Dictionary for easy access and iteration. The behavior scripts would run their logic periodically to update the entity's data fields.
For visibility, I would have a VisibleEntity scene that contains:
- A Sprite2D or something else for the visual representation
- A reference to the corresponding
EntityRef
When an entity should become visible, I would instantiate the VisibleEntity scene and set its
EntityRef
reference to the corresponding entity in background. This would link the visible and invisible representations.To switch an entity from the background to visible (for example, that entity location is within the Camera view area), I would:
- Find the
EntityRef
in the Array/Dictionary by ID - Instantiate the VisibleEntity scene and set its
EntityRef
reference - Add the VisibleEntity to the level's scene tree
- Remove the
EntityRef
from the Array/Dictionary (since it's now visible)
Something like these perhaps:
- Thousands of lightweight
EntityRef
for the background simulation - Only instantiate visual representations when needed to improve performance
- Link the visible and invisible representations to keep their data and behavior in sync
-
Thank you so much!
-
If all else fails you can always resort to raw C++, ie. making your own CustomNode class which is just Node but you strip all the methods and members that you don't need into baldness.
When I have time I'll write how to write your own custom modules in C++. There's example in docs, but I think it could be more detailed.
-
I would take a look on how minecraft was made, using threads to deal with those objects.