Skip to main content

map_tile_toolkit/
mosaic.rs

1//! Stateful reassembly of sliced tiles back into whole features - the accumulating inverse of the
2//! [`Slicer`](crate::Slicer).
3//!
4//! [`Mosaic`] rejoins **polyline** tiles ([`Slicer::line`](crate::Slicer::line)); [`PolygonMosaic`] rejoins
5//! **polygon** tiles ([`Slicer::polygon`](crate::Slicer::polygon)). Both take each tile's geometry
6//! in its local frame, rebase it into the global frame (`local + tile·extent`), and link geometry
7//! across borders by shared **directed edges**. [`add`](Mosaic::add) rejects a tile inconsistent with
8//! those already present - naming the ones it conflicts with, and leaving the mosaic unchanged - in
9//! two ways:
10//!
11//! - **Payload:** slicing duplicates a border-crossing segment identically (position **and** payload)
12//!   in every tile that carries it, so a shared edge whose vertices *disagree* is a conflict. (A single
13//!   position may be shared by several features - edges only collide when their whole segment does - so
14//!   unrelated features meeting at a point never conflict.)
15//! - **Membership:** every tile is complete in its own *core* (the cell it owns), so an edge with an
16//!   endpoint in a present tile's core must be carried by that tile. A present tile that owns an
17//!   endpoint but lacks the edge - a line spanning into a neighbor the neighbor never corroborates,
18//!   or two tiles disagreeing at a shared junction - is a conflict. A buffer only widens the overlap
19//!   two tiles share, and the whole overlap must match; any *disagreement* there surfaces here too,
20//!   because the differing vertex lands in some tile's core. Only a pure *omission* of redundant
21//!   overlap geometry goes unflagged - and that is harmless, since the core tile still supplies the
22//!   edge and duplicates collapse on reassembly.
23//!
24//! [`iter_features`](Mosaic::iter_features) re-chains the distinct edges into maximal chains
25//! (`stitch`) - the same reconstruction a from-scratch merge of all tiles would produce.
26//!
27//! The two mosaics differ only in how a tile's input becomes directed edges:
28//!
29//! - [`Mosaic`] uses every consecutive vertex pair of each **run**. It needs only the `extent`.
30//! - [`PolygonMosaic`] takes each tile's **rings** and keeps only the edges that **touch** the tile's
31//!   buffered box `B`. This drops all the slicer's synthetic geometry - the
32//!   clip-boundary corners, fill boxes, and gap-bridging chords, which are routed strictly *outside*
33//!   `B` - while every real ring edge survives in the tile that owns its start vertex (whose cell lies
34//!   in `B`, so the edge touches `B` there). The *same* edge machinery then reassembles the rings, with
35//!   orientation and holes falling out of the directed edges. Testing the edge rather than the vertex
36//!   is what catches a bridge chord drawn directly between two *original* crossing vertices, which no
37//!   per-vertex tag could. Because it re-derives `B`, it needs the `buffer` as well as the `extent`. A
38//!   tile lying entirely inside a polygon (an all-synthetic fill) contributes no edges - correct, since
39//!   a reassembled polygon's interior is implied by its winding, not by fill tiles.
40
41use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
42
43use geo_types::Coord;
44
45use crate::TileError;
46use crate::clip_polyline::segment_intersects;
47use crate::grid::Grid;
48use crate::tile::{TileId, tile_of};
49use crate::vertex::Vertex;
50
51/// A global directed edge's two vertices (identical across every tile that carries it) and the set of
52/// tiles that do.
53#[derive(Debug, Clone)]
54struct Edge<V> {
55    a: V,
56    b: V,
57    tiles: BTreeSet<TileId>,
58}
59
60/// A directed edge keyed by its endpoint positions.
61type EdgeKey = (Coord<i32>, Coord<i32>);
62
63/// The shared global directed-edge index behind both mosaics: it holds the cross-tile edge map and
64/// per-tile bookkeeping, detects conflicts, and re-chains features - everything except how a tile's
65/// raw geometry is turned into directed edges (runs for [`Mosaic`], synthetic-filtered rings for
66/// [`PolygonMosaic`]).
67#[derive(Debug, Clone)]
68struct EdgeIndex<V: Vertex> {
69    /// Global directed-edge index, keyed by endpoint positions. Every tile at a key holds the same
70    /// vertices (conflicts are rejected on commit).
71    edges: HashMap<EdgeKey, Edge<V>>,
72    /// The edge keys each tile contributed, for `O(tile)` purge and self-exclusion when re-adding.
73    tile_edges: BTreeMap<TileId, Vec<EdgeKey>>,
74}
75
76impl<V: Vertex> EdgeIndex<V> {
77    fn new() -> Self {
78        Self {
79            edges: HashMap::new(),
80            tile_edges: BTreeMap::new(),
81        }
82    }
83
84    /// Replace `tile`'s contribution with `new_edges` (its distinct directed edges, already rebased
85    /// into the global frame), after rejecting any conflict with the other tiles. `ext` is the signed
86    /// extent, used to map an endpoint to its owner tile for the membership check. On conflict nothing
87    /// is mutated.
88    fn commit(&mut self, tile: TileId, new_edges: HashMap<EdgeKey, (V, V)>, ext: i32) -> Result<(), TileError> {
89        // Conflict scan against *other* tiles (this tile's own prior data is replaced, not compared).
90        let mut conflicts = BTreeSet::new();
91        // (a) Payload conflict: another tile carries the same edge (identical positions) but different
92        // vertices - only a payload (e.g. an M value) can differ, since the key is the positions.
93        for (key, (a, b)) in &new_edges {
94            if let Some(existing) = self.edges.get(key)
95                && !(existing.a == *a && existing.b == *b)
96            {
97                conflicts.extend(existing.tiles.iter().copied().filter(|&t| t != tile));
98            }
99        }
100        // (b) Membership conflict: a tile is complete in its own core, so every edge with an endpoint
101        // in a present tile's core must be carried by that tile. A present endpoint-tile that lacks the
102        // edge means the tiles came from inconsistent data. Checked both ways so detection is
103        // order-independent. (Any *disagreement* in a buffer overlap surfaces here too - the differing
104        // vertex lands in some core - so only a harmless omission of a redundant overlap edge slips.)
105        // This tile must carry every already-present edge that names it as an endpoint-tile.
106        for (key, existing) in &self.edges {
107            if (tile_of(key.0, ext) == tile || tile_of(key.1, ext) == tile) && !new_edges.contains_key(key) {
108                conflicts.extend(existing.tiles.iter().copied().filter(|&t| t != tile));
109            }
110        }
111        // Every already-present endpoint-tile of one of this tile's edges must carry that edge.
112        for key in new_edges.keys() {
113            for endpoint in [tile_of(key.0, ext), tile_of(key.1, ext)] {
114                if endpoint != tile
115                    && self.tile_edges.contains_key(&endpoint)
116                    && !self.edges.get(key).is_some_and(|e| e.tiles.contains(&endpoint))
117                {
118                    conflicts.insert(endpoint);
119                }
120            }
121        }
122        if !conflicts.is_empty() {
123            return Err(TileError::Conflict(conflicts.into_iter().collect()));
124        }
125        // Commit: replace any prior contents for this tile, then index the new edges.
126        self.purge(tile);
127        let mut keys = Vec::with_capacity(new_edges.len());
128        for (key, (a, b)) in new_edges {
129            self.edges
130                .entry(key)
131                .or_insert_with(|| Edge {
132                    a,
133                    b,
134                    tiles: BTreeSet::new(),
135                })
136                .tiles
137                .insert(tile);
138            keys.push(key);
139        }
140        if !keys.is_empty() {
141            self.tile_edges.insert(tile, keys);
142        }
143        Ok(())
144    }
145
146    /// Remove `tile` and all geometry it contributed. Returns whether the tile was present.
147    fn purge(&mut self, tile: TileId) -> bool {
148        let Some(keys) = self.tile_edges.remove(&tile) else {
149            return false;
150        };
151        for key in keys {
152            if let Some(edge) = self.edges.get_mut(&key) {
153                edge.tiles.remove(&tile);
154                if edge.tiles.is_empty() {
155                    self.edges.remove(&key);
156                }
157            }
158        }
159        true
160    }
161
162    /// Re-chain the distinct edges into maximal chains, in the global frame (deterministic order).
163    fn iter_features(&self) -> impl Iterator<Item = Vec<V>> {
164        let mut ordered: Vec<&Edge<V>> = self.edges.values().collect();
165        ordered.sort_unstable_by_key(|edge| {
166            let (a, b) = (edge.a.position(), edge.b.position());
167            (a.x, a.y, b.x, b.y)
168        });
169        let runs: Vec<Vec<V>> = ordered.iter().map(|edge| vec![edge.a, edge.b]).collect();
170        stitch(&runs).into_iter()
171    }
172
173    fn contains(&self, tile: TileId) -> bool {
174        self.tile_edges.contains_key(&tile)
175    }
176
177    fn len(&self) -> usize {
178        self.tile_edges.len()
179    }
180
181    fn is_empty(&self) -> bool {
182        self.tile_edges.is_empty()
183    }
184
185    fn clear(&mut self) {
186        self.edges.clear();
187        self.tile_edges.clear();
188    }
189}
190
191/// Reassembles tiled **polyline** features back into whole features as tiles are [added](Self::add).
192///
193/// Generic over the [`Vertex`] type `V` (defaults to [`Coord<i32>`]). Needs only the `extent` the
194/// tiles were sliced at - never the buffer (see the module docs). A payload-carrying vertex (e.g.
195/// [`Measured`](crate::Measured)) additionally makes payload [`Conflict`](TileError::Conflict)s
196/// meaningful.
197#[derive(Debug, Clone)]
198pub struct Mosaic<V: Vertex = Coord<i32>> {
199    extent: u32,
200    index: EdgeIndex<V>,
201}
202
203impl<V: Vertex> Mosaic<V> {
204    /// Create an empty mosaic for tiles sliced at `extent`.
205    ///
206    /// # Errors
207    ///
208    /// [`TileError::InvalidExtent`] if `extent` is `0` or greater than `i32::MAX`.
209    pub fn new(extent: u32) -> Result<Self, TileError> {
210        if extent == 0 || extent > i32::MAX.cast_unsigned() {
211            return Err(TileError::InvalidExtent);
212        }
213        Ok(Self {
214            extent,
215            index: EdgeIndex::new(),
216        })
217    }
218
219    /// The extent every tile is sliced at.
220    #[must_use]
221    pub fn extent(&self) -> u32 {
222        self.extent
223    }
224
225    /// Add `tile`'s runs (in its local frame) to the mosaic. `runs` is anything sliceable to `[V]`
226    /// (e.g. `&[&[V]]` collected from a tile's features). Re-adding a tile replaces its contents. A
227    /// tile with no ≥2-vertex run contributes nothing.
228    ///
229    /// # Errors
230    ///
231    /// - [`TileError::Conflict`] if the tile disagrees with already-added tiles on a shared border
232    ///   segment. The mosaic is unchanged.
233    /// - [`TileError::Overflow`] if a vertex overflows `i32` when rebased into the global frame.
234    #[cfg_attr(feature = "hotpath", hotpath::measure)]
235    pub fn add<L: AsRef<[V]>>(&mut self, tile: TileId, runs: &[L]) -> Result<(), TileError> {
236        let (off_x, off_y) = tile_offset(tile, self.extent);
237        // Rebase to the global frame and collect this tile's distinct directed edges. Nothing is
238        // mutated yet, so an overflow (or a later conflict) leaves the mosaic untouched.
239        let mut new_edges: HashMap<EdgeKey, (V, V)> = HashMap::new();
240        for run in runs {
241            let g = rebase(run.as_ref(), off_x, off_y)?;
242            for &[p, q] in g.array_windows() {
243                let key = (p.position(), q.position());
244                if key.0 != key.1 {
245                    new_edges.entry(key).or_insert((p, q));
246                }
247            }
248        }
249        self.index.commit(tile, new_edges, self.extent.cast_signed())
250    }
251
252    /// Remove `tile` and all geometry it contributed. Returns whether the tile was present.
253    pub fn purge(&mut self, tile: TileId) -> bool {
254        self.index.purge(tile)
255    }
256
257    /// Iterate every reassembled feature - geometry stitched across tile borders into maximal
258    /// polylines, in the global frame. A single iterator over the whole mosaic; deterministic order.
259    pub fn iter_features(&self) -> impl Iterator<Item = Vec<V>> {
260        self.index.iter_features()
261    }
262
263    /// Whether `tile` is currently in the mosaic.
264    #[must_use]
265    pub fn contains(&self, tile: TileId) -> bool {
266        self.index.contains(tile)
267    }
268
269    /// The number of tiles currently in the mosaic.
270    #[must_use]
271    pub fn len(&self) -> usize {
272        self.index.len()
273    }
274
275    /// Whether no tile has been added yet.
276    #[must_use]
277    pub fn is_empty(&self) -> bool {
278        self.index.is_empty()
279    }
280
281    /// Discard every tile, keeping the extent.
282    pub fn clear(&mut self) {
283        self.index.clear();
284    }
285}
286
287/// Reassembles tiled **polygon** features back into whole rings as tiles are [added](Self::add) - the
288/// accumulating inverse of the polygon slicer.
289///
290/// Generic over the [`Vertex`] type `V` (defaults to [`Coord<i32>`]). Needs the `extent` **and**
291/// `buffer` the tiles were sliced at, so it can re-derive each tile's buffered box and recognise the
292/// synthetic clip-boundary corners the slicer injected (see the module docs). Reassembly is by
293/// directed edge, so each ring comes back with its original orientation; a payload-carrying vertex
294/// additionally makes payload [`Conflict`](TileError::Conflict)s meaningful.
295#[derive(Debug, Clone)]
296pub struct PolygonMosaic<V: Vertex = Coord<i32>> {
297    grid: Grid,
298    index: EdgeIndex<V>,
299}
300
301impl<V: Vertex> PolygonMosaic<V> {
302    /// Create an empty polygon mosaic for tiles sliced at `extent` with `buffer`.
303    ///
304    /// # Errors
305    ///
306    /// - [`TileError::InvalidExtent`] if `extent` is `0`, or `extent + buffer` exceeds `i32::MAX`.
307    /// - [`TileError::BufferTooLarge`] if `buffer` is not strictly less than half the `extent`.
308    pub fn new(extent: u32, buffer: u16) -> Result<Self, TileError> {
309        Ok(Self {
310            grid: Grid::new(extent, buffer)?,
311            index: EdgeIndex::new(),
312        })
313    }
314
315    /// The extent every tile is sliced at.
316    #[must_use]
317    pub fn extent(&self) -> u32 {
318        self.grid.extent()
319    }
320
321    /// The buffer every tile is sliced with.
322    #[must_use]
323    pub fn buffer(&self) -> u16 {
324        self.grid.buffer()
325    }
326
327    /// Add `tile`'s rings (in its local frame) to the mosaic. `rings` is anything sliceable to `[V]`
328    /// (e.g. `&[&[V]]` collected from a tile's polygon features - exterior and hole rings alike, in any
329    /// order). Each ring may be given open or closed. Re-adding a tile replaces its contents. A tile
330    /// that contributes only synthetic geometry (a solid interior fill) records nothing.
331    ///
332    /// The synthetic clip-boundary corners are dropped geometrically before anything is indexed, so
333    /// they never enter the edge map and can raise no [`Conflict`](TileError::Conflict).
334    ///
335    /// # Errors
336    ///
337    /// - [`TileError::Conflict`] if the tile disagrees with already-added tiles on a shared border
338    ///   edge. The mosaic is unchanged.
339    /// - [`TileError::Overflow`] if the tile's box or a vertex overflows `i32` in the global frame.
340    #[cfg_attr(feature = "hotpath", hotpath::measure)]
341    pub fn add<L: AsRef<[V]>>(&mut self, tile: TileId, rings: &[L]) -> Result<(), TileError> {
342        let (min, max) = self.grid.tile_buffered_bounds(tile)?;
343        let ext = self.grid.extent();
344        let (off_x, off_y) = tile_offset(tile, ext);
345        // Rebase each ring, drop its synthetic corners, and collect the surviving original directed
346        // edges. Nothing is mutated yet, so an overflow (or a later conflict) leaves the mosaic intact.
347        let mut new_edges: HashMap<EdgeKey, (V, V)> = HashMap::new();
348        for ring in rings {
349            ring_edges(ring.as_ref(), off_x, off_y, min, max, &mut new_edges)?;
350        }
351        self.index.commit(tile, new_edges, ext.cast_signed())
352    }
353
354    /// Remove `tile` and all geometry it contributed. Returns whether the tile was present.
355    pub fn purge(&mut self, tile: TileId) -> bool {
356        self.index.purge(tile)
357    }
358
359    /// Iterate every reassembled ring - geometry stitched across tile borders into maximal chains, in
360    /// the global frame. A single iterator over the whole mosaic; deterministic order.
361    pub fn iter_features(&self) -> impl Iterator<Item = Vec<V>> {
362        self.index.iter_features()
363    }
364
365    /// Whether `tile` is currently in the mosaic.
366    #[must_use]
367    pub fn contains(&self, tile: TileId) -> bool {
368        self.index.contains(tile)
369    }
370
371    /// The number of tiles currently in the mosaic (all-synthetic fill tiles do not count).
372    #[must_use]
373    pub fn len(&self) -> usize {
374        self.index.len()
375    }
376
377    /// Whether no tile has contributed geometry yet.
378    #[must_use]
379    pub fn is_empty(&self) -> bool {
380        self.index.is_empty()
381    }
382
383    /// Discard every tile, keeping the extent and buffer.
384    pub fn clear(&mut self) {
385        self.index.clear();
386    }
387}
388
389/// The global-frame offset `(tile.x·extent, tile.y·extent)` in `i64` (both factors within `i32`, so
390/// the product is below `2^62`).
391fn tile_offset(tile: TileId, extent: u32) -> (i64, i64) {
392    let e = i64::from(extent);
393    (i64::from(tile.x) * e, i64::from(tile.y) * e)
394}
395
396/// Rebase one vertex by `(off_x, off_y)` in `i64` (the offset is `tile · extent`, below `2^62`, and a
397/// vertex adds at most another `i32`, so the sum stays within `i64`), range-checking back into `i32`.
398fn rebase_vertex<V: Vertex>(v: V, off_x: i64, off_y: i64) -> Result<V, TileError> {
399    let p = v.position();
400    Ok(v.with_position(Coord {
401        x: i32::try_from(i64::from(p.x) + off_x).map_err(|_overflow| TileError::Overflow)?,
402        y: i32::try_from(i64::from(p.y) + off_y).map_err(|_overflow| TileError::Overflow)?,
403    }))
404}
405
406/// Rebase every vertex of `run` by `(off_x, off_y)`, range-checking each result back into `i32`.
407fn rebase<V: Vertex>(run: &[V], off_x: i64, off_y: i64) -> Result<Vec<V>, TileError> {
408    run.iter().map(|&v| rebase_vertex(v, off_x, off_y)).collect()
409}
410
411/// Rebase one closed `ring` to the global frame and add to `new_edges` every directed edge that
412/// **touches** the tile's buffered box `[min, max]`.
413///
414/// This one test drops all the slicer's synthetic geometry and reassembles the original rings, because
415/// of a clean split:
416///
417/// - Every **real** ring edge `p -> q` is emitted by the tile that owns `p`'s cell: `p` lies in that
418///   tile's core (⊆ its box), so the edge starts inside the box and touches it. Thus no real edge is
419///   ever lost - it survives in at least the one tile that owns its start.
420/// - Every **synthetic** edge - the clip-boundary corners, fill boxes, and gap-bridging chords the
421///   slicer injects - is routed strictly *outside* the box, so it never touches the box
422///   and is dropped. This catches even a direct bridge chord between two *original* crossing vertices,
423///   which a per-vertex "is this corner synthetic" test cannot (its endpoints are genuine vertices).
424///
425/// An edge that misses the box but *is* real is simply redundant here (its endpoints belong to other
426/// tiles' cores, which re-emit it), so dropping it is harmless. The rule is purely tile-local, hence
427/// order-independent.
428fn ring_edges<V: Vertex>(
429    ring: &[V],
430    off_x: i64,
431    off_y: i64,
432    min: Coord<i32>,
433    max: Coord<i32>,
434    new_edges: &mut HashMap<EdgeKey, (V, V)>,
435) -> Result<(), TileError> {
436    // Rebase to the global frame and drop consecutive duplicate positions in one pass (matching the
437    // slicer, so a zero-length edge never distorts the touch test) - no separate rebased copy.
438    let mut pts: Vec<V> = Vec::with_capacity(ring.len());
439    for &v in ring {
440        let g = rebase_vertex(v, off_x, off_y)?;
441        if pts.last().map(Vertex::position) != Some(g.position()) {
442            pts.push(g);
443        }
444    }
445    // Drop the repeated closing vertex.
446    while pts.len() >= 2 && pts[0].position() == pts[pts.len() - 1].position() {
447        pts.pop();
448    }
449    let m = pts.len();
450    if m < 3 {
451        return Ok(());
452    }
453    // Emit each cyclic edge that touches the tile's box; drop the rest (synthetic or redundant).
454    for i in 0..m {
455        let (p, q) = (pts[i], pts[(i + 1) % m]);
456        if p.position() != q.position() && segment_intersects(p.position(), q.position(), min, max) {
457            new_edges.entry((p.position(), q.position())).or_insert((p, q));
458        }
459    }
460    Ok(())
461}
462
463/// Rejoin overlapping runs into maximal polylines via their **directed edges** (consecutive vertex
464/// pairs, keyed by position): a border-crossing segment is the same edge in both tiles, so keeping the
465/// distinct edges drops every duplicate, and following each vertex to its outgoing edge re-chains them.
466///
467/// Order-independent and deterministic (edges/positions keep first-seen order). A simple polyline
468/// reconstructs exactly; where the geometry revisits a position, some covering chain is produced
469/// (deterministic but arbitrary).
470fn stitch<V: Vertex>(runs: &[Vec<V>]) -> Vec<Vec<V>> {
471    // Distinct directed edges, in first-seen order (dedup by endpoint positions).
472    let mut seen: HashSet<(Coord<i32>, Coord<i32>)> = HashSet::new();
473    let mut edges: Vec<(V, V)> = Vec::new();
474    for run in runs {
475        for &[p, q] in run.array_windows() {
476            if seen.insert((p.position(), q.position())) {
477                edges.push((p, q));
478            }
479        }
480    }
481    if edges.is_empty() {
482        return Vec::new();
483    }
484
485    // Adjacency: each start position -> its outgoing edge indices (FIFO = first-seen). Track in-degree
486    // and first-seen position order so chain starts are found deterministically.
487    let mut out: HashMap<Coord<i32>, VecDeque<usize>> = HashMap::new();
488    let mut indeg: HashMap<Coord<i32>, usize> = HashMap::new();
489    let mut points: Vec<Coord<i32>> = Vec::new();
490    let mut known: HashSet<Coord<i32>> = HashSet::new();
491    for (i, (p, q)) in edges.iter().enumerate() {
492        let (pp, qp) = (p.position(), q.position());
493        out.entry(pp).or_default().push_back(i);
494        *indeg.entry(qp).or_insert(0) += 1;
495        indeg.entry(pp).or_insert(0);
496        for pt in [pp, qp] {
497            if known.insert(pt) {
498                points.push(pt);
499            }
500        }
501    }
502
503    let mut used = vec![false; edges.len()];
504    let mut chains: Vec<Vec<V>> = Vec::new();
505
506    // Phase 1: start a chain at each path source - a position with more outgoing than incoming edges
507    // accounts for `outdeg - indeg` chain starts (the endpoints of open polylines).
508    for &p in &points {
509        let outdeg = out.get(&p).map_or(0, VecDeque::len);
510        let ind = indeg.get(&p).copied().unwrap_or(0);
511        for _ in ind..outdeg {
512            if let Some(first) = next_unused(&mut out, p, &used) {
513                chains.push(build_chain(first, &edges, &mut used, &mut out));
514            }
515        }
516    }
517    // Phase 2: whatever edges remain form closed loops; start each at its first unused edge.
518    for i in 0..edges.len() {
519        if !used[i] {
520            chains.push(build_chain(i, &edges, &mut used, &mut out));
521        }
522    }
523    chains
524}
525
526/// Pop and return the next not-yet-used outgoing edge index from position `p`, discarding used ones
527/// from the front. `None` when `p` has no remaining unused outgoing edge. Used by [`stitch`].
528fn next_unused(out: &mut HashMap<Coord<i32>, VecDeque<usize>>, p: Coord<i32>, used: &[bool]) -> Option<usize> {
529    let dq = out.get_mut(&p)?;
530    while let Some(&i) = dq.front() {
531        if used[i] {
532            dq.pop_front();
533        } else {
534            return dq.pop_front();
535        }
536    }
537    None
538}
539
540/// Follow outgoing edges from edge `first`, consuming each, until a position has no unused outgoing
541/// edge; return the vertex chain `[start, …]`. Used by [`stitch`].
542fn build_chain<V: Vertex>(
543    first: usize,
544    edges: &[(V, V)],
545    used: &mut [bool],
546    out: &mut HashMap<Coord<i32>, VecDeque<usize>>,
547) -> Vec<V> {
548    let mut chain = vec![edges[first].0];
549    let mut cur = first;
550    loop {
551        used[cur] = true;
552        let q = edges[cur].1;
553        chain.push(q);
554        match next_unused(out, q.position(), used) {
555            Some(next) => cur = next,
556            None => break,
557        }
558    }
559    chain
560}