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

Modern-Apps.git / scripts / maps / osm_ingest / src / geom.rs

geom.rs312 lines · 12.9 KiBRaw
1//! Delta encoder for `intermediate.bin` — the per-edge geometry blob.
2//!
3//! The reader is `maps/src/main/rust/src/graph.rs`'s `decode_edge_coords`, and
4//! it is the authority for every rule here:
5//!
6//! * **Only the interior points are stored.** A polyline's first point is its
7//! edge's source node and its last is its target, and the reader has both
8//! from `nodes.bin` already, so storing them costs 12 bytes per edge to
9//! repeat what is known. A blob is `m - 2` pairs of `i16` deltas, i.e.
10//! `4 * (m - 2)` bytes, and the reader recovers `m = byte_len / 4 + 2`.
11//! * The first delta is relative to the source, and the delta that would land
12//! on the target is the one omitted. An **empty** blob is therefore a
13//! well-formed two-point polyline — the chord — and not a special case.
14//! * The reader adds deltas with `wrapping_add`, so a delta that does not fit
15//! is silent corruption rather than an error — hence [`fits`] and the
16//! assertions in [`encode`].
17//! * The decode loop stops at [`MAX_POINTS`] points, and every caller in
18//! `routing.rs` passes a `[LatLon; 256]`, so an edge may hold at most that
19//! many. Beyond it the reader would silently truncate the polyline.
20//!
21//! Whether an edge stores a blob at all is *not* spelled here: `intermediate.bin`
22//! carries one presence bit per directed edge, so "this edge has no stored
23//! geometry" is a bitmap test rather than a length.
24//!
25//! Where a real gap between two consecutive vertices exceeds the `i16` range we
26//! insert extra points *on the straight line between them*. That leaves the
27//! polyline geometrically identical — the inserted vertices are collinear with
28//! the pair they split — and costs 4 bytes each. This is why the encoder can
29//! promise exact geometry while still obeying a 3.2767°/step limit.
30
31/// Most points one edge may carry, endpoints included. `graph.rs`'s decode loop
32/// stops there and its callers allocate exactly `[LatLon; 256]`, so the largest
33/// legal blob is `4 * (MAX_POINTS - 2)` = 1016 bytes.
34pub const MAX_POINTS: u32 = 256;
35
36/// Largest per-axis step the `i16` deltas can express. `i16::MIN` would also
37/// fit, but keeping the bound symmetric means [`interp_steps`] needs only the
38/// magnitude.
39const MAX_DELTA: i64 = i16::MAX as i64;
40
41/// A geometry vertex in the graph's fixed-point degrees.
42pub type Pt = (i32, i32);
43
44/// How many encoded points it takes to travel from `a` to `b`, not counting
45/// `a`. Exactly 1 when the gap already fits in `i16` deltas, more when
46/// collinear interpolation is needed.
47#[inline]
48pub fn segment_points(a: Pt, b: Pt) -> u64 {
49 interp_steps(a, b)
50}
51
52/// Total encoded points for a whole polyline, interpolation included. Compare
53/// against [`MAX_POINTS`] to decide whether an edge must be split.
54pub fn encoded_points(points: &[Pt]) -> u64 {
55 if points.is_empty() {
56 return 0;
57 }
58 let mut n = 1u64;
59 for w in points.windows(2) {
60 n += interp_steps(w[0], w[1]);
61 }
62 n
63}
64
65/// Steps needed to get from `a` to `b` with no axis moving more than
66/// [`MAX_DELTA`] per step. Widened to `i64` because a segment spanning the
67/// antimeridian has a longitude difference of up to 3.6e9, which overflows
68/// `i32`.
69#[inline]
70fn interp_steps(a: Pt, b: Pt) -> u64 {
71 let dlat = (i64::from(b.0) - i64::from(a.0)).abs();
72 let dlon = (i64::from(b.1) - i64::from(a.1)).abs();
73 let worst = dlat.max(dlon);
74 if worst <= MAX_DELTA {
75 return 1;
76 }
77 // Ceiling division; `worst > 0` here so this cannot be zero.
78 ((worst + MAX_DELTA - 1) / MAX_DELTA) as u64
79}
80
81/// True when `points` can be encoded without truncation.
82pub fn fits(points: &[Pt]) -> bool {
83 points.len() >= 2 && encoded_points(points) <= u64::from(MAX_POINTS)
84}
85
86/// Append the encoded form of `points` to `out`, returning the number of points
87/// the reader will decode — which is two more than the number of deltas written.
88///
89/// Panics if the result would exceed [`MAX_POINTS`]: that is a builder bug, and
90/// the failure mode on device (a silently shortened polyline) is much worse than
91/// a failed build. Callers split or drop geometry themselves, using [`fits`].
92pub fn encode(points: &[Pt], out: &mut Vec<u8>) -> u32 {
93 if points.len() < 2 {
94 return 0;
95 }
96 let total = encoded_points(points);
97 assert!(
98 total <= u64::from(MAX_POINTS),
99 "edge geometry needs {total} encoded points, over the {MAX_POINTS} the reader can decode"
100 );
101
102 let mut count = 1u64;
103 let mut cur = points[0];
104
105 for w in points.windows(2) {
106 let (a, b) = (w[0], w[1]);
107 let steps = interp_steps(a, b);
108 let dlat = i64::from(b.0) - i64::from(a.0);
109 let dlon = i64::from(b.1) - i64::from(a.1);
110 for s in 1..=steps {
111 // Truncating division is fine and deliberate: at s == steps it
112 // yields exactly `b`, so interpolation never moves an original
113 // vertex, and every intermediate point lies on the a->b line.
114 let s = s as i64;
115 let steps_i = steps as i64;
116 let next = (
117 (i64::from(a.0) + dlat * s / steps_i) as i32,
118 (i64::from(a.1) + dlon * s / steps_i) as i32,
119 );
120 let step_lat = i64::from(next.0) - i64::from(cur.0);
121 let step_lon = i64::from(next.1) - i64::from(cur.1);
122 debug_assert!(
123 step_lat.abs() <= MAX_DELTA && step_lon.abs() <= MAX_DELTA,
124 "delta ({step_lat}, {step_lon}) does not fit in i16"
125 );
126 count += 1;
127 // The last point is the edge's target, which the reader reads out of
128 // `nodes.bin`, so the delta that lands on it is not stored. Neither
129 // is the absolute first point, for the same reason.
130 if count < total {
131 out.extend_from_slice(&(step_lat as i16).to_le_bytes());
132 out.extend_from_slice(&(step_lon as i16).to_le_bytes());
133 }
134 cur = next;
135 }
136 }
137 debug_assert_eq!(cur, points[points.len() - 1], "encoder lost the final vertex");
138 debug_assert_eq!(count, total, "encoder disagreed with its own point count");
139 count as u32
140}
141
142/// Reimplementation of `graph.rs`'s `decode_edge_coords`, for tests and for the
143/// build's own verification pass. Kept deliberately literal — including the
144/// `wrapping_add` and the [`MAX_POINTS`] stop — so that a divergence between the
145/// two shows up here rather than on a phone.
146///
147/// `source` and `target` are the edge's own endpoints, which is what lets the
148/// blob hold nothing but the interior: an empty `bytes` decodes to the chord.
149pub fn decode(bytes: &[u8], source: Pt, target: Pt) -> Vec<Pt> {
150 let mut out = vec![source];
151 let (mut lat, mut lon) = source;
152 let mut off = 0usize;
153 // One slot is reserved for `target`, so the interior stops one short.
154 while off + 4 <= bytes.len() && (out.len() as u32) + 1 < MAX_POINTS {
155 let d_lat = i16::from_le_bytes([bytes[off], bytes[off + 1]]);
156 let d_lon = i16::from_le_bytes([bytes[off + 2], bytes[off + 3]]);
157 lat = lat.wrapping_add(i32::from(d_lat));
158 lon = lon.wrapping_add(i32::from(d_lon));
159 out.push((lat, lon));
160 off += 4;
161 }
162 out.push(target);
163 out
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 /// Every original vertex must survive a round trip, and the inserted points
171 /// must lie on the segment they split.
172 ///
173 /// The endpoints are handed to [`decode`] rather than read out of the blob,
174 /// exactly as the device takes them from `nodes.bin`.
175 fn round_trip(points: &[Pt]) -> Vec<Pt> {
176 let mut buf = Vec::new();
177 let n = encode(points, &mut buf);
178 let got = decode(&buf, points[0], points[points.len() - 1]);
179 assert_eq!(n as usize, got.len(), "encode count vs decode count");
180 assert_eq!(buf.len(), 4 * (got.len() - 2), "byte length");
181 // The endpoints are never interpolated away, and every original vertex
182 // appears in order.
183 let mut it = got.iter();
184 for p in points {
185 assert!(it.any(|q| q == p), "original vertex {p:?} missing from {got:?}");
186 }
187 got
188 }
189
190 #[test]
191 fn short_polyline_needs_no_interpolation() {
192 let pts = vec![(370_000_000, -1_220_000_000), (370_001_000, -1_220_002_000)];
193 let got = round_trip(&pts);
194 assert_eq!(got, pts);
195 assert_eq!(encoded_points(&pts), 2);
196 }
197
198 #[test]
199 fn a_long_gap_is_split_into_collinear_points() {
200 // 0.5 degrees of latitude is 5_000_000 e7 units, about 153 times the
201 // i16 limit — long enough to interpolate heavily, short enough to stay
202 // inside the 256-point ceiling.
203 let a = (350_000_000, -1_200_000_000);
204 let b = (355_000_000, -1_200_000_000);
205 assert_eq!(interp_steps(a, b), 153);
206 let got = round_trip(&[a, b]);
207 assert_eq!(got.len(), 154);
208 // Collinear: longitude never moves, latitude is monotonic.
209 assert!(got.iter().all(|p| p.1 == -1_200_000_000));
210 assert!(got.windows(2).all(|w| w[0].0 < w[1].0));
211 assert_eq!(*got.last().unwrap(), b);
212 }
213
214 #[test]
215 fn diagonal_interpolation_stays_on_the_line() {
216 let a = (350_000_000, -1_200_000_000);
217 let b = (350_500_000, -1_199_000_000);
218 let got = round_trip(&[a, b]);
219 // Cross product against the a->b direction must be tiny for every point
220 // (exact zero is impossible with integer rounding).
221 let (dx, dy) = (i64::from(b.0 - a.0), i64::from(b.1 - a.1));
222 for p in &got {
223 let (px, py) = (i64::from(p.0 - a.0), i64::from(p.1 - a.1));
224 let cross = (dx * py - dy * px).abs();
225 let scale = dx.abs().max(dy.abs());
226 assert!(cross <= scale * 2, "point {p:?} is off the line: cross={cross}");
227 }
228 }
229
230 #[test]
231 fn negative_deltas_round_trip() {
232 let pts = vec![
233 (400_000_000, 1_100_000_000),
234 (399_960_000, 1_099_950_000),
235 (399_800_000, 1_099_900_000),
236 ];
237 let got = round_trip(&pts);
238 assert_eq!(*got.first().unwrap(), pts[0]);
239 assert_eq!(*got.last().unwrap(), pts[2]);
240 }
241
242 #[test]
243 fn a_delta_exactly_at_the_limit_is_one_step() {
244 let a = (0, 0);
245 let b = (32_767, -32_767);
246 assert_eq!(interp_steps(a, b), 1);
247 assert_eq!(round_trip(&[a, b]), vec![a, b]);
248 // One unit further needs two.
249 assert_eq!(interp_steps(a, (32_768, 0)), 2);
250 }
251
252 #[test]
253 fn fits_rejects_what_the_reader_would_truncate() {
254 let a = (0, 0);
255 // 256 points is the reader's ceiling, so 255 interpolation steps is the
256 // most a single segment may need.
257 let ok = (255 * 32_767, 0);
258 assert_eq!(encoded_points(&[a, ok]), 256);
259 assert!(fits(&[a, ok]));
260 let too_far = (255 * 32_767 + 1, 0);
261 assert_eq!(encoded_points(&[a, too_far]), 257);
262 assert!(!fits(&[a, too_far]));
263 // Degenerate inputs are not encodable geometry.
264 assert!(!fits(&[]));
265 assert!(!fits(&[a]));
266 }
267
268 #[test]
269 fn an_empty_blob_decodes_to_the_chord() {
270 // The interior is all that is stored, so an edge with no interior stores
271 // nothing at all and the two endpoints alone are a valid polyline. This
272 // is why `intermediate.bin` needs a presence bit rather than a length
273 // test: a zero-length blob is meaningful.
274 let mut buf = Vec::new();
275 assert_eq!(encode(&[(1, 2), (3, 4)], &mut buf), 2);
276 assert!(buf.is_empty(), "a two-point polyline is pure redundancy");
277 assert_eq!(decode(&buf, (1, 2), (3, 4)), vec![(1, 2), (3, 4)]);
278 assert_eq!(decode(&[], (1, 2), (3, 4)), vec![(1, 2), (3, 4)]);
279 }
280
281 #[test]
282 fn a_trailing_partial_delta_is_ignored() {
283 // Matching the reader's `off + 4 <= byte_len` guard. A real blob is
284 // always a multiple of 4, so this only ever fires on a corrupt file.
285 let mut buf = Vec::new();
286 let _ = encode(&[(1, 2), (3, 4), (5, 7)], &mut buf);
287 assert_eq!(buf.len(), 4);
288 buf.push(0);
289 assert_eq!(decode(&buf, (1, 2), (5, 7)), vec![(1, 2), (3, 4), (5, 7)]);
290 }
291
292 #[test]
293 fn the_largest_legal_blob_is_1016_bytes() {
294 // `MAX_POINTS` points means `MAX_POINTS - 2` stored deltas, which is the
295 // bound `intermediate.bin`'s within-block u16 rests on.
296 let pts: Vec<Pt> = (0..MAX_POINTS as i32).map(|i| (i * 1_000, 0)).collect();
297 assert_eq!(encoded_points(&pts), u64::from(MAX_POINTS));
298 let mut buf = Vec::new();
299 assert_eq!(encode(&pts, &mut buf), MAX_POINTS);
300 assert_eq!(buf.len(), 4 * (MAX_POINTS as usize - 2));
301 assert_eq!(buf.len(), 1016);
302 assert_eq!(round_trip(&pts), pts);
303 }
304
305 #[test]
306 fn empty_output_for_fewer_than_two_points() {
307 let mut buf = Vec::new();
308 assert_eq!(encode(&[], &mut buf), 0);
309 assert_eq!(encode(&[(1, 1)], &mut buf), 0);
310 assert!(buf.is_empty());
311 }
312}