Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / schema / junction_part2.rs
junction_part2.rs280 lines · 12.1 KiBRaw
| 1 | /// Spread `lanes` across `exits`, both already in left→right order, as `(lane, exit)` pairs. |
| 2 | /// |
| 3 | /// Whichever side is larger drives the pairing, so every lane gets a connector and every exit gets |
| 4 | /// fed. Two left-turn lanes onto one road give two connectors into the same exit, which is right — |
| 5 | /// a dual left turn is two ribbons. One lane onto a two-lane exit gives two connectors out of the |
| 6 | /// same lane, which is also right: the lane fans. |
| 7 | fn distribute(lanes: &[usize], exits: &[usize]) -> Vec<(usize, usize)> { |
| 8 | if lanes.is_empty() || exits.is_empty() { |
| 9 | return Vec::new(); |
| 10 | } |
| 11 | if lanes.len() >= exits.len() { |
| 12 | lanes |
| 13 | .iter() |
| 14 | .enumerate() |
| 15 | .map(|(i, &lane)| (lane, exits[i * exits.len() / lanes.len()])) |
| 16 | .collect() |
| 17 | } else { |
| 18 | exits |
| 19 | .iter() |
| 20 | .enumerate() |
| 21 | .map(|(j, &exit)| (lanes[j * lanes.len() / exits.len()], exit)) |
| 22 | .collect() |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | /// The lane connectors through the junction at node `n`, in emission order. |
| 27 | /// |
| 28 | /// The whole of [`stream_junctions`]'s loop body except the `sink.push` / |
| 29 | /// `emitted` counting: pure per-node work over shared-read-only tables |
| 30 | /// (`Graph`/`LaneTable` are file mappings with `&self` accessors, |
| 31 | /// `InEdges::of` is a pure slice, `Conventions::at_tile` is a |
| 32 | /// `HashMap::get`), so a batch of node ids fans out across the pool exactly |
| 33 | /// as `materialise_ways` does and the serial drain pushes the results in `n` |
| 34 | /// order — which is what keeps the spill, and therefore the archive, |
| 35 | /// byte-identical at every thread count. |
| 36 | /// |
| 37 | /// Within a node the order is exactly the serial loop's: `incoming` order, |
| 38 | /// `legal.sort_by(angle)`, `pairs.sort_unstable(); dedup()`. |
| 39 | fn junctions_for_node( |
| 40 | n: u64, |
| 41 | graph: &Graph, |
| 42 | lanes: Option<&LaneTable>, |
| 43 | incoming: &InEdges, |
| 44 | conventions: &Conventions, |
| 45 | ) -> Vec<Vec<(f64, f64)>> { |
| 46 | let mut out: Vec<Vec<(f64, f64)>> = Vec::new(); |
| 47 | let node = graph.node(n); |
| 48 | let in_arms: Vec<Arm> = incoming |
| 49 | .of(n) |
| 50 | .iter() |
| 51 | .filter_map(|&idx| { |
| 52 | arm(graph, lanes, idx, source_of(graph, idx) as u32, n as u32, false) |
| 53 | }) |
| 54 | .collect(); |
| 55 | let out_arms: Vec<Arm> = (graph.edge_ptr(n)..graph.edge_ptr(n + 1)) |
| 56 | .filter(|&idx| is_drivable(graph.edge_type(idx))) |
| 57 | .filter_map(|idx| { |
| 58 | let target = graph.edge_target(idx, n as u32).ok()?; |
| 59 | arm(graph, lanes, idx, n as u32, target, true) |
| 60 | }) |
| 61 | .collect(); |
| 62 | if in_arms.is_empty() || out_arms.len() < 2 { |
| 63 | return out; |
| 64 | } |
| 65 | // A junction is a node three or more distinct roads meet at. Degree-2 chains are collapsed |
| 66 | // by the generator, so the survivors below this bar are dead ends, attribute breaks and |
| 67 | // transit stops — none of which anything turns at. |
| 68 | let degree: BTreeSet<u32> = |
| 69 | in_arms.iter().chain(&out_arms).map(|a| a.neighbour).collect(); |
| 70 | if degree.len() < 3 { |
| 71 | return out; |
| 72 | } |
| 73 | // Thinning rule: a junction with no arterial arm emits nothing. Quiet |
| 74 | // residential crossings keep their carriageways; they lose only the lane |
| 75 | // markings, which is where the layer's bytes concentrate. |
| 76 | if !in_arms |
| 77 | .iter() |
| 78 | .chain(&out_arms) |
| 79 | .any(|a| a.road_class <= super::junction::ARTERIAL_MAX_CLASS) |
| 80 | { |
| 81 | return out; |
| 82 | } |
| 83 | |
| 84 | let (tx, ty) = tile_build::geom::project( |
| 85 | f64::from(node.1) * 1e-7, |
| 86 | f64::from(node.0) * 1e-7, |
| 87 | super::boundaries::COARSE_ZOOM, |
| 88 | ); |
| 89 | let left_hand = conventions |
| 90 | .at_tile( |
| 91 | super::boundaries::COARSE_ZOOM, |
| 92 | tx.max(0.0) as u64, |
| 93 | ty.max(0.0) as u64, |
| 94 | ) |
| 95 | .left_hand; |
| 96 | |
| 97 | for approach in &in_arms { |
| 98 | // Every exit but the one back the way you came. The graph carries no turn restrictions, |
| 99 | // so this is the whole legality model: inference, and generous. |
| 100 | let mut legal: Vec<(usize, f64, Turn)> = out_arms |
| 101 | .iter() |
| 102 | .enumerate() |
| 103 | .filter(|(_, exit)| exit.neighbour != approach.neighbour) |
| 104 | .map(|(i, exit)| { |
| 105 | let delta = normalise_degrees(exit.heading - approach.heading); |
| 106 | (i, delta, classify_turn(delta)) |
| 107 | }) |
| 108 | // A reversal is not a movement this layer draws, and the neighbour test above does |
| 109 | // not catch it. On a divided highway the median slot reverses onto the *opposing |
| 110 | // carriageway*, which is a different node, so it survives that filter and arrives |
| 111 | // here as a legal 180-degree movement. The curve it produces never enters the |
| 112 | // junction at all: with `f_out = -f_in` all four bezier control points sit behind |
| 113 | // the node, so it draws as a flat hook doubling back along the approach. |
| 114 | .filter(|(_, _, turn)| *turn != Turn::Reverse) |
| 115 | .collect(); |
| 116 | if legal.is_empty() { |
| 117 | continue; |
| 118 | } |
| 119 | // Left→right as the driver sees them, which is the order lane masks are stored in. |
| 120 | legal.sort_by(|a, b| a.1.total_cmp(&b.1)); |
| 121 | |
| 122 | // Both ends read the same function of their own arm, so neither can drift from the |
| 123 | // other and neither depends on who is looking. No count is derived from the junction's |
| 124 | // shape: `legal.len()` counts exits, not lanes, and using it as a width fanned the |
| 125 | // endpoints across phantom lanes and off the carriageway. |
| 126 | let approach_lanes = effective_lanes(approach); |
| 127 | |
| 128 | // `turn:lanes` where it exists, the arm's own lane count where it does not. |
| 129 | let mut pairs: Vec<(usize, usize)> = match &approach.masks { |
| 130 | Some(masks) => { |
| 131 | let mut pairs = Vec::new(); |
| 132 | for turn in Turn::ALL { |
| 133 | let bit = turn.bit(); |
| 134 | let claimants: Vec<usize> = masks |
| 135 | .iter() |
| 136 | .enumerate() |
| 137 | .filter(|(_, m)| { |
| 138 | // A lane whose only marking is "none" is treated as a through lane, |
| 139 | // which is what an unmarked lane at a junction means in practice. |
| 140 | **m & bit != 0 |
| 141 | || (turn == Turn::Through |
| 142 | && (**m == 0 || **m == LANE_NONE)) |
| 143 | }) |
| 144 | .map(|(k, _)| k) |
| 145 | .collect(); |
| 146 | if claimants.is_empty() { |
| 147 | continue; |
| 148 | } |
| 149 | pairs.extend(distribute(&claimants, &exits_for(turn, &legal))); |
| 150 | } |
| 151 | pairs |
| 152 | } |
| 153 | // Untagged, which is the overwhelming majority of roads. The arm's real lanes are |
| 154 | // spread over its legal exits — and since an untagged arm has exactly one, every |
| 155 | // movement leaves from lane 0 and the connectors share the arm's mouth. Assigning |
| 156 | // a lane *index* per exit here was the other half of the fabricated width: it put |
| 157 | // the third movement 1.5 lane widths out on a road with one lane. |
| 158 | None => { |
| 159 | let lanes: Vec<usize> = (0..approach_lanes).collect(); |
| 160 | let exits: Vec<usize> = legal.iter().map(|(i, _, _)| *i).collect(); |
| 161 | distribute(&lanes, &exits) |
| 162 | } |
| 163 | }; |
| 164 | |
| 165 | // Ordered so a movement's lanes rank left→right, and deduplicated because two tagged |
| 166 | // indications can fall back to the same exit and would otherwise draw one connector |
| 167 | // twice on top of itself. |
| 168 | pairs.sort_unstable(); |
| 169 | pairs.dedup(); |
| 170 | |
| 171 | for &(in_lane, exit_index) in &pairs { |
| 172 | let exit = &out_arms[exit_index]; |
| 173 | let Some((_, _, turn)) = legal.iter().find(|(i, _, _)| *i == exit_index) else { |
| 174 | continue; |
| 175 | }; |
| 176 | // Through movements need no connector: the approach lane's own |
| 177 | // carriageway ribbon already paints the straight path, and the |
| 178 | // connector draws as an exact identity over it (same style entry, |
| 179 | // same colour — see the module docs on reading a screenshot). |
| 180 | // Dropping them keeps only turns, which is where the markings |
| 181 | // actually differ from the road beneath. |
| 182 | if *turn == Turn::Through { |
| 183 | continue; |
| 184 | }; |
| 185 | // Thinning rule: a slight (20–45°) movement at a three-way node is |
| 186 | // a road bend, not a turn — the carriageway already shows the path. |
| 187 | // Kept at degree 4+, where a slight exit is a real choice. |
| 188 | if degree.len() == 3 |
| 189 | && matches!(*turn, Turn::SlightLeft | Turn::SlightRight) |
| 190 | { |
| 191 | continue; |
| 192 | } |
| 193 | let out_lanes = effective_lanes(exit); |
| 194 | // This lane's place among the lanes making the same movement into the same exit. |
| 195 | let siblings: Vec<usize> = |
| 196 | pairs.iter().filter(|(_, e)| *e == exit_index).map(|&(l, _)| l).collect(); |
| 197 | let rank = siblings.iter().position(|&l| l == in_lane).unwrap_or(0); |
| 198 | let out_lane = |
| 199 | exit_lane(*turn, in_lane, approach_lanes, out_lanes, rank, siblings.len()); |
| 200 | let Some(points) = connector( |
| 201 | node, |
| 202 | approach, |
| 203 | in_lane, |
| 204 | approach_lanes, |
| 205 | exit, |
| 206 | out_lane, |
| 207 | out_lanes, |
| 208 | *turn, |
| 209 | left_hand, |
| 210 | ) else { |
| 211 | continue; |
| 212 | }; |
| 213 | out.push(points); |
| 214 | } |
| 215 | } |
| 216 | out |
| 217 | } |
| 218 | |
| 219 | /// Read the v6 graph at `dir` and push one line feature per lane connector into `sink`. Returns the |
| 220 | /// number of connectors emitted. |
| 221 | /// |
| 222 | /// `conventions` decides which side of a road's centreline the direction of travel sits on, so a |
| 223 | /// left-hand-traffic country's connectors are not mirrored. It is resolved from each junction's own |
| 224 | /// coordinate at [`super::boundaries::COARSE_ZOOM`], which is the granularity the grid holds. |
| 225 | /// |
| 226 | /// Not clipped to a bounding box, for the same reason [`crate::schema::traffic::stream_graph`] is |
| 227 | /// not: the graph is already the built region and the tiler clips each connector per tile. |
| 228 | pub fn stream_junctions(dir: &Path, conventions: &Conventions, sink: &mut Sink) -> Result<u64> { |
| 229 | let graph = Graph::load(dir)?; |
| 230 | let lanes = LaneTable::load(dir)?; |
| 231 | let incoming = InEdges::build(&graph)?; |
| 232 | let class = junction_class(); |
| 233 | let mut emitted = 0u64; |
| 234 | |
| 235 | // Batched, the `materialise_ways` pattern: `junctions_for_node` is pure |
| 236 | // per-node work over shared-read-only tables, so a batch of node ids goes |
| 237 | // as wide as the pool while the drain pushes **in `n` order**, which is |
| 238 | // what keeps the spill — and therefore the archive — byte-identical at |
| 239 | // every thread count. The bar ticks in the drain, per node, so it spans |
| 240 | // the whole graph and this phase is never silent again. |
| 241 | // |
| 242 | // 32 Ki node ids is a few hundred KB of ids in flight; junctions are |
| 243 | // sparse, so the geometry coming back is far smaller than a ways batch of |
| 244 | // the same count. |
| 245 | const JUNCTION_BATCH: usize = 32 * 1024; |
| 246 | let mut bar = Progress::new( |
| 247 | "Junctions".to_string(), |
| 248 | graph.node_count as usize, |
| 249 | "node(s)", |
| 250 | true, |
| 251 | ); |
| 252 | let mut ids: Vec<u64> = Vec::with_capacity(JUNCTION_BATCH); |
| 253 | let mut built: Vec<Vec<Vec<(f64, f64)>>> = Vec::with_capacity(JUNCTION_BATCH); |
| 254 | let mut next = 0u64; |
| 255 | loop { |
| 256 | ids.clear(); |
| 257 | while ids.len() < JUNCTION_BATCH && next < graph.node_count { |
| 258 | ids.push(next); |
| 259 | next += 1; |
| 260 | } |
| 261 | if ids.is_empty() { |
| 262 | break; |
| 263 | } |
| 264 | built.clear(); |
| 265 | par::install(|| { |
| 266 | ids.par_iter() |
| 267 | .map(|&n| junctions_for_node(n, &graph, lanes.as_ref(), &incoming, conventions)) |
| 268 | .collect_into_vec(&mut built) |
| 269 | }); |
| 270 | for node_geoms in built.drain(..) { |
| 271 | for points in node_geoms { |
| 272 | sink.push(&class, &crate::store::EncodedGeom::live(&Geometry::Lines(vec![points]))?)?; |
| 273 | emitted += 1; |
| 274 | } |
| 275 | bar.tick("node(s)"); |
| 276 | } |
| 277 | } |
| 278 | bar.finish("node(s)"); |
| 279 | Ok(emitted) |
| 280 | } |