Files
voronoi_route/tools/voronoi_route_compile.cpp
2026-09-22 15:44:53 +07:00

413 lines
19 KiB
C++

// voronoi_route_compile — build the Voronoi route graph of a map_server-style map (YAML + image)
// and write the bundle next to it, plus a preview PNG a human can look at.
//
// The tool is the only place with image/YAML dependencies (OpenCV, yaml-cpp). Everything it does
// after decoding is library API a host can call the same way: occupancyFromGray() ->
// VoronoiRoute::rebuild() -> saveBundle().
//
// "Obstacle" = pixel -> occupancy by the map's own `negate` / `occupied_thresh` / `free_thresh`
// (the map_server rule xloc also uses), then occupancy -> cost class by `lethal_cost_threshold` /
// `track_unknown_space` / `trinary_costmap` / `unknown_cost_value`, then NO_INFORMATION blocks or
// not by `unknown: traversable|obstacle`. All of it lives in `voronoi_route_params.yaml`'s own
// `obstacle:` block, decided by this package alone — it never reads another package's costmap or
// planner config. The rule is written to the bundle's `source` so a consumer hashes the live map
// the same way.
//
// Parameters come from `voronoi_route_params.yaml` (--params, else the first one found under
// --config-dir, else built-in defaults); every --flag below overrides one key for this run only.
//
// Usage:
// voronoi_route_compile --map <map.yaml> [--image <file>] [--out <dir, default: the map's folder>]
// [--config-dir <PNKX_NAV_CORE_CONFIG_DIR>] [--params <voronoi_route_params.yaml>]
// [--unknown-as-obstacle | --unknown-free]
// [--min-edge-m X] [--spur-ratio X] [--min-component-m X] [--min-clearance-m X]
// [--start-cell X Y --goal-cell X Y | --start-m X Y --goal-m X Y]
// [--half-width-m X] [--clearance-scale X] [--max-half-width-m X]
// [--no-preview] [--no-dist] [--no-gvd] [--no-graph-image] [--graph-overlay]
//
// --image overrides the YAML's `image:` — RBApp copies xloc's YAML verbatim (`image: t4.png`)
// next to a file it renamed to map.png.
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <yaml-cpp/yaml.h>
#include "voronoi_route/bundle_io.h"
#include "voronoi_route/map_convert.h"
#include "voronoi_route/params.h"
#include "voronoi_route/params_io.h"
#include "voronoi_route/voronoi_route.h"
namespace {
constexpr double kUnset = -1e300;
struct Args {
std::string map_yaml, image_override, out_dir, config_dir, params_yaml;
// Per-run overrides of voronoi_route_params.yaml; kUnset = keep the file's value.
double min_edge_m = kUnset, spur_ratio = kUnset, min_component_m = kUnset, min_clearance_m = kUnset;
double half_width_m = kUnset, clearance_scale = kUnset, max_half_width_m = kUnset;
int unknown_override = -1; // -1 = keep file's, 0 traversable, 1 obstacle
int preview = -1, write_dist = -1, write_gvd = -1, graph_image = -1, graph_overlay = -1; // -1 keep file's
bool have_start = false, have_goal = false, start_in_meters = false, goal_in_meters = false;
double sx = 0, sy = 0, gx = 0, gy = 0;
};
bool parseArgs(int argc, char** argv, Args& a)
{
for (int i = 1; i < argc; ++i)
{
const std::string k = argv[i];
auto need = [&](int n) {
if (i + n >= argc)
{
std::fprintf(stderr, "%s needs %d value(s)\n", k.c_str(), n);
std::exit(2);
}
};
if (k == "--map") { need(1); a.map_yaml = argv[++i]; }
else if (k == "--image") { need(1); a.image_override = argv[++i]; }
else if (k == "--out") { need(1); a.out_dir = argv[++i]; }
else if (k == "--min-edge-m") { need(1); a.min_edge_m = std::atof(argv[++i]); }
else if (k == "--spur-ratio") { need(1); a.spur_ratio = std::atof(argv[++i]); }
else if (k == "--min-component-m") { need(1); a.min_component_m = std::atof(argv[++i]); }
else if (k == "--min-clearance-m") { need(1); a.min_clearance_m = std::atof(argv[++i]); }
else if (k == "--config-dir") { need(1); a.config_dir = argv[++i]; }
else if (k == "--params") { need(1); a.params_yaml = argv[++i]; }
else if (k == "--unknown-free") { a.unknown_override = 0; }
else if (k == "--unknown-as-obstacle") { a.unknown_override = 1; }
else if (k == "--start-cell") { need(2); a.have_start = true; a.start_in_meters = false; a.sx = std::atof(argv[++i]); a.sy = std::atof(argv[++i]); }
else if (k == "--goal-cell") { need(2); a.have_goal = true; a.goal_in_meters = false; a.gx = std::atof(argv[++i]); a.gy = std::atof(argv[++i]); }
else if (k == "--start-m") { need(2); a.have_start = true; a.start_in_meters = true; a.sx = std::atof(argv[++i]); a.sy = std::atof(argv[++i]); }
else if (k == "--goal-m") { need(2); a.have_goal = true; a.goal_in_meters = true; a.gx = std::atof(argv[++i]); a.gy = std::atof(argv[++i]); }
else if (k == "--half-width-m") { need(1); a.half_width_m = std::atof(argv[++i]); }
else if (k == "--clearance-scale") { need(1); a.clearance_scale = std::atof(argv[++i]); }
else if (k == "--max-half-width-m") { need(1); a.max_half_width_m = std::atof(argv[++i]); }
else if (k == "--no-preview") { a.preview = 0; }
else if (k == "--no-dist") { a.write_dist = 0; }
else if (k == "--no-gvd") { a.write_gvd = 0; }
else if (k == "--no-graph-image") { a.graph_image = 0; }
else if (k == "--graph-overlay") { a.graph_overlay = 1; }
else
{
std::fprintf(stderr, "unknown argument: %s\n", k.c_str());
return false;
}
}
if (a.map_yaml.empty())
{
std::fprintf(stderr, "--map <map.yaml> is required\n");
return false;
}
if (a.config_dir.empty())
if (const char* e = std::getenv("PNKX_NAV_CORE_CONFIG_DIR")) a.config_dir = e;
return true;
}
struct MapMeta {
std::string image;
double resolution = 0.05, origin_x = 0, origin_y = 0, origin_yaw = 0;
voronoi_route::MapServerThresholds thr;
};
bool loadMeta(const std::string& yaml_path, MapMeta& m, std::string& err)
{
try
{
YAML::Node n = YAML::LoadFile(yaml_path);
m.image = n["image"].as<std::string>();
m.resolution = n["resolution"].as<double>();
const YAML::Node o = n["origin"];
m.origin_x = o[0].as<double>();
m.origin_y = o[1].as<double>();
m.origin_yaw = o.size() > 2 ? o[2].as<double>() : 0.0;
m.thr.negate = n["negate"] ? n["negate"].as<int>() != 0 : false;
if (n["occupied_thresh"]) m.thr.occupied_thresh = n["occupied_thresh"].as<double>();
if (n["free_thresh"]) m.thr.free_thresh = n["free_thresh"].as<double>();
return true;
}
catch (const std::exception& e)
{
err = e.what();
return false;
}
}
std::string dirOf(const std::string& path)
{
const size_t p = path.find_last_of('/');
return p == std::string::npos ? std::string(".") : path.substr(0, p);
}
} // namespace
int main(int argc, char** argv)
{
Args a;
if (!parseArgs(argc, argv, a)) return 2;
MapMeta meta;
std::string err;
if (!loadMeta(a.map_yaml, meta, err))
{
std::fprintf(stderr, "cannot read %s: %s\n", a.map_yaml.c_str(), err.c_str());
return 1;
}
const std::string map_dir = dirOf(a.map_yaml);
std::string image_path = a.image_override;
if (image_path.empty())
image_path = meta.image.front() == '/' ? meta.image : map_dir + "/" + meta.image;
else if (image_path.front() != '/' && image_path.find('/') == std::string::npos)
image_path = map_dir + "/" + image_path;
if (a.out_dir.empty()) a.out_dir = map_dir; // flat, next to the map files; names are voronoi_* so nothing collides
// UNCHANGED, not GRAYSCALE: the robot's map_server averages ALL channels of a pixel (alpha
// included in trinary mode) — a luminance decode of an RGBA map yields a different lethal set,
// a different hash, and the consumer rejects the graph. See occupancyFromImage().
cv::Mat raw = cv::imread(image_path, cv::IMREAD_UNCHANGED);
if (raw.empty())
{
std::fprintf(stderr, "cannot decode image %s (use --image to point at the real file)\n",
image_path.c_str());
return 1;
}
if (raw.depth() != CV_8U)
{
std::fprintf(stderr, "image %s is not 8-bit per channel (depth %d) — not supported\n",
image_path.c_str(), raw.depth());
return 1;
}
if (!raw.isContinuous()) raw = raw.clone();
const int w = raw.cols, h = raw.rows, channels = raw.channels();
// 8-bit channel average for the human-facing images only; classification uses `raw` in double.
cv::Mat img(h, w, CV_8UC1);
for (int y = 0; y < h; ++y)
{
const uint8_t* src = raw.ptr<uint8_t>(y);
uint8_t* dst = img.ptr<uint8_t>(y);
for (int x = 0; x < w; ++x)
{
int sum = 0;
for (int k = 0; k < channels; ++k) sum += src[x * channels + k];
dst[x] = static_cast<uint8_t>(sum / channels);
}
}
// ---- parameters: YAML first, flags override ---------------------------------------------------
voronoi_route::RouteParams prm;
std::string params_path = a.params_yaml;
if (params_path.empty()) params_path = voronoi_route::findConfigFile(a.config_dir, "voronoi_route_params.yaml");
if (!params_path.empty())
{
std::vector<std::string> notes;
if (!voronoi_route::loadRouteParams(params_path, &prm, &err, &notes))
{
std::fprintf(stderr, "params: %s\n", err.c_str());
return 1;
}
for (const auto& n : notes) std::fprintf(stderr, "params: %s\n", n.c_str());
}
auto ov = [](double& dst, double v) { if (v != kUnset) dst = v; };
ov(prm.min_edge_length_m, a.min_edge_m);
ov(prm.spur_clearance_ratio, a.spur_ratio);
ov(prm.min_component_length_m, a.min_component_m);
ov(prm.min_clearance_m, a.min_clearance_m);
ov(prm.half_width_min_m, a.half_width_m);
ov(prm.clearance_scale, a.clearance_scale);
ov(prm.half_width_max_m, a.max_half_width_m);
if (a.unknown_override != -1) prm.unknown_is_obstacle = a.unknown_override != 0;
if (a.preview >= 0) prm.write_preview = a.preview != 0;
if (a.write_dist >= 0) prm.write_dist = a.write_dist != 0;
if (a.write_gvd >= 0) prm.write_gvd = a.write_gvd != 0;
if (a.graph_image >= 0) prm.write_graph_image = a.graph_image != 0;
if (a.graph_overlay >= 0) prm.write_graph_overlay = a.graph_overlay != 0;
for (const auto& w : voronoi_route::validateRouteParams(&prm)) std::fprintf(stderr, "params: %s\n", w.c_str());
const voronoi_route::ObstacleRule rule = prm.toObstacleRule(meta.resolution);
const std::string rule_str = voronoi_route::obstacleRuleString(rule);
voronoi_route::MapConvertStats cs;
std::vector<uint8_t> occupied =
voronoi_route::occupancyFromImage(raw.ptr<uint8_t>(0), w, h, channels, meta.thr, rule, &cs);
const size_t roi_turned = voronoi_route::applyObstacleRoi(occupied, w, h, rule.roi_margin_cells);
const voronoi_route::VoronoiRoute::Config cfg = prm.toConfig(meta.resolution);
voronoi_route::VoronoiRoute vr(cfg);
const auto t0 = std::chrono::steady_clock::now();
vr.rebuild(occupied, w, h);
const double total_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
const auto& st = vr.stats();
std::printf("map : %s (%d x %d @ %.3f m, %d channel(s), origin %.3f %.3f)\n", image_path.c_str(),
w, h, meta.resolution, channels, meta.origin_x, meta.origin_y);
std::printf("params : %s\n", params_path.empty() ? "built-in defaults (no voronoi_route_params.yaml)" : params_path.c_str());
std::printf("rule : %s%s\n", rule_str.c_str(),
a.unknown_override != -1 ? " (unknown forced by --unknown-free/--unknown-as-obstacle)" : "");
std::printf("cells : lethal=%zu unknown=%zu (%s) free=%zu | roi: %zu cells outside box -> obstacle\n",
cs.occupied, cs.unknown,
rule.unknown == voronoi_route::UnknownPolicy::kObstacle ? "as obstacle" : "traversable",
cs.free, roi_turned);
std::printf("voronoi : field %.0f ms, extract %.0f ms, total %.0f ms\n", st.field_ms,
st.extract_ms, total_ms);
std::printf("graph : gvd_cells=%zu nodes=%d edges=%d components=%d (min_edge=%.1f cells, "
"spur_ratio=%.2f, min_component=%.0f cells, min_clearance=%.1f cells)\n",
st.gvd_cells, st.nodes, st.edges, st.components, cfg.min_edge_length_cells,
cfg.spur_clearance_ratio, cfg.min_component_length_cells, cfg.min_clearance_cells);
std::printf("hash : %016llx\n", static_cast<unsigned long long>(vr.occupancyHash()));
// ---- optional route ------------------------------------------------------------------------
auto toCell = [&](double x, double y, bool meters) {
if (!meters) return voronoi_route::Cell(static_cast<int>(std::lround(x)), static_cast<int>(std::lround(y)));
const double cx = (x - meta.origin_x) / meta.resolution;
const double cy_up = (y - meta.origin_y) / meta.resolution;
return voronoi_route::Cell(static_cast<int>(std::lround(cx)),
static_cast<int>(std::lround(h - 1 - cy_up)));
};
voronoi_route::Polyline route;
std::vector<uint8_t> mask;
size_t mask_cells = 0;
if (a.have_start && a.have_goal)
{
const voronoi_route::Cell s = toCell(a.sx, a.sy, a.start_in_meters);
const voronoi_route::Cell g = toCell(a.gx, a.gy, a.goal_in_meters);
const auto t1 = std::chrono::steady_clock::now();
const auto as = vr.attach(s);
const auto ag = vr.attach(g);
std::printf("attach : start (%d,%d) %s path=%zu | goal (%d,%d) %s path=%zu\n", s.x, s.y,
as.ok ? "ok" : "FAIL", as.path.size(), g.x, g.y, ag.ok ? "ok" : "FAIL",
ag.path.size());
route = vr.query(as, ag);
double route_m = 0.0;
for (size_t i = 1; i < route.size(); ++i)
route_m += ((route[i].x != route[i - 1].x && route[i].y != route[i - 1].y) ? 1.41421356 : 1.0) *
meta.resolution;
const voronoi_route::CorridorParams cp = prm.toCorridor(meta.resolution);
if (!route.empty()) mask = vr.corridorMask(route, cp, &mask_cells);
const double q_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t1).count();
const double euclid_m = std::hypot(g.x - s.x, g.y - s.y) * meta.resolution;
std::printf("route : %s cells=%zu length=%.1f m (euclid %.1f m) | mask=%zu cells (%.2f%% of map) "
"| query+mask %.1f ms\n",
route.empty() ? "NONE" : "ok", route.size(), route_m, euclid_m, mask_cells,
100.0 * mask_cells / (static_cast<double>(w) * h), q_ms);
}
// ---- bundle ----------------------------------------------------------------------------------
voronoi_route::BundleMeta bm;
bm.width = w;
bm.height = h;
bm.resolution = meta.resolution;
bm.origin_x = meta.origin_x;
bm.origin_y = meta.origin_y;
bm.origin_yaw = meta.origin_yaw;
bm.source = "costmap:" + rule_str;
bm.map_hash = vr.occupancyHash();
if (!voronoi_route::saveBundle(vr, bm, a.out_dir, prm.write_gvd, prm.write_dist, &err))
{
std::fprintf(stderr, "bundle: %s\n", err.c_str());
return 1;
}
if (!route.empty()) voronoi_route::appendRouteToBundle(a.out_dir, route, mask_cells, nullptr);
// ---- preview ---------------------------------------------------------------------------------
if (prm.write_preview)
{
cv::Mat pv(h, w, CV_8UC3);
for (int y = 0; y < h; ++y)
{
const uint8_t* row = img.ptr<uint8_t>(y);
cv::Vec3b* prow = pv.ptr<cv::Vec3b>(y);
for (int x = 0; x < w; ++x)
{
const double p = row[x];
const double occ = meta.thr.negate ? p / 255.0 : (255.0 - p) / 255.0;
if (occ > meta.thr.occupied_thresh) prow[x] = cv::Vec3b(0, 0, 0);
else if (occ >= meta.thr.free_thresh) prow[x] = cv::Vec3b(200, 200, 200);
else prow[x] = cv::Vec3b(255, 255, 255);
}
}
if (!mask.empty())
for (int y = 0; y < h; ++y)
for (int x = 0; x < w; ++x)
if (mask[static_cast<size_t>(y) * w + x])
{
cv::Vec3b& px = pv.at<cv::Vec3b>(y, x);
px = cv::Vec3b(static_cast<uint8_t>(px[0] * 0.55), static_cast<uint8_t>(px[1] * 0.75 + 60),
static_cast<uint8_t>(px[2] * 0.75 + 60));
}
// Raw GVD in pale pink (what the diagram is), graph edges in red (what survives pruning and
// is actually routed on). The difference is the pruning at work.
for (int y = 0; y < h; ++y)
for (int x = 0; x < w; ++x)
if (vr.field().isVoronoi(x, y)) pv.at<cv::Vec3b>(y, x) = cv::Vec3b(210, 190, 255);
for (const auto& e : vr.graph().edges())
for (const auto& c : e.cells) pv.at<cv::Vec3b>(c.y, c.x) = cv::Vec3b(0, 0, 255);
const int r = std::max(2, std::min(w, h) / 600);
for (const auto& nd : vr.graph().nodes())
cv::circle(pv, cv::Point(nd.cell.x, nd.cell.y), r, cv::Scalar(0, 180, 0), -1);
for (size_t i = 1; i < route.size(); ++i)
cv::line(pv, cv::Point(route[i - 1].x, route[i - 1].y), cv::Point(route[i].x, route[i].y),
cv::Scalar(255, 0, 0), std::max(1, r - 1));
if (a.have_start && a.have_goal)
{
const auto s = toCell(a.sx, a.sy, a.start_in_meters);
const auto g = toCell(a.gx, a.gy, a.goal_in_meters);
cv::circle(pv, cv::Point(s.x, s.y), r * 3, cv::Scalar(255, 0, 255), 2);
cv::circle(pv, cv::Point(g.x, g.y), r * 3, cv::Scalar(255, 128, 0), 2);
}
if (!cv::imwrite(a.out_dir + "/voronoi_preview.png", pv))
std::fprintf(stderr, "warning: cannot write voronoi_preview.png\n");
}
// ---- graph on the real map image ---------------------------------------------------------------
// Unlike the preview this keeps map.png's own pixels: what the operator sees is the scan, with the
// pruned graph on top. Junctions green, dead ends blue, edges red. The overlay variant is the same
// drawing on a transparent background for a web layer stacked over map.png.
if (prm.write_graph_image || prm.write_graph_overlay)
{
const int t = std::max(1, std::min(w, h) / 1200);
const int r = std::max(2, std::min(w, h) / 600);
auto draw = [&](cv::Mat& canvas, const cv::Scalar& edge, const cv::Scalar& junction,
const cv::Scalar& leaf) {
for (const auto& e : vr.graph().edges())
for (size_t i = 1; i < e.cells.size(); ++i)
cv::line(canvas, cv::Point(e.cells[i - 1].x, e.cells[i - 1].y),
cv::Point(e.cells[i].x, e.cells[i].y), edge, t, cv::LINE_8);
for (const auto& nd : vr.graph().nodes())
cv::circle(canvas, cv::Point(nd.cell.x, nd.cell.y), r,
nd.edges.size() == 1 ? leaf : junction, -1);
};
if (prm.write_graph_image)
{
cv::Mat base;
cv::cvtColor(img, base, cv::COLOR_GRAY2BGR);
draw(base, cv::Scalar(0, 0, 255), cv::Scalar(0, 180, 0), cv::Scalar(255, 120, 0));
if (!cv::imwrite(a.out_dir + "/voronoi_graph.png", base))
std::fprintf(stderr, "warning: cannot write voronoi_graph.png\n");
}
if (prm.write_graph_overlay)
{
cv::Mat ov(h, w, CV_8UC4, cv::Scalar(0, 0, 0, 0));
draw(ov, cv::Scalar(0, 0, 255, 255), cv::Scalar(0, 180, 0, 255), cv::Scalar(255, 120, 0, 255));
if (!cv::imwrite(a.out_dir + "/voronoi_graph_overlay.png", ov))
std::fprintf(stderr, "warning: cannot write voronoi_graph_overlay.png\n");
}
}
std::printf("bundle : %s/{voronoi.json%s%s%s%s%s}\n", a.out_dir.c_str(),
prm.write_gvd ? ", voronoi_gvd.pgm" : "", prm.write_dist ? ", voronoi_dist.pgm" : "",
prm.write_preview ? ", voronoi_preview.png" : "",
prm.write_graph_image ? ", voronoi_graph.png" : "",
prm.write_graph_overlay ? ", voronoi_graph_overlay.png" : "");
return 0;
}