sandbox
Loading...
Searching...
No Matches
component_io.hpp
1// SPDX-License-Identifier: MIT
2#ifndef LIBSBX_SCENES_COMPONENT_IO_HPP_
3#define LIBSBX_SCENES_COMPONENT_IO_HPP_
4
5#include <functional>
6#include <string>
7#include <unordered_map>
8
9#include <yaml-cpp/yaml.h>
10
11#include <libsbx/ecs/registry.hpp>
12
13#include <libsbx/scenes/node.hpp>
14#include <libsbx/scenes/scene_graph.hpp>
15#include <libsbx/scenes/asset_registry.hpp>
16
17namespace sbx::scenes {
18
20
21 std::string name;
22 std::function<void(YAML::Emitter&, scene_graph&, asset_registry&, const node)> save;
23 std::function<void(const YAML::Node&, scene_graph&, asset_registry&, const node)> load;
24
25}; // struct component_io
26
28
29public:
30
31 template<typename Type, std::invocable<YAML::Emitter&, scene_graph&, asset_registry&, const Type&> Save, std::invocable<const YAML::Node&, scene_graph&, asset_registry&> Load>
32 auto register_component(const std::string& name, Save&& save, Load&& load) -> void {
33 const auto id = ecs::type_id<Type>::value();
34
35 _by_name[name] = id;
36
37 _by_id[id] = component_io{
38 .name = name,
39 .save = [s = std::forward<Save>(save)](YAML::Emitter& emitter, scene_graph& graph, asset_registry& registry, const node node) -> void {
40 const auto& component = graph.get_component<Type>(node);
41
42 std::invoke(s, emitter, graph, registry, component);
43 },
44 .load = [l = std::forward<Load>(load)](const YAML::Node& yaml, scene_graph& graph, asset_registry& registry, const node node) -> void {
45 graph.add_or_update_component<Type>(node, std::invoke(l, yaml, graph, registry));
46 }
47 };
48 }
49
50 auto get(const std::uint32_t id) -> component_io& {
51 return _by_id.at(id);
52 }
53
54 auto has(const std::uint32_t id) const -> bool {
55 return _by_id.contains(id);
56 }
57
58 auto get(const std::string& name) -> component_io& {
59 return _by_id.at(_by_name.at(name));
60 }
61
62 auto has(const std::string& name) const -> bool {
63 return _by_name.contains(name);
64 }
65
66private:
67
68 std::unordered_map<std::uint32_t, component_io> _by_id;
69 std::unordered_map<std::string, std::uint32_t> _by_name;
70
71}; // class component_io_registry
72
73} // namespace sbx::scenes
74
75#endif // LIBSBX_SCENES_COMPONENT_IO_HPP_
Definition: tests.cpp:6
Definition: asset_registry.hpp:81
Definition: component_io.hpp:27
Definition: id.hpp:9
Definition: scene_graph.hpp:32
Definition: component_io.hpp:19
static auto value() noexcept -> std::uint32_t
Generates a unique ID for the type.
Definition: type_id.hpp:41