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

Modern-Apps.git / scripts / maps / mamaps_build / src / shapefile.rs

shapefile.rs416 lines · 17.2 KiBRaw
1//! A streaming reader for the one shapefile this project reads.
2//!
3//! # Why write this rather than shell out
4//!
5//! The OSMCoastline land polygons ship as an ESRI shapefile, and converting one normally means GDAL.
6//! This repository has spent its whole life removing that class of dependency — osmium, tippecanoe
7//! and Planetiler are all gone — and a polygon shapefile is a genuinely simple binary format: a
8//! 100-byte header, then length-prefixed records of `f64` pairs. Reading it directly is about a
9//! hundred lines, needs no toolchain, and streams, which matters when the file is 1.26 GB and the
10//! whole point of the change it serves is to stop holding geometry in memory.
11//!
12//! Only what is needed is implemented: shape type 5, `Polygon`. A `PolygonZ` or a `PolyLine` in this
13//! file would mean the wrong artefact was handed over, so those are refused rather than coerced.
14//!
15//! # Ring orientation is the opposite of GeoJSON's
16//!
17//! The ESRI specification orders an outer ring **clockwise** and a hole counter-clockwise — the
18//! reverse of GeoJSON and of this pipeline. That does not matter for winding, because stage C
19//! normalises it. It matters for **grouping**: a record holds a flat list of rings, and knowing which
20//! are exteriors is the only way to tell one island with a lake from two separate islands.
21
22use std::fs::File;
23use std::io::{BufReader, Read};
24use std::path::Path;
25
26use osm_ingest::proto::{err, Error, Result};
27
28/// One record's rings as `(ring, is_exterior)` pairs.
29pub type PolygonRings = Vec<(Vec<(f64, f64)>, bool)>;
30
31/// `.shp` files start with this, big-endian.
32const FILE_CODE: u32 = 9994;
33const HEADER_BYTES: usize = 100;
34const SHAPE_NULL: u32 = 0;
35const SHAPE_POLYGON: u32 = 5;
36
37/// A ring count no real land polygon comes close to, as a guard against a corrupt length driving a
38/// huge allocation.
39const MAX_PARTS: u32 = 1 << 20;
40/// Likewise for points. The largest single land polygon in the *unsplit* product is a few million.
41const MAX_POINTS: u32 = 1 << 26;
42
43/// Streams `Polygon` records out of a `.shp`.
44pub struct ShapeReader {
45 input: BufReader<File>,
46 /// Bytes of records left to read, from the header's file length.
47 remaining: u64,
48 buf: Vec<u8>,
49 /// Only records whose own bounding box meets this one are parsed.
50 ///
51 /// **Not an optimisation — a correctness requirement.** The land polygon product covers the whole
52 /// planet: 825 k polygons, of which a California build wants a few hundred. Without this, a
53 /// regional build tiles every coastline on Earth, which takes hours and produces an archive whose
54 /// bounding box is the globe.
55 filter: Option<(f64, f64, f64, f64)>,
56 /// How many records were skipped by the filter, for the build report.
57 pub skipped: u64,
58}
59
60impl ShapeReader {
61 pub fn open(path: &Path) -> Result<ShapeReader> {
62 let file =
63 File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;
64 let mut input = BufReader::with_capacity(1 << 20, file);
65 let mut header = [0u8; HEADER_BYTES];
66 input.read_exact(&mut header).map_err(|e| {
67 Error(format!("{} is too short to be a shapefile: {e}", path.display()))
68 })?;
69
70 if be32(&header[0..4]) != FILE_CODE {
71 return err(format!("{} is not a shapefile", path.display()));
72 }
73 // The header states the file length in 16-bit words, including the header itself.
74 let words = be32(&header[24..28]) as u64;
75 let total = words * 2;
76 if total < HEADER_BYTES as u64 {
77 return err(format!("{} declares an impossible length", path.display()));
78 }
79 let shape_type = le32(&header[32..36]);
80 if shape_type != SHAPE_POLYGON {
81 return err(format!(
82 "{} holds shape type {shape_type}, and only 5 (Polygon) is read; this is not the \
83 land polygon product",
84 path.display(),
85 ));
86 }
87 Ok(ShapeReader {
88 input,
89 remaining: total - HEADER_BYTES as u64,
90 buf: Vec::new(),
91 filter: None,
92 skipped: 0,
93 })
94 }
95
96 /// Keep only records meeting `(min_lon, min_lat, max_lon, max_lat)`, in degrees.
97 pub fn clip_to(&mut self, bbox: (f64, f64, f64, f64)) {
98 self.filter = Some(bbox);
99 }
100
101 /// How many records the header declares, for progress sizing: the file
102 /// length in words minus the header, over the 8-byte record header plus
103 /// the smallest a `Polygon` body can be. An underestimate when records
104 /// run large, which a progress bar tolerates (it clamps at 100%) — and
105 /// exact for sizing, never for logic.
106 pub fn records(&self) -> usize {
107 const MIN_RECORD_BYTES: u64 = 8 + 44;
108 (self.remaining / MIN_RECORD_BYTES) as usize
109 }
110
111 /// The next record's rings, or `None` at the end of the file.
112 ///
113 /// Rings come back as `(ring, is_exterior)` in file order, so the caller can group them without
114 /// re-deriving orientation.
115 pub fn next(&mut self) -> Result<Option<PolygonRings>> {
116 // A record header is 8 bytes; anything less than that left is the end.
117 if self.remaining < 8 {
118 return Ok(None);
119 }
120 let mut record_header = [0u8; 8];
121 self.input
122 .read_exact(&mut record_header)
123 .map_err(|e| Error(format!("reading a record header: {e}")))?;
124 // Content length is in 16-bit words, as everywhere else in this format.
125 let content_len = be32(&record_header[4..8]) as u64 * 2;
126 self.remaining -= 8;
127 if content_len > self.remaining {
128 return err("a record claims more content than the file has left".to_string());
129 }
130 self.remaining -= content_len;
131
132 self.buf.clear();
133 self.buf.resize(content_len as usize, 0);
134 self.input
135 .read_exact(&mut self.buf)
136 .map_err(|e| Error(format!("reading a record body: {e}")))?;
137
138 // Every Polygon record carries its own bounding box at bytes 4..36, so a record outside the
139 // build's area is rejected for the cost of four `f64` comparisons rather than by decoding
140 // however many thousand points it holds.
141 if let Some(want) = self.filter {
142 if self.buf.len() >= 36 && le32(&self.buf[0..4]) == SHAPE_POLYGON {
143 let (min_x, min_y) = (le64(&self.buf[4..12]), le64(&self.buf[12..20]));
144 let (max_x, max_y) = (le64(&self.buf[20..28]), le64(&self.buf[28..36]));
145 // Intersection, not containment: a polygon straddling the extract's edge is land
146 // inside it and has to be kept.
147 let misses = max_x < want.0 || min_x > want.2 || max_y < want.1 || min_y > want.3;
148 if misses {
149 self.skipped += 1;
150 return Ok(Some(Vec::new()));
151 }
152 }
153 }
154 parse_polygon(&self.buf)
155 }
156}
157
158/// One record's rings.
159fn parse_polygon(body: &[u8]) -> Result<Option<PolygonRings>> {
160 if body.len() < 4 {
161 return err("a record is too short to name its shape type".to_string());
162 }
163 match le32(&body[0..4]) {
164 // A null shape is legal and means "no geometry here". Skipped, not an error.
165 SHAPE_NULL => return Ok(Some(Vec::new())),
166 SHAPE_POLYGON => {}
167 other => return err(format!("record shape type {other} is not a Polygon")),
168 }
169 // 4..36 is the record's own bounding box, which is redundant with the points.
170 if body.len() < 44 {
171 return err("a Polygon record is too short to hold its counts".to_string());
172 }
173 let part_count = le32(&body[36..40]);
174 let point_count = le32(&body[40..44]);
175 if part_count > MAX_PARTS || point_count > MAX_POINTS {
176 return err(format!("a record claims {part_count} part(s) and {point_count} point(s)"));
177 }
178 let parts_at = 44usize;
179 let points_at = parts_at + part_count as usize * 4;
180 let needed = points_at + point_count as usize * 16;
181 if body.len() < needed {
182 return err(format!("a Polygon record is {} bytes short", needed - body.len()));
183 }
184
185 // Each part is the index of its first point; the last runs to the end.
186 let mut starts: Vec<usize> = Vec::with_capacity(part_count as usize);
187 for i in 0..part_count as usize {
188 starts.push(le32(&body[parts_at + i * 4..parts_at + i * 4 + 4]) as usize);
189 }
190 let point = |i: usize| -> (f64, f64) {
191 let at = points_at + i * 16;
192 (le64(&body[at..at + 8]), le64(&body[at + 8..at + 16]))
193 };
194
195 let mut rings = Vec::with_capacity(starts.len());
196 for (i, &start) in starts.iter().enumerate() {
197 let end = starts.get(i + 1).copied().unwrap_or(point_count as usize);
198 if start >= end || end > point_count as usize {
199 return err("a part's range is not inside the record's points".to_string());
200 }
201 let ring: Vec<(f64, f64)> = (start..end).map(point).collect();
202 // Clockwise is an exterior in this format, which is a negative shoelace area with y up.
203 let exterior = signed_area(&ring) < 0.0;
204 rings.push((ring, exterior));
205 }
206 Ok(Some(rings))
207}
208
209/// A ring's signed area in degrees squared. Only its sign is used.
210fn signed_area(ring: &[(f64, f64)]) -> f64 {
211 let mut twice = 0.0;
212 for pair in ring.windows(2) {
213 twice += pair[0].0 * pair[1].1 - pair[1].0 * pair[0].1;
214 }
215 if let (Some(first), Some(last)) = (ring.first(), ring.last()) {
216 if first != last {
217 twice += last.0 * first.1 - first.0 * last.1;
218 }
219 }
220 twice / 2.0
221}
222
223/// Group a record's rings into polygons: each exterior starts one, and the holes that follow are
224/// its.
225///
226/// A file whose first ring is a hole is malformed; those holes have nothing to belong to and are
227/// dropped rather than promoted, because promoting one would paint a lake as land.
228pub fn group(rings: Vec<(Vec<(f64, f64)>, bool)>) -> Vec<Vec<Vec<(f64, f64)>>> {
229 let mut out: Vec<Vec<Vec<(f64, f64)>>> = Vec::new();
230 for (ring, exterior) in rings {
231 // Three distinct points plus a closing one; less bounds no area.
232 if ring.len() < 4 {
233 continue;
234 }
235 if exterior || out.is_empty() {
236 out.push(vec![ring]);
237 } else {
238 out.last_mut().expect("non-empty").push(ring);
239 }
240 }
241 out
242}
243
244fn be32(bytes: &[u8]) -> u32 {
245 u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
246}
247
248fn le32(bytes: &[u8]) -> u32 {
249 u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
250}
251
252fn le64(bytes: &[u8]) -> f64 {
253 f64::from_le_bytes([
254 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
255 ])
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 /// Build a one-record shapefile in memory, so the reader is tested against bytes rather than
263 /// against a 1.26 GB download.
264 fn shapefile(rings: &[Vec<(f64, f64)>]) -> Vec<u8> {
265 let point_count: usize = rings.iter().map(|r| r.len()).sum();
266 let mut content = Vec::new();
267 content.extend_from_slice(&SHAPE_POLYGON.to_le_bytes());
268 for _ in 0..4 {
269 content.extend_from_slice(&0f64.to_le_bytes());
270 }
271 content.extend_from_slice(&(rings.len() as u32).to_le_bytes());
272 content.extend_from_slice(&(point_count as u32).to_le_bytes());
273 let mut at = 0u32;
274 for ring in rings {
275 content.extend_from_slice(&at.to_le_bytes());
276 at += ring.len() as u32;
277 }
278 for ring in rings {
279 for &(x, y) in ring {
280 content.extend_from_slice(&x.to_le_bytes());
281 content.extend_from_slice(&y.to_le_bytes());
282 }
283 }
284
285 let mut out = vec![0u8; HEADER_BYTES];
286 out[0..4].copy_from_slice(&FILE_CODE.to_be_bytes());
287 out[32..36].copy_from_slice(&SHAPE_POLYGON.to_le_bytes());
288 out.extend_from_slice(&1u32.to_be_bytes());
289 out.extend_from_slice(&((content.len() / 2) as u32).to_be_bytes());
290 out.extend_from_slice(&content);
291 let words = (out.len() / 2) as u32;
292 out[24..28].copy_from_slice(&words.to_be_bytes());
293 out
294 }
295
296 fn write_temp(name: &str, bytes: &[u8]) -> std::path::PathBuf {
297 let path =
298 std::env::temp_dir().join(format!("mamaps_shp_{}_{name}.shp", std::process::id()));
299 std::fs::write(&path, bytes).expect("write");
300 path
301 }
302
303 /// Clockwise in a y-up system, which the ESRI spec calls an exterior.
304 fn clockwise() -> Vec<(f64, f64)> {
305 vec![(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)]
306 }
307
308 fn counter_clockwise() -> Vec<(f64, f64)> {
309 let mut ring = clockwise();
310 ring.reverse();
311 ring
312 }
313
314 #[test]
315 fn a_single_polygon_reads_back_with_its_points() {
316 let path = write_temp("single", &shapefile(&[clockwise()]));
317 let mut reader = ShapeReader::open(&path).expect("open");
318 let rings = reader.next().expect("read").expect("a record");
319 assert_eq!(rings.len(), 1);
320 assert!(rings[0].1, "a clockwise ring is an exterior in this format");
321 assert_eq!(rings[0].0, clockwise());
322 assert!(reader.next().expect("read").is_none(), "and then the end");
323 let _ = std::fs::remove_file(&path);
324 }
325
326 /// **The reason orientation is read at all.** One island with a lake and two separate islands
327 /// have the same ring count and the same points; only the winding tells them apart.
328 #[test]
329 fn orientation_groups_rings_into_the_right_polygons() {
330 // Exterior, hole, exterior -> two polygons, the first with a hole.
331 let rings = vec![clockwise(), counter_clockwise(), clockwise()];
332 let path = write_temp("grouped", &shapefile(&rings));
333 let mut reader = ShapeReader::open(&path).expect("open");
334 let polygons = group(reader.next().expect("read").expect("a record"));
335 assert_eq!(polygons.len(), 2, "two islands");
336 assert_eq!(polygons[0].len(), 2, "the first has a lake");
337 assert_eq!(polygons[1].len(), 1, "the second does not");
338 let _ = std::fs::remove_file(&path);
339
340 // Two exteriors and no holes -> two separate polygons, not one with a hole.
341 let path = write_temp("two", &shapefile(&[clockwise(), clockwise()]));
342 let mut reader = ShapeReader::open(&path).expect("open");
343 let polygons = group(reader.next().expect("read").expect("a record"));
344 assert_eq!(polygons.len(), 2);
345 assert!(polygons.iter().all(|p| p.len() == 1));
346 let _ = std::fs::remove_file(&path);
347 }
348
349 #[test]
350 fn a_degenerate_ring_is_dropped_and_a_leading_hole_does_not_become_land() {
351 // A two-point ring bounds nothing.
352 let rings = vec![(vec![(0.0, 0.0), (1.0, 1.0)], true)];
353 assert!(group(rings).is_empty(), "a degenerate ring");
354
355 // A record whose first ring is a hole is malformed. It must not be promoted to land, which
356 // would paint a lake solid.
357 let rings = vec![(counter_clockwise(), false), (clockwise(), true)];
358 let polygons = group(rings);
359 assert_eq!(
360 polygons.len(),
361 2,
362 "the stray hole stands alone rather than swallowing the land"
363 );
364 }
365
366 #[test]
367 fn the_wrong_file_is_refused_rather_than_misread() {
368 // Not a shapefile at all.
369 let path = write_temp("garbage", b"this is not a shapefile, it is a sentence");
370 assert!(ShapeReader::open(&path).is_err());
371 let _ = std::fs::remove_file(&path);
372
373 // A shapefile of the wrong shape type, which means the wrong artefact was downloaded.
374 let mut bytes = shapefile(&[clockwise()]);
375 bytes[32..36].copy_from_slice(&3u32.to_le_bytes()); // PolyLine
376 let path = write_temp("polyline", &bytes);
377 let failure = match ShapeReader::open(&path) {
378 Ok(_) => panic!("a PolyLine shapefile should be refused"),
379 Err(e) => e,
380 };
381 assert!(failure.0.contains("land polygon product"), "{}", failure.0);
382 let _ = std::fs::remove_file(&path);
383 }
384
385 #[test]
386 fn a_truncated_record_is_an_error_rather_than_a_silent_stop() {
387 let mut bytes = shapefile(&[clockwise()]);
388 bytes.truncate(bytes.len() - 40);
389 let path = write_temp("truncated", &bytes);
390 let mut reader = ShapeReader::open(&path).expect("open");
391 assert!(
392 reader.next().is_err(),
393 "a half-read polygon must not look like the end of the file"
394 );
395 let _ = std::fs::remove_file(&path);
396 }
397
398 #[test]
399 fn a_null_shape_is_skipped_rather_than_failing_the_build() {
400 let mut content = Vec::new();
401 content.extend_from_slice(&SHAPE_NULL.to_le_bytes());
402 let mut bytes = vec![0u8; HEADER_BYTES];
403 bytes[0..4].copy_from_slice(&FILE_CODE.to_be_bytes());
404 bytes[32..36].copy_from_slice(&SHAPE_POLYGON.to_le_bytes());
405 bytes.extend_from_slice(&1u32.to_be_bytes());
406 bytes.extend_from_slice(&((content.len() / 2) as u32).to_be_bytes());
407 bytes.extend_from_slice(&content);
408 let words = (bytes.len() / 2) as u32;
409 bytes[24..28].copy_from_slice(&words.to_be_bytes());
410
411 let path = write_temp("null", &bytes);
412 let mut reader = ShapeReader::open(&path).expect("open");
413 assert_eq!(reader.next().expect("read").expect("a record").len(), 0);
414 let _ = std::fs::remove_file(&path);
415 }
416}