From 91bcf932909cf0f908a13455d58363c8f73bd3db Mon Sep 17 00:00:00 2001 From: duongtd Date: Tue, 22 Sep 2026 15:42:55 +0700 Subject: [PATCH] first commit --- CMakeLists.txt | 185 +++++++++++++++ README.md | 34 +++ include/route_graph/bundle_json.h | 35 +++ include/route_graph/corridor.h | 40 ++++ include/route_graph/graph.h | 155 ++++++++++++ include/route_graph/map_hash.h | 70 ++++++ package.xml | 33 +++ src/bundle_json.cpp | 101 ++++++++ src/corridor.cpp | 76 ++++++ src/graph.cpp | 377 ++++++++++++++++++++++++++++++ src/map_hash.cpp | 155 ++++++++++++ test/route_graph_test.cpp | 298 +++++++++++++++++++++++ 12 files changed, 1559 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 include/route_graph/bundle_json.h create mode 100644 include/route_graph/corridor.h create mode 100644 include/route_graph/graph.h create mode 100644 include/route_graph/map_hash.h create mode 100644 package.xml create mode 100644 src/bundle_json.cpp create mode 100644 src/corridor.cpp create mode 100644 src/graph.cpp create mode 100644 src/map_hash.cpp create mode 100644 test/route_graph_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..789048c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,185 @@ +cmake_minimum_required(VERSION 3.0.2) +project(route_graph VERSION 0.1.0 LANGUAGES CXX) + +# ======================================================== +# Build mode detection +# ======================================================== +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building route_graph with Catkin") +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building route_graph with Standalone CMake") +endif() + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Boost header-only (shared_ptr in the generated message headers). +find_package(Boost REQUIRED) +# nlohmann/json is header-only and installed system-wide by the auto_setup scripts; no imported +# target is assumed so the same line works on a machine with the apt package or a manual copy. +find_path(NLOHMANN_JSON_INCLUDE_DIR nlohmann/json.hpp HINTS /usr/local/include /usr/include) +if(NOT NLOHMANN_JSON_INCLUDE_DIR) + message(FATAL_ERROR "route_graph: nlohmann/json.hpp not found — install nlohmann-json3-dev") +endif() + +# ======================================================== +# Standalone configuration +# ======================================================== +if(NOT BUILDING_WITH_CATKIN) + + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") + + # Test/route_graph -> Test -> AMR_T800. + set(PNKX_NAV_CORE_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../..") + set(WORKSPACE_DEVEL_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../devel/lib") + + file(GLOB STANDALONE_PACKAGE_INCLUDE_DIRS + LIST_DIRECTORIES true + ${PNKX_NAV_CORE_SRC_DIR}/*/include + ${PNKX_NAV_CORE_SRC_DIR}/*/*/include + ${PNKX_NAV_CORE_SRC_DIR}/*/*/*/include + ${PNKX_NAV_CORE_SRC_DIR}/*/*/*/*/include + ) + set(STANDALONE_INCLUDE_DIRS + ${STANDALONE_PACKAGE_INCLUDE_DIRS} + /opt/ros/noetic/include + /usr/local/include + ) + if(EXISTS ${WORKSPACE_DEVEL_LIB_DIR}) + link_directories(${WORKSPACE_DEVEL_LIB_DIR}) + endif() + link_directories(/usr/local/lib) + + # Only robot_time (for robot_std_msgs/Header). No costmap, no tf3, no boost::dll: a planner can + # link this without pulling anything it does not already have. + set(STANDALONE_LIBRARIES robot_time) + + include_directories(include) + include_directories(SYSTEM ${STANDALONE_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${NLOHMANN_JSON_INCLUDE_DIR}) + +# ======================================================== +# Catkin configuration +# ======================================================== +else() + + find_package(catkin REQUIRED COMPONENTS + robot_time + robot_std_msgs + robot_sensor_msgs + ) + + catkin_package( + INCLUDE_DIRS include + LIBRARIES route_graph + CATKIN_DEPENDS robot_time robot_std_msgs robot_sensor_msgs + DEPENDS Boost + ) + + include_directories(include) + include_directories(SYSTEM ${catkin_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${NLOHMANN_JSON_INCLUDE_DIR}) + +endif() + +# ======================================================== +# Library +# ======================================================== +add_library(route_graph SHARED + src/graph.cpp + src/corridor.cpp + src/map_hash.cpp + src/bundle_json.cpp +) +target_compile_options(route_graph PRIVATE -Wall -Wextra) + +if(BUILDING_WITH_CATKIN) + add_dependencies(route_graph ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + target_include_directories(route_graph + PUBLIC + $ + $ + ${Boost_INCLUDE_DIRS} + ) + target_link_libraries(route_graph + PUBLIC ${catkin_LIBRARIES} + PRIVATE Boost::boost + ) +else() + target_include_directories(route_graph + PUBLIC + $ + $ + ) + target_include_directories(route_graph SYSTEM + PUBLIC + "$" + ${Boost_INCLUDE_DIRS} + ) + target_link_libraries(route_graph + PUBLIC ${STANDALONE_LIBRARIES} + PRIVATE Boost::boost + ) + set_target_properties(route_graph PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) +endif() + +# ======================================================== +# Install +# ======================================================== +if(BUILDING_WITH_CATKIN) + install(TARGETS route_graph + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + ) +else() + include(GNUInstallDirs) + install(TARGETS route_graph + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} + ) + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} + FILES_MATCHING PATTERN "*.h" + ) +endif() + +# ======================================================== +# Tests +# ======================================================== +if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN) + if(NOT COMMAND catkin_add_gtest) + message(FATAL_ERROR "catkin_add_gtest NOT FOUND") + endif() + catkin_add_gtest(route_graph_test test/route_graph_test.cpp) + if(TARGET route_graph_test) + # catkin_add_gtest marks the target EXCLUDE_FROM_ALL; keep it in a plain `catkin_make` so the + # binary is at ./devel/lib/route_graph/route_graph_test, the way this repo verifies packages. + set_target_properties(route_graph_test PROPERTIES EXCLUDE_FROM_ALL FALSE) + target_compile_options(route_graph_test PRIVATE -Wall -Wextra) + target_include_directories(route_graph_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_include_directories(route_graph_test SYSTEM PRIVATE ${catkin_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) + target_link_libraries(route_graph_test route_graph ${catkin_LIBRARIES} pthread) + target_compile_definitions(route_graph_test PRIVATE + ROUTE_GRAPH_TEST_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test") + endif() +endif() diff --git a/README.md b/README.md new file mode 100644 index 0000000..d8805f2 --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# route_graph + +Graph tuyến biên dịch sẵn (`robot_sensor_msgs/RouteGraph`) giữ trong RAM, cộng ba phép hỏi một +global planner cần để khoanh vùng tìm kiếm cho goal xa. Không dựng Voronoi, không phụ thuộc +costmap/tf3/ROS — vào là message + một predicate "ô này đi được không", ra là chuỗi ô và bitmap. + +Producer (`Test/voronoi_route`, chạy ở host lúc copy map, ghi `voronoi.json` vào thư mục map) và +consumer (`sbpl_lattice_planner`) chỉ chung nhau message này; cách graph đi từ host vào nav core ở +`Test/docs/ROUTE_GRAPH_INJECTION_PLAN.md`. + +## Thành phần + +| Header | Làm gì | +|---|---| +| `graph.h` | `Graph::fromMsg` (kiểm version, kích thước, chỉ số, layout edge u→v), `attach()` BFS 8 hướng tới ô graph gần nhất trong bán kính, `route()` Dijkstra giữa hai điểm gắn (trả `Route{cells, clearance_cells}` start→goal gồm cả hai đoạn gắn), `componentCount()`. | +| `corridor.h` | `corridorMask(route, w, h, params)` — đóng dấu đĩa dọc tuyến, nửa bề rộng `clamp(max(min, scale × clearance), min, max)`, bitmap theo quy ước costmap (hàng 0 = origin). | +| `map_hash.h` | `parseSourceRule(source)`, `obstacleMaskFromCostmap(charmap, w, h, rule)` (254 → 1, 255 → 1 nếu `unknown=obstacle`, lật hàng sang thứ tự ảnh, áp ROI), `hashObstacleMask` FNV-1a 64 — **byte-một-byte giống** `voronoi_route`, đổi một bên là mọi graph bị từ chối. | +| `bundle_json.h` | `loadBundleJson(path, &msg)` đọc `voronoi.json` → message (lật y ảnh → costmap), tự validate như consumer. Phía host. | + +Toạ độ trong message: `x` = cột, `y` = hàng, hàng 0 = hàng origin của map (đúng `(mx, my)` của +costmap). Bundle ghi theo ảnh (hàng 0 = trên) — `loadBundleJson` lật; `map_hash` thì giữ nguyên vì +producer hash theo thứ tự ảnh và `obstacleMaskFromCostmap` cũng dựng mask theo thứ tự đó. + +## Kiểm chứng + +```bash +cd /home/duongtd/T800_ws && catkin_make --pkg route_graph +./devel/lib/route_graph/route_graph_test # 10 test: layout, attach, route, mask, rule, hash, bundle +``` + +Đối chiếu với bundle thật (`Managerments/maps/sehc_factory/voronoi.json`, 3060×3060, 431 node, +1117 edge, 24 thành phần): hash static-layer giả lập từ `sehc_factory.png` = `b058c9487f46e17e` khớp +bundle; nạp JSON 21 ms, `fromMsg` 3 ms, hash 9.4M ô 22 ms; tuyến 108 m qua 2 sảnh: attach + Dijkstra ++ mask 3.3 ms, mask 273k ô = 2.9 % map. diff --git a/include/route_graph/bundle_json.h b/include/route_graph/bundle_json.h new file mode 100644 index 0000000..2808b20 --- /dev/null +++ b/include/route_graph/bundle_json.h @@ -0,0 +1,35 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * route_graph — reading the offline bundle (`voronoi.json`) into a RouteGraph message. Host side: + * the navigation core receives the message, it never opens the file. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROUTE_GRAPH_BUNDLE_JSON_H_ +#define ROUTE_GRAPH_BUNDLE_JSON_H_ + +#include + +#include + +namespace route_graph +{ + +/** + * @brief Load `` (a `voronoi.json` written by voronoi_route::saveBundle) into @p msg. + * + * The bundle stores cells in image order (row 0 = top); they are flipped here to the costmap + * convention the message defines (row 0 = origin row). `map_hash` is taken as stored — it was + * computed over the image-ordered mask and the consumer hashes in that order too. + * + * @param stamp_now Filled into `msg.header.stamp` by the caller if needed; this function leaves + * the header untouched except `frame_id` (empty). + * @return false with @p err set on any read/parse/validation problem. @p msg is then unspecified. + */ +bool loadBundleJson(const std::string& path, robot_sensor_msgs::RouteGraph* msg, std::string* err); + +} // namespace route_graph + +#endif // ROUTE_GRAPH_BUNDLE_JSON_H_ diff --git a/include/route_graph/corridor.h b/include/route_graph/corridor.h new file mode 100644 index 0000000..9c8b0bb --- /dev/null +++ b/include/route_graph/corridor.h @@ -0,0 +1,40 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * route_graph — corridor mask around a route. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROUTE_GRAPH_CORRIDOR_H_ +#define ROUTE_GRAPH_CORRIDOR_H_ + +#include +#include +#include + +#include + +namespace route_graph +{ + +/// Half-width of the corridor at a route cell = clamp(max(min, scale * clearance), min, max). +struct CorridorParams +{ + double half_width_min_cells = 30.0; ///< Must cover the footprint's circumscribed radius. + double clearance_scale = 0.8; ///< 0 = fixed width. + double half_width_max_cells = 120.0; +}; + +/** + * @brief Bitmap (row-major, width x height, costmap convention) with 1 inside the corridor. + * Discs are stamped along the route every ~r/2 cells so consecutive discs overlap. + * @param cells_in_mask Optional count of cells set. + * @return Empty vector when the route is empty. + */ +std::vector corridorMask(const Route& route, int width, int height, + const CorridorParams& params, std::size_t* cells_in_mask); + +} // namespace route_graph + +#endif // ROUTE_GRAPH_CORRIDOR_H_ diff --git a/include/route_graph/graph.h b/include/route_graph/graph.h new file mode 100644 index 0000000..7273cdd --- /dev/null +++ b/include/route_graph/graph.h @@ -0,0 +1,155 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * route_graph — a precompiled route graph (robot_sensor_msgs/RouteGraph) held in RAM, with the + * three queries a planner needs: attach a cell to the graph, route between two attachments, + * and (corridor.h) turn a route into a search corridor. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROUTE_GRAPH_GRAPH_H_ +#define ROUTE_GRAPH_GRAPH_H_ + +#include +#include +#include +#include +#include +#include + +#include + +namespace route_graph +{ + +/// Version of the RouteGraph array layout this library understands. +constexpr uint32_t kSupportedVersion = 1; + +/// Grid cell in costmap convention: x = column, y = row, row 0 = the map's origin row. +struct Cell +{ + int x = 0; + int y = 0; + Cell() = default; + Cell(int x_, int y_) : x(x_), y(y_) {} + bool operator==(const Cell& o) const { return x == o.x && y == o.y; } + bool operator!=(const Cell& o) const { return !(*this == o); } +}; + +/** + * @brief Where a free cell joins the graph: the nearest graph cell reachable through passable + * cells, and the cells walked to get there (from the query cell to the graph cell, both + * included). + */ +struct Attachment +{ + bool ok = false; + int edge = -1; ///< Edge that owns the graph cell. + std::size_t index = 0; ///< Position of that cell inside the edge polyline. + std::vector path; ///< query cell -> ... -> graph cell. Size >= 1 when ok. +}; + +/** + * @brief A route on the graph between two attachments: start cell -> attach path -> graph + * polyline -> attach path -> goal cell. `clearance_cells[i]` is the conservative distance + * to the nearest obstacle at `cells[i]` (the owning edge's narrowest point), what the + * corridor width is scaled by. + */ +struct Route +{ + std::vector cells; + std::vector clearance_cells; + float length_cells = 0.0f; ///< 8-connected length of `cells`. + bool empty() const { return cells.empty(); } +}; + +/** + * @class Graph + * @brief RouteGraph message unpacked into adjacency + per-cell lookup. Immutable after fromMsg(). + * + * Nothing here touches a costmap: passability during attach comes in as a predicate so the + * caller decides what "free" means (lethal only, lethal + inscribed, ...). + */ +class Graph +{ +public: + struct Node + { + Cell cell; + std::vector edges; ///< Incident edge indices (a loop edge appears once). + }; + + struct Edge + { + int u = -1; ///< Node at cells[first]. + int v = -1; ///< Node at cells[first + count - 1]. + float length_cells = 0.0f; + float min_clearance_cells = 0.0f; + std::size_t first = 0; ///< Offset into the cell store. + std::size_t count = 0; ///< >= 2 for a well-formed edge. + }; + + /** + * @brief Unpack a message. Validates version, array sizes, index ranges and the cell layout + * (every edge starts at u's cell and ends at v's cell). + * @return false with a reason in @p err; the graph is left empty. + */ + bool fromMsg(const robot_sensor_msgs::RouteGraph& msg, std::string* err); + + void clear(); + bool empty() const { return edges_.empty(); } + + int width() const { return width_; } + int height() const { return height_; } + const std::vector& nodes() const { return nodes_; } + const std::vector& edges() const { return edges_; } + /// Cells of one edge, in u -> v order. + const Cell* edgeCells(int edge) const { return cells_.data() + edges_[edge].first; } + std::size_t totalCells() const { return cells_.size(); } + + /// @return true and the owning (edge, index) if (x, y) is a graph cell. + bool cellOnGraph(int x, int y, int* edge, std::size_t* index) const; + + /** + * @brief 8-connected BFS from @p from through cells where @p passable is true, stopping at the + * first graph cell whose edge is at least @p min_clearance_cells wide. @p from itself is + * always allowed. Bounded by a Chebyshev radius so a cell in a sealed room fails fast + * instead of flooding the map. + * @param min_clearance_cells Edges narrower than this (their `min_clearance_cells`) are not + * graph for this caller — the producer filters for a generic robot, the consumer knows + * its own inscribed radius. 0 = every edge. + */ + Attachment attach(Cell from, int max_radius_cells, + const std::function& passable, + float min_clearance_cells = 0.0f) const; + + /** + * @brief Shortest route on the graph between two attachments (Dijkstra over nodes, plus the + * partial edges at both ends, plus the attach paths). Edges narrower than + * @p min_clearance_cells are not traversed (the attachments' own edges must already pass — + * use the same value in attach()). Empty when no route exists under that constraint. + */ + Route route(const Attachment& a, const Attachment& b, float min_clearance_cells = 0.0f) const; + + /// Connected components among nodes — 1 means every node reaches every other. + int componentCount() const; + +private: + static uint64_t key(int x, int y, int w) { return static_cast(y) * static_cast(w) + static_cast(x); } + /// Cumulative 8-connected length from cells[first] to cells[first + i]. + float cumAt(int edge, std::size_t i) const { return cum_[edges_[edge].first + i]; } + void appendEdgeCells(int edge, std::size_t from_index, std::size_t to_index, Route& out) const; + + int width_ = 0; + int height_ = 0; + std::vector nodes_; + std::vector edges_; + std::vector cells_; + std::vector cum_; + std::unordered_map> cell_index_; +}; + +} // namespace route_graph + +#endif // ROUTE_GRAPH_GRAPH_H_ diff --git a/include/route_graph/map_hash.h b/include/route_graph/map_hash.h new file mode 100644 index 0000000..ea96136 --- /dev/null +++ b/include/route_graph/map_hash.h @@ -0,0 +1,70 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * route_graph — proving a RouteGraph belongs to the map the consumer runs on. + * + * The producer hashed the obstacle mask it built the graph from and wrote the rule it used into + * `RouteGraph::source`. The consumer rebuilds that mask from its own static layer under the same + * rule, hashes it the same way, and compares. Byte-for-byte the same procedure as the producer's + * (`voronoi_route::hashObstacleMask` / `applyObstacleRoi`) — change one and the other, or every + * graph is rejected. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROUTE_GRAPH_MAP_HASH_H_ +#define ROUTE_GRAPH_MAP_HASH_H_ + +#include +#include +#include +#include + +namespace route_graph +{ + +/// The obstacle rule carried in `RouteGraph::source`. +struct ObstacleRule +{ + int lethal_cost_threshold = 100; ///< OccupancyGrid value >= this -> lethal (informational here) + int unknown_cost_value = -1; ///< informational + bool track_unknown_space = true; ///< informational + bool trinary_costmap = true; ///< informational + bool unknown_is_obstacle = false; ///< NO_INFORMATION (255) counts as obstacle in the mask + int roi_margin_cells = -1; ///< < 0 = no ROI +}; + +/** + * @brief Parse "costmap:lethal>=100;unknown_value=-1;track_unknown=1;trinary=1;unknown=traversable;roi=10". + * The "costmap:" prefix is optional. + * @return false if the string is not in that format. + */ +bool parseSourceRule(const std::string& source, ObstacleRule* rule); + +/** + * @brief Obstacle mask from a costmap layer's char map, in IMAGE order (row 0 = TOP), which is the + * order the producer hashed. 254 (LETHAL_OBSTACLE) -> 1; 255 (NO_INFORMATION) -> 1 only when + * `rule.unknown_is_obstacle`; everything else 0. ROI of the rule is applied. + * @param charmap Row 0 = bottom (costmap convention), width * height bytes. + */ +std::vector obstacleMaskFromCostmap(const unsigned char* charmap, int width, int height, + const ObstacleRule& rule); + +/** + * @brief Everything outside the bounding box of obstacle cells grown by @p margin_cells becomes + * obstacle. No-op when margin < 0 or fewer than @p min_obstacle_cells obstacles exist. + * @return number of cells turned into obstacles. + */ +std::size_t applyObstacleRoi(std::vector& mask, int width, int height, int margin_cells, + std::size_t min_obstacle_cells = 16); + +/// FNV-1a 64 over the bit-packed mask, then mixed with its size. +uint64_t hashObstacleMask(const std::vector& mask); + +/// Hex (16 lowercase digits) <-> uint64, the form `voronoi.json` stores `map_hash` in. +std::string hashToHex(uint64_t h); +bool hexToHash(const std::string& hex, uint64_t* out); + +} // namespace route_graph + +#endif // ROUTE_GRAPH_MAP_HASH_H_ diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..024c075 --- /dev/null +++ b/package.xml @@ -0,0 +1,33 @@ + + route_graph + 0.1.0 + + Graph tuyến biên dịch sẵn (robot_sensor_msgs/RouteGraph) giữ trong RAM, cộng ba phép hỏi một + global planner cần: gắn một ô vào graph (BFS 8 hướng), tìm tuyến giữa hai điểm gắn (Dijkstra), + và dựng dải hành lang quanh tuyến (bitmap). Kèm phần kiểm graph có thuộc map đang chạy không: + dựng lại mask vật cản từ static layer theo đúng luật ghi trong `source`, hash cùng cách producer, + so `map_hash`. + + Không dựng Voronoi, không phụ thuộc costmap/tf3/ROS: vào là message + một predicate "ô này đi + được không", ra là chuỗi ô và bitmap. Producer (voronoi_route, chạy ở host lúc copy map) và + consumer (planner) chỉ chung nhau message này. + + Có luôn `loadBundleJson` đọc `voronoi.json` thành message — cho host (amr_control) đẩy vào nav + core; nav core không mở file. + + T800 Robotics + T800 Robotics + BSD + + catkin + + robot_time + robot_time + + robot_std_msgs + robot_std_msgs + + robot_sensor_msgs + robot_sensor_msgs + + diff --git a/src/bundle_json.cpp b/src/bundle_json.cpp new file mode 100644 index 0000000..18cd92b --- /dev/null +++ b/src/bundle_json.cpp @@ -0,0 +1,101 @@ +#include + +#include + +#include + +#include +#include + +namespace route_graph +{ + +bool loadBundleJson(const std::string& path, robot_sensor_msgs::RouteGraph* msg, std::string* err) +{ + if (msg == nullptr) return false; + auto fail = [&](const std::string& why) { + if (err) *err = path + ": " + why; + return false; + }; + + std::ifstream in(path); + if (!in) return fail("cannot open"); + nlohmann::json j; + try + { + in >> j; + } + catch (const std::exception& e) + { + return fail(std::string("parse error: ") + e.what()); + } + + try + { + robot_sensor_msgs::RouteGraph out; + out.version = j.at("version").get(); + if (out.version != kSupportedVersion) + return fail("bundle version " + std::to_string(out.version) + " unsupported"); + out.source = j.value("source", std::string()); + if (!hexToHash(j.at("map_hash").get(), &out.map_hash)) + return fail("map_hash is not 16 hex digits"); + + const nlohmann::json& info = j.at("info"); + out.width = info.at("width").get(); + out.height = info.at("height").get(); + out.resolution = info.at("resolution").get(); + const nlohmann::json& origin = info.at("origin"); + out.origin_x = origin.at(0).get(); + out.origin_y = origin.at(1).get(); + out.origin_yaw = origin.size() > 2 ? origin.at(2).get() : 0.0; + if (out.width == 0 || out.height == 0) return fail("info.width/height is 0"); + const int h = static_cast(out.height); + auto flipY = [h](int y_img) { return h - 1 - y_img; }; + + const nlohmann::json& nodes = j.at("nodes"); + out.node_x.reserve(nodes.size()); + out.node_y.reserve(nodes.size()); + for (const auto& nd : nodes) + { + out.node_x.push_back(nd.at(0).get()); + out.node_y.push_back(flipY(nd.at(1).get())); + } + + const nlohmann::json& edges = j.at("edges"); + out.edge_u.reserve(edges.size()); + out.edge_v.reserve(edges.size()); + out.edge_length_cells.reserve(edges.size()); + out.edge_min_clearance_cells.reserve(edges.size()); + out.edge_cell_offset.reserve(edges.size() + 1); + out.edge_cell_offset.push_back(0); + for (const auto& e : edges) + { + out.edge_u.push_back(e.at("u").get()); + out.edge_v.push_back(e.at("v").get()); + out.edge_length_cells.push_back(e.at("length_cells").get()); + out.edge_min_clearance_cells.push_back(e.at("min_clearance_cells").get()); + const nlohmann::json& cells = e.at("cells"); + for (const auto& c : cells) + { + out.cell_x.push_back(c.at(0).get()); + out.cell_y.push_back(flipY(c.at(1).get())); + } + out.edge_cell_offset.push_back(static_cast(out.cell_x.size())); + } + + // Validate the same way the consumer will, so a bad bundle is refused at the host with a + // readable reason instead of being pushed and rejected inside the core. + Graph check; + std::string why; + if (!check.fromMsg(out, &why)) return fail("invalid graph: " + why); + + *msg = std::move(out); + return true; + } + catch (const std::exception& e) + { + return fail(std::string("bad field: ") + e.what()); + } +} + +} // namespace route_graph diff --git a/src/corridor.cpp b/src/corridor.cpp new file mode 100644 index 0000000..519e230 --- /dev/null +++ b/src/corridor.cpp @@ -0,0 +1,76 @@ +#include + +#include +#include + +namespace route_graph +{ + +namespace +{ + +void stampDisc(std::vector& mask, int w, int h, int cx, int cy, int r, + std::size_t& count) +{ + const int r2 = r * r; + const int y0 = std::max(0, cy - r), y1 = std::min(h - 1, cy + r); + for (int y = y0; y <= y1; ++y) + { + const int dy = y - cy; + const int span = static_cast(std::sqrt(static_cast(r2 - dy * dy))); + const int x0 = std::max(0, cx - span), x1 = std::min(w - 1, cx + span); + uint8_t* row = mask.data() + static_cast(y) * w; + for (int x = x0; x <= x1; ++x) + { + if (!row[x]) + { + row[x] = 1; + ++count; + } + } + } +} + +} // namespace + +std::vector corridorMask(const Route& route, int width, int height, + const CorridorParams& params, std::size_t* cells_in_mask) +{ + std::vector mask; + if (cells_in_mask) *cells_in_mask = 0; + if (route.empty() || width <= 0 || height <= 0) return mask; + mask.assign(static_cast(width) * height, 0); + + const double wmin = std::max(1.0, params.half_width_min_cells); + const double wmax = std::max(wmin, params.half_width_max_cells); + auto radiusAt = [&](std::size_t i) { + const double c = i < route.clearance_cells.size() ? route.clearance_cells[i] : 0.0; + const double r = std::max(wmin, params.clearance_scale * c); + return static_cast(std::lround(std::min(wmax, r))); + }; + + std::size_t count = 0; + double since_last = 1e9; // force a stamp at the first cell + int last_r = radiusAt(0); + for (std::size_t i = 0; i < route.cells.size(); ++i) + { + const int r = radiusAt(i); + if (i > 0) + { + const Cell& p = route.cells[i - 1]; + const Cell& c = route.cells[i]; + since_last += (p.x != c.x && p.y != c.y) ? 1.41421356 : 1.0; + } + // Re-stamp when half the smaller of the two radii has been walked, so discs overlap even + // where the corridor narrows. + const bool due = since_last >= 0.5 * std::min(r, last_r) || i + 1 == route.cells.size(); + if (!due) continue; + stampDisc(mask, width, height, route.cells[i].x, route.cells[i].y, r, count); + since_last = 0.0; + last_r = r; + } + if (cells_in_mask) *cells_in_mask = count; + return mask; +} + +} // namespace route_graph diff --git a/src/graph.cpp b/src/graph.cpp new file mode 100644 index 0000000..8986ee3 --- /dev/null +++ b/src/graph.cpp @@ -0,0 +1,377 @@ +#include + +#include +#include +#include +#include +#include + +namespace route_graph +{ + +namespace +{ + +constexpr float kInf = std::numeric_limits::infinity(); + +inline float stepLength(const Cell& a, const Cell& b) +{ + return (a.x != b.x && a.y != b.y) ? 1.41421356f : 1.0f; +} + +} // namespace + +void Graph::clear() +{ + width_ = height_ = 0; + nodes_.clear(); + edges_.clear(); + cells_.clear(); + cum_.clear(); + cell_index_.clear(); +} + +bool Graph::fromMsg(const robot_sensor_msgs::RouteGraph& msg, std::string* err) +{ + clear(); + auto fail = [&](const std::string& why) { + if (err) *err = why; + clear(); + return false; + }; + + if (msg.version != kSupportedVersion) + return fail("version " + std::to_string(msg.version) + " unsupported (want " + + std::to_string(kSupportedVersion) + ")"); + if (msg.width == 0 || msg.height == 0) return fail("width/height is 0"); + if (msg.node_x.size() != msg.node_y.size()) return fail("node_x/node_y size mismatch"); + const std::size_t n_nodes = msg.node_x.size(); + const std::size_t n_edges = msg.edge_u.size(); + if (msg.edge_v.size() != n_edges || msg.edge_length_cells.size() != n_edges || + msg.edge_min_clearance_cells.size() != n_edges) + return fail("edge arrays size mismatch"); + if (msg.edge_cell_offset.size() != n_edges + 1) return fail("edge_cell_offset size != edges + 1"); + if (msg.cell_x.size() != msg.cell_y.size()) return fail("cell_x/cell_y size mismatch"); + if (msg.edge_cell_offset.front() != 0 || msg.edge_cell_offset.back() != msg.cell_x.size()) + return fail("edge_cell_offset does not span cell arrays"); + if (n_nodes == 0 || n_edges == 0) return fail("empty graph"); + + width_ = static_cast(msg.width); + height_ = static_cast(msg.height); + auto inGrid = [&](int x, int y) { return x >= 0 && y >= 0 && x < width_ && y < height_; }; + + nodes_.resize(n_nodes); + for (std::size_t i = 0; i < n_nodes; ++i) + { + if (!inGrid(msg.node_x[i], msg.node_y[i])) + return fail("node " + std::to_string(i) + " outside the grid"); + nodes_[i].cell = Cell(msg.node_x[i], msg.node_y[i]); + } + + cells_.resize(msg.cell_x.size()); + for (std::size_t i = 0; i < cells_.size(); ++i) + { + if (!inGrid(msg.cell_x[i], msg.cell_y[i])) + return fail("cell " + std::to_string(i) + " outside the grid"); + cells_[i] = Cell(msg.cell_x[i], msg.cell_y[i]); + } + + edges_.resize(n_edges); + cum_.resize(cells_.size(), 0.0f); + for (std::size_t e = 0; e < n_edges; ++e) + { + Edge& ed = edges_[e]; + ed.u = msg.edge_u[e]; + ed.v = msg.edge_v[e]; + if (ed.u < 0 || ed.v < 0 || static_cast(ed.u) >= n_nodes || + static_cast(ed.v) >= n_nodes) + return fail("edge " + std::to_string(e) + " references a node out of range"); + const uint32_t a = msg.edge_cell_offset[e], b = msg.edge_cell_offset[e + 1]; + if (b < a) return fail("edge_cell_offset not monotonic at " + std::to_string(e)); + ed.first = a; + ed.count = b - a; + if (ed.count < 2) return fail("edge " + std::to_string(e) + " has fewer than 2 cells"); + if (cells_[ed.first] != nodes_[ed.u].cell || cells_[ed.first + ed.count - 1] != nodes_[ed.v].cell) + return fail("edge " + std::to_string(e) + " does not start at u / end at v"); + ed.length_cells = msg.edge_length_cells[e]; + ed.min_clearance_cells = msg.edge_min_clearance_cells[e]; + nodes_[ed.u].edges.push_back(static_cast(e)); + if (ed.v != ed.u) nodes_[ed.v].edges.push_back(static_cast(e)); + + float acc = 0.0f; + cum_[ed.first] = 0.0f; + for (std::size_t i = 1; i < ed.count; ++i) + { + const std::size_t k = ed.first + i; + const int dx = std::abs(cells_[k].x - cells_[k - 1].x); + const int dy = std::abs(cells_[k].y - cells_[k - 1].y); + if (dx > 1 || dy > 1) return fail("edge " + std::to_string(e) + " is not 8-connected"); + acc += stepLength(cells_[k - 1], cells_[k]); + cum_[k] = acc; + } + // Interior cells first, so a junction cell (shared by several edges) resolves to whichever + // edge claimed it first — any of them is a valid attachment. + for (std::size_t i = 0; i < ed.count; ++i) + cell_index_.emplace(key(cells_[ed.first + i].x, cells_[ed.first + i].y, width_), + std::make_pair(static_cast(e), static_cast(i))); + } + return true; +} + +bool Graph::cellOnGraph(int x, int y, int* edge, std::size_t* index) const +{ + if (x < 0 || y < 0 || x >= width_ || y >= height_) return false; + const auto it = cell_index_.find(key(x, y, width_)); + if (it == cell_index_.end()) return false; + if (edge) *edge = it->second.first; + if (index) *index = it->second.second; + return true; +} + +Attachment Graph::attach(Cell from, int max_radius_cells, + const std::function& passable, + float min_clearance_cells) const +{ + Attachment out; + if (empty() || from.x < 0 || from.y < 0 || from.x >= width_ || from.y >= height_) return out; + const int r = std::max(1, max_radius_cells); + const int side = 2 * r + 1; + const int ox = from.x - r, oy = from.y - r; + auto local = [&](int x, int y) { return (y - oy) * side + (x - ox); }; + auto inWindow = [&](int x, int y) { + return x >= ox && y >= oy && x < ox + side && y < oy + side && x >= 0 && y >= 0 && + x < width_ && y < height_; + }; + + std::vector parent(static_cast(side) * side, -2); // -2 unvisited, -1 root + std::queue q; + parent[local(from.x, from.y)] = -1; + q.push(from); + + Cell found; + bool hit = false; + static const int kDx[8] = {1, -1, 0, 0, 1, 1, -1, -1}; + static const int kDy[8] = {0, 0, 1, -1, 1, -1, 1, -1}; + while (!q.empty() && !hit) + { + const Cell c = q.front(); + q.pop(); + if (cellOnGraph(c.x, c.y, &out.edge, &out.index) && + edges_[out.edge].min_clearance_cells >= min_clearance_cells) + { + found = c; + hit = true; + break; + } + for (int k = 0; k < 8; ++k) + { + const int nx = c.x + kDx[k], ny = c.y + kDy[k]; + if (!inWindow(nx, ny)) continue; + int32_t& p = parent[local(nx, ny)]; + if (p != -2) continue; + if (!passable(nx, ny)) continue; + p = local(c.x, c.y); + q.push(Cell(nx, ny)); + } + } + if (!hit) return out; + + // Walk parents back to the root, then reverse so the path runs query -> graph. + std::vector rev; + int cur = local(found.x, found.y); + while (cur >= 0) + { + rev.push_back(Cell(ox + cur % side, oy + cur / side)); + cur = parent[cur]; + } + out.path.assign(rev.rbegin(), rev.rend()); + out.ok = true; + return out; +} + +void Graph::appendEdgeCells(int edge, std::size_t from_index, std::size_t to_index, + Route& out) const +{ + const Edge& e = edges_[edge]; + const Cell* cells = edgeCells(edge); + auto push = [&](std::size_t i) { + const Cell& c = cells[i]; + if (!out.cells.empty()) + { + if (out.cells.back() == c) return; + out.length_cells += stepLength(out.cells.back(), c); + } + out.cells.push_back(c); + out.clearance_cells.push_back(e.min_clearance_cells); + }; + if (from_index <= to_index) + for (std::size_t i = from_index; i <= to_index; ++i) push(i); + else + for (std::size_t i = from_index + 1; i-- > to_index;) push(i); +} + +Route Graph::route(const Attachment& a, const Attachment& b, float min_clearance_cells) const +{ + Route out; + if (empty() || !a.ok || !b.ok) return out; + if (a.edge < 0 || b.edge < 0 || static_cast(a.edge) >= edges_.size() || + static_cast(b.edge) >= edges_.size()) + return out; + if (a.index >= edges_[a.edge].count || b.index >= edges_[b.edge].count) return out; + if (edges_[a.edge].min_clearance_cells < min_clearance_cells || + edges_[b.edge].min_clearance_cells < min_clearance_cells) + return out; + + const Edge& ea = edges_[a.edge]; + const Edge& eb = edges_[b.edge]; + const float a_to_u = cumAt(a.edge, a.index); + const float a_to_v = ea.length_cells - a_to_u; + const float b_to_u = cumAt(b.edge, b.index); + const float b_to_v = eb.length_cells - b_to_u; + + // Same edge: the direct slice is a candidate; the detour through the rest of the graph is the + // other one (it wins only on a loop edge, where the far side can be shorter). + float best = kInf; + enum class Kind { kNone, kDirect, kViaNodes } kind = Kind::kNone; + if (a.edge == b.edge) + { + best = std::fabs(cumAt(a.edge, a.index) - cumAt(b.edge, b.index)); + kind = Kind::kDirect; + } + + // Dijkstra over nodes, seeded from both ends of a's edge. + const std::size_t n = nodes_.size(); + std::vector dist(n, kInf); + std::vector prev_node(n, -1), prev_edge(n, -1); + using Item = std::pair; + std::priority_queue, std::greater> pq; + auto seed = [&](int node, float d) { + if (d < dist[node]) + { + dist[node] = d; + pq.emplace(d, node); + } + }; + seed(ea.u, a_to_u); + seed(ea.v, a_to_v); + while (!pq.empty()) + { + const auto [d, u] = pq.top(); + pq.pop(); + if (d > dist[u]) continue; + for (int e : nodes_[u].edges) + { + const Edge& ed = edges_[e]; + if (ed.min_clearance_cells < min_clearance_cells) continue; // too narrow for this robot + const int w = ed.u == u ? ed.v : ed.u; + const float nd = d + ed.length_cells; + if (nd < dist[w]) + { + dist[w] = nd; + prev_node[w] = u; + prev_edge[w] = e; + pq.emplace(nd, w); + } + } + } + + int end_node = -1; + const float via_u = dist[eb.u] + b_to_u; + const float via_v = dist[eb.v] + b_to_v; + if (via_u < best || via_v < best) + { + if (via_u <= via_v) { best = via_u; end_node = eb.u; } + else { best = via_v; end_node = eb.v; } + kind = Kind::kViaNodes; + } + if (kind == Kind::kNone || !std::isfinite(best)) return out; + + // Attach path of a: query cell -> graph cell. The graph cell itself is pushed again by the + // edge walk and de-duplicated there. + for (const Cell& c : a.path) + { + if (!out.cells.empty()) out.length_cells += stepLength(out.cells.back(), c); + out.cells.push_back(c); + out.clearance_cells.push_back(ea.min_clearance_cells); + } + + if (kind == Kind::kDirect) + { + appendEdgeCells(a.edge, a.index, b.index, out); + } + else + { + // Unwind node chain from end_node back to whichever end of a's edge seeded it. + std::vector chain_nodes, chain_edges; + int cur = end_node; + while (cur != -1 && prev_node[cur] != -1) + { + chain_nodes.push_back(cur); + chain_edges.push_back(prev_edge[cur]); + cur = prev_node[cur]; + } + const int first_node = cur; // ea.u or ea.v + std::reverse(chain_nodes.begin(), chain_nodes.end()); + std::reverse(chain_edges.begin(), chain_edges.end()); + + // a's edge: from a.index to the seeded end. + appendEdgeCells(a.edge, a.index, first_node == ea.u ? 0 : ea.count - 1, out); + // Node chain. + int at = first_node; + for (std::size_t i = 0; i < chain_edges.size(); ++i) + { + const Edge& ed = edges_[chain_edges[i]]; + if (ed.u == at) appendEdgeCells(chain_edges[i], 0, ed.count - 1, out); + else appendEdgeCells(chain_edges[i], ed.count - 1, 0, out); + at = chain_nodes[i]; + } + // b's edge: from the reached end to b.index. + appendEdgeCells(b.edge, end_node == eb.u ? 0 : eb.count - 1, b.index, out); + } + + // Attach path of b, walked backwards: graph cell -> query cell. + for (std::size_t i = b.path.size(); i-- > 0;) + { + const Cell& c = b.path[i]; + if (!out.cells.empty()) + { + if (out.cells.back() == c) continue; + out.length_cells += stepLength(out.cells.back(), c); + } + out.cells.push_back(c); + out.clearance_cells.push_back(eb.min_clearance_cells); + } + return out; +} + +int Graph::componentCount() const +{ + const std::size_t n = nodes_.size(); + std::vector seen(n, 0); + int count = 0; + std::vector stack; + for (std::size_t s = 0; s < n; ++s) + { + if (seen[s]) continue; + ++count; + seen[s] = 1; + stack.assign(1, static_cast(s)); + while (!stack.empty()) + { + const int u = stack.back(); + stack.pop_back(); + for (int e : nodes_[u].edges) + { + const int w = edges_[e].u == u ? edges_[e].v : edges_[e].u; + if (!seen[w]) + { + seen[w] = 1; + stack.push_back(w); + } + } + } + } + return count; +} + +} // namespace route_graph diff --git a/src/map_hash.cpp b/src/map_hash.cpp new file mode 100644 index 0000000..1e559e3 --- /dev/null +++ b/src/map_hash.cpp @@ -0,0 +1,155 @@ +#include + +#include +#include +#include +#include + +namespace route_graph +{ + +namespace +{ +constexpr unsigned char kLethalObstacle = 254; // robot_costmap_2d::LETHAL_OBSTACLE +constexpr unsigned char kNoInformation = 255; // robot_costmap_2d::NO_INFORMATION +} // namespace + +bool parseSourceRule(const std::string& source, ObstacleRule* rule) +{ + const char* s = source.c_str(); + if (std::strncmp(s, "costmap:", 8) == 0) s += 8; + int lethal = 0, unk = 0, track = 0, trin = 0, roi = -1; + char pol[16] = {0}; + if (std::sscanf(s, "lethal>=%d;unknown_value=%d;track_unknown=%d;trinary=%d;unknown=%15[a-z];roi=%d", + &lethal, &unk, &track, &trin, pol, &roi) != 6) + return false; + const bool obstacle = std::strcmp(pol, "obstacle") == 0; + if (!obstacle && std::strcmp(pol, "traversable") != 0) return false; + if (rule) + { + rule->lethal_cost_threshold = lethal; + rule->unknown_cost_value = unk; + rule->track_unknown_space = track != 0; + rule->trinary_costmap = trin != 0; + rule->unknown_is_obstacle = obstacle; + rule->roi_margin_cells = roi; + } + return true; +} + +std::vector obstacleMaskFromCostmap(const unsigned char* charmap, int width, int height, + const ObstacleRule& rule) +{ + std::vector mask; + if (charmap == nullptr || width <= 0 || height <= 0) return mask; + mask.assign(static_cast(width) * height, 0); + for (int y = 0; y < height; ++y) + { + // Image row y is costmap row (height - 1 - y): the producer hashed top row first. + const unsigned char* src = charmap + static_cast(height - 1 - y) * width; + uint8_t* dst = mask.data() + static_cast(y) * width; + for (int x = 0; x < width; ++x) + { + const unsigned char v = src[x]; + dst[x] = (v == kLethalObstacle || (v == kNoInformation && rule.unknown_is_obstacle)) ? 1 : 0; + } + } + applyObstacleRoi(mask, width, height, rule.roi_margin_cells); + return mask; +} + +std::size_t applyObstacleRoi(std::vector& mask, int width, int height, int margin_cells, + std::size_t min_obstacle_cells) +{ + if (margin_cells < 0 || width <= 0 || height <= 0 || + mask.size() != static_cast(width) * height) + return 0; + int x0 = width, y0 = height, x1 = -1, y1 = -1; + std::size_t n_obs = 0; + for (int y = 0; y < height; ++y) + { + const uint8_t* row = mask.data() + static_cast(y) * width; + for (int x = 0; x < width; ++x) + { + if (!row[x]) continue; + ++n_obs; + if (x < x0) x0 = x; + if (x > x1) x1 = x; + if (y < y0) y0 = y; + if (y > y1) y1 = y; + } + } + if (n_obs < min_obstacle_cells) return 0; + x0 = x0 - margin_cells < 0 ? 0 : x0 - margin_cells; + y0 = y0 - margin_cells < 0 ? 0 : y0 - margin_cells; + x1 = x1 + margin_cells >= width ? width - 1 : x1 + margin_cells; + y1 = y1 + margin_cells >= height ? height - 1 : y1 + margin_cells; + std::size_t turned = 0; + for (int y = 0; y < height; ++y) + { + uint8_t* row = mask.data() + static_cast(y) * width; + const bool row_out = y < y0 || y > y1; + for (int x = 0; x < width; ++x) + { + if (row[x]) continue; + if (row_out || x < x0 || x > x1) + { + row[x] = 1; + ++turned; + } + } + } + return turned; +} + +uint64_t hashObstacleMask(const std::vector& mask) +{ + uint64_t h = 1469598103934665603ULL; // FNV offset basis + uint8_t packed = 0; + int bit = 0; + for (uint8_t o : mask) + { + if (o) packed |= static_cast(1u << bit); + if (++bit == 8) + { + h ^= packed; + h *= 1099511628211ULL; // FNV prime + packed = 0; + bit = 0; + } + } + if (bit != 0) + { + h ^= packed; + h *= 1099511628211ULL; + } + h ^= static_cast(mask.size()); + h *= 1099511628211ULL; + return h; +} + +std::string hashToHex(uint64_t h) +{ + std::ostringstream o; + o << std::hex << std::setw(16) << std::setfill('0') << h; + return o.str(); +} + +bool hexToHash(const std::string& hex, uint64_t* out) +{ + if (hex.empty() || hex.size() > 16) return false; + uint64_t v = 0; + for (char c : hex) + { + int d; + if (c >= '0' && c <= '9') d = c - '0'; + else if (c >= 'a' && c <= 'f') d = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') d = c - 'A' + 10; + else return false; + v = (v << 4) | static_cast(d); + } + if (out) *out = v; + return true; +} + +} // namespace route_graph diff --git a/test/route_graph_test.cpp b/test/route_graph_test.cpp new file mode 100644 index 0000000..e4e6215 --- /dev/null +++ b/test/route_graph_test.cpp @@ -0,0 +1,298 @@ +// route_graph — unit tests on a hand-built graph (no map files), plus the hash/rule/bundle paths. +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace +{ + +using route_graph::Cell; +using route_graph::Graph; + +// Straight cell run from a to b (axis-aligned), both ends included. +void appendRun(robot_sensor_msgs::RouteGraph& m, Cell a, Cell b) +{ + const int dx = (b.x > a.x) - (b.x < a.x), dy = (b.y > a.y) - (b.y < a.y); + Cell c = a; + while (true) + { + m.cell_x.push_back(c.x); + m.cell_y.push_back(c.y); + if (c == b) break; + c.x += dx; + c.y += dy; + } +} + +void addEdge(robot_sensor_msgs::RouteGraph& m, int u, int v, float clearance) +{ + const Cell a(m.node_x[u], m.node_y[u]), b(m.node_x[v], m.node_y[v]); + const std::size_t before = m.cell_x.size(); + appendRun(m, a, b); + m.edge_u.push_back(u); + m.edge_v.push_back(v); + m.edge_length_cells.push_back(static_cast(m.cell_x.size() - before - 1)); + m.edge_min_clearance_cells.push_back(clearance); + m.edge_cell_offset.push_back(static_cast(m.cell_x.size())); +} + +// A(10,10) -- B(50,10) -- C(50,40), plus an isolated D(80,80) -- E(90,80). 100 x 100 grid. +robot_sensor_msgs::RouteGraph fixture() +{ + robot_sensor_msgs::RouteGraph m; + m.version = route_graph::kSupportedVersion; + m.width = m.height = 100; + m.resolution = 0.05; + m.node_x = {10, 50, 50, 80, 90}; + m.node_y = {10, 10, 40, 80, 80}; + m.edge_cell_offset.push_back(0); + addEdge(m, 0, 1, 8.0f); // A-B, 40 cells + addEdge(m, 1, 2, 4.0f); // B-C, 30 cells + addEdge(m, 3, 4, 6.0f); // D-E, 10 cells + return m; +} + +const auto kAllPassable = [](int, int) { return true; }; + +} // namespace + +TEST(Graph, FromMsgValidates) +{ + Graph g; + std::string err; + auto m = fixture(); + ASSERT_TRUE(g.fromMsg(m, &err)) << err; + EXPECT_EQ(g.nodes().size(), 5u); + EXPECT_EQ(g.edges().size(), 3u); + EXPECT_EQ(g.componentCount(), 2); + + m.version = 99; + EXPECT_FALSE(g.fromMsg(m, &err)); + EXPECT_TRUE(g.empty()); + + m = fixture(); + m.edge_cell_offset.back() += 1; // does not span the cell arrays + EXPECT_FALSE(g.fromMsg(m, &err)); + + m = fixture(); + m.cell_x[0] = 11; // edge 0 no longer starts at node u's cell + EXPECT_FALSE(g.fromMsg(m, &err)); + EXPECT_NE(err.find("does not start at u"), std::string::npos); +} + +TEST(Graph, AttachFindsNearestGraphCellAndPath) +{ + Graph g; + ASSERT_TRUE(g.fromMsg(fixture(), nullptr)); + const auto a = g.attach(Cell(12, 14), 50, kAllPassable); + ASSERT_TRUE(a.ok); + EXPECT_EQ(a.edge, 0); + EXPECT_EQ(a.index, 2u); // (12,10) is the third cell of A-B + ASSERT_GE(a.path.size(), 2u); + EXPECT_EQ(a.path.front(), Cell(12, 14)); + EXPECT_EQ(a.path.back(), Cell(12, 10)); + + // Walls everywhere except the query cell: nothing reachable. + const auto blocked = g.attach(Cell(12, 14), 50, [](int, int) { return false; }); + EXPECT_FALSE(blocked.ok); + // Radius too small to reach row 10 from row 30. + EXPECT_FALSE(g.attach(Cell(12, 30), 5, kAllPassable).ok); +} + +TEST(Graph, RouteGoesThroughJunctionAndCarriesClearance) +{ + Graph g; + ASSERT_TRUE(g.fromMsg(fixture(), nullptr)); + const auto s = g.attach(Cell(12, 12), 50, kAllPassable); // near A + const auto t = g.attach(Cell(52, 38), 50, kAllPassable); // near C + ASSERT_TRUE(s.ok && t.ok); + const auto r = g.route(s, t); + ASSERT_FALSE(r.empty()); + EXPECT_EQ(r.cells.front(), Cell(12, 12)); + EXPECT_EQ(r.cells.back(), Cell(52, 38)); + EXPECT_EQ(r.cells.size(), r.clearance_cells.size()); + // Passes through B. + bool via_b = false; + for (const auto& c : r.cells) via_b |= (c == Cell(50, 10)); + EXPECT_TRUE(via_b); + // 38 along A-B + 28 along B-C + 2 + 2 attach steps. + EXPECT_NEAR(r.length_cells, 70.0f, 1.0f); + // Clearance follows the owning edge: 8 on A-B cells, 4 on B-C cells. + EXPECT_FLOAT_EQ(r.clearance_cells[5], 8.0f); + EXPECT_FLOAT_EQ(r.clearance_cells[r.clearance_cells.size() - 5], 4.0f); +} + +TEST(Graph, RouteOnSameEdgeIsTheDirectSlice) +{ + Graph g; + ASSERT_TRUE(g.fromMsg(fixture(), nullptr)); + const auto s = g.attach(Cell(20, 10), 5, kAllPassable); + const auto t = g.attach(Cell(40, 10), 5, kAllPassable); + ASSERT_TRUE(s.ok && t.ok); + const auto r = g.route(s, t); + ASSERT_EQ(r.cells.size(), 21u); + EXPECT_NEAR(r.length_cells, 20.0f, 0.01f); + // Reverse direction walks the edge backwards. + const auto rr = g.route(t, s); + ASSERT_EQ(rr.cells.size(), 21u); + EXPECT_EQ(rr.cells.front(), Cell(40, 10)); + EXPECT_EQ(rr.cells.back(), Cell(20, 10)); +} + +TEST(Graph, NarrowEdgesAreSkippedForTheCallersClearance) +{ + Graph g; + ASSERT_TRUE(g.fromMsg(fixture(), nullptr)); + // B-C has clearance 4: with a robot needing 5 cells it is not a route, and (50, 40) near C + // cannot even attach to it — the BFS walks on to the nearest wide edge (A-B at (50, 10)). + const auto s = g.attach(Cell(10, 10), 5, kAllPassable, 5.0f); + const auto t = g.attach(Cell(50, 40), 50, kAllPassable, 5.0f); + ASSERT_TRUE(s.ok && t.ok); + EXPECT_EQ(t.edge, 0); + EXPECT_EQ(t.path.back(), Cell(50, 10)); + const auto r = g.route(s, t, 5.0f); + ASSERT_FALSE(r.empty()); + for (const auto& c : r.cells) EXPECT_LE(c.y, 40); + // Same attachments, but a route() asking for more clearance than A-B has -> nothing. + EXPECT_TRUE(g.route(s, t, 9.0f).empty()); +} + +TEST(Graph, NoRouteAcrossComponents) +{ + Graph g; + ASSERT_TRUE(g.fromMsg(fixture(), nullptr)); + const auto s = g.attach(Cell(10, 10), 5, kAllPassable); + const auto t = g.attach(Cell(85, 80), 5, kAllPassable); + ASSERT_TRUE(s.ok && t.ok); + EXPECT_TRUE(g.route(s, t).empty()); +} + +TEST(Corridor, MaskCoversRouteAndScalesWithClearance) +{ + Graph g; + ASSERT_TRUE(g.fromMsg(fixture(), nullptr)); + const auto s = g.attach(Cell(10, 10), 5, kAllPassable); + const auto t = g.attach(Cell(50, 40), 5, kAllPassable); + const auto r = g.route(s, t); + ASSERT_FALSE(r.empty()); + route_graph::CorridorParams p; + p.half_width_min_cells = 3; + p.clearance_scale = 1.0; + p.half_width_max_cells = 20; + std::size_t n = 0; + const auto mask = route_graph::corridorMask(r, 100, 100, p, &n); + ASSERT_EQ(mask.size(), 10000u); + EXPECT_EQ(n, static_cast(std::count(mask.begin(), mask.end(), 1))); + for (const auto& c : r.cells) EXPECT_EQ(mask[c.y * 100 + c.x], 1) << c.x << "," << c.y; + // A-B has clearance 8 -> radius 8: (30, 17) inside, (30, 19) outside. B-C clearance 4: (47, 25) + // inside, (44, 25) outside. Discs are stamped every r/2 cells, so the union scallops slightly + // inside r between stamps — probe one cell in from the nominal boundary. + EXPECT_EQ(mask[17 * 100 + 30], 1); + EXPECT_EQ(mask[19 * 100 + 30], 0); + EXPECT_EQ(mask[25 * 100 + 47], 1); + EXPECT_EQ(mask[25 * 100 + 44], 0); + // Far corner untouched. + EXPECT_EQ(mask[90 * 100 + 90], 0); +} + +TEST(MapHash, RuleRoundTripAndPrefix) +{ + route_graph::ObstacleRule r; + ASSERT_TRUE(route_graph::parseSourceRule( + "costmap:lethal>=100;unknown_value=-1;track_unknown=1;trinary=1;unknown=traversable;roi=10", &r)); + EXPECT_EQ(r.lethal_cost_threshold, 100); + EXPECT_FALSE(r.unknown_is_obstacle); + EXPECT_EQ(r.roi_margin_cells, 10); + ASSERT_TRUE(route_graph::parseSourceRule( + "lethal>=50;unknown_value=-1;track_unknown=0;trinary=0;unknown=obstacle;roi=-1", &r)); + EXPECT_TRUE(r.unknown_is_obstacle); + EXPECT_FALSE(r.track_unknown_space); + EXPECT_EQ(r.roi_margin_cells, -1); + EXPECT_FALSE(route_graph::parseSourceRule("map_server:occupied", &r)); +} + +TEST(MapHash, CostmapMaskIsImageOrderedAndRoiApplied) +{ + // 4 x 3 costmap, row 0 = bottom. Lethal at (1, 0) (bottom row) and unknown at (3, 2) (top row). + unsigned char cm[12] = {0}; + cm[0 * 4 + 1] = 254; + cm[2 * 4 + 3] = 255; + route_graph::ObstacleRule r; // unknown traversable, no ROI + auto m = route_graph::obstacleMaskFromCostmap(cm, 4, 3, r); + ASSERT_EQ(m.size(), 12u); + EXPECT_EQ(m[2 * 4 + 1], 1); // image row 2 = costmap row 0 + EXPECT_EQ(m[0 * 4 + 3], 0); // unknown not an obstacle + r.unknown_is_obstacle = true; + m = route_graph::obstacleMaskFromCostmap(cm, 4, 3, r); + EXPECT_EQ(m[0 * 4 + 3], 1); + + // ROI: 10 x 10 mask with a 3 x 3 block in the middle, margin 1 -> everything outside 5 x 5 box is obstacle. + std::vector mask(100, 0); + for (int y = 4; y <= 6; ++y) + for (int x = 4; x <= 6; ++x) mask[y * 10 + x] = 1; + const auto turned = route_graph::applyObstacleRoi(mask, 10, 10, 1, /*min_obstacle_cells=*/1); + EXPECT_EQ(turned, 100u - 25u); + EXPECT_EQ(mask[3 * 10 + 3], 0); + EXPECT_EQ(mask[2 * 10 + 3], 1); +} + +TEST(MapHash, HashIsStableAndHexRoundTrips) +{ + std::vector a(37, 0), b(37, 0); + a[5] = 1; + EXPECT_EQ(route_graph::hashObstacleMask(a), route_graph::hashObstacleMask(a)); + EXPECT_NE(route_graph::hashObstacleMask(a), route_graph::hashObstacleMask(b)); + b.push_back(0); // size is part of the hash + EXPECT_NE(route_graph::hashObstacleMask(std::vector(37, 0)), route_graph::hashObstacleMask(b)); + const uint64_t h = route_graph::hashObstacleMask(a); + uint64_t back = 0; + ASSERT_TRUE(route_graph::hexToHash(route_graph::hashToHex(h), &back)); + EXPECT_EQ(back, h); + EXPECT_FALSE(route_graph::hexToHash("xyz", &back)); +} + +TEST(BundleJson, LoadsAndFlipsRows) +{ + // Image order: node (2, 0) is the TOP row of a 5-row map -> costmap row 4. + const std::string path = "/tmp/route_graph_test_" + std::to_string(::getpid()) + ".json"; + { + std::ofstream f(path); + f << R"({"version":1,"source":"costmap:lethal>=100;unknown_value=-1;track_unknown=1;trinary=1;unknown=traversable;roi=-1", + "map_hash":"00000000000000ff", + "info":{"width":6,"height":5,"resolution":0.1,"origin":[-1.0,-2.0,0.0]}, + "nodes":[[2,0],[2,3]], + "edges":[{"u":0,"v":1,"length_cells":3.0,"min_clearance_cells":2.5,"cells":[[2,0],[2,1],[2,2],[2,3]]}]})"; + } + robot_sensor_msgs::RouteGraph msg; + std::string err; + ASSERT_TRUE(route_graph::loadBundleJson(path, &msg, &err)) << err; + std::remove(path.c_str()); + EXPECT_EQ(msg.width, 6u); + EXPECT_EQ(msg.height, 5u); + EXPECT_DOUBLE_EQ(msg.origin_x, -1.0); + EXPECT_EQ(msg.map_hash, 255u); + ASSERT_EQ(msg.node_y.size(), 2u); + EXPECT_EQ(msg.node_y[0], 4); + EXPECT_EQ(msg.node_y[1], 1); + ASSERT_EQ(msg.cell_y.size(), 4u); + EXPECT_EQ(msg.cell_y[0], 4); + EXPECT_EQ(msg.cell_y[3], 1); + Graph g; + EXPECT_TRUE(g.fromMsg(msg, &err)) << err; + + EXPECT_FALSE(route_graph::loadBundleJson("/nonexistent/voronoi.json", &msg, &err)); +} + +int main(int argc, char** argv) +{ + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +}