Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / maps / src / main / rust / src / graph_part3.rs

graph_part3.rs302 lines · 12.8 KiBRaw
1
2impl Graph {
3 /// Byte offset of edge `idx`'s name in the string pool, or `None` when it has
4 /// none.
5 ///
6 /// Separate from [`Edge`] because two thirds of edges are unnamed — 62.3% of
7 /// California's, 68.9% of Europe's — and this is read on the
8 /// instruction-emission path, never in the A* relaxation. So the field is a
9 /// sparse side table: three loads instead of one, for the third of edges that
10 /// have a name and nothing at all for the rest.
11 ///
12 /// Being the *sole* reader is what made that possible. The A* relaxation used to
13 /// copy this into the scratchpad on every improving edge — into a field nothing
14 /// ever read — and until that store went away no sparse representation was
15 /// affordable.
16 #[inline]
17 pub fn edge_name_offset(&self, idx: u64) -> Option<u32> {
18 if !self.names.contains(idx) {
19 return None;
20 }
21 Some(unsafe { read_at::<u32>(self.name_off, self.names.rank_of(idx) as usize) })
22 }
23
24 /// Real OSM per-lane turn-indication masks for directed edge `idx`, ordered
25 /// left→right. Each `u16` is a set of `LANE_*` bits. Returns `None` when the
26 /// graph has no lane data or this edge carries none (callers then fall back
27 /// to topology-inferred lanes).
28 ///
29 /// The index is sparse, so "this edge has no lanes" is spelled as absence from
30 /// it and found by binary search. `turn:lanes` is rare — 2.9 M of a planet's
31 /// 1.07 G edges — and this is called once per maneuver rather than per edge,
32 /// so ~22 probes buys back 8.6 GB of dense offset table.
33 pub fn edge_lane_masks(&self, idx: u64) -> Option<Vec<u16>> {
34 if self.lane_index.is_null() || idx >= self.edge_count {
35 return None;
36 }
37 let want = u32::try_from(idx).ok()?;
38 let entry = |i: u32| unsafe { read_at::<LaneEntry>(self.lane_index, i as usize) };
39 // Lower bound over the real entries; the trailing sentinel is only ever
40 // read for its offset, which is how the last edge gets a length.
41 let mut lo = 0u32;
42 let mut hi = self.lane_edges;
43 while lo < hi {
44 let mid = lo + (hi - lo) / 2;
45 if entry(mid).edge_idx < want {
46 lo = mid + 1;
47 } else {
48 hi = mid;
49 }
50 }
51 if lo >= self.lane_edges || entry(lo).edge_idx != want {
52 return None;
53 }
54 let start = entry(lo).blob_off;
55 let end = entry(lo + 1).blob_off;
56 if end <= start {
57 return None;
58 }
59 let count = ((end - start) as usize) / std::mem::size_of::<u16>();
60 let mut out = Vec::with_capacity(count);
61 for k in 0..count {
62 let byte_off = start as usize + k * std::mem::size_of::<u16>();
63 let mask = unsafe { (self.lane_data.add(byte_off) as *const u16).read_unaligned() };
64 out.push(mask);
65 }
66 Some(out)
67 }
68
69 /// Byte offset of the `g`-th geometry edge's polyline in the intermediate blob.
70 ///
71 /// Two loads instead of one: a `u64` per [`INTERMEDIATE_BLOCK`] geometry edges
72 /// plus a `u16` each. Same cost profile, and 1.5 GB smaller at planet scale
73 /// than one `u64` apiece.
74 #[inline]
75 fn geometry_offset(&self, g: u64) -> u64 {
76 let coarse =
77 unsafe { read_at::<u64>(self.intermediate_coarse, (g / INTERMEDIATE_BLOCK) as usize) };
78 let within = unsafe { read_at::<u16>(self.intermediate_within, g as usize) };
79 coarse + u64::from(within)
80 }
81
82 /// `(byte offset, length)` of edge `idx`'s stored polyline, or `None` when it
83 /// stores none.
84 #[inline]
85 fn intermediate_range(&self, idx: u64) -> Option<(u64, u32)> {
86 if !self.geometry.contains(idx) {
87 return None;
88 }
89 let g = self.geometry.rank_of(idx);
90 let start = self.geometry_offset(g);
91 let end = self.geometry_offset(g + 1);
92 Some((start, (end - start) as u32))
93 }
94
95 /// Borrow a NUL-terminated road/feed/stop name from the string pool at
96 /// `offset`. Returns `None` for the sentinel or out-of-range offsets.
97 pub fn road_name(&self, offset: u32) -> Option<String> {
98 if offset == NO_NAME || (offset as usize) >= self.road_names_size {
99 return None;
100 }
101 Some(self.cstr_at(offset as usize))
102 }
103
104 /// Read the NUL-terminated string starting at byte `offset` in the pool.
105 fn cstr_at(&self, offset: usize) -> String {
106 unsafe {
107 let start = self.road_names.add(offset);
108 let mut len = 0usize;
109 while offset + len < self.road_names_size && *start.add(len) != 0 {
110 len += 1;
111 }
112 let slice = std::slice::from_raw_parts(start, len);
113 String::from_utf8_lossy(slice).into_owned()
114 }
115 }
116
117 /// The node whose edge range `edge_idx` falls in, i.e. the edge's source.
118 ///
119 /// Found by binary search on the monotonic `edge_ptr`, ~29 probes on a planet.
120 /// Only for the one caller that genuinely has no source: an edge index arriving
121 /// from Kotlin in `updateTrafficNative`. Everything else already holds the
122 /// source, because it got the edge index by iterating a node's own range.
123 ///
124 /// # The tie-break is a contract, not an accident
125 ///
126 /// This returns the **largest** node index whose `edge_ptr <= edge_idx`. That is
127 /// the unique owner of the edge — any larger node's `edge_ptr` is at least
128 /// `edge_ptr(owner + 1)`, which is past `edge_idx` — but it is only the same
129 /// thing as the *first* such node when every node has out-degree at least one.
130 /// Degree-0 nodes exist (1,480 of California's 6.4 M, 0.023%), and they make
131 /// runs of nodes share an `edge_ptr`. A reimplementation that returned the first
132 /// of such a run would satisfy the description "a node whose `edge_ptr <=
133 /// edge_idx`" and be wrong: that node's range is empty, and the result seeds
134 /// [`Graph::decode_edge_coords`], so the failure is a polyline drawn from the
135 /// wrong place rather than anything that reports an error.
136 pub fn find_node_idx_for_edge(&self, edge_idx: u64) -> u32 {
137 let mut low: i64 = 0;
138 let mut high: i64 = self.node_count as i64 - 1;
139 let mut res: u32 = 0;
140 while low <= high {
141 let mid = low + (high - low) / 2;
142 if self.node(mid as u32).edge_ptr <= edge_idx {
143 res = mid as u32;
144 low = mid + 1;
145 } else {
146 high = mid - 1;
147 }
148 }
149 res
150 }
151
152 /// 64-bit Morton (Z-order) code from lat/lon degrees.
153 ///
154 /// The node array is sorted by this, so it decides both what
155 /// [`crate::routing::find_nearest_edge`]'s fixed 800-node window covers and how
156 /// far apart two adjacent nodes' *indices* are. It must agree bit for bit with
157 /// `latlng_to_spatial` in `scripts/maps/osm_ingest/src/spatial.rs`, which is
158 /// what sorts the array; that crate has a test comparing the two
159 /// transcriptions.
160 ///
161 /// # Hilbert was tried and is not better
162 ///
163 /// Z-order's known flaw is the "Z" discontinuity at every quadrant boundary:
164 /// the cells either side are neighbours on the ground and up to a whole
165 /// quadrant apart in index. Hilbert has no long-range jumps at all, so it looks
166 /// like the obvious win for `edges.bin`, which stores `target` as an `i16`
167 /// delta from its source and needs an escape table for the pairs that do not
168 /// fit.
169 ///
170 /// Measured on California (`road_graph --stats`), it is not. The two curves
171 /// cross almost exactly at the `i16` boundary:
172 ///
173 /// | `|target - source|` > | Morton | Hilbert |
174 /// |---|---|---|
175 /// | 1,024 | 2.225% | 2.155% |
176 /// | 16,384 | 0.4711% | 0.4648% |
177 /// | **32,767** | **0.3014%** | **0.3076%** |
178 /// | 262,144 | 0.0713% | 0.0892% |
179 ///
180 /// Hilbert wins below ~16 k and loses above it: it concentrates the
181 /// distribution rather than shortening it, trading mid-range deltas for far
182 /// ones. So the quadrant discontinuities are *not* what generates the 0.3%
183 /// tail — mapping a 2-D neighbourhood onto a 1-D index costs that much however
184 /// it is done — and the escape table is unavoidable. Not worth a node
185 /// permutation change for 2% the wrong way.
186 pub fn latlng_to_spatial(lat: f64, lon: f64) -> u64 {
187 let x = (lon + 180.0) / 360.0;
188 let y = (lat + 90.0) / 180.0;
189 let ix = (x * 4_294_967_295.0) as u32;
190 let iy = (y * 4_294_967_295.0) as u32;
191 let mut res: u64 = 0;
192 for i in 0..32u64 {
193 res |= (((ix >> i) & 1) as u64) << (2 * i);
194 res |= (((iy >> i) & 1) as u64) << (2 * i + 1);
195 }
196 res
197 }
198
199 #[inline]
200 pub fn node_spatial_id(node: &NodeMaster) -> u64 {
201 Graph::latlng_to_spatial(node.lat_e7 as f64 * 1e-7, node.lon_e7 as f64 * 1e-7)
202 }
203
204 /// Decode the delta-encoded coordinate blob for `edge_idx`, whose source is
205 /// `source`, into `out`. Returns `Some((count, is_reversed))`, with `count == 0`
206 /// when the edge stores no polyline. `out` must hold at least 256 points.
207 ///
208 /// The `edges.is_null()` arm means "graph without an edge table", not
209 /// "blocked layout": under v7 the base is still the section base (see
210 /// `load`/`assemble`), and the per-record path reads the inflate cache.
211 ///
212 /// `source` must really be the node whose range `edge_idx` falls in. It seeds
213 /// the decode, so a wrong one silently draws the polyline from the wrong place.
214 /// Every call site iterating a node's edge range already has it; the one that
215 /// does not recovers it with [`Graph::find_node_idx_for_edge`].
216 pub fn get_edge_coordinates_from(
217 &self,
218 source: u32,
219 edge_idx: u64,
220 out: &mut [LatLon],
221 ) -> Option<(u32, bool)> {
222 if self.edges.is_null() || edge_idx >= self.edge_count {
223 return None;
224 }
225 let e = self.edge(source, edge_idx);
226 if source >= self.node_count || e.target >= self.node_count {
227 return None;
228 }
229
230 if e.type_ & REVERSE_GEOMETRY_FLAG != 0 {
231 // The twin runs `target -> source`, so it is seeded and terminated the
232 // other way round. `get_pt_at` is what flips the result for callers.
233 let (s, e_ptr) = self.edge_range(e.target);
234 for k in s..e_ptr {
235 if self.edge_targets(k, e.target, source) {
236 let cnt = self.decode_edge_coords(k, e.target, source, out);
237 return Some((cnt, true));
238 }
239 }
240 None
241 } else {
242 let cnt = self.decode_edge_coords(edge_idx, source, e.target, out);
243 Some((cnt, false))
244 }
245 }
246
247 /// Delta-decode edge `idx`'s polyline into `out`, seeded with node `source`'s
248 /// coordinates and terminated with node `target`'s. Returns the number of
249 /// decoded points, or 0 when the edge stores no polyline.
250 ///
251 /// The blob holds *only* the interior points, because the first and last are
252 /// always the edge's own endpoints and `nodes.bin` already has both. Nothing
253 /// here distinguishes an absent blob from an empty one; the presence bitmap
254 /// does, in [`Graph::intermediate_range`].
255 fn decode_edge_coords(&self, idx: u64, source: u32, target: u32, out: &mut [LatLon]) -> u32 {
256 let Some((data_off, byte_len)) = self.intermediate_range(idx) else {
257 return 0;
258 };
259 let a = self.node(source);
260 let mut lat = a.lat_e7;
261 let mut lon = a.lon_e7;
262 out[0] = LatLon {
263 lat_e7: lat,
264 lon_e7: lon,
265 };
266
267 let data = unsafe { self.intermediate_data.add(data_off as usize) };
268 let mut count: u32 = 1;
269 let mut off: u32 = 0;
270 // One slot is reserved for the target, so the interior stops one short of
271 // the 256 points every caller's buffer holds.
272 while off + 4 <= byte_len && count + 1 < 256 {
273 let d_lat = unsafe { (data.add(off as usize) as *const i16).read_unaligned() };
274 let d_lon = unsafe { (data.add(off as usize + 2) as *const i16).read_unaligned() };
275 lat = lat.wrapping_add(d_lat as i32);
276 lon = lon.wrapping_add(d_lon as i32);
277 out[count as usize] = LatLon {
278 lat_e7: lat,
279 lon_e7: lon,
280 };
281 count += 1;
282 off += 4;
283 }
284
285 let b = self.node(target);
286 out[count as usize] = LatLon {
287 lat_e7: b.lat_e7,
288 lon_e7: b.lon_e7,
289 };
290 count + 1
291 }
292}
293
294/// Fetch point `idx` from a decoded coordinate buffer, honouring reversal.
295#[inline]
296pub fn get_pt_at(coords: &[LatLon], count: u32, is_reversed: bool, idx: u32) -> LatLon {
297 if is_reversed {
298 coords[(count - 1 - idx) as usize]
299 } else {
300 coords[idx as usize]
301 }
302}