aboutsummaryrefslogtreecommitdiff
path: root/src/utils.h
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils.h')
-rw-r--r--src/utils.h29
1 files changed, 24 insertions, 5 deletions
diff --git a/src/utils.h b/src/utils.h
index 71041a7..005e5be 100644
--- a/src/utils.h
+++ b/src/utils.h
@@ -1,6 +1,7 @@
#pragma once
-#include "json.hpp"
+#include <nlohmann/json.hpp>
#include "entry.h"
+#include "defines.h"
#include <string>
#include <vector>
#include <map>
@@ -9,6 +10,21 @@
#include <stdexcept>
#include <filesystem>
+namespace nlohmann {
+ template <typename T> struct adl_serializer<std::shared_ptr<T>> {
+ static void to_json(json& j, const std::shared_ptr<T>& opt) {
+ if(opt) {
+ j = opt->serialize();
+ } else {
+ j = nullptr;
+ }
+ }
+ static void from_json(const json& j, std::shared_ptr<T>& opt) {
+ opt = std::shared_ptr<T>(T::create(j));
+ }
+ };
+}
+
namespace utils {
nlohmann::json loadJson(const std::filesystem::path& path);
@@ -48,13 +64,17 @@ namespace utils {
int parseInt(const std::string& s);
template<typename S, typename D> std::shared_ptr<S> loadDFromJson(const nlohmann::json& data) {
+ nlohmann::json j = data;
try {
- return std::shared_ptr<S>(new D(loadJson(data["type"], data["name"]), data));
+ j = loadJson(data["type"], data["name"]);
} catch(std::exception& e) {
// Covers errors in building the creature or fs traversal.
// Fall back on the data passed in.
- return std::shared_ptr<S>(new D(data, data));
}
+ D *d = new D();
+ from_json(j, *d);
+ d->init();
+ return std::shared_ptr<S>(d);
}
template<typename F, typename T> std::vector<std::shared_ptr<T>> castPtrs(std::vector<std::shared_ptr<F>> from) {
@@ -109,8 +129,7 @@ namespace utils {
template<typename T> std::vector<std::shared_ptr<T>> instantiateNames(const std::string& type, const std::vector<std::string>& names) {
std::vector<std::shared_ptr<T>> ret;
for(auto name : names) {
- auto j = utils::loadJson(type, name);
- ret.push_back(std::shared_ptr<T>(new T(j, j)));
+ ret.push_back(loadDFromJson<T, T>(utils::loadJson(type, name)));
}
return ret;
}