Efficient Data Structure for Storing Game Objects

This topic is 1982 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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:

1. 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.
2. 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?

Edited by jbates

Share on other sites

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:

1. All the players and items are allocated and set to their initial states.
2. Whenever a player dies, they respawn soon after.
3. 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.

• 21
• 16
• 9
• 17
• 13