Serializer now has a nice register function
This commit is contained in:
62
ecs-serial/include/ecs-serial.h
Normal file
62
ecs-serial/include/ecs-serial.h
Normal file
@@ -0,0 +1,62 @@
|
||||
#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}});
|
||||
}
|
||||
|
||||
void serialize(std::ostream& os, Entity* entity);
|
||||
void deserialize(std::istream& is, Manager& manager);
|
||||
}
|
||||
Reference in New Issue
Block a user