Nav2 Navigation Stack - humble  humble
ROS 2 Navigation Stack
node_spatial_tree.cpp
1 // Copyright (c) 2025, Open Navigation LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <string>
16 #include <memory>
17 #include <vector>
18 
19 #include "nav2_route/node_spatial_tree.hpp"
20 
21 namespace nav2_route
22 {
23 
25 {
26  if (kdtree_) {
27  delete kdtree_;
28  kdtree_ = nullptr;
29  }
30 
31  if (adaptor_) {
32  delete adaptor_;
33  adaptor_ = nullptr;
34  }
35 }
36 
37 void NodeSpatialTree::setNumOfNearestNodes(int num_of_nearest_nodes)
38 {
39  num_of_nearest_nodes_ = num_of_nearest_nodes;
40 }
41 
42 void NodeSpatialTree::computeTree(Graph & graph)
43 {
44  if (kdtree_) {
45  delete kdtree_;
46  kdtree_ = nullptr;
47  }
48 
49  if (adaptor_) {
50  delete adaptor_;
51  adaptor_ = nullptr;
52  }
53 
54  adaptor_ = new GraphAdaptor(graph);
55  kdtree_ = new kd_tree_t(DIMENSION, *adaptor_, nanoflann::KDTreeSingleIndexAdaptorParams(10));
56  kdtree_->buildIndex();
57  graph_ = &graph;
58 }
59 
61  const geometry_msgs::msg::PoseStamped & pose_in, std::vector<unsigned int> & node_ids)
62 {
63  size_t num_results = static_cast<size_t>(num_of_nearest_nodes_);
64  std::vector<unsigned int> ret_index(num_results);
65  std::vector<double> out_dist_sqr(num_results);
66  const double query_pt[2] = {pose_in.pose.position.x, pose_in.pose.position.y};
67  num_results = kdtree_->knnSearch(&query_pt[0], num_results, &ret_index[0], &out_dist_sqr[0]);
68 
69  if (num_results == 0) {
70  return false;
71  }
72 
73  for (int i = 0; i < static_cast<int>(ret_index.size()); ++i) {
74  node_ids.push_back(ret_index[i]);
75  }
76  return true;
77 }
78 
79 } // namespace nav2_route
bool findNearestGraphNodesToPose(const geometry_msgs::msg::PoseStamped &pose_in, std::vector< unsigned int > &node_ids)
Find the closest node to a given pose.
void setNumOfNearestNodes(int num_of_nearest_nodes)
Set the number of nodes to search in local area for.
void computeTree(Graph &graph)
Compute the kd-tree based on the graph node information.
An adaptor for Nanoflann to operate on our graph object without copying.