Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / graph_build_part5.rs
graph_build_part5.rs210 lines · 8.0 KiBRaw
| 1 | /// `lanes.bin`, as a sparse index: `[ u32 n ][ (u32 edge_idx, u32 off) x (n + 1) ]` |
| 2 | /// then the `u16` mask blob. |
| 3 | /// |
| 4 | /// `turn:lanes` is rare — 2.9 M of a planet's 1.07 G directed edges carry any — so |
| 5 | /// a dense `u64` per edge made 99.8% of an 8.60 GB file describe edges with no |
| 6 | /// lanes. Listing only the edges that have them is ~23 MB of index plus a 13 MB |
| 7 | /// blob. Entry *i*'s masks run from its offset to entry *i+1*'s, so the trailing |
| 8 | /// sentinel gives the last edge its length and the blob its total. |
| 9 | /// |
| 10 | /// The round-partitioned writer cannot know `n` up front, so the blob streams to a |
| 11 | /// scratch file while the index accumulates in memory (23 MB at planet scale) and |
| 12 | /// the header plus index are written in front of it at the end. |
| 13 | struct LaneFile { |
| 14 | path: PathBuf, |
| 15 | blob_path: PathBuf, |
| 16 | blob: BufWriter<File>, |
| 17 | index: Vec<(u32, u32)>, |
| 18 | blob_len: u64, |
| 19 | } |
| 20 | |
| 21 | impl LaneFile { |
| 22 | fn create(dir: &Path, name: &str) -> Result<LaneFile> { |
| 23 | let blob_path = dir.join(format!("{name}.blob")); |
| 24 | Ok(LaneFile { |
| 25 | path: dir.join(name), |
| 26 | blob: BufWriter::new(create(&blob_path)?), |
| 27 | blob_path, |
| 28 | index: Vec::new(), |
| 29 | blob_len: 0, |
| 30 | }) |
| 31 | } |
| 32 | |
| 33 | /// Record `bytes` as edge `idx`'s masks. Only called for edges that have any, |
| 34 | /// and always with an ascending `idx`, because the rounds ascend and each round |
| 35 | /// writes its edges in index order. |
| 36 | fn push(&mut self, idx: u64, bytes: &[u8]) -> Result<()> { |
| 37 | debug_assert!(!bytes.is_empty(), "an empty lane blob would read back as absent"); |
| 38 | debug_assert!( |
| 39 | self.index.last().is_none_or(|(last, _)| *last < idx as u32), |
| 40 | "lane index entries must ascend by edge index" |
| 41 | ); |
| 42 | let off = self.blob_off()?; |
| 43 | self.index.push((idx as u32, off)); |
| 44 | self.blob.write_all(bytes).map_err(io_err)?; |
| 45 | self.blob_len += bytes.len() as u64; |
| 46 | Ok(()) |
| 47 | } |
| 48 | |
| 49 | /// The current blob length as the `u32` an index entry stores. |
| 50 | fn blob_off(&self) -> Result<u32> { |
| 51 | u32::try_from(self.blob_len).map_err(|_| { |
| 52 | Error(format!( |
| 53 | "the lane blob reached {} bytes, past the {} a u32 offset can address", |
| 54 | self.blob_len, |
| 55 | u32::MAX |
| 56 | )) |
| 57 | }) |
| 58 | } |
| 59 | |
| 60 | /// Write the header and index, then the blob behind it. Returns the finished |
| 61 | /// file's size. |
| 62 | fn finish(mut self) -> Result<u64> { |
| 63 | self.blob.flush().map_err(io_err)?; |
| 64 | let n = u32::try_from(self.index.len()).map_err(|_| { |
| 65 | Error(format!( |
| 66 | "{} lane-bearing edge(s) is past the {} the index header can count", |
| 67 | self.index.len(), |
| 68 | u32::MAX |
| 69 | )) |
| 70 | })?; |
| 71 | let mut out = BufWriter::new(create(&self.path)?); |
| 72 | out.write_all(&n.to_le_bytes()).map_err(io_err)?; |
| 73 | for (idx, off) in &self.index { |
| 74 | out.write_all(&idx.to_le_bytes()).map_err(io_err)?; |
| 75 | out.write_all(&off.to_le_bytes()).map_err(io_err)?; |
| 76 | } |
| 77 | // The sentinel's edge index is `u32::MAX` rather than a real one: it exists |
| 78 | // only to give the last entry a length, and the reader's binary search |
| 79 | // covers the first `n` entries, so no valid index may collide with it. Its |
| 80 | // offset is the blob length, which is also how the reader length-validates |
| 81 | // the blob. |
| 82 | let blob_end = self.blob_off()?; |
| 83 | out.write_all(&u32::MAX.to_le_bytes()).map_err(io_err)?; |
| 84 | out.write_all(&blob_end.to_le_bytes()).map_err(io_err)?; |
| 85 | |
| 86 | let mut src = BufReader::with_capacity(1 << 20, open(&self.blob_path)?); |
| 87 | std::io::copy(&mut src, &mut out).map_err(io_err)?; |
| 88 | out.flush().map_err(io_err)?; |
| 89 | Ok(4 + u64::from(n + 1) * 8 + self.blob_len) |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | impl Drop for LaneFile { |
| 94 | fn drop(&mut self) { |
| 95 | let _ = std::fs::remove_file(&self.blob_path); |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | /// `nodes.bin` is 12 bytes a record: `edge_ptr` is a `u32`, which planet's 1.07 G |
| 100 | /// directed edges leave 4x of headroom in. [`cap_u32`] on the edge count is what |
| 101 | /// keeps that safe — a wrapped `edge_ptr` would address a real but wrong node's |
| 102 | /// edge range. |
| 103 | fn write_node<W: Write>( |
| 104 | out: &mut W, |
| 105 | lat_e7: i32, |
| 106 | lon_e7: i32, |
| 107 | edge_ptr: u32, |
| 108 | ) -> std::io::Result<()> { |
| 109 | out.write_all(&lat_e7.to_le_bytes())?; |
| 110 | out.write_all(&lon_e7.to_le_bytes())?; |
| 111 | out.write_all(&edge_ptr.to_le_bytes()) |
| 112 | } |
| 113 | |
| 114 | fn create(path: &Path) -> Result<File> { |
| 115 | File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display()))) |
| 116 | } |
| 117 | |
| 118 | fn open(path: &Path) -> Result<File> { |
| 119 | File::open(path).map_err(|e| Error(format!("cannot read {}: {e}", path.display()))) |
| 120 | } |
| 121 | |
| 122 | fn io_err(e: std::io::Error) -> Error { |
| 123 | Error(e.to_string()) |
| 124 | } |
| 125 | |
| 126 | /// Parse the tool's command line: |
| 127 | /// `road_graph IN.osm.pbf [--out DIR] [--reference-collapse] [--rounds N] |
| 128 | /// [--spill-dir DIR] [--spill-pts-dir DIR] [--dem DATASET.mdem] [--region california|world] [--stats]`. |
| 129 | pub fn parse_args( |
| 130 | args: &[String], |
| 131 | ) -> std::result::Result<(PathBuf, PathBuf, Options), String> { |
| 132 | let mut input: Option<PathBuf> = None; |
| 133 | let mut out = PathBuf::from("map_data"); |
| 134 | let mut opts = Options::default(); |
| 135 | // The CLI defaults to the streaming within-way collapse: it is the only path |
| 136 | // whose working set fits a planet build on a commodity box. The reference |
| 137 | // whole-graph collapse stays reachable for cross-checking via |
| 138 | // --reference-collapse. The library default (`Options::default`) is unchanged. |
| 139 | opts.within_way_chains = true; |
| 140 | let mut i = 0; |
| 141 | while i < args.len() { |
| 142 | match args[i].as_str() { |
| 143 | "--out" | "-o" => { |
| 144 | i += 1; |
| 145 | let dir = args.get(i).ok_or_else(|| "--out needs a directory".to_string())?; |
| 146 | out = PathBuf::from(dir); |
| 147 | } |
| 148 | "--reference-collapse" => opts.within_way_chains = false, |
| 149 | "--stats" => opts.stats = true, |
| 150 | "--threads" => { |
| 151 | i += 1; |
| 152 | let n = args |
| 153 | .get(i) |
| 154 | .ok_or_else(|| "--threads needs a count".to_string())?; |
| 155 | opts.threads = Some(crate::par::parse_threads(n)?); |
| 156 | } |
| 157 | "--spill-dir" => { |
| 158 | i += 1; |
| 159 | let dir = args |
| 160 | .get(i) |
| 161 | .ok_or_else(|| "--spill-dir needs a directory".to_string())?; |
| 162 | opts.spill_dir = Some(PathBuf::from(dir)); |
| 163 | } |
| 164 | "--spill-pts-dir" => { |
| 165 | i += 1; |
| 166 | let dir = args |
| 167 | .get(i) |
| 168 | .ok_or_else(|| "--spill-pts-dir needs a directory".to_string())?; |
| 169 | opts.spill_pts_dir = Some(PathBuf::from(dir)); |
| 170 | } |
| 171 | "--rounds" => { |
| 172 | i += 1; |
| 173 | let n = args.get(i).ok_or_else(|| "--rounds needs a count".to_string())?; |
| 174 | opts.rounds = n |
| 175 | .parse::<u32>() |
| 176 | .ok() |
| 177 | .filter(|n| *n > 0) |
| 178 | .ok_or_else(|| format!("--rounds wants a positive count, not {n}"))?; |
| 179 | } |
| 180 | "--dem" => { |
| 181 | i += 1; |
| 182 | let path = args |
| 183 | .get(i) |
| 184 | .ok_or_else(|| "--dem needs a .mdem dataset path".to_string())?; |
| 185 | opts.dem = Some(PathBuf::from(path)); |
| 186 | } |
| 187 | "--region" => { |
| 188 | i += 1; |
| 189 | let value = args |
| 190 | .get(i) |
| 191 | .ok_or_else(|| "--region needs `california`, `na` or `world`".to_string())?; |
| 192 | let region = crate::region::Region::parse(value).map_err(|e| e.0)?; |
| 193 | opts.bbox = region.bbox(); |
| 194 | } |
| 195 | a if a.starts_with('-') => return Err(format!("unknown option: {a}")), |
| 196 | a => { |
| 197 | if input.is_some() { |
| 198 | return Err(format!("unexpected extra argument: {a}")); |
| 199 | } |
| 200 | input = Some(PathBuf::from(a)); |
| 201 | } |
| 202 | } |
| 203 | i += 1; |
| 204 | } |
| 205 | Ok(( |
| 206 | input.ok_or_else(|| "missing IN.osm.pbf".to_string())?, |
| 207 | out, |
| 208 | opts, |
| 209 | )) |
| 210 | } |