path.cc 30.9 KB
Newer Older
Z
Zhang Liangliang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

17
#include "modules/map/pnc_map/path.h"
Z
Zhang Liangliang 已提交
18

19
#include <algorithm>
Z
Zhang Liangliang 已提交
20 21 22 23 24 25 26
#include <cstdlib>
#include <limits>
#include <unordered_map>

#include "modules/common/math/line_segment2d.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/math/polygon2d.h"
27
#include "modules/common/math/vec2d.h"
28
#include "modules/common/util/string_util.h"
Z
Zhang Liangliang 已提交
29 30

namespace apollo {
31
namespace hdmap {
Z
Zhang Liangliang 已提交
32

33 34 35 36 37 38
using common::math::LineSegment2d;
using common::math::Polygon2d;
using common::math::Vec2d;
using common::math::Box2d;
using common::math::kMathEpsilon;
using common::math::Sqr;
Z
Zhang Liangliang 已提交
39 40 41 42 43 44
using std::placeholders::_1;

namespace {

const double kSampleDistance = 0.25;

45
bool find_lane_segment(const MapPathPoint& p1, const MapPathPoint& p2,
Z
Zhang Liangliang 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
                       LaneSegment* const lane_segment) {
  for (const auto& wp1 : p1.lane_waypoints()) {
    for (const auto& wp2 : p2.lane_waypoints()) {
      if (wp1.lane->id().id() == wp2.lane->id().id() && wp1.s < wp2.s) {
        *lane_segment = LaneSegment(wp1.lane, wp1.s, wp2.s);
        return true;
      }
    }
  }
  return false;
}

}  // namespace

std::string LaneWaypoint::debug_string() const {
  if (lane == nullptr) {
    return "(lane is null)";
  }
64
  return common::util::StrCat("id = ", lane->id().id(), "  s = ", s);
Z
Zhang Liangliang 已提交
65 66 67 68 69 70
}

std::string LaneSegment::debug_string() const {
  if (lane == nullptr) {
    return "(lane is null)";
  }
71 72 73 74 75 76 77
  return common::util::StrCat("id = ", lane->id().id(),
                              "  "
                              "start_s = ",
                              start_s,
                              "  "
                              "end_s = ",
                              end_s);
Z
Zhang Liangliang 已提交
78 79
}

80
std::string MapPathPoint::debug_string() const {
Z
Zhang Liangliang 已提交
81
  std::ostringstream sout;
82
  sout << "x = " << x_ << "  y = " << y_ << "  heading = " << _heading
Z
Zhang Liangliang 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96
       << "  lwp = {";
  bool first_lwp = true;
  for (const auto& lwp : _lane_waypoints) {
    sout << "(" << lwp.debug_string() << ")";
    if (!first_lwp) {
      sout << ", ";
      first_lwp = false;
    }
  }
  sout << "}";
  sout.flush();
  return sout.str();
}

97
std::string Path::debug_string() const {
Z
Zhang Liangliang 已提交
98 99 100
  std::ostringstream sout;
  sout << "num_points = " << _num_points << "  points = {";
  bool first_point = true;
101
  for (const auto& point : _path_points) {
Z
Zhang Liangliang 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    sout << "(" << point.debug_string() << ")";
    if (!first_point) {
      sout << ", ";
      first_point = false;
    }
  }
  sout << "}  num_lane_segments = " << _lane_segments.size()
       << "  lane_segments = {";
  bool first_segment = true;
  for (const auto& segment : _lane_segments) {
    sout << "(" << segment.debug_string() << ")";
    if (!first_segment) {
      sout << ", ";
      first_segment = false;
    }
  }
  sout << "}";
  sout.flush();
  return sout.str();
}

123
std::string PathOverlap::debug_string() const {
124
  return common::util::StrCat(object_id, " ", start_s, " ", end_s);
Z
Zhang Liangliang 已提交
125 126
}

127 128
Path::Path(const HDMap* hdmap, std::vector<MapPathPoint> path_points)
    : hdmap_(hdmap), _path_points(std::move(path_points)) {
Z
Zhang Liangliang 已提交
129 130 131
  init();
}

132
Path::Path(const HDMap* hdmap, std::vector<MapPathPoint> path_points,
133
           std::vector<LaneSegment> lane_segments)
134 135
    : hdmap_(hdmap),
      _path_points(std::move(path_points)),
Z
Zhang Liangliang 已提交
136 137 138 139
      _lane_segments(std::move(lane_segments)) {
  init();
}

140
Path::Path(const HDMap* hdmap, std::vector<MapPathPoint> path_points,
141 142
           std::vector<LaneSegment> lane_segments,
           const double max_approximation_error)
143 144
    : hdmap_(hdmap),
      _path_points(std::move(path_points)),
Z
Zhang Liangliang 已提交
145 146 147
      _lane_segments(std::move(lane_segments)) {
  init();
  if (max_approximation_error > 0.0) {
D
Dong Li 已提交
148 149
    _use_path_approximation = true;
    _approximation = PathApproximation(*this, max_approximation_error);
Z
Zhang Liangliang 已提交
150 151 152
  }
}

153
void Path::init() {
Z
Zhang Liangliang 已提交
154 155 156 157
  init_points();
  init_lane_segments();
  init_point_index();
  init_width();
J
Jiangtao Hu 已提交
158
  //  init_overlaps();
Z
Zhang Liangliang 已提交
159 160
}

161 162
void Path::init_points() {
  _num_points = static_cast<int>(_path_points.size());
Z
Zhang Liangliang 已提交
163 164 165 166 167 168 169 170 171 172 173
  CHECK_GE(_num_points, 2);

  _accumulated_s.clear();
  _accumulated_s.reserve(_num_points);
  _segments.clear();
  _segments.reserve(_num_points);
  _unit_directions.clear();
  _unit_directions.reserve(_num_points);
  double s = 0.0;
  for (int i = 0; i < _num_points; ++i) {
    _accumulated_s.push_back(s);
174
    Vec2d heading;
Z
Zhang Liangliang 已提交
175
    if (i + 1 >= _num_points) {
176
      heading = _path_points[i] - _path_points[i - 1];
Z
Zhang Liangliang 已提交
177
    } else {
178 179
      _segments.emplace_back(_path_points[i], _path_points[i + 1]);
      heading = _path_points[i + 1] - _path_points[i];
C
Calvin Miao 已提交
180 181
      // TODO(lianglia_apollo):
      // use heading.length when all adjacent lanes are guarantee to be
Z
Zhang Liangliang 已提交
182 183
      // connected.
      LaneSegment lane_segment;
184
      if (find_lane_segment(_path_points[i], _path_points[i + 1],
Z
Zhang Liangliang 已提交
185 186 187
                            &lane_segment)) {
        s += lane_segment.end_s - lane_segment.start_s;
      } else {
188
        s += heading.Length();
Z
Zhang Liangliang 已提交
189 190
      }
    }
191
    heading.Normalize();
Z
Zhang Liangliang 已提交
192 193 194 195 196 197 198 199 200 201 202
    _unit_directions.push_back(heading);
  }
  _length = s;
  _num_sample_points = static_cast<int>(_length / kSampleDistance) + 1;
  _num_segments = _num_points - 1;

  CHECK_EQ(_accumulated_s.size(), _num_points);
  CHECK_EQ(_unit_directions.size(), _num_points);
  CHECK_EQ(_segments.size(), _num_segments);
}

203
void Path::init_lane_segments() {
Z
Zhang Liangliang 已提交
204 205 206 207
  if (_lane_segments.empty()) {
    _lane_segments.reserve(_num_points);
    for (int i = 0; i + 1 < _num_points; ++i) {
      LaneSegment lane_segment;
208
      if (find_lane_segment(_path_points[i], _path_points[i + 1],
Z
Zhang Liangliang 已提交
209 210 211 212 213 214 215 216 217 218
                            &lane_segment)) {
        _lane_segments.push_back(lane_segment);
      }
    }
  }

  _lane_segments_to_next_point.clear();
  _lane_segments_to_next_point.reserve(_num_points);
  for (int i = 0; i + 1 < _num_points; ++i) {
    LaneSegment lane_segment;
219
    if (find_lane_segment(_path_points[i], _path_points[i + 1],
Z
Zhang Liangliang 已提交
220 221 222 223 224 225 226 227 228
                          &lane_segment)) {
      _lane_segments_to_next_point.push_back(lane_segment);
    } else {
      _lane_segments_to_next_point.push_back(LaneSegment());
    }
  }
  CHECK_EQ(_lane_segments_to_next_point.size(), _num_segments);
}

229
void Path::init_width() {
Z
Zhang Liangliang 已提交
230 231 232 233 234 235 236
  _left_width.clear();
  _left_width.reserve(_num_sample_points);
  _right_width.clear();
  _right_width.reserve(_num_sample_points);

  double s = 0;
  for (int i = 0; i < _num_sample_points; ++i) {
237
    const MapPathPoint point = get_smooth_point(s);
Z
Zhang Liangliang 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    if (point.lane_waypoints().empty()) {
      _left_width.push_back(0.0);
      _right_width.push_back(0.0);
    } else {
      const LaneWaypoint waypoint = point.lane_waypoints()[0];
      CHECK_NOTNULL(waypoint.lane);
      double left_width = 0.0;
      double right_width = 0.0;
      waypoint.lane->get_width(waypoint.s, &left_width, &right_width);
      _left_width.push_back(left_width);
      _right_width.push_back(right_width);
    }
    s += kSampleDistance;
  }
  CHECK_EQ(_left_width.size(), _num_sample_points);
  CHECK_EQ(_right_width.size(), _num_sample_points);
}

256
void Path::init_point_index() {
Z
Zhang Liangliang 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  _last_point_index.clear();
  _last_point_index.reserve(_num_sample_points);
  double s = 0.0;
  int last_index = 0;
  for (int i = 0; i < _num_sample_points; ++i) {
    while (last_index + 1 < _num_points &&
           _accumulated_s[last_index + 1] <= s) {
      ++last_index;
    }
    _last_point_index.push_back(last_index);
    s += kSampleDistance;
  }
  CHECK_EQ(_last_point_index.size(), _num_sample_points);
}

272 273
void Path::get_all_overlaps(GetOverlapFromLaneFunc get_overlaps_from_lane,
                            std::vector<PathOverlap>* const overlaps) const {
Z
Zhang Liangliang 已提交
274 275 276 277 278 279 280
  if (overlaps == nullptr) {
    return;
  }
  overlaps->clear();
  std::unordered_map<std::string, std::vector<std::pair<double, double>>>
      overlaps_by_id;
  double s = 0.0;
281
  /*
Z
Zhang Liangliang 已提交
282 283 284 285
  for (const auto& lane_segment : _lane_segments) {
    if (lane_segment.lane == nullptr) {
      continue;
    }
286 287 288 289
    for (const auto overlap_id : get_overlaps_from_lane(*(lane_segment.lane))) {



Z
Zhang Liangliang 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
      const auto* overlap_info =
          overlap->get_object_overlap_info(lane_segment.lane->id());
      if (overlap_info == nullptr) {
        continue;
      }
      const auto& lane_overlap_info = overlap_info->lane_overlap_info();
      if (lane_overlap_info.start_s() < lane_segment.end_s &&
          lane_overlap_info.end_s() > lane_segment.start_s) {
        const double ref_s = s - lane_segment.start_s;
        const double adjusted_start_s =
            std::max(lane_overlap_info.start_s(), lane_segment.start_s) + ref_s;
        const double adjusted_end_s =
            std::min(lane_overlap_info.end_s(), lane_segment.end_s) + ref_s;
        for (const auto& object : overlap->overlap().object()) {
          if (object.id().id() != lane_segment.lane->id().id()) {
            overlaps_by_id[object.id().id()].emplace_back(adjusted_start_s,
                                                          adjusted_end_s);
          }
        }
      }
    }
    s += lane_segment.end_s - lane_segment.start_s;
  }
  for (auto& overlaps_one_object : overlaps_by_id) {
    const std::string& object_id = overlaps_one_object.first;
    auto& segments = overlaps_one_object.second;
    std::sort(segments.begin(), segments.end());

    const double kMinOverlapDistanceGap = 1.5;  // in meters.
    for (const auto& segment : segments) {
      if (!overlaps->empty() && overlaps->back().object_id == object_id &&
          segment.first - overlaps->back().end_s <= kMinOverlapDistanceGap) {
        overlaps->back().end_s =
            std::max(overlaps->back().end_s, segment.second);
      } else {
        overlaps->emplace_back(object_id, segment.first, segment.second);
      }
    }
  }
329 330 331 332 333
  std::sort(overlaps->begin(), overlaps->end(),
            [](const PathOverlap& overlap1, const PathOverlap& overlap2) {
              return overlap1.start_s < overlap2.start_s;
            });
  */
Z
Zhang Liangliang 已提交
334 335
}

336
void Path::init_overlaps() {
337
  // TODO: implement this function. (Liangliang)
338
  /*
339 340 341 342
  get_all_overlaps(std::bind(&LaneInfo::cross_lanes, _1), &_lane_overlaps);
  get_all_overlaps(std::bind(LaneInfoConstPtr::signals, _1),
                   &_signal_overlaps);
  get_all_overlaps(std::bind(LaneInfoConstPtr::yield_signs, _1),
Z
Zhang Liangliang 已提交
343
                   &_yield_sign_overlaps);
344 345 346 347 348
  get_all_overlaps(std::bind(LaneInfoConstPtr::stop_signs, _1),
                   &_stop_sign_overlaps);
  get_all_overlaps(std::bind(LaneInfoConstPtr::crosswalks, _1),
                   &_crosswalk_overlaps);
  get_all_overlaps(std::bind(LaneInfoConstPtr::parking_spaces, _1),
Z
Zhang Liangliang 已提交
349
                   &_parking_space_overlaps);
350 351 352
  get_all_overlaps(std::bind(LaneInfoConstPtr::junctions, _1),
                   &_junction_overlaps);
  get_all_overlaps(std::bind(LaneInfoConstPtr::speed_bumps, _1),
Z
Zhang Liangliang 已提交
353
                   &_speed_bump_overlaps);
354
  */
Z
Zhang Liangliang 已提交
355 356
}

357
MapPathPoint Path::get_smooth_point(const InterpolatedIndex& index) const {
Z
Zhang Liangliang 已提交
358 359 360
  CHECK_GE(index.id, 0);
  CHECK_LT(index.id, _num_points);

361
  const MapPathPoint& ref_point = _path_points[index.id];
Z
Zhang Liangliang 已提交
362
  if (std::abs(index.offset) > kMathEpsilon) {
363
    const Vec2d delta = _unit_directions[index.id] * index.offset;
364 365
    MapPathPoint point({ref_point.x() + delta.x(), ref_point.y() + delta.y()},
                       ref_point.heading());
Z
Zhang Liangliang 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378
    if (index.id < _num_segments) {
      const LaneSegment& lane_segment = _lane_segments_to_next_point[index.id];
      if (lane_segment.lane != nullptr) {
        point.add_lane_waypoint(LaneWaypoint(
            lane_segment.lane, lane_segment.start_s + index.offset));
      }
    }
    return point;
  } else {
    return ref_point;
  }
}

379
MapPathPoint Path::get_smooth_point(double s) const {
Z
Zhang Liangliang 已提交
380 381 382
  return get_smooth_point(get_index_from_s(s));
}

383
double Path::get_s_from_index(const InterpolatedIndex& index) const {
Z
Zhang Liangliang 已提交
384 385 386 387 388 389 390 391 392
  if (index.id < 0) {
    return 0.0;
  }
  if (index.id >= _num_points) {
    return _length;
  }
  return _accumulated_s[index.id] + index.offset;
}

393
InterpolatedIndex Path::get_index_from_s(double s) const {
Z
Zhang Liangliang 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  if (s <= 0.0) {
    return {0, 0.0};
  }
  CHECK_GT(_num_points, 0);
  if (s >= _length) {
    return {_num_points - 1, 0.0};
  }
  const int sample_id = static_cast<int>(s / kSampleDistance);
  if (sample_id >= _num_sample_points) {
    return {_num_points - 1, 0.0};
  }
  const int next_sample_id = sample_id + 1;
  int low = _last_point_index[sample_id];
  int high = (next_sample_id < _num_sample_points
                  ? std::min(_num_points, _last_point_index[next_sample_id] + 1)
                  : _num_points);
  while (low + 1 < high) {
    const int mid = (low + high) / 2;
    if (_accumulated_s[mid] <= s) {
      low = mid;
    } else {
      high = mid;
    }
  }
  return {low, s - _accumulated_s[low]};
}

421
bool Path::get_nearest_point(const Vec2d& point, double* accumulate_s,
422
                             double* lateral) const {
Z
Zhang Liangliang 已提交
423 424 425 426
  double distance = 0.0;
  return get_nearest_point(point, accumulate_s, lateral, &distance);
}

427
bool Path::get_nearest_point(const Vec2d& point, double* accumulate_s,
428
                             double* lateral, double* min_distance) const {
Z
Zhang Liangliang 已提交
429 430 431 432 433
  if (!get_projection(point, accumulate_s, lateral, min_distance)) {
    return false;
  }
  if (*accumulate_s < 0.0) {
    *accumulate_s = 0.0;
434
    *min_distance = point.DistanceTo(_path_points[0]);
Z
Zhang Liangliang 已提交
435 436
  } else if (*accumulate_s > _length) {
    *accumulate_s = _length;
437
    *min_distance = point.DistanceTo(_path_points.back());
Z
Zhang Liangliang 已提交
438 439 440 441
  }
  return true;
}

442
bool Path::get_projection(const common::math::Vec2d& point,
443
                          double* accumulate_s, double* lateral) const {
Z
Zhang Liangliang 已提交
444 445 446 447
  double distance = 0.0;
  return get_projection(point, accumulate_s, lateral, &distance);
}

448
bool Path::get_projection(const Vec2d& point, double* accumulate_s,
449
                          double* lateral, double* min_distance) const {
Z
Zhang Liangliang 已提交
450 451 452 453 454 455 456
  if (_segments.empty()) {
    return false;
  }
  if (accumulate_s == nullptr || lateral == nullptr ||
      min_distance == nullptr) {
    return false;
  }
D
Dong Li 已提交
457 458 459
  if (_use_path_approximation) {
    return _approximation.get_projection(*this, point, accumulate_s, lateral,
                                         min_distance);
Z
Zhang Liangliang 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473
  }
  CHECK_GE(_num_points, 2);
  *min_distance = std::numeric_limits<double>::infinity();

  for (int i = 0; i < _num_segments; ++i) {
    const auto& segment = _segments[i];
    const double distance = segment.DistanceTo(point);
    if (distance < *min_distance) {
      const double proj = segment.ProjectOntoUnit(point);
      if (proj < 0.0 && i > 0) {
        continue;
      }
      if (proj > segment.length() && i + 1 < _num_segments) {
        const auto& next_segment = _segments[i + 1];
474 475
        if ((point - next_segment.start())
                .InnerProd(next_segment.unit_direction()) >= 0.0) {
Z
Zhang Liangliang 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
          continue;
        }
      }
      *min_distance = distance;
      if (i + 1 >= _num_segments) {
        *accumulate_s = _accumulated_s[i] + proj;
      } else {
        *accumulate_s = _accumulated_s[i] + std::min(proj, segment.length());
      }
      const double prod = segment.ProductOntoUnit(point);
      if ((i == 0 && proj < 0.0) ||
          (i + 1 == _num_segments && proj > segment.length())) {
        *lateral = prod;
      } else {
        *lateral = (prod > 0.0 ? distance : -distance);
      }
    }
  }
  return true;
}

497
bool Path::get_heading_along_path(const Vec2d& point, double* heading) const {
Z
Zhang Liangliang 已提交
498 499 500 501 502 503 504 505 506 507 508 509
  if (heading == nullptr) {
    return false;
  }
  double s = 0;
  double l = 0;
  if (get_projection(point, &s, &l)) {
    *heading = get_smooth_point(s).heading();
    return true;
  }
  return false;
}

510
double Path::get_left_width(const double s) const {
Z
Zhang Liangliang 已提交
511 512 513
  return get_sample(_left_width, s);
}

514
double Path::get_right_width(const double s) const {
Z
Zhang Liangliang 已提交
515 516 517
  return get_sample(_right_width, s);
}

518 519
bool Path::get_width(const double s, double* left_width,
                     double* right_width) const {
Z
Zhang Liangliang 已提交
520 521 522 523 524 525 526 527 528 529 530
  CHECK_NOTNULL(left_width);
  CHECK_NOTNULL(right_width);

  if (s < 0.0 || s > _length) {
    return false;
  }
  *left_width = get_sample(_left_width, s);
  *right_width = get_sample(_right_width, s);
  return true;
}

531 532
double Path::get_sample(const std::vector<double>& samples,
                        const double s) const {
Z
Zhang Liangliang 已提交
533 534 535 536 537 538 539 540 541 542 543 544 545 546
  if (samples.empty()) {
    return 0.0;
  }
  if (s <= 0.0) {
    return samples[0];
  }
  const int idx = static_cast<int>(s / kSampleDistance);
  if (idx >= _num_sample_points - 1) {
    return samples.back();
  }
  const double ratio = (s - idx * kSampleDistance) / kSampleDistance;
  return samples[idx] * (1.0 - ratio) + samples[idx + 1] * ratio;
}

547
bool Path::is_on_path(const Vec2d& point) const {
Z
Zhang Liangliang 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
  double accumulate_s = 0.0;
  double lateral = 0.0;
  if (!get_projection(point, &accumulate_s, &lateral)) {
    return false;
  }
  double left_width = 0.0;
  double right_width = 0.0;
  if (!get_width(accumulate_s, &left_width, &right_width)) {
    return false;
  }
  if (lateral < left_width && lateral > -right_width) {
    return true;
  }
  return false;
}

564
bool Path::is_on_path(const Box2d& box) const {
565
  std::vector<Vec2d> corners;
Z
Zhang Liangliang 已提交
566 567
  box.GetAllCorners(&corners);
  for (const auto& corner : corners) {
568
    if (!is_on_path(corner)) {
Z
Zhang Liangliang 已提交
569 570 571 572 573 574
      return false;
    }
  }
  return true;
}

575
bool Path::overlap_with(const common::math::Box2d& box, double width) const {
D
Dong Li 已提交
576 577
  if (_use_path_approximation) {
    return _approximation.overlap_with(*this, box, width);
Z
Zhang Liangliang 已提交
578
  }
579
  const Vec2d center = box.center();
Z
Zhang Liangliang 已提交
580 581 582 583 584 585 586 587 588 589 590 591
  const double radius_sqr = Sqr(box.diagonal() / 2.0 + width) + kMathEpsilon;
  for (const auto& segment : _segments) {
    if (segment.DistanceSquareTo(center) > radius_sqr) {
      continue;
    }
    if (box.DistanceTo(segment) <= width + kMathEpsilon) {
      return true;
    }
  }
  return false;
}

592 593
double PathApproximation::compute_max_error(const Path& path, const int s,
                                            const int t) {
Z
Zhang Liangliang 已提交
594 595 596
  if (s + 1 >= t) {
    return 0.0;
  }
597
  const auto& points = path.path_points();
598
  const LineSegment2d segment(points[s], points[t]);
Z
Zhang Liangliang 已提交
599 600 601
  double max_distance_sqr = 0.0;
  for (int i = s + 1; i < t; ++i) {
    max_distance_sqr =
602
        std::max(max_distance_sqr, segment.DistanceSquareTo(points[i]));
Z
Zhang Liangliang 已提交
603 604 605 606
  }
  return sqrt(max_distance_sqr);
}

607 608
bool PathApproximation::is_within_max_error(const Path& path, const int s,
                                            const int t) {
Z
Zhang Liangliang 已提交
609 610 611
  if (s + 1 >= t) {
    return true;
  }
612
  const auto& points = path.path_points();
613
  const LineSegment2d segment(points[s], points[t]);
Z
Zhang Liangliang 已提交
614
  for (int i = s + 1; i < t; ++i) {
615
    if (segment.DistanceSquareTo(points[i]) > _max_sqr_error) {
Z
Zhang Liangliang 已提交
616 617 618 619 620 621
      return false;
    }
  }
  return true;
}

622 623 624
void PathApproximation::init(const Path& path) {
  init_dilute(path);
  init_projections(path);
Z
Zhang Liangliang 已提交
625 626
}

627 628
void PathApproximation::init_dilute(const Path& path) {
  const int num_original_points = path.num_points();
Z
Zhang Liangliang 已提交
629 630 631 632 633 634 635
  _original_ids.clear();
  int last_idx = 0;
  while (last_idx < num_original_points - 1) {
    _original_ids.push_back(last_idx);
    int next_idx = last_idx + 1;
    int delta = 2;
    for (; last_idx + delta < num_original_points; delta *= 2) {
636
      if (!is_within_max_error(path, last_idx, last_idx + delta)) {
Z
Zhang Liangliang 已提交
637 638 639 640 641 642
        break;
      }
      next_idx = last_idx + delta;
    }
    for (; delta > 0; delta /= 2) {
      if (next_idx + delta < num_original_points &&
643
          is_within_max_error(path, last_idx, next_idx + delta)) {
Z
Zhang Liangliang 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656 657
        next_idx += delta;
      }
    }
    last_idx = next_idx;
  }
  _original_ids.push_back(last_idx);
  _num_points = static_cast<int>(_original_ids.size());
  if (_num_points == 0) {
    return;
  }

  _segments.clear();
  _segments.reserve(_num_points - 1);
  for (int i = 0; i < _num_points - 1; ++i) {
658 659
    _segments.emplace_back(path.path_points()[_original_ids[i]],
                           path.path_points()[_original_ids[i + 1]]);
Z
Zhang Liangliang 已提交
660 661 662 663 664
  }
  _max_error_per_segment.clear();
  _max_error_per_segment.reserve(_num_points - 1);
  for (int i = 0; i < _num_points - 1; ++i) {
    _max_error_per_segment.push_back(
665
        compute_max_error(path, _original_ids[i], _original_ids[i + 1]));
Z
Zhang Liangliang 已提交
666 667 668
  }
}

669
void PathApproximation::init_projections(const Path& path) {
Z
Zhang Liangliang 已提交
670 671 672 673 674 675 676 677 678 679 680
  if (_num_points == 0) {
    return;
  }
  _projections.clear();
  _projections.reserve(_segments.size() + 1);
  double s = 0.0;
  _projections.push_back(0);
  for (const auto& segment : _segments) {
    s += segment.length();
    _projections.push_back(s);
  }
681
  const auto& original_points = path.path_points();
Z
Zhang Liangliang 已提交
682 683 684 685 686 687 688 689
  const int num_original_points = original_points.size();
  _original_projections.clear();
  _original_projections.reserve(num_original_points);
  for (size_t i = 0; i < _projections.size(); ++i) {
    _original_projections.push_back(_projections[i]);
    if (i + 1 < _projections.size()) {
      const auto& segment = _segments[i];
      for (int idx = _original_ids[i] + 1; idx < _original_ids[i + 1]; ++idx) {
690
        const double proj = segment.ProjectOntoUnit(original_points[idx]);
Z
Zhang Liangliang 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
        _original_projections.push_back(
            _projections[i] + std::max(0.0, std::min(proj, segment.length())));
      }
    }
  }

  // max_p_to_left[i] = max(p[0], p[1], ... p[i]).
  _max_original_projections_to_left.resize(num_original_points);
  double last_projection = -std::numeric_limits<double>::infinity();
  for (int i = 0; i < num_original_points; ++i) {
    last_projection = std::max(last_projection, _original_projections[i]);
    _max_original_projections_to_left[i] = last_projection;
  }
  for (int i = 0; i + 1 < num_original_points; ++i) {
    CHECK_LE(_max_original_projections_to_left[i],
             _max_original_projections_to_left[i + 1] + kMathEpsilon);
  }

  // min_p_to_right[i] = min(p[i], p[i + 1], ... p[size - 1]).
  _min_original_projections_to_right.resize(_original_projections.size());
  last_projection = std::numeric_limits<double>::infinity();
  for (int i = num_original_points - 1; i >= 0; --i) {
    last_projection = std::min(last_projection, _original_projections[i]);
    _min_original_projections_to_right[i] = last_projection;
  }
  for (int i = 0; i + 1 < num_original_points; ++i) {
    CHECK_LE(_min_original_projections_to_right[i],
             _min_original_projections_to_right[i + 1] + kMathEpsilon);
  }

  // Sample max_p_to_left by sample_distance.
  _max_projection = _projections.back();
  _num_projection_samples =
      static_cast<int>(_max_projection / kSampleDistance) + 1;
  _sampled_max_original_projections_to_left.clear();
  _sampled_max_original_projections_to_left.reserve(_num_projection_samples);
  double proj = 0.0;
  int last_index = 0;
  for (int i = 0; i < _num_projection_samples; ++i) {
    while (last_index + 1 < num_original_points &&
           _max_original_projections_to_left[last_index + 1] < proj) {
      ++last_index;
    }
    _sampled_max_original_projections_to_left.push_back(last_index);
    proj += kSampleDistance;
  }
  CHECK_EQ(_sampled_max_original_projections_to_left.size(),
           _num_projection_samples);
}

741
bool PathApproximation::get_projection(const Path& path,
742
                                       const common::math::Vec2d& point,
743 744
                                       double* accumulate_s, double* lateral,
                                       double* min_distance) const {
Z
Zhang Liangliang 已提交
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
  if (_num_points == 0) {
    return false;
  }
  if (accumulate_s == nullptr || lateral == nullptr ||
      min_distance == nullptr) {
    return false;
  }
  double min_distance_sqr = std::numeric_limits<double>::infinity();
  int estimate_nearest_segment_idx = -1;
  std::vector<double> distance_sqr_to_segments;
  distance_sqr_to_segments.reserve(_segments.size());
  for (size_t i = 0; i < _segments.size(); ++i) {
    const double distance_sqr = _segments[i].DistanceSquareTo(point);
    distance_sqr_to_segments.push_back(distance_sqr);
    if (distance_sqr < min_distance_sqr) {
      min_distance_sqr = distance_sqr;
      estimate_nearest_segment_idx = i;
    }
  }
  if (estimate_nearest_segment_idx < 0) {
    return false;
  }
767
  const auto& original_segments = path.segments();
Z
Zhang Liangliang 已提交
768
  const int num_original_segments = static_cast<int>(original_segments.size());
769
  const auto& original_accumulated_s = path.accumulated_s();
Z
Zhang Liangliang 已提交
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
  double min_distance_sqr_with_error =
      Sqr(sqrt(min_distance_sqr) +
          _max_error_per_segment[estimate_nearest_segment_idx] + _max_error);
  *min_distance = std::numeric_limits<double>::infinity();
  int nearest_segment_idx = -1;
  for (size_t i = 0; i < _segments.size(); ++i) {
    if (distance_sqr_to_segments[i] >= min_distance_sqr_with_error) {
      continue;
    }
    int first_segment_idx = _original_ids[i];
    int last_segment_idx = _original_ids[i + 1] - 1;
    double max_original_projection = std::numeric_limits<double>::infinity();
    if (first_segment_idx < last_segment_idx) {
      const auto& segment = _segments[i];
      const double projection = segment.ProjectOntoUnit(point);
      const double prod_sqr = Sqr(segment.ProductOntoUnit(point));
      if (prod_sqr >= min_distance_sqr_with_error) {
        continue;
      }
      const double scan_distance = sqrt(min_distance_sqr_with_error - prod_sqr);
      const double min_projection = projection - scan_distance;
      max_original_projection = _projections[i] + projection + scan_distance;
      if (min_projection > 0.0) {
        const double limit = _projections[i] + min_projection;
        const int sample_index =
            std::max(0, static_cast<int>(limit / kSampleDistance));
        if (sample_index >= _num_projection_samples) {
          first_segment_idx = last_segment_idx;
        } else {
          first_segment_idx =
              std::max(first_segment_idx,
                       _sampled_max_original_projections_to_left[sample_index]);
          if (first_segment_idx >= last_segment_idx) {
            first_segment_idx = last_segment_idx;
          } else {
            while (first_segment_idx < last_segment_idx &&
                   _max_original_projections_to_left[first_segment_idx + 1] <
                       limit) {
              ++first_segment_idx;
            }
          }
        }
      }
    }
    bool min_distance_updated = false;
    bool is_within_end_point = false;
    for (int idx = first_segment_idx; idx <= last_segment_idx; ++idx) {
      if (_min_original_projections_to_right[idx] > max_original_projection) {
        break;
      }
      const auto& original_segment = original_segments[idx];
      const double x0 = point.x() - original_segment.start().x();
      const double y0 = point.y() - original_segment.start().y();
      const double ux = original_segment.unit_direction().x();
      const double uy = original_segment.unit_direction().y();
      double proj = x0 * ux + y0 * uy;
      double distance = 0.0;
      if (proj < 0.0) {
        if (is_within_end_point) {
          continue;
        }
        is_within_end_point = true;
        distance = hypot(x0, y0);
      } else if (proj <= original_segment.length()) {
        is_within_end_point = true;
        distance = std::abs(x0 * uy - y0 * ux);
      } else {
        is_within_end_point = false;
        if (idx != last_segment_idx) {
          continue;
        }
841
        distance = original_segment.end().DistanceTo(point);
Z
Zhang Liangliang 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
      }
      if (distance < *min_distance) {
        min_distance_updated = true;
        *min_distance = distance;
        nearest_segment_idx = idx;
      }
    }
    if (min_distance_updated) {
      min_distance_sqr_with_error = Sqr(*min_distance + _max_error);
    }
  }
  if (nearest_segment_idx >= 0) {
    const auto& segment = original_segments[nearest_segment_idx];
    double proj = segment.ProjectOntoUnit(point);
    const double prod = segment.ProductOntoUnit(point);
    if (nearest_segment_idx > 0) {
      proj = std::max(0.0, proj);
    }
    if (nearest_segment_idx + 1 < num_original_segments) {
      proj = std::min(segment.length(), proj);
    }
    *accumulate_s = original_accumulated_s[nearest_segment_idx] + proj;
    if ((nearest_segment_idx == 0 && proj < 0.0) ||
        (nearest_segment_idx + 1 == num_original_segments &&
         proj > segment.length())) {
      *lateral = prod;
    } else {
      *lateral = (prod > 0 ? (*min_distance) : -(*min_distance));
    }
    return true;
  }
  return false;
}

876 877
bool PathApproximation::overlap_with(const Path& path, const Box2d& box,
                                     double width) const {
Z
Zhang Liangliang 已提交
878 879 880
  if (_num_points == 0) {
    return false;
  }
881
  const Vec2d center = box.center();
Z
Zhang Liangliang 已提交
882 883
  const double radius = box.diagonal() / 2.0 + width;
  const double radius_sqr = Sqr(radius);
884
  const auto& original_segments = path.segments();
Z
Zhang Liangliang 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
  for (size_t i = 0; i < _segments.size(); ++i) {
    const LineSegment2d& segment = _segments[i];
    const double max_error = _max_error_per_segment[i];
    const double radius_sqr_with_error = Sqr(radius + max_error);
    if (segment.DistanceSquareTo(center) > radius_sqr_with_error) {
      continue;
    }
    int first_segment_idx = _original_ids[i];
    int last_segment_idx = _original_ids[i + 1] - 1;
    double max_original_projection = std::numeric_limits<double>::infinity();
    if (first_segment_idx < last_segment_idx) {
      const auto& segment = _segments[i];
      const double projection = segment.ProjectOntoUnit(center);
      const double prod_sqr = Sqr(segment.ProductOntoUnit(center));
      if (prod_sqr >= radius_sqr_with_error) {
        continue;
      }
      const double scan_distance = sqrt(radius_sqr_with_error - prod_sqr);
      const double min_projection = projection - scan_distance;
      max_original_projection = _projections[i] + projection + scan_distance;
      if (min_projection > 0.0) {
        const double limit = _projections[i] + min_projection;
        const int sample_index =
            std::max(0, static_cast<int>(limit / kSampleDistance));
        if (sample_index >= _num_projection_samples) {
          first_segment_idx = last_segment_idx;
        } else {
          first_segment_idx =
              std::max(first_segment_idx,
                       _sampled_max_original_projections_to_left[sample_index]);
          if (first_segment_idx >= last_segment_idx) {
            first_segment_idx = last_segment_idx;
          } else {
            while (first_segment_idx < last_segment_idx &&
                   _max_original_projections_to_left[first_segment_idx + 1] <
                       limit) {
              ++first_segment_idx;
            }
          }
        }
      }
    }
    for (int idx = first_segment_idx; idx <= last_segment_idx; ++idx) {
      if (_min_original_projections_to_right[idx] > max_original_projection) {
        break;
      }
      const auto& original_segment = original_segments[idx];
      if (original_segment.DistanceSquareTo(center) > radius_sqr) {
        continue;
      }
      if (box.DistanceTo(original_segment) <= width) {
        return true;
      }
    }
  }
  return false;
}

943
}  // namespace hdmap
Z
Zhang Liangliang 已提交
944
}  // namespace apollo