From c2f785d2c7b66795c1a859792bf4eed65ca7e6b9 Mon Sep 17 00:00:00 2001 From: treston Date: Tue, 13 Oct 2026 11:49:33 -0500 Subject: [PATCH] fix(motion_planning): clamp the waypoint angle cosine before acosf (#29141) On an out-and-back leg the dot product of the two unit vectors can round above 1, and acosf then returns NaN, which skipped the turn speed limit so the vehicle reached the turnaround too fast. Co-authored-by: Jacob Dahl --- src/lib/motion_planning/PositionSmoothing.cpp | 6 ++++-- src/lib/motion_planning/TrajectoryConstraints.hpp | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/lib/motion_planning/PositionSmoothing.cpp b/src/lib/motion_planning/PositionSmoothing.cpp index bf7c96151ae..f0ac796b1d9 100644 --- a/src/lib/motion_planning/PositionSmoothing.cpp +++ b/src/lib/motion_planning/PositionSmoothing.cpp @@ -121,8 +121,10 @@ float PositionSmoothing::_getMaxZSpeed(const Vector3f(&waypoints)[3]) const const bool target_next_different = fabsf(target(2) - next_target(2)) > 0.001f; if (target_next_different) { - const float alpha = acosf(Vector2f((target_xy_z - start_position_xy_z)).unit_or_zero().dot( - Vector2f((target_xy_z - next_target_xy_z)).unit_or_zero())); + // rounding can push the dot product of two unit vectors past 1, which acosf turns into NaN + const float cos_alpha = math::constrain(Vector2f((target_xy_z - start_position_xy_z)).unit_or_zero().dot( + Vector2f((target_xy_z - next_target_xy_z)).unit_or_zero()), -1.f, 1.f); + const float alpha = acosf(cos_alpha); const float safe_alpha = math::constrain(alpha, 0.f, M_PI_F - FLT_EPSILON); float accel_tmp = _trajectory[2].getMaxAccel(); diff --git a/src/lib/motion_planning/TrajectoryConstraints.hpp b/src/lib/motion_planning/TrajectoryConstraints.hpp index 9c0fd511799..6deaadc949c 100644 --- a/src/lib/motion_planning/TrajectoryConstraints.hpp +++ b/src/lib/motion_planning/TrajectoryConstraints.hpp @@ -80,8 +80,10 @@ inline float computeStartXYSpeedFromWaypoints(const Vector3f &start_position, co if (target_next_different && !waypoint_overlap ) { - const float alpha = acosf(Vector2f((target - start_position).xy()).unit_or_zero().dot( - Vector2f((target - next_target).xy()).unit_or_zero())); + // rounding can push the dot product of two unit vectors past 1, which acosf turns into NaN + const float cos_alpha = constrain(Vector2f((target - start_position).xy()).unit_or_zero().dot( + Vector2f((target - next_target).xy()).unit_or_zero()), -1.f, 1.f); + const float alpha = acosf(cos_alpha); const float safe_alpha = constrain(alpha, 0.f, M_PI_F - FLT_EPSILON); float accel_tmp = config.max_acc_xy_radius_scale * config.max_acc_xy; float max_speed_in_turn = computeMaxSpeedInWaypoint(safe_alpha, accel_tmp, config.xy_accept_rad);