Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / lanefill_s1.rs
lanefill_s1.rs302 lines · 12.7 KiBRaw
| 1 | impl Collector { |
| 2 | /// Open the partition files. `stem` is a scratch path; each partition appends to it. |
| 3 | pub fn create(stem: &Path) -> Result<Collector> { |
| 4 | let mut files = Vec::with_capacity(PARTITIONS); |
| 5 | let mut paths = Vec::with_capacity(PARTITIONS); |
| 6 | for i in 0..PARTITIONS { |
| 7 | let path = stem.with_extension(format!("lanefill{i:03}.tmp")); |
| 8 | // Read and write on one handle, so `finish` reads the partition back through it and |
| 9 | // the name can be unlinked straight away: a build killed mid-scan leaves nothing. |
| 10 | let file = std::fs::OpenOptions::new() |
| 11 | .read(true) |
| 12 | .write(true) |
| 13 | .create(true) |
| 14 | .truncate(true) |
| 15 | .open(&path) |
| 16 | .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; |
| 17 | // Small buffers: there are `PARTITIONS` of them held open at once, and each takes a |
| 18 | // steady trickle rather than a burst. |
| 19 | files.push(BufWriter::with_capacity(1 << 14, file)); |
| 20 | paths.push(path); |
| 21 | } |
| 22 | let mut unlinked = true; |
| 23 | for path in &paths { |
| 24 | unlinked &= osm_ingest::mem::unlink_open_scratch(path); |
| 25 | } |
| 26 | Ok(Collector { files, paths, unlinked }) |
| 27 | } |
| 28 | |
| 29 | /// Offer one way to the join. Ways that cannot take part are dropped here. |
| 30 | #[cfg_attr(not(test), allow(dead_code))] |
| 31 | pub fn push(&mut self, segment: &Segment) -> Result<()> { |
| 32 | match prepare(segment) { |
| 33 | Some(prepared) => self.push_prepared(&prepared), |
| 34 | None => Ok(()), |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /// Write the two endpoint records [`prepare`] built, in the order `push` always wrote them |
| 39 | /// (first end, then last end). Split from `push` so the geometry -- length, bearings, name |
| 40 | /// hash -- runs on the pool and only these two fixed-width writes stay serial. |
| 41 | pub fn push_prepared(&mut self, prepared: &Prepared) -> Result<()> { |
| 42 | for record in prepared.0 { |
| 43 | record.write(&mut self.files[partition_of(record.node)])?; |
| 44 | } |
| 45 | Ok(()) |
| 46 | } |
| 47 | |
| 48 | /// Resolve every partition and return `(way id, inherited lane count)` for the ways that |
| 49 | /// actually change, ascending by way id so the materialise pass can binary-search it. |
| 50 | /// |
| 51 | /// Ways whose inherited count equals the default they would have had anyway are left out, the |
| 52 | /// same way [`crate::corridor::promote`] leaves out ways its corridor does not move. |
| 53 | pub fn finish(mut self) -> Result<Vec<(i64, u8)>> { |
| 54 | let mut files: Vec<File> = Vec::with_capacity(self.files.len()); |
| 55 | for file in std::mem::take(&mut self.files) { |
| 56 | files.push( |
| 57 | file.into_inner() |
| 58 | .map_err(|e| Error(format!("cannot flush a lanefill partition: {e}")))?, |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | // `(way, end, donor lanes, one-way)`. The only state that outlives a partition, because a |
| 63 | // way's two endpoints hash to two different files and the "donor at both ends" condition |
| 64 | // cannot be decided until both have been seen. |
| 65 | // |
| 66 | // The 256 partitions are independent — every record for a node lives in exactly the one |
| 67 | // partition `partition_of` sends it to — so each is read, sorted and paired on its own |
| 68 | // thread and the per-partition pairs concatenated. `found` is globally sorted below, so the |
| 69 | // concatenation order never reaches the output: the resolution stays independent of both |
| 70 | // the write order and the partition order. |
| 71 | let per_partition: Vec<Vec<(i64, u8, u8, bool)>> = par::install(|| { |
| 72 | files |
| 73 | .par_iter_mut() |
| 74 | .zip(self.paths.par_iter()) |
| 75 | .map(|(file, path)| -> Result<Vec<(i64, u8, u8, bool)>> { |
| 76 | let mut records: Vec<Record> = Vec::new(); |
| 77 | read_partition(file, path, &mut records)?; |
| 78 | let mut local: Vec<(i64, u8, u8, bool)> = Vec::new(); |
| 79 | if !records.is_empty() { |
| 80 | // Sorted rather than hashed, for the reason `corridor::promote` gives: a |
| 81 | // hash map over the record count is the largest thing this pass would |
| 82 | // otherwise allocate. The full key makes the order total, so the output |
| 83 | // does not depend on the write order. |
| 84 | records.sort_unstable_by_key(|r| (r.node, r.way, r.flags)); |
| 85 | for run in records.chunk_by(|a, b| a.node == b.node) { |
| 86 | pair_up(run, &mut local); |
| 87 | } |
| 88 | } |
| 89 | Ok(local) |
| 90 | }) |
| 91 | .collect::<Result<Vec<_>>>() |
| 92 | })?; |
| 93 | let mut found: Vec<(i64, u8, u8, bool)> = per_partition.into_iter().flatten().collect(); |
| 94 | drop(files); |
| 95 | if !self.unlinked { |
| 96 | for path in &self.paths { |
| 97 | let _ = std::fs::remove_file(path); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | found.sort_unstable(); |
| 102 | let mut out: Vec<(i64, u8)> = Vec::new(); |
| 103 | for run in found.chunk_by(|a, b| a.0 == b.0) { |
| 104 | if !run.iter().any(|e| e.1 == 0) || !run.iter().any(|e| e.1 == 1) { |
| 105 | continue; |
| 106 | } |
| 107 | let inherited = run.iter().map(|e| e.2).min().unwrap_or(0); |
| 108 | // What the renderer would have drawn without us: `tile/geometry.rs` turns a zero lane |
| 109 | // count into one lane for a one-way and two for anything else. |
| 110 | let default = if run[0].3 { 1 } else { 2 }; |
| 111 | if inherited != default { |
| 112 | out.push((run[0].0, inherited)); |
| 113 | } |
| 114 | } |
| 115 | Ok(out) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | impl Drop for Collector { |
| 120 | /// Only where the names could not be unlinked at creation: a collector dropped on an error |
| 121 | /// path must not leave its partitions behind. |
| 122 | fn drop(&mut self) { |
| 123 | if !self.unlinked { |
| 124 | self.files.clear(); |
| 125 | for path in &self.paths { |
| 126 | let _ = std::fs::remove_file(path); |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// Every recipient in `run` against every donor, appending the pairs that survive the conditions. |
| 133 | fn pair_up(run: &[Record], found: &mut Vec<(i64, u8, u8, bool)>) { |
| 134 | for recipient in run.iter().filter(|r| r.lanes == 0) { |
| 135 | for donor in run.iter().filter(|d| d.lanes > 0) { |
| 136 | if donor.way == recipient.way |
| 137 | || donor.name_hash != recipient.name_hash |
| 138 | || donor.oneway() != recipient.oneway() |
| 139 | { |
| 140 | continue; |
| 141 | } |
| 142 | if deviation(f64::from(recipient.bearing), f64::from(donor.bearing)) > MAX_TURN_DEGREES |
| 143 | { |
| 144 | continue; |
| 145 | } |
| 146 | found.push((recipient.way, recipient.end(), donor.lanes, recipient.oneway())); |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | fn read_partition(file: &mut File, path: &Path, out: &mut Vec<Record>) -> Result<()> { |
| 152 | out.clear(); |
| 153 | std::io::Seek::rewind(file) |
| 154 | .map_err(|e| Error(format!("cannot rewind {}: {e}", path.display())))?; |
| 155 | let mut bytes = Vec::new(); |
| 156 | file.read_to_end(&mut bytes) |
| 157 | .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?; |
| 158 | if bytes.len() % RECORD_LEN != 0 { |
| 159 | return err(format!( |
| 160 | "{} holds {} bytes, which is not a whole number of {RECORD_LEN}-byte records", |
| 161 | path.display(), |
| 162 | bytes.len(), |
| 163 | )); |
| 164 | } |
| 165 | out.reserve(bytes.len() / RECORD_LEN); |
| 166 | for chunk in bytes.chunks_exact(RECORD_LEN) { |
| 167 | out.push(Record::read(chunk)); |
| 168 | } |
| 169 | Ok(()) |
| 170 | } |
| 171 | |
| 172 | /// Which partition an endpoint node belongs to. |
| 173 | /// |
| 174 | /// Mixed rather than taken modulo directly: OSM node ids are allocated in runs, so the low bits of |
| 175 | /// neighbouring ids are correlated and a plain modulo would fill a few partitions and starve the |
| 176 | /// rest. This is the SplitMix64 finaliser, which is cheap and spreads the low bits. |
| 177 | fn partition_of(node: i64) -> usize { |
| 178 | let mut z = (node as u64) ^ 0x9e37_79b9_7f4a_7c15; |
| 179 | z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); |
| 180 | z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); |
| 181 | ((z ^ (z >> 31)) % PARTITIONS as u64) as usize |
| 182 | } |
| 183 | |
| 184 | /// FNV-1a over the name's bytes. See the module docs on why a collision is survivable. |
| 185 | fn hash_name(name: &str) -> u64 { |
| 186 | let mut hash: u64 = 0xcbf2_9ce4_8422_2325; |
| 187 | for byte in name.as_bytes() { |
| 188 | hash ^= u64::from(*byte); |
| 189 | hash = hash.wrapping_mul(0x0000_0100_0000_01b3); |
| 190 | } |
| 191 | hash |
| 192 | } |
| 193 | |
| 194 | /// The bearing leaving the line's first (or last) point, walking past repeated coordinates. |
| 195 | /// |
| 196 | /// `None` when every point is the same place, which has no direction to report. |
| 197 | fn leaving(line: &[(f64, f64)], from_start: bool) -> Option<f64> { |
| 198 | if from_start { |
| 199 | let origin = *line.first()?; |
| 200 | Some(bearing(origin, *line.iter().skip(1).find(|p| **p != origin)?)) |
| 201 | } else { |
| 202 | let origin = *line.last()?; |
| 203 | Some(bearing(origin, *line.iter().rev().skip(1).find(|p| **p != origin)?)) |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | /// Bearing from `a` to `b` in degrees clockwise from north. Both are lon/lat. |
| 208 | fn bearing(a: (f64, f64), b: (f64, f64)) -> f64 { |
| 209 | let north = b.1 - a.1; |
| 210 | let east = (b.0 - a.0) * a.1.to_radians().cos(); |
| 211 | east.atan2(north).to_degrees() |
| 212 | } |
| 213 | |
| 214 | /// How far two bearings are from being a straight continuation of one another, in degrees. |
| 215 | /// |
| 216 | /// Both point *away* from the node they share, so a road running straight through it leaves on two |
| 217 | /// bearings 180° apart and scores zero. |
| 218 | fn deviation(a: f64, b: f64) -> f64 { |
| 219 | let mut delta = (a - b) % 360.0; |
| 220 | if delta > 180.0 { |
| 221 | delta -= 360.0; |
| 222 | } else if delta < -180.0 { |
| 223 | delta += 360.0; |
| 224 | } |
| 225 | (180.0 - delta.abs()).abs() |
| 226 | } |
| 227 | |
| 228 | include!("lanefill_part1.rs"); |
| 229 | |
| 230 | #[cfg(test)] |
| 231 | mod lazy_tests { |
| 232 | use super::*; |
| 233 | |
| 234 | /// `prepare_lazy` decides every way exactly as `prepare` on its full line does: same `None`s, |
| 235 | /// same records, for donors and recipients, short and long, with repeated vertices at either |
| 236 | /// end and degenerate ways. |
| 237 | #[test] |
| 238 | fn lazy_preparation_matches_preparing_the_whole_line() { |
| 239 | let mut state = 0x2545_F491_4F6C_DD1Du64; |
| 240 | let mut next = || { |
| 241 | state ^= state << 13; |
| 242 | state ^= state >> 7; |
| 243 | state ^= state << 17; |
| 244 | state |
| 245 | }; |
| 246 | for case in 0..20_000i64 { |
| 247 | let n = 2 + (next() % 12) as usize; |
| 248 | let step = [1e-6, 1e-5, 1e-4, 3e-4][(next() % 4) as usize]; |
| 249 | let mut line = Vec::with_capacity(n); |
| 250 | let (mut x, mut y) = (-122.3 + (next() % 1000) as f64 * 1e-3, 37.5); |
| 251 | for _ in 0..n { |
| 252 | if next() % 5 != 0 { |
| 253 | x += ((next() % 200) as f64 - 100.0) * step; |
| 254 | y += ((next() % 200) as f64 - 100.0) * step; |
| 255 | } |
| 256 | line.push((x, y)); |
| 257 | } |
| 258 | let mut nodes: Vec<i64> = (0..n as i64).map(|k| 1000 + k).collect(); |
| 259 | if case % 9 == 0 { |
| 260 | let last = nodes.len() - 1; |
| 261 | nodes[last] = nodes[0]; |
| 262 | } |
| 263 | let lanes = (next() % 3) as u8; |
| 264 | let oneway = next() % 2 == 0; |
| 265 | let name = if case % 13 == 0 { "" } else { "Main St" }; |
| 266 | let whole = |
| 267 | prepare(&Segment { id: case, name, lanes, oneway, nodes: &nodes, line: &line }); |
| 268 | let lazy = prepare_lazy(case, name, lanes, oneway, &nodes, |i| line[i]); |
| 269 | match (whole, lazy) { |
| 270 | (None, None) => {} |
| 271 | (Some(a), Some(b)) => { |
| 272 | for (ra, rb) in a.0.iter().zip(b.0.iter()) { |
| 273 | let (mut ba, mut bb) = (Vec::new(), Vec::new()); |
| 274 | ra.write(&mut ba).unwrap(); |
| 275 | rb.write(&mut bb).unwrap(); |
| 276 | assert_eq!(ba, bb, "case {case}"); |
| 277 | } |
| 278 | } |
| 279 | (a, b) => panic!("case {case}: whole {} lazy {}", a.is_some(), b.is_some()), |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | /// The partition files are unlinked at creation on Unix: their directory is empty while the |
| 285 | /// collector is live, and `finish` still reads every record back through the handles. |
| 286 | #[test] |
| 287 | fn partitions_leave_no_names_behind() { |
| 288 | let dir = |
| 289 | std::env::temp_dir().join(format!("mamaps_lanefill_unlink_{}", std::process::id())); |
| 290 | std::fs::create_dir_all(&dir).unwrap(); |
| 291 | let mut c = Collector::create(&dir.join("tiles.features.tmp")).unwrap(); |
| 292 | let line = [(-122.0, 37.0), (-122.0, 37.0001)]; |
| 293 | let a = |
| 294 | Segment { id: 1, name: "A St", lanes: 0, oneway: false, nodes: &[10, 11], line: &line }; |
| 295 | c.push(&a).unwrap(); |
| 296 | #[cfg(unix)] |
| 297 | assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "a partition name was left"); |
| 298 | let _ = c.finish().unwrap(); |
| 299 | assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); |
| 300 | std::fs::remove_dir(&dir).unwrap(); |
| 301 | } |
| 302 | } |