maps: port offline routing engine from C++ to Rust
- Commit
0c52b5adcdafd7bd35e669c581723e0645d0321e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-30 03:03 UTC (4 months ago)
- Parents
df47309
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 3ec519e641..9ac89266d8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -859,6 +859,15 @@ dependencies = [ "serde_json", ] +[[package]]+name = "offlinerouter"+version = "0.1.0"+dependencies = [+ "flate2",+ "jni",+ "libc",+]+ [[package]] name = "om-file-format-sys" version = "0.0.0"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 91e49db743..4c3ddb88ed 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -6,6 +6,7 @@ members = [ "weather/src/main/rust", "pdf/src/main/rust", "camera/src/main/rust",+ "maps/src/main/rust", "passwords/src/main/rust", "library/e2ee-p2p/src/main/rust", "third_party/om-file-format-sys",
maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex ac619af1ff..920946fc8b 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -12,15 +12,20 @@ android { defaultConfig { applicationId = "com.vayunmathur.maps" }+} - externalNativeBuild {- cmake {- path = file("src/main/cpp/CMakeLists.txt")- version = "4.1.2"- }+androidComponents {+ onVariants { variant ->+ variant.sources.jniLibs?.addStaticSourceDirectory(+ layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ ) } } +// Native offline routing engine + traffic MVT tile encoder (Rust). See+// maps/src/main/rust/. Replaces the previous CMake/C++ libofflinerouter.+rustNativeLib("offlinerouter", "maps")+ dependencies { implementation(libs.maplibre.compose) implementation(libs.coil.compose)
maps/src/main/cpp/CMakeLists.txt
diff --git a/maps/src/main/cpp/CMakeLists.txt b/maps/src/main/cpp/CMakeLists.txtdeleted file mode 100644index 2021fa895a..0000000000--- a/maps/src/main/cpp/CMakeLists.txt+++ /dev/null@@ -1,30 +0,0 @@-cmake_minimum_required(VERSION 4.1.2)-project("offlinerouter")--add_library(offlinerouter SHARED native-lib.cpp)--target_compile_options(offlinerouter PRIVATE- -O3 # Maximum optimization- -ffast-math # Speed up coordinate math (breaks strict IEEE compliance)- -fomit-frame-pointer # Frees up register x29 for general use- -fno-plt # Encourages direct calls over PLT jumps-)--if(${ANDROID_ABI} MATCHES "arm.*")- target_compile_options(offlinerouter PRIVATE -mbranch-protection=none)-endif()--if(${ANDROID_ABI} STREQUAL "arm64-v8a")- target_compile_options(offlinerouter PRIVATE -march=armv8-a+simd+crypto)-endif()--find_library(log-lib log)-find_library(z-lib z)--# Android SQLite removed: maps offline router now memory-only.-# Previously bundled sqlite3.c (9MB) for traffic_cache.mbtiles MBTiles cache.-# Android's system libsqlite.so is private (not NDK-stable), and Room-# (amenities.db) already uses Android SQLite via androidx.sqlite.-# Traffic cache was just an optimization that invalidated tiles on every-# update (DELETE FROM tiles), so in-memory cache + NetworkClient is sufficient.-target_link_libraries(offlinerouter ${log-lib} ${z-lib})\ No newline at end of file
maps/src/main/cpp/native-lib.cpp
diff --git a/maps/src/main/cpp/native-lib.cpp b/maps/src/main/cpp/native-lib.cppdeleted file mode 100644index c634809e87..0000000000--- a/maps/src/main/cpp/native-lib.cpp+++ /dev/null@@ -1,1225 +0,0 @@-#include <jni.h>-#include <sys/mman.h>-#include <fcntl.h>-#include <unistd.h>-#include <vector>-#include <string>-#include <cmath>-#include <algorithm>-#include <mutex>-#include <set>-#include <map>-#include <android/log.h>-#include <zlib.h>-// sqlite3.c removed – maps router now memory-only. Android SQLite via Room (amenities.db) and in-memory g_traffic_by_square for traffic overlay. See CMakeLists.txt.--#include "scratchpad.h"-#include "radix_heap.h"--#define LOG_TAG "OfflineRouterNative"-#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)--// User-specified Travel Mode mapping-enum TravelMode { DRIVING = 0, PUBLIC_TRANSIT = 1, WALK = 2, BICYCLE = 3 };--// Road types based on OpenStreetMap tags-enum RoadType {- MOTORWAY = 1, TRUNK = 2, PRIMARY = 3, SECONDARY = 4, TERTIARY = 5,- UNCLASSIFIED = 6, RESIDENTIAL = 7, SERVICE = 8, LIVING_STREET = 9,- PEDESTRIAN = 10, TRACK = 11, FOOTWAY = 12, CYCLEWAY = 13, PATH = 14, STEPS = 15-};--#define REVERSE_GEOMETRY_FLAG 0x40-#define TRANSIT_FLAG 0x80--#pragma pack(push, 1)-struct NodeMaster {- int32_t lat_e7, lon_e7;- uint64_t edge_ptr;-};--struct Edge {- uint32_t target;- uint32_t dist_mm;- uint32_t name_offset;- uint8_t type;- uint8_t speed_limit;-};--struct TransitVoyageCompact {- uint16_t dep_delta;- uint16_t duration;-};--struct TransitAttribute {- uint32_t stop_code_off;- uint32_t feed_name_off;-};-#pragma pack(pop)--// Sentinel for "no edge" where a u64 global edge index is expected.-static constexpr uint64_t INVALID_EDGE = 0xFFFFFFFFFFFFFFFFULL;--// --- GLOBALS ----// The routing graph is now a single global whole-world dataset (no zonation).-NodeMaster* g_nodes = nullptr; // g_node_count real nodes + 1 sentinel-uint32_t g_node_count = 0; // node IDs stay 32-bit-Edge* g_edges = nullptr;-uint64_t g_edge_count = 0; // edge indices are global 64-bit-TransitVoyageCompact* g_transit_voyages = nullptr;-uint64_t g_transit_voyage_count = 0;-TransitAttribute* g_transit_attributes = nullptr;--char* g_road_names = nullptr;-size_t g_road_names_size = 0;-std::string g_base_path;--struct LatLon {- int32_t lat_e7;- int32_t lon_e7;-};--void* g_intermediate_mmap_ptr = nullptr;-size_t g_intermediate_mmap_size = 0;-uint64_t* g_intermediate_edge_offsets = nullptr; // length g_edge_count + 1 (u64 byte offsets)-uint8_t* g_intermediate_data = nullptr; // delta-encoded coordinate bytes--uint64_t g_time_scale_fixed[4]; // Heuristic scales (10ms units per mm)-uint64_t g_edge_time_multipliers[4][16]; // Speed-to-time conversion factors for WALK/BIKE/DRIVING(fallback)-const double WALK_SPEED_M_S = 4.5 / 3.6;-const double BICYCLE_SPEED_M_S = 16.0 / 3.6;-const double DEG_TO_RAD = M_PI / 180.0;--uint32_t g_lon_to_mm_scale[4096];--static RoutingScratchpad g_scratchpad;-static TrafficPageTable g_traffic;-static RadixHeap g_heap; // Only one heap needed for unidirectional--static std::map<int, std::vector<double>> g_traffic_by_square;-static std::vector<uint32_t> g_requested_squares; // Packed (lat_idx << 16 | lon_idx)-static std::set<std::string> g_present_feeds;-static std::mutex g_traffic_mutex;-// g_db removed – sqlite3.c amalgamation (9MB) dropped. traffic_cache.mbtiles persistence removed; traffic now memory-only via NetworkClient + g_traffic_by_square.--// --- UTILS -----static std::vector<uint8_t> compress_gzip(const std::vector<uint8_t>& input) {- if (input.empty()) return {};- z_stream zs;- memset(&zs, 0, sizeof(zs));- if (deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY) != Z_OK) return {};- zs.next_in = (Bytef*)input.data();- zs.avail_in = input.size();- int ret;- char buffer[32768];- std::vector<uint8_t> output;- do {- zs.next_out = (Bytef*)buffer;- zs.avail_out = sizeof(buffer);- ret = deflate(&zs, Z_FINISH);- if (output.size() < zs.total_out) {- output.insert(output.end(), (uint8_t*)buffer, (uint8_t*)buffer + (zs.total_out - output.size()));- }- } while (ret == Z_OK);- deflateEnd(&zs);- if (ret != Z_STREAM_END) return {};- return output;-}--inline uint32_t find_node_idx_for_edge(uint64_t edge_idx) {- // Largest node index whose edge_ptr <= edge_idx (edge_ptr is monotonic).- int64_t low = 0, high = (int64_t)g_node_count - 1;- uint32_t res = 0;- while (low <= high) {- int64_t mid = low + (high - low) / 2;- if (g_nodes[mid].edge_ptr <= edge_idx) {- res = (uint32_t)mid;- low = mid + 1;- } else {- high = mid - 1;- }- }- return res;-}--struct EdgeCoords {- const LatLon* coords;- uint32_t count;- bool is_reversed;-};--// Static decode buffer for delta-encoded intermediate coordinates.-// Edges rarely exceed ~30 shape points; 256 is very safe.-static LatLon s_decoded_coords[256];--// Decode delta-encoded coordinate blob into s_decoded_coords.-// Returns the number of decoded points.-inline uint32_t decode_edge_coords(const uint8_t* data, uint32_t byte_len) {- if (byte_len < 8) return 0;- // First point is absolute: int32_t lat_e7, int32_t lon_e7 (8 bytes)- int32_t lat, lon;- memcpy(&lat, data, 4);- memcpy(&lon, data + 4, 4);- s_decoded_coords[0] = { lat, lon };- - uint32_t count = 1;- uint32_t off = 8;- while (off + 4 <= byte_len && count < 256) {- int16_t d_lat, d_lon;- memcpy(&d_lat, data + off, 2);- memcpy(&d_lon, data + off + 2, 2);- lat += d_lat;- lon += d_lon;- s_decoded_coords[count++] = { lat, lon };- off += 4;- }- return count;-}--inline EdgeCoords get_edge_coordinates(uint64_t edge_idx) {- if (!g_edges || edge_idx >= g_edge_count) return {nullptr, 0, false};- const Edge& e = g_edges[edge_idx];- - if (e.type & REVERSE_GEOMETRY_FLAG) {- uint32_t u_global = find_node_idx_for_edge(edge_idx);- uint32_t v_global = e.target;- if (v_global < g_node_count && g_edges) {- uint64_t s = g_nodes[v_global].edge_ptr;- uint64_t e_ptr = g_nodes[v_global + 1].edge_ptr; // sentinel guarantees valid- for (uint64_t k = s; k < e_ptr; ++k) {- if (g_edges[k].target == u_global) {- if (g_intermediate_edge_offsets != nullptr && g_intermediate_data != nullptr) {- uint64_t start_byte = g_intermediate_edge_offsets[k];- uint64_t end_byte = g_intermediate_edge_offsets[k + 1];- uint32_t cnt = decode_edge_coords(g_intermediate_data + start_byte, (uint32_t)(end_byte - start_byte));- return { s_decoded_coords, cnt, true };- }- break;- }- }- }- } else {- if (g_intermediate_edge_offsets != nullptr && g_intermediate_data != nullptr) {- uint64_t start_byte = g_intermediate_edge_offsets[edge_idx];- uint64_t end_byte = g_intermediate_edge_offsets[edge_idx + 1];- uint32_t cnt = decode_edge_coords(g_intermediate_data + start_byte, (uint32_t)(end_byte - start_byte));- return { s_decoded_coords, cnt, false };- }- }- return {nullptr, 0, false};-}--inline LatLon get_pt_at(const EdgeCoords& ec, uint32_t idx) {- if (ec.is_reversed) {- return ec.coords[ec.count - 1 - idx];- } else {- return ec.coords[idx];- }-}--static void load_traffic_from_db(int /*packed_square*/) {- // No-op: sqlite3.c removed. Previously loaded raw_traffic from traffic_cache.mbtiles.- // Now traffic is memory-only (fetched via NetworkClient in OfflineRouter.kt -> updateTrafficNative).-}--// --- MVT ENCODING UTILS ----static void write_varint(std::vector<uint8_t>& buf, uint64_t value) {- while (value >= 0x80) {- buf.push_back((uint8_t)(value | 0x80));- value >>= 7;- }- buf.push_back((uint8_t)value);-}--static void write_tag(std::vector<uint8_t>& buf, uint32_t field, uint8_t type) {- write_varint(buf, (field << 3) | type);-}--static void write_string(std::vector<uint8_t>& buf, uint32_t field, const std::string& s) {- write_tag(buf, field, 2);- write_varint(buf, s.size());- buf.insert(buf.end(), s.begin(), s.end());-}--static int32_t zigzag(int32_t n) { return (n << 1) ^ (n >> 31); }--static uint32_t mvt_command(uint32_t cmd, uint32_t count) { return (cmd & 0x7) | (count << 3); }--struct TileProj {- double n;- int x, y;- void wgs84_to_tile_px(double lat, double lon, int32_t& px, int32_t& py) const {- double lat_rad = lat * M_PI / 180.0;- double tx = (lon + 180.0) / 360.0 * n;- double ty = (1.0 - std::log(std::tan(lat_rad) + (1.0 / std::cos(lat_rad))) / M_PI) / 2.0 * n;- px = (int32_t)((tx - x) * 4096.0);- py = (int32_t)((ty - y) * 4096.0);- }-};--uint64_t latlng_to_spatial(double lat, double lon) {- double x = (lon + 180.0) / 360.0;- double y = (lat + 90.0) / 180.0;- auto ix = (uint32_t)(x * 4294967295.0), iy = (uint32_t)(y * 4294967295.0);- uint64_t res = 0;- for (int i = 0; i < 32; i++) {- res |= ((uint64_t)((ix >> i) & 1) << (2 * i));- res |= ((uint64_t)((iy >> i) & 1) << (2 * i + 1));- }- return res;-}--inline uint64_t get_node_spatial_id(const NodeMaster& node) {- return latlng_to_spatial(node.lat_e7 * 1e-7, node.lon_e7 * 1e-7);-}--inline TransitAttribute get_node_transit_attr(uint32_t node_id) {- if (g_transit_attributes && node_id < g_node_count) {- return g_transit_attributes[node_id];- }- return { 0xFFFFFFFF, 0xFFFFFFFF };-}--inline uint32_t get_node_feed_name_off(uint32_t node_id) {- return get_node_transit_attr(node_id).feed_name_off;-}--inline uint32_t get_node_stop_code_off(uint32_t node_id) {- return get_node_transit_attr(node_id).stop_code_off;-}--inline const NodeMaster& get_node(uint32_t node_id) {- if (!g_nodes || node_id >= g_node_count) {- static NodeMaster null_node = {0,0,0};- return null_node;- }- return g_nodes[node_id];-}--void ensure_traffic_loaded(JNIEnv* env, jobject thiz, int32_t lat_e7, int32_t lon_e7, bool force_async) {- int32_t lat_idx = (int32_t)floor(lat_e7 * 1e-7);- int32_t lon_idx = (int32_t)floor(lon_e7 * 1e-7);- uint32_t packed = ((uint32_t)(lat_idx + 360) << 16) | (uint32_t)(lon_idx + 720);-- {- std::lock_guard<std::mutex> lock(g_traffic_mutex);- if (std::find(g_requested_squares.begin(), g_requested_squares.end(), packed) != g_requested_squares.end()) {- return;- }- LOGD("ensure_traffic_loaded: REQUESTING square %u", packed);- g_requested_squares.push_back(packed);- }-- jclass clazz = env->GetObjectClass(thiz);- jmethodID method = env->GetMethodID(clazz, "fetchTrafficData", "(DDDDIZ)V");- if (method) {- LOGD("ensure_traffic_loaded: CALLING fetchTrafficData for square %u, async=%d", packed, force_async);- env->CallVoidMethod(thiz, method, (double)lat_idx, (double)lon_idx, (double)lat_idx + 1.0, (double)lon_idx + 1.0, (jint)packed, (jboolean)force_async);- LOGD("ensure_traffic_loaded: RETURNED from fetchTrafficData for square %u", packed);- }-}--// --- ROAD PERMISSIONS -----inline bool is_mode_allowed(uint8_t road_type, int mode) {- uint8_t type = road_type & 0x7F;- if (mode == DRIVING) {- return (type >= MOTORWAY && type <= LIVING_STREET);- }- if (mode == PUBLIC_TRANSIT) {- return (road_type & TRANSIT_FLAG) || (type >= MOTORWAY && type <= STEPS);- }- return (type >= MOTORWAY && type <= STEPS);-}--// --- GEOMETRY -----__attribute__((always_inline)) inline uint32_t fast_dist_mm(int32_t lat1_e7, int32_t lon1_e7, int32_t lat2_e7, int32_t lon2_e7) {- int64_t dlat = std::abs((int64_t)lat1_e7 - lat2_e7);- int64_t dlon = std::abs((int64_t)lon1_e7 - lon2_e7);-- // 1 unit (1e-7 deg) latitude is ~11.1139 mm- int64_t dy_mm = (dlat * 111139) / 10000;-- auto scale_idx = (uint32_t)(((lat1_e7 + lat2_e7) / 2 >> 19) + 2048);- uint32_t scale = g_lon_to_mm_scale[scale_idx & 4095];- int64_t dx_mm = (dlon * scale) >> 10;-- uint64_t max_v = (dx_mm > dy_mm) ? dx_mm : dy_mm;- uint64_t min_v = (dx_mm > dy_mm) ? dy_mm : dx_mm;- return (uint32_t)(max_v - (max_v >> 5) + (min_v >> 1) - (min_v >> 3));-}--inline uint32_t accurate_dist_mm(int32_t lat1_e7, int32_t lon1_e7, int32_t lat2_e7, int32_t lon2_e7) {- const double R = 6371000800.0;- double phi1 = (lat1_e7 * 1e-7) * DEG_TO_RAD;- double phi2 = (lat2_e7 * 1e-7) * DEG_TO_RAD;- double delta_phi = (lat2_e7 - lat1_e7) * 1e-7 * DEG_TO_RAD;- double delta_lambda = (lon2_e7 - lon1_e7) * 1e-7 * DEG_TO_RAD;- double s_dphi = sin(delta_phi / 2.0);- double s_dlamb = sin(delta_lambda / 2.0);- double a = s_dphi * s_dphi + cos(phi1) * cos(phi2) * s_dlamb * s_dlamb;- double dist = R * 2.0 * atan2(sqrt(a), sqrt(1.0 - a));- // Saturate instead of truncating: uint32_t maxes out at ~4 294 km,- // and cross-country transit edges can exceed that. A wraparound- // turns a 5 000 km segment into a 705 km segment in the cost- // function and silently breaks routing; saturating preserves the- // "this edge is enormous" signal even if it's no longer exact.- if (dist >= (double)UINT32_MAX) return UINT32_MAX;- if (dist < 0.0) return 0;- return (uint32_t)dist;-}--inline uint32_t get_edge_time_10ms(uint64_t edge_id, uint32_t dist_mm, uint8_t type, uint8_t limit, int mode) {- if (mode == DRIVING) {- uint8_t traffic_speed = (edge_id != INVALID_EDGE) ? g_traffic.get_speed(edge_id) : 0;- uint8_t effective_limit = (traffic_speed > 0) ? traffic_speed : limit;- if (effective_limit > 0) {- double speed_m_s = (double)effective_limit / 3.6;- return (uint32_t)((double)dist_mm / (speed_m_s * 10.0));- }- }- uint64_t multiplier = g_edge_time_multipliers[mode & 0x3][(type & 0x7F) & 0xF];- return (uint32_t)(((uint64_t)dist_mm * multiplier) >> 32);-}--inline uint32_t get_transit_edge_time_10ms(const Edge& edge, uint32_t current_time_from_start, uint32_t start_time_abs, uint32_t feed_off, bool is_boarding_or_transfer, uint32_t& wait_out, uint32_t& travel_out) {- wait_out = 0; travel_out = 0;- if (!g_transit_voyages) return 0xFFFFFFFF;-- uint32_t voyage_offset = edge.dist_mm;- uint32_t voyage_count = edge.speed_limit;- if (voyage_count == 0) return 0xFFFFFFFF;-- const char* route_name = (edge.name_offset < g_road_names_size) ? (g_road_names + edge.name_offset) : "Unknown";-- TransitVoyageCompact* base = g_transit_voyages + voyage_offset;-- if (feed_off != 0xFFFFFFFF && feed_off < g_road_names_size) {- const char* feed_name = g_road_names + feed_off;- if (g_present_feeds.find(feed_name) == g_present_feeds.end()) {- wait_out = 0; - travel_out = base[1].dep_delta; // duration of voyage 0- return travel_out;- }- }-- const uint32_t BOARDING_PENALTY = 6000; // 1 minute to platform- uint32_t abs_now = (start_time_abs + current_time_from_start) % (24 * 3600 * 100);- uint32_t arrival_at_platform = (abs_now + (is_boarding_or_transfer ? BOARDING_PENALTY : 0)) % (24 * 3600 * 100);- const uint32_t DAY_10MS = 24 * 3600 * 100;-- uint32_t best_wait = 0xFFFFFFFF;- uint32_t best_travel = 0;-- // Voyage 0- uint32_t dep = *(uint32_t*)base;- uint32_t duration = base[1].dep_delta;- {- uint32_t dep_mod = dep % DAY_10MS;- uint32_t wait = 0;- if (dep_mod >= arrival_at_platform) {- wait = dep_mod - arrival_at_platform;- } else {- wait = (DAY_10MS - arrival_at_platform) + dep_mod;- }- if (wait < best_wait) {- best_wait = wait;- best_travel = duration;- }- }-- // Voyages 1+- uint32_t dep_prev = dep;- for (uint32_t i = 1; i < voyage_count; ++i) {- TransitVoyageCompact compact = base[1 + i];- dep = dep_prev + (uint32_t)compact.dep_delta * 100;- dep_prev = dep;- - uint32_t dep_mod = dep % DAY_10MS;- uint32_t wait = 0;- if (dep_mod >= arrival_at_platform) {- wait = dep_mod - arrival_at_platform;- } else {- wait = (DAY_10MS - arrival_at_platform) + dep_mod;- }- if (wait < best_wait) {- best_wait = wait;- best_travel = compact.duration;- }- }-- if (best_wait == 0xFFFFFFFF) return 0xFFFFFFFF;-- wait_out = best_wait; travel_out = best_travel;- return (is_boarding_or_transfer ? BOARDING_PENALTY : 0) + best_wait + best_travel;-}--inline uint32_t heuristic_time_10ms(int32_t lat1, int32_t lon1, int32_t lat2, int32_t lon2, int mode) {- uint32_t dist_mm = fast_dist_mm(lat1, lon1, lat2, lon2);- uint64_t scaled_time = (uint64_t)dist_mm * g_time_scale_fixed[mode & 0x3];- return (uint32_t)(scaled_time >> 32);-}--double get_bearing(int32_t lat1, int32_t lon1, int32_t lat2, int32_t lon2) {- double f1 = (lat1 / 1e7) * DEG_TO_RAD;- double f2 = (lat2 / 1e7) * DEG_TO_RAD;- double dl = ((lon2 - lon1) / 1e7) * DEG_TO_RAD;- double y = sin(dl) * cos(f2);- double x = cos(f1) * sin(f2) - sin(f1) * cos(f2) * cos(dl);- return atan2(y, x) * (180.0 / M_PI);-}--int get_maneuver(double prev_bearing, double next_bearing) {- double angle_diff = next_bearing - prev_bearing;- while (angle_diff < -180) angle_diff += 360;- while (angle_diff > 180) angle_diff -= 360;- if (angle_diff > 155 || angle_diff < -155) return 3;- if (angle_diff < -100) return 2;- if (angle_diff < -45) return 4;- if (angle_diff < -10) return 1;- if (angle_diff < 10) return 9;- if (angle_diff < 45) return 5;- if (angle_diff < 100) return 8;- return 6;-}--// --- CORE ROUTING -----struct SnappedEdge {- uint32_t nodeA, nodeB;- int32_t proj_lat, proj_lon;- uint32_t distA_mm, distB_mm;- uint8_t type;- uint8_t speed_limit;- uint32_t name_offset;- uint64_t edge_idx = INVALID_EDGE;- uint32_t segment_idx = 0;-};--struct RoutingContext {- SnappedEdge start, end;- uint32_t target_node = 0xFFFFFFFF;- int iterations = 0;- uint32_t startTime = 0;-};--struct Projection { int32_t lat_e7, lon_e7; uint32_t dist_mm; };--Projection get_projection(int32_t px, int32_t py, int32_t x1, int32_t y1, int32_t x2, int32_t y2) {- double lat_avg = (x1 + x2) / 2.0 * 1e-7;- double lon_scale = cos(lat_avg * DEG_TO_RAD);-- double dx = (double)x2 - x1;- double dy = ((double)y2 - y1) * lon_scale;- double dpx = (double)px - x1;- double dpy = ((double)py - y1) * lon_scale;-- double mag_sq = dx * dx + dy * dy;- double t = (mag_sq == 0) ? 0 : (dpx * dx + dpy * dy) / mag_sq;- t = std::max(0.0, std::min(1.0, t));-- int32_t proj_lat = (int32_t)(x1 + t * (x2 - x1));- int32_t proj_lon = (int32_t)(y1 + t * (y2 - y1));- return {proj_lat, proj_lon, fast_dist_mm(px, py, proj_lat, proj_lon)};-}--SnappedEdge find_nearest_edge(double lat, double lon, int mode) {- uint64_t target_spatial = latlng_to_spatial(lat, lon);- int32_t pLat = lat * 1e7, pLon = lon * 1e7;- SnappedEdge best;- best.nodeA = 0xFFFFFFFF;- best.nodeB = 0xFFFFFFFF;- best.proj_lat = pLat;- best.proj_lon = pLon;- best.distA_mm = 0;- best.distB_mm = 0;- best.type = 0;- best.speed_limit = 0;- best.name_offset = 0xFFFFFFFF;- best.edge_idx = INVALID_EDGE;- best.segment_idx = 0;-- if (!g_nodes || g_node_count == 0) return best;-- uint32_t minSnapDist = 0xFFFFFFFF;-- // Binary search the single globally spatial-sorted node array for the node- // nearest (just below) the target Morton code.- uint32_t low = 0, high = g_node_count - 1, local_center = 0;- while (low <= high) {- uint32_t mid = low + (high - low) / 2;- if (get_node_spatial_id(g_nodes[mid]) < target_spatial) {- local_center = mid;- low = mid + 1;- } else {- if (mid == 0) break;- high = mid - 1;- }- }-- int window = 800;- for (int i = std::max(0, (int)local_center - window); i <= std::min((int)g_node_count - 1, (int)local_center + window); ++i) {- uint32_t u_global = (uint32_t)i;- const auto& node_u = g_nodes[i];- uint64_t e_ptr = g_nodes[i + 1].edge_ptr; // sentinel guarantees valid- for (uint64_t j = node_u.edge_ptr; j < e_ptr; ++j) {- Edge& e = g_edges[j];- if (e.type & TRANSIT_FLAG) continue;- if (!is_mode_allowed(e.type, mode)) continue;- if (e.target >= g_node_count) continue;-- EdgeCoords ec = get_edge_coordinates(j);- if (ec.coords != nullptr && ec.count >= 2) {- uint32_t num_pts = ec.count;- uint32_t current_dist_from_start_mm = 0;- for (uint32_t p = 0; p < num_pts - 1; ++p) {- const auto p1 = get_pt_at(ec, p);- const auto p2 = get_pt_at(ec, p + 1);-- Projection proj = get_projection(pLat, pLon, p1.lat_e7, p1.lon_e7, p2.lat_e7, p2.lon_e7);- if (proj.dist_mm < minSnapDist) {- minSnapDist = proj.dist_mm;- best.nodeA = u_global;- best.nodeB = e.target;- best.proj_lat = proj.lat_e7;- best.proj_lon = proj.lon_e7;- best.type = e.type;- best.speed_limit = e.speed_limit;- best.name_offset = e.name_offset;- best.edge_idx = j;- best.segment_idx = p;-- uint32_t dist_to_proj_seg_mm = fast_dist_mm(p1.lat_e7, p1.lon_e7, proj.lat_e7, proj.lon_e7);- best.distA_mm = current_dist_from_start_mm + dist_to_proj_seg_mm;- best.distB_mm = (e.dist_mm > best.distA_mm) ? (e.dist_mm - best.distA_mm) : 0;- }- current_dist_from_start_mm += fast_dist_mm(p1.lat_e7, p1.lon_e7, p2.lat_e7, p2.lon_e7);- }- } else {- const auto& node_v = g_nodes[e.target];- Projection p = get_projection(pLat, pLon, node_u.lat_e7, node_u.lon_e7, node_v.lat_e7, node_v.lon_e7);- if (p.dist_mm < minSnapDist) {- minSnapDist = p.dist_mm;- best.nodeA = u_global; best.nodeB = e.target; best.proj_lat = p.lat_e7; best.proj_lon = p.lon_e7;- best.distA_mm = fast_dist_mm(p.lat_e7, p.lon_e7, node_u.lat_e7, node_u.lon_e7);- best.distB_mm = fast_dist_mm(p.lat_e7, p.lon_e7, node_v.lat_e7, node_v.lon_e7);- best.type = e.type; best.speed_limit = e.speed_limit; best.name_offset = e.name_offset;- best.edge_idx = j; best.segment_idx = 0;- }- }- }- }- return best;-}--bool prepare_routing(JNIEnv* env, jobject thiz, double sLat, double sLon, double eLat, double eLon, int mode, uint32_t startTime, RoutingContext& ctx) {- LOGD("prepare_routing: mode=%d, start=(%f,%f), end=(%f,%f)", mode, sLat, sLon, eLat, eLon);- g_scratchpad.reset(); g_heap.clear();- ctx.iterations = 0; ctx.target_node = 0xFFFFFFFF; ctx.startTime = startTime;- ctx.start = find_nearest_edge(sLat, sLon, mode);- ctx.end = find_nearest_edge(eLat, eLon, mode);- if (ctx.start.nodeA == 0xFFFFFFFF) {- LOGE("prepare_routing: failed to find start edge");- return false;- }- if (ctx.end.nodeA == 0xFFFFFFFF) {- LOGE("prepare_routing: failed to find end edge");- return false;- }- LOGD("prepare_routing: start snapped to nodeA=%u, nodeB=%u", ctx.start.nodeA, ctx.start.nodeB);- if (mode == DRIVING) ensure_traffic_loaded(env, thiz, ctx.start.proj_lat, ctx.start.proj_lon, false);- auto push = [&](uint32_t node, uint32_t travel_dist_mm) {- uint32_t t_actual = get_edge_time_10ms(INVALID_EDGE, travel_dist_mm, ctx.start.type, ctx.start.speed_limit, mode);- auto& entry = g_scratchpad.get_entry(node, 0);- entry.g_fwd = t_actual;- entry.g_bwd = t_actual;- entry.last_type = ctx.start.type;- const auto& n_data = get_node(node);- uint32_t h = heuristic_time_10ms(n_data.lat_e7, n_data.lon_e7, ctx.end.proj_lat, ctx.end.proj_lon, mode);- g_heap.push(t_actual + h, node << 1); // Start in state 0- };- push(ctx.start.nodeA, ctx.start.distA_mm); push(ctx.start.nodeB, ctx.start.distB_mm);- return true;-}--void perform_search_loop(JNIEnv* env, jobject thiz, int mode, RoutingContext& ctx) {- LOGD("perform_search_loop: starting search");- while (!g_heap.empty() && ctx.iterations < 1000000) {- ctx.iterations++;- uint32_t u_idx = g_heap.pop();- uint32_t u = u_idx >> 1;- int u_state = u_idx & 1;-- if ((u == ctx.end.nodeA || u == ctx.end.nodeB) && (mode != PUBLIC_TRANSIT || u_state == 1)) {- ctx.target_node = u_idx;- LOGD("perform_search_loop: target found in %d iterations", ctx.iterations);- break;- }-- auto& entry_u = g_scratchpad.get_entry(u, u_state);- uint32_t u_cost = entry_u.g_fwd;- uint32_t u_actual_time = entry_u.g_bwd;- if (!g_nodes || u >= g_node_count) continue;- const auto& n_u = g_nodes[u];-- if (mode == DRIVING) ensure_traffic_loaded(env, thiz, n_u.lat_e7, n_u.lon_e7, false);- uint64_t s = n_u.edge_ptr;- uint64_t e_ptr = g_nodes[u + 1].edge_ptr; // sentinel guarantees valid-- for (uint64_t i = s; i < e_ptr; ++i) {- Edge& edge = g_edges[i];- if (!is_mode_allowed(edge.type, mode)) continue;-- uint32_t travel_time;- int v_state = (mode == PUBLIC_TRANSIT && (edge.type & TRANSIT_FLAG)) ? 1 : 0;- if (v_state == 1) {- bool is_boarding = !(entry_u.last_type & TRANSIT_FLAG);- bool is_transfer = !is_boarding && (edge.name_offset != entry_u.last_name_off);-- TransitAttribute ta_u = get_node_transit_attr(u);- // FIX: Only allow boarding or transfers at recognized transit stops- if ((is_boarding || is_transfer) && ta_u.stop_code_off == 0xFFFFFFFF) continue;-- uint32_t wait, transit_move;- travel_time = get_transit_edge_time_10ms(edge, u_actual_time, ctx.startTime, ta_u.feed_name_off, is_boarding || is_transfer, wait, transit_move);- if (travel_time == 0xFFFFFFFF) continue;- } else {- // FIX: Only allow alighting from transit at recognized transit stops- if (mode == PUBLIC_TRANSIT && (entry_u.last_type & TRANSIT_FLAG)) {- TransitAttribute ta_u = get_node_transit_attr(u);- if (ta_u.stop_code_off == 0xFFFFFFFF) continue;- }- travel_time = get_edge_time_10ms(i, edge.dist_mm, edge.type, edge.speed_limit, mode);- }-- uint32_t v = edge.target;- uint32_t new_g = u_cost + travel_time;- auto& entry_v = g_scratchpad.get_entry(v, v_state);- if (new_g < entry_v.g_fwd) {- entry_v.g_fwd = new_g;- entry_v.g_bwd = new_g;- entry_v.p_fwd = u_idx;- entry_v.last_type = edge.type;- entry_v.last_name_off = edge.name_offset;- const auto& n_v = get_node(v);- uint32_t h = heuristic_time_10ms(n_v.lat_e7, n_v.lon_e7, ctx.end.proj_lat, ctx.end.proj_lon, mode);- g_heap.push(new_g + h, (v << 1) | v_state);- }- }- }-}--jobjectArray reconstruct_path(JNIEnv* env, int mode, const RoutingContext& ctx) {- LOGD("reconstruct_path: mode=%d, target_idx=%u", mode, ctx.target_node);- std::vector<uint32_t> path_indices;- uint32_t curr = ctx.target_node;- uint32_t safety = 0;- while (curr != 0xFFFFFFFF && safety < 1000000) {- path_indices.push_back(curr);- curr = g_scratchpad.get_entry(curr >> 1, curr & 1).p_fwd;- safety++;- }- std::reverse(path_indices.begin(), path_indices.end());- if (path_indices.empty()) return nullptr;-- std::vector<uint32_t> path_nodes;- for (uint32_t idx : path_indices) path_nodes.push_back(idx >> 1);-- struct StepData {- uint32_t name_off; uint64_t dist_mm = 0; uint64_t time_10ms = 0;- std::vector<double> coords; int maneuver = 0;- double speed_ratio = 1.0;- bool is_transit = false;- uint32_t feed_off = 0xFFFFFFFF;- uint32_t code_off = 0xFFFFFFFF;- uint32_t end_code_off = 0xFFFFFFFF;- int stop_count = 0;- };- std::vector<StepData> steps; double last_bearing = 0;- uint32_t current_elapsed_10ms = 0;- bool last_was_transit = false;-- auto add_segment = [&](double lat1, double lon1, double lat2, double lon2, uint32_t name_off, uint8_t type, uint8_t limit, uint32_t dist_mm, uint64_t edge_idx, uint32_t feed_off, uint32_t code_off, uint32_t target_code_off) {- double ratio = 1.0;- uint8_t traffic_speed = 0;- if (edge_idx != INVALID_EDGE) {- traffic_speed = g_traffic.get_speed(edge_idx);- if (traffic_speed > 0 && limit > 0) ratio = (double)traffic_speed / limit;- }-- uint32_t time_10ms;- bool is_transit = false;- if (mode == PUBLIC_TRANSIT && (type & TRANSIT_FLAG)) {- is_transit = true;- if (edge_idx != INVALID_EDGE) {- bool is_boarding = !last_was_transit;- bool is_transfer = last_was_transit && (name_off != steps.back().name_off);- uint32_t wait, transit_move;- time_10ms = get_transit_edge_time_10ms(g_edges[edge_idx], current_elapsed_10ms, ctx.startTime, feed_off, is_boarding || is_transfer, wait, transit_move);- if (time_10ms == 0xFFFFFFFF) { time_10ms = 0; wait = 0; transit_move = 0; }-- if ((is_boarding || is_transfer)) {- uint32_t penalty = 6000;- steps.push_back({name_off, 0, wait + penalty, {lon1, lat1}, 21, 1.0, true, feed_off, code_off});- current_elapsed_10ms += (wait + penalty);- time_10ms = transit_move;- } else {- time_10ms = transit_move;- }- } else {- time_10ms = 0;- }- } else {- time_10ms = get_edge_time_10ms(edge_idx, dist_mm, type, limit, mode);- }- current_elapsed_10ms += time_10ms;- last_was_transit = (type & TRANSIT_FLAG);- double bearing = get_bearing((int32_t)(lat1 * 1e7), (int32_t)(lon1 * 1e7), (int32_t)(lat2 * 1e7), (int32_t)(lon2 * 1e7));-- auto get_ratio_cat = [](double r) {- if (r < 0.5) return 0;- if (r < 0.9) return 1;- return 2;- };-- int maneuver = steps.empty() ? 0 : get_maneuver(last_bearing, bearing);- if (is_transit && !steps.empty() && steps.back().maneuver != 21) {- maneuver = 23; // RIDE- }-- if (steps.empty() || name_off != steps.back().name_off || get_ratio_cat(ratio) != get_ratio_cat(steps.back().speed_ratio) || is_transit != steps.back().is_transit || (maneuver != 9 && maneuver != 0 && maneuver != 23) || steps.back().maneuver == 21) {- steps.push_back({name_off, 0, 0, {lon1, lat1}, maneuver, ratio, is_transit, feed_off, code_off, 0xFFFFFFFF, 0});- }- steps.back().dist_mm += dist_mm;- steps.back().time_10ms += time_10ms;- steps.back().coords.push_back(lon2);- steps.back().coords.push_back(lat2);- if (is_transit && steps.back().maneuver != 21) {- steps.back().end_code_off = target_code_off;- steps.back().stop_count++;- }- last_bearing = bearing;- };-- // 1. Start stub: proj_s -> path_nodes[0]- {- uint32_t n0 = path_nodes[0];- const auto& node0 = get_node(n0);- uint64_t j = ctx.start.edge_idx;- - EdgeCoords ec = get_edge_coordinates(j);- if (j != INVALID_EDGE && ec.coords != nullptr && ec.count >= 2) {- uint32_t num_pts = ec.count;- uint32_t seg_idx = ctx.start.segment_idx;- - if (n0 == ctx.start.nodeA) {- // Snapped point to P_seg_idx- const auto p_next = get_pt_at(ec, seg_idx);- uint32_t d1 = fast_dist_mm(ctx.start.proj_lat, ctx.start.proj_lon, p_next.lat_e7, p_next.lon_e7);- add_segment(ctx.start.proj_lat * 1e-7, ctx.start.proj_lon * 1e-7, p_next.lat_e7 * 1e-7, p_next.lon_e7 * 1e-7,- ctx.start.name_offset, ctx.start.type, ctx.start.speed_limit, d1, j, get_node_feed_name_off(n0), get_node_stop_code_off(n0), get_node_stop_code_off(n0));- - // Then trace backwards: P_p -> P_{p-1}- for (int p = (int)seg_idx; p >= 1; --p) {- const auto p_from = get_pt_at(ec, p);- const auto p_to = get_pt_at(ec, p - 1);- uint32_t d_seg = fast_dist_mm(p_from.lat_e7, p_from.lon_e7, p_to.lat_e7, p_to.lon_e7);- add_segment(p_from.lat_e7 * 1e-7, p_from.lon_e7 * 1e-7, p_to.lat_e7 * 1e-7, p_to.lon_e7 * 1e-7,- ctx.start.name_offset, ctx.start.type, ctx.start.speed_limit, d_seg, j, get_node_feed_name_off(n0), get_node_stop_code_off(n0), get_node_stop_code_off(n0));- }- } else {- // Snapped point to P_{seg_idx + 1}- const auto p_next = get_pt_at(ec, seg_idx + 1);- uint32_t d1 = fast_dist_mm(ctx.start.proj_lat, ctx.start.proj_lon, p_next.lat_e7, p_next.lon_e7);- add_segment(ctx.start.proj_lat * 1e-7, ctx.start.proj_lon * 1e-7, p_next.lat_e7 * 1e-7, p_next.lon_e7 * 1e-7,- ctx.start.name_offset, ctx.start.type, ctx.start.speed_limit, d1, j, get_node_feed_name_off(n0), get_node_stop_code_off(n0), get_node_stop_code_off(n0));- - // Then trace forwards: P_p -> P_{p+1}- for (uint32_t p = seg_idx + 1; p < num_pts - 1; ++p) {- const auto p_from = get_pt_at(ec, p);- const auto p_to = get_pt_at(ec, p + 1);- uint32_t d_seg = fast_dist_mm(p_from.lat_e7, p_from.lon_e7, p_to.lat_e7, p_to.lon_e7);- add_segment(p_from.lat_e7 * 1e-7, p_from.lon_e7 * 1e-7, p_to.lat_e7 * 1e-7, p_to.lon_e7 * 1e-7,- ctx.start.name_offset, ctx.start.type, ctx.start.speed_limit, d_seg, j, get_node_feed_name_off(n0), get_node_stop_code_off(n0), get_node_stop_code_off(n0));- }- }- } else {- uint32_t dist = (n0 == ctx.start.nodeA) ? ctx.start.distA_mm : ctx.start.distB_mm;- add_segment(ctx.start.proj_lat * 1e-7, ctx.start.proj_lon * 1e-7, node0.lat_e7 * 1e-7, node0.lon_e7 * 1e-7,- ctx.start.name_offset, ctx.start.type, ctx.start.speed_limit, dist, INVALID_EDGE, get_node_feed_name_off(n0), get_node_stop_code_off(n0), get_node_stop_code_off(n0));- }- }-- // 2. Main path segments- for (size_t i = 0; i < path_nodes.size() - 1; ++i) {- uint32_t u = path_nodes[i], v = path_nodes[i+1];- if (!g_nodes || u >= g_node_count) continue;- const auto& node_u = g_nodes[u];- const auto& node_v = get_node(v);-- uint64_t s = node_u.edge_ptr;- uint64_t e_ptr = g_nodes[u + 1].edge_ptr; // sentinel guarantees valid-- uint64_t best_e_idx = INVALID_EDGE;- for (uint64_t k = s; k < e_ptr; ++k) {- if (g_edges[k].target == v) {- best_e_idx = k; break;- }- }- if (best_e_idx == INVALID_EDGE) continue;-- const Edge& e = g_edges[best_e_idx];- uint32_t d = e.dist_mm;- if (d == 0 || (e.type & TRANSIT_FLAG)) {- d = accurate_dist_mm(node_u.lat_e7, node_u.lon_e7, node_v.lat_e7, node_v.lon_e7);- }-- EdgeCoords ec = get_edge_coordinates(best_e_idx);- if (ec.coords != nullptr && ec.count >= 2) {- uint32_t num_pts = ec.count;- for (uint32_t p = 0; p < num_pts - 1; ++p) {- const auto p1 = get_pt_at(ec, p);- const auto p2 = get_pt_at(ec, p + 1);- uint32_t seg_dist = fast_dist_mm(p1.lat_e7, p1.lon_e7, p2.lat_e7, p2.lon_e7);- add_segment(p1.lat_e7 * 1e-7, p1.lon_e7 * 1e-7, p2.lat_e7 * 1e-7, p2.lon_e7 * 1e-7,- e.name_offset, e.type, e.speed_limit, seg_dist, best_e_idx, get_node_feed_name_off(u), get_node_stop_code_off(u), get_node_stop_code_off(v));- }- } else {- add_segment(node_u.lat_e7 * 1e-7, node_u.lon_e7 * 1e-7, node_v.lat_e7 * 1e-7, node_v.lon_e7 * 1e-7,- e.name_offset, e.type, e.speed_limit, d, best_e_idx, get_node_feed_name_off(u), get_node_stop_code_off(u), get_node_stop_code_off(v));- }- }-- // 3. End stub: path_nodes.back() -> proj_e- {- uint32_t nk = path_nodes.back();- const auto& nodek = get_node(nk);- uint64_t j = ctx.end.edge_idx;- - EdgeCoords ec = get_edge_coordinates(j);- if (j != INVALID_EDGE && ec.coords != nullptr && ec.count >= 2) {- uint32_t num_pts = ec.count;- uint32_t seg_idx = ctx.end.segment_idx;- - if (nk == ctx.end.nodeA) {- // Trace forwards: P_p -> P_{p+1} up to seg_idx- for (uint32_t p = 0; p < seg_idx; ++p) {- const auto p_from = get_pt_at(ec, p);- const auto p_to = get_pt_at(ec, p + 1);- uint32_t d_seg = fast_dist_mm(p_from.lat_e7, p_from.lon_e7, p_to.lat_e7, p_to.lon_e7);- add_segment(p_from.lat_e7 * 1e-7, p_from.lon_e7 * 1e-7, p_to.lat_e7 * 1e-7, p_to.lon_e7 * 1e-7,- ctx.end.name_offset, ctx.end.type, ctx.end.speed_limit, d_seg, j, get_node_feed_name_off(nk), get_node_stop_code_off(nk), 0xFFFFFFFF);- }- - // Then final segment: P_seg_idx -> Proj- const auto p_last = get_pt_at(ec, seg_idx);- uint32_t d2 = fast_dist_mm(p_last.lat_e7, p_last.lon_e7, ctx.end.proj_lat, ctx.end.proj_lon);- add_segment(p_last.lat_e7 * 1e-7, p_last.lon_e7 * 1e-7, ctx.end.proj_lat * 1e-7, ctx.end.proj_lon * 1e-7,- ctx.end.name_offset, ctx.end.type, ctx.end.speed_limit, d2, j, get_node_feed_name_off(nk), get_node_stop_code_off(nk), 0xFFFFFFFF);- } else {- // Trace backwards: P_p -> P_{p-1} down to seg_idx + 1- for (int p = (int)num_pts - 1; p > (int)seg_idx + 1; --p) {- const auto p_from = get_pt_at(ec, p);- const auto p_to = get_pt_at(ec, p - 1);- uint32_t d_seg = fast_dist_mm(p_from.lat_e7, p_from.lon_e7, p_to.lat_e7, p_to.lon_e7);- add_segment(p_from.lat_e7 * 1e-7, p_from.lon_e7 * 1e-7, p_to.lat_e7 * 1e-7, p_to.lon_e7 * 1e-7,- ctx.end.name_offset, ctx.end.type, ctx.end.speed_limit, d_seg, j, get_node_feed_name_off(nk), get_node_stop_code_off(nk), 0xFFFFFFFF);- }- - // Then final segment: P_{seg_idx + 1} -> Proj- const auto p_last = get_pt_at(ec, seg_idx + 1);- uint32_t d2 = fast_dist_mm(p_last.lat_e7, p_last.lon_e7, ctx.end.proj_lat, ctx.end.proj_lon);- add_segment(p_last.lat_e7 * 1e-7, p_last.lon_e7 * 1e-7, ctx.end.proj_lat * 1e-7, ctx.end.proj_lon * 1e-7,- ctx.end.name_offset, ctx.end.type, ctx.end.speed_limit, d2, j, get_node_feed_name_off(nk), get_node_stop_code_off(nk), 0xFFFFFFFF);- }- } else {- uint32_t dist = (nk == ctx.end.nodeA) ? ctx.end.distA_mm : ctx.end.distB_mm;- add_segment(nodek.lat_e7 * 1e-7, nodek.lon_e7 * 1e-7, ctx.end.proj_lat * 1e-7, ctx.end.proj_lon * 1e-7,- ctx.end.name_offset, ctx.end.type, ctx.end.speed_limit, dist, INVALID_EDGE, get_node_feed_name_off(nk), get_node_stop_code_off(nk), 0xFFFFFFFF);- }- }-- jclass stepClass = env->FindClass("com/vayunmathur/maps/util/OfflineRouter$RawStep");- if (!stepClass) {- LOGE("reconstruct_path: could not find RawStep class");- return nullptr;- }- jmethodID stepCtor = env->GetMethodID(stepClass, "<init>", "(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V");- if (!stepCtor) {- LOGE("reconstruct_path: could not find RawStep constructor");- return nullptr;- }- LOGD("reconstruct_path: creating array of size %zu", steps.size());- jobjectArray res = env->NewObjectArray(steps.size(), stepClass, nullptr);- for (size_t i = 0; i < steps.size(); ++i) {- const char* name_ptr = (steps[i].name_off < g_road_names_size) ? (g_road_names + steps[i].name_off) : "Unknown Road";- jstring jName = env->NewStringUTF(name_ptr); jdoubleArray jGeom = env->NewDoubleArray(steps[i].coords.size());- env->SetDoubleArrayRegion(jGeom, 0, steps[i].coords.size(), steps[i].coords.data());-- jstring jFeed = nullptr;- if (steps[i].feed_off != 0xFFFFFFFF && steps[i].feed_off < g_road_names_size) {- jFeed = env->NewStringUTF(g_road_names + steps[i].feed_off);- }- jstring jCode = nullptr;- if (steps[i].code_off != 0xFFFFFFFF && steps[i].code_off < g_road_names_size) {- jCode = env->NewStringUTF(g_road_names + steps[i].code_off);- }- jstring jEndCode = nullptr;- if (steps[i].end_code_off != 0xFFFFFFFF && steps[i].end_code_off < g_road_names_size) {- jEndCode = env->NewStringUTF(g_road_names + steps[i].end_code_off);- }-- jobject stepObj = env->NewObject(stepClass, stepCtor, (jint)steps[i].maneuver, jName, (jlong)steps[i].dist_mm, (jlong)steps[i].time_10ms, jGeom, (jdouble)steps[i].speed_ratio, (jboolean)steps[i].is_transit, jFeed, jCode, jEndCode, (jint)steps[i].stop_count);- env->SetObjectArrayElement(res, i, stepObj);- env->DeleteLocalRef(jName); env->DeleteLocalRef(jGeom); env->DeleteLocalRef(stepObj);- if (jFeed) env->DeleteLocalRef(jFeed);- if (jCode) env->DeleteLocalRef(jCode);- if (jEndCode) env->DeleteLocalRef(jEndCode);- }- return res;-}--// --- JNI INTERFACE -----extern "C" JNIEXPORT jboolean JNICALL-Java_com_vayunmathur_maps_util_OfflineRouter_init(JNIEnv* env, jobject thiz, jstring base_path, jobjectArray present_feeds) {- const char* path_raw = env->GetStringUTFChars(base_path, nullptr); std::string base(path_raw);- LOGD("Native init started with path: %s", path_raw);- if (!base.empty() && base.back() != '/') base += "/";- g_base_path = base;-- g_present_feeds.clear();- if (present_feeds) {- int len = env->GetArrayLength(present_feeds);- for (int i = 0; i < len; ++i) {- jstring s = (jstring)env->GetObjectArrayElement(present_feeds, i);- const char* raw = env->GetStringUTFChars(s, nullptr);- g_present_feeds.insert(raw);- env->ReleaseStringUTFChars(s, raw);- env->DeleteLocalRef(s);- }- }-- auto m_file = [&](const std::string& p, size_t& s) -> void* {- s = 0; int fd = open(p.c_str(), O_RDONLY); if (fd < 0) return nullptr;- off_t end = lseek(fd, 0, SEEK_END);- if (end <= 0) { close(fd); return nullptr; } // empty / unreadable file- s = (size_t)end;- void* a = mmap(nullptr, s, PROT_READ, MAP_SHARED, fd, 0); close(fd);- return (a == MAP_FAILED) ? nullptr : a;- };- // metadata.bin is now a single u64 node_count.- size_t s_meta; uint64_t* meta = (uint64_t*)m_file(base + "metadata.bin", s_meta);- if (!meta || s_meta < sizeof(uint64_t)) {- if (meta) munmap(meta, s_meta);- env->ReleaseStringUTFChars(base_path, path_raw);- return false;- }- g_node_count = (uint32_t)meta[0];- munmap(meta, s_meta);-- size_t s_n, s_e, s_t, s_ta;- g_nodes = (NodeMaster*)m_file(base + "nodes.bin", s_n);- g_edges = (Edge*)m_file(base + "edges.bin", s_e);- g_edge_count = s_e / sizeof(Edge);- g_transit_voyages = (TransitVoyageCompact*)m_file(base + "transit_voyages.bin", s_t);- g_transit_voyage_count = s_t / sizeof(TransitVoyageCompact);- g_transit_attributes = (TransitAttribute*)m_file(base + "transit_attributes.bin", s_ta);- if (!g_nodes || !g_edges) {- env->ReleaseStringUTFChars(base_path, path_raw);- return false;- }-- // intermediate.bin: [ u64 edge_offsets[g_edge_count + 1] ][ coord blob ].- g_intermediate_mmap_ptr = m_file(base + "intermediate.bin", g_intermediate_mmap_size);- if (g_intermediate_mmap_ptr) {- g_intermediate_edge_offsets = (uint64_t*)g_intermediate_mmap_ptr;- g_intermediate_data = (uint8_t*)((char*)g_intermediate_mmap_ptr + (g_edge_count + 1) * sizeof(uint64_t));- }-- size_t s_r; g_road_names = (char*)m_file(base + "road_names.bin", s_r); g_road_names_size = s_r;- for (int i = 0; i < 4096; ++i) {- double lat_deg = ((double)((int64_t)(i - 2048) << 19)) / 1e7;- g_lon_to_mm_scale[i] = (uint32_t)((111139000.0 / 1e7) * cos(lat_deg * DEG_TO_RAD) * 1024.0);- }- auto calc_scale = [](double speed_m_s) { return (uint64_t)((100.0 / (speed_m_s * 1000.0)) * 4294967296.0); };-- // HEURISTIC SCALES FIX: We increase transit speed bounds (using a highly optimistic 80 km/h)- // to ensure the heuristic remains optimistic/admissible, keeping search components directed- // without over-penalizing transit extensions and yielding flat routes instead of jagged ones.- g_time_scale_fixed[WALK] = calc_scale(WALK_SPEED_M_S);- g_time_scale_fixed[BICYCLE] = calc_scale(BICYCLE_SPEED_M_S);- g_time_scale_fixed[DRIVING] = calc_scale(105.0 / 3.6);- g_time_scale_fixed[PUBLIC_TRANSIT] = calc_scale(80.0 / 3.6); // Optimistic 80 km/h transit velocity-- for (int m = 0; m < 4; ++m) {- for (int r = 0; r < 16; ++r) {- double speed_m_s = 1.0;- if (m == DRIVING) {- switch(r) {- case MOTORWAY: speed_m_s = 105.0/3.6; break; case TRUNK: speed_m_s = 85.0/3.6; break;- case PRIMARY: speed_m_s = 65.0/3.6; break; case SECONDARY: speed_m_s = 55.0/3.6; break;- case TERTIARY: speed_m_s = 45.0/3.6; break; default: speed_m_s = 30.0/3.6;- }- } else { speed_m_s = (m == BICYCLE) ? BICYCLE_SPEED_M_S : WALK_SPEED_M_S; }- g_edge_time_multipliers[m][r] = (uint64_t)((100.0 / (speed_m_s * 1000.0)) * 4294967296.0);- }- }- // sqlite3.c removed (9MB) – maps now memory-only, no traffic_cache.mbtiles- // Android SQLite remains via Room for amenities.db (androidx.sqlite)- env->ReleaseStringUTFChars(base_path, path_raw); return true;-}--extern "C" JNIEXPORT jobjectArray JNICALL-Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNative(JNIEnv* env, jobject thiz, jdouble sLat, jdouble sLon, jdouble eLat, jdouble eLon, jint mode, jlong startTime) {- LOGD("findRouteNative: sLat=%f, sLon=%f, eLat=%f, eLon=%f, mode=%d", sLat, sLon, eLat, eLon, mode);- RoutingContext ctx; if (!prepare_routing(env, thiz, sLat, sLon, eLat, eLon, mode, (uint32_t)startTime, ctx)) return nullptr;- perform_search_loop(env, thiz, mode, ctx);- if (ctx.target_node == 0xFFFFFFFF) {- LOGE("findRouteNative: no path found after %d iterations", ctx.iterations);- return nullptr;- }- LOGD("findRouteNative: path found, reconstructing...");- return reconstruct_path(env, mode, ctx);-}--extern "C" JNIEXPORT void JNICALL-Java_com_vayunmathur_maps_util_OfflineRouter_updateTrafficNative(JNIEnv* env, jobject thiz, jlongArray edge_ids, jbyteArray speeds, jint packed_square) {- jsize len = env->GetArrayLength(edge_ids); jlong* ids_ptr = env->GetLongArrayElements(edge_ids, nullptr);- jbyte* speeds_ptr = env->GetByteArrayElements(speeds, nullptr);- std::lock_guard<std::mutex> lock(g_traffic_mutex);-auto& segments = g_traffic_by_square[packed_square];- segments.clear();- for (jsize i = 0; i < len; i++) {- uint64_t edge_id = (uint64_t)ids_ptr[i]; uint8_t speed = (uint8_t)speeds_ptr[i];- if (g_edges && edge_id < g_edge_count) {- const Edge& edge = g_edges[edge_id];- if (speed < 255) {- g_traffic.set_speed(edge_id, speed);- const NodeMaster& node_u = g_nodes[find_node_idx_for_edge(edge_id)];- if (edge.target < g_node_count) {- const NodeMaster& node_v = g_nodes[edge.target];- double ratio = (edge.speed_limit > 0) ? (double)speed / edge.speed_limit : 1.0;- segments.push_back(node_u.lat_e7 * 1e-7); segments.push_back(node_u.lon_e7 * 1e-7);- segments.push_back(node_v.lat_e7 * 1e-7); segments.push_back(node_v.lon_e7 * 1e-7);- segments.push_back(ratio);- }- }- }- }- env->ReleaseLongArrayElements(edge_ids, ids_ptr, JNI_ABORT); env->ReleaseByteArrayElements(speeds, speeds_ptr, JNI_ABORT);-}--extern "C" JNIEXPORT void JNICALL-Java_com_vayunmathur_maps_util_OfflineRouter_notifyTrafficFetchFinishedNative(JNIEnv* env, jobject thiz, jint packed_square) {- LOGD("notifyTrafficFetchFinishedNative: packed %u", (uint32_t)packed_square);-}--extern "C" JNIEXPORT jdoubleArray JNICALL-Java_com_vayunmathur_maps_util_OfflineRouter_getTrafficSegmentsNative(JNIEnv* env, jobject thiz) {- std::lock_guard<std::mutex> lock(g_traffic_mutex);- std::vector<double> flattened;- for (auto const& [square, segments] : g_traffic_by_square) {- flattened.insert(flattened.end(), segments.begin(), segments.end());- if (flattened.size() > 50000) break;- }- size_t count = flattened.size();- if (count > 50000) count = 50000;- jdoubleArray jRes = env->NewDoubleArray(count);- if (count > 0) env->SetDoubleArrayRegion(jRes, 0, count, flattened.data());- return jRes;-}--extern "C" JNIEXPORT jbyteArray JNICALL-Java_com_vayunmathur_maps_util_OfflineRouter_getTrafficTileNative(JNIEnv* env, jobject thiz, jint z, jint x, jint y) {- std::lock_guard<std::mutex> lock(g_traffic_mutex);- int tms_y = (1 << z) - 1 - y;- (void)tms_y; // previously used for MBTiles row flip, now tiles generated on-the-fly-- double n = std::pow(2.0, z);- double lon_min = (double)x / n * 360.0 - 180.0;- double lon_max = (double)(x + 1) / n * 360.0 - 180.0;- double lat_max = std::atan(std::sinh(M_PI * (1 - 2 * (double)y / n))) * 180.0 / M_PI;- double lat_min = std::atan(std::sinh(M_PI * (1 - 2 * (double)(y + 1) / n))) * 180.0 / M_PI;-- TileProj proj{n, x, y};- std::vector<uint8_t> layer_buf;- write_string(layer_buf, 1, "traffic");- write_tag(layer_buf, 15, 0); write_varint(layer_buf, 2);- write_tag(layer_buf, 5, 0); write_varint(layer_buf, 4096);-- int min_lat_idx = (int)std::floor(lat_min); int max_lat_idx = (int)std::floor(lat_max);- int min_lon_idx = (int)std::floor(lon_min); int max_lon_idx = (int)std::floor(lon_max);-- std::vector<std::string> keys = {"color"};- std::vector<std::string> values;- std::map<std::string, uint32_t> val_map;- auto get_val_idx = [&](const std::string& v) {- if (val_map.find(v) == val_map.end()) { val_map[v] = values.size(); values.push_back(v); }- return val_map[v];- };-- for (int lat_i = min_lat_idx; lat_i <= max_lat_idx; ++lat_i) {- for (int lon_i = min_lon_idx; lon_i <= max_lon_idx; ++lon_i) {- uint32_t square_id = ((uint32_t)(lat_i + 360) << 16) | (uint32_t)(lon_i + 720);- if (g_traffic_by_square.find(square_id) == g_traffic_by_square.end()) load_traffic_from_db(square_id);- auto it = g_traffic_by_square.find(square_id);- if (it == g_traffic_by_square.end()) continue;-- const auto& data = it->second;- for (size_t i = 0; i + 4 < data.size(); i += 5) {- double lat1 = data[i], lon1 = data[i+1], lat2 = data[i+2], lon2 = data[i+3], speed_ratio = data[i+4];- if (speed_ratio <= 0.0) continue;- int32_t px1, py1, px2, py2;- proj.wgs84_to_tile_px(lat1, lon1, px1, py1); proj.wgs84_to_tile_px(lat2, lon2, px2, py2);- if (std::max(px1, px2) < -512 || std::min(px1, px2) > 4608 || std::max(py1, py2) < -512 || std::min(py1, py2) > 4608) continue;-- std::vector<uint8_t> feat_buf;- write_varint(feat_buf, (3 << 3) | 0); write_varint(feat_buf, 2);- std::vector<uint8_t> geom_buf;- write_varint(geom_buf, mvt_command(1, 1)); write_varint(geom_buf, zigzag(px1)); write_varint(geom_buf, zigzag(py1));- write_varint(geom_buf, mvt_command(2, 1)); write_varint(geom_buf, zigzag(px2 - px1)); write_varint(geom_buf, zigzag(py2 - py1));- write_tag(feat_buf, 4, 2); write_varint(feat_buf, geom_buf.size());- feat_buf.insert(feat_buf.end(), geom_buf.begin(), geom_buf.end());-- std::string color = "#1B5E20";- if (speed_ratio < 0.5) color = "#B71C1C"; else if (speed_ratio < 0.9) color = "#E65100";- write_tag(feat_buf, 2, 2); std::vector<uint8_t> tag_buf;- write_varint(tag_buf, 0); write_varint(tag_buf, get_val_idx(color));- write_varint(feat_buf, tag_buf.size()); feat_buf.insert(feat_buf.end(), tag_buf.begin(), tag_buf.end());- write_tag(layer_buf, 2, 2); write_varint(layer_buf, feat_buf.size());- layer_buf.insert(layer_buf.end(), feat_buf.begin(), feat_buf.end());- }- }- }- for (const auto& k : keys) write_string(layer_buf, 3, k);- for (const auto& v : values) {- write_tag(layer_buf, 4, 2); std::vector<uint8_t> v_buf; write_string(v_buf, 1, v);- write_varint(layer_buf, v_buf.size()); layer_buf.insert(layer_buf.end(), v_buf.begin(), v_buf.end());- }- std::vector<uint8_t> tile_buf;- write_tag(tile_buf, 3, 2); write_varint(tile_buf, layer_buf.size());- tile_buf.insert(tile_buf.end(), layer_buf.begin(), layer_buf.end());- std::vector<uint8_t> compressed = compress_gzip(tile_buf);-- // If gzip somehow failed, we MUST NOT return the raw tile because the- // HTTP wrapper in Kotlin unconditionally tags the body- // `Content-Encoding: gzip`. MapLibre would then try to gunzip plain- // protobuf and fail to render. Returning null here makes the server- // respond with 204 (no tile) and MapLibre falls back to no traffic- // overlay for that cell instead of breaking the render.- if (compressed.empty()) {- return nullptr;- }- jbyteArray res = env->NewByteArray(compressed.size());- env->SetByteArrayRegion(res, 0, compressed.size(), (jbyte*)compressed.data());- return res;-}--extern "C" JNIEXPORT void JNICALL-Java_com_vayunmathur_maps_util_OfflineRouter_ensureTrafficLoadedNative(JNIEnv* env, jobject thiz, jdouble lat, jdouble lon, jboolean force_async) {- ensure_traffic_loaded(env, thiz, (int32_t)(lat * 1e7), (int32_t)(lon * 1e7), force_async);-}
maps/src/main/cpp/radix_heap.h
diff --git a/maps/src/main/cpp/radix_heap.h b/maps/src/main/cpp/radix_heap.hdeleted file mode 100644index 8b7c03954d..0000000000--- a/maps/src/main/cpp/radix_heap.h+++ /dev/null@@ -1,88 +0,0 @@-#ifndef RADIX_HEAP_H-#define RADIX_HEAP_H--#include <cstdint>-#include <algorithm>-#include <cstdlib>--struct HeapNode {- uint32_t score;- uint32_t id;-};--/**- * @brief Ultra-fast Radix Heap using static 2D arrays.- * Removed all heap allocations and vector overhead from the search loop.- */-class RadixHeap {-private:- static constexpr uint32_t BUCKET_CAPACITY = 256 * 1024;-- uint64_t m_bucket_mask;- uint32_t m_last_pop_value;- uint32_t m_count;-- uint32_t m_sizes[33];- HeapNode m_buckets[33][BUCKET_CAPACITY];-- inline uint32_t get_bucket_idx(uint32_t score) const {- uint32_t x = score ^ m_last_pop_value;- return x == 0 ? 0 : 32 - __builtin_clz(x);- }--public:- RadixHeap() : m_bucket_mask(0), m_last_pop_value(0), m_count(0) {- memset(m_sizes, 0, sizeof(m_sizes));- }-- inline void push(uint32_t score, uint32_t node_id) {- uint32_t i = get_bucket_idx(score);- uint32_t pos = m_sizes[i]++;- m_buckets[i][pos] = {score, node_id};- m_bucket_mask |= (1ULL << i);- m_count++;- }-- inline uint32_t pop() {- if (__builtin_expect(m_sizes[0] == 0, 0)) {- uint32_t i = __builtin_ctzll(m_bucket_mask & ~1ULL);- HeapNode* b = m_buckets[i];- uint32_t b_size = m_sizes[i];-- uint32_t min_score = b[0].score;- for (uint32_t j = 1; j < b_size; ++j) {- if (b[j].score < min_score) min_score = b[j].score;- }-- m_last_pop_value = min_score;-- for (uint32_t j = 0; j < b_size; ++j) {- const HeapNode& node = b[j];- uint32_t idx = get_bucket_idx(node.score);- m_buckets[idx][m_sizes[idx]++] = node;- m_bucket_mask |= (1ULL << idx);- }-- m_sizes[i] = 0;- m_bucket_mask &= ~(1ULL << i);- }-- uint32_t node_id = m_buckets[0][--m_sizes[0]].id;- if (m_sizes[0] == 0) m_bucket_mask &= ~1ULL;- m_count--;- return node_id;- }-- void clear() {- for (uint32_t i = 0; i < 33; ++i) m_sizes[i] = 0;- m_last_pop_value = 0;- m_count = 0;- m_bucket_mask = 0;- }-- inline bool empty() const { return m_count == 0; }- inline uint32_t size() const { return m_count; }- inline uint32_t top_key() const { return m_last_pop_value; }-};--#endif // RADIX_HEAP_H\ No newline at end of file
maps/src/main/cpp/scratchpad.h
diff --git a/maps/src/main/cpp/scratchpad.h b/maps/src/main/cpp/scratchpad.hdeleted file mode 100644index 77ca081d38..0000000000--- a/maps/src/main/cpp/scratchpad.h+++ /dev/null@@ -1,119 +0,0 @@-#ifndef SCRATCHPAD_H-#define SCRATCHPAD_H--#include <cstdint>-#include <vector>-#include <cstring>-#include <cstdlib>-#include <unordered_map>-#include <android/log.h>--#define LOG_TAG "OfflineRouterNative"-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)--/**- * @brief Two-Level Page Table Scratchpad.- */-class RoutingScratchpad {-public:- struct Entry {- uint32_t node_id;- uint32_t g_fwd;- uint32_t g_bwd;- uint32_t p_fwd;- uint32_t p_bwd;- uint32_t last_name_off;- uint8_t last_type;- };--private:- static constexpr uint32_t PAGE_BITS = 14;- static constexpr uint32_t ROUTING_PAGE_SIZE = (1 << PAGE_BITS);- static constexpr uint32_t ROUTING_PAGE_MASK = (ROUTING_PAGE_SIZE - 1);- static constexpr uint32_t DIR_SIZE = (1ULL << 32) >> PAGE_BITS;-- Entry** m_directory;- std::vector<uint32_t> m_active_pages;--public:- RoutingScratchpad() {- m_directory = (Entry**)calloc(DIR_SIZE, sizeof(Entry*));- m_active_pages.reserve(1024);- }-- ~RoutingScratchpad() {- cleanup_pages();- if (m_directory) free(m_directory);- }-- void cleanup_pages() {- for (uint32_t page_idx : m_active_pages) {- if (m_directory[page_idx]) {- free(m_directory[page_idx]);- m_directory[page_idx] = nullptr;- }- }- m_active_pages.clear();- }-- inline void reset() {- cleanup_pages();- }-- inline Entry& get_entry(uint32_t node_id, int state = 0) {- uint32_t index = (node_id << 1) | (state & 1);- uint32_t dir_idx = index >> PAGE_BITS;- uint32_t page_offset = index & ROUTING_PAGE_MASK;-- if (__builtin_expect(m_directory[dir_idx] == nullptr, 0)) {- Entry* new_page = (Entry*)malloc(ROUTING_PAGE_SIZE * sizeof(Entry));- memset(new_page, 0xFF, ROUTING_PAGE_SIZE * sizeof(Entry));- for (uint32_t i = 0; i < ROUTING_PAGE_SIZE; i++) {- new_page[i].last_type = 0;- new_page[i].last_name_off = 0xFFFFFFFF;- }- m_directory[dir_idx] = new_page;- m_active_pages.push_back(dir_idx);- }-- Entry& e = m_directory[dir_idx][page_offset];- if (__builtin_expect(e.node_id == 0xFFFFFFFF, 0)) {- e.node_id = node_id;- }- return e;- }-- inline Entry& operator[](uint32_t node_id) {- return get_entry(node_id);- }-};--/**- * @brief Sparse traffic-speed table keyed by 64-bit global edge ID.- *- * Edge indices are now global u64 and can exceed the 32-bit space, so the old- * flat 32-bit page directory can no longer address them. Traffic only covers a- * sparse subset of edges, so a hash map is both correct and memory-efficient.- */-class TrafficPageTable {-private:- std::unordered_map<uint64_t, uint8_t> m_speeds;--public:- TrafficPageTable() = default;-- inline void set_speed(uint64_t edge_id, uint8_t speed_kph) {- m_speeds[edge_id] = speed_kph;- }-- inline uint8_t get_speed(uint64_t edge_id) const {- auto it = m_speeds.find(edge_id);- return it == m_speeds.end() ? 0 : it->second;- }-- void clear() {- m_speeds.clear();- }-};--#endif
maps/src/main/rust/Cargo.toml
diff --git a/maps/src/main/rust/Cargo.toml b/maps/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..25a9bfe9a9--- /dev/null+++ b/maps/src/main/rust/Cargo.toml@@ -0,0 +1,29 @@+[package]+name = "offlinerouter"+version = "0.1.0"+edition = "2021"+description = "Offline routing engine + traffic MVT tile encoder for the Maps app, exposed to Kotlin via JNI"+license = "GPL-2.0-only"++[lib]+name = "offlinerouter"+crate-type = ["cdylib", "rlib"]++[dependencies]+# JNI surface (armv8-only, in-repo jni-android – see third_party/jni-android).+jni.workspace = true+# mmap of the whole-world graph (nodes/edges/intermediate/…), mirroring the old+# C++ router's mmap loader. Direct libc rather than memmap2 to keep the dep tree+# minimal (memmap2 was intentionally dropped from the workspace).+libc.workspace = true+# gzip for the traffic MVT tiles served to MapLibre (replaces the C++ zlib deflate).+flate2.workspace = true++# Patch inherited from workspace root Cargo.toml.++[profile.release]+opt-level = 3+lto = true+codegen-units = 1+panic = "abort"+strip = true
maps/src/main/rust/src/geometry.rs
diff --git a/maps/src/main/rust/src/geometry.rs b/maps/src/main/rust/src/geometry.rsnew file mode 100644index 0000000000..5636a6100f--- /dev/null+++ b/maps/src/main/rust/src/geometry.rs@@ -0,0 +1,272 @@+//! Distance/time/bearing math and road-permission rules.+//!+//! Direct port of the `--- GEOMETRY ---`, `--- ROAD PERMISSIONS ---` and the+//! transit-scheduling helpers from `native-lib.cpp`. Integer arithmetic and+//! casts are reproduced exactly to keep routing output bit-identical.++use std::collections::HashMap;++use crate::graph::{+ Edge, Graph, DEG_TO_RAD, DRIVING, INVALID_EDGE, LIVING_STREET, MOTORWAY, PUBLIC_TRANSIT, STEPS,+ TRANSIT_FLAG,+};++/// Live traffic snapshot: global edge id -> speed (km/h). 0 means "unknown".+pub type TrafficSpeeds = HashMap<u64, u8>;++#[inline]+pub fn is_mode_allowed(road_type: u8, mode: i32) -> bool {+ let ty = road_type & 0x7F;+ if mode == DRIVING {+ return ty >= MOTORWAY && ty <= LIVING_STREET;+ }+ if mode == PUBLIC_TRANSIT {+ return (road_type & TRANSIT_FLAG != 0) || (ty >= MOTORWAY && ty <= STEPS);+ }+ ty >= MOTORWAY && ty <= STEPS+}++/// Fast equirectangular distance in millimetres (octagonal `max/min` approx),+/// using the precomputed cos-scaled longitude table.+#[inline(always)]+pub fn fast_dist_mm(g: &Graph, lat1_e7: i32, lon1_e7: i32, lat2_e7: i32, lon2_e7: i32) -> u32 {+ let dlat = (lat1_e7 as i64 - lat2_e7 as i64).abs();+ let dlon = (lon1_e7 as i64 - lon2_e7 as i64).abs();++ // 1 unit (1e-7 deg) latitude is ~11.1139 mm.+ let dy_mm = (dlat * 111_139) / 10_000;++ let mid = (lat1_e7.wrapping_add(lat2_e7)) / 2;+ let scale_idx = ((mid >> 19) + 2048) as u32;+ let scale = g.lon_to_mm_scale[(scale_idx & 4095) as usize] as i64;+ let dx_mm = (dlon * scale) >> 10;++ let (max_v, min_v): (u64, u64) = if dx_mm > dy_mm {+ (dx_mm as u64, dy_mm as u64)+ } else {+ (dy_mm as u64, dx_mm as u64)+ };+ (max_v - (max_v >> 5) + (min_v >> 1) - (min_v >> 3)) as u32+}++/// Haversine distance in millimetres, saturating at u32::MAX.+#[inline]+pub fn accurate_dist_mm(lat1_e7: i32, lon1_e7: i32, lat2_e7: i32, lon2_e7: i32) -> u32 {+ const R: f64 = 6_371_000_800.0;+ let phi1 = (lat1_e7 as f64 * 1e-7) * DEG_TO_RAD;+ let phi2 = (lat2_e7 as f64 * 1e-7) * DEG_TO_RAD;+ let delta_phi = (lat2_e7 - lat1_e7) as f64 * 1e-7 * DEG_TO_RAD;+ let delta_lambda = (lon2_e7 - lon1_e7) as f64 * 1e-7 * DEG_TO_RAD;+ let s_dphi = (delta_phi / 2.0).sin();+ let s_dlamb = (delta_lambda / 2.0).sin();+ let a = s_dphi * s_dphi + phi1.cos() * phi2.cos() * s_dlamb * s_dlamb;+ let dist = R * 2.0 * a.sqrt().atan2((1.0 - a).sqrt());+ if dist >= u32::MAX as f64 {+ return u32::MAX;+ }+ if dist < 0.0 {+ return 0;+ }+ dist as u32+}++/// Time (10 ms units) to traverse a non-transit edge, applying live traffic for+/// driving.+#[inline]+pub fn get_edge_time_10ms(+ g: &Graph,+ traffic: &TrafficSpeeds,+ edge_id: u64,+ dist_mm: u32,+ type_: u8,+ limit: u8,+ mode: i32,+) -> u32 {+ if mode == DRIVING {+ let traffic_speed = if edge_id != INVALID_EDGE {+ *traffic.get(&edge_id).unwrap_or(&0)+ } else {+ 0+ };+ let effective_limit = if traffic_speed > 0 { traffic_speed } else { limit };+ if effective_limit > 0 {+ let speed_m_s = effective_limit as f64 / 3.6;+ return (dist_mm as f64 / (speed_m_s * 10.0)) as u32;+ }+ }+ let multiplier = g.edge_time_multipliers[(mode & 0x3) as usize][((type_ & 0x7F) & 0xF) as usize];+ ((dist_mm as u64 * multiplier) >> 32) as u32+}++/// Optimistic A* heuristic in 10 ms units.+#[inline]+pub fn heuristic_time_10ms(g: &Graph, lat1: i32, lon1: i32, lat2: i32, lon2: i32, mode: i32) -> u32 {+ let dist_mm = fast_dist_mm(g, lat1, lon1, lat2, lon2);+ let scaled_time = dist_mm as u64 * g.time_scale_fixed[(mode & 0x3) as usize];+ (scaled_time >> 32) as u32+}++/// GTFS transit edge cost with next-departure scheduling. Returns+/// `0xFFFFFFFF` when no voyage is usable. Mirrors `get_transit_edge_time_10ms`.+#[inline]+pub fn get_transit_edge_time_10ms(+ g: &Graph,+ edge: &Edge,+ current_time_from_start: u32,+ start_time_abs: u32,+ feed_off: u32,+ is_boarding_or_transfer: bool,+) -> (u32, u32, u32) {+ // Returns (total_time, wait_out, travel_out).+ if !g.has_transit_voyages() {+ return (0xFFFF_FFFF, 0, 0);+ }++ let voyage_offset = edge.dist_mm as u64;+ let voyage_count = edge.speed_limit as u32;+ if voyage_count == 0 {+ return (0xFFFF_FFFF, 0, 0);+ }++ // Feed not present offline: report just the (unscheduled) voyage-0 duration.+ if feed_off != 0xFFFF_FFFF && (feed_off as usize) < g.road_names_size {+ if let Some(feed_name) = g.road_name(feed_off) {+ if !g.present_feeds.contains(&feed_name) {+ let travel = g.transit_voyage_at(voyage_offset + 1).dep_delta as u32;+ return (travel, 0, travel);+ }+ }+ }++ const BOARDING_PENALTY: u32 = 6000; // 1 minute to platform+ const DAY_10MS: u32 = 24 * 3600 * 100;+ let abs_now = (start_time_abs + current_time_from_start) % DAY_10MS;+ let arrival_at_platform =+ (abs_now + if is_boarding_or_transfer { BOARDING_PENALTY } else { 0 }) % DAY_10MS;++ let mut best_wait: u32 = 0xFFFF_FFFF;+ let mut best_travel: u32 = 0;++ let wait_for = |dep: u32| -> u32 {+ let dep_mod = dep % DAY_10MS;+ if dep_mod >= arrival_at_platform {+ dep_mod - arrival_at_platform+ } else {+ (DAY_10MS - arrival_at_platform) + dep_mod+ }+ };++ // Voyage 0.+ let dep0 = g.transit_dep_u32(voyage_offset);+ let duration0 = g.transit_voyage_at(voyage_offset + 1).dep_delta as u32;+ {+ let wait = wait_for(dep0);+ if wait < best_wait {+ best_wait = wait;+ best_travel = duration0;+ }+ }++ // Voyages 1+.+ let mut dep_prev = dep0;+ for i in 1..voyage_count as u64 {+ let compact = g.transit_voyage_at(voyage_offset + 1 + i);+ let dep = dep_prev.wrapping_add(compact.dep_delta as u32 * 100);+ dep_prev = dep;+ let wait = wait_for(dep);+ if wait < best_wait {+ best_wait = wait;+ best_travel = compact.duration as u32;+ }+ }++ if best_wait == 0xFFFF_FFFF {+ return (0xFFFF_FFFF, 0, 0);+ }++ let total =+ (if is_boarding_or_transfer { BOARDING_PENALTY } else { 0 }) + best_wait + best_travel;+ (total, best_wait, best_travel)+}++pub fn get_bearing(lat1: i32, lon1: i32, lat2: i32, lon2: i32) -> f64 {+ let f1 = (lat1 as f64 / 1e7) * DEG_TO_RAD;+ let f2 = (lat2 as f64 / 1e7) * DEG_TO_RAD;+ let dl = ((lon2 - lon1) as f64 / 1e7) * DEG_TO_RAD;+ let y = dl.sin() * f2.cos();+ let x = f1.cos() * f2.sin() - f1.sin() * f2.cos() * dl.cos();+ y.atan2(x) * (180.0 / std::f64::consts::PI)+}++pub fn get_maneuver(prev_bearing: f64, next_bearing: f64) -> i32 {+ let mut angle_diff = next_bearing - prev_bearing;+ while angle_diff < -180.0 {+ angle_diff += 360.0;+ }+ while angle_diff > 180.0 {+ angle_diff -= 360.0;+ }+ if angle_diff > 155.0 || angle_diff < -155.0 {+ return 3;+ }+ if angle_diff < -100.0 {+ return 2;+ }+ if angle_diff < -45.0 {+ return 4;+ }+ if angle_diff < -10.0 {+ return 1;+ }+ if angle_diff < 10.0 {+ return 9;+ }+ if angle_diff < 45.0 {+ return 5;+ }+ if angle_diff < 100.0 {+ return 8;+ }+ 6+}++pub struct Projection {+ pub lat_e7: i32,+ pub lon_e7: i32,+ pub dist_mm: u32,+}++/// Project point (px,py) onto segment (x1,y1)-(x2,y2). All coords are e7.+pub fn get_projection(+ g: &Graph,+ px: i32,+ py: i32,+ x1: i32,+ y1: i32,+ x2: i32,+ y2: i32,+) -> Projection {+ let lat_avg = (x1 + x2) as f64 / 2.0 * 1e-7;+ let lon_scale = (lat_avg * DEG_TO_RAD).cos();++ let dx = x2 as f64 - x1 as f64;+ let dy = (y2 as f64 - y1 as f64) * lon_scale;+ let dpx = px as f64 - x1 as f64;+ let dpy = (py as f64 - y1 as f64) * lon_scale;++ let mag_sq = dx * dx + dy * dy;+ let mut t = if mag_sq == 0.0 {+ 0.0+ } else {+ (dpx * dx + dpy * dy) / mag_sq+ };+ t = t.clamp(0.0, 1.0);++ let proj_lat = (x1 as f64 + t * (x2 - x1) as f64) as i32;+ let proj_lon = (y1 as f64 + t * (y2 - y1) as f64) as i32;+ Projection {+ lat_e7: proj_lat,+ lon_e7: proj_lon,+ dist_mm: fast_dist_mm(g, px, py, proj_lat, proj_lon),+ }+}
maps/src/main/rust/src/graph.rs
diff --git a/maps/src/main/rust/src/graph.rs b/maps/src/main/rust/src/graph.rsnew file mode 100644index 0000000000..c2c6a1bb3c--- /dev/null+++ b/maps/src/main/rust/src/graph.rs@@ -0,0 +1,517 @@+//! Whole-world routing graph: mmap loader, on-disk packed structs, derived+//! cost tables, spatial (Morton) indexing and delta-decoded edge geometry.+//!+//! Faithful port of the data model in the old `native-lib.cpp` (`NodeMaster`,+//! `Edge`, `TransitVoyageCompact`, `TransitAttribute`, the `m_file` mmap loader+//! in `init`, and the geometry helpers around it). The graph is loaded once and+//! is read-only afterwards, so it is shared behind an `Arc` (see `lib.rs`).++use std::collections::HashSet;+use std::ffi::CString;+use std::ptr;++// --- Travel modes (must match Kotlin RouteService.TravelMode.ordinal) ---+pub const DRIVING: i32 = 0;+pub const PUBLIC_TRANSIT: i32 = 1;+pub const WALK: i32 = 2;+pub const BICYCLE: i32 = 3;++// --- OSM-derived road types ---+pub const MOTORWAY: u8 = 1;+pub const LIVING_STREET: u8 = 9;+pub const STEPS: u8 = 15;++pub const REVERSE_GEOMETRY_FLAG: u8 = 0x40;+pub const TRANSIT_FLAG: u8 = 0x80;++/// Sentinel for "no edge" where a u64 global edge index is expected.+pub const INVALID_EDGE: u64 = 0xFFFF_FFFF_FFFF_FFFF;++pub const WALK_SPEED_M_S: f64 = 4.5 / 3.6;+pub const BICYCLE_SPEED_M_S: f64 = 16.0 / 3.6;+pub const DEG_TO_RAD: f64 = std::f64::consts::PI / 180.0;++// --- On-disk packed structs ---+// `#[repr(C, packed)]` reproduces the exact byte strides the generator writes+// (notably `Edge` is 14 bytes, not the 16 a naturally-aligned layout would give).+// All reads go through `read_unaligned`, so element pointers need no alignment.++#[repr(C, packed)]+#[derive(Clone, Copy)]+pub struct NodeMaster {+ pub lat_e7: i32,+ pub lon_e7: i32,+ pub edge_ptr: u64,+}++#[repr(C, packed)]+#[derive(Clone, Copy)]+pub struct Edge {+ pub target: u32,+ pub dist_mm: u32,+ pub name_offset: u32,+ pub type_: u8,+ pub speed_limit: u8,+}++#[repr(C, packed)]+#[derive(Clone, Copy)]+pub struct TransitVoyageCompact {+ pub dep_delta: u16,+ pub duration: u16,+}++#[repr(C, packed)]+#[derive(Clone, Copy)]+pub struct TransitAttribute {+ pub stop_code_off: u32,+ pub feed_name_off: u32,+}++#[derive(Clone, Copy)]+pub struct LatLon {+ pub lat_e7: i32,+ pub lon_e7: i32,+}++/// Owns a read-only `mmap` region and unmaps it on drop.+struct MmapRegion {+ ptr: *mut libc::c_void,+ len: usize,+}++// The graph is only ever read after init, so sharing the raw pointer across+// threads is sound.+unsafe impl Send for MmapRegion {}+unsafe impl Sync for MmapRegion {}++impl MmapRegion {+ /// mmap `path` read-only. Returns `None` for missing/empty/unreadable files,+ /// mirroring the C++ `m_file` lambda.+ fn map(path: &str) -> Option<MmapRegion> {+ let c = CString::new(path).ok()?;+ unsafe {+ let fd = libc::open(c.as_ptr(), libc::O_RDONLY);+ if fd < 0 {+ return None;+ }+ let end = libc::lseek(fd, 0, libc::SEEK_END);+ if end <= 0 {+ libc::close(fd);+ return None;+ }+ let len = end as usize;+ let ptr = libc::mmap(+ ptr::null_mut(),+ len,+ libc::PROT_READ,+ libc::MAP_SHARED,+ fd,+ 0,+ );+ libc::close(fd);+ if ptr == libc::MAP_FAILED {+ return None;+ }+ Some(MmapRegion { ptr, len })+ }+ }++ #[inline]+ fn base(&self) -> *const u8 {+ self.ptr as *const u8+ }+}++impl Drop for MmapRegion {+ fn drop(&mut self) {+ unsafe {+ libc::munmap(self.ptr, self.len);+ }+ }+}++/// Read a `Copy` value of type `T` from `base` at element index `idx`+/// (byte offset `idx * size_of::<T>()`), tolerating any alignment.+#[inline(always)]+unsafe fn read_at<T: Copy>(base: *const u8, idx: usize) -> T {+ (base.add(idx * std::mem::size_of::<T>()) as *const T).read_unaligned()+}++/// The whole-world routing dataset. Immutable after construction.+pub struct Graph {+ // mmap regions kept alive for the lifetime of the graph.+ _nodes_region: MmapRegion,+ _edges_region: MmapRegion,+ _transit_voyages_region: Option<MmapRegion>,+ _transit_attributes_region: Option<MmapRegion>,+ _intermediate_region: Option<MmapRegion>,+ _road_names_region: Option<MmapRegion>,++ nodes: *const u8,+ pub node_count: u32, // real nodes; nodes.bin has node_count + 1 (sentinel)+ edges: *const u8,+ pub edge_count: u64,+ transit_voyages: *const u8,+ #[allow(dead_code)]+ transit_voyage_count: u64,+ transit_attributes: *const u8,++ intermediate_edge_offsets: *const u8, // u64[edge_count + 1] byte offsets+ intermediate_data: *const u8, // delta-encoded coordinate bytes+ has_intermediate: bool,++ road_names: *const u8,+ pub road_names_size: usize,++ pub present_feeds: HashSet<String>,++ // Derived cost tables (computed in `load`, matching the C++ `init`).+ pub lon_to_mm_scale: [u32; 4096],+ pub time_scale_fixed: [u64; 4],+ pub edge_time_multipliers: [[u64; 16]; 4],+}++unsafe impl Send for Graph {}+unsafe impl Sync for Graph {}++impl Graph {+ /// Load the graph from `base` (a directory path, trailing slash optional).+ /// Returns `None` if the mandatory nodes/edges/metadata files are absent,+ /// mirroring the failure cases of the C++ `init`.+ pub fn load(base: &str, present_feeds: HashSet<String>) -> Option<Graph> {+ let mut base = base.to_string();+ if !base.is_empty() && !base.ends_with('/') {+ base.push('/');+ }++ // metadata.bin is a single u64 node_count.+ let meta = MmapRegion::map(&format!("{base}metadata.bin"))?;+ if meta.len < std::mem::size_of::<u64>() {+ return None;+ }+ let node_count = unsafe { read_at::<u64>(meta.base(), 0) } as u32;+ drop(meta);++ let nodes_region = MmapRegion::map(&format!("{base}nodes.bin"))?;+ let edges_region = MmapRegion::map(&format!("{base}edges.bin"))?;+ let edge_count = (edges_region.len / std::mem::size_of::<Edge>()) as u64;++ let transit_voyages_region = MmapRegion::map(&format!("{base}transit_voyages.bin"));+ let transit_voyage_count = transit_voyages_region+ .as_ref()+ .map(|r| (r.len / std::mem::size_of::<TransitVoyageCompact>()) as u64)+ .unwrap_or(0);+ let transit_attributes_region = MmapRegion::map(&format!("{base}transit_attributes.bin"));++ // intermediate.bin: [ u64 edge_offsets[edge_count + 1] ][ coord blob ].+ let intermediate_region = MmapRegion::map(&format!("{base}intermediate.bin"));+ let (intermediate_edge_offsets, intermediate_data, has_intermediate) =+ match &intermediate_region {+ Some(r) => {+ let offsets = r.base();+ let data = unsafe {+ r.base()+ .add(((edge_count + 1) * std::mem::size_of::<u64>() as u64) as usize)+ };+ (offsets, data, true)+ }+ None => (ptr::null(), ptr::null(), false),+ };++ let road_names_region = MmapRegion::map(&format!("{base}road_names.bin"));+ let (road_names, road_names_size) = match &road_names_region {+ Some(r) => (r.base(), r.len),+ None => (ptr::null(), 0),+ };++ let nodes = nodes_region.base();+ let edges = edges_region.base();+ let transit_voyages = transit_voyages_region+ .as_ref()+ .map(|r| r.base())+ .unwrap_or(ptr::null());+ let transit_attributes = transit_attributes_region+ .as_ref()+ .map(|r| r.base())+ .unwrap_or(ptr::null());++ // --- Derived tables (identical formulas to the C++ init) ---+ let mut lon_to_mm_scale = [0u32; 4096];+ for i in 0..4096usize {+ let lat_deg = (((i as i64 - 2048) << 19) as f64) / 1e7;+ lon_to_mm_scale[i] =+ ((111_139_000.0 / 1e7) * (lat_deg * DEG_TO_RAD).cos() * 1024.0) as u32;+ }++ let calc_scale =+ |speed_m_s: f64| -> u64 { ((100.0 / (speed_m_s * 1000.0)) * 4_294_967_296.0) as u64 };++ let mut time_scale_fixed = [0u64; 4];+ time_scale_fixed[WALK as usize] = calc_scale(WALK_SPEED_M_S);+ time_scale_fixed[BICYCLE as usize] = calc_scale(BICYCLE_SPEED_M_S);+ time_scale_fixed[DRIVING as usize] = calc_scale(105.0 / 3.6);+ // Optimistic 80 km/h transit velocity keeps the heuristic admissible.+ time_scale_fixed[PUBLIC_TRANSIT as usize] = calc_scale(80.0 / 3.6);++ let mut edge_time_multipliers = [[0u64; 16]; 4];+ for m in 0..4usize {+ for r in 0..16usize {+ let speed_m_s = if m == DRIVING as usize {+ match r as u8 {+ 1 => 105.0 / 3.6, // MOTORWAY+ 2 => 85.0 / 3.6, // TRUNK+ 3 => 65.0 / 3.6, // PRIMARY+ 4 => 55.0 / 3.6, // SECONDARY+ 5 => 45.0 / 3.6, // TERTIARY+ _ => 30.0 / 3.6,+ }+ } else if m == BICYCLE as usize {+ BICYCLE_SPEED_M_S+ } else {+ WALK_SPEED_M_S+ };+ edge_time_multipliers[m][r] =+ ((100.0 / (speed_m_s * 1000.0)) * 4_294_967_296.0) as u64;+ }+ }++ Some(Graph {+ _nodes_region: nodes_region,+ _edges_region: edges_region,+ _transit_voyages_region: transit_voyages_region,+ _transit_attributes_region: transit_attributes_region,+ _intermediate_region: intermediate_region,+ _road_names_region: road_names_region,+ nodes,+ node_count,+ edges,+ edge_count,+ transit_voyages,+ transit_voyage_count,+ transit_attributes,+ intermediate_edge_offsets,+ intermediate_data,+ has_intermediate,+ road_names,+ road_names_size,+ present_feeds,+ lon_to_mm_scale,+ time_scale_fixed,+ edge_time_multipliers,+ })+ }++ // --- Raw accessors (all unaligned-safe) ---++ #[inline]+ pub fn node(&self, id: u32) -> NodeMaster {+ // Callers guarantee id <= node_count (sentinel index is valid).+ unsafe { read_at::<NodeMaster>(self.nodes, id as usize) }+ }++ /// Safe node fetch: returns a zeroed node for out-of-range ids, mirroring+ /// the C++ `get_node` fallback.+ #[inline]+ pub fn get_node(&self, id: u32) -> NodeMaster {+ if self.nodes.is_null() || id >= self.node_count {+ return NodeMaster {+ lat_e7: 0,+ lon_e7: 0,+ edge_ptr: 0,+ };+ }+ self.node(id)+ }++ #[inline]+ pub fn edge(&self, idx: u64) -> Edge {+ unsafe { read_at::<Edge>(self.edges, idx as usize) }+ }++ #[inline]+ fn intermediate_offset(&self, idx: u64) -> u64 {+ unsafe { read_at::<u64>(self.intermediate_edge_offsets, idx as usize) }+ }++ #[inline]+ fn transit_voyage(&self, idx: u64) -> TransitVoyageCompact {+ unsafe { read_at::<TransitVoyageCompact>(self.transit_voyages, idx as usize) }+ }++ #[inline]+ pub fn has_transit_voyages(&self) -> bool {+ !self.transit_voyages.is_null()+ }++ #[inline]+ pub fn get_node_transit_attr(&self, node_id: u32) -> TransitAttribute {+ if !self.transit_attributes.is_null() && node_id < self.node_count {+ unsafe { read_at::<TransitAttribute>(self.transit_attributes, node_id as usize) }+ } else {+ TransitAttribute {+ stop_code_off: 0xFFFF_FFFF,+ feed_name_off: 0xFFFF_FFFF,+ }+ }+ }++ #[inline]+ pub fn get_node_feed_name_off(&self, node_id: u32) -> u32 {+ self.get_node_transit_attr(node_id).feed_name_off+ }++ #[inline]+ pub fn get_node_stop_code_off(&self, node_id: u32) -> u32 {+ self.get_node_transit_attr(node_id).stop_code_off+ }++ /// Borrow a NUL-terminated road/feed/stop name from the string pool at+ /// `offset`. Returns `None` for the sentinel or out-of-range offsets.+ pub fn road_name(&self, offset: u32) -> Option<String> {+ if offset == 0xFFFF_FFFF || (offset as usize) >= self.road_names_size {+ return None;+ }+ Some(self.cstr_at(offset as usize))+ }++ /// Read the NUL-terminated string starting at byte `offset` in the pool.+ fn cstr_at(&self, offset: usize) -> String {+ unsafe {+ let start = self.road_names.add(offset);+ let mut len = 0usize;+ while offset + len < self.road_names_size && *start.add(len) != 0 {+ len += 1;+ }+ let slice = std::slice::from_raw_parts(start, len);+ String::from_utf8_lossy(slice).into_owned()+ }+ }++ /// Largest node index whose `edge_ptr <= edge_idx` (edge_ptr is monotonic).+ pub fn find_node_idx_for_edge(&self, edge_idx: u64) -> u32 {+ let mut low: i64 = 0;+ let mut high: i64 = self.node_count as i64 - 1;+ let mut res: u32 = 0;+ while low <= high {+ let mid = low + (high - low) / 2;+ if self.node(mid as u32).edge_ptr <= edge_idx {+ res = mid as u32;+ low = mid + 1;+ } else {+ high = mid - 1;+ }+ }+ res+ }++ /// 64-bit Morton code from lat/lon degrees (matches C++ `latlng_to_spatial`).+ pub fn latlng_to_spatial(lat: f64, lon: f64) -> u64 {+ let x = (lon + 180.0) / 360.0;+ let y = (lat + 90.0) / 180.0;+ let ix = (x * 4_294_967_295.0) as u32;+ let iy = (y * 4_294_967_295.0) as u32;+ let mut res: u64 = 0;+ for i in 0..32u64 {+ res |= (((ix >> i) & 1) as u64) << (2 * i);+ res |= (((iy >> i) & 1) as u64) << (2 * i + 1);+ }+ res+ }++ #[inline]+ pub fn node_spatial_id(node: &NodeMaster) -> u64 {+ Graph::latlng_to_spatial(node.lat_e7 as f64 * 1e-7, node.lon_e7 as f64 * 1e-7)+ }++ /// Decode the delta-encoded coordinate blob for `edge_idx` into `out`.+ /// Returns `Some((count, is_reversed))` when geometry is available,+ /// mirroring `get_edge_coordinates`. `out` must hold at least 256 points.+ pub fn get_edge_coordinates(&self, edge_idx: u64, out: &mut [LatLon]) -> Option<(u32, bool)> {+ if self.edges.is_null() || edge_idx >= self.edge_count {+ return None;+ }+ let e = self.edge(edge_idx);++ if e.type_ & REVERSE_GEOMETRY_FLAG != 0 {+ let u_global = self.find_node_idx_for_edge(edge_idx);+ let v_global = e.target;+ if v_global < self.node_count && self.has_intermediate {+ let s = self.node(v_global).edge_ptr;+ let e_ptr = self.node(v_global + 1).edge_ptr; // sentinel valid+ for k in s..e_ptr {+ if self.edge(k).target == u_global {+ let start_byte = self.intermediate_offset(k);+ let end_byte = self.intermediate_offset(k + 1);+ let cnt =+ self.decode_edge_coords(start_byte, (end_byte - start_byte) as u32, out);+ return Some((cnt, true));+ }+ }+ }+ None+ } else if self.has_intermediate {+ let start_byte = self.intermediate_offset(edge_idx);+ let end_byte = self.intermediate_offset(edge_idx + 1);+ let cnt = self.decode_edge_coords(start_byte, (end_byte - start_byte) as u32, out);+ Some((cnt, false))+ } else {+ None+ }+ }++ /// Delta-decode `byte_len` bytes at byte offset `data_off` in the+ /// intermediate blob into `out`. Returns the number of decoded points.+ fn decode_edge_coords(&self, data_off: u64, byte_len: u32, out: &mut [LatLon]) -> u32 {+ if byte_len < 8 {+ return 0;+ }+ let data = unsafe { self.intermediate_data.add(data_off as usize) };+ // First point is absolute (int32 lat_e7, int32 lon_e7).+ let mut lat = unsafe { (data as *const i32).read_unaligned() };+ let mut lon = unsafe { (data.add(4) as *const i32).read_unaligned() };+ out[0] = LatLon {+ lat_e7: lat,+ lon_e7: lon,+ };++ let mut count: u32 = 1;+ let mut off: u32 = 8;+ while off + 4 <= byte_len && count < 256 {+ let d_lat = unsafe { (data.add(off as usize) as *const i16).read_unaligned() };+ let d_lon = unsafe { (data.add(off as usize + 2) as *const i16).read_unaligned() };+ lat = lat.wrapping_add(d_lat as i32);+ lon = lon.wrapping_add(d_lon as i32);+ out[count as usize] = LatLon {+ lat_e7: lat,+ lon_e7: lon,+ };+ count += 1;+ off += 4;+ }+ count+ }++ /// Voyage record at absolute index `idx` (used for durations / deltas).+ #[inline]+ pub fn transit_voyage_at(&self, idx: u64) -> TransitVoyageCompact {+ self.transit_voyage(idx)+ }++ /// The first 4 bytes at voyage index `idx` reinterpreted as a u32 — the+ /// absolute departure time of voyage 0 (`*(uint32_t*)base` in the C++).+ #[inline]+ pub fn transit_dep_u32(&self, idx: u64) -> u32 {+ unsafe { read_at::<u32>(self.transit_voyages, idx as usize) }+ }+}++/// Fetch point `idx` from a decoded coordinate buffer, honouring reversal.+#[inline]+pub fn get_pt_at(coords: &[LatLon], count: u32, is_reversed: bool, idx: u32) -> LatLon {+ if is_reversed {+ coords[(count - 1 - idx) as usize]+ } else {+ coords[idx as usize]+ }+}
maps/src/main/rust/src/lib.rs
diff --git a/maps/src/main/rust/src/lib.rs b/maps/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..f84b0fc103--- /dev/null+++ b/maps/src/main/rust/src/lib.rs@@ -0,0 +1,461 @@+//! Offline routing engine + live-traffic MVT tile encoder for the Maps app,+//! exposed to Kotlin (`com.vayunmathur.maps.util.OfflineRouter`) via JNI.+//!+//! Rust port of the former CMake/C++ `libofflinerouter` (`native-lib.cpp` ++//! `scratchpad.h` + `radix_heap.h`). The whole-world graph is mmap'd once and+//! shared read-only behind an `Arc`; routing state is serialized behind a mutex;+//! traffic speeds and the per-square segment cache live in their own locks,+//! mirroring the C++ globals but made explicit.++mod geometry;+mod graph;+mod mvt;+mod routing;+mod state;++use std::collections::{BTreeMap, HashMap, HashSet};+use std::sync::{Arc, Mutex, OnceLock, RwLock};++use jni::objects::{+ JByteArray, JLongArray, JObject, JObjectArray, JString, JValue,+};+use jni::sys::{jboolean, jbyteArray, jdouble, jdoubleArray, jint, jlong, jobjectArray};+use jni::JNIEnv;++use crate::geometry::TrafficSpeeds;+use crate::graph::Graph;+use crate::routing::{perform_search_loop, prepare_routing, reconstruct_path};+use crate::state::{RadixHeap, RoutingScratchpad};++// ---------------------------------------------------------------------------+// Global state+// ---------------------------------------------------------------------------++/// The immutable whole-world graph, set once by `init`.+static GRAPH: RwLock<Option<Arc<Graph>>> = RwLock::new(None);++fn graph() -> Option<Arc<Graph>> {+ GRAPH.read().ok()?.clone()+}++/// Live traffic speeds (global edge id -> km/h). Read (snapshot) per route,+/// written by `updateTrafficNative`.+fn traffic_speeds() -> &'static RwLock<TrafficSpeeds> {+ static S: OnceLock<RwLock<TrafficSpeeds>> = OnceLock::new();+ S.get_or_init(|| RwLock::new(HashMap::new()))+}++/// Per-square traffic segments + requested-square set for the overlay/tiles.+struct TrafficMeta {+ by_square: BTreeMap<i32, Vec<f64>>,+ requested: Vec<u32>,+}++fn traffic_meta() -> &'static Mutex<TrafficMeta> {+ static M: OnceLock<Mutex<TrafficMeta>> = OnceLock::new();+ M.get_or_init(|| {+ Mutex::new(TrafficMeta {+ by_square: BTreeMap::new(),+ requested: Vec::new(),+ })+ })+}++/// Reusable A* working sets, serialized so only one route runs at a time.+struct RouteState {+ scratch: RoutingScratchpad,+ heap: RadixHeap,+}++fn route_state() -> &'static Mutex<RouteState> {+ static R: OnceLock<Mutex<RouteState>> = OnceLock::new();+ R.get_or_init(|| {+ Mutex::new(RouteState {+ scratch: RoutingScratchpad::new(),+ heap: RadixHeap::new(),+ })+ })+}++// ---------------------------------------------------------------------------+// Traffic prefetch reverse-callback+// ---------------------------------------------------------------------------++/// Request the traffic square containing `(lat_e7, lon_e7)` from Kotlin if it+/// hasn't been requested yet. Mirrors the C++ `ensure_traffic_loaded`.+fn ensure_traffic_loaded(+ env: &mut JNIEnv,+ thiz: &JObject,+ lat_e7: i32,+ lon_e7: i32,+ force_async: bool,+) {+ let lat_idx = (lat_e7 as f64 * 1e-7).floor() as i32;+ let lon_idx = (lon_e7 as f64 * 1e-7).floor() as i32;+ let packed = (((lat_idx + 360) as u32) << 16) | (lon_idx + 720) as u32;++ {+ let mut meta = traffic_meta().lock().unwrap();+ if meta.requested.contains(&packed) {+ return;+ }+ meta.requested.push(packed);+ }++ let _ = env.call_method(+ thiz,+ "fetchTrafficData",+ "(DDDDIZ)V",+ &[+ JValue::Double(lat_idx as f64),+ JValue::Double(lon_idx as f64),+ JValue::Double(lat_idx as f64 + 1.0),+ JValue::Double(lon_idx as f64 + 1.0),+ JValue::Int(packed as i32),+ JValue::Bool(force_async as u8),+ ],+ );+}++// ---------------------------------------------------------------------------+// JNI: init+// ---------------------------------------------------------------------------++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_init<'local>(+ mut env: JNIEnv<'local>,+ _thiz: JObject<'local>,+ base_path: JString<'local>,+ present_feeds: JObjectArray<'local>,+) -> jboolean {+ let base: String = match env.get_string(&base_path) {+ Ok(s) => s.into(),+ Err(_) => return 0,+ };++ let mut feeds: HashSet<String> = HashSet::new();+ if !present_feeds.is_null() {+ let len = env.get_array_length(&present_feeds).unwrap_or(0);+ for i in 0..len {+ if let Ok(obj) = env.get_object_array_element(&present_feeds, i) {+ let s = JString::from(obj);+ // Convert to an owned String within this statement so the+ // borrowing `JavaStr` is dropped before `s`.+ let val: Option<String> = env.get_string(&s).ok().map(|js| js.into());+ if let Some(v) = val {+ feeds.insert(v);+ }+ }+ }+ }++ match Graph::load(&base, feeds) {+ Some(g) => {+ if let Ok(mut w) = GRAPH.write() {+ *w = Some(Arc::new(g));+ 1+ } else {+ 0+ }+ }+ None => 0,+ }+}++// ---------------------------------------------------------------------------+// JNI: findRouteNative+// ---------------------------------------------------------------------------++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNative<'local>(+ mut env: JNIEnv<'local>,+ thiz: JObject<'local>,+ s_lat: jdouble,+ s_lon: jdouble,+ e_lat: jdouble,+ e_lon: jdouble,+ mode: jint,+ start_time: jlong,+) -> jobjectArray {+ let null = std::ptr::null_mut();+ let g = match graph() {+ Some(g) => g,+ None => return null,+ };++ // Snapshot the current traffic speeds so the hot loop needs no locking and+ // concurrent updateTrafficNative calls don't block the whole route.+ let speeds: TrafficSpeeds = traffic_speeds().read().map(|m| m.clone()).unwrap_or_default();++ let state_mutex = route_state();+ let mut state = state_mutex.lock().unwrap();+ let RouteState { scratch, heap } = &mut *state;++ // prepare + search need the JNI env for the driving traffic prefetch.+ let ctx = {+ let mut ensure = |lat_e7: i32, lon_e7: i32| {+ ensure_traffic_loaded(&mut env, &thiz, lat_e7, lon_e7, false);+ };++ let mut ctx = match prepare_routing(+ &g, &speeds, &mut ensure, s_lat, s_lon, e_lat, e_lon, mode, start_time as u32, scratch,+ heap,+ ) {+ Some(c) => c,+ None => return null,+ };+ perform_search_loop(&g, &speeds, &mut ensure, mode, &mut ctx, scratch, heap);+ ctx+ };++ if ctx.target_node == 0xFFFF_FFFF {+ return null;+ }++ let steps = reconstruct_path(&g, &speeds, mode, &ctx, scratch);++ // --- Marshal steps into OfflineRouter.RawStep[] ---+ let class = match env.find_class("com/vayunmathur/maps/util/OfflineRouter$RawStep") {+ Ok(c) => c,+ Err(_) => return null,+ };+ let ctor = "(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V";++ let array = match env.new_object_array(steps.len() as i32, &class, JObject::null()) {+ Ok(a) => a,+ Err(_) => return null,+ };++ for (i, step) in steps.iter().enumerate() {+ let name = g.road_name(step.name_off).unwrap_or_else(|| "Unknown Road".to_string());+ let jname: JObject = match env.new_string(&name) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };+ let jgeom = match env.new_double_array(step.coords.len() as i32) {+ Ok(a) => a,+ Err(_) => return null,+ };+ if env.set_double_array_region(&jgeom, 0, &step.coords).is_err() {+ return null;+ }+ let jgeom_obj: JObject = jgeom.into();++ let make_opt_string = |env: &mut JNIEnv<'local>, off: u32| -> JObject<'local> {+ match g.road_name(off) {+ Some(s) => match env.new_string(&s) {+ Ok(js) => js.into(),+ Err(_) => JObject::null(),+ },+ None => JObject::null(),+ }+ };+ let jfeed = make_opt_string(&mut env, step.feed_off);+ let jcode = make_opt_string(&mut env, step.code_off);+ let jend = make_opt_string(&mut env, step.end_code_off);++ let obj = match env.new_object(+ &class,+ ctor,+ &[+ JValue::Int(step.maneuver),+ JValue::Object(&jname),+ JValue::Long(step.dist_mm as i64),+ JValue::Long(step.time_10ms as i64),+ JValue::Object(&jgeom_obj),+ JValue::Double(step.speed_ratio),+ JValue::Bool(step.is_transit as u8),+ JValue::Object(&jfeed),+ JValue::Object(&jcode),+ JValue::Object(&jend),+ JValue::Int(step.stop_count),+ ],+ ) {+ Ok(o) => o,+ Err(_) => return null,+ };+ if env.set_object_array_element(&array, i as i32, &obj).is_err() {+ return null;+ }+ }++ array.into_raw()+}++// ---------------------------------------------------------------------------+// JNI: updateTrafficNative+// ---------------------------------------------------------------------------++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_updateTrafficNative<'local>(+ env: JNIEnv<'local>,+ _thiz: JObject<'local>,+ edge_ids: JLongArray<'local>,+ speeds: JByteArray<'local>,+ packed_square: jint,+) {+ let g = match graph() {+ Some(g) => g,+ None => return,+ };++ let len = env.get_array_length(&edge_ids).unwrap_or(0);+ if len <= 0 {+ // Still record an (empty) square so the overlay clears it.+ let mut meta = traffic_meta().lock().unwrap();+ meta.by_square.entry(packed_square).or_default().clear();+ return;+ }+ let mut ids = vec![0i64; len as usize];+ if env.get_long_array_region(&edge_ids, 0, &mut ids).is_err() {+ return;+ }+ let mut sp = vec![0i8; len as usize];+ if env.get_byte_array_region(&speeds, 0, &mut sp).is_err() {+ return;+ }++ let mut speeds_w = traffic_speeds().write().unwrap();+ let mut meta = traffic_meta().lock().unwrap();+ let segments = meta.by_square.entry(packed_square).or_default();+ segments.clear();++ for i in 0..len as usize {+ let edge_id = ids[i] as u64;+ let speed = sp[i] as u8;+ if edge_id < g.edge_count {+ let edge = g.edge(edge_id);+ if speed < 255 {+ speeds_w.insert(edge_id, speed);+ let node_u = g.node(g.find_node_idx_for_edge(edge_id));+ if edge.target < g.node_count {+ let node_v = g.node(edge.target);+ let ratio = if edge.speed_limit > 0 {+ speed as f64 / edge.speed_limit as f64+ } else {+ 1.0+ };+ segments.push(node_u.lat_e7 as f64 * 1e-7);+ segments.push(node_u.lon_e7 as f64 * 1e-7);+ segments.push(node_v.lat_e7 as f64 * 1e-7);+ segments.push(node_v.lon_e7 as f64 * 1e-7);+ segments.push(ratio);+ }+ }+ }+ }+}++// ---------------------------------------------------------------------------+// JNI: notifyTrafficFetchFinishedNative (no-op, kept for ABI compatibility)+// ---------------------------------------------------------------------------++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_notifyTrafficFetchFinishedNative<+ 'local,+>(+ _env: JNIEnv<'local>,+ _thiz: JObject<'local>,+ _packed_square: jint,+) {+}++// ---------------------------------------------------------------------------+// JNI: getTrafficSegmentsNative+// ---------------------------------------------------------------------------++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getTrafficSegmentsNative<+ 'local,+>(+ env: JNIEnv<'local>,+ _thiz: JObject<'local>,+) -> jdoubleArray {+ let null = std::ptr::null_mut();+ let meta = traffic_meta().lock().unwrap();++ let mut flattened: Vec<f64> = Vec::new();+ for segments in meta.by_square.values() {+ flattened.extend_from_slice(segments);+ if flattened.len() > 50000 {+ break;+ }+ }+ if flattened.len() > 50000 {+ flattened.truncate(50000);+ }++ match env.new_double_array(flattened.len() as i32) {+ Ok(arr) => {+ if !flattened.is_empty()+ && env.set_double_array_region(&arr, 0, &flattened).is_err()+ {+ return null;+ }+ arr.into_raw()+ }+ Err(_) => null,+ }+}++// ---------------------------------------------------------------------------+// JNI: getTrafficTileNative+// ---------------------------------------------------------------------------++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getTrafficTileNative<'local>(+ env: JNIEnv<'local>,+ _thiz: JObject<'local>,+ z: jint,+ x: jint,+ y: jint,+) -> jbyteArray {+ let null = std::ptr::null_mut();+ let tile = {+ let meta = traffic_meta().lock().unwrap();+ mvt::generate_traffic_tile(&meta.by_square, z, x, y)+ };+ let bytes = match tile {+ Some(b) => b,+ None => return null,+ };++ // set_byte_array_region takes &[i8]; reinterpret the gzip bytes.+ let signed: &[i8] =+ unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const i8, bytes.len()) };+ match env.new_byte_array(bytes.len() as i32) {+ Ok(arr) => {+ if env.set_byte_array_region(&arr, 0, signed).is_err() {+ return null;+ }+ arr.into_raw()+ }+ Err(_) => null,+ }+}++// ---------------------------------------------------------------------------+// JNI: ensureTrafficLoadedNative+// ---------------------------------------------------------------------------++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_ensureTrafficLoadedNative<+ 'local,+>(+ mut env: JNIEnv<'local>,+ thiz: JObject<'local>,+ lat: jdouble,+ lon: jdouble,+ force_async: jboolean,+) {+ if graph().is_none() {+ return;+ }+ ensure_traffic_loaded(+ &mut env,+ &thiz,+ (lat * 1e7) as i32,+ (lon * 1e7) as i32,+ force_async != 0,+ );+}
maps/src/main/rust/src/mvt.rs
diff --git a/maps/src/main/rust/src/mvt.rs b/maps/src/main/rust/src/mvt.rsnew file mode 100644index 0000000000..e10d8332ae--- /dev/null+++ b/maps/src/main/rust/src/mvt.rs@@ -0,0 +1,199 @@+//! Hand-rolled Mapbox Vector Tile encoder for the live-traffic overlay, plus+//! gzip. Port of the `--- MVT ENCODING UTILS ---` helpers and+//! `getTrafficTileNative` body from `native-lib.cpp`.++use std::collections::BTreeMap;+use std::io::Write;++use flate2::write::GzEncoder;+use flate2::Compression;++fn write_varint(buf: &mut Vec<u8>, mut value: u64) {+ while value >= 0x80 {+ buf.push((value as u8) | 0x80);+ value >>= 7;+ }+ buf.push(value as u8);+}++fn write_tag(buf: &mut Vec<u8>, field: u32, wire_type: u8) {+ write_varint(buf, ((field << 3) | wire_type as u32) as u64);+}++fn write_string(buf: &mut Vec<u8>, field: u32, s: &str) {+ write_tag(buf, field, 2);+ write_varint(buf, s.len() as u64);+ buf.extend_from_slice(s.as_bytes());+}++fn zigzag(n: i32) -> i32 {+ (n << 1) ^ (n >> 31)+}++fn mvt_command(cmd: u32, count: u32) -> u32 {+ (cmd & 0x7) | (count << 3)+}++struct TileProj {+ n: f64,+ x: i32,+ y: i32,+}++impl TileProj {+ fn wgs84_to_tile_px(&self, lat: f64, lon: f64) -> (i32, i32) {+ let lat_rad = lat * std::f64::consts::PI / 180.0;+ let tx = (lon + 180.0) / 360.0 * self.n;+ let ty =+ (1.0 - (lat_rad.tan() + (1.0 / lat_rad.cos())).ln() / std::f64::consts::PI) / 2.0 * self.n;+ let px = ((tx - self.x as f64) * 4096.0) as i32;+ let py = ((ty - self.y as f64) * 4096.0) as i32;+ (px, py)+ }+}++fn compress_gzip(input: &[u8]) -> Vec<u8> {+ if input.is_empty() {+ return Vec::new();+ }+ let mut enc = GzEncoder::new(Vec::new(), Compression::default());+ if enc.write_all(input).is_err() {+ return Vec::new();+ }+ enc.finish().unwrap_or_default()+}++/// Generate a gzip-compressed traffic MVT tile for `(z, x, y)`, or `None` if+/// there is no traffic to render / gzip fails. `by_square` maps packed square+/// ids to flat `[lat1, lon1, lat2, lon2, speed_ratio, ...]` segment lists.+pub fn generate_traffic_tile(+ by_square: &BTreeMap<i32, Vec<f64>>,+ z: i32,+ x: i32,+ y: i32,+) -> Option<Vec<u8>> {+ let n = 2f64.powi(z);+ let lon_min = x as f64 / n * 360.0 - 180.0;+ let lon_max = (x + 1) as f64 / n * 360.0 - 180.0;+ let lat_max = (std::f64::consts::PI * (1.0 - 2.0 * y as f64 / n)).sinh().atan() * 180.0+ / std::f64::consts::PI;+ let lat_min = (std::f64::consts::PI * (1.0 - 2.0 * (y + 1) as f64 / n)).sinh().atan() * 180.0+ / std::f64::consts::PI;++ let proj = TileProj { n, x, y };+ let mut layer_buf: Vec<u8> = Vec::new();+ write_string(&mut layer_buf, 1, "traffic");+ write_tag(&mut layer_buf, 15, 0);+ write_varint(&mut layer_buf, 2);+ write_tag(&mut layer_buf, 5, 0);+ write_varint(&mut layer_buf, 4096);++ let min_lat_idx = lat_min.floor() as i32;+ let max_lat_idx = lat_max.floor() as i32;+ let min_lon_idx = lon_min.floor() as i32;+ let max_lon_idx = lon_max.floor() as i32;++ // "color" is the only key; values are interned in first-seen order.+ let mut values: Vec<String> = Vec::new();+ let mut val_map: BTreeMap<String, u32> = BTreeMap::new();+ let mut get_val_idx = |v: &str| -> u32 {+ if let Some(&idx) = val_map.get(v) {+ idx+ } else {+ let idx = values.len() as u32;+ val_map.insert(v.to_string(), idx);+ values.push(v.to_string());+ idx+ }+ };++ for lat_i in min_lat_idx..=max_lat_idx {+ for lon_i in min_lon_idx..=max_lon_idx {+ let square_id = (((lat_i + 360) as u32) << 16) | (lon_i + 720) as u32;+ let data = match by_square.get(&(square_id as i32)) {+ Some(d) => d,+ None => continue,+ };++ let mut i = 0usize;+ while i + 4 < data.len() {+ let lat1 = data[i];+ let lon1 = data[i + 1];+ let lat2 = data[i + 2];+ let lon2 = data[i + 3];+ let speed_ratio = data[i + 4];+ i += 5;+ if speed_ratio <= 0.0 {+ continue;+ }+ let (px1, py1) = proj.wgs84_to_tile_px(lat1, lon1);+ let (px2, py2) = proj.wgs84_to_tile_px(lat2, lon2);+ if px1.max(px2) < -512+ || px1.min(px2) > 4608+ || py1.max(py2) < -512+ || py1.min(py2) > 4608+ {+ continue;+ }++ let mut feat_buf: Vec<u8> = Vec::new();+ write_varint(&mut feat_buf, ((3 << 3) | 0) as u64); // field 3 (id), wiretype 0+ write_varint(&mut feat_buf, 2);++ let mut geom_buf: Vec<u8> = Vec::new();+ write_varint(&mut geom_buf, mvt_command(1, 1) as u64); // MoveTo+ write_varint(&mut geom_buf, zigzag(px1) as u64);+ write_varint(&mut geom_buf, zigzag(py1) as u64);+ write_varint(&mut geom_buf, mvt_command(2, 1) as u64); // LineTo+ write_varint(&mut geom_buf, zigzag(px2 - px1) as u64);+ write_varint(&mut geom_buf, zigzag(py2 - py1) as u64);++ write_tag(&mut feat_buf, 4, 2);+ write_varint(&mut feat_buf, geom_buf.len() as u64);+ feat_buf.extend_from_slice(&geom_buf);++ let color = if speed_ratio < 0.5 {+ "#B71C1C"+ } else if speed_ratio < 0.9 {+ "#E65100"+ } else {+ "#1B5E20"+ };+ write_tag(&mut feat_buf, 2, 2);+ let mut tag_buf: Vec<u8> = Vec::new();+ write_varint(&mut tag_buf, 0); // key index (color)+ write_varint(&mut tag_buf, get_val_idx(color) as u64);+ write_varint(&mut feat_buf, tag_buf.len() as u64);+ feat_buf.extend_from_slice(&tag_buf);++ write_tag(&mut layer_buf, 2, 2); // feature+ write_varint(&mut layer_buf, feat_buf.len() as u64);+ layer_buf.extend_from_slice(&feat_buf);+ }+ }+ }++ // keys+ write_string(&mut layer_buf, 3, "color");+ // values+ for v in &values {+ write_tag(&mut layer_buf, 4, 2);+ let mut v_buf: Vec<u8> = Vec::new();+ write_string(&mut v_buf, 1, v);+ write_varint(&mut layer_buf, v_buf.len() as u64);+ layer_buf.extend_from_slice(&v_buf);+ }++ let mut tile_buf: Vec<u8> = Vec::new();+ write_tag(&mut tile_buf, 3, 2);+ write_varint(&mut tile_buf, layer_buf.len() as u64);+ tile_buf.extend_from_slice(&layer_buf);++ let compressed = compress_gzip(&tile_buf);+ if compressed.is_empty() {+ // Must not return raw protobuf: the Kotlin HTTP wrapper always tags the+ // body `Content-Encoding: gzip`, so a non-gzip body breaks MapLibre.+ return None;+ }+ Some(compressed)+}
maps/src/main/rust/src/routing.rs
diff --git a/maps/src/main/rust/src/routing.rs b/maps/src/main/rust/src/routing.rsnew file mode 100644index 0000000000..64343eff3d--- /dev/null+++ b/maps/src/main/rust/src/routing.rs@@ -0,0 +1,749 @@+//! Core A* routing: edge snapping, search, and path reconstruction.+//!+//! Port of the `--- CORE ROUTING ---` and path-reconstruction sections of+//! `native-lib.cpp`. Kept JNI-free: `perform_search_loop` calls back through an+//! `ensure_traffic` closure for the DRIVING traffic prefetch, and+//! `reconstruct_path` returns plain [`StepData`] that `lib.rs` marshals into the+//! Kotlin `RawStep[]`.++use crate::geometry::*;+use crate::graph::*;+use crate::state::{RadixHeap, RoutingScratchpad};++pub struct SnappedEdge {+ pub node_a: u32,+ pub node_b: u32,+ pub proj_lat: i32,+ pub proj_lon: i32,+ pub dist_a_mm: u32,+ pub dist_b_mm: u32,+ pub type_: u8,+ pub speed_limit: u8,+ pub name_offset: u32,+ pub edge_idx: u64,+ pub segment_idx: u32,+}++impl SnappedEdge {+ fn empty(proj_lat: i32, proj_lon: i32) -> SnappedEdge {+ SnappedEdge {+ node_a: 0xFFFF_FFFF,+ node_b: 0xFFFF_FFFF,+ proj_lat,+ proj_lon,+ dist_a_mm: 0,+ dist_b_mm: 0,+ type_: 0,+ speed_limit: 0,+ name_offset: 0xFFFF_FFFF,+ edge_idx: INVALID_EDGE,+ segment_idx: 0,+ }+ }+}++pub struct RoutingContext {+ pub start: SnappedEdge,+ pub end: SnappedEdge,+ pub target_node: u32,+ pub iterations: i32,+ pub start_time: u32,+}++/// One coalesced navigation step (pre-localization). Marshaled to Kotlin+/// `OfflineRouter.RawStep` in `lib.rs`.+pub struct StepData {+ pub name_off: u32,+ pub dist_mm: u64,+ pub time_10ms: u64,+ pub coords: Vec<f64>, // flat [lon, lat, lon, lat, ...]+ pub maneuver: i32,+ pub speed_ratio: f64,+ pub is_transit: bool,+ pub feed_off: u32,+ pub code_off: u32,+ pub end_code_off: u32,+ pub stop_count: i32,+}++/// Snap a WGS84 point to the nearest routable edge for `mode`.+pub fn find_nearest_edge(g: &Graph, lat: f64, lon: f64, mode: i32) -> SnappedEdge {+ let target_spatial = Graph::latlng_to_spatial(lat, lon);+ let p_lat = (lat * 1e7) as i32;+ let p_lon = (lon * 1e7) as i32;+ let mut best = SnappedEdge::empty(p_lat, p_lon);++ if g.node_count == 0 {+ return best;+ }++ let mut min_snap_dist: u32 = 0xFFFF_FFFF;++ // Binary search the globally Morton-sorted node array for the node just+ // below the target code.+ let mut low: u32 = 0;+ let mut high: u32 = g.node_count - 1;+ let mut local_center: u32 = 0;+ while low <= high {+ let mid = low + (high - low) / 2;+ if Graph::node_spatial_id(&g.node(mid)) < target_spatial {+ local_center = mid;+ low = mid + 1;+ } else {+ if mid == 0 {+ break;+ }+ high = mid - 1;+ }+ }++ let mut coords = [LatLon { lat_e7: 0, lon_e7: 0 }; 256];++ const WINDOW: i32 = 800;+ let lo = std::cmp::max(0, local_center as i32 - WINDOW);+ let hi = std::cmp::min(g.node_count as i32 - 1, local_center as i32 + WINDOW);+ for i in lo..=hi {+ let u_global = i as u32;+ let node_u = g.node(u_global);+ let e_ptr = g.node(u_global + 1).edge_ptr; // sentinel valid+ for j in node_u.edge_ptr..e_ptr {+ let e = g.edge(j);+ if e.type_ & TRANSIT_FLAG != 0 {+ continue;+ }+ if !is_mode_allowed(e.type_, mode) {+ continue;+ }+ if e.target >= g.node_count {+ continue;+ }++ if let Some((count, is_reversed)) = g.get_edge_coordinates(j, &mut coords) {+ if count >= 2 {+ let num_pts = count;+ let mut current_dist_from_start_mm: u32 = 0;+ for p in 0..num_pts - 1 {+ let p1 = get_pt_at(&coords, count, is_reversed, p);+ let p2 = get_pt_at(&coords, count, is_reversed, p + 1);++ let proj =+ get_projection(g, p_lat, p_lon, p1.lat_e7, p1.lon_e7, p2.lat_e7, p2.lon_e7);+ if proj.dist_mm < min_snap_dist {+ min_snap_dist = proj.dist_mm;+ best.node_a = u_global;+ best.node_b = e.target;+ best.proj_lat = proj.lat_e7;+ best.proj_lon = proj.lon_e7;+ best.type_ = e.type_;+ best.speed_limit = e.speed_limit;+ best.name_offset = e.name_offset;+ best.edge_idx = j;+ best.segment_idx = p;++ let dist_to_proj_seg_mm =+ fast_dist_mm(g, p1.lat_e7, p1.lon_e7, proj.lat_e7, proj.lon_e7);+ best.dist_a_mm = current_dist_from_start_mm + dist_to_proj_seg_mm;+ best.dist_b_mm = if e.dist_mm > best.dist_a_mm {+ e.dist_mm - best.dist_a_mm+ } else {+ 0+ };+ }+ current_dist_from_start_mm +=+ fast_dist_mm(g, p1.lat_e7, p1.lon_e7, p2.lat_e7, p2.lon_e7);+ }+ continue;+ }+ }++ // No geometry: snap to the straight node-to-node segment.+ let node_v = g.node(e.target);+ let p = get_projection(+ g, p_lat, p_lon, node_u.lat_e7, node_u.lon_e7, node_v.lat_e7, node_v.lon_e7,+ );+ if p.dist_mm < min_snap_dist {+ min_snap_dist = p.dist_mm;+ best.node_a = u_global;+ best.node_b = e.target;+ best.proj_lat = p.lat_e7;+ best.proj_lon = p.lon_e7;+ best.dist_a_mm = fast_dist_mm(g, p.lat_e7, p.lon_e7, node_u.lat_e7, node_u.lon_e7);+ best.dist_b_mm = fast_dist_mm(g, p.lat_e7, p.lon_e7, node_v.lat_e7, node_v.lon_e7);+ best.type_ = e.type_;+ best.speed_limit = e.speed_limit;+ best.name_offset = e.name_offset;+ best.edge_idx = j;+ best.segment_idx = 0;+ }+ }+ }+ best+}++/// Snap endpoints, seed the open set. Returns `None` if snapping fails.+#[allow(clippy::too_many_arguments)]+pub fn prepare_routing(+ g: &Graph,+ traffic: &TrafficSpeeds,+ ensure_traffic: &mut dyn FnMut(i32, i32),+ s_lat: f64,+ s_lon: f64,+ e_lat: f64,+ e_lon: f64,+ mode: i32,+ start_time: u32,+ scratch: &mut RoutingScratchpad,+ heap: &mut RadixHeap,+) -> Option<RoutingContext> {+ scratch.reset();+ heap.clear();++ let start = find_nearest_edge(g, s_lat, s_lon, mode);+ let end = find_nearest_edge(g, e_lat, e_lon, mode);+ if start.node_a == 0xFFFF_FFFF || end.node_a == 0xFFFF_FFFF {+ return None;+ }++ if mode == DRIVING {+ ensure_traffic(start.proj_lat, start.proj_lon);+ }++ let push = |node: u32, travel_dist_mm: u32, scratch: &mut RoutingScratchpad, heap: &mut RadixHeap| {+ let t_actual = get_edge_time_10ms(+ g, traffic, INVALID_EDGE, travel_dist_mm, start.type_, start.speed_limit, mode,+ );+ {+ let entry = scratch.get_entry(node, 0);+ entry.g_fwd = t_actual;+ entry.g_bwd = t_actual;+ entry.last_type = start.type_;+ }+ let n_data = g.get_node(node);+ let h = heuristic_time_10ms(g, n_data.lat_e7, n_data.lon_e7, end.proj_lat, end.proj_lon, mode);+ heap.push(t_actual.wrapping_add(h), node << 1);+ };+ push(start.node_a, start.dist_a_mm, scratch, heap);+ push(start.node_b, start.dist_b_mm, scratch, heap);++ Some(RoutingContext {+ start,+ end,+ target_node: 0xFFFF_FFFF,+ iterations: 0,+ start_time,+ })+}++/// A* main loop. Fills `ctx.target_node` on success.+pub fn perform_search_loop(+ g: &Graph,+ traffic: &TrafficSpeeds,+ ensure_traffic: &mut dyn FnMut(i32, i32),+ mode: i32,+ ctx: &mut RoutingContext,+ scratch: &mut RoutingScratchpad,+ heap: &mut RadixHeap,+) {+ while !heap.empty() && ctx.iterations < 1_000_000 {+ ctx.iterations += 1;+ let u_idx = heap.pop();+ let u = u_idx >> 1;+ let u_state = (u_idx & 1) as i32;++ if (u == ctx.end.node_a || u == ctx.end.node_b)+ && (mode != PUBLIC_TRANSIT || u_state == 1)+ {+ ctx.target_node = u_idx;+ break;+ }++ let (u_cost, u_actual_time, u_last_type, u_last_name_off) = {+ let e = scratch.get_entry(u, u_state);+ (e.g_fwd, e.g_bwd, e.last_type, e.last_name_off)+ };+ if u >= g.node_count {+ continue;+ }+ let n_u = g.node(u);++ if mode == DRIVING {+ ensure_traffic(n_u.lat_e7, n_u.lon_e7);+ }+ let s = n_u.edge_ptr;+ let e_ptr = g.node(u + 1).edge_ptr; // sentinel valid++ for i in s..e_ptr {+ let edge = g.edge(i);+ if !is_mode_allowed(edge.type_, mode) {+ continue;+ }++ let travel_time: u32;+ let v_state: i32 = if mode == PUBLIC_TRANSIT && (edge.type_ & TRANSIT_FLAG) != 0 {+ 1+ } else {+ 0+ };+ if v_state == 1 {+ let is_boarding = (u_last_type & TRANSIT_FLAG) == 0;+ let is_transfer = !is_boarding && (edge.name_offset != u_last_name_off);++ let ta_u = g.get_node_transit_attr(u);+ // Only board/transfer at recognized transit stops.+ if (is_boarding || is_transfer) && ta_u.stop_code_off == 0xFFFF_FFFF {+ continue;+ }++ let (tt, _wait, _move) = get_transit_edge_time_10ms(+ g,+ &edge,+ u_actual_time,+ ctx.start_time,+ ta_u.feed_name_off,+ is_boarding || is_transfer,+ );+ if tt == 0xFFFF_FFFF {+ continue;+ }+ travel_time = tt;+ } else {+ // Only alight from transit at recognized transit stops.+ if mode == PUBLIC_TRANSIT && (u_last_type & TRANSIT_FLAG) != 0 {+ let ta_u = g.get_node_transit_attr(u);+ if ta_u.stop_code_off == 0xFFFF_FFFF {+ continue;+ }+ }+ travel_time =+ get_edge_time_10ms(g, traffic, i, edge.dist_mm, edge.type_, edge.speed_limit, mode);+ }++ let v = edge.target;+ let new_g = u_cost.wrapping_add(travel_time);+ let update = {+ let entry_v = scratch.get_entry(v, v_state);+ if new_g < entry_v.g_fwd {+ entry_v.g_fwd = new_g;+ entry_v.g_bwd = new_g;+ entry_v.p_fwd = u_idx;+ entry_v.last_type = edge.type_;+ entry_v.last_name_off = edge.name_offset;+ true+ } else {+ false+ }+ };+ if update {+ let n_v = g.get_node(v);+ let h = heuristic_time_10ms(+ g, n_v.lat_e7, n_v.lon_e7, ctx.end.proj_lat, ctx.end.proj_lon, mode,+ );+ heap.push(new_g.wrapping_add(h), (v << 1) | v_state as u32);+ }+ }+ }+}++/// Accumulates coalesced steps while walking the reconstructed path.+struct StepBuilder<'a> {+ g: &'a Graph,+ traffic: &'a TrafficSpeeds,+ mode: i32,+ start_time_abs: u32,+ steps: Vec<StepData>,+ last_bearing: f64,+ current_elapsed_10ms: u32,+ last_w
Diff truncated.