From ee635b7f174f1a954994426153ca514dbf28552f Mon Sep 17 00:00:00 2001 From: Orange Date: Sun, 18 Aug 2024 11:04:24 +0300 Subject: [PATCH] added serialization --- include/omath/pathfinding/NavigationMesh.h | 5 +- source/pathfinding/NavigationMesh.cpp | 60 ++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/include/omath/pathfinding/NavigationMesh.h b/include/omath/pathfinding/NavigationMesh.h index f786501..a3194f2 100644 --- a/include/omath/pathfinding/NavigationMesh.h +++ b/include/omath/pathfinding/NavigationMesh.h @@ -30,8 +30,9 @@ namespace omath::pathfinding [[nodiscard]] const std::vector& GetNeighbors(const Vector3& vertex) const; - std::list m_vertexes; - + [[nodiscard]] std::vector Serialize() const; + void Deserialize(const std::vector& raw); + std::unordered_map> m_verTextMap; }; } \ No newline at end of file diff --git a/source/pathfinding/NavigationMesh.cpp b/source/pathfinding/NavigationMesh.cpp index 55de0f0..39ba6fb 100644 --- a/source/pathfinding/NavigationMesh.cpp +++ b/source/pathfinding/NavigationMesh.cpp @@ -3,6 +3,8 @@ // #include "omath/pathfinding/NavigationMesh.h" +#include + namespace omath::pathfinding { std::expected NavigationMesh::GetClossestVertex(const Vector3 &point) const @@ -23,4 +25,62 @@ namespace omath::pathfinding { return m_verTextMap.at(vertex); } + + std::vector NavigationMesh::Serialize() const + { + auto dumpToVector =[](const T& t, std::vector& vec){ + for (size_t i = 0; i < sizeof(t); i++) + vec.push_back(*(reinterpret_cast(&t)+i)); + }; + + std::vector raw; + + + for (const auto& [vertex, neighbors] : m_verTextMap) + { + const uint16_t neighborsCount = neighbors.size(); + + dumpToVector(vertex, raw); + dumpToVector(neighborsCount, raw); + + for (const auto& neighbor : neighbors) + dumpToVector(neighbor, raw); + } + return raw; + + } + + void NavigationMesh::Deserialize(const std::vector &raw) + { + auto loadFromVector = [](const std::vector& vec, size_t& offset, auto& value) { + if (offset + sizeof(value) > vec.size()) { + throw std::runtime_error("Deserialize: Invalid input data size."); + } + std::memcpy(&value, vec.data() + offset, sizeof(value)); + offset += sizeof(value); + }; + + m_verTextMap.clear(); + + size_t offset = 0; + + while (offset < raw.size()) { + Vector3 vertex; + loadFromVector(raw, offset, vertex); + + uint16_t neighborsCount; + loadFromVector(raw, offset, neighborsCount); + + std::vector neighbors; + neighbors.reserve(neighborsCount); + + for (size_t i = 0; i < neighborsCount; ++i) { + Vector3 neighbor; + loadFromVector(raw, offset, neighbor); + neighbors.push_back(neighbor); + } + + m_verTextMap.emplace(vertex, std::move(neighbors)); + } + } }