first commit
This commit is contained in:
82
src/attachment.cpp
Normal file
82
src/attachment.cpp
Normal file
@@ -0,0 +1,82 @@
|
||||
#include "voronoi_route/attachment.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <queue>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "voronoi_route/voronoi_field.h"
|
||||
#include "voronoi_route/voronoi_graph.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
constexpr int kDx[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
|
||||
constexpr int kDy[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
|
||||
} // namespace
|
||||
|
||||
Attachment attachPoint(const VoronoiField& field, const VoronoiGraph& graph, Cell from,
|
||||
int max_radius_cells)
|
||||
{
|
||||
Attachment out;
|
||||
if (!field.ready() || graph.empty() || !field.inBounds(from.x, from.y)) return out;
|
||||
|
||||
// Already on the graph.
|
||||
if (graph.edgeAt(from.x, from.y) >= 0)
|
||||
{
|
||||
out.ok = true;
|
||||
out.edge = graph.edgeAt(from.x, from.y);
|
||||
out.index = graph.indexOnEdge(from.x, from.y);
|
||||
out.path = {from};
|
||||
return out;
|
||||
}
|
||||
|
||||
// Parent map keyed by linear index; a full-grid array would cost 4M entries per query.
|
||||
const int w = field.sizeX();
|
||||
auto key = [w](const Cell& c) { return static_cast<long long>(c.y) * w + c.x; };
|
||||
std::unordered_map<long long, long long> parent;
|
||||
std::queue<Cell> q;
|
||||
parent[key(from)] = -1;
|
||||
q.push(from);
|
||||
|
||||
Cell hit;
|
||||
bool found = false;
|
||||
while (!q.empty())
|
||||
{
|
||||
const Cell c = q.front();
|
||||
q.pop();
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const Cell n(c.x + kDx[k], c.y + kDy[k]);
|
||||
if (!field.inBounds(n.x, n.y)) continue;
|
||||
if (std::abs(n.x - from.x) > max_radius_cells || std::abs(n.y - from.y) > max_radius_cells)
|
||||
continue;
|
||||
if (field.isOccupied(n.x, n.y)) continue;
|
||||
const long long nk = key(n);
|
||||
if (parent.count(nk)) continue;
|
||||
parent[nk] = key(c);
|
||||
if (graph.edgeAt(n.x, n.y) >= 0)
|
||||
{
|
||||
hit = n;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
q.push(n);
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
if (!found) return out;
|
||||
|
||||
Polyline rev;
|
||||
for (long long k = key(hit); k != -1; k = parent[k])
|
||||
rev.push_back(Cell(static_cast<int>(k % w), static_cast<int>(k / w)));
|
||||
std::reverse(rev.begin(), rev.end());
|
||||
|
||||
out.ok = true;
|
||||
out.edge = graph.edgeAt(hit.x, hit.y);
|
||||
out.index = graph.indexOnEdge(hit.x, hit.y);
|
||||
out.path = std::move(rev);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
235
src/bundle_io.cpp
Normal file
235
src/bundle_io.cpp
Normal file
@@ -0,0 +1,235 @@
|
||||
#include "voronoi_route/bundle_io.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
bool ensureDir(const std::string& dir)
|
||||
{
|
||||
// mkdir -p: the bundle dir normally sits inside a map folder that already exists, but a tool
|
||||
// pointed at a fresh --out must not fail on the parent.
|
||||
std::string cur;
|
||||
for (size_t i = 0; i <= dir.size(); ++i)
|
||||
{
|
||||
if (i < dir.size() && dir[i] != '/') continue;
|
||||
cur = dir.substr(0, i);
|
||||
if (cur.empty()) continue;
|
||||
struct stat st;
|
||||
if (::stat(cur.c_str(), &st) == 0)
|
||||
{
|
||||
if (!S_ISDIR(st.st_mode)) return false;
|
||||
continue;
|
||||
}
|
||||
if (::mkdir(cur.c_str(), 0775) != 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string hexOf(uint64_t v)
|
||||
{
|
||||
std::ostringstream o;
|
||||
o << std::hex << std::setw(16) << std::setfill('0') << v;
|
||||
return o.str();
|
||||
}
|
||||
|
||||
bool parseHex(const std::string& s, uint64_t* out)
|
||||
{
|
||||
if (s.empty() || !out) return false;
|
||||
char* end = nullptr;
|
||||
const unsigned long long v = std::strtoull(s.c_str(), &end, 16);
|
||||
if (end == nullptr || *end != '\0') return false;
|
||||
*out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool writePgm8(const std::string& path, const std::vector<uint8_t>& data, int w, int h)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f) return false;
|
||||
f << "P5\n" << w << " " << h << "\n255\n";
|
||||
f.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
|
||||
return static_cast<bool>(f);
|
||||
}
|
||||
|
||||
bool writePgm16(const std::string& path, const std::vector<uint16_t>& data, int w, int h)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f) return false;
|
||||
f << "P5\n" << w << " " << h << "\n65535\n";
|
||||
std::vector<uint8_t> be(data.size() * 2);
|
||||
for (size_t i = 0; i < data.size(); ++i)
|
||||
{
|
||||
be[2 * i] = static_cast<uint8_t>(data[i] >> 8);
|
||||
be[2 * i + 1] = static_cast<uint8_t>(data[i] & 0xFF);
|
||||
}
|
||||
f.write(reinterpret_cast<const char*>(be.data()), static_cast<std::streamsize>(be.size()));
|
||||
return static_cast<bool>(f);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool saveBundle(const VoronoiRoute& vr, const BundleMeta& meta, const std::string& dir,
|
||||
bool with_gvd, bool with_dist, std::string* err)
|
||||
{
|
||||
if (!vr.ready())
|
||||
{
|
||||
if (err) *err = "graph not built";
|
||||
return false;
|
||||
}
|
||||
if (!ensureDir(dir))
|
||||
{
|
||||
if (err) *err = "cannot create " + dir;
|
||||
return false;
|
||||
}
|
||||
const int w = vr.field().sizeX(), h = vr.field().sizeY();
|
||||
const auto& st = vr.stats();
|
||||
const auto& cfg = vr.config();
|
||||
|
||||
nlohmann::json j;
|
||||
j["version"] = meta.version;
|
||||
j["source"] = meta.source;
|
||||
j["map_hash"] = hexOf(meta.map_hash ? meta.map_hash : vr.occupancyHash());
|
||||
j["info"] = {{"width", w}, {"height", h}, {"resolution", meta.resolution},
|
||||
{"origin", {meta.origin_x, meta.origin_y, meta.origin_yaw}}};
|
||||
j["params"] = {{"min_edge_length_cells", cfg.min_edge_length_cells},
|
||||
{"spur_clearance_ratio", cfg.spur_clearance_ratio},
|
||||
{"min_component_length_cells", cfg.min_component_length_cells}};
|
||||
j["stats"] = {{"nodes", st.nodes}, {"edges", st.edges}, {"components", st.components},
|
||||
{"gvd_cells", st.gvd_cells}, {"obstacle_cells", st.obstacle_cells},
|
||||
{"field_ms", st.field_ms}, {"extract_ms", st.extract_ms}};
|
||||
j["files"] = {{"gvd", with_gvd ? "voronoi_gvd.pgm" : ""},
|
||||
{"dist", with_dist ? "voronoi_dist.pgm" : ""}};
|
||||
|
||||
nlohmann::json nodes = nlohmann::json::array();
|
||||
for (const auto& nd : vr.graph().nodes()) nodes.push_back({nd.cell.x, nd.cell.y});
|
||||
j["nodes"] = std::move(nodes);
|
||||
nlohmann::json edges = nlohmann::json::array();
|
||||
for (const auto& e : vr.graph().edges())
|
||||
{
|
||||
nlohmann::json cells = nlohmann::json::array();
|
||||
for (const auto& c : e.cells) cells.push_back({c.x, c.y});
|
||||
edges.push_back({{"u", e.u}, {"v", e.v}, {"length_cells", e.length_cells},
|
||||
{"min_clearance_cells", e.min_clearance_cells}, {"cells", std::move(cells)}});
|
||||
}
|
||||
j["edges"] = std::move(edges);
|
||||
|
||||
{
|
||||
std::ofstream f(dir + "/voronoi.json");
|
||||
if (!f)
|
||||
{
|
||||
if (err) *err = "cannot write " + dir + "/voronoi.json";
|
||||
return false;
|
||||
}
|
||||
f << j.dump();
|
||||
}
|
||||
|
||||
if (with_gvd)
|
||||
{
|
||||
std::vector<uint8_t> gvd(static_cast<size_t>(w) * h, 0);
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
if (vr.field().isVoronoi(x, y)) gvd[static_cast<size_t>(y) * w + x] = 255;
|
||||
if (!writePgm8(dir + "/voronoi_gvd.pgm", gvd, w, h))
|
||||
{
|
||||
if (err) *err = "cannot write voronoi_gvd.pgm";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (with_dist)
|
||||
{
|
||||
std::vector<uint16_t> dist(static_cast<size_t>(w) * h, 0);
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
const double d = vr.field().distanceCells(x, y) * 10.0;
|
||||
dist[static_cast<size_t>(y) * w + x] =
|
||||
static_cast<uint16_t>(std::min(65535.0, std::max(0.0, d)));
|
||||
}
|
||||
if (!writePgm16(dir + "/voronoi_dist.pgm", dist, w, h))
|
||||
{
|
||||
if (err) *err = "cannot write voronoi_dist.pgm";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool loadBundleMeta(const std::string& dir, BundleMeta* meta, std::string* err)
|
||||
{
|
||||
std::ifstream f(dir + "/voronoi.json");
|
||||
if (!f)
|
||||
{
|
||||
if (err) *err = "no voronoi.json in " + dir;
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
nlohmann::json j;
|
||||
f >> j;
|
||||
BundleMeta m;
|
||||
m.version = j.value("version", 0u);
|
||||
m.source = j.value("source", "");
|
||||
if (!parseHex(j.value("map_hash", ""), &m.map_hash))
|
||||
{
|
||||
if (err) *err = "bad map_hash";
|
||||
return false;
|
||||
}
|
||||
const auto& info = j.at("info");
|
||||
m.width = info.value("width", 0);
|
||||
m.height = info.value("height", 0);
|
||||
m.resolution = info.value("resolution", 0.0);
|
||||
const auto& o = info.at("origin");
|
||||
m.origin_x = o.at(0).get<double>();
|
||||
m.origin_y = o.at(1).get<double>();
|
||||
m.origin_yaw = o.size() > 2 ? o.at(2).get<double>() : 0.0;
|
||||
if (meta) *meta = m;
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
if (err) *err = std::string("voronoi.json: ") + e.what();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool appendRouteToBundle(const std::string& dir, const Polyline& route, size_t mask_cells,
|
||||
std::string* err)
|
||||
{
|
||||
nlohmann::json j;
|
||||
{
|
||||
std::ifstream f(dir + "/voronoi.json");
|
||||
if (!f)
|
||||
{
|
||||
if (err) *err = "no voronoi.json in " + dir;
|
||||
return false;
|
||||
}
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
if (err) *err = e.what();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
nlohmann::json rc = nlohmann::json::array();
|
||||
for (const auto& c : route) rc.push_back({c.x, c.y});
|
||||
j["route"] = {{"cells", std::move(rc)}, {"mask_cells", mask_cells}};
|
||||
std::ofstream f(dir + "/voronoi.json");
|
||||
if (!f)
|
||||
{
|
||||
if (err) *err = "cannot write voronoi.json";
|
||||
return false;
|
||||
}
|
||||
f << j.dump();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
87
src/corridor_mask.cpp
Normal file
87
src/corridor_mask.cpp
Normal file
@@ -0,0 +1,87 @@
|
||||
#include "voronoi_route/corridor_mask.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
#include "voronoi_route/voronoi_field.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
void stampDisc(std::vector<uint8_t>& mask, int w, int h, const Cell& c, double r, size_t& count)
|
||||
{
|
||||
const int ri = static_cast<int>(std::ceil(r));
|
||||
const double r2 = r * r;
|
||||
const int y0 = std::max(0, c.y - ri), y1 = std::min(h - 1, c.y + ri);
|
||||
const int x0 = std::max(0, c.x - ri), x1 = std::min(w - 1, c.x + ri);
|
||||
for (int y = y0; y <= y1; ++y)
|
||||
{
|
||||
const double dy = static_cast<double>(y - c.y);
|
||||
uint8_t* row = mask.data() + static_cast<size_t>(y) * w;
|
||||
for (int x = x0; x <= x1; ++x)
|
||||
{
|
||||
const double dx = static_cast<double>(x - c.x);
|
||||
if (dx * dx + dy * dy > r2) continue;
|
||||
if (!row[x])
|
||||
{
|
||||
row[x] = 1;
|
||||
++count;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<uint8_t> corridorMask(const VoronoiField& field, const Polyline& polyline,
|
||||
const CorridorParams& params, size_t* cells_in_mask)
|
||||
{
|
||||
const int w = field.sizeX(), h = field.sizeY();
|
||||
std::vector<uint8_t> mask(static_cast<size_t>(w) * h, 0);
|
||||
size_t count = 0;
|
||||
if (!field.ready() || polyline.empty())
|
||||
{
|
||||
if (cells_in_mask) *cells_in_mask = 0;
|
||||
return mask;
|
||||
}
|
||||
|
||||
const double w_min = std::max(1.0, params.half_width_min_cells);
|
||||
const double w_max = std::max(w_min, params.half_width_max_cells);
|
||||
|
||||
double last_stamp_pos = -1e9;
|
||||
double pos = 0.0;
|
||||
for (size_t i = 0; i < polyline.size(); ++i)
|
||||
{
|
||||
const Cell& c = polyline[i];
|
||||
if (i > 0)
|
||||
{
|
||||
const Cell& p = polyline[i - 1];
|
||||
pos += (p.x != c.x && p.y != c.y) ? 1.41421356 : 1.0;
|
||||
}
|
||||
const double clearance = field.distanceCells(c.x, c.y);
|
||||
double r = std::max(w_min, params.clearance_scale * clearance);
|
||||
r = std::min(r, w_max);
|
||||
|
||||
const bool last = i + 1 == polyline.size();
|
||||
if (i == 0 || last || pos - last_stamp_pos >= r * 0.5)
|
||||
{
|
||||
stampDisc(mask, w, h, c, r, count);
|
||||
last_stamp_pos = pos;
|
||||
}
|
||||
// The line itself is always inside, whatever the sampling did.
|
||||
if (field.inBounds(c.x, c.y))
|
||||
{
|
||||
uint8_t& m = mask[static_cast<size_t>(c.y) * w + c.x];
|
||||
if (!m)
|
||||
{
|
||||
m = 1;
|
||||
++count;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cells_in_mask) *cells_in_mask = count;
|
||||
return mask;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
724
src/dynamic_voronoi.cpp
Normal file
724
src/dynamic_voronoi.cpp
Normal file
@@ -0,0 +1,724 @@
|
||||
#include "voronoi_route/dynamic_voronoi.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <iostream>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
DynamicVoronoi::DynamicVoronoi() {
|
||||
sqrt2 = sqrt(2.0);
|
||||
data = NULL;
|
||||
gridMap = NULL;
|
||||
alternativeDiagram = NULL;
|
||||
allocatedGridMap = false;
|
||||
}
|
||||
|
||||
DynamicVoronoi::~DynamicVoronoi() {
|
||||
if (data) {
|
||||
for (int x=0; x<sizeX; x++) delete[] data[x];
|
||||
delete[] data;
|
||||
}
|
||||
if (allocatedGridMap && gridMap) {
|
||||
for (int x=0; x<sizeX; x++) delete[] gridMap[x];
|
||||
delete[] gridMap;
|
||||
}
|
||||
}
|
||||
|
||||
void DynamicVoronoi::initializeEmpty(int _sizeX, int _sizeY, bool initGridMap) {
|
||||
if (data) {
|
||||
for (int x=0; x<sizeX; x++) delete[] data[x];
|
||||
delete[] data;
|
||||
data = NULL;
|
||||
}
|
||||
if(alternativeDiagram){
|
||||
for (int x=0; x<sizeX; x++) delete[] alternativeDiagram[x];
|
||||
delete[] alternativeDiagram;
|
||||
alternativeDiagram = NULL;
|
||||
}
|
||||
if (initGridMap) {
|
||||
if (allocatedGridMap && gridMap) {
|
||||
for (int x=0; x<sizeX; x++) delete[] gridMap[x];
|
||||
delete[] gridMap;
|
||||
gridMap = NULL;
|
||||
allocatedGridMap = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
sizeX = _sizeX;
|
||||
sizeY = _sizeY;
|
||||
data = new dataCell*[sizeX];
|
||||
for (int x=0; x<sizeX; x++) data[x] = new dataCell[sizeY];
|
||||
|
||||
if (initGridMap) {
|
||||
gridMap = new bool*[sizeX];
|
||||
for (int x=0; x<sizeX; x++) gridMap[x] = new bool[sizeY];
|
||||
allocatedGridMap = true;
|
||||
}
|
||||
|
||||
dataCell c;
|
||||
c.dist = INFINITY;
|
||||
c.sqdist = INT_MAX;
|
||||
c.obstX = invalidObstData;
|
||||
c.obstY = invalidObstData;
|
||||
c.voronoi = free;
|
||||
c.queueing = fwNotQueued;
|
||||
c.needsRaise = false;
|
||||
|
||||
for (int x=0; x<sizeX; x++)
|
||||
for (int y=0; y<sizeY; y++) data[x][y] = c;
|
||||
|
||||
if (initGridMap) {
|
||||
for (int x=0; x<sizeX; x++)
|
||||
for (int y=0; y<sizeY; y++) gridMap[x][y] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void DynamicVoronoi::initializeMap(int _sizeX, int _sizeY, bool** _gridMap) {
|
||||
gridMap = _gridMap;
|
||||
initializeEmpty(_sizeX, _sizeY, false);
|
||||
|
||||
for (int x=0; x<sizeX; x++) {
|
||||
for (int y=0; y<sizeY; y++) {
|
||||
if (gridMap[x][y]) {
|
||||
dataCell c = data[x][y];
|
||||
if (!isOccupied(x,y,c)) {
|
||||
|
||||
bool isSurrounded = true;
|
||||
for (int dx=-1; dx<=1; dx++) {
|
||||
int nx = x+dx;
|
||||
if (nx<=0 || nx>=sizeX-1) continue;
|
||||
for (int dy=-1; dy<=1; dy++) {
|
||||
if (dx==0 && dy==0) continue;
|
||||
int ny = y+dy;
|
||||
if (ny<=0 || ny>=sizeY-1) continue;
|
||||
|
||||
if (!gridMap[nx][ny]) {
|
||||
isSurrounded = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isSurrounded) {
|
||||
c.obstX = x;
|
||||
c.obstY = y;
|
||||
c.sqdist = 0;
|
||||
c.dist=0;
|
||||
c.voronoi=occupied;
|
||||
c.queueing = fwProcessed;
|
||||
data[x][y] = c;
|
||||
} else setObstacle(x,y);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DynamicVoronoi::occupyCell(int x, int y) {
|
||||
gridMap[x][y] = 1;
|
||||
setObstacle(x,y);
|
||||
}
|
||||
void DynamicVoronoi::clearCell(int x, int y) {
|
||||
gridMap[x][y] = 0;
|
||||
removeObstacle(x,y);
|
||||
}
|
||||
|
||||
void DynamicVoronoi::setObstacle(int x, int y) {
|
||||
dataCell c = data[x][y];
|
||||
if(isOccupied(x,y,c)) return;
|
||||
|
||||
addList.push_back(INTPOINT(x,y));
|
||||
c.obstX = x;
|
||||
c.obstY = y;
|
||||
data[x][y] = c;
|
||||
}
|
||||
|
||||
void DynamicVoronoi::removeObstacle(int x, int y) {
|
||||
dataCell c = data[x][y];
|
||||
if(isOccupied(x,y,c) == false) return;
|
||||
|
||||
removeList.push_back(INTPOINT(x,y));
|
||||
c.obstX = invalidObstData;
|
||||
c.obstY = invalidObstData;
|
||||
c.queueing = bwQueued;
|
||||
data[x][y] = c;
|
||||
}
|
||||
|
||||
void DynamicVoronoi::exchangeObstacles(std::vector<INTPOINT>& points) {
|
||||
|
||||
for (unsigned int i=0; i<lastObstacles.size(); i++) {
|
||||
int x = lastObstacles[i].x;
|
||||
int y = lastObstacles[i].y;
|
||||
|
||||
bool v = gridMap[x][y];
|
||||
if (v) continue;
|
||||
removeObstacle(x,y);
|
||||
}
|
||||
|
||||
lastObstacles.clear();
|
||||
|
||||
for (unsigned int i=0; i<points.size(); i++) {
|
||||
int x = points[i].x;
|
||||
int y = points[i].y;
|
||||
bool v = gridMap[x][y];
|
||||
if (v) continue;
|
||||
setObstacle(x,y);
|
||||
lastObstacles.push_back(points[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void DynamicVoronoi::update(bool updateRealDist) {
|
||||
|
||||
commitAndColorize(updateRealDist);
|
||||
|
||||
while (!open.empty()) {
|
||||
INTPOINT p = open.pop();
|
||||
int x = p.x;
|
||||
int y = p.y;
|
||||
dataCell c = data[x][y];
|
||||
|
||||
if(c.queueing==fwProcessed) continue;
|
||||
|
||||
if (c.needsRaise) {
|
||||
// RAISE
|
||||
for (int dx=-1; dx<=1; dx++) {
|
||||
int nx = x+dx;
|
||||
if (nx<=0 || nx>=sizeX-1) continue;
|
||||
for (int dy=-1; dy<=1; dy++) {
|
||||
if (dx==0 && dy==0) continue;
|
||||
int ny = y+dy;
|
||||
if (ny<=0 || ny>=sizeY-1) continue;
|
||||
dataCell nc = data[nx][ny];
|
||||
if (nc.obstX!=invalidObstData && !nc.needsRaise) {
|
||||
if(!isOccupied(nc.obstX,nc.obstY,data[nc.obstX][nc.obstY])) {
|
||||
open.push(nc.sqdist, INTPOINT(nx,ny));
|
||||
nc.queueing = fwQueued;
|
||||
nc.needsRaise = true;
|
||||
nc.obstX = invalidObstData;
|
||||
nc.obstY = invalidObstData;
|
||||
if (updateRealDist) nc.dist = INFINITY;
|
||||
nc.sqdist = INT_MAX;
|
||||
data[nx][ny] = nc;
|
||||
} else {
|
||||
if(nc.queueing != fwQueued){
|
||||
open.push(nc.sqdist, INTPOINT(nx,ny));
|
||||
nc.queueing = fwQueued;
|
||||
data[nx][ny] = nc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
c.needsRaise = false;
|
||||
c.queueing = bwProcessed;
|
||||
data[x][y] = c;
|
||||
}
|
||||
else if (c.obstX != invalidObstData && isOccupied(c.obstX,c.obstY,data[c.obstX][c.obstY])) {
|
||||
|
||||
// LOWER
|
||||
c.queueing = fwProcessed;
|
||||
c.voronoi = occupied;
|
||||
|
||||
for (int dx=-1; dx<=1; dx++) {
|
||||
int nx = x+dx;
|
||||
if (nx<=0 || nx>=sizeX-1) continue;
|
||||
for (int dy=-1; dy<=1; dy++) {
|
||||
if (dx==0 && dy==0) continue;
|
||||
int ny = y+dy;
|
||||
if (ny<=0 || ny>=sizeY-1) continue;
|
||||
dataCell nc = data[nx][ny];
|
||||
if(!nc.needsRaise) {
|
||||
int distx = nx-c.obstX;
|
||||
int disty = ny-c.obstY;
|
||||
int newSqDistance = distx*distx + disty*disty;
|
||||
bool overwrite = (newSqDistance < nc.sqdist);
|
||||
if(!overwrite && newSqDistance==nc.sqdist) {
|
||||
if (nc.obstX == invalidObstData || isOccupied(nc.obstX,nc.obstY,data[nc.obstX][nc.obstY])==false) overwrite = true;
|
||||
}
|
||||
if (overwrite) {
|
||||
open.push(newSqDistance, INTPOINT(nx,ny));
|
||||
nc.queueing = fwQueued;
|
||||
if (updateRealDist) {
|
||||
nc.dist = sqrt((double) newSqDistance);
|
||||
}
|
||||
nc.sqdist = newSqDistance;
|
||||
nc.obstX = c.obstX;
|
||||
nc.obstY = c.obstY;
|
||||
} else {
|
||||
checkVoro(x,y,nx,ny,c,nc);
|
||||
}
|
||||
data[nx][ny] = nc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
data[x][y] = c;
|
||||
}
|
||||
}
|
||||
|
||||
float DynamicVoronoi::getDistance( int x, int y ) const {
|
||||
if( (x>0) && (x<sizeX) && (y>0) && (y<sizeY)) return data[x][y].dist;
|
||||
else return -INFINITY;
|
||||
}
|
||||
|
||||
bool DynamicVoronoi::isVoronoi( int x, int y ) const {
|
||||
dataCell c = data[x][y];
|
||||
return (c.voronoi==free || c.voronoi==voronoiKeep);
|
||||
}
|
||||
|
||||
bool DynamicVoronoi::isVoronoiAlternative(int x, int y) const {
|
||||
int v = alternativeDiagram[x][y];
|
||||
return (v == free || v == voronoiKeep);
|
||||
}
|
||||
|
||||
void DynamicVoronoi::commitAndColorize(bool updateRealDist) {
|
||||
// ADD NEW OBSTACLES
|
||||
for (unsigned int i=0; i<addList.size(); i++) {
|
||||
INTPOINT p = addList[i];
|
||||
int x = p.x;
|
||||
int y = p.y;
|
||||
dataCell c = data[x][y];
|
||||
|
||||
if(c.queueing != fwQueued){
|
||||
if (updateRealDist) c.dist = 0;
|
||||
c.sqdist = 0;
|
||||
c.obstX = x;
|
||||
c.obstY = y;
|
||||
c.queueing = fwQueued;
|
||||
c.voronoi = occupied;
|
||||
data[x][y] = c;
|
||||
open.push(0, INTPOINT(x,y));
|
||||
}
|
||||
}
|
||||
|
||||
// REMOVE OLD OBSTACLES
|
||||
for (unsigned int i=0; i<removeList.size(); i++) {
|
||||
INTPOINT p = removeList[i];
|
||||
int x = p.x;
|
||||
int y = p.y;
|
||||
dataCell c = data[x][y];
|
||||
|
||||
if (isOccupied(x,y,c)==true) continue; // obstacle was removed and reinserted
|
||||
open.push(0, INTPOINT(x,y));
|
||||
if (updateRealDist) c.dist = INFINITY;
|
||||
c.sqdist = INT_MAX;
|
||||
c.needsRaise = true;
|
||||
data[x][y] = c;
|
||||
}
|
||||
removeList.clear();
|
||||
addList.clear();
|
||||
}
|
||||
|
||||
|
||||
void DynamicVoronoi::checkVoro(int x, int y, int nx, int ny, dataCell& c, dataCell& nc) {
|
||||
|
||||
if ((c.sqdist>1 || nc.sqdist>1) && nc.obstX!=invalidObstData) {
|
||||
if (abs(c.obstX-nc.obstX) > 1 || abs(c.obstY-nc.obstY) > 1) {
|
||||
//compute dist from x,y to obstacle of nx,ny
|
||||
int dxy_x = x-nc.obstX;
|
||||
int dxy_y = y-nc.obstY;
|
||||
int sqdxy = dxy_x*dxy_x + dxy_y*dxy_y;
|
||||
int stability_xy = sqdxy - c.sqdist;
|
||||
if (sqdxy - c.sqdist<0) return;
|
||||
|
||||
//compute dist from nx,ny to obstacle of x,y
|
||||
int dnxy_x = nx - c.obstX;
|
||||
int dnxy_y = ny - c.obstY;
|
||||
int sqdnxy = dnxy_x*dnxy_x + dnxy_y*dnxy_y;
|
||||
int stability_nxy = sqdnxy - nc.sqdist;
|
||||
if (sqdnxy - nc.sqdist <0) return;
|
||||
|
||||
//which cell is added to the Voronoi diagram?
|
||||
if(stability_xy <= stability_nxy && c.sqdist>2) {
|
||||
if (c.voronoi != free) {
|
||||
c.voronoi = free;
|
||||
reviveVoroNeighbors(x,y);
|
||||
pruneQueue.push(INTPOINT(x,y));
|
||||
}
|
||||
}
|
||||
if(stability_nxy <= stability_xy && nc.sqdist>2) {
|
||||
if (nc.voronoi != free) {
|
||||
nc.voronoi = free;
|
||||
reviveVoroNeighbors(nx,ny);
|
||||
pruneQueue.push(INTPOINT(nx,ny));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void DynamicVoronoi::reviveVoroNeighbors(int &x, int &y) {
|
||||
for (int dx=-1; dx<=1; dx++) {
|
||||
int nx = x+dx;
|
||||
if (nx<=0 || nx>=sizeX-1) continue;
|
||||
for (int dy=-1; dy<=1; dy++) {
|
||||
if (dx==0 && dy==0) continue;
|
||||
int ny = y+dy;
|
||||
if (ny<=0 || ny>=sizeY-1) continue;
|
||||
dataCell nc = data[nx][ny];
|
||||
if (nc.sqdist != INT_MAX && !nc.needsRaise && (nc.voronoi == voronoiKeep || nc.voronoi == voronoiPrune)) {
|
||||
nc.voronoi = free;
|
||||
data[nx][ny] = nc;
|
||||
pruneQueue.push(INTPOINT(nx,ny));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool DynamicVoronoi::isOccupied(int x, int y) const {
|
||||
dataCell c = data[x][y];
|
||||
return (c.obstX==x && c.obstY==y);
|
||||
}
|
||||
|
||||
bool DynamicVoronoi::isOccupied(int &x, int &y, dataCell &c) {
|
||||
return (c.obstX==x && c.obstY==y);
|
||||
}
|
||||
|
||||
void DynamicVoronoi::visualize(const char *filename) {
|
||||
// write ppm files
|
||||
|
||||
FILE* F = fopen(filename, "w");
|
||||
if (!F) {
|
||||
std::cerr << "could not open 'result.pgm' for writing!\n";
|
||||
return;
|
||||
}
|
||||
fprintf(F, "P6\n#\n");
|
||||
fprintf(F, "%d %d\n255\n", sizeX, sizeY);
|
||||
|
||||
for(int y = sizeY-1; y >=0; y--){
|
||||
for(int x = 0; x<sizeX; x++){
|
||||
unsigned char c = 0;
|
||||
if (alternativeDiagram!=NULL && (alternativeDiagram[x][y] == free || alternativeDiagram[x][y]==voronoiKeep)) {
|
||||
fputc( 255, F );
|
||||
fputc( 0, F );
|
||||
fputc( 0, F );
|
||||
} else if(isVoronoi(x,y)){
|
||||
fputc( 0, F );
|
||||
fputc( 0, F );
|
||||
fputc( 255, F );
|
||||
} else if (data[x][y].sqdist==0) {
|
||||
fputc( 0, F );
|
||||
fputc( 0, F );
|
||||
fputc( 0, F );
|
||||
} else {
|
||||
float f = 80+(sqrt(data[x][y].sqdist)*10);
|
||||
if (f>255) f=255;
|
||||
if (f<0) f=0;
|
||||
c = (unsigned char)f;
|
||||
fputc( c, F );
|
||||
fputc( c, F );
|
||||
fputc( c, F );
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose(F);
|
||||
}
|
||||
|
||||
|
||||
void DynamicVoronoi::prune() {
|
||||
// filler
|
||||
while(!pruneQueue.empty()) {
|
||||
INTPOINT p = pruneQueue.front();
|
||||
pruneQueue.pop();
|
||||
int x = p.x;
|
||||
int y = p.y;
|
||||
|
||||
if (data[x][y].voronoi==occupied) continue;
|
||||
if (data[x][y].voronoi==freeQueued) continue;
|
||||
|
||||
data[x][y].voronoi = freeQueued;
|
||||
sortedPruneQueue.push(data[x][y].sqdist, p);
|
||||
|
||||
/* tl t tr
|
||||
l c r
|
||||
bl b br */
|
||||
|
||||
dataCell tr,tl,br,bl;
|
||||
tr = data[x+1][y+1];
|
||||
tl = data[x-1][y+1];
|
||||
br = data[x+1][y-1];
|
||||
bl = data[x-1][y-1];
|
||||
|
||||
dataCell r,b,t,l;
|
||||
r = data[x+1][y];
|
||||
l = data[x-1][y];
|
||||
t = data[x][y+1];
|
||||
b = data[x][y-1];
|
||||
|
||||
if (x+2<sizeX && r.voronoi==occupied) {
|
||||
// fill to the right
|
||||
if (tr.voronoi!=occupied && br.voronoi!=occupied && data[x+2][y].voronoi!=occupied) {
|
||||
r.voronoi = freeQueued;
|
||||
sortedPruneQueue.push(r.sqdist, INTPOINT(x+1,y));
|
||||
data[x+1][y] = r;
|
||||
}
|
||||
}
|
||||
if (x-2>=0 && l.voronoi==occupied) {
|
||||
// fill to the left
|
||||
if (tl.voronoi!=occupied && bl.voronoi!=occupied && data[x-2][y].voronoi!=occupied) {
|
||||
l.voronoi = freeQueued;
|
||||
sortedPruneQueue.push(l.sqdist, INTPOINT(x-1,y));
|
||||
data[x-1][y] = l;
|
||||
}
|
||||
}
|
||||
if (y+2<sizeY && t.voronoi==occupied) {
|
||||
// fill to the top
|
||||
if (tr.voronoi!=occupied && tl.voronoi!=occupied && data[x][y+2].voronoi!=occupied) {
|
||||
t.voronoi = freeQueued;
|
||||
sortedPruneQueue.push(t.sqdist, INTPOINT(x,y+1));
|
||||
data[x][y+1] = t;
|
||||
}
|
||||
}
|
||||
if (y-2>=0 && b.voronoi==occupied) {
|
||||
// fill to the bottom
|
||||
if (br.voronoi!=occupied && bl.voronoi!=occupied && data[x][y-2].voronoi!=occupied) {
|
||||
b.voronoi = freeQueued;
|
||||
sortedPruneQueue.push(b.sqdist, INTPOINT(x,y-1));
|
||||
data[x][y-1] = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
while(!sortedPruneQueue.empty()) {
|
||||
INTPOINT p = sortedPruneQueue.pop();
|
||||
dataCell c = data[p.x][p.y];
|
||||
int v = c.voronoi;
|
||||
if (v!=freeQueued && v!=voronoiRetry) { // || v>free || v==voronoiPrune || v==voronoiKeep) {
|
||||
// assert(v!=retry);
|
||||
continue;
|
||||
}
|
||||
|
||||
markerMatchResult r = markerMatch(p.x,p.y);
|
||||
if (r==pruned) c.voronoi = voronoiPrune;
|
||||
else if (r==keep) c.voronoi = voronoiKeep;
|
||||
else { // r==retry
|
||||
c.voronoi = voronoiRetry;
|
||||
// printf("RETRY %d %d\n", x, sizeY-1-y);
|
||||
pruneQueue.push(p);
|
||||
}
|
||||
data[p.x][p.y] = c;
|
||||
|
||||
if (sortedPruneQueue.empty()) {
|
||||
while (!pruneQueue.empty()) {
|
||||
INTPOINT p = pruneQueue.front();
|
||||
pruneQueue.pop();
|
||||
sortedPruneQueue.push(data[p.x][p.y].sqdist, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
// printf("match: %d\nnomat: %d\n", matchCount, noMatchCount);
|
||||
}
|
||||
|
||||
void DynamicVoronoi::updateAlternativePrunedDiagram() {
|
||||
|
||||
if(alternativeDiagram==NULL){
|
||||
alternativeDiagram = new int*[sizeX];
|
||||
for(int x=0; x<sizeX; x++){
|
||||
alternativeDiagram[x] = new int[sizeY];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
std::queue<INTPOINT> end_cells;
|
||||
BucketPrioQueue<INTPOINT> sortedPruneQueue;
|
||||
for(int x=1; x<sizeX-1; x++){
|
||||
for(int y=1; y<sizeY-1; y++){
|
||||
dataCell& c = data[x][y];
|
||||
alternativeDiagram[x][y] = c.voronoi;
|
||||
if(c.voronoi <=free){
|
||||
sortedPruneQueue.push(c.sqdist, INTPOINT(x,y));
|
||||
end_cells.push(INTPOINT(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(int x=1; x<sizeX-1; x++){
|
||||
for(int y=1; y<sizeY-1; y++){
|
||||
if( getNumVoronoiNeighborsAlternative(x, y) >= 3){
|
||||
alternativeDiagram[x][y] = voronoiKeep;
|
||||
sortedPruneQueue.push(data[x][y].sqdist, INTPOINT(x,y));
|
||||
end_cells.push(INTPOINT(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(int x=1; x<sizeX-1; x++){
|
||||
for(int y=1; y<sizeY-1; y++){
|
||||
if( getNumVoronoiNeighborsAlternative(x, y) >= 3){
|
||||
alternativeDiagram[x][y] = voronoiKeep;
|
||||
sortedPruneQueue.push(data[x][y].sqdist, INTPOINT(x,y));
|
||||
end_cells.push(INTPOINT(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
while (!sortedPruneQueue.empty()) {
|
||||
INTPOINT p = sortedPruneQueue.pop();
|
||||
|
||||
if (markerMatchAlternative(p.x, p.y)) {
|
||||
alternativeDiagram[p.x][p.y]=voronoiPrune;
|
||||
} else {
|
||||
alternativeDiagram[p.x][p.y]=voronoiKeep;
|
||||
}
|
||||
}
|
||||
|
||||
// //delete worms
|
||||
while (!end_cells.empty()) {
|
||||
INTPOINT p = end_cells.front();
|
||||
end_cells.pop();
|
||||
|
||||
if (isVoronoiAlternative(p.x,p.y) && getNumVoronoiNeighborsAlternative(p.x, p.y) == 1) {
|
||||
alternativeDiagram[p.x][p.y] = voronoiPrune;
|
||||
|
||||
for (int dx = -1; dx <= 1; ++dx) {
|
||||
for (int dy = -1; dy <= 1; ++dy) {
|
||||
if (!(dx || dy) || (dx && dy)) {
|
||||
continue;
|
||||
}
|
||||
int nx = p.x + dx;
|
||||
int ny = p.y + dy;
|
||||
if (nx < 0 || nx >= sizeX || ny < 0 || ny >= sizeY) {
|
||||
continue;
|
||||
}
|
||||
if (isVoronoiAlternative(nx,ny)) {
|
||||
if (getNumVoronoiNeighborsAlternative(nx, ny) == 1) {
|
||||
end_cells.push(INTPOINT(nx, ny));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool DynamicVoronoi::markerMatchAlternative(int x, int y) {
|
||||
// prune if this returns true
|
||||
|
||||
bool f[8];
|
||||
|
||||
int nx, ny;
|
||||
int dx, dy;
|
||||
|
||||
int i = 0;
|
||||
// int obstacleCount=0;
|
||||
int voroCount = 0;
|
||||
for (dy = 1; dy >= -1; dy--) {
|
||||
ny = y + dy;
|
||||
for (dx = -1; dx <= 1; dx++) {
|
||||
if (dx || dy) {
|
||||
nx = x + dx;
|
||||
int v = alternativeDiagram[nx][ny];
|
||||
bool b = (v <= free && v != voronoiPrune);
|
||||
// if (v==occupied) obstacleCount++;
|
||||
f[i] = b;
|
||||
if (v <= free && !(dx && dy))
|
||||
voroCount++;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 5 6 7
|
||||
* 3 4
|
||||
* 0 1 2
|
||||
*/
|
||||
|
||||
{
|
||||
//connected horizontal or vertically to only one cell
|
||||
if (voroCount == 1 && (f[1] || f[3] || f[4] || f[6])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 4-connected
|
||||
if ((!f[0] && f[1] && f[3]) || (!f[2] && f[1] && f[4]) || (!f[5] && f[3] && f[6]) || (!f[7] && f[6] && f[4]))
|
||||
return false;
|
||||
|
||||
if ((f[3] && f[4] && !f[1] && !f[6]) || (f[1] && f[6] && !f[3] && !f[4]))
|
||||
return false;
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int DynamicVoronoi::getNumVoronoiNeighborsAlternative(int x, int y) const {
|
||||
int count = 0;
|
||||
for (int dx = -1; dx <= 1; dx++) {
|
||||
for (int dy = -1; dy <= 1; dy++) {
|
||||
if ((dx == 0 && dy == 0) || (dx != 0 && dy != 0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int nx = x + dx;
|
||||
int ny = y + dy;
|
||||
if (nx < 0 || nx >= sizeX || ny < 0 || ny >= sizeY) {
|
||||
continue;
|
||||
}
|
||||
if (alternativeDiagram[nx][ny]==free || alternativeDiagram[nx][ny]==voronoiKeep) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
|
||||
DynamicVoronoi::markerMatchResult DynamicVoronoi::markerMatch(int x, int y) {
|
||||
// implementation of connectivity patterns
|
||||
bool f[8];
|
||||
|
||||
int nx, ny;
|
||||
int dx, dy;
|
||||
|
||||
int i=0;
|
||||
int count=0;
|
||||
// int obstacleCount=0;
|
||||
int voroCount=0;
|
||||
int voroCountFour=0;
|
||||
|
||||
for (dy=1; dy>=-1; dy--) {
|
||||
ny = y+dy;
|
||||
for (dx=-1; dx<=1; dx++) {
|
||||
if (dx || dy) {
|
||||
nx = x+dx;
|
||||
dataCell nc = data[nx][ny];
|
||||
int v = nc.voronoi;
|
||||
bool b = (v<=free && v!=voronoiPrune);
|
||||
// if (v==occupied) obstacleCount++;
|
||||
f[i] = b;
|
||||
if (b) {
|
||||
voroCount++;
|
||||
if (!(dx && dy)) voroCountFour++;
|
||||
}
|
||||
if (b && !(dx && dy) ) count++;
|
||||
// if (v<=free && !(dx && dy)) voroCount++;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (voroCount<3 && voroCountFour==1 && (f[1] || f[3] || f[4] || f[6])) {
|
||||
// assert(voroCount<2);
|
||||
// if (voroCount>=2) printf("voro>2 %d %d\n", x, y);
|
||||
return keep;
|
||||
}
|
||||
|
||||
// 4-connected
|
||||
if ((!f[0] && f[1] && f[3]) || (!f[2] && f[1] && f[4]) || (!f[5] && f[3] && f[6]) || (!f[7] && f[6] && f[4])) return keep;
|
||||
if ((f[3] && f[4] && !f[1] && !f[6]) || (f[1] && f[6] && !f[3] && !f[4])) return keep;
|
||||
|
||||
|
||||
|
||||
// keep voro cells inside of blocks and retry later
|
||||
if (voroCount>=5 && voroCountFour>=3 && data[x][y].voronoi!=voronoiRetry) {
|
||||
return retry;
|
||||
}
|
||||
|
||||
return pruned;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
211
src/map_convert.cpp
Normal file
211
src/map_convert.cpp
Normal file
@@ -0,0 +1,211 @@
|
||||
#include "voronoi_route/map_convert.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
CostClass classifyGridValue(int value, const StaticLayerRule& rule)
|
||||
{
|
||||
// Mirror of StaticLayer::interpretValue(), branch for branch.
|
||||
if (value == rule.unknown_cost_value)
|
||||
return rule.track_unknown_space ? CostClass::kNoInformation : CostClass::kFree;
|
||||
if (value >= rule.lethal_cost_threshold) return CostClass::kLethal;
|
||||
if (rule.trinary_costmap) return CostClass::kFree;
|
||||
return CostClass::kScaled;
|
||||
}
|
||||
|
||||
bool isObstacleClass(CostClass c, const ObstacleRule& rule)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case CostClass::kLethal:
|
||||
return true;
|
||||
case CostClass::kNoInformation:
|
||||
return rule.unknown == UnknownPolicy::kObstacle;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
inline void count(CostClass c, MapConvertStats& st)
|
||||
{
|
||||
if (c == CostClass::kLethal) ++st.occupied;
|
||||
else if (c == CostClass::kNoInformation) ++st.unknown;
|
||||
else ++st.free;
|
||||
}
|
||||
|
||||
// map_server image_loader.cpp, trinary mode: average of every channel (alpha included), in double.
|
||||
inline int mapServerValue(const uint8_t* px, int channels, const MapServerThresholds& t)
|
||||
{
|
||||
int sum = 0;
|
||||
for (int k = 0; k < channels; ++k) sum += px[k];
|
||||
double avg = sum / static_cast<double>(channels);
|
||||
if (t.negate) avg = 255.0 - avg;
|
||||
const double occ = (255.0 - avg) / 255.0;
|
||||
if (occ > t.occupied_thresh) return 100;
|
||||
if (occ < t.free_thresh) return 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<uint8_t> occupancyFromImage(const uint8_t* pixels, int width, int height, int channels,
|
||||
const MapServerThresholds& thresholds,
|
||||
const ObstacleRule& rule, MapConvertStats* stats)
|
||||
{
|
||||
std::vector<uint8_t> out;
|
||||
if (pixels == nullptr || width <= 0 || height <= 0 || channels <= 0) return out;
|
||||
out.assign(static_cast<size_t>(width) * height, 0);
|
||||
MapConvertStats st;
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
const uint8_t* row = pixels + static_cast<size_t>(y) * width * channels;
|
||||
uint8_t* orow = out.data() + static_cast<size_t>(y) * width;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
const CostClass c =
|
||||
classifyGridValue(mapServerValue(row + static_cast<size_t>(x) * channels, channels, thresholds),
|
||||
rule.layer);
|
||||
count(c, st);
|
||||
orow[x] = isObstacleClass(c, rule) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
if (stats) *stats = st;
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> occupancyFromGray(const uint8_t* gray, int width, int height,
|
||||
const MapServerThresholds& thresholds,
|
||||
const ObstacleRule& rule, MapConvertStats* stats)
|
||||
{
|
||||
return occupancyFromImage(gray, width, height, 1, thresholds, rule, stats);
|
||||
}
|
||||
|
||||
std::vector<uint8_t> occupancyFromGrid(const int8_t* data, int width, int height,
|
||||
const ObstacleRule& rule, MapConvertStats* stats)
|
||||
{
|
||||
std::vector<uint8_t> out;
|
||||
if (data == nullptr || width <= 0 || height <= 0) return out;
|
||||
out.assign(static_cast<size_t>(width) * height, 0);
|
||||
MapConvertStats st;
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
const int8_t* row = data + static_cast<size_t>(height - 1 - y) * width; // ROS: row 0 = bottom
|
||||
uint8_t* orow = out.data() + static_cast<size_t>(y) * width;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
const CostClass c = classifyGridValue(row[x], rule.layer);
|
||||
count(c, st);
|
||||
orow[x] = isObstacleClass(c, rule) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
if (stats) *stats = st;
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> occupancyFromCostmap(const unsigned char* charmap, int width, int height,
|
||||
UnknownPolicy unknown, bool rows_bottom_up)
|
||||
{
|
||||
std::vector<uint8_t> out;
|
||||
if (charmap == nullptr || width <= 0 || height <= 0) return out;
|
||||
out.assign(static_cast<size_t>(width) * height, 0);
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
const int src_row = rows_bottom_up ? height - 1 - y : y;
|
||||
const unsigned char* row = charmap + static_cast<size_t>(src_row) * width;
|
||||
uint8_t* orow = out.data() + static_cast<size_t>(y) * width;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
const unsigned char v = row[x];
|
||||
orow[x] = (v == kCostmapLethalObstacle ||
|
||||
(v == kCostmapNoInformation && unknown == UnknownPolicy::kObstacle))
|
||||
? 1
|
||||
: 0;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
size_t applyObstacleRoi(std::vector<uint8_t>& mask, int width, int height, int margin_cells,
|
||||
size_t min_obstacle_cells)
|
||||
{
|
||||
if (margin_cells < 0 || width <= 0 || height <= 0 ||
|
||||
mask.size() != static_cast<size_t>(width) * height)
|
||||
return 0;
|
||||
int x0 = width, y0 = height, x1 = -1, y1 = -1;
|
||||
size_t n_obs = 0;
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
const uint8_t* row = mask.data() + static_cast<size_t>(y) * width;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
if (!row[x]) continue;
|
||||
++n_obs;
|
||||
if (x < x0) x0 = x;
|
||||
if (x > x1) x1 = x;
|
||||
if (y < y0) y0 = y;
|
||||
if (y > y1) y1 = y;
|
||||
}
|
||||
}
|
||||
if (n_obs < min_obstacle_cells) return 0;
|
||||
x0 = x0 - margin_cells < 0 ? 0 : x0 - margin_cells;
|
||||
y0 = y0 - margin_cells < 0 ? 0 : y0 - margin_cells;
|
||||
x1 = x1 + margin_cells >= width ? width - 1 : x1 + margin_cells;
|
||||
y1 = y1 + margin_cells >= height ? height - 1 : y1 + margin_cells;
|
||||
size_t turned = 0;
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
uint8_t* row = mask.data() + static_cast<size_t>(y) * width;
|
||||
const bool row_out = y < y0 || y > y1;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
if (row[x]) continue;
|
||||
if (row_out || x < x0 || x > x1)
|
||||
{
|
||||
row[x] = 1;
|
||||
++turned;
|
||||
}
|
||||
}
|
||||
}
|
||||
return turned;
|
||||
}
|
||||
|
||||
std::string obstacleRuleString(const ObstacleRule& rule)
|
||||
{
|
||||
char buf[160];
|
||||
std::snprintf(buf, sizeof(buf),
|
||||
"lethal>=%d;unknown_value=%d;track_unknown=%d;trinary=%d;unknown=%s;roi=%d",
|
||||
rule.layer.lethal_cost_threshold, rule.layer.unknown_cost_value,
|
||||
rule.layer.track_unknown_space ? 1 : 0, rule.layer.trinary_costmap ? 1 : 0,
|
||||
rule.unknown == UnknownPolicy::kObstacle ? "obstacle" : "traversable",
|
||||
rule.roi_margin_cells);
|
||||
return buf;
|
||||
}
|
||||
|
||||
bool parseObstacleRuleString(const std::string& s, ObstacleRule* rule)
|
||||
{
|
||||
int lethal = 0, unk = 0, track = 0, trin = 0, roi = -1;
|
||||
char pol[16] = {0};
|
||||
if (std::sscanf(s.c_str(),
|
||||
"lethal>=%d;unknown_value=%d;track_unknown=%d;trinary=%d;unknown=%15[a-z];roi=%d",
|
||||
&lethal, &unk, &track, &trin, pol, &roi) != 6)
|
||||
return false;
|
||||
if (std::strcmp(pol, "obstacle") != 0 && std::strcmp(pol, "traversable") != 0) return false;
|
||||
if (rule)
|
||||
{
|
||||
rule->layer.lethal_cost_threshold = lethal;
|
||||
rule->layer.unknown_cost_value = unk;
|
||||
rule->layer.track_unknown_space = track != 0;
|
||||
rule->layer.trinary_costmap = trin != 0;
|
||||
rule->unknown = std::strcmp(pol, "obstacle") == 0 ? UnknownPolicy::kObstacle
|
||||
: UnknownPolicy::kTraversable;
|
||||
rule->roi_margin_cells = roi;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
93
src/params.cpp
Normal file
93
src/params.cpp
Normal file
@@ -0,0 +1,93 @@
|
||||
#include "voronoi_route/params.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
double cellsOf(double metres, double resolution_m)
|
||||
{
|
||||
return resolution_m > 0.0 ? metres / resolution_m : 0.0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
VoronoiRoute::Config RouteParams::toConfig(double resolution_m) const
|
||||
{
|
||||
VoronoiRoute::Config c;
|
||||
c.min_edge_length_cells = cellsOf(min_edge_length_m, resolution_m);
|
||||
c.spur_clearance_ratio = spur_clearance_ratio;
|
||||
c.min_component_length_cells = cellsOf(min_component_length_m, resolution_m);
|
||||
c.min_clearance_cells = cellsOf(min_clearance_m, resolution_m);
|
||||
c.attach_max_radius_cells = static_cast<int>(std::lround(cellsOf(attach_max_radius_m, resolution_m)));
|
||||
c.graph_rebuild_min_changed_cells = static_cast<size_t>(std::max(0, graph_rebuild_min_changed_cells));
|
||||
c.full_rebuild_fraction = full_rebuild_fraction;
|
||||
return c;
|
||||
}
|
||||
|
||||
CorridorParams RouteParams::toCorridor(double resolution_m) const
|
||||
{
|
||||
CorridorParams p;
|
||||
p.half_width_min_cells = cellsOf(half_width_min_m, resolution_m);
|
||||
p.clearance_scale = clearance_scale;
|
||||
p.half_width_max_cells = cellsOf(half_width_max_m, resolution_m);
|
||||
return p;
|
||||
}
|
||||
|
||||
ObstacleRule RouteParams::toObstacleRule(double resolution_m) const
|
||||
{
|
||||
ObstacleRule rule;
|
||||
rule.layer.track_unknown_space = track_unknown_space;
|
||||
rule.layer.lethal_cost_threshold = lethal_cost_threshold;
|
||||
rule.layer.unknown_cost_value = unknown_cost_value;
|
||||
rule.layer.trinary_costmap = trinary_costmap;
|
||||
rule.unknown = unknown_is_obstacle ? UnknownPolicy::kObstacle : UnknownPolicy::kTraversable;
|
||||
rule.roi_margin_cells =
|
||||
roi_margin_m < 0.0 ? -1 : static_cast<int>(std::lround(roi_margin_m / resolution_m));
|
||||
return rule;
|
||||
}
|
||||
|
||||
std::vector<std::string> validateRouteParams(RouteParams* p)
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
if (!p) return out;
|
||||
auto fix = [&out](const char* key, double& v, double lo, double hi, double dflt) {
|
||||
if (std::isfinite(v) && v >= lo && v <= hi) return;
|
||||
out.push_back(std::string(key) + " out of range, using " + std::to_string(dflt));
|
||||
v = dflt;
|
||||
};
|
||||
fix("graph.min_edge_length_m", p->min_edge_length_m, 0.0, 100.0, 0.3);
|
||||
fix("graph.spur_clearance_ratio", p->spur_clearance_ratio, 0.0, 10.0, 1.2);
|
||||
fix("graph.min_component_length_m", p->min_component_length_m, 0.0, 1000.0, 2.0);
|
||||
fix("graph.min_clearance_m", p->min_clearance_m, 0.0, 10.0, 0.3);
|
||||
fix("graph.attach_max_radius_m", p->attach_max_radius_m, 0.1, 1000.0, 10.0);
|
||||
fix("graph.full_rebuild_fraction", p->full_rebuild_fraction, 0.0, 1.0, 0.02);
|
||||
if (p->graph_rebuild_min_changed_cells < 0)
|
||||
{
|
||||
out.push_back("graph.graph_rebuild_min_changed_cells negative, using 200");
|
||||
p->graph_rebuild_min_changed_cells = 200;
|
||||
}
|
||||
fix("corridor.half_width_min_m", p->half_width_min_m, 0.05, 100.0, 1.5);
|
||||
fix("corridor.clearance_scale", p->clearance_scale, 0.0, 10.0, 0.8);
|
||||
fix("corridor.half_width_max_m", p->half_width_max_m, 0.05, 1000.0, 6.0);
|
||||
if (p->half_width_max_m < p->half_width_min_m)
|
||||
{
|
||||
out.push_back("corridor.half_width_max_m < half_width_min_m, raising max to min");
|
||||
p->half_width_max_m = p->half_width_min_m;
|
||||
}
|
||||
if (!std::isfinite(p->roi_margin_m) || p->roi_margin_m > 1000.0)
|
||||
{
|
||||
out.push_back("obstacle.roi_margin_m out of range, using 0.5");
|
||||
p->roi_margin_m = 0.5;
|
||||
}
|
||||
if (p->lethal_cost_threshold < 0 || p->lethal_cost_threshold > 255)
|
||||
{
|
||||
out.push_back("obstacle.lethal_cost_threshold out of range, using 100");
|
||||
p->lethal_cost_threshold = 100;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
101
src/params_io.cpp
Normal file
101
src/params_io.cpp
Normal file
@@ -0,0 +1,101 @@
|
||||
#include "voronoi_route/params_io.h"
|
||||
|
||||
#include <filesystem>
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
std::string findConfigFile(const std::string& dir, const std::string& name)
|
||||
{
|
||||
std::error_code ec;
|
||||
if (dir.empty() || !std::filesystem::is_directory(dir, ec)) return "";
|
||||
for (const auto& e : std::filesystem::recursive_directory_iterator(dir, ec))
|
||||
if (e.is_regular_file(ec) && e.path().filename() == name) return e.path().string();
|
||||
return "";
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
template <class T>
|
||||
void take(const YAML::Node& n, const char* section, const char* key, T& out,
|
||||
std::vector<std::string>* notes)
|
||||
{
|
||||
const YAML::Node s = n[section];
|
||||
if (s && s[key])
|
||||
{
|
||||
try
|
||||
{
|
||||
out = s[key].as<T>();
|
||||
return;
|
||||
}
|
||||
catch (const std::exception&)
|
||||
{
|
||||
if (notes) notes->push_back(std::string(section) + "." + key + ": bad value, using default");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (notes) notes->push_back(std::string(section) + "." + key + ": missing, using default");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool loadRouteParams(const std::string& yaml_path, RouteParams* params, std::string* err,
|
||||
std::vector<std::string>* notes)
|
||||
{
|
||||
if (!params) return false;
|
||||
YAML::Node root;
|
||||
try
|
||||
{
|
||||
root = YAML::LoadFile(yaml_path);
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
if (err) *err = std::string(yaml_path) + ": " + e.what();
|
||||
return false;
|
||||
}
|
||||
const YAML::Node n = root["voronoi_route"];
|
||||
if (!n)
|
||||
{
|
||||
if (err) *err = yaml_path + ": no `voronoi_route` root key";
|
||||
return false;
|
||||
}
|
||||
RouteParams& p = *params;
|
||||
take(n, "graph", "min_edge_length_m", p.min_edge_length_m, notes);
|
||||
take(n, "graph", "spur_clearance_ratio", p.spur_clearance_ratio, notes);
|
||||
take(n, "graph", "min_component_length_m", p.min_component_length_m, notes);
|
||||
take(n, "graph", "min_clearance_m", p.min_clearance_m, notes);
|
||||
take(n, "graph", "attach_max_radius_m", p.attach_max_radius_m, notes);
|
||||
take(n, "graph", "graph_rebuild_min_changed_cells", p.graph_rebuild_min_changed_cells, notes);
|
||||
take(n, "graph", "full_rebuild_fraction", p.full_rebuild_fraction, notes);
|
||||
take(n, "corridor", "half_width_min_m", p.half_width_min_m, notes);
|
||||
take(n, "corridor", "clearance_scale", p.clearance_scale, notes);
|
||||
take(n, "corridor", "half_width_max_m", p.half_width_max_m, notes);
|
||||
take(n, "bundle", "write_gvd", p.write_gvd, notes);
|
||||
take(n, "bundle", "write_dist", p.write_dist, notes);
|
||||
take(n, "bundle", "write_preview", p.write_preview, notes);
|
||||
take(n, "bundle", "write_graph_image", p.write_graph_image, notes);
|
||||
take(n, "bundle", "write_graph_overlay", p.write_graph_overlay, notes);
|
||||
|
||||
take(n, "obstacle", "track_unknown_space", p.track_unknown_space, notes);
|
||||
take(n, "obstacle", "lethal_cost_threshold", p.lethal_cost_threshold, notes);
|
||||
take(n, "obstacle", "unknown_cost_value", p.unknown_cost_value, notes);
|
||||
take(n, "obstacle", "trinary_costmap", p.trinary_costmap, notes);
|
||||
take(n, "obstacle", "roi_margin_m", p.roi_margin_m, notes);
|
||||
|
||||
std::string unknown = "traversable";
|
||||
take(n, "obstacle", "unknown", unknown, notes);
|
||||
if (unknown == "traversable") p.unknown_is_obstacle = false;
|
||||
else if (unknown == "obstacle") p.unknown_is_obstacle = true;
|
||||
else
|
||||
{
|
||||
if (notes) notes->push_back("obstacle.unknown: '" + unknown + "' unknown, using traversable");
|
||||
p.unknown_is_obstacle = false;
|
||||
}
|
||||
|
||||
for (const std::string& w : validateRouteParams(&p))
|
||||
if (notes) notes->push_back(w);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
107
src/voronoi_field.cpp
Normal file
107
src/voronoi_field.cpp
Normal file
@@ -0,0 +1,107 @@
|
||||
#include "voronoi_route/voronoi_field.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
#include "voronoi_route/dynamic_voronoi.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
VoronoiField::VoronoiField() = default;
|
||||
VoronoiField::~VoronoiField() = default;
|
||||
|
||||
void VoronoiField::rebuild(const std::vector<uint8_t>& occupied, int size_x, int size_y)
|
||||
{
|
||||
ready_ = false;
|
||||
if (size_x <= 0 || size_y <= 0 || occupied.size() != static_cast<size_t>(size_x) * size_y)
|
||||
{
|
||||
size_x_ = size_y_ = 0;
|
||||
return;
|
||||
}
|
||||
size_x_ = size_x;
|
||||
size_y_ = size_y;
|
||||
occupancy_ = occupied;
|
||||
|
||||
// DynamicVoronoi keeps the bool** it is given and writes into it on occupy/clear, so the
|
||||
// storage has to outlive it and stay put. Column-major because it indexes data[x][y].
|
||||
columns_.clear();
|
||||
columns_.reserve(size_x_);
|
||||
column_ptrs_.assign(size_x_, nullptr);
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
{
|
||||
columns_.emplace_back(new bool[size_y_]);
|
||||
bool* col = columns_.back().get();
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
col[y] = occupancy_[static_cast<size_t>(y) * size_x_ + x] != 0;
|
||||
column_ptrs_[x] = col;
|
||||
}
|
||||
|
||||
dv_.reset(new DynamicVoronoi());
|
||||
dv_->initializeMap(size_x_, size_y_, column_ptrs_.data());
|
||||
dv_->update(true);
|
||||
dv_->prune();
|
||||
ready_ = true;
|
||||
}
|
||||
|
||||
void VoronoiField::setOccupied(const std::vector<Cell>& cells)
|
||||
{
|
||||
if (!ready_) return;
|
||||
for (const Cell& c : cells)
|
||||
{
|
||||
if (!inBounds(c.x, c.y)) continue;
|
||||
uint8_t& o = occupancy_[static_cast<size_t>(c.y) * size_x_ + c.x];
|
||||
if (o) continue;
|
||||
o = 1;
|
||||
dv_->occupyCell(c.x, c.y);
|
||||
}
|
||||
}
|
||||
|
||||
void VoronoiField::setFree(const std::vector<Cell>& cells)
|
||||
{
|
||||
if (!ready_) return;
|
||||
for (const Cell& c : cells)
|
||||
{
|
||||
if (!inBounds(c.x, c.y)) continue;
|
||||
uint8_t& o = occupancy_[static_cast<size_t>(c.y) * size_x_ + c.x];
|
||||
if (!o) continue;
|
||||
o = 0;
|
||||
dv_->clearCell(c.x, c.y);
|
||||
}
|
||||
}
|
||||
|
||||
void VoronoiField::refresh()
|
||||
{
|
||||
if (!ready_) return;
|
||||
dv_->update(true);
|
||||
dv_->prune();
|
||||
}
|
||||
|
||||
bool VoronoiField::isVoronoi(int x, int y) const
|
||||
{
|
||||
// DynamicVoronoi initialises every cell in state `free` (= "on the diagram") and its update
|
||||
// loops only touch neighbours inside [1, size-2], so the outer row/column is never processed
|
||||
// and stays flagged. It is not a ridge, it is untouched memory: the map frame is not GVD.
|
||||
if (!ready_ || x <= 0 || y <= 0 || x >= size_x_ - 1 || y >= size_y_ - 1) return false;
|
||||
return dv_->isVoronoi(x, y);
|
||||
}
|
||||
|
||||
bool VoronoiField::isOccupied(int x, int y) const
|
||||
{
|
||||
return ready_ && inBounds(x, y) && occupancy_[static_cast<size_t>(y) * size_x_ + x] != 0;
|
||||
}
|
||||
|
||||
float VoronoiField::distanceCells(int x, int y) const
|
||||
{
|
||||
if (!ready_ || !inBounds(x, y)) return 0.0f;
|
||||
if (isOccupied(x, y)) return 0.0f;
|
||||
// Port quirk: getDistance() treats x==0 / y==0 as out of range and returns -inf. Border cells
|
||||
// are next to the frame anyway; report them as touching an obstacle rather than leaking -inf
|
||||
// into a corridor width.
|
||||
const float d = dv_->getDistance(x, y);
|
||||
if (d < 0.0f) return 0.0f;
|
||||
// Cells no obstacle wave ever reached (a map with no obstacle at all) keep +inf; clamp to
|
||||
// "farther than the grid" so callers can still do arithmetic on it.
|
||||
if (!std::isfinite(d)) return static_cast<float>(size_x_ + size_y_);
|
||||
return d;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
681
src/voronoi_graph.cpp
Normal file
681
src/voronoi_graph.cpp
Normal file
@@ -0,0 +1,681 @@
|
||||
#include "voronoi_route/voronoi_graph.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <queue>
|
||||
#include <utility>
|
||||
|
||||
#include "voronoi_route/voronoi_field.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kDx[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
|
||||
constexpr int kDy[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
|
||||
|
||||
inline float stepLength(const Cell& a, const Cell& b)
|
||||
{
|
||||
return (a.x != b.x && a.y != b.y) ? 1.41421356f : 1.0f;
|
||||
}
|
||||
|
||||
float chainLength(const Polyline& cells)
|
||||
{
|
||||
float len = 0.0f;
|
||||
for (size_t i = 1; i < cells.size(); ++i) len += stepLength(cells[i - 1], cells[i]);
|
||||
return len;
|
||||
}
|
||||
|
||||
// Number of 8-connected components among the GVD cells in the 3x3 ring around (x, y), ignoring
|
||||
// the centre. Two ring cells are joined when they touch (Chebyshev distance 1).
|
||||
int ringComponents(const std::vector<uint8_t>& is_gvd, int w, int h, int x, int y, int* count)
|
||||
{
|
||||
int rx[8], ry[8], n = 0;
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const int nx = x + kDx[k], ny = y + kDy[k];
|
||||
if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
|
||||
if (!is_gvd[static_cast<size_t>(ny) * w + nx]) continue;
|
||||
rx[n] = nx;
|
||||
ry[n] = ny;
|
||||
++n;
|
||||
}
|
||||
if (count) *count = n;
|
||||
int parent[8];
|
||||
for (int i = 0; i < n; ++i) parent[i] = i;
|
||||
auto find = [&](int a) { while (parent[a] != a) a = parent[a] = parent[parent[a]]; return a; };
|
||||
for (int i = 0; i < n; ++i)
|
||||
for (int j = i + 1; j < n; ++j)
|
||||
if (std::abs(rx[i] - rx[j]) <= 1 && std::abs(ry[i] - ry[j]) <= 1) parent[find(i)] = find(j);
|
||||
int comps = 0;
|
||||
for (int i = 0; i < n; ++i) comps += find(i) == i ? 1 : 0;
|
||||
return comps;
|
||||
}
|
||||
|
||||
// Lau's prune leaves 8-connected lines that are two cells thick on diagonals ("**" stairs); with
|
||||
// 8-neighbour degrees every such cell looks like a junction. Delete cells whose GVD neighbours
|
||||
// stay one 8-connected piece without them, but only when they have >= 3 neighbours: a cell with
|
||||
// two neighbours is line interior or a line tip, and deleting tips would eat a two-thick branch
|
||||
// from its end inward one cell at a time. Stair cells have 3-4 neighbours, so the stairs collapse
|
||||
// to a single diagonal while branch length and topology stay. Sequential in scan order, so it is
|
||||
// deterministic.
|
||||
void thinToSkeleton(std::vector<uint8_t>& is_gvd, int w, int h)
|
||||
{
|
||||
for (int pass = 0; pass < 32; ++pass)
|
||||
{
|
||||
bool changed = false;
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
const size_t i = static_cast<size_t>(y) * w + x;
|
||||
if (!is_gvd[i]) continue;
|
||||
int n = 0;
|
||||
const int comps = ringComponents(is_gvd, w, h, x, y, &n);
|
||||
if (n >= 3 && comps == 1)
|
||||
{
|
||||
is_gvd[i] = 0;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void VoronoiGraph::clear()
|
||||
{
|
||||
size_x_ = size_y_ = 0;
|
||||
nodes_.clear();
|
||||
edges_.clear();
|
||||
cell_edge_.clear();
|
||||
cell_index_.clear();
|
||||
}
|
||||
|
||||
void VoronoiGraph::extract(const VoronoiField& field, const ExtractParams& params)
|
||||
{
|
||||
clear();
|
||||
if (!field.ready()) return;
|
||||
size_x_ = field.sizeX();
|
||||
size_y_ = field.sizeY();
|
||||
const size_t n = static_cast<size_t>(size_x_) * size_y_;
|
||||
|
||||
std::vector<uint8_t> is_gvd(n, 0);
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
is_gvd[static_cast<size_t>(y) * size_x_ + x] = field.isVoronoi(x, y) ? 1 : 0;
|
||||
thinToSkeleton(is_gvd, size_x_, size_y_);
|
||||
|
||||
std::vector<int> degree(n, 0);
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
{
|
||||
const size_t i = static_cast<size_t>(y) * size_x_ + x;
|
||||
if (!is_gvd[i]) continue;
|
||||
int d = 0;
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const int nx = x + kDx[k], ny = y + kDy[k];
|
||||
if (field.inBounds(nx, ny) && is_gvd[static_cast<size_t>(ny) * size_x_ + nx]) ++d;
|
||||
}
|
||||
degree[i] = d;
|
||||
}
|
||||
|
||||
// Nodes: junctions (>= 3) and dead ends (1). Isolated GVD pixels (0) are noise, dropped.
|
||||
std::vector<int> node_of_cell(n, -1);
|
||||
std::vector<uint8_t> visited(n, 0);
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
{
|
||||
const size_t i = static_cast<size_t>(y) * size_x_ + x;
|
||||
if (!is_gvd[i]) continue;
|
||||
if (degree[i] == 0)
|
||||
{
|
||||
visited[i] = 1;
|
||||
continue;
|
||||
}
|
||||
if (degree[i] != 2)
|
||||
{
|
||||
node_of_cell[i] = static_cast<int>(nodes_.size());
|
||||
nodes_.push_back(GraphNode{Cell(x, y), {}});
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<RawEdge> raw;
|
||||
traceFromNodes(field, is_gvd, degree, node_of_cell, visited, raw);
|
||||
traceCycles(field, is_gvd, node_of_cell, visited, raw);
|
||||
|
||||
edges_.clear();
|
||||
edges_.reserve(raw.size());
|
||||
for (RawEdge& r : raw)
|
||||
{
|
||||
GraphEdge e;
|
||||
e.u = r.u;
|
||||
e.v = r.v;
|
||||
e.cells = std::move(r.cells);
|
||||
e.length_cells = chainLength(e.cells);
|
||||
float mn = std::numeric_limits<float>::max();
|
||||
for (const Cell& c : e.cells) mn = std::min(mn, field.distanceCells(c.x, c.y));
|
||||
e.min_clearance_cells = e.cells.empty() ? 0.0f : mn;
|
||||
edges_.push_back(std::move(e));
|
||||
}
|
||||
|
||||
pruneSpursAndMerge(field, params);
|
||||
if (params.min_component_length_cells > 0.0) dropSmallComponents(params.min_component_length_cells);
|
||||
finalize(field);
|
||||
}
|
||||
|
||||
void VoronoiGraph::traceFromNodes(const VoronoiField& field, const std::vector<uint8_t>& is_gvd,
|
||||
const std::vector<int>& degree,
|
||||
std::vector<int>& node_of_cell, std::vector<uint8_t>& visited,
|
||||
std::vector<RawEdge>& raw)
|
||||
{
|
||||
(void)degree;
|
||||
auto idx = [this](int x, int y) { return static_cast<size_t>(y) * size_x_ + x; };
|
||||
|
||||
for (size_t ni = 0; ni < nodes_.size(); ++ni)
|
||||
{
|
||||
const Cell nc = nodes_[ni].cell;
|
||||
visited[idx(nc.x, nc.y)] = 1;
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const int sx = nc.x + kDx[k], sy = nc.y + kDy[k];
|
||||
if (!field.inBounds(sx, sy) || !is_gvd[idx(sx, sy)]) continue;
|
||||
const int other = node_of_cell[idx(sx, sy)];
|
||||
if (other >= 0)
|
||||
{
|
||||
// Two nodes touching: a zero-interior edge. Record once, from the lower index.
|
||||
if (static_cast<int>(ni) < other)
|
||||
raw.push_back(RawEdge{static_cast<int>(ni), other, {nc, Cell(sx, sy)}});
|
||||
continue;
|
||||
}
|
||||
if (visited[idx(sx, sy)]) continue; // chain already traced from its other end
|
||||
|
||||
Polyline chain{nc, Cell(sx, sy)};
|
||||
Cell prev = nc;
|
||||
Cell cur(sx, sy);
|
||||
visited[idx(cur.x, cur.y)] = 1;
|
||||
int end_node = -1;
|
||||
for (;;)
|
||||
{
|
||||
int next_node = -1;
|
||||
Cell next_free;
|
||||
bool have_free = false;
|
||||
for (int j = 0; j < 8; ++j)
|
||||
{
|
||||
const int nx = cur.x + kDx[j], ny = cur.y + kDy[j];
|
||||
if (!field.inBounds(nx, ny) || !is_gvd[idx(nx, ny)]) continue;
|
||||
if (nx == prev.x && ny == prev.y) continue;
|
||||
const int nn = node_of_cell[idx(nx, ny)];
|
||||
if (nn >= 0)
|
||||
{
|
||||
next_node = nn;
|
||||
break;
|
||||
}
|
||||
if (!visited[idx(nx, ny)] && !have_free)
|
||||
{
|
||||
next_free = Cell(nx, ny);
|
||||
have_free = true;
|
||||
}
|
||||
}
|
||||
if (next_node >= 0)
|
||||
{
|
||||
chain.push_back(nodes_[next_node].cell);
|
||||
end_node = next_node;
|
||||
break;
|
||||
}
|
||||
if (!have_free) break; // ran into already-visited territory: dangling, drop below
|
||||
prev = cur;
|
||||
cur = next_free;
|
||||
visited[idx(cur.x, cur.y)] = 1;
|
||||
chain.push_back(cur);
|
||||
}
|
||||
if (end_node >= 0) raw.push_back(RawEdge{static_cast<int>(ni), end_node, std::move(chain)});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void VoronoiGraph::traceCycles(const VoronoiField& field, const std::vector<uint8_t>& is_gvd,
|
||||
std::vector<int>& node_of_cell, std::vector<uint8_t>& visited,
|
||||
std::vector<RawEdge>& raw)
|
||||
{
|
||||
auto idx = [this](int x, int y) { return static_cast<size_t>(y) * size_x_ + x; };
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
{
|
||||
const size_t i = idx(x, y);
|
||||
if (!is_gvd[i] || visited[i]) continue;
|
||||
// Every unvisited GVD cell here has degree 2 and no node anywhere on its chain: a closed
|
||||
// ring. Make this cell a synthetic node and walk the ring back to it.
|
||||
const int ni = static_cast<int>(nodes_.size());
|
||||
nodes_.push_back(GraphNode{Cell(x, y), {}});
|
||||
node_of_cell[i] = ni;
|
||||
visited[i] = 1;
|
||||
|
||||
Polyline chain{Cell(x, y)};
|
||||
Cell prev(x, y);
|
||||
Cell cur(x, y);
|
||||
bool started = false;
|
||||
for (;;)
|
||||
{
|
||||
Cell next;
|
||||
bool found = false;
|
||||
for (int j = 0; j < 8; ++j)
|
||||
{
|
||||
const int nx = cur.x + kDx[j], ny = cur.y + kDy[j];
|
||||
if (!field.inBounds(nx, ny) || !is_gvd[idx(nx, ny)]) continue;
|
||||
if (started && nx == prev.x && ny == prev.y) continue;
|
||||
if (node_of_cell[idx(nx, ny)] == ni && started)
|
||||
{
|
||||
next = Cell(nx, ny);
|
||||
found = true;
|
||||
break; // closed the ring
|
||||
}
|
||||
if (!visited[idx(nx, ny)])
|
||||
{
|
||||
next = Cell(nx, ny);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) break;
|
||||
started = true;
|
||||
prev = cur;
|
||||
cur = next;
|
||||
chain.push_back(cur);
|
||||
if (node_of_cell[idx(cur.x, cur.y)] == ni) break;
|
||||
visited[idx(cur.x, cur.y)] = 1;
|
||||
}
|
||||
if (chain.size() >= 3 && chain.back() == chain.front())
|
||||
raw.push_back(RawEdge{ni, ni, std::move(chain)});
|
||||
}
|
||||
}
|
||||
|
||||
void VoronoiGraph::pruneSpursAndMerge(const VoronoiField& field, const ExtractParams& params)
|
||||
{
|
||||
const double min_edge_length_cells = params.min_edge_length_cells;
|
||||
auto clearanceAt = [&field](const Cell& c) { return static_cast<double>(field.distanceCells(c.x, c.y)); };
|
||||
std::vector<uint8_t> edge_alive(edges_.size(), 1);
|
||||
std::vector<uint8_t> node_alive(nodes_.size(), 1);
|
||||
|
||||
auto nodeDegree = [&](std::vector<int>& deg) {
|
||||
deg.assign(nodes_.size(), 0);
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
++deg[edges_[e].u];
|
||||
if (edges_[e].v != edges_[e].u) ++deg[edges_[e].v];
|
||||
}
|
||||
};
|
||||
|
||||
// 0a) Impassable edges go first; the rest of the loop then cleans up what they leave behind.
|
||||
if (params.min_clearance_cells > 0.0)
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
if (edges_[e].min_clearance_cells < params.min_clearance_cells) edge_alive[e] = 0;
|
||||
|
||||
for (int pass = 0; pass < 64; ++pass)
|
||||
{
|
||||
bool changed = false;
|
||||
std::vector<int> deg;
|
||||
nodeDegree(deg);
|
||||
|
||||
// 0) Junction clusters. Where the thinned GVD is still a small tangle (a triangle of three
|
||||
// cells at a fork, a tiny ring at a tip), the tangle shows up as short edges between
|
||||
// non-leaf nodes and short loops. Contract those edges into one node, splicing their cells
|
||||
// into the neighbouring edges so every chain stays 8-connected through the junction.
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
GraphEdge& ge = edges_[e];
|
||||
if (ge.length_cells >= min_edge_length_cells) continue;
|
||||
if (ge.u == ge.v)
|
||||
{
|
||||
edge_alive[e] = 0; // tiny loop: noise
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if (deg[ge.u] < 2 || deg[ge.v] < 2) continue; // leaf spurs handled below
|
||||
const int keep = std::min(ge.u, ge.v), drop = std::max(ge.u, ge.v);
|
||||
Polyline keep_to_drop = ge.cells; // oriented keep -> drop
|
||||
if (ge.u != keep) std::reverse(keep_to_drop.begin(), keep_to_drop.end());
|
||||
for (size_t f = 0; f < edges_.size(); ++f)
|
||||
{
|
||||
if (f == e || !edge_alive[f]) continue;
|
||||
GraphEdge& gf = edges_[f];
|
||||
if (gf.u == drop)
|
||||
{
|
||||
Polyline spliced = keep_to_drop;
|
||||
spliced.insert(spliced.end(), gf.cells.begin() + 1, gf.cells.end());
|
||||
gf.cells = std::move(spliced);
|
||||
gf.u = keep;
|
||||
}
|
||||
if (gf.v == drop)
|
||||
{
|
||||
gf.cells.insert(gf.cells.end(), keep_to_drop.rbegin() + 1, keep_to_drop.rend());
|
||||
gf.v = keep;
|
||||
}
|
||||
if (gf.u == drop || gf.v == drop) gf.length_cells = chainLength(gf.cells);
|
||||
else if (gf.u == keep && gf.v == keep) gf.length_cells = chainLength(gf.cells);
|
||||
}
|
||||
edge_alive[e] = 0;
|
||||
node_alive[drop] = 0;
|
||||
changed = true;
|
||||
nodeDegree(deg);
|
||||
}
|
||||
|
||||
// 1) Drop short dead-end branches.
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
const GraphEdge& ge = edges_[e];
|
||||
if (ge.u == ge.v) continue;
|
||||
const bool leaf_u = deg[ge.u] == 1, leaf_v = deg[ge.v] == 1;
|
||||
if (!leaf_u && !leaf_v) continue;
|
||||
bool drop = ge.length_cells < min_edge_length_cells;
|
||||
if (!drop && params.spur_clearance_ratio > 0.0 && leaf_u != leaf_v)
|
||||
{
|
||||
const Cell& root = leaf_u ? nodes_[ge.v].cell : nodes_[ge.u].cell;
|
||||
drop = ge.length_cells < params.spur_clearance_ratio * clearanceAt(root);
|
||||
}
|
||||
if (!drop) continue;
|
||||
edge_alive[e] = 0;
|
||||
changed = true;
|
||||
if (leaf_u) node_alive[ge.u] = 0;
|
||||
if (leaf_v) node_alive[ge.v] = 0;
|
||||
}
|
||||
if (changed) nodeDegree(deg);
|
||||
|
||||
// 2) A node left with exactly two distinct, non-loop edges is just a bend: merge them.
|
||||
for (size_t ni = 0; ni < nodes_.size(); ++ni)
|
||||
{
|
||||
if (!node_alive[ni] || deg[ni] != 2) continue;
|
||||
int e1 = -1, e2 = -1;
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
const GraphEdge& ge = edges_[e];
|
||||
if (ge.u == ge.v) continue;
|
||||
if (ge.u == static_cast<int>(ni) || ge.v == static_cast<int>(ni))
|
||||
{
|
||||
if (e1 < 0) e1 = static_cast<int>(e);
|
||||
else if (e2 < 0) e2 = static_cast<int>(e);
|
||||
}
|
||||
}
|
||||
if (e1 < 0 || e2 < 0) continue; // one of them is a loop; leave the node
|
||||
GraphEdge& a = edges_[e1];
|
||||
GraphEdge& b = edges_[e2];
|
||||
// Orient a to end at ni, b to start at ni.
|
||||
if (a.u == static_cast<int>(ni))
|
||||
{
|
||||
std::reverse(a.cells.begin(), a.cells.end());
|
||||
std::swap(a.u, a.v);
|
||||
}
|
||||
if (b.v == static_cast<int>(ni))
|
||||
{
|
||||
std::reverse(b.cells.begin(), b.cells.end());
|
||||
std::swap(b.u, b.v);
|
||||
}
|
||||
GraphEdge merged;
|
||||
merged.u = a.u;
|
||||
merged.v = b.v;
|
||||
merged.cells = a.cells;
|
||||
merged.cells.insert(merged.cells.end(), b.cells.begin() + 1, b.cells.end());
|
||||
merged.length_cells = a.length_cells + b.length_cells;
|
||||
merged.min_clearance_cells = std::min(a.min_clearance_cells, b.min_clearance_cells);
|
||||
edge_alive[e1] = edge_alive[e2] = 0;
|
||||
node_alive[ni] = 0;
|
||||
edges_.push_back(std::move(merged));
|
||||
edge_alive.push_back(1);
|
||||
changed = true;
|
||||
nodeDegree(deg);
|
||||
}
|
||||
if (!changed) break;
|
||||
}
|
||||
|
||||
// Compact, remapping node indices.
|
||||
std::vector<int> remap(nodes_.size(), -1);
|
||||
std::vector<GraphNode> new_nodes;
|
||||
for (size_t ni = 0; ni < nodes_.size(); ++ni)
|
||||
{
|
||||
if (!node_alive[ni]) continue;
|
||||
remap[ni] = static_cast<int>(new_nodes.size());
|
||||
new_nodes.push_back(GraphNode{nodes_[ni].cell, {}});
|
||||
}
|
||||
std::vector<GraphEdge> new_edges;
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
GraphEdge ge = std::move(edges_[e]);
|
||||
ge.u = remap[ge.u];
|
||||
ge.v = remap[ge.v];
|
||||
if (ge.u < 0 || ge.v < 0) continue;
|
||||
new_edges.push_back(std::move(ge));
|
||||
}
|
||||
nodes_ = std::move(new_nodes);
|
||||
edges_ = std::move(new_edges);
|
||||
}
|
||||
|
||||
void VoronoiGraph::dropSmallComponents(double min_total_length_cells)
|
||||
{
|
||||
std::vector<int> parent(nodes_.size());
|
||||
for (size_t i = 0; i < parent.size(); ++i) parent[i] = static_cast<int>(i);
|
||||
std::function<int(int)> find = [&](int a) { return parent[a] == a ? a : parent[a] = find(parent[a]); };
|
||||
for (const GraphEdge& e : edges_) parent[find(e.u)] = find(e.v);
|
||||
std::vector<double> total(nodes_.size(), 0.0);
|
||||
for (const GraphEdge& e : edges_) total[find(e.u)] += e.length_cells;
|
||||
|
||||
std::vector<int> remap(nodes_.size(), -1);
|
||||
std::vector<GraphNode> new_nodes;
|
||||
for (size_t i = 0; i < nodes_.size(); ++i)
|
||||
{
|
||||
if (total[find(static_cast<int>(i))] < min_total_length_cells) continue;
|
||||
remap[i] = static_cast<int>(new_nodes.size());
|
||||
new_nodes.push_back(GraphNode{nodes_[i].cell, {}});
|
||||
}
|
||||
std::vector<GraphEdge> new_edges;
|
||||
for (GraphEdge& e : edges_)
|
||||
{
|
||||
if (remap[e.u] < 0 || remap[e.v] < 0) continue;
|
||||
e.u = remap[e.u];
|
||||
e.v = remap[e.v];
|
||||
new_edges.push_back(std::move(e));
|
||||
}
|
||||
nodes_ = std::move(new_nodes);
|
||||
edges_ = std::move(new_edges);
|
||||
}
|
||||
|
||||
void VoronoiGraph::finalize(const VoronoiField& field)
|
||||
{
|
||||
// Deterministic order: sort edges by their first cell, then rebuild incidence lists.
|
||||
std::sort(edges_.begin(), edges_.end(), [](const GraphEdge& a, const GraphEdge& b) {
|
||||
const Cell& ca = a.cells.front();
|
||||
const Cell& cb = b.cells.front();
|
||||
return ca.y != cb.y ? ca.y < cb.y : ca.x < cb.x;
|
||||
});
|
||||
for (GraphNode& nd : nodes_) nd.edges.clear();
|
||||
|
||||
const size_t n = static_cast<size_t>(size_x_) * size_y_;
|
||||
cell_edge_.assign(n, -1);
|
||||
cell_index_.assign(n, -1);
|
||||
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
GraphEdge& ge = edges_[e];
|
||||
ge.cum_cells.assign(ge.cells.size(), 0.0f);
|
||||
float mn = std::numeric_limits<float>::max();
|
||||
for (size_t i = 0; i < ge.cells.size(); ++i)
|
||||
{
|
||||
if (i > 0) ge.cum_cells[i] = ge.cum_cells[i - 1] + stepLength(ge.cells[i - 1], ge.cells[i]);
|
||||
mn = std::min(mn, field.distanceCells(ge.cells[i].x, ge.cells[i].y));
|
||||
const size_t ci = static_cast<size_t>(ge.cells[i].y) * size_x_ + ge.cells[i].x;
|
||||
if (cell_edge_[ci] < 0)
|
||||
{
|
||||
cell_edge_[ci] = static_cast<int32_t>(e);
|
||||
cell_index_[ci] = static_cast<int32_t>(i);
|
||||
}
|
||||
}
|
||||
ge.length_cells = ge.cells.empty() ? 0.0f : ge.cum_cells.back();
|
||||
ge.min_clearance_cells = ge.cells.empty() ? 0.0f : mn;
|
||||
nodes_[ge.u].edges.push_back(static_cast<int>(e));
|
||||
if (ge.v != ge.u) nodes_[ge.v].edges.push_back(static_cast<int>(e));
|
||||
}
|
||||
}
|
||||
|
||||
int VoronoiGraph::edgeAt(int x, int y) const
|
||||
{
|
||||
if (x < 0 || y < 0 || x >= size_x_ || y >= size_y_ || cell_edge_.empty()) return -1;
|
||||
return cell_edge_[static_cast<size_t>(y) * size_x_ + x];
|
||||
}
|
||||
|
||||
int VoronoiGraph::indexOnEdge(int x, int y) const
|
||||
{
|
||||
if (x < 0 || y < 0 || x >= size_x_ || y >= size_y_ || cell_index_.empty()) return -1;
|
||||
return cell_index_[static_cast<size_t>(y) * size_x_ + x];
|
||||
}
|
||||
|
||||
int VoronoiGraph::componentCount() const
|
||||
{
|
||||
std::vector<int> parent(nodes_.size());
|
||||
for (size_t i = 0; i < parent.size(); ++i) parent[i] = static_cast<int>(i);
|
||||
std::function<int(int)> find = [&](int a) { return parent[a] == a ? a : parent[a] = find(parent[a]); };
|
||||
for (const GraphEdge& e : edges_) parent[find(e.u)] = find(e.v);
|
||||
int count = 0;
|
||||
for (size_t i = 0; i < parent.size(); ++i)
|
||||
if (find(static_cast<int>(i)) == static_cast<int>(i)) ++count;
|
||||
return count;
|
||||
}
|
||||
|
||||
Polyline VoronoiGraph::route(const Attachment& a, const Attachment& b) const
|
||||
{
|
||||
Polyline out;
|
||||
if (!a.ok || !b.ok || a.edge < 0 || b.edge < 0) return out;
|
||||
if (a.edge >= static_cast<int>(edges_.size()) || b.edge >= static_cast<int>(edges_.size())) return out;
|
||||
const GraphEdge& ea = edges_[a.edge];
|
||||
const GraphEdge& eb = edges_[b.edge];
|
||||
if (a.index < 0 || b.index < 0 || a.index >= static_cast<int>(ea.cells.size()) ||
|
||||
b.index >= static_cast<int>(eb.cells.size()))
|
||||
return out;
|
||||
|
||||
const float kInf = std::numeric_limits<float>::infinity();
|
||||
|
||||
// Candidate 0: stay on the same edge.
|
||||
float best = kInf;
|
||||
bool direct = false;
|
||||
if (a.edge == b.edge)
|
||||
{
|
||||
best = std::fabs(ea.cum_cells[a.index] - ea.cum_cells[b.index]);
|
||||
direct = true;
|
||||
}
|
||||
|
||||
// Dijkstra over nodes, seeded from both ends of a's edge.
|
||||
std::vector<float> dist(nodes_.size(), kInf);
|
||||
std::vector<int> parent_edge(nodes_.size(), -1);
|
||||
std::vector<int> parent_node(nodes_.size(), -1);
|
||||
std::vector<int> seed_side(nodes_.size(), -1); // 0 = reached via ea.u, 1 = via ea.v
|
||||
using QItem = std::pair<float, int>;
|
||||
std::priority_queue<QItem, std::vector<QItem>, std::greater<QItem>> pq;
|
||||
const float off_u = ea.cum_cells[a.index];
|
||||
const float off_v = ea.length_cells - off_u;
|
||||
auto seed = [&](int node, float d, int side) {
|
||||
if (d < dist[node])
|
||||
{
|
||||
dist[node] = d;
|
||||
seed_side[node] = side;
|
||||
parent_node[node] = -1;
|
||||
parent_edge[node] = -1;
|
||||
pq.push({d, node});
|
||||
}
|
||||
};
|
||||
seed(ea.u, off_u, 0);
|
||||
seed(ea.v, off_v, 1);
|
||||
|
||||
while (!pq.empty())
|
||||
{
|
||||
const QItem top = pq.top();
|
||||
pq.pop();
|
||||
const int u = top.second;
|
||||
if (top.first > dist[u]) continue;
|
||||
for (int e : nodes_[u].edges)
|
||||
{
|
||||
const GraphEdge& ge = edges_[e];
|
||||
if (ge.u == ge.v) continue;
|
||||
const int w = ge.u == u ? ge.v : ge.u;
|
||||
const float nd = dist[u] + ge.length_cells;
|
||||
if (nd < dist[w])
|
||||
{
|
||||
dist[w] = nd;
|
||||
parent_node[w] = u;
|
||||
parent_edge[w] = e;
|
||||
seed_side[w] = seed_side[u];
|
||||
pq.push({nd, w});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Candidate 1/2: arrive at b's edge through eb.u or eb.v.
|
||||
const float b_off_u = eb.cum_cells[b.index];
|
||||
const float b_off_v = eb.length_cells - b_off_u;
|
||||
int target = -1;
|
||||
int target_side = -1; // 0 = entered at eb.u, 1 = at eb.v
|
||||
if (dist[eb.u] + b_off_u < best)
|
||||
{
|
||||
best = dist[eb.u] + b_off_u;
|
||||
target = eb.u;
|
||||
target_side = 0;
|
||||
direct = false;
|
||||
}
|
||||
if (dist[eb.v] + b_off_v < best)
|
||||
{
|
||||
best = dist[eb.v] + b_off_v;
|
||||
target = eb.v;
|
||||
target_side = 1;
|
||||
direct = false;
|
||||
}
|
||||
if (!std::isfinite(best)) return out;
|
||||
|
||||
auto appendUnique = [&out](const Cell& c) {
|
||||
if (out.empty() || out.back() != c) out.push_back(c);
|
||||
};
|
||||
|
||||
if (direct)
|
||||
{
|
||||
if (a.index <= b.index)
|
||||
for (int i = a.index; i <= b.index; ++i) appendUnique(ea.cells[i]);
|
||||
else
|
||||
for (int i = a.index; i >= b.index; --i) appendUnique(ea.cells[i]);
|
||||
return out;
|
||||
}
|
||||
|
||||
// a's cell -> seed endpoint of ea.
|
||||
const int side = seed_side[target];
|
||||
if (side == 0)
|
||||
for (int i = a.index; i >= 0; --i) appendUnique(ea.cells[i]);
|
||||
else
|
||||
for (int i = a.index; i < static_cast<int>(ea.cells.size()); ++i) appendUnique(ea.cells[i]);
|
||||
|
||||
// Node chain from seed to target.
|
||||
std::vector<int> chain_nodes;
|
||||
for (int n = target; n != -1; n = parent_node[n]) chain_nodes.push_back(n);
|
||||
std::reverse(chain_nodes.begin(), chain_nodes.end());
|
||||
for (size_t i = 1; i < chain_nodes.size(); ++i)
|
||||
{
|
||||
const int to = chain_nodes[i];
|
||||
const GraphEdge& ge = edges_[parent_edge[to]];
|
||||
if (ge.u == chain_nodes[i - 1])
|
||||
for (size_t k = 0; k < ge.cells.size(); ++k) appendUnique(ge.cells[k]);
|
||||
else
|
||||
for (size_t k = ge.cells.size(); k-- > 0;) appendUnique(ge.cells[k]);
|
||||
}
|
||||
|
||||
// target endpoint of eb -> b's cell.
|
||||
if (target_side == 0)
|
||||
for (int i = 0; i <= b.index; ++i) appendUnique(eb.cells[i]);
|
||||
else
|
||||
for (int i = static_cast<int>(eb.cells.size()) - 1; i >= b.index; --i) appendUnique(eb.cells[i]);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
148
src/voronoi_route.cpp
Normal file
148
src/voronoi_route.cpp
Normal file
@@ -0,0 +1,148 @@
|
||||
#include "voronoi_route/voronoi_route.h"
|
||||
|
||||
#include <chrono>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
double msSince(const std::chrono::steady_clock::time_point& t0)
|
||||
{
|
||||
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
uint64_t hashObstacleMask(const std::vector<uint8_t>& occupied)
|
||||
{
|
||||
uint64_t h = 1469598103934665603ULL; // FNV offset basis
|
||||
uint8_t packed = 0;
|
||||
int bit = 0;
|
||||
for (uint8_t o : occupied)
|
||||
{
|
||||
if (o) packed |= static_cast<uint8_t>(1u << bit);
|
||||
if (++bit == 8)
|
||||
{
|
||||
h ^= packed;
|
||||
h *= 1099511628211ULL; // FNV prime
|
||||
packed = 0;
|
||||
bit = 0;
|
||||
}
|
||||
}
|
||||
if (bit != 0)
|
||||
{
|
||||
h ^= packed;
|
||||
h *= 1099511628211ULL;
|
||||
}
|
||||
h ^= static_cast<uint64_t>(occupied.size());
|
||||
h *= 1099511628211ULL;
|
||||
return h;
|
||||
}
|
||||
|
||||
VoronoiRoute::VoronoiRoute() = default;
|
||||
VoronoiRoute::VoronoiRoute(const Config& cfg) : cfg_(cfg) {}
|
||||
|
||||
void VoronoiRoute::rebuild(const std::vector<uint8_t>& occupied, int size_x, int size_y)
|
||||
{
|
||||
stats_ = Stats();
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
field_.rebuild(occupied, size_x, size_y);
|
||||
stats_.field_ms = msSince(t0);
|
||||
occupancy_hash_ = hashObstacleMask(field_.occupancy());
|
||||
for (uint8_t o : field_.occupancy()) stats_.obstacle_cells += o ? 1 : 0;
|
||||
extractGraph();
|
||||
}
|
||||
|
||||
size_t VoronoiRoute::syncOccupancy(const std::vector<uint8_t>& occupied, int size_x, int size_y)
|
||||
{
|
||||
if (!field_.ready() || size_x != field_.sizeX() || size_y != field_.sizeY() ||
|
||||
occupied.size() != field_.occupancy().size())
|
||||
{
|
||||
rebuild(occupied, size_x, size_y);
|
||||
stats_.last_sync_changed = occupied.size();
|
||||
stats_.last_sync_full_rebuild = true;
|
||||
return occupied.size();
|
||||
}
|
||||
|
||||
const std::vector<uint8_t>& have = field_.occupancy();
|
||||
std::vector<Cell> now_occupied, now_free;
|
||||
const int w = size_x;
|
||||
for (size_t i = 0; i < occupied.size(); ++i)
|
||||
{
|
||||
const bool a = have[i] != 0, b = occupied[i] != 0;
|
||||
if (a == b) continue;
|
||||
const Cell c(static_cast<int>(i % w), static_cast<int>(i / w));
|
||||
(b ? now_occupied : now_free).push_back(c);
|
||||
}
|
||||
const size_t changed = now_occupied.size() + now_free.size();
|
||||
stats_.last_sync_changed = changed;
|
||||
stats_.last_sync_full_rebuild = false;
|
||||
if (changed == 0) return 0;
|
||||
|
||||
if (static_cast<double>(changed) > cfg_.full_rebuild_fraction * static_cast<double>(occupied.size()))
|
||||
{
|
||||
rebuild(occupied, size_x, size_y);
|
||||
stats_.last_sync_changed = changed;
|
||||
stats_.last_sync_full_rebuild = true;
|
||||
return changed;
|
||||
}
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
field_.setOccupied(now_occupied);
|
||||
field_.setFree(now_free);
|
||||
field_.refresh();
|
||||
stats_.field_ms = msSince(t0);
|
||||
occupancy_hash_ = hashObstacleMask(field_.occupancy());
|
||||
stats_.obstacle_cells = 0;
|
||||
for (uint8_t o : field_.occupancy()) stats_.obstacle_cells += o ? 1 : 0;
|
||||
if (changed > cfg_.graph_rebuild_min_changed_cells || graph_.empty()) extractGraph();
|
||||
return changed;
|
||||
}
|
||||
|
||||
void VoronoiRoute::extractGraph()
|
||||
{
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
VoronoiGraph::ExtractParams ep;
|
||||
ep.min_edge_length_cells = cfg_.min_edge_length_cells;
|
||||
ep.spur_clearance_ratio = cfg_.spur_clearance_ratio;
|
||||
ep.min_component_length_cells = cfg_.min_component_length_cells;
|
||||
ep.min_clearance_cells = cfg_.min_clearance_cells;
|
||||
graph_.extract(field_, ep);
|
||||
stats_.extract_ms = msSince(t0);
|
||||
stats_.nodes = static_cast<int>(graph_.nodes().size());
|
||||
stats_.edges = static_cast<int>(graph_.edges().size());
|
||||
stats_.components = graph_.componentCount();
|
||||
stats_.gvd_cells = 0;
|
||||
for (int y = 0; y < field_.sizeY(); ++y)
|
||||
for (int x = 0; x < field_.sizeX(); ++x)
|
||||
if (field_.isVoronoi(x, y)) ++stats_.gvd_cells;
|
||||
}
|
||||
|
||||
Attachment VoronoiRoute::attach(Cell c) const
|
||||
{
|
||||
return attachPoint(field_, graph_, c, cfg_.attach_max_radius_cells);
|
||||
}
|
||||
|
||||
Polyline VoronoiRoute::query(const Attachment& start, const Attachment& goal) const
|
||||
{
|
||||
Polyline out;
|
||||
if (!start.ok || !goal.ok) return out;
|
||||
Polyline mid = graph_.route(start, goal);
|
||||
if (mid.empty()) return out;
|
||||
|
||||
auto appendUnique = [&out](const Cell& c) {
|
||||
if (out.empty() || out.back() != c) out.push_back(c);
|
||||
};
|
||||
for (const Cell& c : start.path) appendUnique(c); // start cell -> attach cell
|
||||
for (const Cell& c : mid) appendUnique(c); // along the graph
|
||||
for (size_t i = goal.path.size(); i-- > 0;) appendUnique(goal.path[i]); // attach -> goal cell
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> VoronoiRoute::corridorMask(const Polyline& route, const CorridorParams& p,
|
||||
size_t* cells_in_mask) const
|
||||
{
|
||||
return voronoi_route::corridorMask(field_, route, p, cells_in_mask);
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
Reference in New Issue
Block a user