Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 35 additions & 12 deletions backends/osmand/ch/ch_sidecar.h
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ class SidecarStore {

class Sidecar {
public:
struct Candidate { u32 node; double metres; };
struct Candidate { u32 node; double metres; int32_t x, y; };

// Opens the file and checks it is a sidecar of this version and size.
static std::unique_ptr<Sidecar> open(const char* path, std::string& error,
Expand Down Expand Up @@ -209,7 +209,11 @@ class Sidecar {
const int64_t cx = ((int64_t)x31 - header_.grid_min_x) >> header_.grid_shift;
const int64_t cy = ((int64_t)y31 - header_.grid_min_y) >> header_.grid_shift;
const int64_t cell = (int64_t)1 << header_.grid_shift;
std::vector<std::pair<int64_t, u32>> best; // max-heap on squared distance, <= k entries
std::vector<std::pair<int64_t, SidecarGridEntry>> best; // max-heap on squared distance, <= k entries
const auto by_distance = [](const std::pair<int64_t, SidecarGridEntry>& a,
const std::pair<int64_t, SidecarGridEntry>& b) {
return a.first != b.first ? a.first < b.first : a.second.node < b.second.node;
};
auto scan = [&](int64_t gx, int64_t gy) {
if (gx < 0 || gy < 0 || gx >= (int64_t)header_.grid_w || gy >= (int64_t)header_.grid_h) return;
const u32 c = (u32)(gy * header_.grid_w + gx);
Expand All @@ -222,9 +226,9 @@ class Sidecar {
const int64_t dx = (int64_t)e.x - x31, dy = (int64_t)e.y - y31;
const int64_t d = dx * dx + dy * dy;
if (best.size() == k && d >= best.front().first) continue;
best.push_back({d, e.node});
std::push_heap(best.begin(), best.end());
if (best.size() > k) { std::pop_heap(best.begin(), best.end()); best.pop_back(); }
best.push_back({d, e});
std::push_heap(best.begin(), best.end(), by_distance);
if (best.size() > k) { std::pop_heap(best.begin(), best.end(), by_distance); best.pop_back(); }
}
};
const int max_ring = 128; // about 50 km at a 400 m cell
Expand All @@ -238,9 +242,10 @@ class Sidecar {
// anything not scanned yet is at least r cells away
if (best.size() == k && std::sqrt((double)best.front().first) <= (double)r * (double)cell) break;
}
std::sort(best.begin(), best.end());
std::sort(best.begin(), best.end(), by_distance);
const double scale = metres_per_unit((double)y31);
for (const auto& b : best) out.push_back({b.second, std::sqrt((double)b.first) * scale});
for (const auto& b : best)
out.push_back({b.second.node, std::sqrt((double)b.first) * scale, b.second.x, b.second.y});
}

private:
Expand Down Expand Up @@ -313,10 +318,13 @@ class Router {
// Start and end are snapped to the nearest few nodes within kMaxSnapMetres (a point
// farther from every road has no route); the snap distance counts as a slow walk
// (120 ms per metre) against the route cost, so a far node does not win on route
// cost alone. On success runs are the road stretches in travel order (empty when
// both ends snap to the same node: too short to route here) and cost is the routing
// cost in milliseconds.
Status route(int sx, int sy, int ex, int ey, std::vector<RoadRun>& runs, u32& cost)
// cost alone. With a start heading (degrees clockwise from north) a start node more
// than 120 degrees off it, i.e. behind the car, costs kReversePenaltyMs more, as
// OsmAnd's own routers charge for starting against the initial direction. On success
// runs are the road stretches in travel order (empty when both ends snap to the same
// node: too short to route here) and cost is the routing cost in milliseconds.
Status route(int sx, int sy, int ex, int ey, std::vector<RoadRun>& runs, u32& cost,
double start_heading_degrees = kNoHeading)
{
runs.clear();
sidecar_.nearest_nodes(sx, sy, kSnapNodes, from_);
Expand All @@ -331,7 +339,8 @@ class Router {
u32 meet = 0;
const u32 c = query_.run(s.node, t.node, meet);
if (c == INF) continue;
const double total = c + 120.0 * (s.metres + t.metres);
const double total = c + 120.0 * (s.metres + t.metres) +
reverse_penalty(sx, sy, s, start_heading_degrees);
if (total < best) { best = total; best_from = s.node; best_to = t.node; best_cost = c; }
}
}
Expand All @@ -347,9 +356,23 @@ class Router {
const std::vector<u32>& edges() const { return edges_; } // original edges of the last route

static constexpr double kMaxSnapMetres = 1000.0;
static constexpr double kNoHeading = -1.0;
static constexpr double kReversePenaltyMs = 60000.0; // OsmAnd's default 60 s

private:
static constexpr size_t kSnapNodes = 4;
static constexpr double kHeadingNearMetres = 10.0; // a node this close has no direction

static double reverse_penalty(int sx, int sy, const Sidecar::Candidate& node,
double heading_degrees)
{
if (heading_degrees < 0.0 || node.metres < kHeadingNearMetres) return 0.0;
// 31-bit tile y grows southwards
const double bearing = std::atan2((double)node.x - sx, (double)sy - node.y) *
180.0 / 3.14159265358979323846;
const double off = std::fabs(std::remainder(bearing - heading_degrees, 360.0));
return off > 120.0 ? kReversePenaltyMs : 0.0;
}

// Consecutive original edges of one road become one stretch; junction
// transitions (ids beyond the real edges) have no road and are skipped.
Expand Down
6 changes: 4 additions & 2 deletions backends/osmand/ch_planner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,16 @@ std::unique_ptr<ChPlanner> ChPlanner::open(const std::string& sidecar_path,
std::string ChPlanner::describe() const { return impl_->description; }

ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHARED_PTR<RoutingContext>& context,
int start_x, int start_y, int end_x, int end_y, std::string& why)
int start_x, int start_y, int end_x, int end_y, std::string& why,
double start_heading_degrees)
{
timing_ = Timing();
why.clear();
auto step = Clock::now();
std::vector<onc_ch::RoadRun> runs;
onc_ch::u32 cost = 0;
const auto status = impl_->router->route(start_x, start_y, end_x, end_y, runs, cost);
const auto status = impl_->router->route(start_x, start_y, end_x, end_y, runs, cost,
start_heading_degrees);
timing_.search_ms = ms_since(step);
timing_.settled = impl_->router->settled();
timing_.base_edges = impl_->router->edges().size();
Expand Down
5 changes: 4 additions & 1 deletion backends/osmand/ch_planner.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,11 @@ class ChPlanner {
// when the sidecar cannot serve it (a point too far from every road,
// start and end on one road node, a road missing from the loaded maps);
// `why` then names the reason and the caller falls back to HH or A*.
// start_heading_degrees: the car's direction (clockwise from north), or
// negative when unknown; start nodes behind it cost a reverse penalty.
Segments route(RoutePlannerFrontEnd& front_end, const SHARED_PTR<RoutingContext>& context,
int start_x, int start_y, int end_x, int end_y, std::string& why);
int start_x, int start_y, int end_x, int end_y, std::string& why,
double start_heading_degrees = -1.0);

const Timing& last_timing() const { return timing_; }
// One-line description for the log: nodes, edges, maps.
Expand Down
31 changes: 31 additions & 0 deletions backends/osmand/guidance_tracker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,32 @@ double distance(const ui::GeoPoint& a, const ui::GeoPoint& b) noexcept
return std::hypot(x, y);
}

// Direction of the route geometry at `along` metres of its own length.
bool bearing_at(const std::vector<ui::GeoPoint>& geometry, double along,
double& bearing_degrees) noexcept
{
double walked = 0.0;
for (std::size_t index = 1; index < geometry.size(); ++index) {
const auto& a = geometry[index - 1];
const auto& b = geometry[index];
const double latitude = radians((a.latitude + b.latitude) * 0.5);
const double east = (b.longitude - a.longitude) *
earth_metres_per_degree * std::cos(latitude);
const double north = (b.latitude - a.latitude) * earth_metres_per_degree;
const double length = std::hypot(east, north);
if (length <= 0.0)
continue;
walked += length;
if (walked >= along || index + 1 == geometry.size()) {
bearing_degrees = std::atan2(east, north) * 180.0 / 3.14159265358979323846;
if (bearing_degrees < 0.0)
bearing_degrees += 360.0;
return true;
}
}
return false;
}

void choose_maneuvers(const ui::RouteAlternative& route,
ui::GuidanceState& state) noexcept
{
Expand Down Expand Up @@ -119,6 +145,11 @@ ui::GuidanceState GuidanceTracker::update(const ui::RouteAlternative& route,
const double fraction = route.distance_metres > 0.0
? state.remaining_metres / route.distance_metres : 0.0;
state.remaining_seconds = route.duration_seconds * fraction;
// At the progress point rather than the nearest segment: a route that
// comes back along the other carriageway is near but points the other way.
state.route_bearing_known = route.distance_metres > 0.0 &&
bearing_at(route.geometry, progress_metres_ / route.distance_metres * geometry_length,
state.route_bearing_degrees);
state.arrived = state.remaining_metres <= arrival_radius_metres ||
distance(position, route.geometry.back()) <= arrival_radius_metres;
choose_maneuvers(route, state);
Expand Down
34 changes: 25 additions & 9 deletions backends/osmand/navigation_worker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -420,13 +420,15 @@ class NavigationWorker::Impl {
}

void submit_route(std::uint64_t revision, ui::Destination destination,
ui::GeoPoint origin, bool alternatives)
ui::GeoPoint origin, bool alternatives,
std::optional<double> heading_degrees)
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) return;
if (active_) active_->cancel();
pending_ = Request::route(revision, std::move(destination), origin);
pending_.alternatives = alternatives;
pending_.heading_degrees = heading_degrees;
has_pending_ = true;
trace_result("worker=route_queued", revision, 1u);
condition_.notify_one();
Expand Down Expand Up @@ -496,6 +498,7 @@ class NavigationWorker::Impl {
ui::GeoPoint origin; // route start; search: "near"
std::vector<ui::GeoPoint> recent; // search: destinations picked before
bool alternatives = false; // route: also look for alternatives
std::optional<double> heading_degrees; // route: driving direction at the origin

static Request search(std::uint64_t revision, std::string query)
{
Expand Down Expand Up @@ -759,11 +762,24 @@ class NavigationWorker::Impl {
RoutePlannerFrontEnd front_end;
std::vector<Segments> found;
const char* method = "ch";
if (ch_) {
// The routers read the start direction from the shared configuration
// (radians clockwise from north, as RouteDataObject::directionRoute),
// and HH clears it when done, so it is set again before each router.
const auto new_context = [&] {
routing_config_->initialDirection = request.heading_degrees
? static_cast<float>(*request.heading_degrees * M_PI / 180.0) : NO_DIRECTION;
auto context = front_end.buildRoutingContext(routing_config_);
context->progress = std::make_shared<RouteProgress>(cancel);
return context;
};
if (request.heading_degrees)
trace_result("worker=route_heading", request.revision,
static_cast<std::size_t>(*request.heading_degrees));
if (ch_) {
auto context = new_context();
std::string why;
Segments segments = ch_->route(front_end, context, sx, sy, ex, ey, why);
Segments segments = ch_->route(front_end, context, sx, sy, ex, ey, why,
request.heading_degrees.value_or(-1.0));
if (!segments.empty() && accept_route(segments, "ch")) {
const ChPlanner::Timing& timing = ch_->last_timing();
char line[160];
Expand All @@ -779,8 +795,7 @@ class NavigationWorker::Impl {
}
if (found.empty() && !cancel->isAborted()) method = "hh";
if (found.empty() && has_hh_) {
auto context = front_end.buildRoutingContext(routing_config_);
context->progress = std::make_shared<RouteProgress>(cancel);
auto context = new_context();
found = route_hh(front_end, context, sx, sy, ex, ey,
request.alternatives && kAlternativeRoutes);
}
Expand All @@ -789,8 +804,7 @@ class NavigationWorker::Impl {
method = "astar";
trace(has_hh_ ? "worker=route_fallback why=hh_unusable"
: "worker=route_fallback why=no_hh_data");
auto context = front_end.buildRoutingContext(routing_config_);
context->progress = std::make_shared<RouteProgress>(cancel);
auto context = new_context();
std::vector<int> intermediates_x;
std::vector<int> intermediates_y;
auto segments = front_end.searchRoute(context, sx, sy, ex, ey,
Expand Down Expand Up @@ -1037,9 +1051,11 @@ bool NavigationWorker::has_search_index() const

void NavigationWorker::submit_route(std::uint64_t revision,
ui::Destination destination,
ui::GeoPoint origin, bool alternatives)
ui::GeoPoint origin, bool alternatives,
std::optional<double> heading_degrees)
{
impl_->submit_route(revision, std::move(destination), origin, alternatives);
impl_->submit_route(revision, std::move(destination), origin, alternatives,
heading_degrees);
}

NavigationWorker::~NavigationWorker() = default;
Expand Down
8 changes: 6 additions & 2 deletions backends/osmand/navigation_worker.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <vector>

Expand Down Expand Up @@ -55,9 +56,12 @@ class NavigationWorker {
// Searches take milliseconds with the index, seconds without.
bool has_search_index() const;
// alternatives: also offer up to two other routes (route preview; a
// reroute during guidance takes the fastest only).
// reroute during guidance takes the fastest only). heading_degrees: the
// car's driving direction (clockwise from north) when known; the route
// then prefers to start that way instead of turning back.
void submit_route(std::uint64_t revision, ui::Destination destination,
ui::GeoPoint origin, bool alternatives);
ui::GeoPoint origin, bool alternatives,
std::optional<double> heading_degrees);
// Replaces a pending request like the others (one job at a time).
void submit_address(std::uint64_t revision, ui::GeoPoint point);
bool take_search_result(SearchResult& output);
Expand Down
31 changes: 26 additions & 5 deletions backends/osmand/osmand_engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ class OsmAndEngine final : public Engine {
bool simulation_arrival_reported_ = false;
// Off-route recalculation.
RerouteState reroute_;
HeadingMemory heading_memory_;
BenchDetour bench_detour_;
double simulation_progress_metres_ = 0.0;
double simulation_geometry_length_metres_ = 0.0;
Expand Down Expand Up @@ -704,14 +705,26 @@ bool OsmAndEngine::update_guidance()
}

// More than 50 m from the route for 4 s (GPS noise and short parallel
// stretches stay below that) asks for a new route from the position to the
// same destination. One request at a time; a failed one waits 10 s.
// stretches stay below that), or driving against it for 5 s, asks for a new
// route from the position to the same destination, starting in the driving
// direction. One request at a time; a failed one waits 10 s.
void OsmAndEngine::check_off_route(const ui::GuidanceState& state,
const ui::GeoPoint& position)
{
const auto now = std::chrono::steady_clock::now();
if (!reroute_.off_route_long_enough(state.arrived, state.off_route_metres, now))
// Moving now: a heading from the last two seconds.
const auto heading = heading_memory_.heading(now, std::chrono::seconds(2));
std::optional<double> against;
if (heading && state.route_bearing_known)
against = *heading - state.route_bearing_degrees;
const bool off_route =
reroute_.off_route_long_enough(state.arrived, state.off_route_metres, now);
const bool wrong_way = reroute_.wrong_way_long_enough(state.arrived, against, now);
if (!off_route && !wrong_way)
return;
if (wrong_way)
trace_result("reroute=wrong_way", navigation_->route_revision(),
static_cast<std::size_t>(std::fabs(std::remainder(*against, 360.0))));
if (navigation_->rerouting() || reroute_.retry_blocked(now) ||
!navigation_->destination() || !ensure_navigation_worker())
return;
Expand All @@ -721,7 +734,8 @@ void OsmAndEngine::check_off_route(const ui::GuidanceState& state,
submitted_route_revision_ = revision;
trace_result("reroute=submit", revision,
static_cast<std::size_t>(state.off_route_metres));
navigation_worker_->submit_route(revision, *navigation_->destination(), position, false);
navigation_worker_->submit_route(revision, *navigation_->destination(), position, false,
heading_memory_.heading(now));
}

void OsmAndEngine::apply_map_commands()
Expand Down Expand Up @@ -839,6 +853,11 @@ bool OsmAndEngine::apply_camera()
camera_updated_at_ = now;
const double now_s =
std::chrono::duration<double>(now - clock_origin_).count();
{
// Also while searching: a destination picked there starts this way.
const auto moving = motion_.predict(now_s);
heading_memory_.observe(moving.valid, moving.speed_mps, moving.heading_degrees, now);
}
const auto screen = navigation_->screen();
if (screen == ui::Screen::Search) {
vector_view_.tile_zoom_limit = -1.0;
Expand Down Expand Up @@ -1572,7 +1591,9 @@ void OsmAndEngine::submit_navigation_requests()
if (ensure_navigation_worker()) {
navigation_worker_->submit_route(submitted_route_revision_,
*navigation_->destination(), current_location(),
true);
true,
heading_memory_.heading(
std::chrono::steady_clock::now()));
}
}
}
Expand Down
Loading