Files
costmap_2d/src/reference_graph_worker.cpp
duongtd 5034029c6e feat(costmap_2d): background reference graph, shared keys under root:
- ReferenceGraph / ReferenceGraphWorker: Voronoi ridges and one-way lanes are
  computed on a low-priority thread when the map changes (reference_graph_*
  keys, off with rolling_window), with unit tests.
- Shared costmap keys can live in a root: map or flat at the top of the YAML;
  costmap_common_root_test covers both layouts.
- Static and directional layers report map changes to the layered costmap.
2026-11-10 16:37:55 +07:00

298 lines
9.5 KiB
C++

#include <robot_costmap_2d/reference_graph_worker.h>
#include <algorithm>
#include <chrono>
#include <exception>
#include <stdexcept>
#include <string>
#include <utility>
#ifdef __linux__
#include <sys/resource.h>
#include <sys/syscall.h>
#include <unistd.h>
#endif
#include <robot/robot.h>
#include <robot_costmap_2d/cost_values.h>
namespace robot_costmap_2d
{
namespace
{
using Clock = std::chrono::steady_clock;
// While an input is not ready the thread takes the master mutex this often. It sleeps for good once the graph is ready.
constexpr std::chrono::milliseconds kRetryPeriod(200);
// The NUC has 2 cores, and this thread must not take time from the control loop or the sensors.
constexpr int kThreadNice = 10;
double msSince(Clock::time_point begin) { return std::chrono::duration<double, std::milli>(Clock::now() - begin).count(); }
void lowerThreadPriority()
{
#ifdef __linux__
// Without this the graph still comes out, only the control loop may feel it, so a refusal is not an error.
if (setpriority(PRIO_PROCESS, static_cast<id_t>(syscall(SYS_gettid)), kThreadNice) != 0)
robot::log_warning("ReferenceGraphWorker: could not lower the thread priority\n");
#endif
}
bool sameGeometry(const DirectionGeometry& a, const DirectionGeometry& b)
{
return a.width == b.width && a.height == b.height && a.resolution == b.resolution && a.origin_x == b.origin_x &&
a.origin_y == b.origin_y && a.frame_id == b.frame_id;
}
} // namespace
std::vector<uint8_t> mergeStaticLayers(const std::vector<std::vector<uint8_t>>& layers)
{
if (layers.empty())
return {};
const std::size_t count = layers.front().size();
for (const std::vector<uint8_t>& layer : layers)
if (layer.size() != count)
throw std::invalid_argument("reference_graph: static layers differ in size");
std::vector<uint8_t> merged(count, NO_INFORMATION);
for (const std::vector<uint8_t>& layer : layers)
{
for (std::size_t i = 0; i < count; ++i)
{
if (layer[i] == LETHAL_OBSTACLE)
merged[i] = LETHAL_OBSTACLE;
else if (layer[i] != NO_INFORMATION && merged[i] == NO_INFORMATION)
merged[i] = FREE_SPACE;
}
}
return merged;
}
ReferenceGraphWorker::ReferenceGraphWorker(Source source, const ReferenceGraphParams& params)
: source_(std::move(source)), params_(params)
{
const std::string error = validateReferenceGraphParams(params_);
if (!error.empty())
throw std::invalid_argument("reference_graph: " + error);
if (!source_.capture || !source_.direction)
throw std::invalid_argument("reference_graph: missing source callback");
snapshot_.state = ReferenceGraphState::kPending;
snapshot_.generation = 1;
thread_ = std::thread(&ReferenceGraphWorker::run, this);
}
ReferenceGraphWorker::~ReferenceGraphWorker()
{
{
std::lock_guard<std::mutex> lock(mutex_);
stop_ = true;
cancel_.store(true, std::memory_order_relaxed);
}
wake_.notify_all();
thread_.join();
}
void ReferenceGraphWorker::markPendingLocked()
{
// Drop the old graph at once: it may hold the wrong map or the wrong zones, and the backup planner can run meanwhile.
if (snapshot_.state != ReferenceGraphState::kPending)
{
snapshot_.state = ReferenceGraphState::kPending;
snapshot_.graph.reset();
++snapshot_.generation;
}
cancel_.store(true, std::memory_order_relaxed);
}
void ReferenceGraphWorker::notifyStaticChanged()
{
{
std::lock_guard<std::mutex> lock(mutex_);
++static_revision_;
markPendingLocked();
}
wake_.notify_all();
}
void ReferenceGraphWorker::notifyDirectionChanged()
{
{
std::lock_guard<std::mutex> lock(mutex_);
++step2_revision_;
markPendingLocked();
}
wake_.notify_all();
}
void ReferenceGraphWorker::notifyFootprintChanged() { notifyDirectionChanged(); }
ReferenceGraphSnapshot ReferenceGraphWorker::snapshot() const
{
std::lock_guard<std::mutex> lock(mutex_);
return snapshot_;
}
ReferenceGraphWorkerStats ReferenceGraphWorker::stats() const
{
std::lock_guard<std::mutex> lock(mutex_);
return stats_;
}
ReferenceGraphWorker::Outcome ReferenceGraphWorker::compute(uint64_t static_revision, ReferenceGraph* graph)
{
const bool need_step1 = !skeleton_valid_ || skeleton_revision_ != static_revision;
ReferenceGraphInput input;
const Clock::time_point capture_began = Clock::now();
const ReferenceCaptureStatus status = source_.capture(need_step1, &input);
const double capture_ms = msSince(capture_began);
{
std::lock_guard<std::mutex> lock(mutex_);
stats_.capture_ms_max = std::max(stats_.capture_ms_max, capture_ms);
}
if (status == ReferenceCaptureStatus::kNoStaticLayer)
{
if (!no_static_logged_)
robot::log_error("ReferenceGraphWorker: reference_graph_enabled is true but no static layer is enabled\n");
no_static_logged_ = true;
return Outcome::kWait;
}
if (status != ReferenceCaptureStatus::kReady)
return Outcome::kWait;
no_static_logged_ = false;
ReferenceGridView view;
if (need_step1)
{
skeleton_valid_ = false;
static_cost_ = mergeStaticLayers(input.static_layers);
input.static_layers.clear();
geometry_ = input.geometry;
view.cost = static_cost_.data();
view.geometry = geometry_;
const Clock::time_point began = Clock::now();
skeleton_ = computeVoronoiSkeleton(view, params_, &cancel_);
if (cancel_.load(std::memory_order_relaxed))
return Outcome::kCancelled;
skeleton_valid_ = true;
skeleton_revision_ = static_revision;
std::lock_guard<std::mutex> lock(mutex_);
++stats_.step1_runs;
stats_.step1_ms_last = msSince(began);
}
const DirectionFieldSnapshot direction = source_.direction();
if (direction.state == DirectionFieldState::kPending)
return Outcome::kWait;
std::vector<uint8_t> codes;
if (direction.state == DirectionFieldState::kReady && direction.field != nullptr)
{
// A grid for another map layout belongs to the previous map. The new one is on its way.
if (!sameGeometry(direction.field->geometry(), geometry_))
return Outcome::kWait;
if (direction.field->hasConstraints())
{
codes.resize(static_cast<std::size_t>(geometry_.width) * geometry_.height);
for (uint32_t y = 0; y < geometry_.height; ++y)
{
if (cancel_.load(std::memory_order_relaxed))
return Outcome::kCancelled;
for (uint32_t x = 0; x < geometry_.width; ++x)
codes[static_cast<std::size_t>(y) * geometry_.width + x] = direction.field->code(x, y);
}
}
}
view.cost = static_cost_.data();
view.geometry = geometry_;
view.direction_codes = codes.empty() ? nullptr : codes.data();
const Clock::time_point began = Clock::now();
*graph = buildReferenceGraph(view, skeleton_, input.footprint, params_, &cancel_);
if (cancel_.load(std::memory_order_relaxed))
return Outcome::kCancelled;
graph->direction_generation = direction.generation;
std::lock_guard<std::mutex> lock(mutex_);
++stats_.step2_runs;
stats_.step2_ms_last = msSince(began);
return Outcome::kDone;
}
void ReferenceGraphWorker::run()
{
lowerThreadPriority();
while (true)
{
uint64_t static_revision = 0;
uint64_t step2_revision = 0;
{
std::unique_lock<std::mutex> lock(mutex_);
wake_.wait(lock, [this]() { return stop_ || static_revision_ != handled_static_ || step2_revision_ != handled_step2_; });
if (stop_)
return;
static_revision = static_revision_;
step2_revision = step2_revision_;
cancel_.store(false, std::memory_order_relaxed);
}
ReferenceGraph graph;
Outcome outcome = Outcome::kFailed;
std::string failure;
try
{
outcome = compute(static_revision, &graph);
}
catch (const std::exception& error)
{
failure = error.what();
}
catch (...)
{
failure = "unknown exception";
}
// An exception here must not take the whole navigation process down. The planner keeps failing over to its backup.
if (outcome == Outcome::kFailed)
robot::log_error("ReferenceGraphWorker: computation failed, staying pending until the next change: %s\n", failure.c_str());
std::unique_lock<std::mutex> lock(mutex_);
if (stop_)
return;
if (outcome == Outcome::kFailed)
++stats_.errors;
if (static_revision_ != static_revision || step2_revision_ != step2_revision)
continue; // Three maps in a row compute only the last one.
if (outcome == Outcome::kCancelled)
continue;
if (outcome == Outcome::kWait)
{
wake_.wait_for(lock, kRetryPeriod, [&]() {
return stop_ || static_revision_ != static_revision || step2_revision_ != step2_revision;
});
continue;
}
handled_static_ = static_revision;
handled_step2_ = step2_revision;
if (outcome != Outcome::kDone)
continue;
const std::size_t nodes = graph.nodes.size();
const std::size_t edges = graph.edges.size();
const std::size_t lanes = graph.lanes.size();
snapshot_.state = ReferenceGraphState::kReady;
snapshot_.graph = std::make_shared<const ReferenceGraph>(std::move(graph));
++snapshot_.generation;
++stats_.published;
const ReferenceGraphWorkerStats stats = stats_;
const uint64_t generation = snapshot_.generation;
lock.unlock();
if (params_.debug_log)
robot::log_info("[debug] ReferenceGraph ready: generation=%llu nodes=%zu edges=%zu lanes=%zu step1_ms=%.0f step2_ms=%.0f capture_ms_max=%.1f\n",
static_cast<unsigned long long>(generation), nodes, edges, lanes, stats.step1_ms_last, stats.step2_ms_last,
stats.capture_ms_max);
}
}
} // namespace robot_costmap_2d