   Efficient Data Structure for Storing Game Objects
For the past year or so I've been toying with game engine dev on and off and I've tried a couple different approaches to allocating and storing "game objects" (actors, entities, whatever you want to call them). For a couple months now I've favored the solution presented in this Stack Exchange answer: http://gamedev.stackexchange.com/a/33905/39265 To put it briefly, the solution described is an array where allocated objects are kept contiguous in memory for the sake of cache coherency by swapping the object highest in memory with any gaps created during deallocation. It also uses two levels of indirection to maintain stable unique ids for referencing the moving objects. The author on Stack Exchange didn't mention this, but the data structure could easily be augmented by making it a struct of arrays using the same id allocation/dereferencing scheme. I like this solution, but it has some flaws that always concerned me:How long does it take to swap an object during deallocation? My game objects have a huge amount of data associated with them: Location, rotation, a 4x4 world matrix, a 4x4 world-view-projection matrix, a 3x3 world-inverse-transpose matrix... those alone make up at least 47 floats, or 188 bytes.Swapping is not only an issue for deallocation. Sorting would have the same implications. What if I want to sort my objects for some reason, e.g. to reduce GL state changes during rendering. I assume a cache miss on a small game object component on the CPU is nothing compared to a cache miss on the GPU looking for an entire texture.While making my own implementation of the data structure, I realized something: x86 cache lines are usually only 64 bytes long now-adays. That's only one 4x4 float matrix. If I'm doing matrix heavy calculations (which are ripe of tight loop and multi-threading optimizations), so long as the matricies are cache-aligned, I don't have to worry about contiguousness for the sake of cache coherency. Without the need for contiguousness, there's no need to swap during deallocation. That solves my first concern. It has the added bonus of reducing the levels of indirection from two to one since the objects will never move in memory. Also, while I'm no longer keeping the objects themselves compact in memory, I'm still maintaining a list of allocated ids that's compact. This way, all objects can be iterated over without wasting time with unallocated objects. As a plus, this list of allocated ids can simply be the other half of an unallocated id list (or "free list" as the Stack Exchange author calls it). The list of allocated ids can also be sorted efficiently as per my second concern, since you only need to swap integers and not entire objects. Just make sure you update any "reverse ids" for efficient deallocation accordingly (this can be done with one linear pass of the sorted allocated id list). Also, if you make the id number itself part of your sorting criteria, that would theoretically improve cache coherency during iteration. Below is a sample C++ template that implements the id management of the data structure.#include <array>#include <stdexcept>#include <utility>template<typename IdType, IdType MaxSize>class id_manager{private:  typedef std::array<IdType, MaxSize> array_type;public:  typedef IdType size_type;  typedef typename array_type::value_type value_type;  typedef typename array_type::difference_type difference_type;  typedef typename array_type::const_reference const_reference;  typedef typename array_type::const_pointer const_pointer;  typedef typename array_type::const_iterator const_iterator;  typedef typename array_type::const_reverse_iterator const_reverse_iterator;private:  size_type _size;  // The first _size elements in _ids are allocated ids.  // The remaining elements are unallocated ids.  array_type _ids;  // _reverse_ids maps ids to indexes into the _ids table for efficient  // deallocation.  array_type _reverse_ids;public:  id_manager()    : _size(0)  {    // All entries in _ids are initially unallocated.    for (IdType i = 0; i < MaxSize; ++i)    { _ids[i] = i;    }  }  IdType allocate_id()  {    if (_size == MaxSize)    { throw std::length_error(  "Attempt to allocate beyond this id_manager's maximum size");    }    IdType result = _ids[_size];    _reverse_ids[result] = _size;    ++_size;    return result;  }  void deallocate_id(IdType target)  {    --_size;    // Swap the now unallocated gap with the end of the allocated section.    IdType reverse_id = _reverse_ids[target];    std::swap(_ids[reverse_id], _ids[_size]);    _reverse_ids[_ids[reverse_id]] = reverse_id;  }  void clear()  {    _size = 0;    // All entries in _ids are reset to unallocated.    for (IdType i = 0; i < MaxSize; ++i)    { _ids[i] = i;    }  }  bool empty() const  {    return _size == 0;  }  size_type size() const  {    return _size;  }  size_type max_size() const  {    return MaxSize;  }  const_iterator begin() const  {    return _ids.begin();  }  const_iterator end() const  {    return _ids.begin() + _size;  }  const_reverse_iterator rbegin() const  {    return const_reverse_iterator(end());  }  const_reverse_iterator rend() const  {    return const_reverse_iterator(begin());  }};The ids can be used as indices into arrays of object data with the same max_size(). I haven't actually done performance tests, but I can't think of a better solution if sorting (or simply not swapping during deallocation) is more important to you than contiguous memory. What do you all think? Are my priorities in the right place? Any enhancements you can think of?
x86 cache lines are usually only 64 bytes long now-adays. That's only one 4x4 float matrix. If I'm doing matrix heavy calculations (which are ripe of tight loop and multi-threading optimizations), so long as the matricies are cache-aligned, I don't have to worry about contiguousness for the sake of cache coherency. Without the need for contiguousness, there's no need to swap during deallocation. That solves my first concern. It has the added bonus of reducing the levels of indirection from two to one since the objects will never move in memory.You still want the data to be contiguous, because of pre-fetching. If you read line 1, then 2, then 3... then the CPU will assume that this pattern will likely continue, and it will try to start grabbing line 4 and 5 and 6... before you even ask for them, which greatly reduces cache misses.If performing micro-optimizations before shipping, you can assist the CPU by inserting your own explicit pre-fetching instructions.So not only should your data be contiguous, but it should be segregated by type. If you've got a task that's only reading world-matrices, then you really don't want to have location/rotation/projection data all interleaved along with these matrices, because this unused data is basically just a bubble, breaking your contiguity.How long does it take to swap an object during deallocation? My game objects have a huge amount of data associated with them: Location, rotation, a 4x4 world matrix, a 4x4 world-view-projection matrix, a 3x3 world-inverse-transpose matrix... those alone make up at least 47 floats, or 188 bytes.Due to the above explanation, you probably don't want your game object to be one large structure like this. You should look at the different processes that read/write game objects, and rearrange the data based on the needs of these processes. If there's a process that reads position/rotation data and outputs world-matrix data, then keep that stuff separate from the other variables, etc, etc...Swapping will be bogged down by cache misses, like any other process that works with this data. If you can buffer up deallocation requests in a queue, and then process them all at once, you'll probably end up with less cache misses when reading/writing the object data array(s).Also, do you really need to store a world-view-proj and inverse-transpose matrices per object? i.e. can they just be computed as required? Or are they required too frequently?Swapping is not only an issue for deallocation. Sorting would have the same implications. What if I want to sort my objects for some reason, e.g. to reduce GL state changes during rendering. I assume a cache miss on a small game object component on the CPU is nothing compared to a cache miss on the GPU looking for an entire texture.You don't have to actually move your objects around in memory every frame based on the optimal GPU-submission order. You can just sort the indices to the objects.e.g. if you've got a list of visible object IDs { 1, 4, 5, 7 }, then you can sort this list to produce your GPU-optimal order. Say #1&7 share the same material, you might get { 1, 7, 4, 5 }, which is then given to the renderer to submit.Regarding your id_manager, this is basically the core of a "pool allocator" My version of the same idea is (unimaginatively) called PoolBase, though it's implemented quite differently internally -- instead of initializing my id array with 0,1,2... (i.e. the absolute index of each slot), I initialize my ID array with "the offset to the next slot minus 1", which is 0,0,0... When a slot is freed, it's put into a "free-list".Building upon this, I've then got template<T> Pool which has a PoolBase and also has an Array<T>.Many parts of my game then make use of the Pool class for simple allocation of objects, and a few other structures also make use of PoolBase for ID management.So yep, it's useful Here's a good article: http://molecularmusings.wordpress.com/2012/09/17/memory-allocation-strategies-a-pool-allocator/;You still want the data to be contiguous, because of pre-fetching. If you read line 1, then 2, then 3... then the CPU will assume that this pattern will likely continue, and it will try to start grabbing line 4 and 5 and 6... before you even ask for them, which greatly reduces cache misses.Aha! I didn't know about pre-fetching. I figured something like it might exist, but I wanted to get my idea written down before finding out it's sub-optimal. Question: What if I read lines 1,2,3, then 5,6,7,8, then 10,11... etc. Ordered chunks with small gaps. If I sorted my allocated id list by id number, this is essentially what my iteration would look like. Are CPUs smart enough to pre-fetch even when these small gaps exist? I'm aware that, even if a CPU did prefetch my subsequent data in-spite of gaps, it would still have to do so more often than if there weren't gaps, but it wouldn't be any worse than if all the gaps were filled (which they would have had to have been at one time, otherwise they wouldn't exist to begin with). So not only should your data be contiguous, but it should be segregated by type. If you've got a task that's only reading world-matrices, then you really don't want to have location/rotation/projection data all interleaved along with these matrices, because this unused data is basically just a bubble, breaking your contiguity.I already store my object data as a struct of arrays. Is that what you mean? My location/rotation pairs are in one array, world matricies in another, world-view-projection in yet another, etc. But they're all grouped by the same indicies. Are you saying they should have separate id schemes? And if so, how do you suggest associating them? I do keep graphics objects and logic objects separate. "VisualID" is just one member of logical game objects. Do you think I should get more granular than that with my groupings? Also, do you really need to store a world-view-proj and inverse-transpose matrices per object? i.e. can they just be computed as required? Or are they required too frequently?Like I said, matrix calculations are great candidates for multi-threading and tight loops. Instead of calculating them on demand, I think it's better to calculate all the world matricies that are going to be used by a particular frame in one pass, then the world-view-projection matricies, then the world-inverse-transpose matricies. At the same time, I just realized there'd be no need to swap them if I'm re-calculating them every frame anyway. This whole discussion is only for dynamic objects by the way. Static environment stuff can obviously be allocated and calculated once upfront. You don't have to actually move your objects around in memory every frame based on the optimal GPU-submission order. You can just sort the indices to the objects.e.g. if you've got a list of visible object IDs { 1, 4, 5, 7 }, then you can sort this list to produce your GPU-optimal order. Say #1&7 share the same material, you might get { 1, 7, 4, 5 }, which is then given to the renderer to submit.But if I'm not accessing them in order, what's the point of keeping them contiguous? Also, I imagine my solution will keep the data relatively compact anyway. Consider the following game flow for a traditional arena-style deathmatch game:All the players and items are allocated and set to their initial states.Whenever a player dies, they respawn soon after.Whenever an item is picked up, it respawns after some fixed amount of time after.In my solution, immediately after the initial allocation, all the allocated objects are compact at ids 0,1,2,3... up to however many there are. Whenever an object is deallocated (a player dies or an item is picked up) it leaves a gap. But since that gap goes to the top of the free id stack, it will be the first to be filled in as soon as something else is allocated. I guess it all depends on the data allocation patterns of a particular game. If the number of allocated objects is kept in equilibrium like above, then my pool allocator sounds pretty good. If, however, a large number of things are allocated, then a non-contiguous half of them are deallocated, then my data structure is left with many wasted holes. Also, I wonder how ephemeral objects like bullets factor into all this... I have more thinking to do. Regarding your id_manager, this is basically the core of a "pool allocator" It's always a nice feeling when you realize your own good solution is the same as a well-known good solution. ;Question: What if I read lines 1,2,3, then 5,6,7,8, then 10,11... etc. Ordered chunks with small gaps. If I sorted my allocated id list by id number, this is essentially what my iteration would look like. Are CPUs smart enough to pre-fetch even when these small gaps exist?It depends on the CPU. Searching "cache prefetch patterns" will bring up some overviews on the topic, but the specifics would lie with each individual CPU. They can't be too smart, so there's probably only hard-coded pattern recognition for things like linear array access, reverse linear array access, accessing every second line, etc...In your example, it will probably go into linear pre-fetching mode and get 4 & 9 along with the rest of that sequence.For complex patterns, this is where you can put your low-level optimization hat on, get your profiler out, and get dirty.Say you've got some code like:while( iterator )  iterator->DoStuff();  iterator = iterator->nextA typical software prefetch might look like:prefetch( iterator->next, L1 )while( iterator )  prefetch( iterator->next->next, L1 );  iterator->DoStuff();  iterator = iterator->nextThis is often a strange combination of art and science to get right though. It requires testing and validation of every change, because prefetching can very easily harm performance rather than help it.Above, each iteration, I've told it to fetch the next-next item (i.e. 2 items ahead) -- this would have to be tweaked. The placement of the prefetch in the loop would have to be tweaked. The cache level that you're pulling the data into (L1, L2, L3, non-temporal) would have to be tweaked... There'll be lots of testing with real data, and recording of observations with a good profiler required to get this right.Here's a decent link: http://lwn.net/Articles/255364/Because this is often an empirical (rather than theoretical) practice, and because it makes your code ugly/unreadable/harder-to-maintain, this kind of low-level optimisation is usually only done on an as-needed basis, right at the end of a project.I already store my object data as a struct of arrays. Is that what you mean?Yep, that's exactly what I meant. SoA data storage is very useful for many different purposes.Do you think I should get more granular than that with my groupings?The granularity should be based on the functions that access the data. If rotation and translation are always used together, then there's no harm in having an array of struct{rotation, translation}(AoS style). However, if there's a function that only processes rotations, then they should be separated from the translations. The optimal storage will often be a blend of both styles, "structure of arrays of structures".But if I'm not accessing them in order, what's the point of keeping them contiguous?I'm assuming that they're contiguous for other operations -- e.g. for frustrum culling you iterate through the whole array linearly... but then later you iterate through a sub-set of the array for rendering.So keeping them contiguous has helped the culling iteration, but yes, has done nothing for the rendering iteration.Keep in mind though that if you sort them each frame prior to rendering, so that the rendering iteration is compact and linear, then it may still be slower overall, because you've just spent a bunch of time on the sort. The sort task has had to do random access reads and writes to the array! In order for this to be a net win, there will likely have to be more than one iteration following the sort that benefits from the work done by the sort task.IIRC, another member on this forum, L.Spiro, is often advocating that you sort your objects into the ideal order over time. e.g. if you perform a large amount of sorting work on one frame to get the objects into the right order, then on the next frame, it's very likely that no sorting will be required, because the order will remain the same. Another likely case is that only a small amount of sorting is required each frame. Only on large camera transitions (e.g. respawning) will the sort pass be costly, as long as the results carry over from one frame to the next.Consider the following game flow for a traditional arena-style deathmatch gameOff on a tangent for a moment -- Keep in mind that for such cases, you may only be dealing with, say, 32 players, or 2KB of matrix data. In cases like this, you could prefetch the entire 2K array into the L1 cache and then happily make random accesses into it!It's the cases where you're working with 10000 objects where you've got to apply more scrutiny ;) Also, you need the game to run within your perfomance budget when running at the worst-cases. If you've got a player limit of 32 players, then your worst case is that you always need to iterate through an array of size 32, accessing every element. This is the case that you have to optimize for.Optimizing for the average case, where you've got 16 players and several free slots in the array doesn't actually help you very much. I've worked on a few games where we've optimized for the best case, and that just means that you end up with very inconsistent frame-rates. We get an average of 30FPS, then in other situations it spikes up to 60FPS, and then in others again it spikes down to 20FPS.So because we optimized the best-cases, we occasionally got 60, usually 30, with a range of 20-60...If we didn't optimize the best-case, we would've got usually 30, with a range of 20-30.If we optimized for the worst-case, maybe we would've had a consistent 30FPS with no fluctuations...Another example of always remembering your actual constraints -- at an old job, my lead programmer spent a long time trying to design a perfectly reusable "component pool", which would provide efficient resorting, compaction, iterations, transforms, etc, etc... After coming up with lots of mutually-exclusive designs and fretting about the trade-offs, he finally remembered "Hey, we make sports games here, we're never going to have more than 100 players, I can just use 7-bit object ID's and arrays with a max size of 128 items, which simplifies constraint X and incompatibility Y..." Regarding the pools, I would implement a few different variations of these collections. Implement yourself a pool that creates holes when items are deallocated, and also implement yourself an array/vector that uses the pop-and-swap deallocation strategy (i.e. move the last item to the erased item's slot, then decrease array size by 1) and a double-indirection table for ID's to cope with the fact that items can relocate.Some parts of your game will work best with the stable pool, others will work better with the relocating array. Experiment within different systems, using intuition based on the functions that operate on the data, and what their access patterns are.