1
0

Moved ProtocolBlockTypePalette functionality into BlockTypePalette.

This commit is contained in:
Mattes D
2019-12-02 16:45:55 +01:00
parent 2de6b7537d
commit 7453a9fbe1
11 changed files with 268 additions and 404 deletions

View File

@@ -1,5 +1,8 @@
#include "Globals.h"
#include "BlockTypePalette.h"
#include "json/value.h"
#include "json/reader.h"
@@ -113,3 +116,82 @@ std::map<UInt32, UInt32> BlockTypePalette::createTransformMapWithFallback(const
}
return res;
}
void BlockTypePalette::loadFromString(const AString & aString)
{
// TODO: Detect format (Json vs Lua)
return loadFromJsonString(aString);
}
void BlockTypePalette::loadFromJsonString(const AString & aJsonPalette)
{
// Parse the string into JSON object:
Json::Value root;
Json::CharReaderBuilder builder;
std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
std::string errs;
if (!reader->parse(aJsonPalette.data(), aJsonPalette.data() + aJsonPalette.size(), &root, &errs))
{
throw LoadFailedException(errs);
}
// Check the JSON's metadata + version:
if (!root.isObject() ||
!root.isMember("Metadata") ||
!root["Metadata"].isMember("ProtocolBlockTypePaletteVersion") ||
!root.isMember("Palette") ||
!root["Palette"].isArray())
{
throw LoadFailedException("Incorrect palette format, wrong or missing metadata.");
}
auto version = root["Metadata"]["ProtocolBlockTypePaletteVersion"].asUInt();
if (version != 1)
{
throw(Printf("Palette format version %d not supported.", version));
}
// Load the palette:
auto len = root["Palette"].size();
for (decltype(len) i = 0; i < len; ++i)
{
const auto & record = root["Palette"][i];
if (!record.isObject())
{
throw LoadFailedException(Printf("Palette record #%u is not a JSON object.", i));
}
auto blockTypeName = record["name"].asString();
auto id = static_cast<UInt32>(std::stoul(record["id"].asString()));
std::map<AString, AString> state;
if (record.isMember("props"))
{
const auto & props = record["props"];
if (!props.isObject())
{
throw LoadFailedException(Printf("Palette record #%u: \"props\" value is not a JSON object.", i));
}
for (const auto & key: props.getMemberNames())
{
state[key] = props[key].asString();
}
}
BlockState blockState(state);
// Insert / update in the maps:
mNumberToBlock[id] = {blockTypeName, blockState};
mBlockToNumber[blockTypeName][blockState] = id;
if (id > mMaxIndex)
{
mMaxIndex = id;
}
} // for i - Palette[]
}