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.
This commit is contained in:
@@ -63,7 +63,7 @@ namespace robot_costmap_2d
|
||||
template <class T>
|
||||
void move_parameter(robot::NodeHandle& old_h, robot::NodeHandle& new_h, std::string name,T& value)
|
||||
{
|
||||
if (!old_h.hasParam(name))
|
||||
if (new_h.hasParam(name) || !old_h.hasParam(name))
|
||||
return;
|
||||
|
||||
// A failed getParam() writes its default (0, false, "") into value; copying that would replace
|
||||
@@ -86,6 +86,17 @@ void move_parameters(robot::NodeHandle& old_h, robot::NodeHandle& new_h,
|
||||
}
|
||||
}
|
||||
|
||||
robot::NodeHandle Costmap2DROBOT::commonParametersHandle(robot::NodeHandle& tree_nh)
|
||||
{
|
||||
if (!tree_nh.hasParam("root"))
|
||||
return tree_nh;
|
||||
// A scalar or list `root:` would still be selected, and every shared key (sensor sources, zone
|
||||
// topics, transform_tolerance) would then read as missing. Refuse it instead of running blind.
|
||||
if (!tree_nh.getParamValue("root").IsMap())
|
||||
throw std::invalid_argument("'root' must be a map of shared costmap parameters");
|
||||
return robot::NodeHandle("root");
|
||||
}
|
||||
|
||||
Costmap2DROBOT::Costmap2DROBOT(const std::string& name, tf3::BufferCore& tf) :
|
||||
layered_costmap_(NULL),
|
||||
name_(name),
|
||||
@@ -127,6 +138,27 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
YAML::Node layer = config["robot_costmap_2d"];
|
||||
|
||||
robot::NodeHandle priv_nh(nh, name);
|
||||
robot::NodeHandle tree_nh("~");
|
||||
const bool rooted = tree_nh.hasParam("root");
|
||||
robot::NodeHandle common_nh = commonParametersHandle(tree_nh);
|
||||
robot::log_info("costmap '%s': shared parameters use %s layout\n",
|
||||
name.c_str(), rooted ? "root" : "flat");
|
||||
if (rooted)
|
||||
{
|
||||
std::string ignored_keys;
|
||||
for (const char* key : {"robot_base_frame", "transform_tolerance", "footprint_padding"})
|
||||
{
|
||||
if (tree_nh.hasParam(key))
|
||||
{
|
||||
if (!ignored_keys.empty())
|
||||
ignored_keys += ", ";
|
||||
ignored_keys += key;
|
||||
}
|
||||
}
|
||||
if (!ignored_keys.empty())
|
||||
robot::log_warning("costmap '%s': root layout ignores file-root keys: %s\n",
|
||||
name.c_str(), ignored_keys.c_str());
|
||||
}
|
||||
|
||||
// A costmap missing a layer, the layers after it or its update thread still looks alive to the
|
||||
// planner, which then drives on a map that never marks obstacles. Refuse to build it instead:
|
||||
@@ -147,8 +179,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
if (priv_nh.hasParam("global_frame"))
|
||||
priv_nh.getParam("global_frame", global_frame);
|
||||
|
||||
if (nh.hasParam("robot_base_frame"))
|
||||
nh.getParam("robot_base_frame", robot_base_frame);
|
||||
if (common_nh.hasParam("robot_base_frame"))
|
||||
common_nh.getParam("robot_base_frame", robot_base_frame);
|
||||
|
||||
global_frame_ = global_frame;
|
||||
robot_base_frame_ = robot_base_frame;
|
||||
@@ -285,12 +317,11 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
}
|
||||
}
|
||||
}
|
||||
robot::NodeHandle private_nh("~");
|
||||
for (auto& info : my_list)
|
||||
{
|
||||
try
|
||||
{
|
||||
copyParentParameters(name_, info.name, info.type, private_nh);
|
||||
copyParentParameters(name_, info.name, info.type, common_nh, tree_nh);
|
||||
creators_.push_back(
|
||||
boost::dll::import_alias<PluginLayerPtr()>(
|
||||
path_plugins, info.type, boost::dll::load_mode::append_decorations)
|
||||
@@ -318,8 +349,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
new_footprint = makeFootprintFromParams(priv_nh);
|
||||
}
|
||||
|
||||
if (nh.hasParam("transform_tolerance"))
|
||||
nh.getParam("transform_tolerance", transform_tolerance_);
|
||||
if (common_nh.hasParam("transform_tolerance"))
|
||||
common_nh.getParam("transform_tolerance", transform_tolerance_);
|
||||
// robot::log_info("transform_tolerance: %d", transform_tolerance_);
|
||||
|
||||
setUnpaddedRobotFootprint(new_footprint);
|
||||
@@ -342,8 +373,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
// If the padding has changed, call setUnpaddedRobotFootprint() to
|
||||
// re-apply the padding.
|
||||
float footprint_padding = loadParam(layer, "footprint_padding", 0.0);
|
||||
if (nh.hasParam("footprint_padding"))
|
||||
nh.getParam("footprint_padding", footprint_padding);
|
||||
if (common_nh.hasParam("footprint_padding"))
|
||||
common_nh.getParam("footprint_padding", footprint_padding);
|
||||
if (footprint_padding_ != footprint_padding)
|
||||
{
|
||||
footprint_padding_ = footprint_padding;
|
||||
@@ -355,6 +386,40 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
priv_nh.getParam("robot_radius", robot_radius);
|
||||
readFootprintFromConfig(new_footprint, unpadded_footprint_, robot_radius);
|
||||
|
||||
bool reference_graph_enabled = loadParam(layer, "reference_graph_enabled", false);
|
||||
if (priv_nh.hasParam("reference_graph_enabled"))
|
||||
priv_nh.getParam("reference_graph_enabled", reference_graph_enabled);
|
||||
if (reference_graph_enabled)
|
||||
{
|
||||
if (rolling_window)
|
||||
fail("reference_graph_enabled: true does not work with rolling_window: true");
|
||||
ReferenceGraphParams graph_params;
|
||||
const auto read_length = [&](const char* key, double* value) {
|
||||
*value = loadParam(layer, key, *value);
|
||||
if (priv_nh.hasParam(key))
|
||||
priv_nh.getParam(key, *value);
|
||||
};
|
||||
read_length("reference_graph_min_clearance_m", &graph_params.min_clearance_m);
|
||||
read_length("reference_graph_ridge_min_separation_m", &graph_params.ridge_min_separation_m);
|
||||
read_length("reference_graph_spur_min_length_m", &graph_params.spur_min_length_m);
|
||||
read_length("reference_graph_lane_offset_step_m", &graph_params.lane_offset_step_m);
|
||||
graph_params.debug_log = loadParam(layer, "reference_graph_debug_log", graph_params.debug_log);
|
||||
if (priv_nh.hasParam("reference_graph_debug_log"))
|
||||
priv_nh.getParam("reference_graph_debug_log", graph_params.debug_log);
|
||||
const std::string graph_error = validateReferenceGraphParams(graph_params);
|
||||
if (!graph_error.empty())
|
||||
fail("reference_graph: " + graph_error);
|
||||
if (!layered_costmap_->enableReferenceGraph(graph_params))
|
||||
fail("reference_graph: could not start");
|
||||
robot::log_info("costmap '%s': reference graph on, min_clearance=%.3f m ridge_separation=%.3f m spur=%.3f m lane_step=%.3f m debug_log=%d\n",
|
||||
name_.c_str(), graph_params.min_clearance_m, graph_params.ridge_min_separation_m, graph_params.spur_min_length_m,
|
||||
graph_params.lane_offset_step_m, graph_params.debug_log ? 1 : 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_info("costmap '%s': reference graph off\n", name_.c_str());
|
||||
}
|
||||
|
||||
// only construct the thread if the frequency is positive
|
||||
if(map_update_frequency > 0.0)
|
||||
map_update_thread_ = new boost::thread(boost::bind(&Costmap2DROBOT::mapUpdateLoop, this, map_update_frequency));
|
||||
@@ -372,21 +437,27 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
|
||||
const std::string& plugin_name,
|
||||
const std::string& plugin_type,
|
||||
robot::NodeHandle& nh)
|
||||
robot::NodeHandle& source_nh,
|
||||
robot::NodeHandle& target_nh)
|
||||
{
|
||||
// Step 2 of the layer config flow. A layer reads its default file, then overrides each key found
|
||||
// in "<costmap>/<plugin>". This copies the keys of the shared "<plugin>:" block there first, so the
|
||||
// lists below must hold every key the layer reads with hasParam(): a key missing here is ignored
|
||||
// without a word when it is set in the shared block. A copied key overwrites the same key in
|
||||
// "<costmap>/<plugin>". Types follow what the layer reads.
|
||||
robot::NodeHandle costmap_nh(nh, costmap_name);
|
||||
// in "<costmap>/<plugin>". Shared "<plugin>:" values fill only keys that the costmap block
|
||||
// does not set. The lists must cover every shared key read by the layer, with matching types.
|
||||
if (!source_nh.hasParam(plugin_name))
|
||||
return;
|
||||
// Child handles fall back to their parent when an intermediate namespace is missing.
|
||||
if (!target_nh.hasParam(costmap_name))
|
||||
target_nh.setParam(costmap_name, YAML::Node(YAML::NodeType::Map));
|
||||
robot::NodeHandle costmap_nh(target_nh, costmap_name);
|
||||
robot::NodeHandle costmap_plugin_nh(costmap_nh, plugin_name);
|
||||
robot::NodeHandle plugin_nh(nh, plugin_name);
|
||||
robot::NodeHandle plugin_nh(source_nh, plugin_name);
|
||||
|
||||
// observation_sources, then the keys of each source under "<plugin>/<source>/".
|
||||
const auto move_sources = [&](const auto& move_source_keys) {
|
||||
std::string topics_string;
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "observation_sources", topics_string);
|
||||
if (costmap_plugin_nh.hasParam("observation_sources"))
|
||||
costmap_plugin_nh.getParam("observation_sources", topics_string);
|
||||
std::stringstream ss(topics_string);
|
||||
std::string source;
|
||||
while (ss >> source)
|
||||
@@ -397,7 +468,10 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
|
||||
}
|
||||
};
|
||||
|
||||
if (plugin_type == "StaticLayer")
|
||||
// PreferredLayer and UnPreferredLayer inherit StaticLayer::getParams(), so they read the same keys.
|
||||
// Without them here a shared "preferred:" block is ignored and the layer keeps the default
|
||||
// map_topic "map", i.e. it would consume the static map itself.
|
||||
if (plugin_type == "StaticLayer" || plugin_type == "PreferredLayer" || plugin_type == "UnPreferredLayer")
|
||||
{
|
||||
move_parameters<std::string>(plugin_nh, costmap_plugin_nh, {"map_topic", "base_frame_id"});
|
||||
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"unknown_cost_value", "lethal_cost_threshold"});
|
||||
@@ -717,7 +791,7 @@ bool Costmap2DROBOT::getRobotPose(robot_geometry_msgs::PoseStamped& global_pose)
|
||||
// check global_pose timeout
|
||||
if (!global_pose.header.stamp.isZero() && current_time.toSec() - global_pose.header.stamp.toSec() > transform_tolerance_)
|
||||
{
|
||||
robot::log_warning("Costmap2DROBOT %s transform timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f\n", name_.c_str(),
|
||||
robot::log_warning_throttle(1.0,"Costmap2DROBOT %s transform timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f\n", name_.c_str(),
|
||||
current_time.toSec(), global_pose.header.stamp.toSec(), transform_tolerance_);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -37,7 +37,10 @@
|
||||
*********************************************************************/
|
||||
#include <robot_costmap_2d/layered_costmap.h>
|
||||
#include <robot_costmap_2d/footprint.h>
|
||||
#include <robot_costmap_2d/reference_graph_worker.h>
|
||||
#include <cstdio>
|
||||
#include <exception>
|
||||
#include <utility>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
@@ -186,6 +189,8 @@ namespace robot_costmap_2d
|
||||
|
||||
LayeredCostmap::~LayeredCostmap()
|
||||
{
|
||||
// The worker reads the plugins, so it stops first.
|
||||
reference_graph_worker_.reset();
|
||||
while (plugins_.size() > 0)
|
||||
{
|
||||
plugins_.pop_back();
|
||||
@@ -385,6 +390,88 @@ namespace robot_costmap_2d
|
||||
return result;
|
||||
}
|
||||
|
||||
bool LayeredCostmap::enableReferenceGraph(const ReferenceGraphParams& params)
|
||||
{
|
||||
if (rolling_window_)
|
||||
{
|
||||
robot::log_error("Reference graph needs a static map; it cannot run on a rolling costmap\n");
|
||||
return false;
|
||||
}
|
||||
if (reference_graph_worker_)
|
||||
{
|
||||
robot::log_error("Reference graph is already enabled\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
ReferenceGraphWorker::Source source;
|
||||
source.capture = [this](bool with_grid, ReferenceGraphInput* input) {
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*costmap_.getMutex());
|
||||
input->geometry = {costmap_.getSizeInCellsX(), costmap_.getSizeInCellsY(), costmap_.getResolution(),
|
||||
costmap_.getOriginX(), costmap_.getOriginY(), global_frame_};
|
||||
input->footprint = footprint_;
|
||||
if (!with_grid)
|
||||
return ReferenceCaptureStatus::kReady;
|
||||
|
||||
// Copy under the lock and merge outside it: a large map must not stall the costmap update.
|
||||
std::vector<const Costmap2D*> grids;
|
||||
for (const auto& plugin : plugins_)
|
||||
{
|
||||
if (!plugin->isEnabled() || plugin->getType() != LayerType::STATIC_LAYER)
|
||||
continue;
|
||||
const auto* grid = dynamic_cast<const Costmap2D*>(plugin.get());
|
||||
if (grid == nullptr || !plugin->isCurrent() || grid->getSizeInCellsX() != costmap_.getSizeInCellsX() ||
|
||||
grid->getSizeInCellsY() != costmap_.getSizeInCellsY())
|
||||
return ReferenceCaptureStatus::kWait;
|
||||
grids.push_back(grid);
|
||||
}
|
||||
if (grids.empty())
|
||||
return ReferenceCaptureStatus::kNoStaticLayer;
|
||||
const std::size_t cells = static_cast<std::size_t>(costmap_.getSizeInCellsX()) * costmap_.getSizeInCellsY();
|
||||
if (cells == 0)
|
||||
return ReferenceCaptureStatus::kWait;
|
||||
input->static_layers.reserve(grids.size());
|
||||
for (const Costmap2D* grid : grids)
|
||||
input->static_layers.emplace_back(grid->getCharMap(), grid->getCharMap() + cells);
|
||||
return ReferenceCaptureStatus::kReady;
|
||||
};
|
||||
source.direction = [this]() { return getDirectionFieldSnapshot(); };
|
||||
try
|
||||
{
|
||||
reference_graph_worker_.reset(new ReferenceGraphWorker(std::move(source), params));
|
||||
}
|
||||
catch (const std::exception& error)
|
||||
{
|
||||
robot::log_error("Reference graph not started: %s\n", error.what());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
ReferenceGraphSnapshot LayeredCostmap::getReferenceGraphSnapshot() const
|
||||
{
|
||||
return reference_graph_worker_ ? reference_graph_worker_->snapshot() : ReferenceGraphSnapshot{};
|
||||
}
|
||||
|
||||
static_assert(static_cast<std::size_t>(LayerType::DEPTH_CAMERA_LAYER) < 16, "grow kMaxLayerTypes");
|
||||
|
||||
uint64_t LayeredCostmap::getStaticMapRevision(LayerType type) const
|
||||
{
|
||||
return static_map_revisions_[static_cast<std::size_t>(type)].load();
|
||||
}
|
||||
|
||||
void LayeredCostmap::notifyStaticMapChanged(LayerType type)
|
||||
{
|
||||
++static_map_revisions_[static_cast<std::size_t>(type)];
|
||||
if (type == LayerType::STATIC_LAYER && reference_graph_worker_)
|
||||
reference_graph_worker_->notifyStaticChanged();
|
||||
}
|
||||
|
||||
void LayeredCostmap::notifyDirectionFieldChanged()
|
||||
{
|
||||
if (reference_graph_worker_)
|
||||
reference_graph_worker_->notifyDirectionChanged();
|
||||
}
|
||||
|
||||
bool LayeredCostmap::isCurrent()
|
||||
{
|
||||
current_ = true;
|
||||
@@ -399,7 +486,16 @@ namespace robot_costmap_2d
|
||||
|
||||
void LayeredCostmap::setFootprint(const std::vector<robot_geometry_msgs::Point> &footprint_spec)
|
||||
{
|
||||
footprint_ = footprint_spec;
|
||||
bool changed = footprint_.size() != footprint_spec.size();
|
||||
for (std::size_t i = 0; !changed && i < footprint_.size(); ++i)
|
||||
changed = footprint_[i].x != footprint_spec[i].x || footprint_[i].y != footprint_spec[i].y;
|
||||
{
|
||||
// The reference graph thread copies the footprint under this lock.
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*costmap_.getMutex());
|
||||
footprint_ = footprint_spec;
|
||||
}
|
||||
if (changed && reference_graph_worker_)
|
||||
reference_graph_worker_->notifyFootprintChanged();
|
||||
robot_costmap_2d::calculateMinAndMaxDistances(footprint_spec, inscribed_radius_, circumscribed_radius_);
|
||||
|
||||
for (vector<boost::shared_ptr<Layer>>::iterator plugin = plugins_.begin(); plugin != plugins_.end();
|
||||
|
||||
979
src/reference_graph.cpp
Normal file
979
src/reference_graph.cpp
Normal file
@@ -0,0 +1,979 @@
|
||||
#include <robot_costmap_2d/reference_graph.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
// Lane scan constants of the prototype. They are geometry of the search, not robot tuning, so they
|
||||
// stay out of YAML. A direction grid finer than 5 cm would need a smaller sample step.
|
||||
constexpr double kLaneScanStepM = 0.1;
|
||||
constexpr double kLaneSampleStepM = 0.05;
|
||||
constexpr double kLaneMatchToleranceM = 0.12;
|
||||
constexpr double kLaneMinLengthM = 0.3;
|
||||
constexpr double kLaneSameEntryM = 0.02;
|
||||
constexpr int kMaxSpurRounds = 20;
|
||||
constexpr int kKeepEveryCells = 5; // 0.25 m at 5 cm, enough for the route search.
|
||||
constexpr double kPi = 3.141592653589793;
|
||||
constexpr uint16_t kMaxClearanceMm = 65535;
|
||||
|
||||
bool cancelled(const std::atomic<bool>* cancel)
|
||||
{
|
||||
return cancel != nullptr && cancel->load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void checkGeometry(const DirectionGeometry& geometry)
|
||||
{
|
||||
if (geometry.width == 0 || geometry.height == 0 || !std::isfinite(geometry.resolution) || geometry.resolution <= 0.0 ||
|
||||
!std::isfinite(geometry.origin_x) || !std::isfinite(geometry.origin_y))
|
||||
throw std::invalid_argument("reference_graph: invalid grid geometry");
|
||||
// Cell indices are int32_t in this file, with a one-cell padding on each side.
|
||||
const uint64_t padded = (static_cast<uint64_t>(geometry.width) + 2) * (static_cast<uint64_t>(geometry.height) + 2);
|
||||
if (padded > static_cast<uint64_t>(std::numeric_limits<int32_t>::max()))
|
||||
throw std::invalid_argument("reference_graph: grid too large");
|
||||
}
|
||||
|
||||
void checkParams(const ReferenceGraphParams& params)
|
||||
{
|
||||
const std::string error = validateReferenceGraphParams(params);
|
||||
if (!error.empty())
|
||||
throw std::invalid_argument("reference_graph: " + error);
|
||||
}
|
||||
|
||||
/** Binary grid with a one-cell empty border, so neighbour lookups need no bounds checks. */
|
||||
class PaddedMask
|
||||
{
|
||||
public:
|
||||
PaddedMask(int32_t width, int32_t height)
|
||||
: width_(width), height_(height), stride_(width + 2),
|
||||
cells_(static_cast<std::size_t>(width + 2) * static_cast<std::size_t>(height + 2), 0)
|
||||
{
|
||||
}
|
||||
|
||||
int32_t index(int32_t x, int32_t y) const { return (y + 1) * stride_ + x + 1; }
|
||||
int32_t x(int32_t padded) const { return padded % stride_ - 1; }
|
||||
int32_t y(int32_t padded) const { return padded / stride_ - 1; }
|
||||
int32_t stride() const { return stride_; }
|
||||
int32_t width() const { return width_; }
|
||||
int32_t height() const { return height_; }
|
||||
std::size_t size() const { return cells_.size(); }
|
||||
uint8_t& operator[](int32_t padded) { return cells_[static_cast<std::size_t>(padded)]; }
|
||||
uint8_t operator[](int32_t padded) const { return cells_[static_cast<std::size_t>(padded)]; }
|
||||
|
||||
private:
|
||||
int32_t width_, height_, stride_;
|
||||
std::vector<uint8_t> cells_;
|
||||
};
|
||||
|
||||
/** Skeleton neighbours. A diagonal step is skipped when a 4-connected path already links the two cells. */
|
||||
int skeletonNeighbours(const PaddedMask& mask, int32_t cell, int32_t out[8])
|
||||
{
|
||||
const int32_t stride = mask.stride();
|
||||
int count = 0;
|
||||
for (int dy = -1; dy <= 1; ++dy)
|
||||
{
|
||||
for (int dx = -1; dx <= 1; ++dx)
|
||||
{
|
||||
if (dx == 0 && dy == 0)
|
||||
continue;
|
||||
const int32_t other = cell + dy * stride + dx;
|
||||
if (mask[other] == 0)
|
||||
continue;
|
||||
if (dx != 0 && dy != 0 && (mask[cell + dx] != 0 || mask[cell + dy * stride] != 0))
|
||||
continue;
|
||||
out[count++] = other;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** Nearest feature cell per grid cell, as row-major index, -1 when the grid has no feature.
|
||||
*
|
||||
* Same tie-breaking as scipy.ndimage.distance_transform_edt, which the ridge test is sensitive to:
|
||||
* the lower row wins in the column pass, the lower column in the row pass.
|
||||
* @return False when cancelled. */
|
||||
template <typename IsFeature>
|
||||
bool nearestFeature(int32_t width, int32_t height, IsFeature is_feature, std::vector<int32_t>* nearest,
|
||||
const std::atomic<bool>* cancel)
|
||||
{
|
||||
nearest->assign(static_cast<std::size_t>(width) * static_cast<std::size_t>(height), -1);
|
||||
std::vector<int32_t>& result = *nearest;
|
||||
|
||||
// Column pass, walked row by row to stay cache friendly on a 3000 x 3000 grid. Holds the feature row.
|
||||
std::vector<int32_t> column_feature(static_cast<std::size_t>(width), -1);
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return false;
|
||||
int32_t* row = result.data() + static_cast<std::ptrdiff_t>(y) * width;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (is_feature(y * width + x))
|
||||
column_feature[static_cast<std::size_t>(x)] = y;
|
||||
row[x] = column_feature[static_cast<std::size_t>(x)];
|
||||
}
|
||||
}
|
||||
std::fill(column_feature.begin(), column_feature.end(), -1);
|
||||
for (int32_t y = height - 1; y >= 0; --y)
|
||||
{
|
||||
int32_t* row = result.data() + static_cast<std::ptrdiff_t>(y) * width;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (is_feature(y * width + x))
|
||||
column_feature[static_cast<std::size_t>(x)] = y;
|
||||
const int32_t below = column_feature[static_cast<std::size_t>(x)];
|
||||
if (below >= 0 && (row[x] < 0 || below - y < y - row[x]))
|
||||
row[x] = below;
|
||||
}
|
||||
}
|
||||
|
||||
// Row pass: lower envelope of the column results, as in Maurer's linear-time transform.
|
||||
std::vector<int32_t> feature_row(static_cast<std::size_t>(width));
|
||||
std::vector<int32_t> envelope(static_cast<std::size_t>(width));
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return false;
|
||||
int32_t* row = result.data() + static_cast<std::ptrdiff_t>(y) * width;
|
||||
std::copy(row, row + width, feature_row.begin());
|
||||
const auto squared_row = [&](int32_t x) {
|
||||
const double dy = feature_row[static_cast<std::size_t>(x)] - y;
|
||||
return dy * dy;
|
||||
};
|
||||
int32_t last = -1;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (feature_row[static_cast<std::size_t>(x)] < 0)
|
||||
continue;
|
||||
const double new_row = squared_row(x);
|
||||
while (last >= 1)
|
||||
{
|
||||
const int32_t middle = envelope[static_cast<std::size_t>(last)];
|
||||
const int32_t before = envelope[static_cast<std::size_t>(last - 1)];
|
||||
const double a = middle - before;
|
||||
const double b = x - middle;
|
||||
const double c = a + b;
|
||||
if (c * squared_row(middle) - b * squared_row(before) - a * new_row - a * b * c <= 0.0)
|
||||
break;
|
||||
--last;
|
||||
}
|
||||
envelope[static_cast<std::size_t>(++last)] = x;
|
||||
}
|
||||
if (last < 0)
|
||||
continue;
|
||||
int32_t current = 0;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
const auto squared_distance = [&](int32_t slot) {
|
||||
const int32_t column = envelope[static_cast<std::size_t>(slot)];
|
||||
const double dx = column - x;
|
||||
return squared_row(column) + dx * dx;
|
||||
};
|
||||
double best = squared_distance(current);
|
||||
while (current < last)
|
||||
{
|
||||
const double next = squared_distance(current + 1);
|
||||
if (best <= next)
|
||||
break;
|
||||
best = next;
|
||||
++current;
|
||||
}
|
||||
const int32_t column = envelope[static_cast<std::size_t>(current)];
|
||||
row[x] = feature_row[static_cast<std::size_t>(column)] * width + column;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Zhang-Suen thinning. Only ridge cells are visited, so the cost follows the ridge size and not the map size.
|
||||
* A cell is re-tested in a phase only after a neighbour changed, since the test depends on nothing else.
|
||||
* @return False when cancelled. */
|
||||
bool thinSkeleton(PaddedMask* mask_ptr, std::vector<int32_t>* active, const std::atomic<bool>* cancel)
|
||||
{
|
||||
PaddedMask& mask = *mask_ptr;
|
||||
const int32_t stride = mask.stride();
|
||||
const int32_t offsets[8] = { -stride, -stride + 1, 1, stride + 1, stride, stride - 1, -1, -stride - 1 };
|
||||
std::vector<uint8_t> pending(mask.size(), 0);
|
||||
for (int32_t cell : *active)
|
||||
pending[static_cast<std::size_t>(cell)] = 3;
|
||||
|
||||
std::vector<int32_t> removal;
|
||||
while (true)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return false;
|
||||
bool changed = false;
|
||||
for (int phase = 0; phase < 2; ++phase)
|
||||
{
|
||||
const uint8_t bit = static_cast<uint8_t>(1U << phase);
|
||||
removal.clear();
|
||||
for (int32_t cell : *active)
|
||||
{
|
||||
uint8_t& flags = pending[static_cast<std::size_t>(cell)];
|
||||
if ((flags & bit) == 0 || mask[cell] == 0)
|
||||
continue;
|
||||
flags = static_cast<uint8_t>(flags & ~bit);
|
||||
const uint8_t n = mask[cell + offsets[0]], ne = mask[cell + offsets[1]], e = mask[cell + offsets[2]],
|
||||
se = mask[cell + offsets[3]], s = mask[cell + offsets[4]], sw = mask[cell + offsets[5]],
|
||||
w = mask[cell + offsets[6]], nw = mask[cell + offsets[7]];
|
||||
const int count = n + ne + e + se + s + sw + w + nw;
|
||||
if (count < 2 || count > 6)
|
||||
continue;
|
||||
const uint8_t sequence[9] = { n, ne, e, se, s, sw, w, nw, n };
|
||||
int transitions = 0;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
transitions += (sequence[i] == 0 && sequence[i + 1] != 0) ? 1 : 0;
|
||||
if (transitions != 1)
|
||||
continue;
|
||||
const bool extra = phase == 0 ? ((n == 0 || e == 0 || s == 0) && (e == 0 || s == 0 || w == 0)) :
|
||||
((n == 0 || e == 0 || w == 0) && (n == 0 || s == 0 || w == 0));
|
||||
if (extra)
|
||||
removal.push_back(cell);
|
||||
}
|
||||
for (int32_t cell : removal)
|
||||
{
|
||||
mask[cell] = 0;
|
||||
for (int32_t offset : offsets)
|
||||
pending[static_cast<std::size_t>(cell + offset)] = 3;
|
||||
}
|
||||
changed = changed || !removal.empty();
|
||||
}
|
||||
active->erase(std::remove_if(active->begin(), active->end(), [&](int32_t cell) { return mask[cell] == 0; }),
|
||||
active->end());
|
||||
if (!changed)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove terminal branches shorter than `minimum` [m] that end on a junction. An isolated line stays.
|
||||
* @return False when cancelled. */
|
||||
bool pruneSpurs(PaddedMask* mask_ptr, std::vector<int32_t>* pixels, double resolution, double minimum,
|
||||
const std::atomic<bool>* cancel)
|
||||
{
|
||||
PaddedMask& mask = *mask_ptr;
|
||||
const int32_t stride = mask.stride();
|
||||
const double diagonal = std::hypot(1.0, 1.0);
|
||||
std::vector<int32_t> path;
|
||||
std::vector<int32_t> doomed;
|
||||
for (int round = 0; round < kMaxSpurRounds; ++round)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return false;
|
||||
doomed.clear();
|
||||
int32_t around[8];
|
||||
for (int32_t start : *pixels)
|
||||
{
|
||||
if (skeletonNeighbours(mask, start, around) != 1)
|
||||
continue;
|
||||
path.assign(1, start);
|
||||
int32_t previous = -1;
|
||||
int32_t current = start;
|
||||
double length = 0.0;
|
||||
int degree = 1;
|
||||
while (true)
|
||||
{
|
||||
int32_t next = -1;
|
||||
int others = 0;
|
||||
degree = skeletonNeighbours(mask, current, around);
|
||||
for (int i = 0; i < degree; ++i)
|
||||
{
|
||||
if (around[i] != previous)
|
||||
{
|
||||
next = around[i];
|
||||
++others;
|
||||
}
|
||||
}
|
||||
if (others != 1)
|
||||
break;
|
||||
const int32_t step = next - current;
|
||||
const bool straight = step == 1 || step == -1 || step == stride || step == -stride;
|
||||
length += resolution * (straight ? 1.0 : diagonal);
|
||||
previous = current;
|
||||
current = next;
|
||||
degree = skeletonNeighbours(mask, current, around);
|
||||
if (degree != 2)
|
||||
break;
|
||||
path.push_back(current);
|
||||
if (length >= minimum)
|
||||
break;
|
||||
}
|
||||
if (length < minimum && degree > 2)
|
||||
doomed.insert(doomed.end(), path.begin(), path.end());
|
||||
}
|
||||
if (doomed.empty())
|
||||
break;
|
||||
for (int32_t cell : doomed)
|
||||
mask[cell] = 0;
|
||||
pixels->erase(std::remove_if(pixels->begin(), pixels->end(), [&](int32_t cell) { return mask[cell] == 0; }),
|
||||
pixels->end());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
uint64_t linkKey(int32_t a, int32_t b)
|
||||
{
|
||||
const uint32_t low = static_cast<uint32_t>(std::min(a, b));
|
||||
const uint32_t high = static_cast<uint32_t>(std::max(a, b));
|
||||
return (static_cast<uint64_t>(high) << 32) | low;
|
||||
}
|
||||
|
||||
/** Rectangle against lethal and unknown cell squares, separating-axis test. Centre cell must also be free. */
|
||||
bool footprintFree(const uint8_t* cost, const DirectionGeometry& geometry, double x, double y, double c, double s,
|
||||
double half_x, double half_y)
|
||||
{
|
||||
const double resolution = geometry.resolution;
|
||||
const double abs_c = std::abs(c);
|
||||
const double abs_s = std::abs(s);
|
||||
const double reach_x = half_x * abs_c + half_y * abs_s;
|
||||
const double reach_y = half_x * abs_s + half_y * abs_c;
|
||||
const double x0 = std::floor((x - reach_x - geometry.origin_x) / resolution);
|
||||
const double x1 = std::floor((x + reach_x - geometry.origin_x) / resolution);
|
||||
const double y0 = std::floor((y - reach_y - geometry.origin_y) / resolution);
|
||||
const double y1 = std::floor((y + reach_y - geometry.origin_y) / resolution);
|
||||
if (x0 < 0.0 || y0 < 0.0 || x1 >= geometry.width || y1 >= geometry.height)
|
||||
return false;
|
||||
const int32_t width = static_cast<int32_t>(geometry.width);
|
||||
const int32_t centre_x = static_cast<int32_t>(std::floor((x - geometry.origin_x) / resolution));
|
||||
const int32_t centre_y = static_cast<int32_t>(std::floor((y - geometry.origin_y) / resolution));
|
||||
if (cost[centre_y * width + centre_x] >= INSCRIBED_INFLATED_OBSTACLE)
|
||||
return false;
|
||||
const double half_cell = resolution / 2.0;
|
||||
const double projected = half_cell * (abs_c + abs_s);
|
||||
for (int32_t iy = static_cast<int32_t>(y0); iy <= static_cast<int32_t>(y1); ++iy)
|
||||
{
|
||||
const uint8_t* row = cost + static_cast<std::ptrdiff_t>(iy) * width;
|
||||
for (int32_t ix = static_cast<int32_t>(x0); ix <= static_cast<int32_t>(x1); ++ix)
|
||||
{
|
||||
if (row[ix] != LETHAL_OBSTACLE && row[ix] != NO_INFORMATION)
|
||||
continue;
|
||||
const double dx = geometry.origin_x + (ix + 0.5) * resolution - x;
|
||||
const double dy = geometry.origin_y + (iy + 0.5) * resolution - y;
|
||||
if (std::abs(dx) <= reach_x + half_cell && std::abs(dy) <= reach_y + half_cell &&
|
||||
std::abs(c * dx + s * dy) <= half_x + projected && std::abs(-s * dx + c * dy) <= half_y + projected)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
struct LaneCandidate
|
||||
{
|
||||
ReferencePoint entry, exit;
|
||||
double lateral;
|
||||
double length;
|
||||
};
|
||||
|
||||
struct ZoneRegion
|
||||
{
|
||||
uint8_t direction_index;
|
||||
int32_t label;
|
||||
std::vector<int32_t> cells;
|
||||
};
|
||||
|
||||
/** 8-connected regions of equal nonzero code, ordered by direction, then by first cell in raster order. */
|
||||
std::vector<ZoneRegion> findZoneRegions(const uint8_t* codes, int32_t width, int32_t height, std::vector<int32_t>* labels)
|
||||
{
|
||||
labels->assign(static_cast<std::size_t>(width) * static_cast<std::size_t>(height), 0);
|
||||
std::vector<ZoneRegion> regions;
|
||||
std::vector<int32_t> stack;
|
||||
int32_t next_label = 0;
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
const int32_t seed = y * width + x;
|
||||
const uint8_t code = codes[seed];
|
||||
if (code == 0 || code > 8 || (*labels)[static_cast<std::size_t>(seed)] != 0)
|
||||
continue;
|
||||
ZoneRegion region;
|
||||
region.direction_index = static_cast<uint8_t>(code - 1);
|
||||
region.label = ++next_label;
|
||||
(*labels)[static_cast<std::size_t>(seed)] = region.label;
|
||||
stack.assign(1, seed);
|
||||
while (!stack.empty())
|
||||
{
|
||||
const int32_t cell = stack.back();
|
||||
stack.pop_back();
|
||||
region.cells.push_back(cell);
|
||||
const int32_t cx = cell % width;
|
||||
const int32_t cy = cell / width;
|
||||
for (int32_t ny = std::max(cy - 1, 0); ny <= std::min(cy + 1, height - 1); ++ny)
|
||||
{
|
||||
for (int32_t nx = std::max(cx - 1, 0); nx <= std::min(cx + 1, width - 1); ++nx)
|
||||
{
|
||||
const int32_t other = ny * width + nx;
|
||||
if (codes[other] == code && (*labels)[static_cast<std::size_t>(other)] == 0)
|
||||
{
|
||||
(*labels)[static_cast<std::size_t>(other)] = region.label;
|
||||
stack.push_back(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
regions.push_back(std::move(region));
|
||||
}
|
||||
}
|
||||
std::stable_sort(regions.begin(), regions.end(), [](const ZoneRegion& a, const ZoneRegion& b) {
|
||||
return a.direction_index < b.direction_index;
|
||||
});
|
||||
return regions;
|
||||
}
|
||||
|
||||
/** Candidate lanes of one region: free stretches along the zone direction, at each lateral offset.
|
||||
* Fills `preferred_lateral` with the main lane's offset. */
|
||||
std::vector<LaneCandidate> compileRegionLanes(const ZoneRegion& region, const std::vector<int32_t>& labels,
|
||||
const uint8_t* cost, const DirectionGeometry& geometry, double half_x,
|
||||
double half_y, double offset_step, double* preferred_lateral)
|
||||
{
|
||||
const int32_t width = static_cast<int32_t>(geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(geometry.height);
|
||||
const double resolution = geometry.resolution;
|
||||
const double yaw = region.direction_index * kPi / 4.0;
|
||||
const double c = std::cos(yaw);
|
||||
const double s = std::sin(yaw);
|
||||
|
||||
double lateral_min = std::numeric_limits<double>::infinity();
|
||||
double lateral_max = -lateral_min;
|
||||
double along_min = lateral_min;
|
||||
double along_max = -lateral_min;
|
||||
for (int32_t cell : region.cells)
|
||||
{
|
||||
const double x = geometry.origin_x + (cell % width + 0.5) * resolution;
|
||||
const double y = geometry.origin_y + (cell / width + 0.5) * resolution;
|
||||
const double along = x * c + y * s;
|
||||
const double lateral = -x * s + y * c;
|
||||
along_min = std::min(along_min, along);
|
||||
along_max = std::max(along_max, along);
|
||||
lateral_min = std::min(lateral_min, lateral);
|
||||
lateral_max = std::max(lateral_max, lateral);
|
||||
}
|
||||
const double pad = resolution * 0.5 * (std::abs(c) + std::abs(s));
|
||||
const double lo = lateral_min - pad;
|
||||
const double hi = lateral_max + pad;
|
||||
const double along_lo = along_min - pad;
|
||||
const double along_hi = along_max + pad;
|
||||
const double middle = (lo + hi) / 2.0;
|
||||
const double section = (along_lo + along_hi) / 2.0;
|
||||
|
||||
const auto usable = [&](double t, double v) {
|
||||
const double wx = t * c - v * s;
|
||||
const double wy = t * s + v * c;
|
||||
const double fx = std::floor((wx - geometry.origin_x) / resolution);
|
||||
const double fy = std::floor((wy - geometry.origin_y) / resolution);
|
||||
if (fx < 0.0 || fy < 0.0 || fx >= width || fy >= height)
|
||||
return false;
|
||||
const int32_t cell = static_cast<int32_t>(fy) * width + static_cast<int32_t>(fx);
|
||||
return labels[static_cast<std::size_t>(cell)] == region.label &&
|
||||
footprintFree(cost, geometry, wx, wy, c, s, half_x, half_y);
|
||||
};
|
||||
|
||||
// Offsets across the mid section, spaced like numpy.arange so the values match the prototype.
|
||||
std::vector<double> scan;
|
||||
const double scan_start = lo + kLaneScanStepM / 2.0;
|
||||
const double scan_delta = (scan_start + kLaneScanStepM) - scan_start;
|
||||
const double scan_count = std::ceil((hi - scan_start) / kLaneScanStepM);
|
||||
for (int64_t i = 0; i < static_cast<int64_t>(scan_count); ++i)
|
||||
scan.push_back(i == 1 ? scan_start + kLaneScanStepM : scan_start + static_cast<double>(i) * scan_delta);
|
||||
|
||||
std::vector<std::pair<double, double>> spans;
|
||||
int64_t begin = -1;
|
||||
for (std::size_t i = 0; i <= scan.size(); ++i)
|
||||
{
|
||||
const bool free = i < scan.size() && usable(section, scan[i]);
|
||||
if (free && begin < 0)
|
||||
{
|
||||
begin = static_cast<int64_t>(i);
|
||||
}
|
||||
else if (!free && begin >= 0)
|
||||
{
|
||||
spans.emplace_back(scan[static_cast<std::size_t>(begin)], scan[i - 1]);
|
||||
begin = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// The zone centre may be blocked. The main lane then moves to the free span closest to the centre.
|
||||
double preferred = middle;
|
||||
bool centre_free = spans.empty();
|
||||
for (const auto& span : spans)
|
||||
centre_free = centre_free || (span.first - kLaneScanStepM / 2.0 <= middle && middle <= span.second + kLaneScanStepM / 2.0);
|
||||
if (!centre_free)
|
||||
{
|
||||
double best = std::numeric_limits<double>::infinity();
|
||||
for (const auto& span : spans)
|
||||
{
|
||||
const double distance = std::abs((span.first + span.second) / 2.0 - middle);
|
||||
if (distance < best)
|
||||
{
|
||||
best = distance;
|
||||
preferred = (span.first + span.second) / 2.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
*preferred_lateral = preferred;
|
||||
|
||||
std::set<double> offsets{ middle, preferred };
|
||||
for (int64_t k = 1; preferred - k * offset_step > lo || preferred + k * offset_step < hi; ++k)
|
||||
{
|
||||
if (preferred - k * offset_step > lo)
|
||||
offsets.insert(preferred - k * offset_step);
|
||||
if (preferred + k * offset_step < hi)
|
||||
offsets.insert(preferred + k * offset_step);
|
||||
}
|
||||
offsets.insert(scan.begin(), scan.end());
|
||||
|
||||
// numpy.linspace layout: the last sample is exactly along_hi.
|
||||
const int64_t samples =
|
||||
std::max<int64_t>(2, static_cast<int64_t>(std::ceil((along_hi - along_lo) / kLaneSampleStepM)) + 1);
|
||||
const double sample_delta = (along_hi - along_lo) / static_cast<double>(samples - 1);
|
||||
const auto sample = [&](int64_t i) {
|
||||
return i == samples - 1 ? along_hi : static_cast<double>(i) * sample_delta + along_lo;
|
||||
};
|
||||
|
||||
std::vector<LaneCandidate> lanes;
|
||||
for (double v : offsets)
|
||||
{
|
||||
int64_t start = -1;
|
||||
for (int64_t i = 0; i <= samples; ++i)
|
||||
{
|
||||
const bool free = i < samples && usable(sample(i), v);
|
||||
if (free && start < 0)
|
||||
{
|
||||
start = i;
|
||||
}
|
||||
else if (!free && start >= 0)
|
||||
{
|
||||
const int64_t end = i - 1;
|
||||
if (end > start)
|
||||
{
|
||||
const double t0 = sample(start);
|
||||
const double t1 = sample(end);
|
||||
LaneCandidate lane;
|
||||
lane.entry = { t0 * c - v * s, t0 * s + v * c };
|
||||
lane.exit = { t1 * c - v * s, t1 * s + v * c };
|
||||
lane.lateral = v;
|
||||
lane.length = t1 - t0;
|
||||
lanes.push_back(lane);
|
||||
}
|
||||
start = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return lanes;
|
||||
}
|
||||
|
||||
/** Keep the main lane and up to two lanes on each side. */
|
||||
void selectLanes(const ZoneRegion& region, uint32_t zone_id, const std::vector<LaneCandidate>& lanes, double middle,
|
||||
double offset_step, std::vector<ReferenceLane>* out)
|
||||
{
|
||||
if (lanes.empty())
|
||||
return;
|
||||
const std::size_t first_of_zone = out->size();
|
||||
const double targets[5] = { 0.0, -offset_step, offset_step, -2.0 * offset_step, 2.0 * offset_step };
|
||||
for (double target : targets)
|
||||
{
|
||||
const LaneCandidate* chosen = nullptr;
|
||||
double best_distance = std::numeric_limits<double>::infinity();
|
||||
for (const LaneCandidate& lane : lanes)
|
||||
{
|
||||
const double distance = std::abs(lane.lateral - (middle + target));
|
||||
if (chosen == nullptr || distance < best_distance || (distance == best_distance && lane.length > chosen->length))
|
||||
{
|
||||
chosen = &lane;
|
||||
best_distance = distance;
|
||||
}
|
||||
}
|
||||
if (best_distance > kLaneMatchToleranceM || chosen->length < kLaneMinLengthM)
|
||||
continue;
|
||||
bool duplicate = false;
|
||||
for (std::size_t i = first_of_zone; i < out->size(); ++i)
|
||||
{
|
||||
const ReferencePoint& entry = (*out)[i].entry;
|
||||
duplicate = duplicate || std::hypot(chosen->entry.x - entry.x, chosen->entry.y - entry.y) < kLaneSameEntryM;
|
||||
}
|
||||
if (duplicate)
|
||||
continue;
|
||||
ReferenceLane lane;
|
||||
lane.zone_id = zone_id;
|
||||
lane.direction_index = region.direction_index;
|
||||
lane.entry = chosen->entry;
|
||||
lane.exit = chosen->exit;
|
||||
lane.length_m = chosen->length;
|
||||
lane.offset_from_centre_m = std::abs(chosen->lateral - middle);
|
||||
out->push_back(lane);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string validateReferenceGraphParams(const ReferenceGraphParams& params)
|
||||
{
|
||||
std::ostringstream error;
|
||||
if (!std::isfinite(params.min_clearance_m) || params.min_clearance_m < 0.0)
|
||||
error << "min_clearance_m must be finite and >= 0, got " << params.min_clearance_m;
|
||||
else if (!std::isfinite(params.ridge_min_separation_m) || params.ridge_min_separation_m <= 0.0)
|
||||
error << "ridge_min_separation_m must be finite and > 0, got " << params.ridge_min_separation_m;
|
||||
else if (!std::isfinite(params.spur_min_length_m) || params.spur_min_length_m < 0.0)
|
||||
error << "spur_min_length_m must be finite and >= 0, got " << params.spur_min_length_m;
|
||||
else if (!std::isfinite(params.lane_offset_step_m) || params.lane_offset_step_m <= 0.0)
|
||||
error << "lane_offset_step_m must be finite and > 0, got " << params.lane_offset_step_m;
|
||||
return error.str();
|
||||
}
|
||||
|
||||
VoronoiSkeleton computeVoronoiSkeleton(const ReferenceGridView& grid, const ReferenceGraphParams& params,
|
||||
const std::atomic<bool>* cancel)
|
||||
{
|
||||
checkParams(params);
|
||||
checkGeometry(grid.geometry);
|
||||
if (grid.cost == nullptr)
|
||||
throw std::invalid_argument("reference_graph: null cost grid");
|
||||
|
||||
const int32_t width = static_cast<int32_t>(grid.geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(grid.geometry.height);
|
||||
const double resolution = grid.geometry.resolution;
|
||||
const std::size_t cell_count = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
|
||||
const uint8_t* cost = grid.cost;
|
||||
|
||||
VoronoiSkeleton result;
|
||||
result.geometry = grid.geometry;
|
||||
|
||||
std::vector<int32_t> nearest;
|
||||
if (!nearestFeature(width, height, [cost](int32_t cell) { return cost[cell] == LETHAL_OBSTACLE; }, &nearest, cancel))
|
||||
return result;
|
||||
|
||||
std::vector<uint16_t> clearance_mm(cell_count, kMaxClearanceMm);
|
||||
// A supplied clearance is already rounded down to millimetres, so it is compared in millimetres.
|
||||
const int64_t supplied_threshold_mm = static_cast<int64_t>(std::ceil(params.min_clearance_m * 1000.0 - 1e-9));
|
||||
PaddedMask mask(width, height);
|
||||
std::vector<int32_t> ridge_cells;
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return result;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
const int32_t cell = y * width + x;
|
||||
const int32_t feature = nearest[static_cast<std::size_t>(cell)];
|
||||
bool clear_enough = feature >= 0;
|
||||
if (grid.clearance_mm != nullptr)
|
||||
{
|
||||
clearance_mm[static_cast<std::size_t>(cell)] = grid.clearance_mm[cell];
|
||||
clear_enough = clear_enough && grid.clearance_mm[cell] >= supplied_threshold_mm;
|
||||
}
|
||||
else if (feature >= 0)
|
||||
{
|
||||
const double dy = feature / width - y;
|
||||
const double dx = feature % width - x;
|
||||
const double metres = std::sqrt(dy * dy + dx * dx) * resolution;
|
||||
clearance_mm[static_cast<std::size_t>(cell)] =
|
||||
static_cast<uint16_t>(std::min(std::floor(metres * 1000.0), static_cast<double>(kMaxClearanceMm)));
|
||||
clear_enough = metres >= params.min_clearance_m;
|
||||
}
|
||||
if (!clear_enough || cost[cell] >= INSCRIBED_INFLATED_OBSTACLE)
|
||||
continue;
|
||||
|
||||
// A ridge cell has a neighbour whose nearest obstacle lies far from its own.
|
||||
const auto separated = [&](int32_t other) {
|
||||
const int32_t other_feature = nearest[static_cast<std::size_t>(other)];
|
||||
if (other_feature == feature)
|
||||
return false;
|
||||
const double fy = feature / width - other_feature / width;
|
||||
const double fx = feature % width - other_feature % width;
|
||||
return std::hypot(fy, fx) * resolution >= params.ridge_min_separation_m;
|
||||
};
|
||||
if ((x + 1 < width && separated(cell + 1)) || (y + 1 < height && separated(cell + width)))
|
||||
{
|
||||
const int32_t padded = mask.index(x, y);
|
||||
mask[padded] = 1;
|
||||
ridge_cells.push_back(padded);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<int32_t>().swap(nearest);
|
||||
|
||||
if (!thinSkeleton(&mask, &ridge_cells, cancel) ||
|
||||
!pruneSpurs(&mask, &ridge_cells, resolution, params.spur_min_length_m, cancel))
|
||||
return result;
|
||||
|
||||
result.mask.assign(cell_count, 0);
|
||||
for (int32_t padded : ridge_cells)
|
||||
result.mask[static_cast<std::size_t>(mask.y(padded)) * static_cast<std::size_t>(width) + static_cast<std::size_t>(mask.x(padded))] = 1;
|
||||
result.clearance_mm = std::move(clearance_mm);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> computeRegionCentreLine(const std::vector<uint8_t>& region_mask, const DirectionGeometry& geometry,
|
||||
const ReferenceGraphParams& params)
|
||||
{
|
||||
checkParams(params);
|
||||
checkGeometry(geometry);
|
||||
const int32_t width = static_cast<int32_t>(geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(geometry.height);
|
||||
if (region_mask.size() != static_cast<std::size_t>(width) * static_cast<std::size_t>(height))
|
||||
throw std::invalid_argument("reference_graph: region mask size does not match the geometry");
|
||||
|
||||
std::vector<uint8_t> result(region_mask.size(), 0);
|
||||
int32_t x_min = width, x_max = -1, y_min = height, y_max = -1;
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (region_mask[static_cast<std::size_t>(y * width + x)] == 0)
|
||||
continue;
|
||||
x_min = std::min(x_min, x);
|
||||
x_max = std::max(x_max, x);
|
||||
y_min = std::min(y_min, y);
|
||||
y_max = std::max(y_max, y);
|
||||
}
|
||||
}
|
||||
if (x_max < 0)
|
||||
return result;
|
||||
|
||||
// Two cells of margin so the region always has an outside to measure from.
|
||||
const int32_t crop_x = std::max(0, x_min - 2);
|
||||
const int32_t crop_y = std::max(0, y_min - 2);
|
||||
const int32_t crop_width = std::min(width, x_max + 3) - crop_x;
|
||||
const int32_t crop_height = std::min(height, y_max + 3) - crop_y;
|
||||
std::vector<uint8_t> crop(static_cast<std::size_t>(crop_width) * static_cast<std::size_t>(crop_height), 0);
|
||||
for (int32_t y = 0; y < crop_height; ++y)
|
||||
for (int32_t x = 0; x < crop_width; ++x)
|
||||
crop[static_cast<std::size_t>(y * crop_width + x)] =
|
||||
region_mask[static_cast<std::size_t>((y + crop_y) * width + x + crop_x)] != 0 ? 1 : 0;
|
||||
|
||||
std::vector<int32_t> nearest;
|
||||
nearestFeature(crop_width, crop_height, [&crop](int32_t cell) { return crop[static_cast<std::size_t>(cell)] == 0; },
|
||||
&nearest, nullptr);
|
||||
|
||||
// Two cells apart is the narrowest pair of boundary points that still has a centre.
|
||||
PaddedMask mask(crop_width, crop_height);
|
||||
std::vector<int32_t> cells;
|
||||
for (int32_t y = 0; y < crop_height; ++y)
|
||||
{
|
||||
for (int32_t x = 0; x < crop_width; ++x)
|
||||
{
|
||||
const int32_t cell = y * crop_width + x;
|
||||
if (crop[static_cast<std::size_t>(cell)] == 0)
|
||||
continue;
|
||||
const int32_t feature = nearest[static_cast<std::size_t>(cell)];
|
||||
const auto separated = [&](int32_t other) {
|
||||
const int32_t other_feature = nearest[static_cast<std::size_t>(other)];
|
||||
const double fy = feature / crop_width - other_feature / crop_width;
|
||||
const double fx = feature % crop_width - other_feature % crop_width;
|
||||
return std::hypot(fy, fx) >= 2.0;
|
||||
};
|
||||
if (feature >= 0 && ((x + 1 < crop_width && separated(cell + 1)) || (y + 1 < crop_height && separated(cell + crop_width))))
|
||||
{
|
||||
const int32_t padded = mask.index(x, y);
|
||||
mask[padded] = 1;
|
||||
cells.push_back(padded);
|
||||
}
|
||||
}
|
||||
}
|
||||
thinSkeleton(&mask, &cells, nullptr);
|
||||
pruneSpurs(&mask, &cells, geometry.resolution, params.spur_min_length_m, nullptr);
|
||||
for (int32_t padded : cells)
|
||||
result[static_cast<std::size_t>((mask.y(padded) + crop_y) * width + mask.x(padded) + crop_x)] = 1;
|
||||
return result;
|
||||
}
|
||||
|
||||
void extractVoronoiEdges(const std::vector<uint8_t>& skeleton_mask, const uint8_t* direction_codes,
|
||||
const DirectionGeometry& geometry, const std::vector<uint16_t>* clearance_mm,
|
||||
std::vector<ReferencePoint>* nodes, std::vector<VoronoiEdge>* edges,
|
||||
const std::atomic<bool>* cancel)
|
||||
{
|
||||
checkGeometry(geometry);
|
||||
if (nodes == nullptr || edges == nullptr)
|
||||
throw std::invalid_argument("reference_graph: null output");
|
||||
const int32_t width = static_cast<int32_t>(geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(geometry.height);
|
||||
const std::size_t cell_count = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
|
||||
if (skeleton_mask.size() != cell_count || (clearance_mm != nullptr && clearance_mm->size() != cell_count))
|
||||
throw std::invalid_argument("reference_graph: skeleton size does not match the geometry");
|
||||
nodes->clear();
|
||||
edges->clear();
|
||||
|
||||
PaddedMask mask(width, height);
|
||||
std::vector<int32_t> pixels;
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (skeleton_mask[static_cast<std::size_t>(y * width + x)] != 0)
|
||||
{
|
||||
const int32_t padded = mask.index(x, y);
|
||||
mask[padded] = 1;
|
||||
pixels.push_back(padded);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto code_at = [&](int32_t padded) -> uint8_t {
|
||||
return direction_codes == nullptr ? 0 : direction_codes[mask.y(padded) * width + mask.x(padded)];
|
||||
};
|
||||
|
||||
// Node cells: anything but a plain chain link, and both sides of a zone boundary.
|
||||
PaddedMask critical(width, height);
|
||||
std::vector<int32_t> critical_cells;
|
||||
int32_t around[8];
|
||||
for (int32_t cell : pixels)
|
||||
{
|
||||
const int degree = skeletonNeighbours(mask, cell, around);
|
||||
bool is_critical = degree != 2;
|
||||
for (int i = 0; i < degree && !is_critical; ++i)
|
||||
is_critical = code_at(cell) != code_at(around[i]);
|
||||
if (is_critical)
|
||||
{
|
||||
critical[cell] = 1;
|
||||
critical_cells.push_back(cell);
|
||||
}
|
||||
}
|
||||
|
||||
const auto world = [&](int32_t padded) -> ReferencePoint {
|
||||
return { geometry.origin_x + (mask.x(padded) + 0.5) * geometry.resolution,
|
||||
geometry.origin_y + (mask.y(padded) + 0.5) * geometry.resolution };
|
||||
};
|
||||
std::unordered_map<int32_t, uint32_t> node_of;
|
||||
const auto node_index = [&](int32_t padded) {
|
||||
const auto inserted = node_of.emplace(padded, static_cast<uint32_t>(nodes->size()));
|
||||
if (inserted.second)
|
||||
nodes->push_back(world(padded));
|
||||
return inserted.first->second;
|
||||
};
|
||||
|
||||
std::unordered_set<uint64_t> visited;
|
||||
visited.reserve(pixels.size() * 2);
|
||||
std::vector<int32_t> chain;
|
||||
for (int32_t start : critical_cells)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
{
|
||||
nodes->clear();
|
||||
edges->clear();
|
||||
return;
|
||||
}
|
||||
int32_t first_steps[8];
|
||||
const int first_count = skeletonNeighbours(mask, start, first_steps);
|
||||
for (int i = 0; i < first_count; ++i)
|
||||
{
|
||||
if (!visited.insert(linkKey(start, first_steps[i])).second)
|
||||
continue;
|
||||
chain.assign({ start, first_steps[i] });
|
||||
int32_t previous = start;
|
||||
int32_t current = first_steps[i];
|
||||
// Every non-critical cell has exactly two neighbours, so the walk always ends on a critical cell.
|
||||
while (critical[current] == 0)
|
||||
{
|
||||
const int degree = skeletonNeighbours(mask, current, around);
|
||||
int32_t next = around[0] != previous ? around[0] : around[degree - 1];
|
||||
visited.insert(linkKey(current, next));
|
||||
chain.push_back(next);
|
||||
previous = current;
|
||||
current = next;
|
||||
}
|
||||
if (current == start)
|
||||
continue;
|
||||
|
||||
VoronoiEdge edge;
|
||||
edge.from = node_index(start);
|
||||
edge.to = node_index(current);
|
||||
edge.min_clearance_m = std::numeric_limits<double>::infinity();
|
||||
edge.length_m = 0.0;
|
||||
for (std::size_t k = 0; k < chain.size(); k += kKeepEveryCells)
|
||||
edge.points.push_back(world(chain[k]));
|
||||
if ((chain.size() - 1) % kKeepEveryCells != 0)
|
||||
edge.points.push_back(world(chain.back()));
|
||||
for (std::size_t k = 0; k < edge.points.size(); ++k)
|
||||
{
|
||||
if (k > 0)
|
||||
edge.length_m += std::hypot(edge.points[k].x - edge.points[k - 1].x, edge.points[k].y - edge.points[k - 1].y);
|
||||
}
|
||||
if (clearance_mm != nullptr)
|
||||
{
|
||||
for (std::size_t k = 0; k < chain.size(); ++k)
|
||||
{
|
||||
if (k % kKeepEveryCells != 0 && k + 1 != chain.size())
|
||||
continue;
|
||||
const std::size_t cell = static_cast<std::size_t>(mask.y(chain[k])) * static_cast<std::size_t>(width) +
|
||||
static_cast<std::size_t>(mask.x(chain[k]));
|
||||
edge.min_clearance_m = std::min(edge.min_clearance_m, (*clearance_mm)[cell] / 1000.0);
|
||||
}
|
||||
}
|
||||
edges->push_back(std::move(edge));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ReferenceGraph buildReferenceGraph(const ReferenceGridView& grid, const VoronoiSkeleton& skeleton,
|
||||
const std::vector<robot_geometry_msgs::Point>& footprint,
|
||||
const ReferenceGraphParams& params, const std::atomic<bool>* cancel)
|
||||
{
|
||||
checkParams(params);
|
||||
checkGeometry(grid.geometry);
|
||||
if (grid.cost == nullptr)
|
||||
throw std::invalid_argument("reference_graph: null cost grid");
|
||||
const int32_t width = static_cast<int32_t>(grid.geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(grid.geometry.height);
|
||||
const std::size_t cell_count = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
|
||||
if (skeleton.mask.size() != cell_count || skeleton.clearance_mm.size() != cell_count)
|
||||
throw std::invalid_argument("reference_graph: skeleton size does not match the grid");
|
||||
|
||||
double half_x = 0.0;
|
||||
double half_y = 0.0;
|
||||
if (grid.direction_codes != nullptr)
|
||||
{
|
||||
if (footprint.size() < 3)
|
||||
throw std::invalid_argument("reference_graph: footprint needs at least 3 points");
|
||||
for (const robot_geometry_msgs::Point& point : footprint)
|
||||
{
|
||||
if (!std::isfinite(point.x) || !std::isfinite(point.y))
|
||||
throw std::invalid_argument("reference_graph: footprint holds a non-finite point");
|
||||
half_x = std::max(half_x, std::abs(point.x));
|
||||
half_y = std::max(half_y, std::abs(point.y));
|
||||
}
|
||||
if (half_x <= 0.0 || half_y <= 0.0)
|
||||
throw std::invalid_argument("reference_graph: footprint has no area");
|
||||
}
|
||||
|
||||
ReferenceGraph graph;
|
||||
graph.geometry = grid.geometry;
|
||||
graph.params = params;
|
||||
extractVoronoiEdges(skeleton.mask, grid.direction_codes, grid.geometry, &skeleton.clearance_mm, &graph.nodes,
|
||||
&graph.edges, cancel);
|
||||
if (cancelled(cancel))
|
||||
return ReferenceGraph{};
|
||||
|
||||
if (grid.direction_codes != nullptr)
|
||||
{
|
||||
std::vector<int32_t> labels;
|
||||
const std::vector<ZoneRegion> regions = findZoneRegions(grid.direction_codes, width, height, &labels);
|
||||
for (std::size_t i = 0; i < regions.size(); ++i)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return ReferenceGraph{};
|
||||
if (regions[i].cells.size() < 2)
|
||||
continue;
|
||||
double preferred = 0.0;
|
||||
const std::vector<LaneCandidate> candidates =
|
||||
compileRegionLanes(regions[i], labels, grid.cost, grid.geometry, half_x, half_y, params.lane_offset_step_m, &preferred);
|
||||
selectLanes(regions[i], static_cast<uint32_t>(i), candidates, preferred, params.lane_offset_step_m, &graph.lanes);
|
||||
}
|
||||
}
|
||||
|
||||
graph.static_cost.assign(grid.cost, grid.cost + cell_count);
|
||||
graph.clearance_mm = skeleton.clearance_mm;
|
||||
return graph;
|
||||
}
|
||||
|
||||
} // namespace robot_costmap_2d
|
||||
297
src/reference_graph_worker.cpp
Normal file
297
src/reference_graph_worker.cpp
Normal file
@@ -0,0 +1,297 @@
|
||||
#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
|
||||
Reference in New Issue
Block a user