Skip to content

Commit 38d7ba3

Browse files
committed
geometry utils
Signed-off-by: silanus23 <[email protected]>
1 parent 27dab69 commit 38d7ba3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

nav2_util/include/nav2_util/geometry_utils.hpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,51 @@ inline int find_next_matching_goal_in_waypoint_statuses(
188188
return itr - waypoint_statuses.begin();
189189
}
190190

191+
/**
192+
* @brief Find the distance to a point
193+
* @param global_pose Robot's current or planned position
194+
* @param target
195+
* @return int
196+
*/
197+
inline double distanceToPoint(const geometry_msgs::msg::PoseStamped &global_pose,
198+
const geometry_msgs::msg::PoseStamped &target)
199+
{
200+
const double xDist = global_pose.pose.position.x - target.pose.position.x;
201+
const double yDist = global_pose.pose.position.y - target.pose.position.y;
202+
return std::hypot(xDist,yDist);
203+
}
204+
205+
/**
206+
* @brief Find the shortest distance to a vector
207+
* @param global_pose Robot's current or planned position
208+
* @param start Starting point of target vector
209+
* @param finish End point of target vector
210+
* @return int
211+
*/
212+
inline double distanceToSegment(
213+
const geometry_msgs::msg::PoseStamped & point,
214+
const geometry_msgs::msg::PoseStamped & start,
215+
const geometry_msgs::msg::PoseStamped & end)
216+
{
217+
const auto & p = point.pose.position;
218+
const auto & a = start.pose.position;
219+
const auto & b = end.pose.position;
220+
221+
const double seg_len_sq = distanceToPoint(start, end);
222+
if (seg_len_sq <= 1e-8) {
223+
return std::sqrt(distanceToPoint(start, end));
224+
}
225+
226+
const double dot = ((p.x - a.x) * (b.x - a.x)) + ((p.y - a.y) * (b.y - a.y));
227+
const double t = std::clamp(dot / seg_len_sq, 0.0, 1.0);
228+
229+
const double proj_x = a.x + t * (b.x - a.x);
230+
const double proj_y = a.y + t * (b.y - a.y);
231+
232+
const double dx_proj = p.x - proj_x;
233+
const double dy_proj = p.y - proj_y;
234+
return std::hypot(dx_proj,dy_proj);
235+
}
191236
} // namespace geometry_utils
192237
} // namespace nav2_util
193238

0 commit comments

Comments
 (0)