Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
graceful_controller.cpp
1 // Copyright (c) 2023 Alberto J. Tudela Roldán
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 <memory>
16 #include <mutex>
17 
18 #include "angles/angles.h"
19 #include "nav2_core/controller_exceptions.hpp"
20 #include "nav2_util/geometry_utils.hpp"
21 #include "nav2_util/controller_utils.hpp"
22 #include "nav2_util/path_utils.hpp"
23 #include "nav2_graceful_controller/graceful_controller.hpp"
24 #include "nav2_costmap_2d/costmap_filters/filter_values.hpp"
25 #include "nav2_ros_common/tf2_factories.hpp"
26 
27 namespace nav2_graceful_controller
28 {
29 
31  const nav2::LifecycleNode::WeakPtr & parent,
32  std::string name, const nav2::TransformBuffer::SharedPtr tf,
33  const std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros)
34 {
35  nav2::LifecycleNode::SharedPtr node = parent.lock();
36  if (!node) {
37  throw nav2_core::ControllerException("Unable to lock node!");
38  }
39 
40  costmap_ros_ = costmap_ros;
41  tf_buffer_ = tf;
42  plugin_name_ = name;
43  logger_ = node->get_logger();
44 
45  // Handles storage and dynamic configuration of parameters.
46  // Returns pointer to data current param settings.
47  param_handler_ = std::make_unique<ParameterHandler>(
48  node, plugin_name_, logger_);
49  params_ = param_handler_->getParams();
50 
51  // Handles the control law to generate the velocity commands
52  control_law_ = std::make_unique<SmoothControlLaw>(
53  params_->k_phi, params_->k_delta, params_->beta, params_->lambda,
54  params_->slowdown_radius, params_->deceleration_max,
55  params_->v_linear_min, params_->v_linear_max, params_->v_angular_max);
56 
57  // Initialize footprint collision checker
58  if (params_->use_collision_detection) {
59  collision_checker_ = std::make_unique<nav2_costmap_2d::
60  FootprintCollisionChecker<nav2_costmap_2d::Costmap2D *>>(costmap_ros_->getCostmap());
61  }
62 
63  double max_valid_cost = costmap_ros_->getUseRadius() ?
64  static_cast<double>(nav2_costmap_2d::MAX_NON_OBSTACLE) :
65  static_cast<double>(nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE);
66  if (max_valid_cost - static_cast<double>(params_->obstacle_cost_margin) < 0.0) {
67  RCLCPP_WARN(
68  logger_, "obstacle_cost_margin (%d) is higher than max cost (%d).",
69  params_->obstacle_cost_margin, nav2_costmap_2d::MAX_NON_OBSTACLE);
70  throw nav2_core::ControllerException("obstacle_cost_margin is higher than max cost.");
71  }
72 
73  // Publishers
74  local_plan_pub_ = node->create_publisher<nav_msgs::msg::Path>("local_plan");
75  motion_target_pub_ = node->create_publisher<geometry_msgs::msg::PoseStamped>("motion_target");
76  slowdown_pub_ = node->create_publisher<visualization_msgs::msg::Marker>("slowdown");
77 
78  RCLCPP_INFO(logger_, "Configured Graceful Motion Controller: %s", plugin_name_.c_str());
79 }
80 
82 {
83  RCLCPP_INFO(
84  logger_,
85  "Cleaning up controller: %s of type graceful_controller::GracefulController",
86  plugin_name_.c_str());
87  local_plan_pub_.reset();
88  motion_target_pub_.reset();
89  slowdown_pub_.reset();
90  collision_checker_.reset();
91  param_handler_.reset();
92  control_law_.reset();
93 }
94 
96 {
97  RCLCPP_INFO(
98  logger_,
99  "Activating controller: %s of type nav2_graceful_controller::GracefulController",
100  plugin_name_.c_str());
101  local_plan_pub_->on_activate();
102  motion_target_pub_->on_activate();
103  slowdown_pub_->on_activate();
104  param_handler_->activate();
105 }
106 
108 {
109  RCLCPP_INFO(
110  logger_,
111  "Deactivating controller: %s of type nav2_graceful_controller::GracefulController",
112  plugin_name_.c_str());
113  local_plan_pub_->on_deactivate();
114  motion_target_pub_->on_deactivate();
115  slowdown_pub_->on_deactivate();
116  param_handler_->deactivate();
117 }
118 
119 geometry_msgs::msg::TwistStamped GracefulController::computeVelocityCommands(
120  const geometry_msgs::msg::PoseStamped & pose,
121  const geometry_msgs::msg::Twist & velocity,
122  nav2_core::GoalChecker * goal_checker,
123  const nav_msgs::msg::Path & transformed_global_plan,
124  const geometry_msgs::msg::PoseStamped & global_goal)
125 {
126  std::lock_guard<std::mutex> param_lock(param_handler_->getMutex());
127 
128  geometry_msgs::msg::TwistStamped cmd_vel;
129  cmd_vel.header = pose.header;
130 
131  // Transform the plan from costmap's global frame to robot base frame
132  nav_msgs::msg::Path transformed_plan;
133  if (!nav2_util::transformPathInTargetFrame(
134  transformed_global_plan, transformed_plan, *tf_buffer_,
135  costmap_ros_->getBaseFrameID(), costmap_ros_->getTransformTolerance()))
136  {
138  "Unable to transform plan pose into local frame");
139  }
140 
141  // Update the smooth control law with the new params
142  control_law_->setCurvatureConstants(
143  params_->k_phi, params_->k_delta, params_->beta, params_->lambda);
144  control_law_->setSlowdownRadius(params_->slowdown_radius);
145  control_law_->setMaxDeceleration(params_->deceleration_max);
146  control_law_->setSpeedLimit(params_->v_linear_min, params_->v_linear_max, params_->v_angular_max);
147  // Add proper orientations to plan, if needed
148  validateOrientations(transformed_plan.poses);
149 
150  // ControllerServer supplies pose in the local costmap's global frame, so it already
151  // represents the transform from the robot base frame to the costmap's global frame.
152  geometry_msgs::msg::TransformStamped costmap_transform = nav2_util::poseToTransformStamped(pose,
153  costmap_ros_->getBaseFrameID());
154 
155  // Compute distance to goal as the path's integrated distance to account for path curvatures
156  double dist_to_goal = nav2_util::geometry_utils::calculate_path_length(transformed_plan);
157 
158  // If we've reached the XY goal tolerance, just rotate.
159  // Feed the goal checker the GLOBAL-frame plan (same frame as `pose` / `global_goal`), not the
160  // base_link-frame `transformed_plan` used for control.
161  if (goal_checker->isGoalXYReached(pose.pose, global_goal.pose, velocity,
162  transformed_global_plan))
163  {
164  double angle_to_goal = tf2::getYaw(transformed_plan.poses.back().pose.orientation);
165  // Check for collisions between our current pose and goal pose
166  size_t num_steps = fabs(angle_to_goal) / params_->in_place_collision_resolution;
167  // Need to check at least the end pose
168  num_steps = std::max(static_cast<size_t>(1), num_steps);
169  bool collision_free = true;
170  for (size_t i = 1; i <= num_steps; ++i) {
171  double step = static_cast<double>(i) / static_cast<double>(num_steps);
172  double yaw = step * angle_to_goal;
173  geometry_msgs::msg::PoseStamped next_pose;
174  next_pose.header.frame_id = costmap_ros_->getBaseFrameID();
175  next_pose.pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(yaw);
176  geometry_msgs::msg::PoseStamped costmap_pose;
177  tf2::doTransform(next_pose, costmap_pose, costmap_transform);
178  if (params_->use_collision_detection && inCollision(
179  costmap_pose.pose.position.x, costmap_pose.pose.position.y,
180  tf2::getYaw(costmap_pose.pose.orientation)))
181  {
182  collision_free = false;
183  break;
184  }
185  }
186  // Compute velocity if rotation is possible
187  if (collision_free) {
188  cmd_vel.twist = rotateToTarget(angle_to_goal);
189  return cmd_vel;
190  }
191  // Else, fall through and see if we should follow control law longer
192  }
193 
194  // Find a valid target pose and its trajectory
195  nav_msgs::msg::Path local_plan;
196  geometry_msgs::msg::PoseStamped target_pose;
197 
198  double dist_to_target;
199  std::vector<double> target_distances;
200  computeDistanceAlongPath(transformed_plan.poses, target_distances);
201 
202  bool is_first_iteration = true;
203  for (int i = transformed_plan.poses.size() - 1; i >= 0; --i) {
204  if (is_first_iteration) {
205  // Calculate target pose through lookahead interpolation to get most accurate
206  // lookahead point, if possible
207  dist_to_target = params_->max_lookahead;
208  // Interpolate after goal false for graceful controller
209  // Requires interpolating the orientation which is not yet implemented
210  // Updates dist_to_target for target_pose returned if using the point on the path
211  target_pose = nav2_util::getLookAheadPoint(dist_to_target, transformed_plan, false);
212  is_first_iteration = false;
213  } else {
214  // Underlying control law needs a single target pose, which should:
215  // * Be as far away as possible from the robot (for smoothness)
216  // * But no further than the max_lookahed_ distance
217  // * Be feasible to reach in a collision free manner
218  dist_to_target = target_distances[i];
219  target_pose = transformed_plan.poses[i];
220  }
221 
222  // Compute velocity at this moment if valid target pose is found
223  if (
224  validateTargetPoseOnApproach(target_pose, dist_to_target, dist_to_goal, local_plan,
225  costmap_transform, cmd_vel) ||
226  validateTargetPose(target_pose, dist_to_target, local_plan, costmap_transform, cmd_vel))
227  {
228  // Publish the selected target_pose
229  motion_target_pub_->publish(std::make_unique<geometry_msgs::msg::PoseStamped>(target_pose));
230  // Publish marker for slowdown radius around motion target for debugging / visualization
231  auto slowdown_marker = nav2_graceful_controller::createSlowdownMarker(
232  target_pose, params_->slowdown_radius);
233  slowdown_pub_->publish(std::make_unique<visualization_msgs::msg::Marker>(slowdown_marker));
234  // Publish the local plan
235  local_plan.header = transformed_plan.header;
236  local_plan_pub_->publish(std::make_unique<nav_msgs::msg::Path>(local_plan));
237  // Successfully found velocity command
238  return cmd_vel;
239  }
240  }
241 
242  throw nav2_core::NoValidControl("Collision detected in trajectory");
243 }
244 
245 void GracefulController::newPathReceived(const nav_msgs::msg::Path & /*raw_global_path*/)
246 {
247  do_initial_rotation_ = true;
248  safe_approach_angle_.reset();
249 }
250 
252  const double & speed_limit, const bool & percentage)
253 {
254  std::lock_guard<std::mutex> param_lock(param_handler_->getMutex());
255 
256  if (speed_limit == nav2_costmap_2d::NO_SPEED_LIMIT) {
257  params_->v_linear_max = params_->v_linear_max_initial;
258  params_->v_angular_max = params_->v_angular_max_initial;
259  } else {
260  if (percentage) {
261  // Speed limit is expressed in % from maximum speed of robot
262  params_->v_linear_max = std::max(
263  params_->v_linear_max_initial * speed_limit / 100.0, params_->v_linear_min);
264  params_->v_angular_max = params_->v_angular_max_initial * speed_limit / 100.0;
265  } else {
266  // Speed limit is expressed in m/s
267  params_->v_linear_max = std::max(speed_limit, params_->v_linear_min);
268  // Limit the angular velocity to be proportional to the linear velocity
269  params_->v_angular_max = params_->v_angular_max_initial *
270  speed_limit / params_->v_linear_max_initial;
271  }
272  }
273 }
274 
276  geometry_msgs::msg::PoseStamped & target_pose, double dist_to_target,
277  nav_msgs::msg::Path & trajectory, geometry_msgs::msg::TransformStamped & costmap_transform,
278  geometry_msgs::msg::TwistStamped & cmd_vel)
279 {
280  // Continue if target_pose is too far away from robot
281  if (dist_to_target > params_->max_lookahead) {
282  return false;
283  }
284 
285  // Flip the orientation of the motion target if the robot is moving backwards
286  bool reversing = false;
287  if (params_->allow_backward && target_pose.pose.position.x < 0.0) {
288  reversing = true;
289  target_pose.pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(
290  tf2::getYaw(target_pose.pose.orientation) + M_PI);
291  }
292 
293  // Actually simulate the path
294  double sim_linear_velocity = params_->v_linear_max;
295  do {
296  control_law_->setSpeedLimit(params_->v_linear_min, sim_linear_velocity, params_->v_angular_max);
297  if (simulateTrajectory(target_pose, costmap_transform, trajectory, cmd_vel, reversing)) {
298  // Successfully simulated to target_pose
299  return true;
300  }
301  // Reduce velocity and try again for same target_pose
302  sim_linear_velocity -= params_->footprint_scaling_step;
303  } while (sim_linear_velocity >= params_->footprint_scaling_linear_vel);
304 
305  // Validation not successful
306  return false;
307 }
308 
310  geometry_msgs::msg::PoseStamped & target_pose, double dist_to_target, double dist_to_goal,
311  nav_msgs::msg::Path & trajectory, geometry_msgs::msg::TransformStamped & costmap_transform,
312  geometry_msgs::msg::TwistStamped & cmd_vel)
313 {
314  // Not approaching goal with large lookahead and don't evaluate shortcut trajectories
315  // when we do not prefer rotating to goal at the end.
316  if (dist_to_goal >= params_->max_lookahead || !params_->prefer_final_rotation) {
317  return false;
318  }
319  // Avoid instability and big sweeping turns at the end of paths by
320  // ignoring final heading
321  double yaw = std::atan2(target_pose.pose.position.y, target_pose.pose.position.x);
322  target_pose.pose.orientation =
323  nav2_util::geometry_utils::orientationAroundZAxis(yaw);
324 
325  if (validateTargetPose(target_pose, dist_to_target, trajectory, costmap_transform, cmd_vel)) {
326  // Determine the maximum valid cost based on robot footprint type
327  double max_valid_cost =
328  costmap_ros_->getUseRadius() ? static_cast<double>(nav2_costmap_2d::MAX_NON_OBSTACLE) :
329  static_cast<double>(nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE);
330 
331  // Check if the final rotation path is risky
332  double safety_threshold = max_valid_cost - static_cast<double>(params_->obstacle_cost_margin);
333  if (getMaxCost(trajectory, costmap_transform) >= safety_threshold) {
334  // Try to find a better approach by searching spiral curves
336  target_pose, dist_to_target, costmap_transform, max_valid_cost, trajectory, cmd_vel);
337  }
338  return true;
339  }
340  return false;
341 }
342 
344  const geometry_msgs::msg::PoseStamped & motion_target,
345  const geometry_msgs::msg::TransformStamped & costmap_transform,
346  nav_msgs::msg::Path & trajectory,
347  geometry_msgs::msg::TwistStamped & cmd_vel,
348  bool backward)
349 {
350  trajectory.poses.clear();
351 
352  // First pose is robot current pose
353  geometry_msgs::msg::PoseStamped next_pose;
354  next_pose.header.frame_id = costmap_ros_->getBaseFrameID();
355  next_pose.pose.orientation.w = 1.0;
356 
357  // Should we simulate rotation initially?
358  bool sim_initial_rotation = do_initial_rotation_ && params_->initial_rotation;
359  double angle_to_target =
360  std::atan2(motion_target.pose.position.y, motion_target.pose.position.x);
361  if (fabs(angle_to_target) < params_->initial_rotation_tolerance) {
362  sim_initial_rotation = false;
363  do_initial_rotation_ = false;
364  }
365 
366  double distance = std::numeric_limits<double>::max();
367  double resolution = costmap_ros_->getCostmap()->getResolution();
368  double dt = (params_->v_linear_max > 0.0) ? resolution / params_->v_linear_max : 0.0;
369 
370  // Set max iter to avoid infinite loop
371  unsigned int max_iter = 3 *
372  std::hypot(motion_target.pose.position.x, motion_target.pose.position.y) / resolution;
373 
374  // Generate path
375  do{
376  if (sim_initial_rotation) {
377  // Compute rotation velocity
378  double next_pose_yaw = tf2::getYaw(next_pose.pose.orientation);
379  auto cmd = rotateToTarget(angle_to_target - next_pose_yaw);
380 
381  // If this is first iteration, this is our current target velocity
382  if (trajectory.poses.empty()) {cmd_vel.twist = cmd;}
383 
384  // Are we done simulating initial rotation?
385  if (fabs(angle_to_target - next_pose_yaw) < params_->initial_rotation_tolerance) {
386  sim_initial_rotation = false;
387  }
388 
389  // Forward simulate rotation command
390  next_pose_yaw += cmd_vel.twist.angular.z * dt;
391  next_pose.pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(next_pose_yaw);
392  } else {
393  // If this is first iteration, this is our current target velocity
394  if (trajectory.poses.empty()) {
395  cmd_vel.twist = control_law_->calculateRegularVelocity(
396  motion_target.pose, next_pose.pose, backward);
397  }
398 
399  // Apply velocities to calculate next pose
400  next_pose.pose = control_law_->calculateNextPose(
401  dt, motion_target.pose, next_pose.pose, backward);
402  }
403 
404  // Add the pose to the trajectory for visualization
405  trajectory.poses.push_back(next_pose);
406 
407  // Compute footprint scaling
408  double footprint_scaling = 1.0;
409  if (cmd_vel.twist.linear.x > params_->footprint_scaling_linear_vel) {
410  // Scaling = (vel_x - scaling_vel_x) / (max_vel_x - scaling_vel_x)
411  double ratio = params_->v_linear_max - params_->footprint_scaling_linear_vel;
412  // Avoid divide by zero
413  if (ratio > 0) {
414  ratio = (cmd_vel.twist.linear.x - params_->footprint_scaling_linear_vel) / ratio;
415  footprint_scaling += ratio * params_->footprint_scaling_factor;
416  }
417  }
418 
419  // Check for collision
420  geometry_msgs::msg::PoseStamped global_pose;
421  tf2::doTransform(next_pose, global_pose, costmap_transform);
422  if (params_->use_collision_detection && inCollision(
423  global_pose.pose.position.x, global_pose.pose.position.y,
424  tf2::getYaw(global_pose.pose.orientation), footprint_scaling))
425  {
426  return false;
427  }
428 
429  // Check if we reach the goal
430  distance = nav2_util::geometry_utils::euclidean_distance(motion_target.pose, next_pose.pose);
431  }while(distance > resolution && trajectory.poses.size() < max_iter);
432 
433  return true;
434 }
435 
436 geometry_msgs::msg::Twist GracefulController::rotateToTarget(double angle_to_target)
437 {
438  geometry_msgs::msg::Twist vel;
439  vel.linear.x = 0.0;
440  vel.angular.z = params_->rotation_scaling_factor * angle_to_target * params_->v_angular_max;
441  vel.angular.z = std::copysign(1.0, vel.angular.z) * std::max(
442  abs(vel.angular.z),
443  params_->v_angular_min_in_place);
444  return vel;
445 }
446 
448  const nav_msgs::msg::Path & path, geometry_msgs::msg::TransformStamped & costmap_transform)
449 {
450  double max_cost = 0.0;
451 
452  for (const auto & pose : path.poses) {
453  geometry_msgs::msg::PoseStamped costmap_pose;
454  tf2::doTransform(pose, costmap_pose, costmap_transform);
455  unsigned int mx, my;
456  if (costmap_ros_->getCostmap()->worldToMap(costmap_pose.pose.position.x,
457  costmap_pose.pose.position.y, mx, my))
458  {
459  max_cost = std::max(max_cost, collision_checker_->pointCost(mx, my));
460  }
461  }
462 
463  return max_cost;
464 }
465 
467  const double & x, const double & y, const double & theta,
468  double inflation_scale)
469 {
470  unsigned int mx, my;
471  if (!costmap_ros_->getCostmap()->worldToMap(x, y, mx, my)) {
472  RCLCPP_WARN(
473  logger_, "The path is not in the costmap. Cannot check for collisions. "
474  "Proceed at your own risk, slow the robot, or increase your costmap size.");
475  return false;
476  }
477 
478  if (inflation_scale < 1.0) {
479  RCLCPP_WARN(logger_, "Inflation ratio cannot be less than 1.0");
480  throw nav2_core::NoValidControl("Inflation ratio less than 1.0");
481  }
482 
483  // Calculate the cost of the footprint at the robot's current position depending
484  // on the shape of the footprint
485  bool is_tracking_unknown =
486  costmap_ros_->getLayeredCostmap()->isTrackingUnknown();
487  bool consider_footprint = !costmap_ros_->getUseRadius();
488 
489  double footprint_cost;
490  if (consider_footprint) {
491  std::vector<geometry_msgs::msg::Point> spec = costmap_ros_->getRobotFootprint();
492  if (spec.size() > 3) {
493  for (auto & point : spec) {
494  point.x *= inflation_scale;
495  point.y *= inflation_scale;
496  }
497  }
498  footprint_cost = collision_checker_->footprintCostAtPose(x, y, theta, spec);
499  } else {
500  footprint_cost = collision_checker_->pointCost(mx, my);
501  }
502 
503  switch (static_cast<unsigned char>(footprint_cost)) {
504  case (nav2_costmap_2d::LETHAL_OBSTACLE):
505  return true;
506  case (nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE):
507  return consider_footprint ? false : true;
508  case (nav2_costmap_2d::NO_INFORMATION):
509  return is_tracking_unknown ? false : true;
510  }
511 
512  return false;
513 }
514 
516  const std::vector<geometry_msgs::msg::PoseStamped> & poses,
517  std::vector<double> & distances)
518 {
519  distances.resize(poses.size());
520  // Do the first pose from robot
521  double d = std::hypot(poses[0].pose.position.x, poses[0].pose.position.y);
522  distances[0] = d;
523  // Compute remaining poses
524  for (size_t i = 1; i < poses.size(); ++i) {
525  d += nav2_util::geometry_utils::euclidean_distance(poses[i - 1].pose, poses[i].pose);
526  distances[i] = d;
527  }
528 }
529 
531  std::vector<geometry_msgs::msg::PoseStamped> & path)
532 {
533  // We never change the orientation of the first & last pose
534  // So we need at least three poses to do anything here
535  if (path.size() < 3) {return;}
536 
537  // Check if we actually need to add orientations
538  double initial_yaw = tf2::getYaw(path[1].pose.orientation);
539  for (size_t i = 2; i < path.size() - 1; ++i) {
540  double this_yaw = tf2::getYaw(path[i].pose.orientation);
541  if (angles::shortest_angular_distance(this_yaw, initial_yaw) > 1e-6) {return;}
542  }
543 
544  // For each pose, point at the next one
545  // NOTE: control loop will handle reversing logic
546  for (size_t i = 0; i < path.size() - 1; ++i) {
547  // Get relative yaw angle
548  double dx = path[i + 1].pose.position.x - path[i].pose.position.x;
549  double dy = path[i + 1].pose.position.y - path[i].pose.position.y;
550  double yaw = std::atan2(dy, dx);
551  path[i].pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(yaw);
552  }
553 }
554 
556  geometry_msgs::msg::PoseStamped & target_pose, double dist_to_target,
557  geometry_msgs::msg::TransformStamped & costmap_transform, double safety_cost,
558  nav_msgs::msg::Path & best_trajectory, geometry_msgs::msg::TwistStamped & best_cmd_vel)
559 {
560  bool found_valid = false;
561  double best_eta = std::numeric_limits<double>::max();
562 
563  for (int i = 0; i < 2 * M_PI / params_->final_rotation_search_step; ++i) {
564  double angle = static_cast<double>(i) * params_->final_rotation_search_step;
565  // Prioritize previously selected approach angles
566  if (safe_approach_angle_.has_value()) {
567  angle += safe_approach_angle_.value();
568  }
569 
570  // Create candidate pose
571  auto candidate_pose = target_pose;
572  candidate_pose.pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(angle);
573 
574  nav_msgs::msg::Path candidate_path = best_trajectory;
575  geometry_msgs::msg::TwistStamped candidate_cmd_vel = best_cmd_vel;
576 
577  // Validate the candidate
578  if (validateTargetPose(
579  candidate_pose, dist_to_target, candidate_path, costmap_transform,
580  candidate_cmd_vel))
581  {
582  double candidate_cost = getMaxCost(candidate_path, costmap_transform);
583 
584  bool reversing = false;
585  if (params_->allow_backward && target_pose.pose.position.x < 0.0) {
586  reversing = true;
587  }
588  // Calculate ETA
589  double eta = 0.0;
590  for (size_t j = 1; j < candidate_path.poses.size(); ++j) {
591  auto current_pose = candidate_path.poses[j - 1];
592  auto next_pose = candidate_path.poses[j];
593  auto cmd = control_law_->calculateRegularVelocity(candidate_pose.pose, current_pose.pose,
594  reversing);
595  double speed = std::abs(cmd.linear.x);
596  // Avoid division by zero
597  speed = std::max(speed, 1e-3);
598  double step_dist = nav2_util::geometry_utils::euclidean_distance(
599  current_pose.pose, next_pose.pose);
600  double step_time = step_dist / speed;
601  eta += step_time;
602  }
603 
604  // Selection logic: Pick the fastest among the safe ones
605  if (eta < best_eta) {
606  best_eta = eta;
607  if (candidate_cost < safety_cost) {
608  best_trajectory = candidate_path;
609  best_cmd_vel = candidate_cmd_vel;
610  target_pose = candidate_pose;
611  found_valid = true;
612  // Reuse known safe approach angle if still valid
613  if (safe_approach_angle_.value_or(1e3 /*Never in (-PI, PI]*/) == angle) {
614  break;
615  }
616  safe_approach_angle_ = angle;
617  }
618  }
619  }
620  }
621 
622  return found_valid;
623 }
624 
625 } // namespace nav2_graceful_controller
626 
627 // Register this controller as a nav2_core plugin
628 PLUGINLIB_EXPORT_CLASS(
controller interface that acts as a virtual base class for all controller plugins
Definition: controller.hpp:60
Function-object for checking whether a goal has been reached.
virtual bool isGoalXYReached(const geometry_msgs::msg::Pose &query_pose, const geometry_msgs::msg::Pose &goal_pose, const geometry_msgs::msg::Twist &velocity, const nav_msgs::msg::Path &transformed_global_plan)=0
Check if XY goal position has been reached (without considering yaw) This is useful for controllers t...
void activate() override
Activate controller state machine.
void computeDistanceAlongPath(const std::vector< geometry_msgs::msg::PoseStamped > &poses, std::vector< double > &distances)
Compute the distance to each pose in a path.
bool validateTargetPose(geometry_msgs::msg::PoseStamped &target_pose, double dist_to_target, nav_msgs::msg::Path &trajectory, geometry_msgs::msg::TransformStamped &costmap_transform, geometry_msgs::msg::TwistStamped &cmd_vel)
Validate a given target pose for calculating command velocity.
bool validateTargetPoseOnApproach(geometry_msgs::msg::PoseStamped &target_pose, double dist_to_target, double dist_to_goal, nav_msgs::msg::Path &trajectory, geometry_msgs::msg::TransformStamped &costmap_transform, geometry_msgs::msg::TwistStamped &cmd_vel)
Validate a given target pose for calculating command velocity on approach to goal.
void deactivate() override
Deactivate controller state machine.
bool inCollision(const double &x, const double &y, const double &theta, double inflation_scale=1.0)
Checks if the robot is in collision.
bool findBestApproachTrajectory(geometry_msgs::msg::PoseStamped &target_pose, double dist_to_target, geometry_msgs::msg::TransformStamped &costmap_transform, double safety_cost, nav_msgs::msg::Path &best_trajectory, geometry_msgs::msg::TwistStamped &best_cmd_vel)
Find the best approach trajectory by searching multiple orientations.
bool simulateTrajectory(const geometry_msgs::msg::PoseStamped &motion_target, const geometry_msgs::msg::TransformStamped &costmap_transform, nav_msgs::msg::Path &trajectory, geometry_msgs::msg::TwistStamped &cmd_vel, bool backward)
Simulate trajectory calculating in every step the new velocity command based on a new curvature value...
geometry_msgs::msg::TwistStamped computeVelocityCommands(const geometry_msgs::msg::PoseStamped &pose, const geometry_msgs::msg::Twist &velocity, nav2_core::GoalChecker *goal_checker, const nav_msgs::msg::Path &transformed_global_plan, const geometry_msgs::msg::PoseStamped &global_goal) override
Compute the best command given the current pose and velocity.
void configure(const nav2::LifecycleNode::WeakPtr &parent, std::string name, nav2::TransformBuffer::SharedPtr tf, std::shared_ptr< nav2_costmap_2d::Costmap2DROS > costmap_ros) override
Configure controller state machine.
void cleanup() override
Cleanup controller state machine.
geometry_msgs::msg::Twist rotateToTarget(double angle_to_target)
Rotate the robot to face the motion target with maximum angular velocity.
void newPathReceived(const nav_msgs::msg::Path &raw_global_path) override
nav2_core newPathReceived - Receives a new plan from the Planner Server
void setSpeedLimit(const double &speed_limit, const bool &percentage) override
Limits the maximum linear speed of the robot.
void validateOrientations(std::vector< geometry_msgs::msg::PoseStamped > &path)
Control law requires proper orientations, not all planners provide them.
double getMaxCost(const nav_msgs::msg::Path &path, geometry_msgs::msg::TransformStamped &costmap_transform)
Get the maximum cost of a path.