Add voronoi map generator

This commit is contained in:
Nikita Lisitsa 2020-09-13 11:07:59 +03:00
parent 39765c9d26
commit 519adcae3a
2 changed files with 75 additions and 0 deletions

View file

@ -0,0 +1,29 @@
#pragma once
#include <psemek/geom/point.hpp>
#include <psemek/pcg/seamless.hpp>
#include <vector>
namespace psemek::pcg
{
struct voronoi
{
voronoi(std::vector<geom::point<float, 2>> points);
voronoi(std::vector<geom::point<float, 2>> points, seamless_tag);
struct result_type
{
std::size_t index;
float distance;
};
result_type operator()(float x, float y) const;
private:
std::vector<geom::point<float, 2>> points_;
bool seamless_ = false;
};
}

View file

@ -0,0 +1,46 @@
#include <psemek/pcg/voronoi.hpp>
namespace psemek::pcg
{
voronoi::voronoi(std::vector<geom::point<float, 2>> points)
: points_(std::move(points))
, seamless_{false}
{}
voronoi::voronoi(std::vector<geom::point<float, 2>> points, seamless_tag)
: points_(std::move(points))
, seamless_{true}
{}
voronoi::result_type voronoi::operator()(float x, float y) const
{
float v = std::numeric_limits<float>::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};
}
}