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

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

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