From 519adcae3a6f5f1f7d3e0ff267be87af3677cbb4 Mon Sep 17 00:00:00 2001 From: lisyarus Date: Sun, 13 Sep 2020 11:07:59 +0300 Subject: [PATCH] Add voronoi map generator --- libs/pcg/include/psemek/pcg/voronoi.hpp | 29 ++++++++++++++++ libs/pcg/source/voronoi.cpp | 46 +++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 libs/pcg/include/psemek/pcg/voronoi.hpp create mode 100644 libs/pcg/source/voronoi.cpp diff --git a/libs/pcg/include/psemek/pcg/voronoi.hpp b/libs/pcg/include/psemek/pcg/voronoi.hpp new file mode 100644 index 00000000..6a57cc37 --- /dev/null +++ b/libs/pcg/include/psemek/pcg/voronoi.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include + +#include + +namespace psemek::pcg +{ + + struct voronoi + { + voronoi(std::vector> points); + voronoi(std::vector> points, seamless_tag); + + struct result_type + { + std::size_t index; + float distance; + }; + + result_type operator()(float x, float y) const; + + private: + std::vector> points_; + bool seamless_ = false; + }; + +} diff --git a/libs/pcg/source/voronoi.cpp b/libs/pcg/source/voronoi.cpp new file mode 100644 index 00000000..42553c19 --- /dev/null +++ b/libs/pcg/source/voronoi.cpp @@ -0,0 +1,46 @@ +#include + +namespace psemek::pcg +{ + + voronoi::voronoi(std::vector> points) + : points_(std::move(points)) + , seamless_{false} + {} + + voronoi::voronoi(std::vector> points, seamless_tag) + : points_(std::move(points)) + , seamless_{true} + {} + + voronoi::result_type voronoi::operator()(float x, float y) const + { + float v = std::numeric_limits::infinity(); + std::size_t index = 0; + + for (std::size_t i = 0; i < points_.size(); ++i) + { + auto const & p = points_[i]; + + float dx = std::abs(p[0] - x); + float dy = std::abs(p[1] - y); + + if (seamless_) + { + dx = std::min(dx, 1.f - dx); + dy = std::min(dy, 1.f - dy); + } + + float const d = std::sqrt(dx * dx + dy * dy); + + if (d < v) + { + v = d; + index = i; + } + } + + return {index, v}; + } + +}