Modern Apps git

← Modern-Apps.git

maps: routing snap to edge rather than node

Commit
4f2a9bbbdc45cd0a0d2e386d794df32cf34a7de4
Author
Vayun Mathur <[email protected]>
When
2026-03-11 00:48 UTC (9 months ago)
Parents
e8e2dbc

Diff

maps/src/main/cpp/native-lib.cpp
diff --git a/maps/src/main/cpp/native-lib.cpp b/maps/src/main/cpp/native-lib.cppindex d037c32233..d4c27cd2a7 100644--- a/maps/src/main/cpp/native-lib.cpp+++ b/maps/src/main/cpp/native-lib.cpp@@ -18,13 +18,15 @@ struct Edge { uint32_t source, target, dist_mm; uint8_t type; }; struct SpatialNode { uint64_t spatial_id; uint32_t local_id; }; #pragma pack(pop) +// Global Mapped Memory Pointers NodePos* g_nodes = nullptr; uint64_t* g_edge_index = nullptr; Edge* g_edges = nullptr;-SpatialNode* g_spatial = nullptr; // Added spatial mapping+SpatialNode* g_spatial = nullptr; size_t g_node_count = 0; -// Mapping function for Z-Order Curve+// --- MATH HELPERS ---+ uint64_t latlng_to_spatial(double lat, double lon) {     double x = (lon + 180.0) / 360.0;     double y = (lat + 90.0) / 180.0;@@ -38,31 +40,6 @@ uint64_t latlng_to_spatial(double lat, double lon) {     return res; } -// Binary search on the spatial index to find the nearest routable node-uint32_t find_nearest_node(double lat, double lon) {-    uint64_t target_spatial = latlng_to_spatial(lat, lon);--    // Find first element not less than target-    auto it = std::lower_bound(g_spatial, g_spatial + g_node_count, target_spatial,-                               [](const SpatialNode& a, uint64_t val) {-                                   return a.spatial_id < val;-                               });--    // Check neighbors to find the absolute closest spatial ID-    uint32_t best_id = 0;-    if (it == g_spatial + g_node_count) {-        best_id = (g_spatial + g_node_count - 1)->local_id;-    } else if (it == g_spatial) {-        best_id = it->local_id;-    } else {-        // Compare current 'it' and 'prev(it)' for closest match-        uint64_t diff1 = it->spatial_id - target_spatial;-        uint64_t diff2 = target_spatial - (it - 1)->spatial_id;-        best_id = (diff1 < diff2) ? it->local_id : (it - 1)->local_id;-    }-    return best_id;-}- uint32_t haversine_mm(int32_t lat1_e7, int32_t lon1_e7, int32_t lat2_e7, int32_t lon2_e7) {     double lat1 = (lat1_e7 / 1e7) * (M_PI / 180.0);     double lon1 = (lon1_e7 / 1e7) * (M_PI / 180.0);@@ -74,6 +51,67 @@ uint32_t haversine_mm(int32_t lat1_e7, int32_t lon1_e7, int32_t lat2_e7, int32_t     return (uint32_t)(2 * atan2(sqrt(a), sqrt(1 - a)) * 6371000.0 * 1000.0); } +struct Projection {+    int32_t lat_e7, lon_e7;+    uint32_t dist_mm;+};++// Calculates the closest point on segment (x1,y1)-(x2,y2) to point (px, py)+Projection get_projection(int32_t px, int32_t py, int32_t x1, int32_t y1, int32_t x2, int32_t y2) {+    double dx = (double)x2 - x1;+    double dy = (double)y2 - y1;+    double mag_sq = dx * dx + dy * dy;++    double t = (mag_sq == 0) ? 0 : ((double)(px - x1) * dx + (double)(py - y1) * dy) / mag_sq;+    t = std::max(0.0, std::min(1.0, t)); // Clamp to segment boundaries++    int32_t proj_lat = (int32_t)(x1 + t * dx);+    int32_t proj_lon = (int32_t)(y1 + t * dy);++    return {proj_lat, proj_lon, haversine_mm(px, py, proj_lat, proj_lon)};+}++// --- SNAPPING LOGIC ---++struct SnappedEdge {+    uint32_t nodeA, nodeB;+    int32_t proj_lat, proj_lon;+    uint32_t distToA, distToB;+};++SnappedEdge find_nearest_edge(double lat, double lon) {+    uint64_t target_spatial = latlng_to_spatial(lat, lon);+    int32_t pLat = (int32_t)(lat * 1e7), pLon = (int32_t)(lon * 1e7);++    // Binary search for the starting point in the Z-Order array+    auto it = std::lower_bound(g_spatial, g_spatial + g_node_count, target_spatial,+                               [](const SpatialNode& a, uint64_t val) { return a.spatial_id < val; });++    intptr_t center = std::distance(g_spatial, it);+    uint32_t bestA = 0, bestB = 0, minDist = 0xFFFFFFFF;+    int32_t finalLat = pLat, finalLon = pLon;++    // Windowed search (500 neighbors each way) to find the physically closest edge+    for (intptr_t i = std::max((intptr_t)0, center - 500); i <= std::min((intptr_t)g_node_count - 1, center + 500); ++i) {+        uint32_t u = g_spatial[i].local_id;+        for (uint64_t j = g_edge_index[u]; j < g_edge_index[u + 1]; ++j) {+            uint32_t v = g_edges[j].target;+            Projection p = get_projection(pLat, pLon, g_nodes[u].lat_e7, g_nodes[u].lon_e7, g_nodes[v].lat_e7, g_nodes[v].lon_e7);+            if (p.dist_mm < minDist) {+                minDist = p.dist_mm;+                bestA = u; bestB = v;+                finalLat = p.lat_e7; finalLon = p.lon_e7;+            }+        }+    }++    return {bestA, bestB, finalLat, finalLon,+            haversine_mm(finalLat, finalLon, g_nodes[bestA].lat_e7, g_nodes[bestA].lon_e7),+            haversine_mm(finalLat, finalLon, g_nodes[bestB].lat_e7, g_nodes[bestB].lon_e7)};+}++// --- JNI INTERFACE ---+ void* map_file(const char* path, size_t& size) {     int fd = open(path, O_RDONLY);     if (fd < 0) return nullptr;@@ -101,51 +139,60 @@ Java_com_vayunmathur_maps_OfflineRouter_init(JNIEnv* env, jobject thiz, jstring extern "C" JNIEXPORT jdoubleArray JNICALL Java_com_vayunmathur_maps_OfflineRouter_findShortestRouteNative(JNIEnv* env, jobject thiz,                                                                 jdouble sLat, jdouble sLon, jdouble eLat, jdouble eLon) {-    // 1. SNAPPING: Find actual start and end IDs from GPS-    uint32_t start_id = find_nearest_node(sLat, sLon);-    uint32_t end_id = find_nearest_node(eLat, eLon);+    // 1. SNAPPING TO ROAD EDGES+    SnappedEdge start = find_nearest_edge(sLat, sLon);+    SnappedEdge end = find_nearest_edge(eLat, eLon); -    LOGD("Snapped Start: %u (%.7f, %.7f) | Snapped End: %u (%.7f, %.7f)",-         start_id, g_nodes[start_id].lat_e7/1e7, g_nodes[start_id].lon_e7/1e7,-         end_id, g_nodes[end_id].lat_e7/1e7, g_nodes[end_id].lon_e7/1e7);+    LOGD("Snapped Start to Road: %.7f, %.7f | Snapped End to Road: %.7f, %.7f",+         start.proj_lat/1e7, start.proj_lon/1e7, end.proj_lat/1e7, end.proj_lon/1e7); -    // 2. A* SEARCH+    // 2. A* PREPARATION     std::vector<uint32_t> g_score(g_node_count, 0xFFFFFFFF);     std::vector<uint32_t> parent(g_node_count, 0xFFFFFFFF);     using NodeDist = std::pair<uint32_t, uint32_t>;     std::priority_queue<NodeDist, std::vector<NodeDist>, std::greater<NodeDist>> pq; -    g_score[start_id] = 0;-    uint32_t h_initial = haversine_mm(g_nodes[start_id].lat_e7, g_nodes[start_id].lon_e7,-                                      g_nodes[end_id].lat_e7, g_nodes[end_id].lon_e7);-    pq.push({h_initial, start_id});+    // Seed the priority queue with BOTH endpoints of the starting road segment+    // Seed the priority queue with BOTH endpoints of the starting road segment+    g_score[start.nodeA] = start.distToA;+    g_score[start.nodeB] = start.distToB;++    // Use the actual snapped destination coordinates for the heuristic+    uint32_t hA = haversine_mm(g_nodes[start.nodeA].lat_e7, g_nodes[start.nodeA].lon_e7, end.proj_lat, end.proj_lon);+    uint32_t hB = haversine_mm(g_nodes[start.nodeB].lat_e7, g_nodes[start.nodeB].lon_e7, end.proj_lat, end.proj_lon);++    pq.push({g_score[start.nodeA] + hA, start.nodeA});+    pq.push({g_score[start.nodeB] + hB, start.nodeB});      uint32_t nodes_visited = 0;-    uint32_t min_h = h_initial;+    uint32_t min_h = 0xFFFFFFFF;+    uint32_t found_end_node = 0xFFFFFFFF; +    // 3. A* SEARCH LOOP     while (!pq.empty()) {         uint32_t u = pq.top().second;         pq.pop();         nodes_visited++; -        uint32_t current_h = haversine_mm(g_nodes[u].lat_e7, g_nodes[u].lon_e7,-                                          g_nodes[end_id].lat_e7, g_nodes[end_id].lon_e7);+        // Heuristic distance to the snapped destination point+        uint32_t current_h = haversine_mm(g_nodes[u].lat_e7, g_nodes[u].lon_e7, end.proj_lat, end.proj_lon);          if (current_h < min_h) {             min_h = current_h;-            LOGD("[Progress] Closer: %.7f, %.7f (%.2f m to goal)",-                 g_nodes[u].lat_e7 / 1e7, g_nodes[u].lon_e7 / 1e7, current_h / 1000.0);-        }--        if (nodes_visited % 100 == 0) { // Increased log interval for performance-            LOGD("Visited: %u | MinDist: %.2f m", nodes_visited, min_h / 1000.0);+            if (nodes_visited % 10 == 0) {+                LOGD("[Progress] Closer: %.7f, %.7f (%.2f m to goal)",+                     g_nodes[u].lat_e7 / 1e7, g_nodes[u].lon_e7 / 1e7, current_h / 1000.0);+            }         } -        if (u == end_id) {+        // Target condition: Did we reach either endpoint of the destination's road?+        if (u == end.nodeA || u == end.nodeB) {+            found_end_node = u;             LOGD("Path found! Nodes searched: %u", nodes_visited);             break;         } +        if (u + 1 >= g_node_count) continue; // Safety bounds check for index         uint64_t start_off = g_edge_index[u];         uint64_t end_off = g_edge_index[u + 1]; @@ -155,26 +202,39 @@ Java_com_vayunmathur_maps_OfflineRouter_findShortestRouteNative(JNIEnv* env, job             if (g_score[u] + e.dist_mm < g_score[v]) {                 g_score[v] = g_score[u] + e.dist_mm;                 parent[v] = u;-                uint32_t h = haversine_mm(g_nodes[v].lat_e7, g_nodes[v].lon_e7,-                                          g_nodes[end_id].lat_e7, g_nodes[end_id].lon_e7);+                // Cost = dist_traveled + estimated_remaining_to_snapped_goal+                uint32_t h = haversine_mm(g_nodes[v].lat_e7, g_nodes[v].lon_e7, end.proj_lat, end.proj_lon);                 pq.push({g_score[v] + h, v});             }         }     } -    // 3. RECONSTRUCTION-    std::vector<double> flat_coords;-    if (g_score[end_id] != 0xFFFFFFFF) {-        for (uint32_t curr = end_id; curr != 0xFFFFFFFF; curr = parent[curr]) {-            flat_coords.push_back(g_nodes[curr].lat_e7 / 1e7);-            flat_coords.push_back(g_nodes[curr].lon_e7 / 1e7);+    // 4. PATH RECONSTRUCTION+    std::vector<double> final_path;++    // Add the snapped start coordinate first+    final_path.push_back(start.proj_lon / 1e7);+    final_path.push_back(start.proj_lat / 1e7);++    if (found_end_node != 0xFFFFFFFF) {+        std::vector<uint32_t> path_nodes;+        for (uint32_t curr = found_end_node; curr != 0xFFFFFFFF; curr = parent[curr]) {+            path_nodes.push_back(curr);+        }+        std::reverse(path_nodes.begin(), path_nodes.end());+        for (uint32_t id : path_nodes) {+            final_path.push_back(g_nodes[id].lon_e7 / 1e7);+            final_path.push_back(g_nodes[id].lat_e7 / 1e7);         }-        std::reverse(flat_coords.begin(), flat_coords.end());     } else {-        LOGD("Route not found between requested points.");+        LOGD("Route not found between snapped points.");     } -    jdoubleArray result = env->NewDoubleArray(flat_coords.size());-    env->SetDoubleArrayRegion(result, 0, flat_coords.size(), flat_coords.data());+    // Add the snapped end coordinate last+    final_path.push_back(end.proj_lon / 1e7);+    final_path.push_back(end.proj_lat / 1e7);++    jdoubleArray result = env->NewDoubleArray(final_path.size());+    env->SetDoubleArrayRegion(result, 0, final_path.size(), final_path.data());     return result; }\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/OfflineRouter.ktindex e6d766ab51..8f880272b0 100644--- a/maps/src/main/java/com/vayunmathur/maps/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/OfflineRouter.kt@@ -3,11 +3,19 @@ package com.vayunmathur.maps import android.content.Context import android.util.Log import com.vayunmathur.maps.data.SpecificFeature+import io.github.kevincianfarini.alchemist.scalar.meters import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.maplibre.spatialk.geojson.Position import java.io.File+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.pow+import kotlin.math.sin+import kotlin.math.sqrt+import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds  object OfflineRouter {     init {@@ -72,13 +80,40 @@ object OfflineRouter {             positions.add(Position(rawCoords[i], rawCoords[i + 1]))         } +        val distance = positions.zipWithNext().sumOf {+            haversine(it.first, it.second)+        }++        val time = (distance.meters / (4500.meters/1.hours))+         RouteService.Route(-            duration = 5.minutes, // You could calculate this in C++ and return as part of the array-            distanceMeters = 100.0,+            duration = time.inWholeSeconds.seconds, // You could calculate this in C++ and return as part of the array+            distanceMeters = distance,             polyline = positions,             step = listOf(RouteService.Step(-                100.0, 5.minutes, positions, RouteService.API.NavInstruction(), RouteService.TravelMode.WALK)+                distance, time.inWholeSeconds.seconds, positions, RouteService.API.NavInstruction(), RouteService.TravelMode.WALK)             )         )     }++    fun haversine(pos1: Position, pos2: Position): Double {+        val r = 6371_000.0++        val lat1 = Math.toRadians(pos1.latitude)+        val lon1 = Math.toRadians(pos1.longitude)+        val lat2 = Math.toRadians(pos2.latitude)+        val lon2 = Math.toRadians(pos2.longitude)++        val dLat = lat2 - lat1+        val dLon = lon2 - lon1++        // The Haversine formula+        val a = sin(dLat / 2).pow(2.0) ++                cos(lat1) * cos(lat2) *+                sin(dLon / 2).pow(2.0)++        val c = 2 * atan2(sqrt(a), sqrt(1 - a))++        return r * c+    } }\ No newline at end of file