diff --git a/include/dock_planner/dock_calc.h b/include/dock_planner/dock_calc.h index 2b4c11b..cb7c313 100644 --- a/include/dock_planner/dock_calc.h +++ b/include/dock_planner/dock_calc.h @@ -52,17 +52,46 @@ private: static robot_geometry_msgs::Pose offsetPoint(const robot_geometry_msgs::Pose& pose, double yaw, double distance); - bool sampleForwardApproach(const robot_geometry_msgs::Pose& start, - const robot_geometry_msgs::Pose& goal, - double goal_yaw, double start_longitudinal, - double start_lateral, double minimum_cusp_distance, - double minimum_turning_radius, - std::vector& path, - double& cusp_distance, double& curve_radius) const; - bool sampleReverseTerminal(const robot_geometry_msgs::Pose& cusp, - const robot_geometry_msgs::Pose& goal, - double goal_yaw, - std::vector& path) const; + /** + * @brief Leg from the start to the cusp, driven away from the dock. + * + * Everything is computed in the approach frame, whose X axis points from the + * dock toward the side the robot stands on. @p heading_offset is 0 rad when + * the leg is driven forward (rear-edge docking) and pi rad when it is driven + * in reverse (front-edge docking); the positions are identical either way. + */ + bool sampleLeadIn(const robot_geometry_msgs::Pose& start, + const robot_geometry_msgs::Pose& goal, + double approach_yaw, double heading_offset, + double start_longitudinal, + double start_lateral, double minimum_cusp_distance, + double minimum_turning_radius, + std::vector& path, + double& cusp_distance, double& curve_radius) const; + + /** + * @brief No-cusp entry: one arc that converges onto the goal axis, then the + * straight terminal continues in the SAME travel direction. + * + * Feasible only when the robot is far enough along the approach axis that an + * arc of at least @p minimum_turning_radius fits between the start and the + * point @p straight_distance ahead of the goal. Returns false when it does + * not fit, which is a normal outcome: the caller then plans a cusp instead. + */ + bool sampleDirectEntry(const robot_geometry_msgs::Pose& start, + const robot_geometry_msgs::Pose& goal, + double approach_yaw, double heading_offset, + double start_longitudinal, double start_lateral, + double straight_distance, + double minimum_turning_radius, + std::vector& path, + double& curve_radius) const; + + /** Straight leg from the cusp into the goal; body yaw is @p goal_yaw throughout. */ + bool sampleTerminal(const robot_geometry_msgs::Pose& cusp, + const robot_geometry_msgs::Pose& goal, + double goal_yaw, + std::vector& path) const; }; } // namespace dock_planner diff --git a/include/dock_planner/dock_planner_config.h b/include/dock_planner/dock_planner_config.h index e9da65f..26610b6 100644 --- a/include/dock_planner/dock_planner_config.h +++ b/include/dock_planner/dock_planner_config.h @@ -43,6 +43,22 @@ struct DockPlannerConfig double maximum_forward_extension = 3.0; // [m], rejects unexpectedly large maneuvers double path_point_spacing = 0.05; // [m] + /** + * [m] Requested length of the straight terminal leg. The effective length is + * max(straight_length, mating robot extent + dock near extent + padding), so + * 0 keeps the clearance-only behaviour. + */ + double straight_length = 0.0; + + /** + * [m] Enable the no-cusp entry when the room left for the curve + * (start longitudinal distance minus the straight terminal length) exceeds + * this. The curve radius is still checked against the Ackermann limit, and + * the single-cusp maneuver is used whenever either test fails. + * 0 disables the direct entry entirely and always plans a cusp. + */ + double direct_entry_min_curve_room = 0.0; + /** * Per-marker key copied down by move_base2 (like footprint_dock). * Default kCenter keeps the legacy formula for existing profiles. diff --git a/include/dock_planner/utils/dubins.h b/include/dock_planner/utils/dubins.h new file mode 100644 index 0000000..149edfc --- /dev/null +++ b/include/dock_planner/utils/dubins.h @@ -0,0 +1,76 @@ +#ifndef DOCK_PLANNER_UTILS_DUBINS_H_ +#define DOCK_PLANNER_UTILS_DUBINS_H_ + +#include +#include + +namespace dock_planner +{ +namespace dubins +{ + +/** Planar pose in the frame the caller works in. */ +struct Pose2D +{ + double x = 0.0; // [m] + double y = 0.0; // [m] + double yaw = 0.0; // [rad] +}; + +enum class SegmentType +{ + kLeft, ///< constant-radius turn, counter-clockwise + kStraight, + kRight, ///< constant-radius turn, clockwise +}; + +/** + * @brief Shortest forward-only path between two poses at a fixed turning radius. + * + * The three segment lengths are stored in metres, in travel order, together with + * the word that produced them. `valid` is false when no word applies, which for + * a strictly positive radius only happens if an input is non-finite. + */ +struct Path +{ + bool valid = false; + std::array types{SegmentType::kStraight, SegmentType::kStraight, + SegmentType::kStraight}; + std::array lengths{0.0, 0.0, 0.0}; // [m] + double radius = 0.0; // [m] + + /** Total travelled distance [m]. */ + double length() const; +}; + +/** + * @brief Solve for the shortest of the six Dubins words. + * + * Forward motion only, so the result never reverses direction. That is the + * property the docking approach relies on: the robot reaches the terminal pose + * having changed direction at most where the caller puts a cusp, never inside + * the lead-in. + * + * @param radius Turning radius [m]; must be > 0. A differential-drive robot has + * no such radius and is handled by the caller instead of by a degenerate + * radius here — passing 0 returns an invalid path on purpose. + */ +Path shortestPath(const Pose2D& start, const Pose2D& goal, double radius); + +/** + * @brief Sample a solved path at approximately @p spacing metres. + * + * Includes both endpoints. The final sample carries the goal yaw exactly rather + * than the accumulated one, so a caller can compare it against its own contract + * without absorbing the integration error of three segments. + */ +std::vector sample(const Path& path, const Pose2D& start, const Pose2D& goal, + double spacing); + +/** Wrap to (-pi, pi]. Exposed because callers compare yaw against a contract. */ +double normalizeAngle(double angle); + +} // namespace dubins +} // namespace dock_planner + +#endif // DOCK_PLANNER_UTILS_DUBINS_H_ diff --git a/src/dock_calc.cpp b/src/dock_calc.cpp index 88a4aaa..bafed4c 100644 --- a/src/dock_calc.cpp +++ b/src/dock_calc.cpp @@ -135,10 +135,11 @@ robot_geometry_msgs::Pose DockCalc::offsetPoint( return result; } -bool DockCalc::sampleForwardApproach( +bool DockCalc::sampleLeadIn( const robot_geometry_msgs::Pose& start, const robot_geometry_msgs::Pose& goal, - double goal_yaw, + double approach_yaw, + double heading_offset, double start_longitudinal, double start_lateral, double minimum_cusp_distance, @@ -175,14 +176,17 @@ bool DockCalc::sampleForwardApproach( actual_extension > config_.maximum_forward_extension + kEpsilon) { robot::log_error( - "[dock_calc] Forward cusp extension %.3f m is outside (0, %.3f] m " + "[dock_calc] Lead-in cusp extension %.3f m is outside (0, %.3f] m " "(start_longitudinal=%.3f m, minimum_cusp=%.3f m).\n", actual_extension, config_.maximum_forward_extension, start_longitudinal, minimum_cusp_distance); return false; } - const robot_geometry_msgs::Pose cusp = offsetPoint(goal, goal_yaw, cusp_distance); + const robot_geometry_msgs::Pose cusp = offsetPoint(goal, approach_yaw, cusp_distance); + // Body yaw on the lead-in: the approach axis for a rear dock, its opposite + // for a front dock, where the same positions are traversed in reverse. + const double lead_in_yaw = normalizeAngle(approach_yaw + heading_offset); if (lateral <= kEpsilon) { @@ -197,7 +201,7 @@ bool DockCalc::sampleForwardApproach( pose.position.x = start.position.x + ratio * (cusp.position.x - start.position.x); pose.position.y = start.position.y + ratio * (cusp.position.y - start.position.y); pose.position.z = start.position.z + ratio * (cusp.position.z - start.position.z); - pose.orientation = data_convert::createQuaternionMsgFromYaw(goal_yaw); + pose.orientation = data_convert::createQuaternionMsgFromYaw(lead_in_yaw); appendUnique(path, pose); } return path.size() >= 2; @@ -209,7 +213,7 @@ bool DockCalc::sampleForwardApproach( curve_radius + 1e-7 < minimum_turning_radius) { robot::log_error( - "[dock_calc] Forward arc radius %.6f m violates minimum turning radius %.6f m.\n", + "[dock_calc] Lead-in arc radius %.6f m violates minimum turning radius %.6f m.\n", curve_radius, minimum_turning_radius); return false; } @@ -228,7 +232,7 @@ bool DockCalc::sampleForwardApproach( std::fabs(angle_delta) > kPi + 1e-7) { robot::log_error( - "[dock_calc] Forward arc sweep %.6f rad is invalid; check start side and cusp geometry.\n", + "[dock_calc] Lead-in arc sweep %.6f rad is invalid; check start side and cusp geometry.\n", angle_delta); return false; } @@ -243,9 +247,10 @@ bool DockCalc::sampleForwardApproach( const double angle = start_angle + ratio * angle_delta; const double longitudinal = center_longitudinal + curve_radius * std::cos(angle); const double local_lateral = center_lateral + curve_radius * std::sin(angle); - const double tangent_yaw = normalizeAngle(goal_yaw + angle + - turn_sign * kPi / 2.0); - appendUnique(path, poseFromDockCoordinates(goal, goal_yaw, + const double tangent_yaw = normalizeAngle(approach_yaw + angle + + turn_sign * kPi / 2.0 + + heading_offset); + appendUnique(path, poseFromDockCoordinates(goal, approach_yaw, longitudinal, local_lateral, tangent_yaw)); } @@ -258,11 +263,124 @@ bool DockCalc::sampleForwardApproach( path.front().position = start.position; path.back() = cusp; - path.back().orientation = data_convert::createQuaternionMsgFromYaw(goal_yaw); + path.back().orientation = data_convert::createQuaternionMsgFromYaw(lead_in_yaw); return true; } -bool DockCalc::sampleReverseTerminal( +bool DockCalc::sampleDirectEntry( + const robot_geometry_msgs::Pose& start, + const robot_geometry_msgs::Pose& goal, + double approach_yaw, + double heading_offset, + double start_longitudinal, + double start_lateral, + double straight_distance, + double minimum_turning_radius, + std::vector& path, + double& curve_radius) const +{ + path.clear(); + curve_radius = std::numeric_limits::infinity(); + + // Room left between the robot and the start of the straight terminal. The + // caller already applied its own threshold; this only rejects the degenerate + // case where the robot has already driven past the entry point. + const double curve_room = start_longitudinal - straight_distance; + if (!std::isfinite(curve_room) || curve_room <= kEpsilon) + { + return false; + } + + const robot_geometry_msgs::Pose entry = + offsetPoint(goal, approach_yaw, straight_distance); + // One travel direction for the whole path, so the body yaw at every sample is + // the same one the terminal uses. + const double body_yaw = normalizeAngle(approach_yaw + heading_offset); + const double lateral = std::fabs(start_lateral); + + if (lateral <= kEpsilon) + { + // Already on the dock axis: the entry arc degenerates and the terminal + // simply continues the same line, so the robot drives straight in. + const double line_length = distance(start, entry); + const int sample_count = std::max( + 1, static_cast(std::ceil(line_length / config_.path_point_spacing))); + path.reserve(static_cast(sample_count + 1)); + for (int index = 0; index <= sample_count; ++index) + { + const double ratio = static_cast(index) / sample_count; + robot_geometry_msgs::Pose pose; + pose.position.x = start.position.x + ratio * (entry.position.x - start.position.x); + pose.position.y = start.position.y + ratio * (entry.position.y - start.position.y); + pose.position.z = start.position.z + ratio * (entry.position.z - start.position.z); + pose.orientation = data_convert::createQuaternionMsgFromYaw(body_yaw); + appendUnique(path, pose); + } + return path.size() >= 2; + } + + curve_radius = (curve_room * curve_room + lateral * lateral) / (2.0 * lateral); + if (!std::isfinite(curve_radius) || + curve_radius + 1e-7 < minimum_turning_radius) + { + return false; + } + + const double turn_sign = start_lateral > 0.0 ? 1.0 : -1.0; + const double center_longitudinal = straight_distance; + const double center_lateral = turn_sign * curve_radius; + const double start_angle = std::atan2(start_lateral - center_lateral, + start_longitudinal - center_longitudinal); + const double end_angle = -turn_sign * kPi / 2.0; + + // Mirror of the lead-in sweep. There the cusp sits BEYOND the robot, so the + // arc is traversed away from the dock; here the entry point sits BETWEEN the + // robot and the dock, so the short way round is the opposite one. Using the + // lead-in convention would pick the complementary sweep and be rejected as + // larger than pi. + const double angle_delta = turn_sign > 0.0 + ? -positiveAngle(start_angle - end_angle) + : positiveAngle(end_angle - start_angle); + + // A tangent arc that converges onto the axis from one side never needs more + // than a quarter turn; anything larger means the geometry is inconsistent. + if (!std::isfinite(angle_delta) || std::fabs(angle_delta) <= kEpsilon || + std::fabs(angle_delta) > kPi / 2.0 + 1e-7) + { + return false; + } + + const double arc_length = curve_radius * std::fabs(angle_delta); + const int sample_count = std::max( + 2, static_cast(std::ceil(arc_length / config_.path_point_spacing))); + path.reserve(static_cast(sample_count + 1)); + for (int index = 0; index <= sample_count; ++index) + { + const double ratio = static_cast(index) / sample_count; + const double angle = start_angle + ratio * angle_delta; + const double longitudinal = center_longitudinal + curve_radius * std::cos(angle); + const double local_lateral = center_lateral + curve_radius * std::sin(angle); + const double tangent_yaw = normalizeAngle(approach_yaw + angle + + turn_sign * kPi / 2.0 + + heading_offset); + appendUnique(path, poseFromDockCoordinates(goal, approach_yaw, + longitudinal, local_lateral, + tangent_yaw)); + } + + if (path.size() < 2) + { + path.clear(); + return false; + } + + path.front().position = start.position; + path.back() = entry; + path.back().orientation = data_convert::createQuaternionMsgFromYaw(body_yaw); + return true; +} + +bool DockCalc::sampleTerminal( const robot_geometry_msgs::Pose& cusp, const robot_geometry_msgs::Pose& goal, double goal_yaw, @@ -325,83 +443,186 @@ bool DockCalc::makePlanMoveToDock( } const RobotGeometry robot = computeGeometry(footprint_robot); - if (robot.length <= kEpsilon || robot.width <= kEpsilon || - robot.rear_extent <= kEpsilon) + if (robot.length <= kEpsilon || robot.width <= kEpsilon) { robot::log_error("[dock_calc] Robot footprint is missing or geometrically invalid.\n"); return false; } + // Logged on every plan on purpose. The footprint is pushed in at runtime by + // the host (AmrController reads the "footprint" rosparam and calls + // setRobotFootprint before initialize()) and silently falls back to the + // costmap YAML when that push does not happen. On APM the two differ by more + // than a metre at the front, and that difference moves the cusp by the same + // amount, so the numbers actually used have to be visible in the log. + robot::log_info( + "[dock_calc] Robot footprint: %zu points, length=%.3f m, width=%.3f m, " + "front_extent=%.3f m, rear_extent=%.3f m.\n", + footprint_robot.size(), robot.length, robot.width, + robot.front_extent, robot.rear_extent); + RobotGeometry dock; - if (config_.dock_anchor == DockAnchor::kCenter && !footprint_dock.empty()) + const bool use_dock_footprint = + config_.dock_anchor == DockAnchor::kCenter && !footprint_dock.empty(); + if (use_dock_footprint) { dock = computeGeometry(footprint_dock); - if (dock.length <= kEpsilon || dock.width <= kEpsilon || dock.front_extent < 0.0) + if (dock.length <= kEpsilon || dock.width <= kEpsilon) { robot::log_error("[dock_calc] Dock footprint is geometrically invalid.\n"); return false; } + robot::log_info( + "[dock_calc] Dock footprint: %zu points, length=%.3f m, width=%.3f m, " + "front_extent=%.3f m, rear_extent=%.3f m.\n", + footprint_dock.size(), dock.length, dock.width, + dock.front_extent, dock.rear_extent); } const double goal_yaw = normalizeAngle(data_convert::getYaw(goal.pose.orientation)); const double relative_x = start.pose.position.x - goal.pose.position.x; const double relative_y = start.pose.position.y - goal.pose.position.y; - const double start_longitudinal = relative_x * std::cos(goal_yaw) + - relative_y * std::sin(goal_yaw); - const double start_lateral = -relative_x * std::sin(goal_yaw) + - relative_y * std::cos(goal_yaw); + const double goal_longitudinal = relative_x * std::cos(goal_yaw) + + relative_y * std::sin(goal_yaw); - // This planner now has one explicit contract: the goal yaw points from the - // dock toward the approach side, and the terminal leg is always reverse. - // Flipping the axis would silently finish with the opposite robot heading. - if (!std::isfinite(start_longitudinal) || start_longitudinal <= kEpsilon) + // Which robot edge mates with the dock is DERIVED, not configured: the goal + // pose is already offset upstream so that base_link lands exactly on it for + // the intended maneuver, so the side the robot stands on carries the intent. + // A single-cusp maneuver can only place its cusp on that side anyway -- the + // other side would need a full loop around the dock. + if (!std::isfinite(goal_longitudinal) || std::fabs(goal_longitudinal) <= kEpsilon) { robot::log_error( - "[dock_calc] Start is not on the reverse-docking side of the goal " - "(longitudinal=%.6f m in goal frame).\n", - start_longitudinal); + "[dock_calc] Start sits on the lateral axis of the goal " + "(longitudinal=%.6f m in goal frame); no docking side can be derived.\n", + goal_longitudinal); + return false; + } + const bool dock_with_front = goal_longitudinal < 0.0; + + // Approach frame: X points from the dock toward the side the robot is on. + // Rotating the goal frame by pi for a front dock leaves every geometry + // formula below untouched; only the body yaw picks up the same pi, because + // the robot then drives the lead-in in reverse and the terminal forward. + const double approach_yaw = + dock_with_front ? normalizeAngle(goal_yaw + kPi) : goal_yaw; + const double heading_offset = dock_with_front ? kPi : 0.0; + const double start_longitudinal = relative_x * std::cos(approach_yaw) + + relative_y * std::sin(approach_yaw); + const double start_lateral = -relative_x * std::sin(approach_yaw) + + relative_y * std::cos(approach_yaw); + + // The edge that faces the dock at the cusp is the one that mates with it: + // the rear when the terminal is driven in reverse, the front when forward. + const double mating_extent = + dock_with_front ? robot.front_extent : robot.rear_extent; + if (!std::isfinite(mating_extent) || mating_extent <= kEpsilon) + { + robot::log_error( + "[dock_calc] Robot %s_extent is %.6f m: the footprint does not extend " + "past base_link on the docking side.\n", + dock_with_front ? "front" : "rear", mating_extent); return false; } - const double dock_extent = config_.dock_anchor == DockAnchor::kCenter - ? dock.front_extent : 0.0; - const double minimum_cusp_distance = robot.rear_extent + dock_extent + + // Same rule for the dock body: the near face is the one on the approach side. + const double dock_extent = + !use_dock_footprint ? 0.0 + : (dock_with_front ? dock.rear_extent : dock.front_extent); + if (!std::isfinite(dock_extent) || dock_extent < 0.0) + { + robot::log_error( + "[dock_calc] Dock %s_extent is %.6f m: footprint_dock does not reach the " + "approach side of the goal.\n", + dock_with_front ? "rear" : "front", dock_extent); + return false; + } + + robot::log_info( + "[dock_calc] Docking edge=%s (lead-in drives %s, terminal drives %s), " + "derived from goal-frame longitudinal=%.3f m. Cusp clearance uses robot " + "%s_extent=%.3f m + dock %s_extent=%.3f m + padding=%.3f m.\n", + dock_with_front ? "FRONT" : "REAR", + dock_with_front ? "REVERSE" : "FORWARD", + dock_with_front ? "FORWARD" : "REVERSE", + goal_longitudinal, + dock_with_front ? "front" : "rear", mating_extent, + dock_with_front ? "rear" : "front", dock_extent, + config_.reverse_distance_padding); + + const double minimum_cusp_distance = mating_extent + dock_extent + config_.reverse_distance_padding; if (!std::isfinite(minimum_cusp_distance) || minimum_cusp_distance <= kEpsilon) { robot::log_error( - "[dock_calc] Minimum cusp distance is invalid (rear=%.3f m, dock=%.3f m, " + "[dock_calc] Minimum cusp distance is invalid (mating=%.3f m, dock=%.3f m, " "padding=%.3f m).\n", - robot.rear_extent, dock_extent, config_.reverse_distance_padding); + mating_extent, dock_extent, config_.reverse_distance_padding); return false; } - std::vector forward_segment; - double cusp_distance = 0.0; + // Length of the straight terminal leg. The clearance is a floor, not the + // target: a robot needs a straight run long enough to settle its heading + // before it enters the dock, and that is usually longer than its own overhang. + const double straight_distance = + std::max(minimum_cusp_distance, config_.straight_length); + const double curve_room = start_longitudinal - straight_distance; + + std::vector approach_segment; + double cusp_distance = straight_distance; double curve_radius = 0.0; - if (!sampleForwardApproach(start.pose, goal.pose, goal_yaw, - start_longitudinal, start_lateral, - minimum_cusp_distance, minimum_turning_radius, - forward_segment, cusp_distance, curve_radius)) + bool direct_entry = false; + + // Preferred shape when there is room for it: no direction change at all, so + // the controller never has to detect a cusp, and the robot converges onto the + // dock axis while still far from the dock. + if (config_.direct_entry_min_curve_room > 0.0 && + curve_room > config_.direct_entry_min_curve_room) { - robot::log_error("[dock_calc] Failed to generate the forward approach segment.\n"); + direct_entry = sampleDirectEntry(start.pose, goal.pose, approach_yaw, + heading_offset, start_longitudinal, + start_lateral, straight_distance, + minimum_turning_radius, approach_segment, + curve_radius); + if (!direct_entry) + { + approach_segment.clear(); + const double lateral = std::fabs(start_lateral); + const double radicand = 2.0 * minimum_turning_radius * lateral - + lateral * lateral; + robot::log_info( + "[dock_calc] Direct entry does not fit (curve room=%.3f m, lateral=%.3f m " + "needs >= %.3f m at min_radius=%.3f m); planning the single-cusp " + "maneuver instead.\n", + curve_room, start_lateral, + radicand > 0.0 ? std::sqrt(radicand) : 0.0, minimum_turning_radius); + } + } + + if (!direct_entry && + !sampleLeadIn(start.pose, goal.pose, approach_yaw, heading_offset, + start_longitudinal, start_lateral, + straight_distance, minimum_turning_radius, + approach_segment, cusp_distance, curve_radius)) + { + robot::log_error("[dock_calc] Failed to generate the lead-in segment.\n"); return false; } - std::vector reverse_segment; - if (!sampleReverseTerminal(forward_segment.back(), goal.pose, goal_yaw, - reverse_segment)) + std::vector terminal_segment; + if (!sampleTerminal(approach_segment.back(), goal.pose, goal_yaw, + terminal_segment)) { - robot::log_error("[dock_calc] Failed to generate the reverse terminal segment.\n"); + robot::log_error("[dock_calc] Failed to generate the straight terminal segment.\n"); return false; } - plan.reserve(forward_segment.size() + reverse_segment.size()); - for (const auto& pose : forward_segment) + plan.reserve(approach_segment.size() + terminal_segment.size()); + for (const auto& pose : approach_segment) { appendUnique(plan, pose); } - for (const auto& pose : reverse_segment) + for (const auto& pose : terminal_segment) { appendUnique(plan, pose); } @@ -415,12 +636,19 @@ bool DockCalc::makePlanMoveToDock( plan.back() = goal.pose; robot::log_info( - "[dock_calc] Generated forward-then-reverse path: poses=%zu, " - "wheel_base=%.4f m, max_steer=%.4f rad, min_radius=%.4f m, " - "start=(long=%.3f m, lateral=%.3f m), cusp=%.3f m, arc_radius=%.4f m.\n", - plan.size(), config_.wheel_base, config_.max_steering_angle, + "[dock_calc] Generated %s-edge %s dock path: poses=%zu, approach=%zu (%s), " + "terminal=%zu (%s straight %.3f m), wheel_base=%.4f m, max_steer=%.4f rad, " + "min_radius=%.4f m, start=(long=%.3f m, lateral=%.3f m in approach frame), " + "curve room=%.3f m, arc_radius=%.4f m.\n", + dock_with_front ? "front" : "rear", + direct_entry ? "direct (no cusp)" : "single-cusp", + plan.size(), approach_segment.size(), + direct_entry ? (dock_with_front ? "forward" : "reverse") + : (dock_with_front ? "reverse" : "forward"), + terminal_segment.size(), dock_with_front ? "forward" : "reverse", + cusp_distance, config_.wheel_base, config_.max_steering_angle, minimum_turning_radius, start_longitudinal, start_lateral, - cusp_distance, curve_radius); + curve_room, curve_radius); return true; } diff --git a/src/dock_planner.cpp b/src/dock_planner.cpp index 739f7f1..235db09 100644 --- a/src/dock_planner.cpp +++ b/src/dock_planner.cpp @@ -207,7 +207,8 @@ bool DockPlanner::initialize(std::string name, initialized_ = true; robot::log_info( - "[dock_planner] Initialized forward-then-reverse maneuver: TF %s -> %s, " + "[dock_planner] Initialized single-cusp dock maneuver (docking edge is " + "derived per plan from the side the robot stands on): TF %s -> %s, " "wheel_base=%.4f m, max_steering_angle=%.4f rad, minimum_turning_radius=%.4f m.\n", loaded_config.front_axle_frame.c_str(), loaded_config.rear_axle_frame.c_str(), loaded_config.wheel_base, loaded_config.max_steering_angle, diff --git a/src/dock_planner_config.cpp b/src/dock_planner_config.cpp index dd2f60d..f551d61 100644 --- a/src/dock_planner_config.cpp +++ b/src/dock_planner_config.cpp @@ -99,6 +99,10 @@ bool DockPlannerConfig::load(const robot::NodeHandle& nh, DockPlannerConfig& con loaded.minimum_forward_distance, error) || !readOptionalDouble(nh, "maneuver/maximum_forward_extension", loaded.maximum_forward_extension, error) || + !readOptionalDouble(nh, "terminal/straight_length", + loaded.straight_length, error) || + !readOptionalDouble(nh, "maneuver/direct_entry_min_curve_room", + loaded.direct_entry_min_curve_room, error) || !readOptionalDouble(nh, "sampling/path_point_spacing", loaded.path_point_spacing, error)) { @@ -130,8 +134,10 @@ bool DockPlannerConfig::validate(std::string& error) const {"kinematics/max_steering_angle", max_steering_angle}, {"kinematics/wheel_base", wheel_base}, {"terminal/reverse_distance_padding", reverse_distance_padding}, + {"terminal/straight_length", straight_length}, {"maneuver/minimum_forward_distance", minimum_forward_distance}, {"maneuver/maximum_forward_extension", maximum_forward_extension}, + {"maneuver/direct_entry_min_curve_room", direct_entry_min_curve_room}, {"sampling/path_point_spacing", path_point_spacing}, }; @@ -168,6 +174,17 @@ bool DockPlannerConfig::validate(std::string& error) const error = "parameter 'terminal/reverse_distance_padding' must be >= 0 m"; return false; } + if (straight_length < 0.0) + { + error = "parameter 'terminal/straight_length' must be >= 0 m"; + return false; + } + if (direct_entry_min_curve_room < 0.0) + { + error = "parameter 'maneuver/direct_entry_min_curve_room' must be >= 0 m " + "(0 disables the direct entry)"; + return false; + } if (minimum_forward_distance <= 0.0) { error = "parameter 'maneuver/minimum_forward_distance' must be > 0 m"; diff --git a/src/utils/dubins.cpp b/src/utils/dubins.cpp new file mode 100644 index 0000000..89374ac --- /dev/null +++ b/src/utils/dubins.cpp @@ -0,0 +1,322 @@ +#include "dock_planner/utils/dubins.h" + +#include +#include +#include + +namespace dock_planner +{ +namespace dubins +{ +namespace +{ + +constexpr double kPi = 3.14159265358979323846; +constexpr double kTwoPi = 2.0 * kPi; +constexpr double kEpsilon = 1e-9; + +/** Wrap to [0, 2*pi). The Dubins word equations are written in this range. */ +double positiveAngle(double angle) +{ + angle = std::fmod(angle, kTwoPi); + return angle < 0.0 ? angle + kTwoPi : angle; +} + +/** One candidate word: three normalised parameters plus the segment types. */ +struct Word +{ + bool valid = false; + std::array types{SegmentType::kStraight, SegmentType::kStraight, + SegmentType::kStraight}; + double t = 0.0; // first segment, radians for a turn / normalised length for a straight + double p = 0.0; // middle segment + double q = 0.0; // last segment + + double cost() const + { + return valid ? t + p + q : std::numeric_limits::infinity(); + } +}; + +/** + * The six words in the normalised frame: start at the origin heading @p alpha, + * goal at distance @p d heading @p beta, unit turning radius. + * + * Kept as one function per word rather than a table: each has its own + * feasibility test, and a shared skeleton would hide which test belongs to which. + */ +Word wordLSL(double alpha, double beta, double d) +{ + const double sa = std::sin(alpha), sb = std::sin(beta); + const double ca = std::cos(alpha), cb = std::cos(beta); + const double c_ab = std::cos(alpha - beta); + + const double p_sq = 2.0 + d * d - 2.0 * c_ab + 2.0 * d * (sa - sb); + Word word; + word.types = {SegmentType::kLeft, SegmentType::kStraight, SegmentType::kLeft}; + if (p_sq < 0.0) + { + return word; + } + const double tmp = std::atan2(cb - ca, d + sa - sb); + word.valid = true; + word.t = positiveAngle(tmp - alpha); + word.p = std::sqrt(p_sq); + word.q = positiveAngle(beta - tmp); + return word; +} + +Word wordRSR(double alpha, double beta, double d) +{ + const double sa = std::sin(alpha), sb = std::sin(beta); + const double ca = std::cos(alpha), cb = std::cos(beta); + const double c_ab = std::cos(alpha - beta); + + const double p_sq = 2.0 + d * d - 2.0 * c_ab + 2.0 * d * (sb - sa); + Word word; + word.types = {SegmentType::kRight, SegmentType::kStraight, SegmentType::kRight}; + if (p_sq < 0.0) + { + return word; + } + const double tmp = std::atan2(ca - cb, d - sa + sb); + word.valid = true; + word.t = positiveAngle(alpha - tmp); + word.p = std::sqrt(p_sq); + word.q = positiveAngle(tmp - beta); + return word; +} + +Word wordLSR(double alpha, double beta, double d) +{ + const double sa = std::sin(alpha), sb = std::sin(beta); + const double ca = std::cos(alpha), cb = std::cos(beta); + const double c_ab = std::cos(alpha - beta); + + const double p_sq = -2.0 + d * d + 2.0 * c_ab + 2.0 * d * (sa + sb); + Word word; + word.types = {SegmentType::kLeft, SegmentType::kStraight, SegmentType::kRight}; + if (p_sq < 0.0) + { + return word; + } + word.p = std::sqrt(p_sq); + const double tmp = std::atan2(-ca - cb, d + sa + sb) - std::atan2(-2.0, word.p); + word.valid = true; + word.t = positiveAngle(tmp - alpha); + word.q = positiveAngle(tmp - positiveAngle(beta)); + return word; +} + +Word wordRSL(double alpha, double beta, double d) +{ + const double sa = std::sin(alpha), sb = std::sin(beta); + const double ca = std::cos(alpha), cb = std::cos(beta); + const double c_ab = std::cos(alpha - beta); + + const double p_sq = d * d - 2.0 + 2.0 * c_ab - 2.0 * d * (sa + sb); + Word word; + word.types = {SegmentType::kRight, SegmentType::kStraight, SegmentType::kLeft}; + if (p_sq < 0.0) + { + return word; + } + word.p = std::sqrt(p_sq); + const double tmp = std::atan2(ca + cb, d - sa - sb) - std::atan2(2.0, word.p); + word.valid = true; + word.t = positiveAngle(alpha - tmp); + word.q = positiveAngle(beta - tmp); + return word; +} + +Word wordRLR(double alpha, double beta, double d) +{ + const double sa = std::sin(alpha), sb = std::sin(beta); + const double ca = std::cos(alpha), cb = std::cos(beta); + const double c_ab = std::cos(alpha - beta); + + const double tmp = (6.0 - d * d + 2.0 * c_ab + 2.0 * d * (sa - sb)) / 8.0; + Word word; + word.types = {SegmentType::kRight, SegmentType::kLeft, SegmentType::kRight}; + if (std::fabs(tmp) > 1.0) + { + return word; + } + word.valid = true; + word.p = positiveAngle(kTwoPi - std::acos(tmp)); + word.t = positiveAngle(alpha - std::atan2(ca - cb, d - sa + sb) + word.p / 2.0); + word.q = positiveAngle(alpha - beta - word.t + word.p); + return word; +} + +Word wordLRL(double alpha, double beta, double d) +{ + const double sa = std::sin(alpha), sb = std::sin(beta); + const double ca = std::cos(alpha), cb = std::cos(beta); + const double c_ab = std::cos(alpha - beta); + + const double tmp = (6.0 - d * d + 2.0 * c_ab + 2.0 * d * (sb - sa)) / 8.0; + Word word; + word.types = {SegmentType::kLeft, SegmentType::kRight, SegmentType::kLeft}; + if (std::fabs(tmp) > 1.0) + { + return word; + } + word.valid = true; + word.p = positiveAngle(kTwoPi - std::acos(tmp)); + word.t = positiveAngle(-alpha - std::atan2(ca - cb, d + sa - sb) + word.p / 2.0); + word.q = positiveAngle(positiveAngle(beta) - alpha - word.t + word.p); + return word; +} + +/** Advance one segment. @p length is metres for a straight, radians for a turn. */ +Pose2D advance(const Pose2D& from, SegmentType type, double length, double radius) +{ + Pose2D to = from; + switch (type) + { + case SegmentType::kLeft: + to.x = from.x + radius * (std::sin(from.yaw + length) - std::sin(from.yaw)); + to.y = from.y - radius * (std::cos(from.yaw + length) - std::cos(from.yaw)); + to.yaw = from.yaw + length; + break; + case SegmentType::kRight: + to.x = from.x - radius * (std::sin(from.yaw - length) - std::sin(from.yaw)); + to.y = from.y + radius * (std::cos(from.yaw - length) - std::cos(from.yaw)); + to.yaw = from.yaw - length; + break; + case SegmentType::kStraight: + to.x = from.x + length * std::cos(from.yaw); + to.y = from.y + length * std::sin(from.yaw); + break; + } + return to; +} + +/** Turn angle [rad] a segment consumes; 0 for a straight. */ +double turnAngle(SegmentType type, double length, double radius) +{ + return type == SegmentType::kStraight ? 0.0 : length / radius; +} + +} // namespace + +double Path::length() const +{ + return valid ? lengths[0] + lengths[1] + lengths[2] : 0.0; +} + +double normalizeAngle(double angle) +{ + angle = std::fmod(angle + kPi, kTwoPi); + if (angle <= 0.0) + { + angle += kTwoPi; + } + return angle - kPi; +} + +Path shortestPath(const Pose2D& start, const Pose2D& goal, double radius) +{ + Path result; + if (!std::isfinite(start.x) || !std::isfinite(start.y) || !std::isfinite(start.yaw) || + !std::isfinite(goal.x) || !std::isfinite(goal.y) || !std::isfinite(goal.yaw) || + !std::isfinite(radius) || radius <= kEpsilon) + { + return result; + } + + const double dx = goal.x - start.x; + const double dy = goal.y - start.y; + const double distance = std::hypot(dx, dy); + const double d = distance / radius; + // Bearing is meaningless when the poses coincide; any value works because + // alpha and beta then differ only by the yaw change, which every word still + // resolves. Using the start yaw keeps alpha at zero and the words stable. + const double bearing = distance > kEpsilon ? std::atan2(dy, dx) : start.yaw; + const double alpha = positiveAngle(start.yaw - bearing); + const double beta = positiveAngle(goal.yaw - bearing); + + const Word words[] = { + wordLSL(alpha, beta, d), wordRSR(alpha, beta, d), wordLSR(alpha, beta, d), + wordRSL(alpha, beta, d), wordRLR(alpha, beta, d), wordLRL(alpha, beta, d), + }; + + const Word* best = nullptr; + for (const Word& word : words) + { + if (word.valid && (best == nullptr || word.cost() < best->cost())) + { + best = &word; + } + } + if (best == nullptr || !std::isfinite(best->cost())) + { + return result; + } + + result.valid = true; + result.types = best->types; + result.radius = radius; + // Normalised parameters become metres the same way for both kinds: a turn of + // t radians at this radius covers r*t, and a straight of p normalised units + // covers r*p because the frame was scaled by the radius. + result.lengths = {best->t * radius, best->p * radius, best->q * radius}; + return result; +} + +std::vector sample(const Path& path, const Pose2D& start, const Pose2D& goal, + double spacing) +{ + std::vector samples; + if (!path.valid || !std::isfinite(spacing) || spacing <= 0.0) + { + return samples; + } + + const double total = path.length(); + samples.reserve(static_cast(total / spacing) + 4); + samples.push_back(start); + + Pose2D cursor = start; + for (std::size_t index = 0; index < path.types.size(); ++index) + { + const SegmentType type = path.types[index]; + const double segment_length = path.lengths[index]; + if (!(segment_length > kEpsilon)) + { + continue; + } + + const int steps = std::max(1, static_cast(std::ceil(segment_length / spacing))); + for (int step = 1; step <= steps; ++step) + { + const double travelled = segment_length * static_cast(step) / + static_cast(steps); + const double parameter = type == SegmentType::kStraight + ? travelled + : turnAngle(type, travelled, path.radius); + samples.push_back(advance(cursor, type, parameter, path.radius)); + } + const double parameter = type == SegmentType::kStraight + ? segment_length + : turnAngle(type, segment_length, path.radius); + cursor = advance(cursor, type, parameter, path.radius); + } + + // The caller's contract is about the goal pose, not about the integration of + // three segments. Snapping the last sample keeps a downstream equality test + // meaningful instead of chasing accumulated rounding. + if (!samples.empty()) + { + samples.back() = goal; + } + for (Pose2D& pose : samples) + { + pose.yaw = normalizeAngle(pose.yaw); + } + return samples; +} + +} // namespace dubins +} // namespace dock_planner diff --git a/test/dock_planner_test.cpp b/test/dock_planner_test.cpp index f03ed09..cc7f641 100644 --- a/test/dock_planner_test.cpp +++ b/test/dock_planner_test.cpp @@ -102,16 +102,26 @@ double threePointCurvature(const robot_geometry_msgs::Pose& first, return 2.0 * twice_area / (ab * bc * ac); } -std::size_t checkForwardThenReverse( +/** + * @brief Assert the single-cusp contract: one curved lead-in, one direction + * change, then a straight terminal on the goal axis. + * + * @param terminal_forward true when the terminal leg is driven forward (front + * edge docks, e.g. a charging contact), false when it is driven in + * reverse (rear edge docks, e.g. forks into a pallet). The lead-in + * always runs in the opposite direction. + */ +std::size_t checkSingleCuspPath( const std::vector& path, const robot_geometry_msgs::Pose& goal, - double maximum_curvature) + double maximum_curvature, + bool terminal_forward) { CHECK(path.size() > 3); std::size_t cusp_index = path.size(); int direction_changes = 0; bool previous_forward = edgeIsForward(path[0], path[1]); - CHECK(previous_forward); + CHECK(previous_forward != terminal_forward); for (std::size_t index = 1; index + 1 < path.size(); ++index) { @@ -130,11 +140,11 @@ std::size_t checkForwardThenReverse( for (std::size_t index = 0; index < cusp_index; ++index) { - CHECK(edgeIsForward(path[index], path[index + 1])); + CHECK(edgeIsForward(path[index], path[index + 1]) != terminal_forward); } for (std::size_t index = cusp_index; index + 1 < path.size(); ++index) { - CHECK(!edgeIsForward(path[index], path[index + 1])); + CHECK(edgeIsForward(path[index], path[index + 1]) == terminal_forward); CHECK(std::fabs(lateral(path[index], goal)) < 1e-7); CHECK(std::fabs(normalizeAngle( data_convert::getYaw(path[index].orientation) - @@ -149,6 +159,49 @@ std::size_t checkForwardThenReverse( return cusp_index; } +/** + * @brief Assert the no-cusp contract: one travel direction for the whole path, + * curvature within the Ackermann limit, and a straight tail on the goal + * axis at least @p straight_distance long. + */ +void checkDirectEntry(const std::vector& path, + const robot_geometry_msgs::Pose& goal, + double maximum_curvature, + bool terminal_forward, + double straight_distance) +{ + CHECK(path.size() > 3); + for (std::size_t index = 0; index + 1 < path.size(); ++index) + { + CHECK(edgeIsForward(path[index], path[index + 1]) == terminal_forward); + } + for (std::size_t index = 1; index + 1 < path.size(); ++index) + { + CHECK(threePointCurvature(path[index - 1], path[index], path[index + 1]) <= + maximum_curvature + 1e-5); + } + + std::size_t entry_index = path.size(); + for (std::size_t index = 0; index < path.size(); ++index) + { + if (std::fabs(lateral(path[index], goal)) < 1e-7) + { + entry_index = index; + break; + } + } + CHECK(entry_index + 1 < path.size()); + // Once the path reaches the axis it must stay on it, pointing at the goal. + for (std::size_t index = entry_index; index < path.size(); ++index) + { + CHECK(std::fabs(lateral(path[index], goal)) < 1e-7); + CHECK(std::fabs(normalizeAngle( + data_convert::getYaw(path[index].orientation) - + data_convert::getYaw(goal.orientation))) < 1e-7); + } + CHECK(std::fabs(longitudinal(path[entry_index], goal)) >= straight_distance - 1e-6); +} + std::vector generatePath( dock_planner::DockCalc& calculator, const robot_geometry_msgs::PoseStamped& start, @@ -187,6 +240,9 @@ dock_planner::DockPlannerConfig apmConfig() config.wheel_base = 1.3268; config.max_steering_angle = 0.50; config.path_point_spacing = 0.05; + // The cusp cases below have to keep exercising the cusp: several of their + // starts are far enough that the direct entry would take over. + config.direct_entry_min_curve_room = 0.0; return config; } @@ -235,8 +291,8 @@ void testPathGeneration() { const auto path = generatePath(calculator, start, goal, robot_footprint, dock_footprint); - const std::size_t cusp = checkForwardThenReverse(path, goal.pose, - maximum_curvature); + const std::size_t cusp = checkSingleCuspPath(path, goal.pose, + maximum_curvature, false); CHECK(longitudinal(path[cusp], goal.pose) > longitudinal(start.pose, goal.pose)); CHECK(std::fabs(normalizeAngle( data_convert::getYaw(path.front().orientation) - @@ -247,16 +303,33 @@ void testPathGeneration() const auto rotated_path = generatePath( calculator, pose(0.6, 2.8, 0.0), rotated_goal, robot_footprint, dock_footprint); - checkForwardThenReverse(rotated_path, rotated_goal.pose, maximum_curvature); + checkSingleCuspPath(rotated_path, rotated_goal.pose, maximum_curvature, false); // The previous projection<=1 failure is now valid: the robot first drives // away from the dock until the curvature-safe cusp, then reverses straight. const auto close_path = generatePath(calculator, pose(0.8, 0.2, 0.0), goal, robot_footprint, dock_footprint); - checkForwardThenReverse(close_path, goal.pose, maximum_curvature); + checkSingleCuspPath(close_path, goal.pose, maximum_curvature, false); + // Standing on the far side of the goal is no longer an error: the docking + // edge is derived from the side the robot is on, so the same geometry runs + // mirrored -- reverse lead-in, then a straight FORWARD terminal. This is the + // charging-contact case (APM mates with the front of the robot). + const auto front_path = generatePath(calculator, pose(-2.8, 0.6, 0.0), goal, + robot_footprint, dock_footprint); + const std::size_t front_cusp = + checkSingleCuspPath(front_path, goal.pose, maximum_curvature, true); + // The cusp must sit on the far side of the goal from the rear-dock cases, + // and the clearance must come from front_extent (1.65 m) plus the dock's + // near face (0.50 m), not from rear_extent (0.35 m). + CHECK(longitudinal(front_path[front_cusp], goal.pose) < 0.0); + CHECK(std::fabs(longitudinal(front_path[front_cusp], goal.pose)) >= 2.15); + CHECK(std::fabs(lateral(front_path[front_cusp], goal.pose)) < 1e-7); + + // A start exactly on the goal's lateral axis belongs to neither side, so no + // docking edge can be derived and the plan must be refused. std::vector path; - CHECK(!calculator.makePlanMoveToDock(pose(-2.8, 0.6, 0.0), goal, + CHECK(!calculator.makePlanMoveToDock(pose(0.0, 0.6, 0.0), goal, robot_footprint, dock_footprint, path)); CHECK(path.empty()); @@ -275,6 +348,75 @@ void testPathGeneration() CHECK(path.empty()); } +void testDirectEntry() +{ + dock_planner::DockPlannerConfig config = apmConfig(); + config.direct_entry_min_curve_room = 0.5; + dock_planner::DockCalc calculator(config); + + const std::vector robot_footprint = { + point(1.65, -0.40), point(1.65, 0.40), + point(-0.35, 0.40), point(-0.35, -0.40)}; + const std::vector dock_footprint = { + point(0.50, -0.40), point(0.50, 0.40), + point(-0.50, 0.40), point(-0.50, -0.40)}; + + const auto goal = pose(0.0, 0.0, 0.0); + const double maximum_curvature = 1.0 / config.minimumTurningRadius(); + + // Rear edge: clearance 0.35 (rear_extent) + 0.50 (dock near face) = 0.85 m, + // so a start 2.8 m out leaves 1.95 m of curve room against the 1.598 m the + // 0.60 m lateral offset needs at min_radius 2.4287 m. The whole path reverses. + const double rear_straight = 0.35 + 0.50; + for (const auto& start : {pose(2.8, 0.6, -1.2), pose(2.8, -0.6, 1.2)}) + { + const auto direct_path = generatePath(calculator, start, goal, + robot_footprint, dock_footprint); + checkDirectEntry(direct_path, goal.pose, maximum_curvature, false, + rear_straight); + } + + // Already on the dock axis: the arc degenerates and the robot drives one + // straight line all the way in, instead of the pointless drive-away-and-back + // the cusp maneuver would produce. + const auto aligned_path = generatePath(calculator, pose(2.8, 0.0, 0.5), goal, + robot_footprint, dock_footprint); + checkDirectEntry(aligned_path, goal.pose, maximum_curvature, false, + rear_straight); + for (const auto& sample : aligned_path) + { + CHECK(std::fabs(lateral(sample, goal.pose)) < 1e-7); + } + + // Front edge: clearance 1.65 (front_extent) + 0.50 = 2.15 m, so the start has + // to be much farther out for the arc to fit. The whole path drives forward. + const double front_straight = 1.65 + 0.50; + const auto front_direct = generatePath(calculator, pose(-4.0, 0.6, 0.0), goal, + robot_footprint, dock_footprint); + checkDirectEntry(front_direct, goal.pose, maximum_curvature, true, + front_straight); + + // Enough room to pass the threshold (1.15 m > 0.50 m) but not enough for the + // radius (needs 1.598 m), so the planner must fall back to the cusp rather + // than emit an arc tighter than the steering limit. + const auto fallback_path = generatePath(calculator, pose(2.0, 0.6, 0.0), goal, + robot_footprint, dock_footprint); + checkSingleCuspPath(fallback_path, goal.pose, maximum_curvature, false); + + // Too close for a straight terminal of its own length: still a cusp. + const auto close_path = generatePath(calculator, pose(1.0, 0.2, 0.0), goal, + robot_footprint, dock_footprint); + checkSingleCuspPath(close_path, goal.pose, maximum_curvature, false); + + // A longer requested straight terminal eats the curve room, so the same start + // that took the direct entry above falls back to the cusp. + config.straight_length = 2.5; + calculator.setConfig(config); + const auto long_terminal = generatePath(calculator, pose(2.8, 0.6, -1.2), goal, + robot_footprint, dock_footprint); + checkSingleCuspPath(long_terminal, goal.pose, maximum_curvature, false); +} + bool pathsEqual(const std::vector& first, const std::vector& second) { @@ -363,6 +505,7 @@ int main() { testConfig(); testPathGeneration(); + testDirectEntry(); testAsymmetricFootprint(); testDockAnchor(); if (failures != 0)