iw4x-client/src/Components/Modules/StringTable.cpp

99 lines
2.3 KiB
C++
Raw Normal View History

2016-07-11 11:37:36 -04:00
#include "STDInclude.hpp"
namespace Components
{
Utils::Memory::Allocator StringTable::MemAllocator;
std::map<std::string, Game::StringTable*> StringTable::StringTableMap;
int StringTable::Hash(const char* data)
{
int hash = 0;
while (*data != 0)
{
hash = tolower(*data) + (31 * hash);
++data;
}
return hash;
}
Game::StringTable* StringTable::LoadObject(std::string filename)
{
2016-09-04 11:13:06 -04:00
filename = Utils::String::ToLower(filename);
2016-07-11 11:37:36 -04:00
Game::StringTable* table = nullptr;
FileSystem::File rawTable(filename);
if (rawTable.Exists())
{
Utils::CSV parsedTable(rawTable.GetBuffer(), false, false);
table = StringTable::MemAllocator.Allocate<Game::StringTable>();
if (table)
{
table->name = StringTable::MemAllocator.DuplicateString(filename);
table->columnCount = parsedTable.GetColumns();
table->rowCount = parsedTable.GetRows();
table->values = StringTable::MemAllocator.AllocateArray<Game::StringTableCell>(table->columnCount * table->rowCount);
if (!table->values)
{
return nullptr;
}
for (int i = 0; i < table->rowCount; ++i)
{
for (int j = 0; j < table->columnCount; ++j)
{
2016-08-16 07:58:45 -04:00
std::string value = parsedTable.GetElementAt(i, j);
2016-07-11 11:37:36 -04:00
Game::StringTableCell* cell = &table->values[i * table->columnCount + j];
2016-08-16 07:58:45 -04:00
cell->hash = StringTable::Hash(value.data());
cell->string = StringTable::MemAllocator.DuplicateString(value);
2016-07-11 11:37:36 -04:00
//if (!cell->string) cell->string = ""; // We have to assume it allocated successfully
}
}
StringTable::StringTableMap[filename] = table;
}
}
else
{
StringTable::StringTableMap[filename] = nullptr;
}
return table;
}
StringTable::StringTable()
{
AssetHandler::OnFind(Game::XAssetType::ASSET_TYPE_STRINGTABLE, [] (Game::XAssetType, std::string filename)
{
Game::XAssetHeader header = { 0 };
2016-09-04 11:13:06 -04:00
filename = Utils::String::ToLower(filename);
2016-07-11 11:37:36 -04:00
if (StringTable::StringTableMap.find(filename) != StringTable::StringTableMap.end())
{
header.stringTable = StringTable::StringTableMap[filename];
}
else
{
header.stringTable = StringTable::LoadObject(filename);
}
return header;
});
}
StringTable::~StringTable()
{
StringTable::StringTableMap.clear();
2016-07-22 06:52:12 -04:00
StringTable::MemAllocator.Clear();
2016-07-11 11:37:36 -04:00
}
}