77 lines
2.1 KiB
C++
77 lines
2.1 KiB
C++
#include <functional>
|
|
#include <ostream>
|
|
#pragma once
|
|
#include "ecs.h"
|
|
|
|
#include "iohelper/write.h"
|
|
#include "iohelper/read.h"
|
|
|
|
#include <iostream>
|
|
|
|
namespace ecs::serial {
|
|
namespace internal {
|
|
extern std::unordered_map<size_t, std::tuple<std::function<void(std::ostream&, ecs::Component*)>, std::function<void(std::istream&, ecs::Component*)>, std::function<ecs::Component*()>>> functions;
|
|
}
|
|
|
|
template <typename T>
|
|
void serialize_member(std::ostream&, T*) {
|
|
// We reached the end
|
|
}
|
|
|
|
template <typename T, typename M, typename... Args>
|
|
void serialize_member(std::ostream& os, T* t, M T::*m, Args... args) {
|
|
iohelper::write<M>(os, t->*m);
|
|
|
|
serialize_member(os, t, args...);
|
|
}
|
|
|
|
template <typename T>
|
|
void deserialize_member(std::istream&, T*) {
|
|
// We reached the end
|
|
}
|
|
|
|
template <typename T, typename M, typename... Args>
|
|
void deserialize_member(std::istream& is, T* t, M T::*m, Args... args) {
|
|
t->*m = iohelper::read<M>(is);
|
|
|
|
deserialize_member(is, t, args...);
|
|
}
|
|
|
|
// @todo Allow for custom serializers and deserializers (maybe for this we do need a difference between update and new)
|
|
template <typename T, typename... Args>
|
|
void register_component(Args... args) {
|
|
// Serialize component
|
|
auto func1 = [args...] (std::ostream& os, ecs::Component* component) {
|
|
T* t = (T*)component;
|
|
serialize_member(os, t, args...);
|
|
};
|
|
|
|
// Deserialize component
|
|
auto func2 = [args...] (std::istream& is, ecs::Component* component) {
|
|
T* t = (T*)component;
|
|
deserialize_member(is, t, args...);
|
|
};
|
|
|
|
auto func3 = [] () -> Component* {
|
|
return new T();
|
|
};
|
|
|
|
internal::functions.insert({ComponentID::id<T>, {func1, func2, func3}});
|
|
}
|
|
|
|
template <typename T>
|
|
void register_component_custom(std::function<void(std::ostream&, ecs::Component*)> func1, std::function<void(std::istream&, Component*)> func2) {
|
|
auto func3 = [] () -> Component* {
|
|
return new T();
|
|
};
|
|
|
|
internal::functions.insert({ComponentID::id<T>, {func1, func2, func3}});
|
|
}
|
|
|
|
void serialize(std::ostream& os, Entity* entity);
|
|
void deserialize(std::istream& is, Manager& manager);
|
|
|
|
void serialize_ids(std::ostream& os);
|
|
void deserialize_ids(std::istream& is);
|
|
}
|