From 031223d03cd817e98e4c49cc6f8b785184887f60 Mon Sep 17 00:00:00 2001 From: Oleksandr Shyshatskyi Date: Sat, 24 Oct 2026 21:31:40 +0300 Subject: [PATCH 1/3] ch: a start heading penalises start nodes behind the car Router::route takes an optional start heading (degrees clockwise from north). A snapped start node more than 120 degrees off it costs 60 s more, the same default penalty OsmAnd's own routers charge for starting against the initial direction, so a reroute while driving continues ahead instead of turning back to the nearest junction behind. Snap candidates now carry their node coordinates for the bearing. Co-Authored-By: Claude Opus 5.5 --- backends/osmand/ch/ch_sidecar.h | 47 ++++++++++++++++++++++++--------- tests/ch_test.cpp | 34 ++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 12 deletions(-) diff --git a/backends/osmand/ch/ch_sidecar.h b/backends/osmand/ch/ch_sidecar.h index e617c97..a007a2d 100644 --- a/backends/osmand/ch/ch_sidecar.h +++ b/backends/osmand/ch/ch_sidecar.h @@ -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 open(const char* path, std::string& error, @@ -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> best; // max-heap on squared distance, <= k entries + std::vector> best; // max-heap on squared distance, <= k entries + const auto by_distance = [](const std::pair& a, + const std::pair& 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); @@ -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 @@ -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: @@ -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& 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& runs, u32& cost, + double start_heading_degrees = kNoHeading) { runs.clear(); sidecar_.nearest_nodes(sx, sy, kSnapNodes, from_); @@ -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; } } } @@ -347,9 +356,23 @@ class Router { const std::vector& 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. diff --git a/tests/ch_test.cpp b/tests/ch_test.cpp index a7860b3..037f653 100644 --- a/tests/ch_test.cpp +++ b/tests/ch_test.cpp @@ -226,6 +226,40 @@ int main() unlink(path.c_str()); } + // A start heading makes a start node behind the car cost the reverse penalty: halfway + // between a west and an east junction, the destination is cheaper through the west one + // unless the car is heading east. + { + Graph g; + g.n = 3; + g.x = {kBaseX, kBaseX + 2 * kSpacing, kBaseX}; // west, east, destination + g.y = {kBaseY, kBaseY, kBaseY - 100000}; // destination ~1.3 km north + add_edge(g, 0, 2, 1000, 10, 0, 1, 0); // west -> destination, 1 s + add_edge(g, 1, 2, 30000, 20, 0, 1, 0); // east -> destination, 30 s + Contractor contractor(g, 200); + contractor.run(); + const Hierarchy h = contractor.finish(); + const std::string path = temp_path(); + std::string error; + assert(pack_sidecar(g, h, {}, 15, path.c_str(), error)); + auto sidecar = Sidecar::open(path.c_str(), error); + assert(sidecar); + Router router(*sidecar); + std::vector runs; + u32 cost = 0; + const int car_x = kBaseX + kSpacing, car_y = kBaseY; + assert(router.route(car_x, car_y, g.x[2], g.y[2], runs, cost) == Router::Status::Ok); + assert(runs.size() == 1 && runs[0].road == 10); + assert(router.route(car_x, car_y, g.x[2], g.y[2], runs, cost, 270.0) == Router::Status::Ok); + assert(runs.size() == 1 && runs[0].road == 10); + assert(router.route(car_x, car_y, g.x[2], g.y[2], runs, cost, 90.0) == Router::Status::Ok); + assert(runs.size() == 1 && runs[0].road == 20 && cost == 30000); + // sideways (north) neither junction is behind + assert(router.route(car_x, car_y, g.x[2], g.y[2], runs, cost, 0.0) == Router::Status::Ok); + assert(runs.size() == 1 && runs[0].road == 10); + unlink(path.c_str()); + } + // Damaged files are refused: wrong magic, truncated copy, too small. { Graph g = random_grid(4, 4, 3); From 943724893e3d89fdb1c23ba6049a288ad9f361cd Mon Sep 17 00:00:00 2001 From: Oleksandr Shyshatskyi Date: Sat, 24 Oct 2026 21:43:07 +0300 Subject: [PATCH 2/3] routing: start new routes and reroutes in the driving direction A route request carried only origin and destination, so a reroute while driving away from the route started from the nearest road point in whichever direction was cheapest, usually back the way the car came; every recalculation then put the turn further behind. The engine now keeps the motion heading while the car moves faster than 1.5 m/s (the camera's threshold) and for 30 s after it stops, and passes it with every route and reroute request. The worker sets it as OsmAnd's initialDirection (radians clockwise from north, the directionRoute convention) before each router, since HH clears it after a run, and gives it to the CH planner's start penalty. A parked car has no heading and routes as before. Co-Authored-By: Claude Opus 5.5 --- backends/osmand/ch_planner.cpp | 6 +++-- backends/osmand/ch_planner.h | 5 +++- backends/osmand/navigation_worker.cpp | 34 ++++++++++++++++++++------- backends/osmand/navigation_worker.h | 8 +++++-- backends/osmand/osmand_engine.cpp | 13 ++++++++-- backends/osmand/reroute_state.h | 34 +++++++++++++++++++++++++++ tests/reroute_state_test.cpp | 22 +++++++++++++++++ 7 files changed, 106 insertions(+), 16 deletions(-) diff --git a/backends/osmand/ch_planner.cpp b/backends/osmand/ch_planner.cpp index 4446b5d..a1724a9 100644 --- a/backends/osmand/ch_planner.cpp +++ b/backends/osmand/ch_planner.cpp @@ -85,14 +85,16 @@ std::unique_ptr 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& 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 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(); diff --git a/backends/osmand/ch_planner.h b/backends/osmand/ch_planner.h index 5b167d8..67d018d 100644 --- a/backends/osmand/ch_planner.h +++ b/backends/osmand/ch_planner.h @@ -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& 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. diff --git a/backends/osmand/navigation_worker.cpp b/backends/osmand/navigation_worker.cpp index 6e58963..f3e2027 100644 --- a/backends/osmand/navigation_worker.cpp +++ b/backends/osmand/navigation_worker.cpp @@ -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 heading_degrees) { std::lock_guard 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(); @@ -496,6 +498,7 @@ class NavigationWorker::Impl { ui::GeoPoint origin; // route start; search: "near" std::vector recent; // search: destinations picked before bool alternatives = false; // route: also look for alternatives + std::optional heading_degrees; // route: driving direction at the origin static Request search(std::uint64_t revision, std::string query) { @@ -759,11 +762,24 @@ class NavigationWorker::Impl { RoutePlannerFrontEnd front_end; std::vector 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(*request.heading_degrees * M_PI / 180.0) : NO_DIRECTION; auto context = front_end.buildRoutingContext(routing_config_); context->progress = std::make_shared(cancel); + return context; + }; + if (request.heading_degrees) + trace_result("worker=route_heading", request.revision, + static_cast(*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]; @@ -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(cancel); + auto context = new_context(); found = route_hh(front_end, context, sx, sy, ex, ey, request.alternatives && kAlternativeRoutes); } @@ -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(cancel); + auto context = new_context(); std::vector intermediates_x; std::vector intermediates_y; auto segments = front_end.searchRoute(context, sx, sy, ex, ey, @@ -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 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; diff --git a/backends/osmand/navigation_worker.h b/backends/osmand/navigation_worker.h index 557d665..373b33f 100644 --- a/backends/osmand/navigation_worker.h +++ b/backends/osmand/navigation_worker.h @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -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 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); diff --git a/backends/osmand/osmand_engine.cpp b/backends/osmand/osmand_engine.cpp index 972a626..6a06d41 100644 --- a/backends/osmand/osmand_engine.cpp +++ b/backends/osmand/osmand_engine.cpp @@ -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; @@ -721,7 +722,8 @@ void OsmAndEngine::check_off_route(const ui::GuidanceState& state, submitted_route_revision_ = revision; trace_result("reroute=submit", revision, static_cast(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() @@ -839,6 +841,11 @@ bool OsmAndEngine::apply_camera() camera_updated_at_ = now; const double now_s = std::chrono::duration(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; @@ -1572,7 +1579,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())); } } } diff --git a/backends/osmand/reroute_state.h b/backends/osmand/reroute_state.h index c69e03f..2df954c 100644 --- a/backends/osmand/reroute_state.h +++ b/backends/osmand/reroute_state.h @@ -1,9 +1,43 @@ #pragma once #include +#include namespace navicore_osmand { +// The driving direction a new route starts with: the motion heading while the +// car moves, kept for a while after it stops (lights, a queue) and forgotten +// after that, since a parked car's last heading says little. +class HeadingMemory { +public: + using Clock = std::chrono::steady_clock; + + static constexpr double kMinSpeedMps = 1.5; // the camera's heading threshold + static constexpr std::chrono::seconds kKeepAfterStop{30}; + + void observe(bool valid, double speed_mps, double heading_degrees, Clock::time_point now) + { + if (!valid || speed_mps < kMinSpeedMps) + return; + heading_degrees_ = heading_degrees; + seen_at_ = now; + known_ = true; + } + // The heading if one was seen within max_age. + std::optional heading(Clock::time_point now, + Clock::duration max_age = kKeepAfterStop) const + { + if (!known_ || now - seen_at_ > max_age) + return std::nullopt; + return heading_degrees_; + } + +private: + bool known_ = false; + double heading_degrees_ = 0.0; + Clock::time_point seen_at_{}; +}; + // When the car has left the route long enough to ask for a new one, and how // long to wait after a failed request. class RerouteState { diff --git a/tests/reroute_state_test.cpp b/tests/reroute_state_test.cpp index 17f608d..38d70ce 100644 --- a/tests/reroute_state_test.cpp +++ b/tests/reroute_state_test.cpp @@ -115,6 +115,27 @@ void test_detour_ends_when_route_recovers() } // namespace +void test_heading_memory_keeps_a_moving_heading_for_a_while() +{ + HeadingMemory memory; + const auto t0 = Clock::now(); + CHECK(!memory.heading(t0)); + // Too slow or no fix: no heading. + memory.observe(true, 1.0, 90.0, t0); + memory.observe(false, 10.0, 90.0, t0); + CHECK(!memory.heading(t0)); + memory.observe(true, 10.0, 90.0, t0); + CHECK(memory.heading(t0) && *memory.heading(t0) == 90.0); + // Stopped at lights: the moving heading stays, the standstill one is ignored. + memory.observe(true, 0.2, 200.0, t0 + std::chrono::seconds(10)); + CHECK(*memory.heading(t0 + std::chrono::seconds(30)) == 90.0); + CHECK(!memory.heading(t0 + std::chrono::seconds(31))); + // A shorter age asks whether the car moves now. + CHECK(!memory.heading(t0 + std::chrono::seconds(3), std::chrono::seconds(2))); + memory.observe(true, 5.0, 180.0, t0 + std::chrono::seconds(40)); + CHECK(*memory.heading(t0 + std::chrono::seconds(41)) == 180.0); +} + int main() { test_off_route_needs_sustained_distance(); @@ -123,6 +144,7 @@ int main() test_detour_starts_once_and_times_out(); test_detour_boundaries(); test_detour_ends_when_route_recovers(); + test_heading_memory_keeps_a_moving_heading_for_a_while(); std::puts("reroute_state_test passed"); return 0; } From 21edac223708f2b2389c3f25f9eeb3c4d67980a7 Mon Sep 17 00:00:00 2001 From: Oleksandr Shyshatskyi Date: Sat, 24 Oct 2026 21:48:38 +0300 Subject: [PATCH 3/3] guidance: reroute when driving against the route Driving back along the route stays within the 50 m off-route distance, and progress never counts backwards, so guidance froze and offered no new route. The tracker now reports the route's direction at the car's progress point (not the nearest segment, which on a route returning along the other carriageway points the other way). Driving more than 120 degrees against it for 5 s while moving asks for a route in the driving direction. It does not ask again until the car has driven along a route, so a recalculated route that still begins with a U-turn stands. Co-Authored-By: Claude Opus 5.5 --- backends/osmand/guidance_tracker.cpp | 31 ++++++++++++++++++ backends/osmand/osmand_engine.cpp | 18 ++++++++-- backends/osmand/reroute_state.h | 47 ++++++++++++++++++++++++++- backends/osmand/ui/navigation_model.h | 4 +++ tests/navigation_ui_test.cpp | 11 +++++++ tests/reroute_state_test.cpp | 34 +++++++++++++++++++ 6 files changed, 141 insertions(+), 4 deletions(-) diff --git a/backends/osmand/guidance_tracker.cpp b/backends/osmand/guidance_tracker.cpp index dcc82ea..f869df2 100644 --- a/backends/osmand/guidance_tracker.cpp +++ b/backends/osmand/guidance_tracker.cpp @@ -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& 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 { @@ -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); diff --git a/backends/osmand/osmand_engine.cpp b/backends/osmand/osmand_engine.cpp index 6a06d41..712177a 100644 --- a/backends/osmand/osmand_engine.cpp +++ b/backends/osmand/osmand_engine.cpp @@ -705,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 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::fabs(std::remainder(*against, 360.0)))); if (navigation_->rerouting() || reroute_.retry_blocked(now) || !navigation_->destination() || !ensure_navigation_worker()) return; diff --git a/backends/osmand/reroute_state.h b/backends/osmand/reroute_state.h index 2df954c..b1654c3 100644 --- a/backends/osmand/reroute_state.h +++ b/backends/osmand/reroute_state.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include namespace navicore_osmand { @@ -63,7 +64,48 @@ class RerouteState { } return now - off_route_since_ >= kOffRouteTime; } - void clear_off_route() { off_route_ = false; } + void clear_off_route() + { + off_route_ = false; + wrong_way_ = false; + } + + static constexpr double kWrongWayDegrees = 120.0; + static constexpr double kAlongDegrees = 60.0; + static constexpr std::chrono::seconds kWrongWayTime{5}; + + // Call each guidance update with the angle between the driving direction + // and the route's at the car's progress, or nothing while the car is not + // moving. Driving along a route stays near it, so the distance check never + // fires; this is true once the car has driven more than kWrongWayDegrees + // against the route for kWrongWayTime. It then waits until the car has + // driven along a route again: a new route that still starts with a U-turn + // is the router's answer, not a reason to ask again. + bool wrong_way_long_enough(bool arrived, std::optional off_degrees, + Clock::time_point now) + { + if (arrived || !off_degrees) { + wrong_way_ = false; + return false; + } + const double off = std::fabs(std::remainder(*off_degrees, 360.0)); + if (off <= kAlongDegrees) + wrong_way_armed_ = true; + if (off < kWrongWayDegrees || !wrong_way_armed_) { + wrong_way_ = false; + return false; + } + if (!wrong_way_) { + wrong_way_ = true; + wrong_way_since_ = now; + return false; + } + if (now - wrong_way_since_ < kWrongWayTime) + return false; + wrong_way_ = false; + wrong_way_armed_ = false; + return true; + } // A failed request waits kRetryDelay before the next one. void request_failed(Clock::time_point now) { retry_at_ = now + kRetryDelay; } @@ -72,6 +114,9 @@ class RerouteState { private: bool off_route_ = false; Clock::time_point off_route_since_{}; + bool wrong_way_ = false; + bool wrong_way_armed_ = true; + Clock::time_point wrong_way_since_{}; Clock::time_point retry_at_{}; }; diff --git a/backends/osmand/ui/navigation_model.h b/backends/osmand/ui/navigation_model.h index c93a757..422f100 100644 --- a/backends/osmand/ui/navigation_model.h +++ b/backends/osmand/ui/navigation_model.h @@ -123,6 +123,10 @@ struct GuidanceState { // whether a new route from here is being calculated. double off_route_metres = 0.0; bool recalculating = false; + // The route's direction (degrees clockwise from north) where the car has + // got to along it; with the driving direction it tells a wrong way. + bool route_bearing_known = false; + double route_bearing_degrees = 0.0; // The road at the current position and its speed limit (0: unknown). std::string road; int speed_limit_kmh = 0; diff --git a/tests/navigation_ui_test.cpp b/tests/navigation_ui_test.cpp index 84555b2..2a4bb0c 100644 --- a/tests/navigation_ui_test.cpp +++ b/tests/navigation_ui_test.cpp @@ -942,6 +942,17 @@ void test_reroute() assert(tracker.update(route, {50.005, 30.0}).off_route_metres < 1.0); const auto off = tracker.update(route, {50.005, 30.002}); assert(off.off_route_metres > 100.0 && off.off_route_metres < 200.0); + // The route runs north here. + assert(off.route_bearing_known && + (off.route_bearing_degrees < 1.0 || off.route_bearing_degrees > 359.0)); + // Past the corner of a route that turns east, the direction there is east, + // also where the start of the route (heading north) is as near. + RouteAlternative corner = route; + corner.geometry = {{50.0, 30.0}, {50.01, 30.0}, {50.01, 30.02}}; + corner.distance_metres = 1112.0 + 1430.0; + GuidanceTracker corner_tracker; + const auto east = corner_tracker.update(corner, {50.01, 30.01}); + assert(east.route_bearing_known && std::fabs(east.route_bearing_degrees - 90.0) < 1.0); // One recalculation at a time; stale and wrong-screen results are ignored. const auto revision = model.request_reroute(); diff --git a/tests/reroute_state_test.cpp b/tests/reroute_state_test.cpp index 38d70ce..b6503f9 100644 --- a/tests/reroute_state_test.cpp +++ b/tests/reroute_state_test.cpp @@ -115,6 +115,39 @@ void test_detour_ends_when_route_recovers() } // namespace +void test_wrong_way_needs_sustained_reverse_driving() +{ + RerouteState state; + const auto t0 = Clock::now(); + const auto at = [&](int seconds) { return t0 + std::chrono::seconds(seconds); }; + // Along the route, sideways or not moving: nothing. + CHECK(!state.wrong_way_long_enough(false, 10.0, at(0))); + CHECK(!state.wrong_way_long_enough(false, 90.0, at(10))); + CHECK(!state.wrong_way_long_enough(false, std::nullopt, at(20))); + // Against it (either sign, any wrap) for 5 s. + CHECK(!state.wrong_way_long_enough(false, -175.0, at(30))); + CHECK(!state.wrong_way_long_enough(false, 535.0, at(34))); + CHECK(state.wrong_way_long_enough(false, 180.0, at(35))); + // Then not again on the new route until the car has driven along one. + CHECK(!state.wrong_way_long_enough(false, 180.0, at(36))); + CHECK(!state.wrong_way_long_enough(false, 180.0, at(60))); + state.clear_off_route(); + CHECK(!state.wrong_way_long_enough(false, 180.0, at(61))); + CHECK(!state.wrong_way_long_enough(false, 180.0, at(70))); + CHECK(!state.wrong_way_long_enough(false, 0.0, at(71))); + CHECK(!state.wrong_way_long_enough(false, 180.0, at(72))); + CHECK(state.wrong_way_long_enough(false, 180.0, at(77))); + // Stopping, arriving or a turn back along it restart the timer. + CHECK(!state.wrong_way_long_enough(false, 0.0, at(80))); + CHECK(!state.wrong_way_long_enough(false, 180.0, at(81))); + CHECK(!state.wrong_way_long_enough(false, std::nullopt, at(84))); + CHECK(!state.wrong_way_long_enough(false, 180.0, at(85))); + CHECK(!state.wrong_way_long_enough(true, 180.0, at(88))); + CHECK(!state.wrong_way_long_enough(false, 180.0, at(89))); + CHECK(!state.wrong_way_long_enough(false, 180.0, at(93))); + CHECK(state.wrong_way_long_enough(false, 180.0, at(94))); +} + void test_heading_memory_keeps_a_moving_heading_for_a_while() { HeadingMemory memory; @@ -144,6 +177,7 @@ int main() test_detour_starts_once_and_times_out(); test_detour_boundaries(); test_detour_ends_when_route_recovers(); + test_wrong_way_needs_sustained_reverse_driving(); test_heading_memory_keeps_a_moving_heading_for_a_while(); std::puts("reroute_state_test passed"); return 0;