diff --git a/maps_managers/easynav_navmap_maps_manager/CMakeLists.txt b/maps_managers/easynav_navmap_maps_manager/CMakeLists.txt index a353f281..ae56d975 100644 --- a/maps_managers/easynav_navmap_maps_manager/CMakeLists.txt +++ b/maps_managers/easynav_navmap_maps_manager/CMakeLists.txt @@ -35,6 +35,8 @@ add_library(${PROJECT_NAME} SHARED src/easynav_navmap_maps_manager/filters/NavMapFilter.cpp src/easynav_navmap_maps_manager/filters/ObstacleFilter.cpp src/easynav_navmap_maps_manager/filters/InflationFilter.cpp + src/easynav_navmap_maps_manager/filters/FractalFilter.cpp + src/easynav_navmap_maps_manager/filters/rtin_lod.cpp ) target_include_directories(${PROJECT_NAME} PUBLIC $ @@ -105,6 +107,7 @@ pluginlib_export_plugin_description_file(easynav_core easynav_navmap_maps_manage pluginlib_export_plugin_description_file(easynav_navmap_maps_manager easynav_navmap_maps_manager_obstacle_filter.xml) pluginlib_export_plugin_description_file(easynav_navmap_maps_manager easynav_navmap_maps_manager_inflation_filter.xml) +pluginlib_export_plugin_description_file(easynav_navmap_maps_manager easynav_navmap_maps_manager_fractal_filter.xml) ament_export_dependencies( easynav_common diff --git a/maps_managers/easynav_navmap_maps_manager/README.md b/maps_managers/easynav_navmap_maps_manager/README.md index 52b73299..ea42dd70 100644 --- a/maps_managers/easynav_navmap_maps_manager/README.md +++ b/maps_managers/easynav_navmap_maps_manager/README.md @@ -4,7 +4,7 @@ Maps Manager that maintains a [NavMap](https://github.com/EasyNavigation/NavMap) (triangulated 3D surface) and publishes full maps and layer updates; supports importing from YAML OccupancyGrid or point clouds. -This package also includes map filters implemented as plugins (`ObstacleFilter` and `InflationFilter`) that operate on NavMap layers to detect obstacles and inflate their costs, enabling cost-aware path planning. +This package also includes map filters implemented as plugins (`ObstacleFilter`, `InflationFilter` and `FractalFilter`) that operate on NavMap layers to detect obstacles and inflate their costs, enabling cost-aware path planning, and keep a simplified copy of the map for planning on large maps. ## Authors and Maintainers @@ -101,6 +101,37 @@ With `.local.enabled`, the maps manager keeps a NavMap around the robot, | **Input Layer:** | | | Reads from `"obstacles"`. | | **Output Layer:** | | | Writes to `"inflated_obstacles"`. | +#### **FractalFilter** + +- **Plugin Name:** `easynav_navmap_maps_manager/NavMapMapsManager/FractalFilter` +- **Type:** `easynav::navmap::FractalFilter` +- **Description:** + Keeps a simplified copy of `map.navmap` for planning on large maps: neighbour NavCels with the same value of `layer` merge into larger triangles, and split back down to the source resolution where the value changes. Free space far from obstacles becomes a few large NavCels, while obstacles, the inflation band around them and changes of slope stay at full resolution, so the planner explores far fewer NavCels and still sees every narrow passage. + `map.navmap` is not modified: the other filters keep working on it at full resolution, and the simplified map is written to another NavState key (`output_key`, `map.navmap.lod`). The planner reads it through its own `map_key` parameter (e.g. `easynav_navmap_planner/AStarPlanner`'s `map_key: map.navmap.lod`). + It goes **after** the filters that write its `layer` (`filters: [obstacles, inflation, fractal]`). + + How it works: a binary triangle tree (RTIN) is laid over the source map. Two sibling triangles merge into their parent (twice the area) when every cell below has the same value of `layer` (strict equality), is flat (slopes within `max_angle_deg`, vertices within `height_tolerance` of the merged plane) and has no hole. Otherwise the triangle is split along its hypotenuse; a split forces the neighbour across the hypotenuse to split too, so the mesh has no T-junctions and the planner can cross between levels. Each cycle only reads the costs within `window_radius` of the robot (where the sensors change them) plus `sweep` NavCels of the whole map, taken in turns (what changes far away, such as obstacles an obstacle memory forgets, is caught within a few seconds). The cost per cycle does not depend on the size of the map. The output map is rebuilt in place by tiles of about 50 m: only the tiles where something changed are walked and written again. + + Requirements: the source must be a regular grid of right isosceles triangles (two per square cell), as `pointcloud_to_navmap` and `navmap_ros::from_occupancy_grid` produce, and `layer` must be a `uint8` layer. Otherwise the filter logs an error and writes no output. + + For RViz, the simplified map is published on `///map` (e.g. `/maps_manager_node/navmap/fractal/map`), and between two full maps only what changed is published on `.../map_patch` (`navmap_ros_interfaces/msg/NavMapPatch`), which the NavMap display applies. Nothing is published without subscribers. The `lod_level` layer (merges per NavCel, 0 = source resolution) and the `modified` layer show how much was simplified; turn on the display's *Draw Edges* to see the triangles. + +| Parameter | Type | Default | Description | +|---|---|---:|---| +| `.output_key` | `string` | `"map.navmap.lod"` | NavState key of the simplified map; must not be `map.navmap`. | +| `.layer` | `string` | `"inflated_obstacles"` | `uint8` layer whose value decides what merges; it is copied to the simplified map. | +| `.max_angle_deg` | `double` | `5.0` | NavCels merge only if their slopes differ at most this (deg). | +| `.height_tolerance` | `double` | `0.05` | Source vertices at most this far (m) from the plane of a merged NavCel. | +| `.window_radius` | `double` | `8.0` | Costs read every cycle within this distance (m) of the robot: at least the sensor range plus the inflation radius. | +| `.sweep` | `int` | `100000` | NavCels of the whole map read per cycle, in turns; `0` reads only the window. | +| `.rebuild_period` | `double` | `0.5` | Minimum time (s) between two rebuilds of the simplified map. | +| `.tile_size` | `double` | `50.0` | Side (m, about) of the tiles the simplified map is rebuilt by. | +| `.publish_period` | `double` | `2.0` | Minimum time (s) between two publications for RViz (map or patch). | +| `.full_period` | `double` | `0.0` | Time (s) between two full maps (resync); `0`: only for a new subscriber or a rebuilt map, patches otherwise. | +| `.log_period` | `double` | `10.0` | Time (s) between two logs of the simplified map's statistics; `0`: every rebuild. | +| **Input:** | | | Reads `map.navmap` and its `layer`, and `robot_pose` for the window. | +| **Output Key:** | | | Writes `output_key` (`::navmap::NavMap`), with layers ``, `lod_level` and `modified`. | + The filters update the map in `NavState` in place and record which cells they change; the maps manager publishes those changes and clears them at the end of each cycle. ## Interfaces (Topics and Services) @@ -126,6 +157,7 @@ The filters update the map in `NavState` in place and record which cells they ch |---|---|---|---| | `map.navmap` | `::navmap::NavMap` | **Read** | Reads the NavMap if already present in NavState. | | `map.navmap` | `::navmap::NavMap` | **Write** | Stores the maintained NavMap, including generated layers `"obstacles"` and `"inflated_obstacles"`. | +| `map.navmap.lod` | `::navmap::NavMap` | **Write** | With `FractalFilter`: the simplified map for planning (its `output_key`). | ## TF Frames @@ -147,7 +179,7 @@ maps_manager_node: navmap_path_file: maps/excavation_urjc.navmap filters: [obstacles, inflation] obstacles: - plugin: easynav_navmap_maps_manager/NavMapMapsManager/ObstacleFilter + plugin: easynav_navmap_maps_manager/NavMapMapsManager/ObstaclesFilter height_threshold: 0.25 inflation: plugin: easynav_navmap_maps_manager/NavMapMapsManager/InflationFilter @@ -155,6 +187,50 @@ maps_manager_node: cost_scaling_factor: 2.0 ``` +### With FractalFilter (large maps) + +The maps manager keeps the full map and its simplified copy; A* plans on the copy: + +```yaml +maps_manager_node: + ros__parameters: + map_types: [navmap] + navmap: + freq: 10.0 + plugin: easynav_navmap_maps_manager/NavMapMapsManager + package: my_robot_maps + navmap_path_file: maps/warehouse.navmap + filters: [obstacles, inflation, fractal] # fractal after the filters that write its layer + obstacles: + plugin: easynav_navmap_maps_manager/NavMapMapsManager/ObstaclesFilter + max_range: 6.0 + max_height: 1.5 # m: ignore what the robot passes under (door lintels) + inflation: + plugin: easynav_navmap_maps_manager/NavMapMapsManager/InflationFilter + inflation_radius: 1.5 + cost_scaling_factor: 2.0 + fractal: + plugin: easynav_navmap_maps_manager/NavMapMapsManager/FractalFilter + output_key: map.navmap.lod # where A* reads (its map_key) + layer: inflated_obstacles # neighbour NavCels with the same value merge + max_angle_deg: 5.0 + height_tolerance: 0.05 + window_radius: 8.0 # sensor range (6 m) + inflation radius (1.5 m) + sweep: 100000 # the whole map is read again every few seconds + rebuild_period: 0.5 + publish_period: 2.0 # for RViz: full map, then patches + +planner_node: + ros__parameters: + planner_types: [astar] + astar: + freq: 1.0 + plugin: easynav_navmap_planner/AStarPlanner + map_key: map.navmap.lod # plan on the simplified map +``` + +In RViz, show `/maps_manager_node/navmap/fractal/map` with the NavMap display (its *Patch Topic* defaults to `_patch`). + ## License Apache-2.0 diff --git a/maps_managers/easynav_navmap_maps_manager/easynav_navmap_maps_manager_fractal_filter.xml b/maps_managers/easynav_navmap_maps_manager/easynav_navmap_maps_manager_fractal_filter.xml new file mode 100644 index 00000000..a879774d --- /dev/null +++ b/maps_managers/easynav_navmap_maps_manager/easynav_navmap_maps_manager_fractal_filter.xml @@ -0,0 +1,9 @@ + + + + + A filter which keeps a copy of the NavMap with same-cost NavCels merged, for planning + + + + diff --git a/maps_managers/easynav_navmap_maps_manager/include/easynav_navmap_maps_manager/filters/FractalFilter.hpp b/maps_managers/easynav_navmap_maps_manager/include/easynav_navmap_maps_manager/filters/FractalFilter.hpp new file mode 100644 index 00000000..7bd1850c --- /dev/null +++ b/maps_managers/easynav_navmap_maps_manager/include/easynav_navmap_maps_manager/filters/FractalFilter.hpp @@ -0,0 +1,92 @@ +// Copyright 2026 Intelligent Robotics Lab +// +// This file is part of the project Easy Navigation (EasyNav in short) +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/// \file +/// \brief NavMap filter that keeps a merged/split copy of the NavMap for planning. + +#ifndef EASYNAV_NAVMAP_MAPS_MANAGER__FILTERS__FRACTALFILTER_HPP_ +#define EASYNAV_NAVMAP_MAPS_MANAGER__FILTERS__FRACTALFILTER_HPP_ + +#include +#include +#include + +#include "easynav_common/types/NavState.hpp" +#include "navmap_ros_interfaces/msg/nav_map.hpp" +#include "navmap_ros_interfaces/msg/nav_map_patch.hpp" +#include "rclcpp/rclcpp.hpp" + +#include "easynav_navmap_maps_manager/filters/NavMapFilter.hpp" +#include "easynav_navmap_maps_manager/filters/rtin_lod.hpp" + +namespace easynav +{ +namespace navmap +{ + +/** + * @class FractalFilter + * @brief Simplified copy of "map.navmap" for planning: same-cost NavCels merged into large + * triangles, split back where the cost changes. + * + * Goes after the filters that write its `layer` (filters: [obstacles, inflation, fractal]). + * "map.navmap" is not touched: the filters keep working on it at full resolution. The result is + * left in `output_key` ("map.navmap.lod"), where A* reads it with its `map_key`. Only the costs + * around the robot (`window_radius`) and a slice of the map (`sweep`) are read each cycle. See + * RtinLod. + */ +class FractalFilter : public NavMapFilter +{ +public: + void on_initialize() override; + void update(::easynav::NavState & nav_state) override; + +private: + /// The whole map to a receiver without a copy, else a patch with what changed since. + void publish(const rclcpp::Time & now); + + const std::string input_key_{"map.navmap"}; ///< the maps manager's NavMap + std::string output_key_{"map.navmap.lod"}; + std::string layer_{"inflated_obstacles"}; + double rebuild_period_{0.5}; + double window_radius_{8.0}; ///< m around the robot read every cycle + int sweep_{100000}; ///< NavCels of the whole map read per cycle, in turns + double publish_period_{2.0}; ///< s between two publications for RViz (map or patch) + double full_period_{0.0}; ///< s between two whole maps (resync); 0: only when needed + double log_period_{10.0}; ///< s between two logs of the map's statistics (0: every one) + RtinLod::Params params_; + + RtinLod lod_; + std::uint64_t source_geometry_{0}; + std::size_t source_navcels_{0}; + bool dirty_{false}; + rclcpp::Time last_extract_; + bool extracted_once_{false}; + std::shared_ptr<::navmap::NavMap> out_; + rclcpp::Time last_publish_; + rclcpp::Time last_full_; + bool sent_once_{false}; + bool need_full_{true}; + std::size_t last_subscribers_{0}; + std::uint64_t last_sent_id_{0}; ///< geometry of the last map or patch sent + + rclcpp::Publisher::SharedPtr map_pub_; + rclcpp::Publisher::SharedPtr patch_pub_; +}; + +} // namespace navmap +} // namespace easynav + +#endif // EASYNAV_NAVMAP_MAPS_MANAGER__FILTERS__FRACTALFILTER_HPP_ diff --git a/maps_managers/easynav_navmap_maps_manager/include/easynav_navmap_maps_manager/filters/rtin_lod.hpp b/maps_managers/easynav_navmap_maps_manager/include/easynav_navmap_maps_manager/filters/rtin_lod.hpp new file mode 100644 index 00000000..90de41ae --- /dev/null +++ b/maps_managers/easynav_navmap_maps_manager/include/easynav_navmap_maps_manager/filters/rtin_lod.hpp @@ -0,0 +1,226 @@ +// Copyright 2026 Intelligent Robotics Lab +// +// This file is part of the project Easy Navigation (EasyNav in short) +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/// \file +/// \brief Merge/split level of detail of a grid NavMap driven by the values of one layer. + +#ifndef EASYNAV_NAVMAP_MAPS_MANAGER__FILTERS__RTIN_LOD_HPP_ +#define EASYNAV_NAVMAP_MAPS_MANAGER__FILTERS__RTIN_LOD_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "navmap_core/NavMap.hpp" + +namespace easynav +{ +namespace navmap +{ + +/** + * @brief Simplified copy of a grid NavMap: same-valued neighbour NavCels merged, split back where + * the values change. + * + * The source must be a regular grid of right isosceles triangles (two per square cell, legs = + * resolution), as pointcloud_to_navmap writes. A binary triangle tree (RTIN) is laid over it: two + * sibling triangles merge into their parent (twice the area) when all the cells below have the + * same value of the layer, the same height (within a tolerance) and no hole; otherwise the + * triangle is split in two along its hypotenuse, down to the cell halves. A split forces the + * neighbour sharing the hypotenuse to split too, so the mesh has no T-junctions and every edge + * has its neighbour (A* crosses between levels). + * + * A finest triangle may use the other diagonal of its cell than the source: then it takes the + * highest value of the two source halves and exists only if both exist. + */ +class RtinLod +{ +public: + struct Params + { + float max_angle_deg{5.0f}; ///< deg: merged NavCels differ at most this in slope + float height_tolerance{0.05f}; ///< m: source vertices at most this far from a merged + ///< NavCel's plane (a bound, accumulated per merge) + float tile_size{50.0f}; ///< m: side of the tiles extract() caches (about) + }; + + /// Statistics of the last extraction. + struct Stats + { + std::size_t triangles{0}; ///< NavCels of the simplified map + std::size_t finest{0}; ///< ...of them at the source resolution + int max_level{0}; ///< largest number of merges of one NavCel + std::size_t tiles{0}; ///< tiles with NavCels + std::size_t tiles_rebuilt{0}; ///< ...walked again in this extraction (the rest reused) + std::size_t dead{0}; ///< dead NavCels in the map (degenerate, unreachable) + double ms_mesh{0.0}; ///< time walking the changed tiles of the tree + double ms_assemble{0.0}; ///< time writing the changed tiles into the NavMap + double ms_finish{0.0}; ///< time of NavMap's surface indices + }; + + /// Builds the tree over `src` with the values of `layer` (uint8). false + `error` if `src` is + /// not a regular grid of right isosceles triangles or has no such layer. + bool build( + const ::navmap::NavMap & src, const std::string & layer, const Params & params, + std::string * error = nullptr); + + /// Reads the layer again and merges/splits where it changed. Returns the source NavCels whose + /// value changed (0: nothing to do). The source must be the same map given to build(). + std::size_t update(const ::navmap::NavMap & src); + + /// As update(), reading only the NavCels within `radius` of (x, y) (where the sensors change + /// the costs) and the next `sweep` NavCels of the whole map in turns (what changes far away, + /// as an obstacle memory forgetting, is caught within source_navcels() / sweep calls). The + /// cost does not depend on the size of the map. + std::size_t update_window( + const ::navmap::NavMap & src, double x, double y, double radius, std::size_t sweep); + + /// Builds the simplified NavMap: layers `` (uint8, the value of each NavCel), + /// `lod_level` (uint8, merges: 0 = source resolution, each level doubles the area) and + /// `modified` (uint8, 1 if the NavCel is not at the source resolution). One surface per tile + /// of the tree (about tile_size m). The map is the same object every call, edited in place: + /// only the tiles where something changed since the last call are walked and written again + /// (into their range of NavCels, or a new one at the end when they grew); the others are left + /// as they are. NavCels a tile no longer uses are dead: degenerate (all on vertex 0), without + /// neighbours, in no surface, value 254; when they outnumber the live ones the map is written + /// again from the tiles' cache. Whoever holds the pointer must not read it while extract() runs. + std::shared_ptr<::navmap::NavMap> extract(Stats * stats = nullptr); + + /// What extract() changed in the output since the last take_changes(), to send only that. + struct Changes + { + bool full{true}; ///< a new output (first, rebuilt or compacted): send it all + std::uint32_t first_vertex{0}; ///< vertices from here on are new + std::vector navcels; ///< rewritten NavCels (sorted) + std::vector surfaces; ///< replaced surfaces (sorted) + }; + + /// The changes accumulated since the last call (or since the output was created), and starts + /// accumulating again. + Changes take_changes(); + + bool ready() const {return built_;} + double resolution() const {return res_;} + std::size_t source_navcels() const {return src_count_;} + +private: + static constexpr std::uint32_t kNone = std::numeric_limits::max(); + // node state bits + static constexpr std::uint8_t kExists = 1; ///< leaf: covered by the source + static constexpr std::uint8_t kEmpty = 2; ///< no leaf below exists + static constexpr std::uint8_t kUniform = 4; ///< complete, flat, one value: may stay merged + static constexpr std::uint8_t kFlat = 8; ///< static: one plane (angle and deviation) + static constexpr std::uint8_t kComplete = 16; ///< static: every leaf below exists + static constexpr std::uint8_t kSplit = 32; ///< split in the current mesh + + struct Tri + { + int ax, ay, bx, by, cx, cy; ///< doubled grid units; a-b hypotenuse, c right angle + }; + + void leaf_state(std::uint32_t k, const Tri & t); + bool need_split(std::uint32_t k) const; + const std::vector * layer_data(const ::navmap::NavMap & src) const; + bool read(std::uint32_t i, const std::vector & v); ///< queues its leaves + std::size_t apply(std::size_t changed); ///< merges/splits for the queued leaves + void refresh_leaf(std::uint32_t k, std::size_t cell, int slot); + bool recompute_merge(std::uint32_t k); + /// The NavCels of one tile (or of the top of the tree), in local numbering + struct Tile + { + std::vector grid; ///< per local vertex: its cell corner (shared by + ///< the tiles once assembled) + std::vector<::navmap::NavCel> cells; ///< local vertices and neighbours (kNone: border) + std::vector values, levels; + std::vector<::navmap::BVHNode> bvh; ///< root at 0; leaves index `prim` + std::vector prim; ///< local NavCel ids + std::vector> border; ///< (edge midpoint, cell*3+e) + std::size_t finest{0}; + int max_level{0}; + bool dirty{true}; + }; + /// Emits the NavCels under node k into `tile`; returns its BVH node (-1: none). With + /// `stop_depth`, nodes at that depth are not walked (the top of the tree). + int extract_node(std::uint32_t k, const Tri & t, int depth, int stop_depth, Tile & tile); + void extract_tile(std::size_t i); + void reset_output(); + void write_tile(std::size_t i); + void kill(std::uint32_t from, std::uint32_t to); ///< NavCels [from, to) dead + void mark(std::uint32_t k, bool split_changed); ///< the tiles whose mesh changes with k + Tri node_tri(std::uint32_t k, int depth) const; + static Tri child(const Tri & t, int side); + float zat(int gx, int gy) const; ///< height of a cell corner (cell grid units) + + bool built_{false}; + std::string layer_; + Params params_; + double res_{0.0}, ox_{0.0}, oy_{0.0}; + int n_{0}; ///< cells per side of the padded square (power of two) + int leaf_depth_{0}; ///< depth of the cell halves (roots: 1) + std::size_t src_count_{0}; + + std::vector z_; ///< (n+1)^2 cell corner heights (NaN: none) + std::vector cell_src_; ///< 2 per cell: source NavCel of each half, or kNone + std::vector cell_diag_; ///< per cell: 1 if the source halves split it by the + ///< main diagonal ((0,0)-(1,1)), 0 the other one + std::vector cell_leaf_; ///< 2 per cell: the tree's leaves on it + std::vector cell_leaf_main_; ///< per cell: 1 if the tree splits it by the main + ///< diagonal + std::vector src_cell_; ///< per source NavCel: its cell + std::vector src_value_; ///< per source NavCel: last value read + std::vector pending_; ///< leaves (cell << 1 | half) to refresh + std::size_t cursor_{0}; ///< next source NavCel of the sweep + + std::vector value_; ///< per tree node: its value (if uniform) + std::vector state_; ///< per tree node: k* bits + std::vector partner_; ///< per tree node: the one sharing its hypotenuse + + int tile_depth_{1}; ///< depth of the tiles' root nodes + std::vector tiles_; ///< 2^tile_depth_ tiles + the top of the tree (last) + + // the output, edited in place + struct Slot + { + std::uint32_t base{0}, cap{0}, count{0}; ///< its range of NavCels + std::vector> border; ///< (midpoint, NavCel*3+e) + }; + std::shared_ptr<::navmap::NavMap> out_; + std::vector slots_; ///< per tile + std::unordered_map> border_edges_; + std::vector gvert_; ///< (n+1)^2 cell corners: output vertex + std::vector local_to_global_; + std::size_t dead_{0}; + // changes since the last take_changes() + bool changes_full_{true}; + std::uint32_t changes_first_vertex_{0}; + std::vector> changed_ranges_; ///< [from, to) + std::vector changed_surfaces_; + std::shared_ptr<::navmap::LayerView> values_l_, levels_l_, modified_l_; + + // scratch of extract(), kept empty between calls (only the used entries are reset) + std::vector vmap_; ///< (n+1)^2 cell corners: tile vertex + std::vector edge_; ///< (2n+1)^2 edge midpoints: first NavCel * 3 + edge + std::vector touched_v_, touched_e_; +}; + +} // namespace navmap +} // namespace easynav + +#endif // EASYNAV_NAVMAP_MAPS_MANAGER__FILTERS__RTIN_LOD_HPP_ diff --git a/maps_managers/easynav_navmap_maps_manager/src/easynav_navmap_maps_manager/filters/FractalFilter.cpp b/maps_managers/easynav_navmap_maps_manager/src/easynav_navmap_maps_manager/filters/FractalFilter.cpp new file mode 100644 index 00000000..71d31350 --- /dev/null +++ b/maps_managers/easynav_navmap_maps_manager/src/easynav_navmap_maps_manager/filters/FractalFilter.cpp @@ -0,0 +1,223 @@ +// Copyright 2026 Intelligent Robotics Lab +// +// This file is part of the project Easy Navigation (EasyNav in short) +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "easynav_navmap_maps_manager/filters/FractalFilter.hpp" + +#include +#include +#include + +#include "easynav_common/Parameters.hpp" +#include "easynav_common/RTTFBuffer.hpp" +#include "nav_msgs/msg/odometry.hpp" +#include "navmap_core/NavMap.hpp" +#include "navmap_ros/conversions.hpp" + +namespace easynav +{ +namespace navmap +{ + +void FractalFilter::on_initialize() +{ + auto node = get_node(); + const std::string p = get_plugin_name() + "."; + double height_tolerance = params_.height_tolerance; + double max_angle_deg = params_.max_angle_deg; + double tile_size = params_.tile_size; + easynav::declare_parameter_if_absent(*node, p + "output_key", output_key_); + easynav::declare_parameter_if_absent(*node, p + "layer", layer_); + easynav::declare_parameter_if_absent(*node, p + "rebuild_period", rebuild_period_); + easynav::declare_parameter_if_absent(*node, p + "height_tolerance", height_tolerance); + easynav::declare_parameter_if_absent(*node, p + "max_angle_deg", max_angle_deg); + easynav::declare_parameter_if_absent(*node, p + "tile_size", tile_size); + easynav::declare_parameter_if_absent(*node, p + "window_radius", window_radius_); + easynav::declare_parameter_if_absent(*node, p + "sweep", sweep_); + easynav::declare_parameter_if_absent(*node, p + "publish_period", publish_period_); + easynav::declare_parameter_if_absent(*node, p + "full_period", full_period_); + easynav::declare_parameter_if_absent(*node, p + "log_period", log_period_); + node->get_parameter(p + "output_key", output_key_); + node->get_parameter(p + "layer", layer_); + node->get_parameter(p + "rebuild_period", rebuild_period_); + node->get_parameter(p + "height_tolerance", height_tolerance); + node->get_parameter(p + "max_angle_deg", max_angle_deg); + node->get_parameter(p + "tile_size", tile_size); + node->get_parameter(p + "window_radius", window_radius_); + node->get_parameter(p + "sweep", sweep_); + node->get_parameter(p + "publish_period", publish_period_); + node->get_parameter(p + "full_period", full_period_); + node->get_parameter(p + "log_period", log_period_); + params_.height_tolerance = static_cast(height_tolerance); + params_.max_angle_deg = static_cast(max_angle_deg); + params_.tile_size = static_cast(tile_size); + if (output_key_ == input_key_) { + // the other filters would then run on the merged map + throw std::invalid_argument( + "[" + get_plugin_name() + "] output_key must not be " + input_key_); + } + + // "navmap.fractal" -> ".../navmap/fractal/map" + std::string topic_name = get_plugin_name(); + std::replace(topic_name.begin(), topic_name.end(), '.', '/'); + map_pub_ = node->create_publisher( + node->get_node_base_interface()->get_fully_qualified_name() + std::string("/") + + topic_name + "/map", rclcpp::QoS(1).transient_local().reliable()); + // Only what changed since the last map or patch: what RViz's NavMap display applies + patch_pub_ = node->create_publisher( + node->get_node_base_interface()->get_fully_qualified_name() + std::string("/") + + topic_name + "/map_patch", rclcpp::QoS(10).reliable()); + RCLCPP_INFO( + node->get_logger(), + "[%s] %s (layer %s) -> %s; merges within %.1f deg and %.2f m of the plane; costs read " + "within %.1f m of the robot plus %d NavCels per cycle", get_plugin_name().c_str(), + input_key_.c_str(), layer_.c_str(), output_key_.c_str(), max_angle_deg, height_tolerance, + window_radius_, sweep_); +} + +void FractalFilter::update(::easynav::NavState & nav_state) +{ + if (!nav_state.has(input_key_)) {return;} + auto node = get_node(); + const auto & src = nav_state.get<::navmap::NavMap>(input_key_); + using clock = std::chrono::steady_clock; + + // A new source map (or the first one with the layer): the tree is built again + if (!lod_.ready() || src.geometry_id() != source_geometry_ || + src.navcels.size() != source_navcels_) + { + if (!src.layers.get(layer_)) { + RCLCPP_INFO_THROTTLE( + node->get_logger(), *node->get_clock(), 5000, "[%s] waiting for layer %s in %s", + get_plugin_name().c_str(), layer_.c_str(), input_key_.c_str()); + return; + } + const auto t0 = clock::now(); + std::string error; + if (!lod_.build(src, layer_, params_, &error)) { + RCLCPP_ERROR_THROTTLE( + node->get_logger(), *node->get_clock(), 5000, "[%s] cannot simplify %s: %s", + get_plugin_name().c_str(), input_key_.c_str(), error.c_str()); + return; + } + source_geometry_ = src.geometry_id(); + source_navcels_ = src.navcels.size(); + dirty_ = true; + RCLCPP_INFO( + node->get_logger(), "[%s] tree over %zu NavCels of %.2f m built in %.0f ms", + get_plugin_name().c_str(), source_navcels_, lod_.resolution(), + std::chrono::duration(clock::now() - t0).count()); + } else { + // only around the robot (where the sensors change the costs) and a slice of the map + double x = 0.0, y = 0.0, radius = -1.0; + if (nav_state.has("robot_pose")) { + const auto & pose = nav_state.get("robot_pose").pose.pose.position; + x = pose.x; + y = pose.y; + radius = window_radius_; + } + if (lod_.update_window(src, x, y, radius, static_cast(std::max(0, sweep_))) > 0) { + dirty_ = true; + } + } + + const auto now = node->now(); + if (dirty_ && (!extracted_once_ || (now - last_extract_).seconds() >= rebuild_period_)) { + const auto t0 = clock::now(); + RtinLod::Stats st; + out_ = lod_.extract(&st); + const double ms_extract = + std::chrono::duration(clock::now() - t0).count(); + const std::string frame = RTTFBuffer::getInstance()->get_tf_info().map_frame; + for (auto & s : out_->surfaces) { + s.frame_id = frame; + } + // The same object every time, edited in place by extract(): no copy. Safe because its only + // reader (A*) runs in the same non real-time executor as the maps managers and their filters. + nav_state.set(output_key_, out_); + RCLCPP_INFO_THROTTLE( + node->get_logger(), *node->get_clock(), + extracted_once_ ? static_cast(log_period_ * 1000.0) : 0, + "[%s] %zu NavCels (%.1f %% of %zu; %zu at the source resolution, largest %d merges) in " + "%.0f ms (%zu of %zu tiles walked %.0f, written %.0f, indices %.0f; %zu dead)", + get_plugin_name().c_str(), st.triangles, + 100.0 * st.triangles / std::max(1, source_navcels_), source_navcels_, + st.finest, st.max_level, ms_extract, st.tiles_rebuilt, st.tiles, st.ms_mesh, + st.ms_assemble, st.ms_finish, st.dead); + dirty_ = false; + extracted_once_ = true; + last_extract_ = now; + } + publish(now); +} + +void FractalFilter::publish(const rclcpp::Time & now) +{ + if (!out_) {return;} + auto node = get_node(); + const std::size_t subscribers = + map_pub_->get_subscription_count() + patch_pub_->get_subscription_count(); + const bool new_subscriber = subscribers > last_subscribers_; + last_subscribers_ = subscribers; + if (subscribers == 0) { + // Nobody keeps a copy: the next one gets a full map + lod_.take_changes(); + need_full_ = true; + return; + } + const bool due = !sent_once_ || (now - last_publish_).seconds() >= publish_period_; + if (!due && !new_subscriber) {return;} + + using clock = std::chrono::steady_clock; + const auto t0 = clock::now(); + const auto changes = lod_.take_changes(); + // (times compared only once set: an unset rclcpp::Time is of another clock) + const bool full_due = + sent_once_ && full_period_ > 0.0 && (now - last_full_).seconds() >= full_period_; + std_msgs::msg::Header header; + header.frame_id = RTTFBuffer::getInstance()->get_tf_info().map_frame; + header.stamp = now; + std::size_t sent = 0; + const char * kind = ""; + if (changes.full || need_full_ || new_subscriber || full_due || !sent_once_) { + // A new output, a receiver without a copy, or the periodic resync: the whole map + auto msg = navmap_ros::to_msg(*out_, header); + sent = msg.navcels_v0.size(); + map_pub_->publish(msg); + last_full_ = now; + kind = "map"; + } else if (!changes.navcels.empty() || !changes.surfaces.empty()) { + const auto patch = navmap_ros::to_patch_msg( + *out_, last_sent_id_, changes.first_vertex, changes.navcels, changes.surfaces, header); + sent = patch.navcel_indices.size(); + patch_pub_->publish(patch); + kind = "patch"; + } else { + last_publish_ = now; + return; // nothing changed + } + last_sent_id_ = out_->geometry_id(); + need_full_ = false; + sent_once_ = true; + last_publish_ = now; + RCLCPP_DEBUG( + node->get_logger(), "[%s] %s with %zu NavCels published in %.1f ms", get_plugin_name().c_str(), + kind, sent, std::chrono::duration(clock::now() - t0).count()); +} + +} // namespace navmap +} // namespace easynav + +#include "pluginlib/class_list_macros.hpp" +PLUGINLIB_EXPORT_CLASS(easynav::navmap::FractalFilter, easynav::navmap::NavMapFilter) diff --git a/maps_managers/easynav_navmap_maps_manager/src/easynav_navmap_maps_manager/filters/rtin_lod.cpp b/maps_managers/easynav_navmap_maps_manager/src/easynav_navmap_maps_manager/filters/rtin_lod.cpp new file mode 100644 index 00000000..c2310faa --- /dev/null +++ b/maps_managers/easynav_navmap_maps_manager/src/easynav_navmap_maps_manager/filters/rtin_lod.cpp @@ -0,0 +1,821 @@ +// Copyright 2026 Intelligent Robotics Lab +// +// This file is part of the project Easy Navigation (EasyNav in short) +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "easynav_navmap_maps_manager/filters/rtin_lod.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace easynav +{ +namespace navmap +{ + +namespace +{ + +using LayerU8 = ::navmap::LayerView; + +bool fail(std::string * error, const std::string & msg) +{ + if (error) {*error = msg;} + return false; +} + +} // namespace + +RtinLod::Tri RtinLod::child(const Tri & t, int side) +{ + // the right angle c is joined to the hypotenuse midpoint m: two right triangles with their + // right angle at m, and the legs of t as their hypotenuses + const int mx = (t.ax + t.bx) / 2, my = (t.ay + t.by) / 2; + if (side == 0) {return {t.cx, t.cy, t.ax, t.ay, mx, my};} + return {t.bx, t.by, t.cx, t.cy, mx, my}; +} + +float RtinLod::zat(int gx, int gy) const +{ + return z_[static_cast(gy) * (n_ + 1) + gx]; +} + +bool RtinLod::build( + const ::navmap::NavMap & src, const std::string & layer, const Params & params, + std::string * error) +{ + built_ = false; + out_.reset(); // a new tree: the next extract() writes a new output, not over the old one + layer_ = layer; + params_ = params; + const auto values = std::dynamic_pointer_cast(src.layers.get(layer)); + if (!values) {return fail(error, "the NavMap has no uint8 layer '" + layer + "'");} + const std::size_t nc = src.navcels.size(); + if (nc == 0 || values->size() != nc) {return fail(error, "empty NavMap or layer");} + + // Resolution: the shortest edge of the first NavCel; origin: the lowest corner + auto P = [&src](std::uint32_t v) {return src.positions.at(v);}; + { + const auto & c = src.navcels[0]; + double r = 1e30; + for (int e = 0; e < 3; ++e) { + r = std::min(r, static_cast((P(c.v[e]) - P(c.v[(e + 1) % 3])).head<2>().norm())); + } + res_ = r; + } + if (!(res_ > 1e-6)) {return fail(error, "degenerate NavCels");} + double minx = 1e30, miny = 1e30, maxx = -1e30, maxy = -1e30; + for (std::size_t i = 0; i < src.positions.size(); ++i) { + minx = std::min(minx, static_cast(src.positions.x[i])); + miny = std::min(miny, static_cast(src.positions.y[i])); + maxx = std::max(maxx, static_cast(src.positions.x[i])); + maxy = std::max(maxy, static_cast(src.positions.y[i])); + } + ox_ = minx; + oy_ = miny; + const int cells = std::max( + 1, static_cast(std::lround(std::max(maxx - minx, maxy - miny) / res_))); + n_ = 1; + int log2n = 0; + while (n_ < cells) {n_ *= 2; ++log2n;} + leaf_depth_ = 1 + 2 * log2n; + if (leaf_depth_ > 29) {return fail(error, "the map is too big for the tree");} + const std::size_t ncells = static_cast(n_) * n_; + + // Grid indices of a point, checked against the grid + const double tol = 0.02 * res_; + auto grid = [&](const Eigen::Vector3f & p, int & gx, int & gy) { + const double fx = (p.x() - ox_) / res_, fy = (p.y() - oy_) / res_; + gx = static_cast(std::lround(fx)); + gy = static_cast(std::lround(fy)); + return std::abs(fx - gx) * res_ < tol && std::abs(fy - gy) * res_ < tol; + }; + + z_.assign(static_cast(n_ + 1) * (n_ + 1), std::nanf("")); + cell_src_.assign(2 * ncells, kNone); + cell_diag_.assign(ncells, 0); + src_cell_.assign(nc, kNone); + src_value_ = values->data(); + src_count_ = nc; + pending_.clear(); + cursor_ = 0; + + for (std::uint32_t i = 0; i < nc; ++i) { + const auto & c = src.navcels[i]; + int g[3][2]; + for (int k = 0; k < 3; ++k) { + if (!grid(P(c.v[k]), g[k][0], g[k][1])) { + return fail(error, "NavCel " + std::to_string(i) + " is not on a regular grid"); + } + } + // the right angle: the vertex whose two edges are one cell long, along x and y + int ra = -1; + for (int k = 0; k < 3 && ra < 0; ++k) { + const int * p = g[k], * q = g[(k + 1) % 3], * r = g[(k + 2) % 3]; + const int d1x = q[0] - p[0], d1y = q[1] - p[1], d2x = r[0] - p[0], d2y = r[1] - p[1]; + if (std::abs(d1x) + std::abs(d1y) == 1 && std::abs(d2x) + std::abs(d2y) == 1 && + d1x * d2x + d1y * d2y == 0) + { + ra = k; + } + } + if (ra < 0) { + return fail(error, "NavCel " + std::to_string(i) + " is not a cell half (" + + std::to_string(res_) + " m legs)"); + } + const int cx = std::min({g[0][0], g[1][0], g[2][0]}); + const int cy = std::min({g[0][1], g[1][1], g[2][1]}); + const int rx = g[ra][0] - cx, ry = g[ra][1] - cy; + const std::uint8_t diag = (rx != ry) ? 1 : 0; // right angle off the main diagonal + const std::size_t cell = static_cast(cy) * n_ + cx; + const std::size_t slot = 2 * cell + ry; + if (cell_src_[slot] != kNone || + (cell_src_[2 * cell + 1 - ry] != kNone && cell_diag_[cell] != diag)) + { + return fail(error, "overlapping NavCels in cell (" + std::to_string(cx) + ", " + + std::to_string(cy) + "): several levels are not supported"); + } + cell_src_[slot] = i; + cell_diag_[cell] = diag; + src_cell_[i] = static_cast(cell); + for (int k = 0; k < 3; ++k) { + float & z = z_[static_cast(g[k][1]) * (n_ + 1) + g[k][0]]; + const float pz = P(c.v[k]).z(); + if (std::isnan(z)) { + z = pz; + } else if (std::abs(z - pz) > 0.01f) { + return fail(error, "two heights at one vertex: several levels are not supported"); + } + } + } + + const std::size_t nodes = std::size_t{1} << (leaf_depth_ + 1); + value_.assign(nodes, 0); + state_.assign(nodes, 0); + partner_.assign(nodes, kNone); + cell_leaf_.assign(2 * ncells, kNone); + cell_leaf_main_.assign(ncells, 0); + + // Pass 1: leaves, merges and the pairs sharing a hypotenuse (by its midpoint) + std::vector first_at(z_.size(), kNone); + const int T = 2 * n_; + // recursive: the depth is at most 29 + // corner of the doubled grid -> point; the normal of a node's triangle + auto point = [this](int dx, int dy) { + return Eigen::Vector3f( + static_cast(dx / 2 * res_), static_cast(dy / 2 * res_), zat(dx / 2, dy / 2)); + }; + auto normal = [&point](const Tri & t) { + Eigen::Vector3f n = (point(t.bx, t.by) - point(t.ax, t.ay)).cross( + point(t.cx, t.cy) - point(t.ax, t.ay)); + if (n.z() < 0.0f) {n = -n;} + const float len = n.norm(); + return len > 0.0f ? Eigen::Vector3f(n / len) : Eigen::Vector3f(0.0f, 0.0f, 1.0f); + }; + const float cos_max = std::cos(params_.max_angle_deg * static_cast(M_PI) / 180.0f); + // Geometry of a subtree: the normal of its triangle and a bound of how far the source vertices + // under it are from its plane. Two children merge if both fit the parent's plane: their + // normals within max_angle_deg of it, and the bound within height_tolerance. + struct Geo + { + Eigen::Vector3f n; + float dev; + }; + // recursive: the depth is at most 29 + std::function rec; + rec = [&](std::uint32_t k, const Tri & t, int depth) -> Geo { + if (depth == leaf_depth_) { + leaf_state(k, t); + return {(state_[k] & kExists) ? normal(t) : Eigen::Vector3f(0.0f, 0.0f, 1.0f), 0.0f}; + } + const std::size_t mv = static_cast((t.ay + t.by) / 4) * (n_ + 1) + + (t.ax + t.bx) / 4; + if (first_at[mv] == kNone) { + first_at[mv] = k; + } else { + partner_[k] = first_at[mv]; + partner_[first_at[mv]] = k; + } + const Geo g0 = rec(2 * k, child(t, 0), depth + 1); + const Geo g1 = rec(2 * k + 1, child(t, 1), depth + 1); + const std::uint8_t s0 = state_[2 * k], s1 = state_[2 * k + 1]; + std::uint8_t s = 0; + if ((s0 & kEmpty) && (s1 & kEmpty)) {s |= kEmpty;} + Geo g{Eigen::Vector3f(0.0f, 0.0f, 1.0f), 0.0f}; + if ((s0 & kComplete) && (s1 & kComplete)) { + s |= kComplete; + g.n = normal(t); + // the only vertex of the children off the parent's corners: the hypotenuse midpoint + const float off = std::abs( + g.n.dot(point((t.ax + t.bx) / 2, (t.ay + t.by) / 2) - point(t.ax, t.ay))); + g.dev = off + std::max(g0.dev, g1.dev); + if ((s0 & kFlat) && (s1 & kFlat) && g.n.dot(g0.n) >= cos_max - 1e-6f && + g.n.dot(g1.n) >= cos_max - 1e-6f && g.dev <= params_.height_tolerance) + { + s |= kFlat; + } + } + state_[k] = s; + recompute_merge(k); + return g; + }; + rec(2, Tri{0, 0, T, T, T, 0}, 1); + rec(3, Tri{T, T, 0, 0, 0, T}, 1); + + // Pass 2: splits, deepest first; a split splits the pair sharing the hypotenuse too + for (std::uint32_t k = (std::uint32_t{1} << leaf_depth_) - 1; k >= 2; --k) { + if (need_split(k)) { + state_[k] |= kSplit; + if (partner_[k] != kNone) {state_[partner_[k]] |= kSplit;} + } + } + // Tiles: subtrees of about tile_size^2 m^2 (a root covers (n res)^2 / 2) + const double root_area = 0.5 * (n_ * res_) * (n_ * res_); + const double tile_area = std::max(1e-6, static_cast(params_.tile_size) * + params_.tile_size); + tile_depth_ = 1 + std::max(0, static_cast(std::ceil(std::log2(root_area / tile_area)))); + tile_depth_ = std::min(tile_depth_, leaf_depth_); + tiles_.assign((std::size_t{1} << tile_depth_) + 1, Tile{}); + vmap_.assign(z_.size(), kNone); + edge_.assign(static_cast(2 * n_ + 1) * (2 * n_ + 1), kNone); + built_ = true; + return true; +} + +void RtinLod::leaf_state(std::uint32_t k, const Tri & t) +{ + const int cx = std::min({t.ax, t.bx, t.cx}) / 2, cy = std::min({t.ay, t.by, t.cy}) / 2; + const std::size_t cell = static_cast(cy) * n_ + cx; + const int slot = t.cy / 2 - cy; // the half: the row of its right angle in the cell + cell_leaf_[2 * cell + slot] = k; + cell_leaf_main_[cell] = (t.ax - t.bx) * (t.ay - t.by) > 0 ? 1 : 0; + refresh_leaf(k, cell, slot); +} + +void RtinLod::refresh_leaf(std::uint32_t k, std::size_t cell, int slot) +{ + // the source half it is, or (other diagonal) the two halves it overlaps: the highest value, + // and it exists only if both do + const std::uint32_t s0 = cell_src_[2 * cell], s1 = cell_src_[2 * cell + 1]; + bool exists = false; + std::uint8_t v = 0; + if (cell_diag_[cell] == cell_leaf_main_[cell]) { + const std::uint32_t s = cell_src_[2 * cell + slot]; + exists = s != kNone; + if (exists) {v = src_value_[s];} + } else { + exists = s0 != kNone && s1 != kNone; + if (exists) {v = std::max(src_value_[s0], src_value_[s1]);} + } + value_[k] = v; + state_[k] = exists ? (kExists | kComplete | kFlat | kUniform) : kEmpty; +} + +bool RtinLod::recompute_merge(std::uint32_t k) +{ + const std::uint8_t s = state_[k], s0 = state_[2 * k], s1 = state_[2 * k + 1]; + const bool u = (s & kComplete) && (s & kFlat) && (s0 & kUniform) && (s1 & kUniform) && + value_[2 * k] == value_[2 * k + 1]; + const std::uint8_t v = u ? value_[2 * k] : 0; + const bool changed = u != static_cast(s & kUniform) || v != value_[k]; + state_[k] = u ? (s | kUniform) : (s & ~kUniform); + value_[k] = v; + return changed; +} + +bool RtinLod::need_split(std::uint32_t k) const +{ + const std::uint8_t s = state_[k]; + if (s & kEmpty) {return false;} + return !(s & kUniform) || (state_[2 * k] & kSplit) || (state_[2 * k + 1] & kSplit); +} + +const std::vector * RtinLod::layer_data(const ::navmap::NavMap & src) const +{ + if (!built_) {return nullptr;} + const auto values = std::dynamic_pointer_cast(src.layers.get(layer_)); + if (!values || values->size() != src_count_) {return nullptr;} + return &values->data(); +} + +bool RtinLod::read(std::uint32_t i, const std::vector & v) +{ + if (v[i] == src_value_[i]) {return false;} + src_value_[i] = v[i]; + const std::size_t cell = src_cell_[i]; + for (int s = 0; s < 2; ++s) { + if (cell_leaf_[2 * cell + s] != kNone) {pending_.push_back((cell << 1) | s);} + } + return true; +} + +std::size_t RtinLod::update(const ::navmap::NavMap & src) +{ + const auto * v = layer_data(src); + if (!v) {return 0;} + std::size_t changed = 0; + for (std::uint32_t i = 0; i < src_count_; ++i) { + changed += read(i, *v); + } + return apply(changed); +} + +std::size_t RtinLod::update_window( + const ::navmap::NavMap & src, double x, double y, double radius, std::size_t sweep) +{ + const auto * v = layer_data(src); + if (!v) {return 0;} + std::size_t changed = 0; + // the cells around the robot, where the sensors change the costs + const int i0 = std::max(0, static_cast(std::floor((x - radius - ox_) / res_))); + const int j0 = std::max(0, static_cast(std::floor((y - radius - oy_) / res_))); + const int i1 = std::min(n_ - 1, static_cast(std::floor((x + radius - ox_) / res_))); + const int j1 = std::min(n_ - 1, static_cast(std::floor((y + radius - oy_) / res_))); + for (int j = j0; j <= j1; ++j) { + for (int i = i0; i <= i1; ++i) { + const std::size_t cell = static_cast(j) * n_ + i; + for (int s = 0; s < 2; ++s) { + if (cell_src_[2 * cell + s] != kNone) {changed += read(cell_src_[2 * cell + s], *v);} + } + } + } + // and a slice of the whole map, in turns: what changes far away (an obstacle the memory + // forgets after the robot left) is caught within src_count / sweep cycles + for (std::size_t k = 0; k < std::min(sweep, src_count_); ++k) { + changed += read(static_cast(cursor_), *v); + cursor_ = (cursor_ + 1) % src_count_; + } + return apply(changed); +} + +std::size_t RtinLod::apply(std::size_t changed) +{ + std::vector leaves; + leaves.swap(pending_); + if (changed == 0) {return 0;} + std::sort(leaves.begin(), leaves.end()); + leaves.erase(std::unique(leaves.begin(), leaves.end()), leaves.end()); + + // merges, from the leaves up while something changes + std::priority_queue todo; // deepest (largest id) first + for (const auto cs : leaves) { + const std::size_t cell = cs >> 1; + const int slot = static_cast(cs & 1); + const std::uint32_t leaf = cell_leaf_[2 * cell + slot]; + const std::uint8_t old_v = value_[leaf]; + refresh_leaf(leaf, cell, slot); + if (value_[leaf] == old_v) {continue;} + mark(leaf, false); + for (std::uint32_t k = leaf >> 1; k >= 2; k >>= 1) { + if (!recompute_merge(k)) {break;} + mark(k, false); + todo.push(k); + } + } + // splits: a change in a node's split changes its parent's and its pair's parent's + std::uint32_t last = 0; + while (!todo.empty()) { + const std::uint32_t k = todo.top(); + todo.pop(); + if (k == last) {continue;} + last = k; + const std::uint32_t p = partner_[k]; + const bool split = need_split(k) || (p != kNone && need_split(p)); + if (split == static_cast(state_[k] & kSplit)) {continue;} + auto set = [this, split](std::uint32_t x) { + state_[x] = split ? (state_[x] | kSplit) : (state_[x] & ~kSplit); + }; + set(k); + mark(k, true); + if (k >= 4) {todo.push(k >> 1);} + if (p != kNone) { + set(p); + mark(p, true); + if (p >= 4) {todo.push(p >> 1);} + } + } + return changed; +} + +void RtinLod::mark(std::uint32_t k, bool split_changed) +{ + const int depth = 31 - __builtin_clz(k); + const std::size_t first = std::size_t{1} << tile_depth_; + if (depth >= tile_depth_) { + tiles_[(k >> (depth - tile_depth_)) - first].dirty = true; + return; + } + tiles_.back().dirty = true; // the top of the tree + if (split_changed) { // what it covered (or now uncovers) are whole tiles + const int shift = tile_depth_ - depth; + const std::size_t t0 = (static_cast(k) << shift) - first; + for (std::size_t t = t0; t < t0 + (std::size_t{1} << shift); ++t) { + tiles_[t].dirty = true; + } + } +} + +RtinLod::Tri RtinLod::node_tri(std::uint32_t k, int depth) const +{ + // below the leading bit: the root (2 or 3), then the side taken at each level + const int T = 2 * n_; + Tri t = ((k >> (depth - 1)) & 1) ? Tri{T, T, 0, 0, 0, T} : Tri{0, 0, T, T, T, 0}; + for (int b = depth - 2; b >= 0; --b) { + t = child(t, (k >> b) & 1); + } + return t; +} + +namespace +{ +constexpr std::uint32_t kPaired = std::numeric_limits::max() - 1; +} // namespace + +int RtinLod::extract_node( + std::uint32_t k, const Tri & t, int depth, int stop_depth, Tile & tile) +{ + if (depth == stop_depth) {return -1;} + const std::uint8_t s = state_[k]; + if (s & kEmpty) {return -1;} + const bool leaf = depth == leaf_depth_; + if (!leaf && (s & kSplit)) { + // the tree is the BVH: a split node bounds its two children + const int l = extract_node(2 * k, child(t, 0), depth + 1, stop_depth, tile); + const int r = extract_node(2 * k + 1, child(t, 1), depth + 1, stop_depth, tile); + if (l < 0 || r < 0) {return l < 0 ? r : l;} + ::navmap::BVHNode node; + node.box = tile.bvh[l].box; + node.box.expand(tile.bvh[r].box); + node.left = l; + node.right = r; + tile.bvh.push_back(node); + return static_cast(tile.bvh.size()) - 1; + } + if (leaf && !(s & kExists)) {return -1;} + + auto vertex = [&](int dx, int dy) { + const int gx = dx / 2, gy = dy / 2; + const std::size_t vi = static_cast(gy) * (n_ + 1) + gx; + std::uint32_t & id = vmap_[vi]; + if (id == kNone) { + id = static_cast(tile.grid.size()); + tile.grid.push_back(static_cast(vi)); + touched_v_.push_back(static_cast(vi)); + } + return id; + }; + int px[3] = {t.ax, t.bx, t.cx}, py[3] = {t.ay, t.by, t.cy}; + // counter-clockwise seen from above: the normal points up + if ((t.bx - t.ax) * (t.cy - t.ay) - (t.by - t.ay) * (t.cx - t.ax) < 0) { + std::swap(px[0], px[1]); + std::swap(py[0], py[1]); + } + ::navmap::NavCel cell; + cell.v[0] = vertex(px[0], py[0]); + cell.v[1] = vertex(px[1], py[1]); + cell.v[2] = vertex(px[2], py[2]); + const auto cid = static_cast(tile.cells.size()); + tile.cells.push_back(cell); + + // neighbours: without T-junctions, the midpoint of an edge (doubled grid) is the edge + const int T = 2 * n_; + for (int e = 0; e < 3; ++e) { + const std::size_t m = static_cast((py[e] + py[(e + 1) % 3]) / 2) * (T + 1) + + (px[e] + px[(e + 1) % 3]) / 2; + std::uint32_t & slot = edge_[m]; + if (slot == kNone) { + slot = cid * 3 + e; + touched_e_.push_back(static_cast(m)); + } else { + tile.cells[cid].neighbor[e] = slot / 3; + tile.cells[slot / 3].neighbor[slot % 3] = cid; + slot = kPaired; + } + } + + ::navmap::BVHNode node; + for (int v = 0; v < 3; ++v) { + const int gx = px[v] / 2, gy = py[v] / 2; + node.box.expand( + Eigen::Vector3f( + static_cast(ox_ + gx * res_), static_cast(oy_ + gy * res_), zat(gx, gy))); + } + node.start = static_cast(tile.prim.size()); + node.count = 1; + tile.prim.push_back(static_cast(cid)); + tile.bvh.push_back(node); + + const int level = leaf_depth_ - depth; + tile.values.push_back(value_[k]); + tile.levels.push_back(static_cast(level)); + if (level == 0) {++tile.finest;} + tile.max_level = std::max(tile.max_level, level); + return static_cast(tile.bvh.size()) - 1; +} + +void RtinLod::extract_tile(std::size_t i) +{ + Tile & tile = tiles_[i]; + const std::size_t keep = tile.cells.size(); + tile = Tile{}; + tile.dirty = false; + tile.cells.reserve(keep); + tile.grid.reserve(keep); + tile.bvh.reserve(2 * keep); + tile.prim.reserve(keep); + tile.values.reserve(keep); + tile.levels.reserve(keep); + + int root = -1; + if (i + 1 == tiles_.size()) { + // the top: what is merged above the tiles' depth + const int T = 2 * n_; + const int l = extract_node(2, Tri{0, 0, T, T, T, 0}, 1, tile_depth_, tile); + const int r = extract_node(3, Tri{T, T, 0, 0, 0, T}, 1, tile_depth_, tile); + root = l < 0 ? r : l; + if (l >= 0 && r >= 0) { + ::navmap::BVHNode node; + node.box = tile.bvh[l].box; + node.box.expand(tile.bvh[r].box); + node.left = l; + node.right = r; + tile.bvh.push_back(node); + root = static_cast(tile.bvh.size()) - 1; + } + } else { + const auto k = static_cast((std::size_t{1} << tile_depth_) + i); + // inside a NavCel merged above it (or nothing under it): no NavCels of its own + bool covered = false; + for (std::uint32_t a = k >> 1; a >= 2 && !covered; a >>= 1) { + covered = !(state_[a] & kSplit); + } + if (!covered) {root = extract_node(k, node_tri(k, tile_depth_), tile_depth_, -1, tile);} + } + + if (root >= 0) { + // NavMap starts its traversals at node 0: the root (built last) moves to the front + const int last = static_cast(tile.bvh.size()) - 1; + auto renum = [last](int n) {return n < 0 ? n : (n == last ? 0 : n + 1);}; + std::vector<::navmap::BVHNode> bvh(tile.bvh.size()); + for (int n = 0; n <= last; ++n) { + auto b = tile.bvh[n]; + b.left = renum(b.left); + b.right = renum(b.right); + bvh[renum(n)] = b; + } + tile.bvh.swap(bvh); + } + // the edges left unpaired are the tile's border; the scratch tables back to empty + for (const auto m : touched_e_) { + if (edge_[m] != kPaired) {tile.border.emplace_back(m, edge_[m]);} + edge_[m] = kNone; + } + for (const auto v : touched_v_) { + vmap_[v] = kNone; + } + touched_e_.clear(); + touched_v_.clear(); +} + +void RtinLod::reset_output() +{ + out_ = std::make_shared<::navmap::NavMap>(); + auto & out = *out_; + // vertex 0: the anchor of the dead NavCels (degenerate: no area, no neighbours, in no BVH) + out.add_vertex(Eigen::Vector3f(static_cast(ox_), static_cast(oy_), 0.0f)); + for (std::size_t i = 0; i < tiles_.size(); ++i) { + out.create_surface("map"); + } + values_l_ = out.add_layer(layer_, "value of the source layer", "", 0); + levels_l_ = out.add_layer( + "lod_level", "merges of this NavCel (0: source resolution; each one doubles the area)", "", 0); + modified_l_ = out.add_layer( + "modified", "1: not at the source resolution (merged)", "", 0); + slots_.assign(tiles_.size(), Slot{}); + border_edges_.clear(); + gvert_.assign(z_.size(), kNone); + dead_ = 0; + changes_full_ = true; + changed_ranges_.clear(); + changed_surfaces_.clear(); +} + +RtinLod::Changes RtinLod::take_changes() +{ + Changes ch; + ch.full = changes_full_ || !out_; + ch.first_vertex = changes_first_vertex_; + if (!ch.full) { + std::sort(changed_ranges_.begin(), changed_ranges_.end()); + const std::uint32_t n = static_cast(out_->navcels.size()); + std::uint32_t next = 0; // ranges overlap: each NavCel once + for (const auto & [from, to] : changed_ranges_) { + for (std::uint32_t c = std::max(from, next); c < std::min(to, n); ++c) { + ch.navcels.push_back(c); + } + next = std::max(next, to); + } + std::sort(changed_surfaces_.begin(), changed_surfaces_.end()); + changed_surfaces_.erase( + std::unique(changed_surfaces_.begin(), changed_surfaces_.end()), changed_surfaces_.end()); + ch.surfaces = changed_surfaces_; + } + changes_full_ = false; + changes_first_vertex_ = out_ ? static_cast(out_->positions.x.size()) : 0; + changed_ranges_.clear(); + changed_surfaces_.clear(); + return ch; +} + +void RtinLod::kill(std::uint32_t from, std::uint32_t to) +{ + if (from < to) {changed_ranges_.emplace_back(from, to);} + auto & cells = out_->navcels; + for (std::uint32_t c = from; c < to; ++c) { + cells[c] = ::navmap::NavCel{}; // vertices 0, 0, 0; no neighbours + cells[c].area = 0.0f; + values_l_->data()[c] = 254; // lethal, should anything look at it + levels_l_->data()[c] = 0; + modified_l_->data()[c] = 0; + } + dead_ += to - from; +} + +void RtinLod::write_tile(std::size_t i) +{ + const Tile & t = tiles_[i]; + Slot & s = slots_[i]; + auto & out = *out_; + auto & cells = out.navcels; + + // 1. its border edges let go of the neighbour tiles' NavCels + for (const auto & [m, g] : s.border) { + auto it = border_edges_.find(m); + if (it == border_edges_.end()) {continue;} + auto & own = it->second; + if (own[0] == g) {own[0] = own[1]; own[1] = kNone;} else if (own[1] == g) {own[1] = kNone;} + if (own[0] == kNone) { + border_edges_.erase(it); + } else { + cells[own[0] / 3].neighbor[own[0] % 3] = kNone; // it pointed at us + } + } + s.border.clear(); + + // 2. its range: the same one if it fits, else a new one at the end (the old one dies) + const auto n = static_cast(t.cells.size()); + if (n > s.cap) { + kill(s.base, s.base + s.count); + s.base = static_cast(cells.size()); + s.cap = n + n / 4 + 16; + const std::size_t size = cells.size() + s.cap; + cells.resize(size); + values_l_->data().resize(size, 254); + levels_l_->data().resize(size, 0); + modified_l_->data().resize(size, 0); + dead_ += s.cap; // a new NavCel is dead (vertices 0, 0, 0) until written + s.count = 0; + changed_ranges_.emplace_back(s.base, s.base + s.cap); // all of it is new + } + changed_ranges_.emplace_back(s.base, s.base + std::max(n, s.count)); + changed_surfaces_.push_back(i); + + // 3. the NavCels, on the shared vertices, with their normals + local_to_global_.resize(t.grid.size()); + for (std::size_t v = 0; v < t.grid.size(); ++v) { + const std::uint32_t gi = t.grid[v]; + std::uint32_t & id = gvert_[gi]; + if (id == kNone) { + const int gx = static_cast(gi % (n_ + 1)), gy = static_cast(gi / (n_ + 1)); + id = out.add_vertex( + Eigen::Vector3f( + static_cast(ox_ + gx * res_), static_cast(oy_ + gy * res_), zat(gx, gy))); + } + local_to_global_[v] = id; + } + const std::uint32_t base = s.base; + for (std::uint32_t c = 0; c < n; ++c) { + auto cell = t.cells[c]; + for (int e = 0; e < 3; ++e) { + cell.v[e] = local_to_global_[cell.v[e]]; + if (cell.neighbor[e] != kNone) {cell.neighbor[e] += base;} + } + const Eigen::Vector3f p0 = out.positions.at(cell.v[0]), p1 = out.positions.at(cell.v[1]), + p2 = out.positions.at(cell.v[2]); + const Eigen::Vector3f nn = (p1 - p0).cross(p2 - p0); + const float len = nn.norm(); + cell.area = 0.5f * len; + cell.normal = len > 0.0f ? Eigen::Vector3f(nn / len) : Eigen::Vector3f(0.0f, 0.0f, 1.0f); + cells[base + c] = cell; + values_l_->data()[base + c] = t.values[c]; + levels_l_->data()[base + c] = t.levels[c]; + modified_l_->data()[base + c] = t.levels[c] > 0 ? 1 : 0; + } + if (n < s.count) {kill(base + n, base + s.count);} + if (n > s.count) {dead_ -= n - s.count;} + s.count = n; + + // 4. its surface: the NavCels and the BVH (prim ids made global) + auto & surf = out.surfaces[i]; + surf.navcels.resize(n); + for (std::uint32_t c = 0; c < n; ++c) { + surf.navcels[c] = base + c; + } + surf.prim_indices.resize(t.prim.size()); + for (std::size_t p = 0; p < t.prim.size(); ++p) { + surf.prim_indices[p] = t.prim[p] + static_cast(base); + } + surf.bvh = t.bvh; + surf.aabb = t.bvh.empty() ? ::navmap::AABB{} : t.bvh.front().box; + + // 5. its border edges meet the neighbour tiles' + for (const auto & [m, ce] : t.border) { + const std::uint32_t g = (base + ce / 3) * 3 + ce % 3; + s.border.emplace_back(m, g); + auto & own = border_edges_.try_emplace(m, std::array{kNone, kNone}) + .first->second; + if (own[0] == kNone) { + own[0] = g; + } else { + own[1] = g; + cells[g / 3].neighbor[g % 3] = own[0] / 3; + cells[own[0] / 3].neighbor[own[0] % 3] = g / 3; + } + } +} + +std::shared_ptr<::navmap::NavMap> RtinLod::extract(Stats * stats) +{ + Stats st; + if (!built_) { + if (stats) {*stats = st;} + return std::make_shared<::navmap::NavMap>(); + } + using clock = std::chrono::steady_clock; + auto ms = [](clock::time_point a) { + return std::chrono::duration(clock::now() - a).count(); + }; + + auto t0 = clock::now(); + std::vector changed; + for (std::size_t i = 0; i < tiles_.size(); ++i) { + if (tiles_[i].dirty) {extract_tile(i); changed.push_back(i);} + } + st.tiles_rebuilt = changed.size(); + st.ms_mesh = ms(t0); + + t0 = clock::now(); + std::size_t live = 0; + for (const auto & s : slots_) { + live += s.count; + } + if (!out_ || (dead_ > live && dead_ > 65536)) { + // first time, or more dead NavCels than live ones: every tile again, from its cache + reset_output(); + for (std::size_t i = 0; i < tiles_.size(); ++i) { + write_tile(i); + } + } else { + for (const auto i : changed) { + write_tile(i); + } + } + st.ms_assemble = ms(t0); + + t0 = clock::now(); + // neighbours, BVHs, normals are already there: only the surface indices + out_->rebuild_geometry_accels(false, false, false); + st.ms_finish = ms(t0); + + for (std::size_t i = 0; i < tiles_.size(); ++i) { + const auto & t = tiles_[i]; + if (t.cells.empty()) {continue;} + ++st.tiles; + st.triangles += t.cells.size(); + st.finest += t.finest; + st.max_level = std::max(st.max_level, t.max_level); + } + st.dead = dead_; + if (stats) {*stats = st;} + return out_; +} + +} // namespace navmap +} // namespace easynav diff --git a/maps_managers/easynav_navmap_maps_manager/tests/CMakeLists.txt b/maps_managers/easynav_navmap_maps_manager/tests/CMakeLists.txt index 15c9394c..44329042 100644 --- a/maps_managers/easynav_navmap_maps_manager/tests/CMakeLists.txt +++ b/maps_managers/easynav_navmap_maps_manager/tests/CMakeLists.txt @@ -21,3 +21,9 @@ target_link_libraries(navmap_incremental_filters_tests ${PROJECT_NAME}) ament_add_gtest(navmap_obstacle_memory_tests navmap_obstacle_memory_tests.cpp) target_link_libraries(navmap_obstacle_memory_tests ${PROJECT_NAME}) + +ament_add_gtest(navmap_fractal_rtin_tests navmap_fractal_rtin_tests.cpp) +target_link_libraries(navmap_fractal_rtin_tests ${PROJECT_NAME}) + +ament_add_gtest(navmap_fractal_filter_tests navmap_fractal_filter_tests.cpp) +target_link_libraries(navmap_fractal_filter_tests ${PROJECT_NAME}) diff --git a/maps_managers/easynav_navmap_maps_manager/tests/navmap_fractal_filter_tests.cpp b/maps_managers/easynav_navmap_maps_manager/tests/navmap_fractal_filter_tests.cpp new file mode 100644 index 00000000..eef36280 --- /dev/null +++ b/maps_managers/easynav_navmap_maps_manager/tests/navmap_fractal_filter_tests.cpp @@ -0,0 +1,374 @@ +// Copyright 2026 Intelligent Robotics Lab +// +// This file is part of the project Easy Navigation (EasyNav in short) +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include +#include +#include +#include +#include +#include + +#include "gtest/gtest.h" +#include "nav_msgs/msg/occupancy_grid.hpp" +#include "nav_msgs/msg/odometry.hpp" +#include "navmap_core/NavMap.hpp" +#include "navmap_ros_interfaces/msg/nav_map_patch.hpp" +#include "navmap_ros/conversions.hpp" +#include "rclcpp/rclcpp.hpp" +#include "rclcpp_lifecycle/lifecycle_node.hpp" + +#include "easynav_navmap_maps_manager/filters/FractalFilter.hpp" + +namespace +{ + +constexpr int kCells = 64; // 6.4 x 6.4 m at 0.1 m +constexpr const char * kLayer = "inflated_obstacles"; + +} // namespace + +class NavmapFractalFilterTest : public ::testing::Test +{ +protected: + static void SetUpTestSuite() + { + if (!rclcpp::ok()) { + rclcpp::init(0, nullptr); + } + } + + void SetUp() override + { + nav_msgs::msg::OccupancyGrid grid; + grid.header.frame_id = "map"; + grid.info.resolution = 0.1; + grid.info.width = kCells; + grid.info.height = kCells; + grid.info.origin.orientation.w = 1.0; + grid.data.assign(kCells * kCells, 0); + auto nm = navmap_ros::from_occupancy_grid(grid); + for (std::size_t c = 0; c < nm.navcels.size(); ++c) { + nm.layer_set(kLayer, static_cast<::navmap::NavCelId>(c), 0); + } + source_navcels_ = nm.navcels.size(); + nav_state_.set("map.navmap", nm); + robot_at(0.5, 0.5); + } + + std::shared_ptr make_filter( + std::vector overrides = {}) + { + overrides.emplace_back("navmap.fractal.rebuild_period", 0.0); + node_ = std::make_shared( + "fractal_filter_test_node", rclcpp::NodeOptions().parameter_overrides(overrides)); + auto filter = std::make_shared(); + filter->initialize(node_, "navmap.fractal"); + return filter; + } + + void robot_at(double x, double y) + { + nav_msgs::msg::Odometry odom; + odom.pose.pose.position.x = x; + odom.pose.pose.position.y = y; + nav_state_.set("robot_pose", odom); + } + + // Sets the cost of the source NavCel under (x, y), in place, as a filter does. + void cost_at(float x, float y, std::uint8_t value) + { + auto nm = nav_state_.get_ptr<::navmap::NavMap>("map.navmap"); + std::size_t sidx = 0; + ::navmap::NavCelId cid; + Eigen::Vector3f bary, hit; + ASSERT_TRUE(nm->locate_navcel(Eigen::Vector3f(x, y, 0.0f), sidx, cid, bary, &hit)); + std::const_pointer_cast<::navmap::NavMap>(nm)->layer_set(kLayer, cid, value); + } + + // NavCels of the output that are not dead slots. + std::size_t live_navcels() + { + const auto & out = nav_state_.get<::navmap::NavMap>("map.navmap.lod"); + std::size_t n = 0; + for (const auto & c : out.navcels) { + n += !(c.v[0] == c.v[1] && c.v[1] == c.v[2]); + } + return n; + } + + rclcpp_lifecycle::LifecycleNode::SharedPtr node_; + easynav::NavState nav_state_; + std::size_t source_navcels_{0}; +}; + +TEST_F(NavmapFractalFilterTest, NothingWithoutTheMap) +{ + auto filter = make_filter(); + easynav::NavState empty; + filter->update(empty); + EXPECT_FALSE(empty.has("map.navmap.lod")); +} + +TEST_F(NavmapFractalFilterTest, WaitsForItsLayer) +{ + auto filter = make_filter({{"navmap.fractal.layer", "costs"}}); + filter->update(nav_state_); + EXPECT_FALSE(nav_state_.has("map.navmap.lod")); +} + +TEST_F(NavmapFractalFilterTest, AUniformMapMergesAndTheSourceIsUntouched) +{ + auto filter = make_filter(); + const auto geometry = nav_state_.get<::navmap::NavMap>("map.navmap").geometry_id(); + filter->update(nav_state_); + ASSERT_TRUE(nav_state_.has("map.navmap.lod")); + EXPECT_LT(live_navcels(), source_navcels_ / 100); + const auto & src = nav_state_.get<::navmap::NavMap>("map.navmap"); + EXPECT_EQ(src.navcels.size(), source_navcels_); + EXPECT_EQ(src.geometry_id(), geometry); +} + +TEST_F(NavmapFractalFilterTest, ACostNearTheRobotSplitsAndMergesBack) +{ + auto filter = make_filter(); + filter->update(nav_state_); + const auto merged = live_navcels(); + + cost_at(1.05f, 1.05f, 200); + filter->update(nav_state_); + const auto split = live_navcels(); + EXPECT_GT(split, merged); + + cost_at(1.05f, 1.05f, 0); + filter->update(nav_state_); + EXPECT_EQ(live_navcels(), merged); +} + +TEST_F(NavmapFractalFilterTest, TheOutputIsEditedInPlace) +{ + auto filter = make_filter(); + filter->update(nav_state_); + const auto first = nav_state_.get_ptr<::navmap::NavMap>("map.navmap.lod"); + cost_at(1.05f, 1.05f, 200); + filter->update(nav_state_); + EXPECT_EQ(nav_state_.get_ptr<::navmap::NavMap>("map.navmap.lod").get(), first.get()); +} + +TEST_F(NavmapFractalFilterTest, OutsideTheWindowOnlyTheSweepSeesChanges) +{ + // Window of 1 m around (0.5, 0.5), no sweep: a cost 5 m away is not read + auto filter = make_filter({{"navmap.fractal.window_radius", 1.0}, {"navmap.fractal.sweep", 0}}); + filter->update(nav_state_); + const auto merged = live_navcels(); + cost_at(5.55f, 5.55f, 200); + filter->update(nav_state_); + EXPECT_EQ(live_navcels(), merged); + + // The robot gets there: now it is + robot_at(5.5, 5.5); + filter->update(nav_state_); + EXPECT_GT(live_navcels(), merged); +} + +TEST_F(NavmapFractalFilterTest, TheSweepReadsTheWholeMapInTurns) +{ + auto filter = make_filter( + {{"navmap.fractal.window_radius", 1.0}, {"navmap.fractal.sweep", 1000}}); + filter->update(nav_state_); + const auto merged = live_navcels(); + cost_at(5.55f, 5.55f, 200); + // 8192 source NavCels at 1000 per cycle: read within 9 cycles + for (int i = 0; i < 9; ++i) { + filter->update(nav_state_); + } + EXPECT_GT(live_navcels(), merged); +} + +TEST_F(NavmapFractalFilterTest, TheOutputCannotBeTheSourceMap) +{ + auto node = std::make_shared( + "fractal_filter_bad_key_node", + rclcpp::NodeOptions().parameter_overrides({{"navmap.fractal.output_key", "map.navmap"}})); + easynav::navmap::FractalFilter filter; + EXPECT_THROW(filter.initialize(node, "navmap.fractal"), std::invalid_argument); +} + +TEST_F(NavmapFractalFilterTest, ANewSourceMapRebuildsTheTree) +{ + auto filter = make_filter(); + filter->update(nav_state_); + ASSERT_TRUE(nav_state_.has("map.navmap.lod")); + + // A smaller map (e.g. loaded by the user) replaces the source + nav_msgs::msg::OccupancyGrid grid; + grid.header.frame_id = "map"; + grid.info.resolution = 0.1; + grid.info.width = 16; + grid.info.height = 16; + grid.info.origin.orientation.w = 1.0; + grid.data.assign(16 * 16, 0); + auto nm = navmap_ros::from_occupancy_grid(grid); + for (std::size_t c = 0; c < nm.navcels.size(); ++c) { + nm.layer_set(kLayer, static_cast<::navmap::NavCelId>(c), 0); + } + nav_state_.set("map.navmap", nm); + filter->update(nav_state_); + const auto & out = nav_state_.get<::navmap::NavMap>("map.navmap.lod"); + ASSERT_FALSE(out.positions.x.empty()); + float max_x = 0.0f; + for (float x : out.positions.x) { + max_x = std::max(max_x, x); + } + EXPECT_NEAR(max_x, 1.6f, 1e-3) << "the output covers the new map only"; +} + +// ─── Publication: the whole map once, then patches ─────────────────────────────────────────── + +class NavmapFractalPublishTest : public NavmapFractalFilterTest +{ +protected: + using MapMsg = navmap_ros_interfaces::msg::NavMap; + using PatchMsg = navmap_ros_interfaces::msg::NavMapPatch; + + void subscribe(const std::string & name) + { + listener_ = std::make_shared(name); + const std::string topic = "/fractal_filter_test_node/navmap/fractal/map"; + map_sub_ = listener_->create_subscription( + topic, rclcpp::QoS(1).transient_local().reliable(), + [this](MapMsg::ConstSharedPtr m) {kept_ = *m; ++maps_;}); + patch_sub_ = listener_->create_subscription( + topic + "_patch", rclcpp::QoS(10).reliable(), + [this](PatchMsg::ConstSharedPtr p) { + ++patches_; + applied_ += navmap_ros::apply_patch(*p, kept_) ? 1 : 0; + }); + } + + // One update of the filter, then what arrives + void cycle(easynav::navmap::FractalFilter & filter) + { + filter.update(nav_state_); + rclcpp::executors::SingleThreadedExecutor exec; + exec.add_node(listener_); + for (int i = 0; i < 20; ++i) { + exec.spin_some(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + } + + // Until the filter's publishers see the listener + void wait_matched(easynav::navmap::FractalFilter & filter) + { + (void)filter; + for (int i = 0; i < 200; ++i) { + if (node_->count_subscribers("/fractal_filter_test_node/navmap/fractal/map") > 0 && + node_->count_subscribers("/fractal_filter_test_node/navmap/fractal/map_patch") > 0) + { + return; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + + rclcpp::Node::SharedPtr listener_; + rclcpp::Subscription::SharedPtr map_sub_; + rclcpp::Subscription::SharedPtr patch_sub_; + MapMsg kept_; + int maps_{0}, patches_{0}, applied_{0}; +}; + +TEST_F(NavmapFractalPublishTest, AMapThenPatchesThatKeepTheCopyExact) +{ + auto filter = make_filter( + {{"navmap.fractal.publish_period", 0.0}, {"navmap.fractal.full_period", 0.0}, + {"navmap.fractal.tile_size", 1.0}}); + subscribe("fractal_listener_a"); + wait_matched(*filter); + cycle(*filter); + ASSERT_EQ(maps_, 1) << "the whole map first"; + EXPECT_EQ(patches_, 0); + + const float spots[][2] = {{1.05f, 1.05f}, {0.35f, 0.75f}, {1.45f, 0.25f}, {0.85f, 1.35f}}; + int k = 0; + for (const auto & xy : spots) { + cost_at(xy[0], xy[1], static_cast(50 + 40 * k++)); + cycle(*filter); + } + cost_at(1.05f, 1.05f, 0); + cycle(*filter); + + EXPECT_EQ(maps_, 1) << "no whole map again"; + EXPECT_GE(patches_, 4); + EXPECT_EQ(applied_, patches_) << "every patch fitted the copy"; + const auto full = navmap_ros::to_msg(nav_state_.get<::navmap::NavMap>("map.navmap.lod")); + EXPECT_EQ(kept_.geometry_id, full.geometry_id); + EXPECT_EQ(kept_.navcels_v0, full.navcels_v0); + EXPECT_EQ(kept_.navcels_v1, full.navcels_v1); + EXPECT_EQ(kept_.navcels_v2, full.navcels_v2); + EXPECT_EQ(kept_.positions_x, full.positions_x); + ASSERT_EQ(kept_.layers.size(), full.layers.size()); + for (std::size_t i = 0; i < full.layers.size(); ++i) { + EXPECT_EQ(kept_.layers[i].data_u8, full.layers[i].data_u8) << full.layers[i].name; + } +} + +TEST_F(NavmapFractalPublishTest, NothingChangedNothingSent) +{ + auto filter = make_filter({{"navmap.fractal.publish_period", 0.0}}); + subscribe("fractal_listener_b"); + wait_matched(*filter); + cycle(*filter); + ASSERT_EQ(maps_, 1); + for (int i = 0; i < 5; ++i) { + cycle(*filter); + } + EXPECT_EQ(maps_, 1); + EXPECT_EQ(patches_, 0); +} + +TEST_F(NavmapFractalPublishTest, ANewSubscriberGetsTheWholeMap) +{ + auto filter = make_filter({{"navmap.fractal.publish_period", 0.0}}); + subscribe("fractal_listener_c"); + wait_matched(*filter); + cycle(*filter); + ASSERT_EQ(maps_, 1); + + // A second receiver joins: everyone gets the whole map, so it has a base for the patches + auto other = std::make_shared("fractal_listener_d"); + int other_maps = 0; + auto sub = other->create_subscription( + "/fractal_filter_test_node/navmap/fractal/map_patch", rclcpp::QoS(10).reliable(), + [](PatchMsg::ConstSharedPtr) {}); + auto sub2 = other->create_subscription( + "/fractal_filter_test_node/navmap/fractal/map", rclcpp::QoS(1).transient_local().reliable(), + [&other_maps](MapMsg::ConstSharedPtr) {++other_maps;}); + for (int i = 0; i < 200 && + node_->count_subscribers("/fractal_filter_test_node/navmap/fractal/map") < 2; ++i) + { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + cycle(*filter); + rclcpp::executors::SingleThreadedExecutor exec; + exec.add_node(other); + for (int i = 0; i < 20; ++i) { + exec.spin_some(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + EXPECT_EQ(maps_, 2); + EXPECT_GE(other_maps, 1); +} diff --git a/maps_managers/easynav_navmap_maps_manager/tests/navmap_fractal_rtin_tests.cpp b/maps_managers/easynav_navmap_maps_manager/tests/navmap_fractal_rtin_tests.cpp new file mode 100644 index 00000000..ef00dd84 --- /dev/null +++ b/maps_managers/easynav_navmap_maps_manager/tests/navmap_fractal_rtin_tests.cpp @@ -0,0 +1,907 @@ +// Copyright 2026 Intelligent Robotics Lab +// +// This file is part of the project Easy Navigation (EasyNav in short) +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "easynav_navmap_maps_manager/filters/rtin_lod.hpp" +#include "navmap_core/NavMap.hpp" +#include "navmap_ros/conversions.hpp" + +using easynav::navmap::RtinLod; +using LayerU8 = navmap::LayerView; + +namespace +{ + +constexpr double kRes = 0.4; +constexpr double kOx = -3.0, kOy = 2.0; // not at the origin, on purpose + +// A grid NavMap like pointcloud_to_navmap's: two right triangles per cell. +struct Grid +{ + int nx{4}, ny{4}; + // diagonal of cell (i, j): true = main ((0,0)-(1,1)) + std::function main_diag = [](int, int) {return true;}; + // which halves exist (half 0: right angle in the lower row of the cell) + std::function exists = [](int, int, int) {return true;}; + std::function z = [](int, int) {return 0.0f;}; + std::function value = [](int, int, int) {return 0;}; +}; + +// half h of cell (i, j): its three corners (cell units), right angle first +std::vector> half_corners(bool main, int h) +{ + if (main) { // right angles at (1,0) and (0,1) + return h == 0 ? std::vector>{{1, 0}, {1, 1}, {0, 0}} : + std::vector>{{0, 1}, {0, 0}, {1, 1}}; + } + return h == 0 ? std::vector>{{0, 0}, {1, 0}, {0, 1}} : // anti: (0,0), (1,1) + std::vector>{{1, 1}, {0, 1}, {1, 0}}; +} + +struct Built +{ + navmap::NavMap map; + std::map, navmap::NavCelId> cid; // (i, j, h) -> NavCel +}; + +Built make_map(const Grid & g) +{ + Built b; + auto & m = b.map; + m.create_surface("map"); + std::map, std::uint32_t> vid; + auto vertex = [&](int x, int y) { + auto it = vid.find({x, y}); + if (it != vid.end()) {return it->second;} + const auto id = m.add_vertex( + Eigen::Vector3f( + static_cast(kOx + x * kRes), static_cast(kOy + y * kRes), g.z(x, y))); + vid[{x, y}] = id; + return id; + }; + std::vector vals; + for (int j = 0; j < g.ny; ++j) { + for (int i = 0; i < g.nx; ++i) { + for (int h = 0; h < 2; ++h) { + if (!g.exists(i, j, h)) {continue;} + const auto c = half_corners(g.main_diag(i, j), h); + const auto id = m.add_navcel( + vertex(i + c[0].first, j + c[0].second), vertex(i + c[1].first, j + c[1].second), + vertex(i + c[2].first, j + c[2].second)); + m.add_navcel_to_surface(0, id); + b.cid[{i, j, h}] = id; + vals.push_back(g.value(i, j, h)); + } + } + } + auto l = m.add_layer("cost", "", "", 0); + l->data() = vals; + m.rebuild_geometry_accels(); + return b; +} + +void set_value(Built & b, int i, int j, int h, std::uint8_t v) +{ + auto l = std::dynamic_pointer_cast(b.map.layers.get("cost")); + l->data()[b.cid.at({i, j, h})] = v; +} + +// Grid coordinates of an output vertex +std::pair gxy(const navmap::NavMap & m, std::uint32_t v) +{ + const auto p = m.positions.at(v); + return {static_cast(std::lround((p.x() - kOx) / kRes)), + static_cast(std::lround((p.y() - kOy) / kRes))}; +} + +double area2(const navmap::NavMap & m, const navmap::NavCel & c) +{ + const auto a = gxy(m, c.v[0]), b = gxy(m, c.v[1]), d = gxy(m, c.v[2]); + return static_cast((b.first - a.first) * (d.second - a.second) - + (b.second - a.second) * (d.first - a.first)); +} + +bool inside(const navmap::NavMap & m, const navmap::NavCel & c, double x, double y) +{ + if (area2(m, c) == 0.0) {return false;} // a dead NavCel holds nothing + double s[3]; + for (int e = 0; e < 3; ++e) { + const auto a = gxy(m, c.v[e]), b = gxy(m, c.v[(e + 1) % 3]); + s[e] = (b.first - a.first) * (y - a.second) - (b.second - a.second) * (x - a.first); + } + return (s[0] >= 0 && s[1] >= 0 && s[2] >= 0) || (s[0] <= 0 && s[1] <= 0 && s[2] <= 0); +} + +// The live NavCels of extract()'s map (the dead ones are degenerate, all on vertex 0) +bool live(const navmap::NavCel & c) {return !(c.v[0] == c.v[1] && c.v[1] == c.v[2]);} + +template +navmap::NavMap ex(L && lod, RtinLod::Stats * st = nullptr) +{ + return *lod.extract(st); +} + +// Every check that does not depend on the scenario +void check_invariants(const Built & src, const navmap::NavMap & out, const Grid & g) +{ + const auto lv = std::dynamic_pointer_cast(out.layers.get("cost")); + const auto ll = std::dynamic_pointer_cast(out.layers.get("lod_level")); + const auto lm = std::dynamic_pointer_cast(out.layers.get("modified")); + ASSERT_TRUE(lv && ll && lm); + ASSERT_EQ(lv->size(), out.navcels.size()); + + // the vertices of the live NavCels (the map keeps those of NavCels gone: they are unused) + std::set> verts; + for (const auto & c : out.navcels) { + if (!live(c)) {continue;} + for (int e = 0; e < 3; ++e) { + verts.insert(gxy(out, c.v[e])); + } + } + + // Counter-clockwise, no T-junction: no vertex strictly inside an edge + std::map, std::pair>, int> edges; + std::size_t nlive = 0; + for (const auto & c : out.navcels) { + if (!live(c)) { + for (int e = 0; e < 3; ++e) { + EXPECT_EQ(c.neighbor[e], navmap::NavCel{}.neighbor[e]); + } + continue; + } + ++nlive; + EXPECT_GT(area2(out, c), 0.0); + for (int e = 0; e < 3; ++e) { + auto a = gxy(out, c.v[e]), b = gxy(out, c.v[(e + 1) % 3]); + const int dx = b.first - a.first, dy = b.second - a.second; + const int steps = std::gcd(std::abs(dx), std::abs(dy)); + for (int s = 1; s < steps; ++s) { + EXPECT_FALSE(verts.count({a.first + dx / steps * s, a.second + dy / steps * s})) + << "T-junction on edge (" << a.first << "," << a.second << ")-(" << b.first << "," << + b.second << ")"; + } + if (b < a) {std::swap(a, b);} + ++edges[{a, b}]; + } + } + for (const auto & [e, n] : edges) { + EXPECT_LE(n, 2); + } + EXPECT_LE(out.navcels.size() - nlive, std::max(nlive, 65536)); // dead ones + // a live NavCel's neighbours are live + for (const auto & c : out.navcels) { + if (!live(c)) {continue;} + for (int e = 0; e < 3; ++e) { + if (c.neighbor[e] != navmap::NavCel{}.neighbor[e]) { + EXPECT_TRUE(live(out.navcels[c.neighbor[e]])); + } + } + } + + // Every covered source half lies in exactly one output NavCel, whose value is at least its own + // (merged NavCels: exactly its own); output area = covered area + double covered = 0.0, out_area = 0.0; + for (const auto & c : out.navcels) { + if (live(c)) { + out_area += area2(out, c) / 2.0; + } + } + for (int j = 0; j < g.ny; ++j) { + for (int i = 0; i < g.nx; ++i) { + for (int h = 0; h < 2; ++h) { + if (!g.exists(i, j, h)) {continue;} + const auto c = half_corners(g.main_diag(i, j), h); + // a point strictly inside the half, off the grid lines and off every diagonal + // (x +- y never an integer): the centroid would lie on the edges of merged NavCels + const double x = i + c[0].first + 0.25 * (c[1].first - c[0].first) + + 0.2 * (c[2].first - c[0].first); + const double y = j + c[0].second + 0.25 * (c[1].second - c[0].second) + + 0.2 * (c[2].second - c[0].second); + int found = -1, count = 0; + for (std::size_t k = 0; k < out.navcels.size(); ++k) { + if (live(out.navcels[k]) && inside(out, out.navcels[k], x, y)) { + found = static_cast(k); + ++count; + } + } + if (g.exists(i, j, 0) && g.exists(i, j, 1)) { + EXPECT_EQ(count, 1) << "cell " << i << "," << j << " half " << h << " not covered"; + } + if (count == 0) {continue;} // a half of a cell split by the other diagonal, alone + covered += 0.5; + EXPECT_EQ(count, 1); + const auto v = g.value(i, j, h); + EXPECT_GE(lv->data()[found], v); + if (ll->data()[found] > 0) { + // merged: its own value, or (finest NavCel on the other diagonal) the highest of the + // two halves of its cell + const auto other = g.exists(i, j, 1 - h) ? std::max(v, g.value(i, j, 1 - h)) : v; + EXPECT_TRUE(lv->data()[found] == v || lv->data()[found] == other) + << "cell " << i << "," << j << ": " << int(lv->data()[found]) << " over " << int(v); + } + EXPECT_EQ(lm->data()[found], ll->data()[found] > 0 ? 1 : 0); + } + } + } + // the source halves whose centroids are covered fill the output, up to the halves that lose + // their cell mate when the tree uses the other diagonal + EXPECT_LE(out_area, covered + 1e-9); + (void)src; +} + +using Key = std::vector, std::pair, std::pair, + int, int>>; + +Key canon(const navmap::NavMap & out) +{ + const auto lv = std::dynamic_pointer_cast(out.layers.get("cost")); + const auto ll = std::dynamic_pointer_cast(out.layers.get("lod_level")); + Key k; + for (std::size_t i = 0; i < out.navcels.size(); ++i) { + if (!live(out.navcels[i])) {continue;} + std::vector> v; + for (int e = 0; e < 3; ++e) { + v.push_back(gxy(out, out.navcels[i].v[e])); + } + std::sort(v.begin(), v.end()); + k.emplace_back(v[0], v[1], v[2], lv->data()[i], ll->data()[i]); + } + std::sort(k.begin(), k.end()); + return k; +} + +RtinLod built(const Built & b, float tol = 0.05f, float angle = 5.0f, float tile = 50.0f) +{ + RtinLod lod; + std::string err; + RtinLod::Params p; + p.height_tolerance = tol; + p.max_angle_deg = angle; + p.tile_size = tile; + EXPECT_TRUE(lod.build(b.map, "cost", p, &err)) << err; + return lod; +} + +// largest angle (deg) between an output NavCel and the source halves under it +double worst_angle_under(const navmap::NavMap & out, const Built & src, const Grid & g) +{ + double worst = 0.0; + for (const auto & [key, cid] : src.cid) { + const auto [i, j, h] = key; + const auto c = half_corners(g.main_diag(i, j), h); + const double x = i + c[0].first + 0.25 * (c[1].first - c[0].first) + + 0.2 * (c[2].first - c[0].first); + const double y = j + c[0].second + 0.25 * (c[1].second - c[0].second) + + 0.2 * (c[2].second - c[0].second); + for (const auto & oc : out.navcels) { + if (!inside(out, oc, x, y)) {continue;} + const double d = std::clamp( + static_cast(oc.normal.dot(src.map.navcels[cid].normal)), -1.0, 1.0); + worst = std::max(worst, std::acos(std::abs(d)) * 180.0 / M_PI); + } + } + return worst; +} + +} // namespace + +TEST(RtinLod, UniformSquareMergesIntoTwoTriangles) +{ + Grid g; + g.nx = g.ny = 8; + auto b = make_map(g); + auto lod = built(b); + RtinLod::Stats st; + auto out = ex(lod, &st); + EXPECT_EQ(st.triangles, 2u); + EXPECT_EQ(st.finest, 0u); + EXPECT_EQ(st.max_level, 6); // 8x8 cells: 128 halves -> 2: 6 merges + check_invariants(b, out, g); +} + +TEST(RtinLod, OneCellMapIsKept) +{ + Grid g; + g.nx = g.ny = 1; + auto b = make_map(g); + auto lod = built(b); + RtinLod::Stats st; + auto out = ex(lod, &st); + EXPECT_EQ(st.triangles, 2u); + EXPECT_EQ(st.finest, 2u); + check_invariants(b, out, g); +} + +TEST(RtinLod, NonPowerOfTwoRectangle) +{ + Grid g; + g.nx = 7; + g.ny = 3; + auto b = make_map(g); + auto lod = built(b); + RtinLod::Stats st; + auto out = ex(lod, &st); + check_invariants(b, out, g); + double a = 0.0; + for (const auto & c : out.navcels) { + a += area2(out, c) / 2.0; + } + EXPECT_DOUBLE_EQ(a, 21.0); // every cell covered (main diagonal everywhere, as the tree's + // diagonal or both halves present) + EXPECT_LT(st.triangles, 42u); +} + +TEST(RtinLod, ObstacleKeepsFullResolutionOnlyAroundIt) +{ + Grid g; + g.nx = g.ny = 32; + g.value = [](int i, int j, int) {return (i == 10 && j == 20) ? 254 : 0;}; + auto b = make_map(g); + auto lod = built(b); + RtinLod::Stats st; + auto out = ex(lod, &st); + check_invariants(b, out, g); + EXPECT_GE(st.finest, 2u); + EXPECT_LT(st.triangles, 120u); // a few dozen: the obstacle, the forced splits around it +} + +TEST(RtinLod, SplitThenMergeBackSequence) +{ + Grid g; + g.nx = g.ny = 16; + auto b = make_map(g); + auto lod = built(b); + const auto initial = canon(ex(lod)); + ASSERT_EQ(initial.size(), 2u); + + EXPECT_EQ(lod.update(b.map), 0u); // nothing changed + + set_value(b, 5, 9, 0, 120); + g.value = [](int i, int j, int h) {return (i == 5 && j == 9 && h == 0) ? 120 : 0;}; + EXPECT_EQ(lod.update(b.map), 1u); + RtinLod::Stats st; + auto out = ex(lod, &st); + check_invariants(b, out, g); + EXPECT_GT(st.triangles, 2u); + EXPECT_GE(st.finest, 1u); + + // a value change that keeps the obstacle: the mesh is the same, the value follows + set_value(b, 5, 9, 0, 200); + g.value = [](int i, int j, int h) {return (i == 5 && j == 9 && h == 0) ? 200 : 0;}; + EXPECT_EQ(lod.update(b.map), 1u); + out = ex(lod); + check_invariants(b, out, g); + + // gone: merged back to the two roots + set_value(b, 5, 9, 0, 0); + g.value = [](int, int, int) {return 0;}; + EXPECT_EQ(lod.update(b.map), 1u); + EXPECT_EQ(canon(ex(lod)), initial); +} + +TEST(RtinLod, HolesAreNeverCovered) +{ + Grid g; + g.nx = g.ny = 16; + g.exists = [](int i, int j, int) {return !(i >= 4 && i < 7 && j >= 4 && j < 6);}; + auto b = make_map(g); + auto lod = built(b); + auto out = ex(lod); + check_invariants(b, out, g); + for (const auto & c : out.navcels) { + for (int i = 4; i < 7; ++i) { + for (int j = 4; j < 6; ++j) { + EXPECT_FALSE(inside(out, c, i + 0.5, j + 0.5)) << "cell " << i << "," << j; + } + } + } +} + +TEST(RtinLod, LoneHalfAcrossTheTreeDiagonalIsDropped) +{ + // anti diagonals and one half missing: where the tree uses the main diagonal, the remaining + // half cannot be a full leaf and is not covered (never a NavCel over a hole) + Grid g; + g.nx = g.ny = 4; + g.main_diag = [](int, int) {return false;}; + g.exists = [](int i, int j, int h) {return !(i == 1 && j == 1 && h == 1);}; + auto b = make_map(g); + auto lod = built(b); + auto out = ex(lod); + check_invariants(b, out, g); + for (const auto & c : out.navcels) { + EXPECT_FALSE(inside(out, c, 1.75, 1.75)); // inside the missing half (corner (1,1)) + } +} + +TEST(RtinLod, OtherDiagonalTakesTheHighestOfTheTwoHalves) +{ + Grid g; + g.nx = g.ny = 2; + g.main_diag = [](int, int) {return false;}; // the tree alternates: some cells differ + g.value = [](int i, int j, int h) {return (i == 0 && j == 0 && h == 1) ? 77 : 0;}; + auto b = make_map(g); + auto lod = built(b); + auto out = ex(lod); + check_invariants(b, out, g); + // cell (0,0) is fully covered; whatever covers its half 0 has at least 0, and its half 1 + // at least 77 (checked in the invariants); a NavCel over both halves has 77 + const auto lv = std::dynamic_pointer_cast(out.layers.get("cost")); + for (std::size_t k = 0; k < out.navcels.size(); ++k) { + if (inside(out, out.navcels[k], 0.2, 0.2) && inside(out, out.navcels[k], 0.8, 0.8)) { + EXPECT_EQ(lv->data()[k], 77); + } + } +} + +TEST(RtinLod, PlanarRampMergesWhateverItsHeight) +{ + Grid g; + g.nx = g.ny = 16; + g.z = [](int x, int y) {return 0.1f * x + 0.05f * y;}; // ~15 deg, 2.4 m of rise + auto b = make_map(g); + auto lod = built(b, 0.01f, 0.5f); + RtinLod::Stats st; + auto out = ex(lod, &st); + check_invariants(b, out, g); + EXPECT_EQ(st.triangles, 2u); + EXPECT_LT(worst_angle_under(out, b, g), 0.1); // float32 positions: hundredths of a degree +} + +TEST(RtinLod, CreaseBetweenSlopesIsKept) +{ + // a ridge along x = 8: slopes of +-5.7 deg (11.4 between them) + Grid g; + g.nx = g.ny = 16; + g.z = [](int x, int) {return 0.04f * std::abs(x - 8);}; + auto b = make_map(g); + { + auto lod = built(b, 1.0f, 5.0f); // the deviation does not limit: only the angle + auto out = ex(lod); + check_invariants(b, out, g); + EXPECT_LE(worst_angle_under(out, b, g), 5.0 + 1e-3); + for (const auto & c : out.navcels) { // no NavCel crosses the ridge + int lo = 1 << 30, hi = -(1 << 30); + for (int e = 0; e < 3; ++e) { + lo = std::min(lo, gxy(out, c.v[e]).first); + hi = std::max(hi, gxy(out, c.v[e]).first); + } + EXPECT_FALSE(lo < 8 && hi > 8); + } + } + { + auto lod = built(b, 1.0f, 15.0f); // the ridge angle is allowed: merged across it + RtinLod::Stats st; + auto out = ex(lod, &st); + check_invariants(b, out, g); + EXPECT_LE(worst_angle_under(out, b, g), 15.0 + 1e-3); + EXPECT_LT(st.triangles, 20u); + } +} + +TEST(RtinLod, CurvedGroundIsBoundedByTheDeviation) +{ + // a gentle bowl: every cell within a fraction of a degree of its neighbours + Grid g; + g.nx = g.ny = 32; + g.z = [](int x, int y) {return 0.002f * ((x - 16) * (x - 16) + (y - 16) * (y - 16));}; + auto b = make_map(g); + for (const float tol : {0.01f, 0.1f}) { + auto lod = built(b, tol, 45.0f); // only the deviation limits + auto out = ex(lod); + check_invariants(b, out, g); + // every source vertex within tol of the plane of the output NavCel over it + for (const auto & c : out.navcels) { + const Eigen::Vector3f p0 = out.positions.at(c.v[0]); + for (int x = 0; x <= g.nx; ++x) { + for (int y = 0; y <= g.ny; ++y) { + if (!inside(out, c, x, y)) {continue;} + const Eigen::Vector3f q( + static_cast(kOx + x * kRes), static_cast(kOy + y * kRes), g.z(x, y)); + EXPECT_LE(std::abs(c.normal.dot(q - p0)), tol + 1e-4f); + } + } + } + } + RtinLod::Stats fine, coarse; + ex(built(b, 0.01f, 45.0f), &fine); + ex(built(b, 0.1f, 45.0f), &coarse); + EXPECT_GT(fine.triangles, coarse.triangles); +} + +TEST(RtinLod, ZeroThresholdsStillMergeFlatGround) +{ + Grid g; + g.nx = g.ny = 8; + auto b = make_map(g); + RtinLod::Stats st; + ex(built(b, 0.0f, 0.0f), &st); + EXPECT_EQ(st.triangles, 2u); +} + +TEST(RtinLod, ExtremeValues) +{ + Grid g; + g.nx = g.ny = 8; + g.value = [](int i, int, int) {return i < 4 ? 255 : 254;}; + auto b = make_map(g); + auto lod = built(b); + RtinLod::Stats st; + auto out = ex(lod, &st); + check_invariants(b, out, g); + EXPECT_LT(st.triangles, 64u); // two uniform halves of the square, merged +} + +TEST(RtinLod, IncrementalEqualsRebuildOverRandomSequences) +{ + std::mt19937 rng(42); + const float tiles[] = {0.6f, 1.5f, 100.0f, 3.0f}; // m: many tiles ... one + for (int trial = 0; trial < 4; ++trial) { + const float tile = tiles[trial]; + Grid g; + g.nx = 20 + trial * 3; + g.ny = 13 + trial; + std::uniform_int_distribution coin(0, 9); + std::vector diag(g.nx * g.ny), hole(g.nx * g.ny); + for (auto & d : diag) { + d = coin(rng) < 7; + } + for (auto & h : hole) { + h = coin(rng) == 0; + } + const int nx = g.nx; + g.main_diag = [diag, nx](int i, int j) {return diag[j * nx + i] != 0;}; + g.exists = [hole, nx](int i, int j, int) {return hole[j * nx + i] == 0;}; + std::vector vals(2 * g.nx * g.ny, 0); + g.value = [&vals, nx](int i, int j, int h) {return vals[2 * (j * nx + i) + h];}; + auto b = make_map(g); + auto lod = built(b, 0.05f, 5.0f, tile); + + std::uniform_int_distribution ci(0, g.nx - 1), cj(0, g.ny - 1), ch(0, 1); + const std::uint8_t palette[] = {0, 0, 0, 50, 128, 253, 254, 255}; + std::uniform_int_distribution pv(0, 7), burst(1, 12); + for (int step = 0; step < 25; ++step) { + const int n = burst(rng); + for (int k = 0; k < n; ++k) { + const int i = ci(rng), j = cj(rng), h = ch(rng); + if (!g.exists(i, j, h)) {continue;} + const std::uint8_t v = palette[pv(rng)]; + vals[2 * (j * nx + i) + h] = v; + set_value(b, i, j, h, v); + } + lod.update(b.map); + const auto inc = ex(lod); + auto fresh = built(b, 0.05f, 5.0f, tile); + ASSERT_EQ(canon(inc), canon(ex(fresh))) << "trial " << trial << " step " << step; + check_invariants(b, inc, g); + } + } +} + +TEST(RtinLod, WindowNowSweepLater) +{ + Grid g; + g.nx = g.ny = 32; + std::vector vals(2 * 32 * 32, 0); + g.value = [&vals](int i, int j, int h) {return vals[2 * (j * 32 + i) + h];}; + auto b = make_map(g); + auto lod = built(b); + const auto initial = canon(ex(lod)); + + // one change near the robot (cell 3,3) and one far (cell 28,28) + vals[2 * (3 * 32 + 3)] = 90; + set_value(b, 3, 3, 0, 90); + vals[2 * (28 * 32 + 28)] = 90; + set_value(b, 28, 28, 0, 90); + const double rx = kOx + 3.5 * kRes, ry = kOy + 3.5 * kRes; + + // no sweep: only the near one + EXPECT_EQ(lod.update_window(b.map, rx, ry, 1.0, 0), 1u); + auto out = ex(lod); + const auto lv = std::dynamic_pointer_cast(out.layers.get("cost")); + for (std::size_t k = 0; k < out.navcels.size(); ++k) { + if (inside(out, out.navcels[k], 28.75, 28.25)) {EXPECT_EQ(lv->data()[k], 0);} + } + // the same window again: nothing new + EXPECT_EQ(lod.update_window(b.map, rx, ry, 1.0, 0), 0u); + // a window outside the map does not fail + EXPECT_EQ(lod.update_window(b.map, -1e6, -1e6, 5.0, 0), 0u); + + // the sweep reaches the far one within source_navcels() / sweep calls + const std::size_t sweep = 100; + std::size_t total = 0; + for (std::size_t c = 0; c <= lod.source_navcels() / sweep; ++c) { + total += lod.update_window(b.map, rx, ry, 1.0, sweep); + } + EXPECT_EQ(total, 1u); + check_invariants(b, ex(lod), g); + auto fresh = built(b); + EXPECT_EQ(canon(ex(lod)), canon(ex(fresh))); + + // both back to 0, seen through windows: the initial mesh again + vals[2 * (3 * 32 + 3)] = 0; + set_value(b, 3, 3, 0, 0); + vals[2 * (28 * 32 + 28)] = 0; + set_value(b, 28, 28, 0, 0); + EXPECT_EQ(lod.update_window(b.map, rx, ry, 1.0, 0), 1u); + EXPECT_EQ(lod.update_window(b.map, kOx + 28.5 * kRes, kOy + 28.5 * kRes, 1.0, 0), 1u); + EXPECT_EQ(canon(ex(lod)), initial); +} + +TEST(RtinLod, NeighboursAndBvhMatchTheGenericBuilders) +{ + std::mt19937 rng(7); + const float tiles[] = {0.6f, 2.0f, 100.0f}; + for (int trial = 0; trial < 3; ++trial) { + Grid g; + g.nx = 24 + 5 * trial; + g.ny = 17; + std::uniform_int_distribution coin(0, 9); + std::vector diag(g.nx * g.ny), hole(g.nx * g.ny); + std::vector vals(2 * g.nx * g.ny); + for (auto & d : diag) { + d = coin(rng) < 6; + } + for (auto & h : hole) { + h = coin(rng) == 0; + } + for (auto & v : vals) { + v = coin(rng) < 8 ? 0 : 100; + } + const int nx = g.nx; + g.main_diag = [diag, nx](int i, int j) {return diag[j * nx + i] != 0;}; + g.exists = [hole, nx](int i, int j, int) {return hole[j * nx + i] == 0;}; + g.value = [vals, nx](int i, int j, int h) {return vals[2 * (j * nx + i) + h];}; + auto b = make_map(g); + auto lod = built(b, 0.05f, 5.0f, tiles[trial]); + for (int round = 0; round < 2; ++round) { // the second one from the tiles' cache + auto out = ex(lod); + navmap::NavMap ref = out; + ref.rebuild_geometry_accels(); + ASSERT_EQ(ref.navcels.size(), out.navcels.size()); + for (std::size_t c = 0; c < out.navcels.size(); ++c) { + if (!live(out.navcels[c])) {continue;} + for (int e = 0; e < 3; ++e) { + EXPECT_EQ(out.navcels[c].neighbor[e], ref.navcels[c].neighbor[e]) << c << " " << e; + } + EXPECT_NEAR(out.navcels[c].area, ref.navcels[c].area, 1e-5); + } + ASSERT_TRUE(std::any_of(out.surfaces.begin(), out.surfaces.end(), + [](const auto & s) {return !s.bvh.empty();})); + std::uniform_real_distribution ux(-0.5, g.nx + 0.5), uy(-0.5, g.ny + 0.5); + for (int q = 0; q < 300; ++q) { + const Eigen::Vector3f p( + static_cast(kOx + ux(rng) * kRes), static_cast(kOy + uy(rng) * kRes), + 0.5f); + std::size_t s1 = 0, s2 = 0; + navmap::NavCelId c1 = 0, c2 = 0; + Eigen::Vector3f b1, b2, h1, h2; + const bool f1 = out.locate_navcel(p, s1, c1, b1, &h1); + const bool f2 = ref.locate_navcel(p, s2, c2, b2, &h2); + ASSERT_EQ(f1, f2); + if (f1) { + EXPECT_TRUE(inside(out, out.navcels[c1], (p.x() - kOx) / kRes, + (p.y() - kOy) / kRes)); + } + if (f1) { + EXPECT_TRUE(inside(ref, ref.navcels[c2], (p.x() - kOx) / kRes, + (p.y() - kOy) / kRes)); + } + } + } + } +} + +TEST(RtinLod, OnlyTheChangedTilesAreWalkedAgain) +{ + Grid g; + g.nx = g.ny = 64; // 25.6 m + std::vector vals(2 * 64 * 64, 0); + for (int j = 0; j < 64; j += 7) { // some structure: rows of obstacles + for (int i = 0; i < 64; ++i) { + vals[2 * (j * 64 + i)] = (i % 9) ? 200 : 0; + } + } + g.value = [&vals](int i, int j, int h) {return vals[2 * (j * 64 + i) + h];}; + auto b = make_map(g); + auto lod = built(b, 0.05f, 5.0f, 2.0f); + RtinLod::Stats st; + ex(lod, &st); + const std::size_t tiles = st.tiles; + EXPECT_GT(tiles, 50u); + EXPECT_GE(st.tiles_rebuilt, tiles); // all of them at first (and the empty ones) + + ex(lod, &st); // nothing changed: nothing walked + EXPECT_EQ(st.tiles_rebuilt, 0u); + + vals[2 * (30 * 64 + 30)] = 99; // one change in the middle of a free area + set_value(b, 30, 30, 0, 99); + ASSERT_EQ(lod.update(b.map), 1u); + auto out = ex(lod, &st); + EXPECT_GE(st.tiles_rebuilt, 1u); + EXPECT_LE(st.tiles_rebuilt, 6u); // its tile, the top, and the ones a forced split reaches + check_invariants(b, out, g); + EXPECT_EQ(canon(out), canon(ex(built(b, 0.05f, 5.0f, 2.0f)))); +} + +TEST(RtinLod, RejectsWhatItCannotHandle) +{ + RtinLod lod; + std::string err; + { + navmap::NavMap m; // no layer + Grid g; + auto b = make_map(g); + EXPECT_FALSE(lod.build(b.map, "missing", RtinLod::Params{}, &err)); + EXPECT_NE(err.find("missing"), std::string::npos); + } + { + // a NavCel off the grid + Grid g; + auto b = make_map(g); + b.map.positions.x[0] += 0.13f; + EXPECT_FALSE(lod.build(b.map, "cost", RtinLod::Params{}, &err)); + EXPECT_NE(err.find("grid"), std::string::npos); + } + { + // two floors: the same cell twice at different heights + Grid g; + g.nx = g.ny = 2; + auto b = make_map(g); + auto & m = b.map; + const auto v0 = m.add_vertex(Eigen::Vector3f(kOx + kRes, kOy, 3.0f)); + const auto v1 = m.add_vertex(Eigen::Vector3f(kOx + 2 * kRes, kOy, 3.0f)); + const auto v2 = m.add_vertex(Eigen::Vector3f(kOx + 2 * kRes, kOy + kRes, 3.0f)); + m.add_navcel_to_surface(0, m.add_navcel(v1, v2, v0)); + auto l = std::dynamic_pointer_cast(m.layers.get("cost")); + l->data().push_back(0); + EXPECT_FALSE(lod.build(m, "cost", RtinLod::Params{}, &err)); + EXPECT_NE(err.find("levels"), std::string::npos); + } + EXPECT_FALSE(lod.ready()); + EXPECT_EQ(lod.update(navmap::NavMap{}), 0u); +} + +// ─── Changes since the last take (what a receiver needs) ───────────────────────────────────── + +namespace +{ + +// What a receiver kept must equal the full conversion of the output. +void expect_same_msg( + const navmap_ros_interfaces::msg::NavMap & a, const navmap_ros_interfaces::msg::NavMap & b) +{ + EXPECT_EQ(a.geometry_id, b.geometry_id); + EXPECT_EQ(a.positions_x, b.positions_x); + EXPECT_EQ(a.positions_y, b.positions_y); + EXPECT_EQ(a.positions_z, b.positions_z); + EXPECT_EQ(a.navcels_v0, b.navcels_v0); + EXPECT_EQ(a.navcels_v1, b.navcels_v1); + EXPECT_EQ(a.navcels_v2, b.navcels_v2); + ASSERT_EQ(a.surfaces.size(), b.surfaces.size()); + for (std::size_t i = 0; i < a.surfaces.size(); ++i) { + EXPECT_EQ(a.surfaces[i].navcels, b.surfaces[i].navcels) << "surface " << i; + } + ASSERT_EQ(a.layers.size(), b.layers.size()); + for (std::size_t i = 0; i < a.layers.size(); ++i) { + EXPECT_EQ(a.layers[i].name, b.layers[i].name); + EXPECT_EQ(a.layers[i].data_u8, b.layers[i].data_u8) << a.layers[i].name; + } +} + +} // namespace + +TEST(RtinLod, TheFirstChangesAreTheWholeMap) +{ + Grid g; + g.nx = g.ny = 8; + auto b = make_map(g); + auto lod = built(b); + lod.extract(); + EXPECT_TRUE(lod.take_changes().full); + const auto again = lod.take_changes(); + EXPECT_FALSE(again.full); + EXPECT_TRUE(again.navcels.empty()) << "nothing changed since"; + EXPECT_TRUE(again.surfaces.empty()); +} + +TEST(RtinLod, PatchesFollowTheOutputExactly) +{ + // Many small tiles, random costs changing in places, sometimes growing a tile past its slack: + // after every extraction the patch brings the receiver's copy to the output, exactly. + Grid g; + g.nx = g.ny = 32; + auto b = make_map(g); + auto lod = built(b, 0.05f, 5.0f, 2.0f); + auto out = lod.extract(); + auto kept = navmap_ros::to_msg(*out); + lod.take_changes(); + std::mt19937 rng(11); + std::uniform_int_distribution cell(0, 31), half(0, 1), burst(1, 40); + int patches = 0, fulls = 0; + for (int round = 0; round < 60; ++round) { + const int n = burst(rng); + const std::uint8_t v = (round % 3 == 0) ? 0 : static_cast(10 + round); + for (int k = 0; k < n; ++k) { + set_value(b, cell(rng), cell(rng), half(rng), v); + } + lod.update(b.map); + const auto base = kept.geometry_id; + out = lod.extract(); + const auto ch = lod.take_changes(); + if (ch.full) { + kept = navmap_ros::to_msg(*out); + ++fulls; + } else { + const auto p = navmap_ros::to_patch_msg(*out, base, ch.first_vertex, ch.navcels, ch.surfaces); + ASSERT_TRUE(navmap_ros::apply_patch(p, kept)) << "round " << round; + ++patches; + EXPECT_LT(p.navcel_indices.size(), out->navcels.size()) << "a patch, not the whole map"; + } + expect_same_msg(kept, navmap_ros::to_msg(*out)); + if (HasFatalFailure()) {return;} + } + EXPECT_GT(patches, 40); +} + +TEST(RtinLod, ChangesAccumulateOverSeveralExtractions) +{ + Grid g; + g.nx = g.ny = 16; + auto b = make_map(g); + auto lod = built(b, 0.05f, 5.0f, 2.0f); + auto out = lod.extract(); + auto kept = navmap_ros::to_msg(*out); + lod.take_changes(); + const auto base = kept.geometry_id; + // Three extractions, one take: the patch carries the three + for (int k = 0; k < 3; ++k) { + set_value(b, 2 + 5 * k, 3 + 4 * k, 0, static_cast(100 + k)); + lod.update(b.map); + out = lod.extract(); + } + const auto ch = lod.take_changes(); + ASSERT_FALSE(ch.full); + ASSERT_TRUE( + navmap_ros::apply_patch( + navmap_ros::to_patch_msg(*out, base, ch.first_vertex, ch.navcels, ch.surfaces), kept)); + expect_same_msg(kept, navmap_ros::to_msg(*out)); +} + +TEST(RtinLod, ANewTreeIsAFullChange) +{ + Grid g; + g.nx = g.ny = 8; + auto b = make_map(g); + auto lod = built(b); + lod.extract(); + lod.take_changes(); + std::string err; + ASSERT_TRUE(lod.build(b.map, "cost", RtinLod::Params{}, &err)) << err; + lod.extract(); + EXPECT_TRUE(lod.take_changes().full); +} diff --git a/planners/easynav_navmap_planner/README.md b/planners/easynav_navmap_planner/README.md index d11f5c55..95e03624 100644 --- a/planners/easynav_navmap_planner/README.md +++ b/planners/easynav_navmap_planner/README.md @@ -54,6 +54,7 @@ All parameters are declared under the plugin namespace, i.e. | Name | Type | Default | Description | |---|---|---:|---| +| `.map_key` | `string` | `"map.navmap"` | NavState key of the NavMap to plan on, e.g. `map.navmap.lod`, the map of the maps manager's `fractal` filter. | | `.cost_factor` | `double` | `2.0` | Multiplicative weight for geometric distance; values > 1 increase the relative importance of distance. | | `.heuristic_weight` | `double` | `1.0` | Weighted A*: the heuristic is multiplied by this weight (values below 1 are taken as 1). `1` keeps A* admissible (shortest paths); a larger weight expands fewer NavCels and may return paths up to that factor longer (weighted A* without re-opening: each NavCel is expanded once). | | `.replan_hysteresis` | `double` | `0.0` | If above 0, the path being followed is kept while it stays traversable, unless a new one is shorter by this fraction (`0.2`: 20 %); what is left of it (from the robot, in 3D) is published. Against the oscillation of replanning on a map that changes with the robot's position (a level-of-detail map). `0`: always the new path. | @@ -86,7 +87,7 @@ This plugin does not create subscriptions or services directly; it retrieves all |---|---|---|---| | `goals` | `nav_msgs::msg::Goals` | **Read** | Target pose(s) for path planning. | | `robot_pose` | `nav_msgs::msg::Odometry` | **Read** | Current robot pose (start position). | -| `map.navmap` | `::navmap::NavMap` | **Read** | NavMap containing geometry and cost layer. The planner reads costs from the layer specified in `.layer` (default: `"inflated_obstacles"`). If that layer does not exist, it automatically falls back to `"obstacles"`. | +| `map.navmap` (`.map_key`) | `::navmap::NavMap` | **Read** | NavMap containing geometry and cost layer. The planner reads costs from the layer specified in `.layer` (default: `"inflated_obstacles"`). If that layer does not exist, it automatically falls back to `"obstacles"`. | | `path` | `nav_msgs::msg::Path` | **Write** | Output path, computed as the lowest-cost route. | ## TF Frames diff --git a/planners/easynav_navmap_planner/include/easynav_navmap_planner/AStarPlanner.hpp b/planners/easynav_navmap_planner/include/easynav_navmap_planner/AStarPlanner.hpp index 10db46b7..4f093494 100644 --- a/planners/easynav_navmap_planner/include/easynav_navmap_planner/AStarPlanner.hpp +++ b/planners/easynav_navmap_planner/include/easynav_navmap_planner/AStarPlanner.hpp @@ -84,6 +84,7 @@ class AStarPlanner : public PlannerMethodBase double cost_axial_ {1.0}; ///< Cost multiplier for axial (horizontal/vertical) moves. double cost_diagonal_ {1.0}; ///< Cost multiplier for diagonal moves. std::string layer_name_; + std::string map_key_{"map.navmap"}; ///< NavState key of the NavMap to plan on. bool continuous_replan_ {true}; ///< Whether to replan the path at control frequency. // Terrain: all off by default diff --git a/planners/easynav_navmap_planner/src/easynav_navmap_planner/AStarPlanner.cpp b/planners/easynav_navmap_planner/src/easynav_navmap_planner/AStarPlanner.cpp index c305609d..4ba59456 100644 --- a/planners/easynav_navmap_planner/src/easynav_navmap_planner/AStarPlanner.cpp +++ b/planners/easynav_navmap_planner/src/easynav_navmap_planner/AStarPlanner.cpp @@ -45,6 +45,8 @@ constexpr double kEscapeDistance = 1.0; constexpr double kMaxPathOffset = 2.0; // A point is on a surface if the surface is within this height (m) of it: floors over each other. constexpr float kSurfaceHeightTolerance = 0.5f; +// Largest step (m) between two points of the path, however large the NavCels. +constexpr double kMaxPathSpacing = 0.25; static double compute_path_length(const nav_msgs::msg::Path & path) { @@ -83,6 +85,8 @@ void AStarPlanner::on_initialize() *node, plugin_name + ".replan_hysteresis_horizon", replan_hysteresis_horizon_); node->get_parameter(plugin_name + ".cost_factor", cost_factor_); + easynav::declare_parameter_if_absent(*node, plugin_name + ".map_key", map_key_); + node->get_parameter(plugin_name + ".map_key", map_key_); // Weighted A*: the heuristic is multiplied by this weight (>= 1). 1 keeps A* admissible (optimal // paths); a larger weight expands fewer NavCels and may return paths up to that factor longer. easynav::declare_parameter_if_absent(*node, plugin_name + ".heuristic_weight", 1.0); @@ -145,17 +149,17 @@ void AStarPlanner::on_initialize() void AStarPlanner::update(NavState & nav_state) { current_path_.poses.clear(); - if (!nav_state.has("goals") || !nav_state.has("robot_pose") || !nav_state.has("map.navmap")) { + if (!nav_state.has("goals") || !nav_state.has("robot_pose") || !nav_state.has(map_key_)) { return; } const auto & goals = nav_state.get("goals"); - if (goals.goals.empty() || !nav_state.has("map.navmap")) { + if (goals.goals.empty() || !nav_state.has(map_key_)) { clear_path(nav_state); return; } - const auto & navmap = nav_state.get<::navmap::NavMap>("map.navmap"); + const auto & navmap = nav_state.get<::navmap::NavMap>(map_key_); const auto & robot_pose = nav_state.get_safe("robot_pose"); const auto & goal = goals.goals.front().pose; @@ -614,6 +618,8 @@ std::vector AStarPlanner::shortcut_path( using ::navmap::NavCelId; const std::size_t n = points.size(); if (n < 2) {return points;} + // Large NavCels (a merged map) give a large mean spacing: the path stays dense anyway + const double spacing = std::min(cel_spacing_, kMaxPathSpacing); auto vertices = [&nm](NavCelId c) { const auto & t = nm.navcels[c]; @@ -674,7 +680,7 @@ std::vector AStarPlanner::shortcut_path( allowed_slope = allowed_slope * 1.05f + 1e-3f; const Eigen::Vector3f a = points[i], b = points[j]; const double len = (b - a).head<2>().norm(); - const int steps = std::max(1, static_cast(std::ceil(len / (0.25 * cel_spacing_)))); + const int steps = std::max(1, static_cast(std::ceil(len / (0.25 * spacing)))); NavCelId cur = cels[i]; for (int s = 1; s < steps; ++s) { const Eigen::Vector3f p = a + (b - a) * (static_cast(s) / steps); @@ -728,7 +734,7 @@ std::vector AStarPlanner::shortcut_path( continue; } const double len = (b - a).head<2>().norm(); - const int steps = std::max(1, static_cast(std::round(len / cel_spacing_))); + const int steps = std::max(1, static_cast(std::ceil(len / spacing - 1e-6))); NavCelId cur = cels[kept[k - 1]]; for (int s = 1; s <= steps; ++s) { Eigen::Vector3f p = a + (b - a) * (static_cast(s) / steps); @@ -998,6 +1004,18 @@ std::vector AStarPlanner::a_star_path( for (const auto c : cels) { points.push_back(centroids_[c]); } + // Starts at the robot, not at its NavCel's centroid (off the map: from the closest NavCel) + if (okS) { + const auto & t = nm.navcels[cid_start]; + points.front() = Eigen::Vector3f( + pS.x(), pS.y(), height_at( + pS, nm.positions.at(t.v[0]), nm.positions.at(t.v[1]), nm.positions.at(t.v[2]))); + } + // The goal in the start NavCel (a large merged one): from there to the goal + if (points.size() < 2) { + points.push_back(points.back()); + cels.push_back(cels.back()); + } // Ends exactly at the goal, not at its NavCel's centroid points.back().x() = static_cast(goal.position.x); points.back().y() = static_cast(goal.position.y); diff --git a/planners/easynav_navmap_planner/tests/navmap_planner_tests.cpp b/planners/easynav_navmap_planner/tests/navmap_planner_tests.cpp index 7cdeaaf3..e4365a58 100644 --- a/planners/easynav_navmap_planner/tests/navmap_planner_tests.cpp +++ b/planners/easynav_navmap_planner/tests/navmap_planner_tests.cpp @@ -17,6 +17,7 @@ /// \brief Tests for the NavMap A* planner: a failed plan leaves an empty path, not the previous /// one. +#include #include #include #include @@ -629,6 +630,112 @@ std::vector straight(double x0, double x1, double y) } } // namespace +TEST_F(NavMapPlannerTest, AGoalInTheRobotsOwnLargeNavCelIsADensePathFromTheRobot) +{ + // 5 m cells, as a merged map gives far from obstacles: robot and goal 2 m apart, same NavCel + grid_.info.resolution = 5.0; + grid_.info.width = 4; + grid_.info.height = 4; + grid_.data.assign(16, 0); + update_map(); + for (const auto & [sx, sy, gx, gy] : std::vector>{ + {1.5, 0.3, 3.5, 0.3}, {3.5, 0.3, 1.5, 0.3}, {1.5, 0.3, 1.6, 0.35}}) + { + set_robot(sx, sy); + set_goal(gx, gy); + planner_->update(nav_state_); + const auto p = path(); + ASSERT_GE(p.poses.size(), 2u) << sx << " -> " << gx; + EXPECT_NEAR(p.poses.front().pose.position.x, sx, 1e-5); + EXPECT_NEAR(p.poses.front().pose.position.y, sy, 1e-5); + EXPECT_DOUBLE_EQ(p.poses.back().pose.position.x, gx); + EXPECT_DOUBLE_EQ(p.poses.back().pose.position.y, gy); + double len = 0.0; + for (std::size_t i = 1; i < p.poses.size(); ++i) { + const auto & a = p.poses[i - 1].pose.position; + const auto & b = p.poses[i].pose.position; + EXPECT_LE(std::hypot(b.x - a.x, b.y - a.y), 0.25 + 1e-4) << i; + len += std::hypot(b.x - a.x, b.y - a.y); + } + EXPECT_NEAR(len, std::hypot(gx - sx, gy - sy), 1e-3); + } +} + +TEST_F(NavMapPlannerTest, LargeNavCelsStillGiveADensePath) +{ + grid_.info.resolution = 5.0; + grid_.info.width = 4; + grid_.info.height = 4; + grid_.data.assign(16, 0); + update_map(); + set_robot(2.5, 2.5); + set_goal(17.5, 12.5); + planner_->update(nav_state_); + const auto p = path(); + ASSERT_GE(p.poses.size(), 2u); + for (std::size_t i = 1; i < p.poses.size(); ++i) { + const auto & a = p.poses[i - 1].pose.position; + const auto & b = p.poses[i].pose.position; + EXPECT_LE(std::hypot(b.x - a.x, b.y - a.y), 0.25 + 1e-4) << i; + } +} + +TEST_F(NavMapPlannerTest, ThePathStartsAtTheRobot) +{ + set_robot(0.57, 0.52); // off its NavCel's centroid + set_goal(3.05, 3.05); + planner_->update(nav_state_); + const auto p = path(); + ASSERT_GE(p.poses.size(), 2u); + EXPECT_NEAR(p.poses.front().pose.position.x, 0.57, 1e-5); + EXPECT_NEAR(p.poses.front().pose.position.y, 0.52, 1e-5); +} + +TEST_F(NavMapPlannerTest, ARobotOffTheMapStillGetsAPath) +{ + // Off the map: the planner starts from the closest NavCel + for (const auto & [gx, gy] : std::vector>{{3.05, 3.05}, {0.05, 0.55}}) { + set_robot(-0.3, 0.55); + set_goal(gx, gy); + planner_->update(nav_state_); + const auto p = path(); + ASSERT_GE(p.poses.size(), 2u) << gx; + EXPECT_DOUBLE_EQ(p.poses.back().pose.position.x, gx); + EXPECT_DOUBLE_EQ(p.poses.back().pose.position.y, gy); + } +} + +TEST_F(NavMapPlannerTest, MapKeyChoosesTheNavMapToPlanOn) +{ + // The default planner only reads map.navmap + auto lod = nav_state_.get<::navmap::NavMap>("map.navmap"); + easynav::NavState only_lod; + only_lod.set("map.navmap.lod", lod); + only_lod.set("robot_pose", nav_state_.get("robot_pose")); + set_goal(3.05, 3.05); + only_lod.set("goals", nav_state_.get("goals")); + planner_->update(only_lod); + EXPECT_FALSE(only_lod.has("path") && !only_lod.get("path").poses.empty()); + + rclcpp::NodeOptions options; + options.parameter_overrides({{"planner.map_key", "map.navmap.lod"}}); + auto node = rclcpp_lifecycle::LifecycleNode::make_shared("navmap_planner_map_key", options); + auto planner = std::make_shared(); + planner->initialize(node, "planner"); + planner->update(only_lod); + ASSERT_TRUE(only_lod.has("path")); + const auto p = only_lod.get("path"); + ASSERT_FALSE(p.poses.empty()); + EXPECT_DOUBLE_EQ(p.poses.back().pose.position.x, 3.05); + EXPECT_DOUBLE_EQ(p.poses.back().pose.position.y, 3.05); + + // A wall in map.navmap does not change the plan on map.navmap.lod + vertical_wall(2.0); + only_lod.set("map.navmap", nav_state_.get<::navmap::NavMap>("map.navmap")); + planner->update(only_lod); + EXPECT_FALSE(only_lod.get("path").poses.empty()); +} + TEST_F(NavMapPlannerTest, ManyPlansInARowAreTheSameAsTheFirstPlanOfANewPlanner) { // The search buffers are reused from plan to plan (no reset of the whole map): what a plan