rename 'files' to 'io'

This commit is contained in:
MihailRis
2025-01-30 16:53:52 +03:00
parent e5d558d357
commit 1e22882284
45 changed files with 157 additions and 160 deletions
+340
View File
@@ -0,0 +1,340 @@
#include "engine_paths.hpp"
#include <algorithm>
#include <array>
#include <filesystem>
#include <sstream>
#include <stack>
#include "typedefs.hpp"
#include "util/stringutil.hpp"
#include <utility>
#include "world/files/WorldFiles.hpp"
#include "debug/Logger.hpp"
static debug::Logger logger("engine-paths");
static inline auto SCREENSHOTS_FOLDER = std::filesystem::u8path("screenshots");
static inline auto CONTENT_FOLDER = std::filesystem::u8path("content");
static inline auto WORLDS_FOLDER = std::filesystem::u8path("worlds");
static inline auto CONFIG_FOLDER = std::filesystem::u8path("config");
static inline auto EXPORT_FOLDER = std::filesystem::u8path("export");
static inline auto CONTROLS_FILE = std::filesystem::u8path("controls.toml");
static inline auto SETTINGS_FILE = std::filesystem::u8path("settings.toml");
static std::filesystem::path toCanonic(std::filesystem::path path) {
std::stack<std::string> parts;
path = path.lexically_normal();
do {
parts.push(path.filename().u8string());
path = path.parent_path();
} while (!path.empty());
path = fs::u8path("");
while (!parts.empty()) {
const std::string part = parts.top();
parts.pop();
if (part == ".") {
continue;
}
if (part == "..") {
throw files_access_error("entry point reached");
}
path = path / std::filesystem::path(part);
}
return path;
}
void EnginePaths::prepare() {
if (!fs::is_directory(resourcesFolder)) {
throw std::runtime_error(
resourcesFolder.u8string() + " is not a directory"
);
}
if (!fs::is_directory(userFilesFolder)) {
fs::create_directories(userFilesFolder);
}
logger.info() << "resources folder: " << fs::canonical(resourcesFolder).u8string();
logger.info() << "user files folder: " << fs::canonical(userFilesFolder).u8string();
auto contentFolder = userFilesFolder / CONTENT_FOLDER;
if (!fs::is_directory(contentFolder)) {
fs::create_directories(contentFolder);
}
auto exportFolder = userFilesFolder / EXPORT_FOLDER;
if (!fs::is_directory(exportFolder)) {
fs::create_directories(exportFolder);
}
auto configFolder = userFilesFolder / CONFIG_FOLDER;
if (!fs::is_directory(configFolder)) {
fs::create_directories(configFolder);
}
}
std::filesystem::path EnginePaths::getUserFilesFolder() const {
return userFilesFolder;
}
std::filesystem::path EnginePaths::getResourcesFolder() const {
return resourcesFolder;
}
std::filesystem::path EnginePaths::getNewScreenshotFile(const std::string& ext) {
auto folder = userFilesFolder / SCREENSHOTS_FOLDER;
if (!fs::is_directory(folder)) {
fs::create_directory(folder);
}
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
const char* format = "%Y-%m-%d_%H-%M-%S";
std::stringstream ss;
ss << std::put_time(&tm, format);
std::string datetimestr = ss.str();
auto filename = folder / fs::u8path("screenshot-" + datetimestr + "." + ext);
uint index = 0;
while (fs::exists(filename)) {
filename = folder / fs::u8path(
"screenshot-" + datetimestr + "-" +
std::to_string(index) + "." + ext
);
index++;
}
return filename;
}
std::filesystem::path EnginePaths::getWorldsFolder() const {
return userFilesFolder / WORLDS_FOLDER;
}
std::filesystem::path EnginePaths::getConfigFolder() const {
return userFilesFolder / CONFIG_FOLDER;
}
std::filesystem::path EnginePaths::getCurrentWorldFolder() {
return currentWorldFolder;
}
std::filesystem::path EnginePaths::getWorldFolderByName(const std::string& name) {
return getWorldsFolder() / std::filesystem::path(name);
}
std::filesystem::path EnginePaths::getControlsFile() const {
return userFilesFolder / CONTROLS_FILE;
}
std::filesystem::path EnginePaths::getSettingsFile() const {
return userFilesFolder / SETTINGS_FILE;
}
std::vector<std::filesystem::path> EnginePaths::scanForWorlds() const {
std::vector<std::filesystem::path> folders;
auto folder = getWorldsFolder();
if (!fs::is_directory(folder)) return folders;
for (const auto& entry : fs::directory_iterator(folder)) {
if (!entry.is_directory()) {
continue;
}
const auto& worldFolder = entry.path();
auto worldFile = worldFolder / fs::u8path(WorldFiles::WORLD_FILE);
if (!fs::is_regular_file(worldFile)) {
continue;
}
folders.push_back(worldFolder);
}
std::sort(
folders.begin(),
folders.end(),
[](std::filesystem::path a, std::filesystem::path b) {
a = a / fs::u8path(WorldFiles::WORLD_FILE);
b = b / fs::u8path(WorldFiles::WORLD_FILE);
return fs::last_write_time(a) > fs::last_write_time(b);
}
);
return folders;
}
void EnginePaths::setUserFilesFolder(std::filesystem::path folder) {
this->userFilesFolder = std::move(folder);
}
void EnginePaths::setResourcesFolder(std::filesystem::path folder) {
this->resourcesFolder = std::move(folder);
}
void EnginePaths::setScriptFolder(std::filesystem::path folder) {
this->scriptFolder = std::move(folder);
}
void EnginePaths::setCurrentWorldFolder(std::filesystem::path folder) {
this->currentWorldFolder = std::move(folder);
}
void EnginePaths::setContentPacks(std::vector<ContentPack>* contentPacks) {
this->contentPacks = contentPacks;
}
std::tuple<std::string, std::string> EnginePaths::parsePath(std::string_view path) {
size_t separator = path.find(':');
if (separator == std::string::npos) {
return {"", std::string(path)};
}
auto prefix = std::string(path.substr(0, separator));
auto filename = std::string(path.substr(separator + 1));
return {prefix, filename};
}
std::filesystem::path EnginePaths::resolve(
const std::string& path, bool throwErr
) const {
auto [prefix, filename] = EnginePaths::parsePath(path);
if (prefix.empty()) {
throw files_access_error("no entry point specified");
}
filename = toCanonic(fs::u8path(filename)).u8string();
if (prefix == "res" || prefix == "core") {
return resourcesFolder / fs::u8path(filename);
}
if (prefix == "user") {
return userFilesFolder / fs::u8path(filename);
}
if (prefix == "config") {
return getConfigFolder() / fs::u8path(filename);
}
if (prefix == "world") {
return currentWorldFolder / fs::u8path(filename);
}
if (prefix == "export") {
return userFilesFolder / EXPORT_FOLDER / fs::u8path(filename);
}
if (prefix == "script" && scriptFolder) {
return scriptFolder.value() / fs::u8path(filename);
}
if (contentPacks) {
for (auto& pack : *contentPacks) {
if (pack.id == prefix) {
return pack.folder / fs::u8path(filename);
}
}
}
if (throwErr) {
throw files_access_error("unknown entry point '" + prefix + "'");
}
return std::filesystem::path(filename);
}
ResPaths::ResPaths(std::filesystem::path mainRoot, std::vector<PathsRoot> roots)
: mainRoot(std::move(mainRoot)), roots(std::move(roots)) {
}
std::filesystem::path ResPaths::find(const std::string& filename) const {
for (int i = roots.size() - 1; i >= 0; i--) {
auto& root = roots[i];
auto file = root.path / fs::u8path(filename);
if (fs::exists(file)) {
return file;
}
}
return mainRoot / fs::u8path(filename);
}
std::string ResPaths::findRaw(const std::string& filename) const {
for (int i = roots.size() - 1; i >= 0; i--) {
auto& root = roots[i];
if (fs::exists(root.path / std::filesystem::path(filename))) {
return root.name + ":" + filename;
}
}
throw std::runtime_error("could not to find file " + util::quote(filename));
}
std::vector<std::string> ResPaths::listdirRaw(const std::string& folderName) const {
std::vector<std::string> entries;
for (int i = roots.size() - 1; i >= 0; i--) {
auto& root = roots[i];
auto folder = root.path / fs::u8path(folderName);
if (!fs::is_directory(folder)) continue;
for (const auto& entry : fs::directory_iterator(folder)) {
auto name = entry.path().filename().u8string();
entries.emplace_back(root.name + ":" + folderName + "/" + name);
}
}
return entries;
}
std::vector<std::filesystem::path> ResPaths::listdir(
const std::string& folderName
) const {
std::vector<std::filesystem::path> entries;
for (int i = roots.size() - 1; i >= 0; i--) {
auto& root = roots[i];
std::filesystem::path folder = root.path / fs::u8path(folderName);
if (!fs::is_directory(folder)) continue;
for (const auto& entry : fs::directory_iterator(folder)) {
entries.push_back(entry.path());
}
}
return entries;
}
dv::value ResPaths::readCombinedList(const std::string& filename) const {
dv::value list = dv::list();
for (const auto& root : roots) {
auto path = root.path / fs::u8path(filename);
if (!fs::exists(path)) {
continue;
}
try {
auto value = io::read_object(path);
if (!value.isList()) {
logger.warning() << "reading combined list " << root.name << ":"
<< filename << " is not a list (skipped)";
continue;
}
for (const auto& elem : value) {
list.add(elem);
}
} catch (const std::runtime_error& err) {
logger.warning() << "reading combined list " << root.name << ":"
<< filename << ": " << err.what();
}
}
return list;
}
dv::value ResPaths::readCombinedObject(const std::string& filename) const {
dv::value object = dv::object();
for (const auto& root : roots) {
auto path = root.path / fs::u8path(filename);
if (!fs::exists(path)) {
continue;
}
try {
auto value = io::read_object(path);
if (!value.isObject()) {
logger.warning()
<< "reading combined object " << root.name << ": "
<< filename << " is not an object (skipped)";
}
for (const auto& [key, element] : value.asObject()) {
object[key] = element;
}
} catch (const std::runtime_error& err) {
logger.warning() << "reading combined object " << root.name << ":"
<< filename << ": " << err.what();
}
}
return object;
}
const std::filesystem::path& ResPaths::getMainRoot() const {
return mainRoot;
}
+87
View File
@@ -0,0 +1,87 @@
#pragma once
#include <filesystem>
#include <stdexcept>
#include <optional>
#include <string>
#include <vector>
#include <tuple>
#include "data/dv.hpp"
#include "content/ContentPack.hpp"
class files_access_error : public std::runtime_error {
public:
files_access_error(const std::string& msg) : std::runtime_error(msg) {
}
};
class EnginePaths {
public:
void prepare();
void setUserFilesFolder(std::filesystem::path folder);
std::filesystem::path getUserFilesFolder() const;
void setResourcesFolder(std::filesystem::path folder);
std::filesystem::path getResourcesFolder() const;
void setScriptFolder(std::filesystem::path folder);
std::filesystem::path getWorldFolderByName(const std::string& name);
std::filesystem::path getWorldsFolder() const;
std::filesystem::path getConfigFolder() const;
void setCurrentWorldFolder(std::filesystem::path folder);
std::filesystem::path getCurrentWorldFolder();
std::filesystem::path getNewScreenshotFile(const std::string& ext);
std::filesystem::path getControlsFile() const;
std::filesystem::path getSettingsFile() const;
void setContentPacks(std::vector<ContentPack>* contentPacks);
std::vector<std::filesystem::path> scanForWorlds() const;
std::filesystem::path resolve(const std::string& path, bool throwErr = true) const;
static std::tuple<std::string, std::string> parsePath(std::string_view view);
static inline auto CONFIG_DEFAULTS =
std::filesystem::u8path("config/defaults.toml");
private:
std::filesystem::path userFilesFolder {"."};
std::filesystem::path resourcesFolder {"res"};
std::filesystem::path currentWorldFolder;
std::optional<std::filesystem::path> scriptFolder;
std::vector<ContentPack>* contentPacks = nullptr;
};
struct PathsRoot {
std::string name;
std::filesystem::path path;
};
class ResPaths {
public:
ResPaths(std::filesystem::path mainRoot, std::vector<PathsRoot> roots);
std::filesystem::path find(const std::string& filename) const;
std::string findRaw(const std::string& filename) const;
std::vector<std::filesystem::path> listdir(const std::string& folder) const;
std::vector<std::string> listdirRaw(const std::string& folder) const;
/// @brief Read all found list versions from all packs and combine into a
/// single list. Invalid versions will be skipped with logging a warning
/// @param file *.json file path relative to entry point
dv::value readCombinedList(const std::string& file) const;
dv::value readCombinedObject(const std::string& file) const;
const std::filesystem::path& getMainRoot() const;
private:
std::filesystem::path mainRoot;
std::vector<PathsRoot> roots;
};
+199
View File
@@ -0,0 +1,199 @@
#include "io.hpp"
#include <stdint.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
#include "coders/commons.hpp"
#include "coders/gzip.hpp"
#include "coders/json.hpp"
#include "coders/toml.hpp"
#include "util/stringutil.hpp"
namespace fs = std::filesystem;
io::rafile::rafile(const fs::path& filename)
: file(filename, std::ios::binary | std::ios::ate) {
if (!file) {
throw std::runtime_error("could not to open file " + filename.string());
}
filelength = file.tellg();
file.seekg(0);
}
size_t io::rafile::length() const {
return filelength;
}
void io::rafile::seekg(std::streampos pos) {
file.seekg(pos);
}
void io::rafile::read(char* buffer, std::streamsize size) {
file.read(buffer, size);
}
bool io::write_bytes(
const fs::path& filename, const ubyte* data, size_t size
) {
std::ofstream output(filename, std::ios::binary);
if (!output.is_open()) return false;
output.write((const char*)data, size);
output.close();
return true;
}
uint io::append_bytes(
const fs::path& filename, const ubyte* data, size_t size
) {
std::ofstream output(filename, std::ios::binary | std::ios::app);
if (!output.is_open()) return 0;
uint position = output.tellp();
output.write((const char*)data, size);
output.close();
return position;
}
bool io::read(const fs::path& filename, char* data, size_t size) {
std::ifstream output(filename, std::ios::binary);
if (!output.is_open()) return false;
output.read(data, size);
output.close();
return true;
}
util::Buffer<ubyte> io::read_bytes_buffer(const fs::path& path) {
size_t size;
auto bytes = io::read_bytes(path, size);
return util::Buffer<ubyte>(std::move(bytes), size);
}
std::unique_ptr<ubyte[]> io::read_bytes(
const fs::path& filename, size_t& length
) {
std::ifstream input(filename, std::ios::binary);
if (!input.is_open()) {
throw std::runtime_error(
"could not to load file '" + filename.string() + "'"
);
}
input.seekg(0, std::ios_base::end);
length = input.tellg();
input.seekg(0, std::ios_base::beg);
auto data = std::make_unique<ubyte[]>(length);
input.read((char*)data.get(), length);
input.close();
return data;
}
std::vector<ubyte> io::read_bytes(const fs::path& filename) {
std::ifstream input(filename, std::ios::binary);
if (!input.is_open()) return {};
input.seekg(0, std::ios_base::end);
size_t length = input.tellg();
input.seekg(0, std::ios_base::beg);
std::vector<ubyte> data(length);
data.resize(length);
input.read((char*)data.data(), length);
input.close();
return data;
}
std::string io::read_string(const fs::path& filename) {
size_t size;
auto bytes = read_bytes(filename, size);
return std::string((const char*)bytes.get(), size);
}
bool io::write_string(const fs::path& filename, std::string_view content) {
std::ofstream file(filename);
if (!file) {
return false;
}
file << content;
return true;
}
bool io::write_json(
const fs::path& filename, const dv::value& obj, bool nice
) {
return io::write_string(filename, json::stringify(obj, nice, " "));
}
bool io::write_binary_json(
const fs::path& filename, const dv::value& obj, bool compression
) {
auto bytes = json::to_binary(obj, compression);
return io::write_bytes(filename, bytes.data(), bytes.size());
}
dv::value io::read_json(const fs::path& filename) {
std::string text = io::read_string(filename);
return json::parse(filename.string(), text);
}
dv::value io::read_binary_json(const fs::path& file) {
size_t size;
auto bytes = io::read_bytes(file, size);
return json::from_binary(bytes.get(), size);
}
dv::value io::read_toml(const fs::path& file) {
return toml::parse(file.u8string(), io::read_string(file));
}
std::vector<std::string> io::read_list(const fs::path& filename) {
std::ifstream file(filename);
if (!file) {
throw std::runtime_error(
"could not to open file " + filename.u8string()
);
}
std::vector<std::string> lines;
std::string line;
while (std::getline(file, line)) {
util::trim(line);
if (line.length() == 0) continue;
if (line[0] == '#') continue;
lines.push_back(line);
}
return lines;
}
#include <map>
#include "coders/json.hpp"
#include "coders/toml.hpp"
using DecodeFunc = dv::value(*)(std::string_view, std::string_view);
static std::map<fs::path, DecodeFunc> data_decoders {
{fs::u8path(".json"), json::parse},
{fs::u8path(".toml"), toml::parse},
};
bool io::is_data_file(const fs::path& file) {
return is_data_interchange_format(file.extension());
}
bool io::is_data_interchange_format(const fs::path& ext) {
return data_decoders.find(ext) != data_decoders.end();
}
dv::value io::read_object(const fs::path& file) {
const auto& found = data_decoders.find(file.extension());
if (found == data_decoders.end()) {
throw std::runtime_error("unknown file format");
}
auto text = read_string(file);
try {
return found->second(file.u8string(), text);
} catch (const parsing_error& err) {
throw std::runtime_error(err.errorLog());
}
}
+80
View File
@@ -0,0 +1,80 @@
#pragma once
#include <filesystem>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
#include "typedefs.hpp"
#include "data/dv.hpp"
#include "util/Buffer.hpp"
namespace fs = std::filesystem;
namespace io {
/// @brief Read-only random access file
class rafile {
std::ifstream file;
size_t filelength;
public:
rafile(const fs::path& filename);
void seekg(std::streampos pos);
void read(char* buffer, std::streamsize size);
size_t length() const;
};
/// @brief Write bytes array to the file without any extra data
/// @param file target file
/// @param data data bytes array
/// @param size size of data bytes array
bool write_bytes(const fs::path& file, const ubyte* data, size_t size);
/// @brief Append bytes array to the file without any extra data
/// @param file target file
/// @param data data bytes array
/// @param size size of data bytes array
uint append_bytes(const fs::path& file, const ubyte* data, size_t size);
/// @brief Write string to the file
bool write_string(const fs::path& filename, std::string_view content);
/// @brief Write dynamic data to the JSON file
/// @param nice if true, human readable format will be used, otherwise
/// minimal
bool write_json(
const fs::path& filename, const dv::value& obj, bool nice = true
);
/// @brief Write dynamic data to the binary JSON file
/// (see src/coders/binary_json_spec.md)
/// @param compressed use gzip compression
bool write_binary_json(
const fs::path& filename,
const dv::value& obj,
bool compressed = false
);
bool read(const fs::path&, char* data, size_t size);
util::Buffer<ubyte> read_bytes_buffer(const fs::path&);
std::unique_ptr<ubyte[]> read_bytes(const fs::path&, size_t& length);
std::vector<ubyte> read_bytes(const fs::path&);
std::string read_string(const fs::path& filename);
/// @brief Read JSON or BJSON file
/// @param file *.json or *.bjson file
dv::value read_json(const fs::path& file);
dv::value read_binary_json(const fs::path& file);
/// @brief Read TOML file
/// @param file *.toml file
dv::value read_toml(const fs::path& file);
std::vector<std::string> read_list(const fs::path& file);
bool is_data_file(const fs::path& file);
bool is_data_interchange_format(const fs::path& ext);
dv::value read_object(const fs::path& file);
}
+210
View File
@@ -0,0 +1,210 @@
#include "settings_io.hpp"
#include <memory>
#include <utility>
#include "coders/json.hpp"
#include "coders/toml.hpp"
#include "debug/Logger.hpp"
#include "settings.hpp"
#include "window/Events.hpp"
#include "window/input.hpp"
static debug::Logger logger("settings_io");
struct SectionsBuilder {
std::unordered_map<std::string, Setting*>& map;
std::vector<Section>& sections;
SectionsBuilder(
std::unordered_map<std::string, Setting*>& map,
std::vector<Section>& sections
)
: map(map), sections(sections) {
}
void section(std::string name) {
sections.push_back(Section {std::move(name), {}});
}
void add(const std::string& name, Setting* setting, bool writeable = true) {
Section& section = sections.at(sections.size() - 1);
map[section.name + "." + name] = setting;
section.keys.push_back(name);
}
};
SettingsHandler::SettingsHandler(EngineSettings& settings) {
SectionsBuilder builder(map, sections);
builder.section("audio");
builder.add("enabled", &settings.audio.enabled, false);
builder.add("volume-master", &settings.audio.volumeMaster);
builder.add("volume-regular", &settings.audio.volumeRegular);
builder.add("volume-ui", &settings.audio.volumeUI);
builder.add("volume-ambient", &settings.audio.volumeAmbient);
builder.add("volume-music", &settings.audio.volumeMusic);
builder.section("display");
builder.add("width", &settings.display.width);
builder.add("height", &settings.display.height);
builder.add("samples", &settings.display.samples);
builder.add("framerate", &settings.display.framerate);
builder.add("fullscreen", &settings.display.fullscreen);
builder.add("limit-fps-iconified", &settings.display.limitFpsIconified);
builder.section("camera");
builder.add("sensitivity", &settings.camera.sensitivity);
builder.add("fov", &settings.camera.fov);
builder.add("fov-effects", &settings.camera.fovEffects);
builder.add("shaking", &settings.camera.shaking);
builder.add("inertia", &settings.camera.inertia);
builder.section("chunks");
builder.add("load-distance", &settings.chunks.loadDistance);
builder.add("load-speed", &settings.chunks.loadSpeed);
builder.add("padding", &settings.chunks.padding);
builder.section("graphics");
builder.add("fog-curve", &settings.graphics.fogCurve);
builder.add("backlight", &settings.graphics.backlight);
builder.add("dense-render", &settings.graphics.denseRender);
builder.add("gamma", &settings.graphics.gamma);
builder.add("frustum-culling", &settings.graphics.frustumCulling);
builder.add("skybox-resolution", &settings.graphics.skyboxResolution);
builder.add("chunk-max-vertices", &settings.graphics.chunkMaxVertices);
builder.add("chunk-max-vertices-dense", &settings.graphics.chunkMaxVerticesDense);
builder.add("chunk-max-renderers", &settings.graphics.chunkMaxRenderers);
builder.section("ui");
builder.add("language", &settings.ui.language);
builder.add("world-preview-size", &settings.ui.worldPreviewSize);
builder.section("debug");
builder.add("generator-test-mode", &settings.debug.generatorTestMode);
builder.add("do-write-lights", &settings.debug.doWriteLights);
}
dv::value SettingsHandler::getValue(const std::string& name) const {
auto found = map.find(name);
if (found == map.end()) {
throw std::runtime_error("setting '" + name + "' does not exist");
}
auto setting = found->second;
if (auto number = dynamic_cast<NumberSetting*>(setting)) {
return static_cast<number_t>(number->get());
} else if (auto integer = dynamic_cast<IntegerSetting*>(setting)) {
return static_cast<integer_t>(integer->get());
} else if (auto flag = dynamic_cast<FlagSetting*>(setting)) {
return flag->get();
} else if (auto string = dynamic_cast<StringSetting*>(setting)) {
return string->get();
} else {
throw std::runtime_error("type is not implemented for '" + name + "'");
}
}
dv::value SettingsHandler::getDefault(const std::string& name) const {
auto found = map.find(name);
if (found == map.end()) {
throw std::runtime_error("setting '" + name + "' does not exist");
}
auto setting = found->second;
if (auto number = dynamic_cast<NumberSetting*>(setting)) {
return static_cast<number_t>(number->getDefault());
} else if (auto integer = dynamic_cast<IntegerSetting*>(setting)) {
return static_cast<integer_t>(integer->getDefault());
} else if (auto flag = dynamic_cast<FlagSetting*>(setting)) {
return flag->getDefault();
} else if (auto string = dynamic_cast<StringSetting*>(setting)) {
return string->getDefault();
} else {
throw std::runtime_error("type is not implemented for '" + name + "'");
}
}
std::string SettingsHandler::toString(const std::string& name) const {
auto found = map.find(name);
if (found == map.end()) {
throw std::runtime_error("setting '" + name + "' does not exist");
}
auto setting = found->second;
return setting->toString();
}
Setting* SettingsHandler::getSetting(const std::string& name) const {
auto found = map.find(name);
if (found == map.end()) {
throw std::runtime_error("setting '" + name + "' does not exist");
}
return found->second;
}
bool SettingsHandler::has(const std::string& name) const {
return map.find(name) != map.end();
}
template <class T>
static void set_numeric_value(T* setting, const dv::value& value) {
using dv::value_type;
switch (value.getType()) {
case value_type::integer:
setting->set(value.asInteger());
break;
case value_type::number:
setting->set(value.asNumber());
break;
case value_type::boolean:
setting->set(value.asBoolean());
break;
default:
throw std::runtime_error("type error, numeric value expected");
}
}
void SettingsHandler::setValue(
const std::string& name, const dv::value& value
) {
auto found = map.find(name);
if (found == map.end()) {
throw std::runtime_error("setting '" + name + "' does not exist");
}
auto setting = found->second;
if (auto number = dynamic_cast<NumberSetting*>(setting)) {
set_numeric_value(number, value);
} else if (auto integer = dynamic_cast<IntegerSetting*>(setting)) {
set_numeric_value(integer, value);
} else if (auto flag = dynamic_cast<FlagSetting*>(setting)) {
set_numeric_value(flag, value);
} else if (auto string = dynamic_cast<StringSetting*>(setting)) {
using dv::value_type;
switch (value.getType()) {
case value_type::integer:
string->set(std::to_string(value.asInteger()));
break;
case value_type::number:
string->set(std::to_string(value.asNumber()));
break;
case value_type::boolean:
string->set(value.asBoolean() ? "true" : "false");
break;
case value_type::string:
string->set(value.asString());
break;
default:
throw std::runtime_error("not implemented for type");
}
} else {
throw std::runtime_error(
"type is not implement - setting '" + name + "'"
);
}
}
std::vector<Section>& SettingsHandler::getSections() {
return sections;
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "data/dv.hpp"
class Setting;
struct EngineSettings;
struct Section {
std::string name;
std::vector<std::string> keys;
};
class SettingsHandler {
std::unordered_map<std::string, Setting*> map;
std::vector<Section> sections;
public:
SettingsHandler(EngineSettings& settings);
dv::value getValue(const std::string& name) const;
dv::value getDefault(const std::string& name) const;
void setValue(const std::string& name, const dv::value& value);
std::string toString(const std::string& name) const;
Setting* getSetting(const std::string& name) const;
bool has(const std::string& name) const;
std::vector<Section>& getSections();
};
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include <string>
#include <stdexcept>
namespace io {
inline bool is_valid_name(std::string_view name) {
static std::string illegalChars = "\\/%?!<>:; ";
for (char c : illegalChars) {
if (name.find(c) != std::string::npos) {
return false;
}
}
return !name.empty();
}
}