1
0
Fork 0
cuberite-2a/src/WorldStorage/StatisticsSerializer.cpp

95 lines
2.1 KiB
C++
Raw Permalink Normal View History

2014-05-11 11:57:06 +00:00
2021-05-04 15:11:56 +00:00
// StatisticsSerializer.cpp
2014-05-11 11:57:06 +00:00
#include "Globals.h"
2021-05-04 15:11:56 +00:00
#include "StatisticsManager.h"
#include "StatisticsSerializer.h"
#include "NamespaceSerializer.h"
#include <json/json.h>
2014-05-11 11:57:06 +00:00
static auto MakeStatisticsDirectory(const std::string & WorldPath, std::string && FileName)
2014-05-11 11:57:06 +00:00
{
// Even though stats are shared between worlds, they are (usually) saved
// inside the folder of the default world.
2014-05-13 11:53:15 +00:00
// Path to the world's statistics folder.
const auto Path = WorldPath + cFile::GetPathSeparator() + "stats";
2020-08-19 12:09:39 +00:00
// Ensure that the directory exists.
cFile::CreateFolder(Path);
2014-05-11 11:57:06 +00:00
return Path + cFile::GetPathSeparator() + std::move(FileName) + ".json";
}
2014-05-11 11:57:06 +00:00
static void SaveStatToJSON(const StatisticsManager & Manager, Json::Value & a_Out)
{
if (Manager.Custom.empty())
2020-08-20 22:27:08 +00:00
{
// Avoid saving "custom": null to disk:
return;
}
2020-08-20 22:27:08 +00:00
auto & Custom = a_Out["custom"];
for (const auto & [Statistic, Value] : Manager.Custom)
{
Custom[NamespaceSerializer::From(Statistic).data()] = Value;
2020-08-20 22:27:08 +00:00
}
}
2014-05-11 11:57:06 +00:00
static void LoadCustomStatFromJSON(StatisticsManager & Manager, const Json::Value & a_In)
{
for (auto it = a_In.begin(); it != a_In.end(); ++it)
2014-05-11 11:57:06 +00:00
{
const auto & Key = it.key().asString();
const auto & [Namespace, Name] = NamespaceSerializer::SplitNamespacedID(Key);
if (Namespace == NamespaceSerializer::Namespace::Unknown)
2014-05-11 11:57:06 +00:00
{
// Ignore non-Vanilla, non-Cuberite namespaces for now:
continue;
}
Manager.Custom[NamespaceSerializer::ToCustomStatistic(Name)] = it->asUInt();
2020-08-20 22:27:08 +00:00
}
}
2014-05-11 11:57:06 +00:00
void StatisticsSerializer::Load(StatisticsManager & Manager, const std::string & WorldPath, std::string && FileName)
{
Json::Value Root;
InputFileStream(MakeStatisticsDirectory(WorldPath, std::move(FileName))) >> Root;
2020-08-19 12:09:39 +00:00
LoadCustomStatFromJSON(Manager, Root["stats"]["custom"]);
}
2020-08-19 12:09:39 +00:00
void StatisticsSerializer::Save(const StatisticsManager & Manager, const std::string & WorldPath, std::string && FileName)
{
Json::Value Root;
2014-05-11 11:57:06 +00:00
SaveStatToJSON(Manager, Root["stats"]);
Root["DataVersion"] = NamespaceSerializer::DataVersion();
2020-08-20 22:27:08 +00:00
OutputFileStream(MakeStatisticsDirectory(WorldPath, std::move(FileName))) << Root;
2014-05-11 11:57:06 +00:00
}