Files
aee-arcade/source/game/entities/entity_loader.cpp
T

69 lines
2.4 KiB
C++

#include "game/entities/entity_loader.hpp"
#include <stdexcept>
#include <unordered_map>
#include "core/resources/resource_helper.hpp"
#include "game/entities/entity.hpp"
#include "game/entities/entity_factory.hpp"
#include "game/map/room_yaml.hpp"
#include "utils/defaults.hpp"
namespace EntityLoader {
namespace {
// Cache de plantilles parsejades. La primera crida llegeix disc;
// les següents reben una còpia del node cacheat. fkyaml::node és
// cost-barat de copiar (vector de shared_ptr internament).
auto templateCache() -> std::unordered_map<std::string, fkyaml::node>& {
static std::unordered_map<std::string, fkyaml::node> k_cache_;
return k_cache_;
}
auto templatePath(const std::string& name) -> std::string {
return std::string{Defaults::Paths::ENTITIES_DIR} + name + "/" + name + ".yaml";
}
} // namespace
auto loadTemplate(const std::string& name) -> fkyaml::node {
auto& cache = templateCache();
auto it = cache.find(name);
if (it != cache.end()) { return it->second; }
const auto PATH = templatePath(name);
auto bytes = Resource::Helper::loadFile(PATH);
if (bytes.empty()) {
throw std::runtime_error("EntityLoader: no s'ha pogut obrir " + PATH);
}
const auto* begin = reinterpret_cast<const char*>(bytes.data());
const auto* end = begin + bytes.size();
fkyaml::node node = fkyaml::node::deserialize(begin, end);
cache.emplace(name, node);
return node;
}
auto readSpawns(const std::string& level_yaml_path) -> std::vector<fkyaml::node> {
fkyaml::node root = RoomYaml::loadMerged(level_yaml_path);
std::vector<fkyaml::node> spawns;
if (!root.contains("entities")) { return spawns; }
const auto& list = root["entities"];
if (!list.is_sequence()) { return spawns; }
spawns.reserve(list.size());
// cppcheck-suppress useStlAlgorithm
for (const auto& item : list) { spawns.push_back(item); }
return spawns;
}
auto createByType(const std::string& type) -> std::unique_ptr<Entity> {
try {
fkyaml::node tmpl = loadTemplate(type);
return EntityFactory::instance().create(type, tmpl);
} catch (const std::exception&) {
return nullptr;
}
}
} // namespace EntityLoader