I have this book called "Data Structure for Game Programmers" which has been a really great read so far. It explains this really useful templated array class which works great but I have a few questions about it.
Here is just some generic code I threw together to play around with:
Code:
#include <cstring>
struct GameState {
unsigned int BaseAddress;
unsigned int AllocatedSize;
};
GameState GameStateGlobals;
struct DatumIndex {
unsigned short Index;
unsigned short Salt;
};
template <typename T>
class DataArray {
private:
char Name[32];
unsigned short Max;
unsigned short Size;
bool IsValid;
bool IdentifierZeroInvalid;
unsigned short Padding;
unsigned int Signature;
unsigned short NextIndex;
unsigned short LastIndex;
DatumIndex NextDatum;
T* Data;
public:
void* operator new(unsigned int size)
{
return 0;
}
DataArray(const char* name, unsigned int count)
{
unsigned int DataArraySize = sizeof(DataArray),
DataSize = sizeof(T) * count,
NewArray = GameStateGlobals.BaseAddress + GameStateGlobals.AllocatedSize;
GameStateGlobals.AllocatedSize += DataArraySize + DataSize;
memset(this, 0, sizeof(DataArray));
this->Data = reinterpret_cast<T*>(NewArray + DataArraySize);
strcpy_s(this->Name, 31, name);
this->Max = count;
}
T& operator [](int index)
{
return this->Data[index];
}
};
struct PlayerDatum
{
int Score;
float Speed;
};
DataArray<PlayerDatum> Players("players", 16);
int main()
{
Players[1].Speed = 1.0f;
return 0;
}
The entire game state memory will be preallocated using VirtualAlloc, so we know that the user will have enough memory before starting the game and so that further memory allocation won't be needed. The game state memory structures I want to be contiguous, meaning each time a new structure is created, it will just add to the allocated size and keep track of the next memory address to use in our big preallocated chunk. This also makes it easier to dump the whole game state to file.
DataArray will be a "header" right above the array of objects.
The problem I have with the above code is, I want to be able to have instances of these DataArray objects in the global namespace (accessed from wherever) but created explicitly in code when I want, like inside some other initialization functions.
I tried overloading the new operator and moving my code into there so I could create a global pointers to objects like so:
Code:
DataArray<PlayerDatum>* Players;
int main()
{
Players = new DataArray<PlayerDatum>("players", 16);
}
But now the problem is, I can't use the "[]" square brackets operator:
Code:
Players[3].Score = 1;
I'd like to have all the functions that work with the DataArray, inside its' class, but I may have to write separate templated functions. Trying to make things easier, ended up being more complex than I thought!
Any advice on what I am trying to accomplish here?