FeatherMC/src/data/Registry.cpp

90 lines
2.0 KiB
C++

#include "Common.h"
#include "Registry.h"
#include "block/Block.h"
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
namespace Feather
{
IDMapper<BlockState> Registry::BLOCK_STATES;
RegistryMap<Block> Registry::BLOCKS;
void Registry::Init()
{
static bool initialized = false;
if (initialized) return;
Log::Info("Loading data/blocks.json...");
{
using namespace rapidjson;
std::string text;
FILE* fp = fopen("data/blocks.json", "rb");
if (!fp) {
Log::Error("Failed to read data/blocks.json");
return;
}
fseek(fp, 0, SEEK_END);
text.resize(ftell(fp));
rewind(fp);
fread(&text[0], 1, text.size(), fp);
fclose(fp);
Document doc;
doc.Parse(text.c_str());
for (auto& blockData : doc.GetObject())
{
const char* blockName = blockData.name.GetString();
Block block(blockName);
// TODO
//if (blockData.value.HasMember("properties")) {}
//Log::Info("{}: {} states", blockData.name.GetString(), blockData.value["states"].Size());
for (auto& stateData : blockData.value["states"].GetArray())
{
std::string* name = new std::string(blockName);
BlockState state(*name);
if (stateData.HasMember("properties"))
{
for (auto& prop : stateData["properties"].GetObject())
{
std::string* propName = new std::string(prop.name.GetString());
std::string* propValue = new std::string(prop.value.GetString());
state.AddProperty(*propName, *propValue);
}
}
BLOCK_STATES.AddMapping(stateData["id"].GetInt(), state);
}
BLOCKS.Register(block.GetIdentifier(), std::move(block));
}
Log::Info("Loaded {} blocks and {} block states.", BLOCKS.Size(), BLOCK_STATES.Size());
//StringBuffer buf;
//Writer<StringBuffer> writer(buf);
//doc.Accept(writer);
// FIXME: why does this crash
//Log::Info(text);
}
}
}