Carma-platform v4.11.0
CARMA Platform is built on robot operating system (ROS) and utilizes open source software (OSS) that enables Cooperative Driving Automation (CDA) features to allow Automated Driving Systems to interact and cooperate with infrastructure and other vehicles through communication.
helper_functions.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2021-2024 LEIDOS.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17#include <algorithm>
19
20
21namespace basic_autonomy
22{
23namespace waypoint_generation
24{
25 int get_nearest_point_index(const std::vector<lanelet::BasicPoint2d>& points,
26 const carma_planning_msgs::msg::VehicleState& state)
27 {
28 lanelet::BasicPoint2d veh_point(state.x_pos_global, state.y_pos_global);
29 double min_distance = std::numeric_limits<double>::max();
30 int i = 0;
31 int best_index = 0;
32 for (const auto& p : points)
33 {
34 double distance = lanelet::geometry::distance2d(p, veh_point);
35 if (distance < min_distance)
36 {
37 best_index = i;
38 min_distance = distance;
39 }
40 i++;
41 }
42 return best_index;
43 }
44
45 int get_nearest_point_index(const std::vector<PointSpeedPair>& points,
46 const carma_planning_msgs::msg::VehicleState& state)
47 {
48 lanelet::BasicPoint2d veh_point(state.x_pos_global, state.y_pos_global);
49 RCLCPP_DEBUG_STREAM(rclcpp::get_logger(BASIC_AUTONOMY_LOGGER), "veh_point: " << veh_point.x() << ", " << veh_point.y());
50 double min_distance = std::numeric_limits<double>::max();
51 int i = 0;
52 int best_index = 0;
53 for (const auto& p : points)
54 {
55 double distance = lanelet::geometry::distance2d(p.point, veh_point);
56 if (distance < min_distance)
57 {
58 best_index = i;
59 min_distance = distance;
60 }
61 i++;
62 }
63 return best_index;
64 }
65
67 const std::vector<carma_planning_msgs::msg::TrajectoryPlanPoint>& trajectory,
68 const lanelet::BasicPoint2d& position)
69 {
70 size_t closest_idx = 0;
71 double min_dist = std::numeric_limits<double>::max();
72
73 for (size_t i = 0; i < trajectory.size(); i++)
74 {
75 auto dist = sqrt(pow(position.x() - trajectory.at(i).x, 2) +
76 pow(position.y() - trajectory.at(i).y, 2));
77
78 if (dist < min_dist)
79 {
80 min_dist = dist;
81 closest_idx = i;
82 }
83 }
84
85 return closest_idx;
86 }
87
88 int get_nearest_index_by_downtrack(const std::vector<lanelet::BasicPoint2d>& points, const carma_wm::WorldModelConstPtr& wm, double target_downtrack)
89 {
90 if(std::empty(points)){
91 RCLCPP_WARN_STREAM(rclcpp::get_logger(BASIC_AUTONOMY_LOGGER), "Empty points vector received, returning -1");
92 return -1;
93 }
94
95 // Find first point with a downtrack greater than target_downtrack
96 const auto itr = std::find_if(std::cbegin(points), std::cend(points),
97 [&wm = std::as_const(wm), target_downtrack](const auto & point) { return wm->routeTrackPos(point).downtrack > target_downtrack; });
98
99 int best_index = std::size(points) - 1;
100
101 // Set best_index to the last point with a downtrack less than target_downtrack
102 if(itr != std::cbegin(points)){
103 best_index = std::distance(std::cbegin(points), std::prev(itr));
104 }
105 else{
106 best_index = 0;
107 }
108
109 RCLCPP_DEBUG_STREAM(rclcpp::get_logger(BASIC_AUTONOMY_LOGGER), "get_nearest_index_by_downtrack>> Found best_index: " << best_index<<", points[i].x(): " << points.at(best_index).x() << ", points[i].y(): " << points.at(best_index).y());
110
111 return best_index;
112 }
113
114 void split_point_speed_pairs(const std::vector<PointSpeedPair>& points,
115 std::vector<lanelet::BasicPoint2d>* basic_points,
116 std::vector<double>* speeds)
117 {
118 basic_points->reserve(points.size());
119 speeds->reserve(points.size());
120
121 for (const auto& p : points)
122 {
123 basic_points->push_back(p.point);
124 speeds->push_back(p.speed);
125 }
126 }
127
128 int get_nearest_index_by_downtrack(const std::vector<PointSpeedPair>& points, const carma_wm::WorldModelConstPtr& wm,
129 const carma_planning_msgs::msg::VehicleState& state)
130 {
131 lanelet::BasicPoint2d state_pos(state.x_pos_global, state.y_pos_global);
132 double ending_downtrack = wm->routeTrackPos(state_pos).downtrack;
133 std::vector<lanelet::BasicPoint2d> basic_points;
134 std::vector<double> speeds;
135 split_point_speed_pairs(points, &basic_points, &speeds);
136 return get_nearest_index_by_downtrack(basic_points, wm, ending_downtrack);
137 }
138
139 int get_nearest_index_by_downtrack(const std::vector<lanelet::BasicPoint2d>& points, const carma_wm::WorldModelConstPtr& wm,
140 const carma_planning_msgs::msg::VehicleState& state)
141 {
142 lanelet::BasicPoint2d state_pos(state.x_pos_global, state.y_pos_global);
143 double ending_downtrack = wm->routeTrackPos(state_pos).downtrack;
144 return get_nearest_index_by_downtrack(points, wm, ending_downtrack);
145 }
146
147 std::vector<lanelet::BasicPoint2d> build_chain_centerline(const carma_wm::WorldModelConstPtr &wm,
148 lanelet::ConstLanelet pivot,
149 double backward_length,
150 double forward_length)
151 {
152 std::vector<lanelet::ConstLanelet> chain{pivot};
153 std::unordered_set<lanelet::Id> visited{pivot.id()};
154
155 double covered_back = carma_wm::geometry::get_lanelet_centerline_length(pivot);
156 while (covered_back < backward_length)
157 {
158 auto previous = wm->getMapRoutingGraph()->previous(chain.front(), false);
159 bool no_predecessor = previous.empty();
160 bool loop_detected = !no_predecessor && visited.count(previous.front().id()) > 0;
161
162 if (no_predecessor)
163 {
164 RCLCPP_WARN_STREAM(rclcpp::get_logger(BASIC_AUTONOMY_LOGGER),
165 "create_lanechange_geometry: No routable predecessor lanelet found before lanelet "
166 << chain.front().id() << " (possibly closed or missing from the map). Using the "
167 << covered_back << "m of centerline that was reachable going backward.");
168 }
169
170 if (loop_detected)
171 {
172 RCLCPP_WARN_STREAM(rclcpp::get_logger(BASIC_AUTONOMY_LOGGER),
173 "create_lanechange_geometry: Detected a loop in lanelet connectivity before lanelet "
174 << chain.front().id() << "; stopping centerline extension.");
175 }
176
177 if (no_predecessor || loop_detected)
178 {
179 break;
180 }
181
182 lanelet::ConstLanelet prev = previous.front();
183 visited.insert(prev.id());
185 chain.insert(chain.begin(), prev);
186 }
187
188 double covered_fwd = 0.0;
189 while (covered_fwd < forward_length)
190 {
191 auto following = wm->getMapRoutingGraph()->following(chain.back(), false);
192 bool no_successor = following.empty();
193 bool loop_detected = !no_successor && visited.count(following.front().id()) > 0;
194
195 if (no_successor)
196 {
197 RCLCPP_WARN_STREAM(rclcpp::get_logger(BASIC_AUTONOMY_LOGGER),
198 "create_lanechange_geometry: No routable successor lanelet found after lanelet "
199 << chain.back().id() << " (possibly closed or missing from the map). Using the "
200 << covered_fwd << "m of centerline that was reachable going forward.");
201 }
202
203 if (loop_detected)
204 {
205 RCLCPP_WARN_STREAM(rclcpp::get_logger(BASIC_AUTONOMY_LOGGER),
206 "create_lanechange_geometry: Detected a loop in lanelet connectivity after lanelet "
207 << chain.back().id() << "; stopping centerline extension.");
208 }
209
210 if (no_successor || loop_detected)
211 {
212 break;
213 }
214
215 lanelet::ConstLanelet next = following.front();
216 visited.insert(next.id());
218 chain.push_back(next);
219 }
220
221 std::vector<lanelet::BasicPoint2d> centerline;
222 centerline.reserve(400);
223 for (size_t i = 0; i < chain.size(); ++i)
224 {
225 auto ls = chain[i].centerline2d().basicLineString();
226 if (i == 0)
227 {
228 centerline.insert(centerline.end(), ls.begin(), ls.end());
229 }
230 else
231 {
232 // Concatenate linestring starting from + 1 to avoid duplicating the shared endpoint
233 centerline.insert(centerline.end(), ls.begin() + 1, ls.end());
234 }
235 }
236 return centerline;
237 }
238
239 void extrapolate_to_length(std::vector<lanelet::BasicPoint2d>& centerline, double target_length, const std::string& description)
240 {
241 if (centerline.size() < 2)
242 {
243 throw std::invalid_argument("create_lanechange_geometry: " + description +
244 " has fewer than 2 centerline points; cannot build or extrapolate a lane change trajectory from this map data");
245 }
246
247 double current_length = carma_wm::geometry::compute_arc_lengths(centerline).back();
248 if (current_length >= target_length)
249 {
250 return;
251 }
252
253 RCLCPP_WARN_STREAM(rclcpp::get_logger(BASIC_AUTONOMY_LOGGER),
254 "create_lanechange_geometry: Only " << current_length << "m of connected lanelet centerline was "
255 << "available for " << description << " (needed " << target_length << "m). Extrapolating a "
256 << "straight line from the last known heading so a lane change trajectory can still be produced.");
257
258 lanelet::BasicPoint2d last = centerline.back();
259 lanelet::BasicPoint2d prev = centerline[centerline.size() - 2];
260 lanelet::BasicPoint2d direction = last - prev;
261 if (direction.norm() < 1e-6)
262 {
263 // Degenerate direction from the last segment; fall back to the vector from the first to last point
264 direction = last - centerline.front();
265 }
266 direction.normalize();
267
268 constexpr double step = 1.0; // meters between synthetic points, similar to typical map point spacing
269 double remaining = target_length - current_length;
270 for (int step_count = 1; step_count * step < remaining; ++step_count)
271 {
272 centerline.push_back(last + direction * (step_count * step));
273 }
274 centerline.push_back(last + direction * remaining); // ensure the full requested length is covered
275 }
276
277} // namespace waypoint_generation
278} // namespace basic_autonomy
void split_point_speed_pairs(const std::vector< PointSpeedPair > &points, std::vector< lanelet::BasicPoint2d > *basic_points, std::vector< double > *speeds)
Helper method to split a list of PointSpeedPair into separate point and speed lists.
void extrapolate_to_length(std::vector< lanelet::BasicPoint2d > &centerline, double target_length, const std::string &description)
Pads a centerline out to target_length by extrapolating a straight line from its last known heading,...
static const std::string BASIC_AUTONOMY_LOGGER
std::vector< lanelet::BasicPoint2d > build_chain_centerline(const carma_wm::WorldModelConstPtr &wm, lanelet::ConstLanelet pivot, double backward_length, double forward_length)
Builds a centerline covering [pivot_end_point - backward_length, pivot_end_point + forward_length] by...
int get_nearest_point_index(const std::vector< lanelet::BasicPoint2d > &points, const carma_planning_msgs::msg::VehicleState &state)
Returns the nearest point (in terms of cartesian 2d distance) to the provided vehicle pose in the pro...
int get_nearest_index_by_downtrack(const std::vector< lanelet::BasicPoint2d > &points, const carma_wm::WorldModelConstPtr &wm, double target_downtrack)
Returns the nearest "less than" point to the provided vehicle pose in the provided list by utilizing ...
double get_lanelet_centerline_length(const lanelet::ConstLanelet &ll)
Returns the total 2d arc length of a lanelet's centerline.
Definition: Geometry.cpp:504
std::vector< double > compute_arc_lengths(const std::vector< lanelet::BasicPoint2d > &data)
Compute the arc length at each point around the curve.
Definition: Geometry.cpp:498
std::shared_ptr< const WorldModel > WorldModelConstPtr
Definition: WorldModel.hpp:454