Skip to main content

map_tile_toolkit/
slicer.rs

1//! The public slicing API: [`Slicer`] takes **one geometry** at a time - a line, a point or a polygon -
2//! and returns a lazy iterator over its slices: [`Slicer::line`] / [`Slicer::point`] for every tile
3//! the geometry reaches, or [`Slicer::tile_line`] / [`Slicer::tile_point`] for one given tile.
4//!
5//! A multi-geometry is sliced one element at a time, by the caller: whoever keeps a feature's
6//! attributes with each of its slices, tile by tile, has to do that for a multi-feature too, so the
7//! slicer has no parts of its own to index. Slices of several elements that land in one tile are
8//! simply several slices there, which the caller groups (a `MultiLineString` in that tile, say).
9//!
10//! A line run is never copied: it borrows the caller's vertices ([`Local`]) and is computed only when
11//! the iterator reaches it, so a line with millions of vertices costs no memory beyond the iterator's
12//! own few fields, and stopping early stops the work. A polygon piece is built in the slicer's
13//! working memory, one at a time (a polygon inside one tile is lent as it is).
14//!
15//! Each call reads the whole geometry once, to bound it. That settles every possible overflow up
16//! front: the call returns a [`TileError`] or nothing at all, and the line and point iterators are
17//! plain [`Iterator`]s whose items cannot fail. (The polygon iterator still yields `Result`s, for a
18//! piece too large to index; see [`PolygonSlices`].)
19//!
20//! **Order is unspecified** for the all-tiles iterators: a line that leaves and re-enters a tile
21//! gives that tile several runs, each its own item.
22//!
23//! Runs follow the keep-original rule (see [`clip_polyline`](crate::clip_polyline)): a vertex is kept
24//! when one of its segments touches the tile's buffered box, and a run breaks only where a vertex is
25//! dropped. So a run is always a **contiguous range** of the line's vertices, which [`Local`] lends
26//! together with the tile origin.
27//!
28//! In terms of a line's segments (skipping zero-length ones), with "touches" meaning
29//! [`segment_intersects`] against the tile's buffered box, a run of tile `t` is the vertex range of
30//! segments `k..=e` where
31//! - `k` touches `t`, but neither `k - 1` nor `k - 2` does ([`Prev::run_started`]: the run starts
32//!   there, and only there, so each run is yielded once, at its first segment), and
33//! - the run ends at the first `e` after which neither `e + 1` nor `e + 2` touches `t`
34//!   ([`extend_run`]: one missed segment is bridged, keeping both its endpoints).
35//!
36//! [`LineSlices`] finds each `k` while walking the segments in order, [`TileLines`] by scanning the
37//! line for one tile, and both extend with the same [`extend_run`], so they agree by construction.
38//!
39//! In [`ClipMode::Unclipped`] the same walk and scan decide which tiles a geometry reaches, but each
40//! such tile gets the whole geometry, once: no run is extended and no polygon piece is built.
41
42use core::iter::FusedIterator;
43use std::collections::BTreeSet;
44
45use geo_types::Coord;
46
47use crate::TileError;
48use crate::clip_polyline::segment_intersects;
49use crate::grid::{Grid, Located, SegmentTiles};
50use crate::polygon::{
51    FillRun, PolygonPiece, PolygonSlices, Scratch, clip_polygon_to_tile, fill_ring, whole_polygon_in_tile,
52};
53use crate::tile::TileId;
54use crate::vertex::{PolyVertex, Vertex};
55
56/// How a [`Slicer`] cuts lines and polygons into the tiles they reach (points are never cut, so they
57/// ignore it).
58///
59/// Every mode slices the same inputs to the same tiles, with one difference in failures: a clipped
60/// slicer can still fail building a piece too large to index (`GeometryTooLarge`) where an
61/// unclipped one, which builds nothing, succeeds.
62#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
63#[non_exhaustive]
64pub enum ClipMode {
65    /// Each tile gets only the part of the geometry that touches its buffered box: a line's runs, a
66    /// polygon's piece (with synthetic corners), or a [`FillRun`] for tiles it covers entirely. A
67    /// piece of a valid polygon is itself a valid polygon (OGC), beyond the buffered box too, so it
68    /// can be used on its own; best effort, see the crate docs.
69    #[default]
70    Clipped,
71    /// Each tile the geometry reaches - exactly the tiles [`Clipped`](Self::Clipped) gives anything -
72    /// gets the **whole** geometry, once, in that tile's local frame: a line as a single
73    /// [`LineSlice`] of all its vertices, a polygon as a [`PolygonPiece`] of all its rings (also in
74    /// every tile it covers entirely: no [`FillRun`] is yielded). For renderers that clip themselves.
75    Unclipped,
76}
77
78/// Slices one geometry at a time into per-tile pieces on an integer grid, lazily.
79///
80/// Coordinates are integers in tile space: a vertex belongs to tile `x.div_euclid(extent)`, whose own
81/// area is `[0, extent)` in its local frame (`x - tile·extent`); every tile's clip box grows `buffer`
82/// on each side. Slices come in that local frame, so a vertex outside the tile's own area - in its
83/// buffer, a polygon's synthetic corner one unit past the buffer, or a line's first vertex beyond the
84/// box - lies outside `[0, extent)`. Project, simplify, and scale float source data into this space
85/// before slicing.
86///
87/// Generic over the [`Vertex`] type `V` (defaults to [`Coord<i32>`]): plain coordinates or
88/// payload-carrying vertices (e.g. a per-vertex M value via [`Measured`](crate::Measured)), whose
89/// payload rides through slicing unchanged.
90///
91/// The slicer never panics: bad input yields a [`TileError`] from the call itself (and, for a polygon
92/// piece too large to index, as an `Err` item that ends the iteration).
93///
94/// Lines and polygons are clipped to each tile unless the slicer is built
95/// [`with_clip_mode`](Self::with_clip_mode)`(`[`ClipMode::Unclipped`]`)`, which gives each tile the
96/// whole geometry instead.
97///
98/// Lines and points take `&self`, so one slicer can serve many threads. Polygons take `&mut self`:
99/// they are sliced in the slicer's reusable working memory, so use one slicer per worker.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Slicer<V: Vertex = Coord<i32>> {
102    grid: Grid,
103    mode: ClipMode,
104    /// Working memory for polygon slicing, allocated by the first polygon and kept for its capacity
105    /// (never part of the slicer's value).
106    poly: Scratch<V>,
107}
108
109impl<V: Vertex> Slicer<V> {
110    /// Create a slicer with the given tile side / per-tile output resolution `extent` and `buffer`.
111    ///
112    /// # Errors
113    ///
114    /// - [`TileError::InvalidExtent`] if `extent` is `0`, or `extent + buffer` exceeds `i32::MAX`.
115    /// - [`TileError::BufferTooLarge`] if `buffer` is not strictly less than half the `extent`.
116    pub fn new(extent: u32, buffer: u16) -> Result<Self, TileError> {
117        Ok(Self {
118            grid: Grid::new(extent, buffer)?,
119            mode: ClipMode::Clipped,
120            poly: Scratch::new(),
121        })
122    }
123
124    /// This slicer, cutting lines and polygons by `mode` ([`ClipMode::Clipped`] by default).
125    #[must_use]
126    pub fn with_clip_mode(mut self, mode: ClipMode) -> Self {
127        self.mode = mode;
128        self
129    }
130
131    /// How this slicer cuts lines and polygons.
132    #[must_use]
133    pub fn clip_mode(&self) -> ClipMode {
134        self.mode
135    }
136
137    /// The tile side / per-tile output resolution: a tile's own area is `0..extent` in its local
138    /// frame (its buffer and kept vertices beyond it lie outside).
139    #[must_use]
140    pub fn extent(&self) -> u32 {
141        self.grid.extent()
142    }
143
144    /// The buffer kept around every tile, in tile-space units.
145    #[must_use]
146    pub fn buffer(&self) -> u16 {
147        self.grid.buffer()
148    }
149
150    /// Release the working memory the slicer keeps between features. It only ever grows to what the
151    /// largest polygon row or piece needed, but after an outlier a long-lived slicer would otherwise
152    /// hold that peak forever.
153    pub fn shrink_to_fit(&mut self) {
154        self.poly = Scratch::new();
155    }
156
157    /// Slice a line into every tile it touches.
158    ///
159    /// Yields one [`LineSlice`] per run, in no particular order. A line that leaves a tile and comes
160    /// back gives that tile several items. Consecutive duplicate vertices are skipped. For a
161    /// multi-line, call this for each of its lines.
162    ///
163    /// [`ClipMode::Unclipped`] yields one item per tile instead, its run the whole line; telling a
164    /// tile's later runs apart costs a set of the tiles yielded so far (memory proportional to
165    /// their number, and several times the instructions of a clipped walk over a long diagonal
166    /// line, where nearly every run starts a new tile).
167    ///
168    /// The call reads every vertex once to bound the line, so that nothing can fail once the
169    /// iteration starts; the slices themselves are still computed one at a time as it advances.
170    ///
171    /// # Errors
172    ///
173    /// [`TileError::Overflow`] if the line lies too close to the `i32` limits for this `extent` and
174    /// `buffer`: a tile box beyond `i32`, or a vertex more than an `i32` span from the origin of a
175    /// tile its bounding box reaches. (So a line spanning more than `2^31` units on one axis is
176    /// rejected whole, even if each run would fit its tile.)
177    pub fn line<'a>(&self, line: &'a [V]) -> Result<LineSlices<'a, V>, TileError> {
178        if let Some((lo, hi)) = bounds(line) {
179            self.grid.check_bounds(lo, hi)?;
180        }
181        Ok(LineSlices {
182            grid: self.grid,
183            pts: line,
184            cursor: None,
185            seen: (self.mode == ClipMode::Unclipped).then(BTreeSet::new),
186        })
187    }
188
189    /// Clip a line to one `tile`: yields its runs there, each in walk order - exactly the runs
190    /// [`line`](Self::line) yields for that tile. [`ClipMode::Unclipped`] yields the whole line
191    /// once if it reaches the tile, stopping the scan there.
192    ///
193    /// Like [`line`](Self::line), the call reads every vertex once; a line whose bounds miss the
194    /// tile's buffered box yields nothing without being scanned.
195    ///
196    /// # Errors
197    ///
198    /// [`TileError::Overflow`] if `tile`'s buffered box overflows `i32` (a tile far outside the
199    /// representable range for this `extent`), or if the line reaches the tile but has a vertex more
200    /// than an `i32` span from the tile origin.
201    pub fn tile_line<'a>(&self, tile: TileId, line: &'a [V]) -> Result<TileLines<'a, V>, TileError> {
202        let (min, max) = self.grid.tile_buffered_bounds(tile)?;
203        let origin = self.grid.origin_of(min);
204        let mut next = 0;
205        match bounds(line) {
206            Some((lo, hi)) if hi.x >= min.x && lo.x <= max.x && hi.y >= min.y && lo.y <= max.y => {
207                // The line reaches the tile: every vertex must fit the local frame.
208                let fits = |p: Coord<i32>| p.x.checked_sub(origin.x).is_some() && p.y.checked_sub(origin.y).is_some();
209                if !fits(lo) || !fits(hi) {
210                    return Err(TileError::Overflow);
211                }
212            }
213            // Nothing to scan: no vertices, or none near the tile.
214            _ => next = line.len(),
215        }
216        Ok(TileLines {
217            min,
218            max,
219            origin,
220            tile,
221            pts: line,
222            next,
223            whole: self.mode == ClipMode::Unclipped,
224        })
225    }
226
227    /// Slice a point into every tile whose buffered box holds it: its own tile, plus up to three
228    /// neighbors when it lies within `buffer` of an edge. Yields one [`PointSlice`] per tile. For a
229    /// multi-point, call this for each of its points. The [`ClipMode`] does not apply.
230    ///
231    /// # Errors
232    ///
233    /// [`TileError::Overflow`] if one of those tiles has a buffered box beyond `i32`.
234    pub fn point(&self, point: V) -> Result<PointSlices<V>, TileError> {
235        let p = point.position();
236        self.grid.check_tiles(p, p)?;
237        Ok(PointSlices::new(self.grid, point))
238    }
239
240    /// The `point` in `tile`'s local frame, if the tile's buffered box holds it.
241    ///
242    /// # Errors
243    ///
244    /// [`TileError::Overflow`] if `tile`'s buffered box overflows `i32`.
245    pub fn tile_point(&self, tile: TileId, point: V) -> Result<Option<V>, TileError> {
246        let (extent, buffer) = (i64::from(self.grid.extent()), i64::from(self.grid.buffer()));
247        let p = point.position();
248        // Per axis: the tile's buffered box `[base - buffer, base + extent - 1 + buffer]`, which must fit
249        // `i32` (what `Grid::tile_buffered_bounds` checks), and the point's offset from its base.
250        let axis = |tile: i32, v: i32| {
251            let base = i64::from(tile) * extent;
252            let (lo, hi) = (base - buffer, base + extent - 1 + buffer);
253            if lo < i64::from(i32::MIN) || hi > i64::from(i32::MAX) {
254                return Err(TileError::Overflow);
255            }
256            let v = i64::from(v);
257            // Inside the box, so within `extent + buffer` of the base: the offset fits `i32`.
258            #[expect(clippy::cast_possible_truncation, reason = "within the box, see above")]
259            Ok((lo..=hi).contains(&v).then_some((v - base) as i32))
260        };
261        let (x, y) = (axis(tile.x, p.x)?, axis(tile.y, p.y)?);
262        Ok(x.zip(y).map(|(x, y)| point.with_position(Coord { x, y })))
263    }
264}
265
266impl<V: PolyVertex> Slicer<V> {
267    /// Slice a polygon into every tile it reaches. `rings` are its rings - the exterior first, then
268    /// the holes - each open or closed (a repeated first/last vertex is fine). Rings with fewer than
269    /// 3 vertices once consecutive duplicates are dropped are ignored, and so is a polygon whose
270    /// exterior is. For a multipolygon, call this for each of its polygons.
271    ///
272    /// Yields a [`PolygonPiece`] for every tile a ring edge touches (its
273    /// **edge tiles**), exactly what [`tile_polygon`](Self::tile_polygon) yields there, and a
274    /// [`FillRun`] for every row span of tiles the polygon covers entirely. Output
275    /// rings keep the winding of the input rings (see [`signed_area_2x`](crate::signed_area_2x) to
276    /// normalize it first).
277    ///
278    /// [`ClipMode::Unclipped`] yields the same tiles, but each - those of the fill runs too, one by
279    /// one - as a piece of the whole polygon: every kept ring, lent from the input. No piece is built.
280    ///
281    /// Lazy and lending: see [`PolygonSlices`]. The call reads the rings once, to bound and index
282    /// them (only a ring with consecutive duplicate vertices is copied, to drop them); after that the
283    /// iterator holds one tile row of the polygon at a time, and builds each piece as it is reached.
284    /// Every row of the polygon's bounding box is visited, including rows where it yields nothing;
285    /// [`PolygonSlices::within`] limits the slices, and the rows visited, to a window of tiles.
286    ///
287    /// # Errors
288    ///
289    /// - [`TileError::Overflow`] if the polygon lies too close to the `i32` limits for this `extent`
290    ///   and `buffer`: a tile box (grown one unit, for the synthetic corners) beyond `i32`, or a
291    ///   vertex more than an `i32` span from the origin of a tile its bounding box reaches.
292    /// - [`TileError::GeometryTooLarge`] if there are more than `u32::MAX` rings or edges.
293    ///
294    /// The only error left for the iterator is a piece of more than `u32::MAX` vertices.
295    #[inline]
296    pub fn polygon<'s, R: AsRef<[V]>>(&'s mut self, rings: &'s [R]) -> Result<PolygonSlices<'s, V, R>, TileError> {
297        PolygonSlices::new(self.grid, self.mode, rings, self.poly.get())
298    }
299
300    /// Clip a polygon to one `tile`: its piece there, or `None` if it leaves nothing - what
301    /// [`polygon`](Self::polygon) yields for that tile, with a covered tile's
302    /// [`FillRun`] as its fill ring. The piece borrows the slicer's working memory
303    /// until the next call. [`ClipMode::Unclipped`] gives the whole polygon instead, if it leaves
304    /// anything in the tile, as [`polygon`](Self::polygon) does.
305    ///
306    /// # Errors
307    ///
308    /// - [`TileError::Overflow`] if `tile`'s buffered box overflows `i32`, or a synthetic corner or
309    ///   kept vertex does.
310    /// - [`TileError::GeometryTooLarge`] if there are more than `u32::MAX` rings, or the piece has
311    ///   more than `u32::MAX` vertices.
312    #[inline]
313    pub fn tile_polygon<'s, R: AsRef<[V]>>(
314        &'s mut self,
315        tile: TileId,
316        rings: &'s [R],
317    ) -> Result<Option<PolygonPiece<'s, V, R>>, TileError> {
318        u32::try_from(rings.len()).map_err(|_too_large| TileError::GeometryTooLarge)?;
319        let s = &mut self.poly.get().scratch;
320        match self.mode {
321            ClipMode::Clipped => clip_polygon_to_tile(self.grid, tile, rings, s),
322            ClipMode::Unclipped => whole_polygon_in_tile(self.grid, tile, rings, s),
323        }
324    }
325
326    /// The ring [`tile_polygon`](Self::tile_polygon) yields for `run`'s polygon in each tile of the
327    /// run: the tile's buffered box grown by one unit, tile-local and closed (its first vertex
328    /// repeated), all synthetic vertices, wound like the polygon's exterior. See also
329    /// [`PolygonSlices::fill_ring`], for use while the iterator borrows the slicer.
330    #[must_use]
331    pub fn fill_ring(&self, run: &FillRun) -> [V; 5] {
332        fill_ring(self.grid, run)
333    }
334}
335
336/// Vertices in a tile's local frame - `v - origin`, computed as they are read - every position checked
337/// to fit `i32` before the slice is handed out.
338///
339/// A line run is lent from the caller's input, and skips consecutive duplicate positions (the first
340/// of each is kept). A polygon ring has no consecutive duplicates, and is closed: its first vertex
341/// repeated at the end, which a ring lent open has [`iter`](Self::iter) append (drop it for an MVT
342/// `ClosePath`). It is lent from the input when the polygon lies inside one tile, when it is one small
343/// ring inside the tile's buffered box, or when the slicer is [`ClipMode::Unclipped`]; else built in
344/// the slicer's working memory, clipped and with synthetic corners.
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346pub struct Local<'a, V> {
347    verts: &'a [V],
348    origin: Coord<i32>,
349    shape: Shape,
350}
351
352/// What [`Local::iter`] does besides subtracting the origin.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354enum Shape {
355    /// A line run: skip consecutive duplicates.
356    Run,
357    /// A distinct ring that is already closed.
358    Ring,
359    /// A distinct ring lent open: repeat its first vertex at the end.
360    OpenRing,
361}
362
363impl<'a, V: Vertex> Local<'a, V> {
364    /// A line run, lent as it is.
365    pub(crate) fn run(verts: &'a [V], origin: Coord<i32>) -> Self {
366        Self {
367            verts,
368            origin,
369            shape: Shape::Run,
370        }
371    }
372
373    /// A polygon ring (distinct vertices), closed by `iter` unless it `is_closed` already.
374    pub(crate) fn ring(verts: &'a [V], origin: Coord<i32>, is_closed: bool) -> Self {
375        Self {
376            verts,
377            origin,
378            shape: if is_closed { Shape::Ring } else { Shape::OpenRing },
379        }
380    }
381
382    /// The vertices in the tile's local frame.
383    #[must_use]
384    #[inline]
385    pub fn iter(&self) -> LocalIter<'a, V> {
386        LocalIter {
387            verts: self.verts.iter(),
388            origin: self.origin,
389            dedupe: self.shape == Shape::Run,
390            last: None,
391            closing: if self.shape == Shape::OpenRing {
392                self.verts.first()
393            } else {
394                None
395            },
396        }
397    }
398
399    /// The vertices collected into a `Vec`, in the tile's local frame.
400    #[must_use]
401    pub fn to_vec(self) -> Vec<V> {
402        self.iter().collect()
403    }
404
405    /// The vertices in the **global** frame: each local vertex plus [`origin`](Self::origin),
406    /// consecutive duplicates included. For a line run this is a subslice of the input line, so its
407    /// position in the line tells which vertices the run covers; for a clipped polygon ring it is the
408    /// slicer's built ring. For a ring lent open this is without the repeated first vertex.
409    #[must_use]
410    pub fn global(&self) -> &'a [V] {
411        self.verts
412    }
413
414    /// The tile origin (`tile · extent`) the local frame is relative to.
415    #[must_use]
416    pub fn origin(&self) -> Coord<i32> {
417        self.origin
418    }
419}
420
421impl<'a, V: Vertex> IntoIterator for &Local<'a, V> {
422    type Item = V;
423    type IntoIter = LocalIter<'a, V>;
424
425    fn into_iter(self) -> Self::IntoIter {
426        self.iter()
427    }
428}
429
430impl<'a, V: Vertex> IntoIterator for Local<'a, V> {
431    type Item = V;
432    type IntoIter = LocalIter<'a, V>;
433
434    fn into_iter(self) -> Self::IntoIter {
435        self.iter()
436    }
437}
438
439/// Iterator over a [`Local`]'s vertices.
440#[derive(Debug, Clone)]
441pub struct LocalIter<'a, V> {
442    verts: core::slice::Iter<'a, V>,
443    origin: Coord<i32>,
444    /// Whether to skip consecutive duplicates, and the last position seen if so.
445    dedupe: bool,
446    last: Option<Coord<i32>>,
447    /// The vertex that closes the ring, once the rest is done.
448    closing: Option<&'a V>,
449}
450
451impl<V: Vertex> LocalIter<'_, V> {
452    /// `v` in the local frame (checked to fit before the slice was yielded).
453    #[inline]
454    fn local(&self, v: V) -> V {
455        let p = v.position();
456        v.with_position(Coord {
457            x: p.x.wrapping_sub(self.origin.x),
458            y: p.y.wrapping_sub(self.origin.y),
459        })
460    }
461}
462
463impl<V: Vertex> Iterator for LocalIter<'_, V> {
464    type Item = V;
465
466    #[inline]
467    fn next(&mut self) -> Option<V> {
468        for &v in self.verts.by_ref() {
469            if self.dedupe {
470                let p = v.position();
471                if self.last == Some(p) {
472                    continue;
473                }
474                self.last = Some(p);
475            }
476            return Some(self.local(v));
477        }
478        let closing = *self.closing.take()?;
479        Some(self.local(closing))
480    }
481
482    fn size_hint(&self) -> (usize, Option<usize>) {
483        let closing = usize::from(self.closing.is_some());
484        let left = self.verts.len();
485        // Skipped duplicates make a run shorter, but never empty while vertices are left.
486        let low = if self.dedupe { usize::from(left > 0) } else { left };
487        (low + closing, Some(left + closing))
488    }
489}
490
491impl<V: Vertex> FusedIterator for LocalIter<'_, V> {}
492
493/// One run of a line in one tile: a contiguous piece of it, in the tile's local frame.
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
495pub struct LineSlice<'a, V> {
496    tile: TileId,
497    run: Local<'a, V>,
498}
499
500impl<'a, V: Vertex> LineSlice<'a, V> {
501    /// The tile this run belongs to.
502    #[must_use]
503    pub fn tile(&self) -> TileId {
504        self.tile
505    }
506
507    /// The run's vertices, in the tile's local frame (at least two distinct positions): the whole line
508    /// when [`ClipMode::Unclipped`].
509    #[must_use]
510    pub fn run(&self) -> Local<'a, V> {
511        self.run
512    }
513}
514
515/// The index of the first vertex after `i` at a different position, if any.
516fn next_distinct<V: Vertex>(pts: &[V], i: usize) -> Option<usize> {
517    let p = pts.get(i)?.position();
518    (i + 1..pts.len()).find(|&j| pts[j].position() != p)
519}
520
521/// The bounding box `(lo, hi)` of every vertex of `pts`, or `None` if there is none. One pass, which
522/// is what lets the iterators skip every per-vertex overflow check afterwards.
523fn bounds<V: Vertex>(pts: &[V]) -> Option<(Coord<i32>, Coord<i32>)> {
524    let (mut lo, mut hi) = (
525        Coord {
526            x: i32::MAX,
527            y: i32::MAX,
528        },
529        Coord {
530            x: i32::MIN,
531            y: i32::MIN,
532        },
533    );
534    for v in pts {
535        let p = v.position();
536        (lo.x, lo.y) = (lo.x.min(p.x), lo.y.min(p.y));
537        (hi.x, hi.y) = (hi.x.max(p.x), hi.y.max(p.y));
538    }
539    (lo.x <= hi.x).then_some((lo, hi))
540}
541
542/// Extend a run that has reached vertex `end` (inside the line `pts`) while the next segment, or the one
543/// after it (a single-segment excursion out and back), touches the box `[min, max]`. Returns the
544/// run's last vertex index.
545fn extend_run<V: Vertex>(pts: &[V], mut end: usize, min: Coord<i32>, max: Coord<i32>) -> usize {
546    while let Some(n1) = next_distinct(pts, end) {
547        let (a, b) = (pts[end].position(), pts[n1].position());
548        if segment_intersects(a, b, min, max) {
549            end = n1;
550            continue;
551        }
552        let Some(n2) = next_distinct(pts, n1) else {
553            break;
554        };
555        if segment_intersects(b, pts[n2].position(), min, max) {
556            end = n2;
557            continue;
558        }
559        break;
560    }
561    end
562}
563
564/// A segment, as its two endpoints.
565type Segment = (Coord<i32>, Coord<i32>);
566
567/// The two segments before the current one in the line, most recent first.
568#[derive(Debug, Clone, Copy, Default)]
569struct Prev([Option<Segment>; 2]);
570
571impl Prev {
572    /// `self` after `seg`, the segment just left, joins it.
573    #[inline]
574    fn pushed(self, seg: Segment) -> Self {
575        Self([Some(seg), self.0[0]])
576    }
577
578    /// Whether the previous segment touches the box `[min, max]`: the current one only continues its
579    /// run there.
580    #[inline]
581    fn continues(self, min: Coord<i32>, max: Coord<i32>) -> bool {
582        self.0[0].is_some_and(|(a, b)| segment_intersects(a, b, min, max))
583    }
584
585    /// Whether a run in the box `[min, max]` already started before the current segment: the previous
586    /// one continues it, and the one before bridges a single missed segment (see [`extend_run`]).
587    #[expect(
588        clippy::inline_always,
589        reason = "run per tile of a walk; left out of line it costs the line benchmarks 3%"
590    )]
591    #[inline(always)]
592    fn run_started(self, min: Coord<i32>, max: Coord<i32>) -> bool {
593        self.0
594            .iter()
595            .flatten()
596            .any(|&(a, b)| segment_intersects(a, b, min, max))
597    }
598}
599
600/// The tiles of the current segment still to be considered.
601#[derive(Debug, Clone)]
602enum SegTiles {
603    /// The whole segment lies in one tile's inner box, so it touches only that tile.
604    One(TileId),
605    /// Any other segment: walked row by row through exactly the tiles it touches.
606    Walk(SegmentTiles),
607    /// Nothing left: every tile is done, or the segment only continues a run already yielded.
608    Done,
609}
610
611/// Position inside a [`LineSlices`] walk.
612#[derive(Debug, Clone)]
613struct LineCursor {
614    /// The current segment, as indices of its two (distinct) vertices.
615    a: usize,
616    c: usize,
617    prev: Prev,
618    tiles: SegTiles,
619    /// The tile owning `c`, carried to the next segment's fast-path test.
620    loc_c: Located,
621}
622
623/// Where the next run starts: its tile and buffered box, and its first segment's two vertex indices.
624struct RunAt {
625    tile: TileId,
626    min: Coord<i32>,
627    max: Coord<i32>,
628    first: usize,
629    second: usize,
630}
631
632/// A segment inside one tile's inner box touches only that tile; when the previous segment touches it
633/// too, the segment only continues a run already yielded. So do all the following segments that stay
634/// in that inner box: jump past them at once, with one containment test each, and leave the cursor on
635/// the last of them with nothing to yield ([`SegTiles::Done`]).
636///
637/// Only the previous segment is consulted, not the one before: a segment that merely bridges to a
638/// run takes the general path in [`LineSlices::next_run`].
639fn skip_inside<V: Vertex>(grid: Grid, pts: &[V], cur: &mut LineCursor) {
640    let loc = cur.loc_c;
641    let (min, max) = grid.box_of(&loc);
642    if !cur.prev.continues(min, max) {
643        return;
644    }
645    while let Some(n) = next_distinct(pts, cur.c) {
646        if !loc.contains_inner(pts[n].position()) {
647            break;
648        }
649        cur.prev = cur.prev.pushed((pts[cur.a].position(), pts[cur.c].position()));
650        (cur.a, cur.c) = (cur.c, n);
651    }
652    cur.tiles = SegTiles::Done;
653}
654
655/// Lazy iterator over the runs of a line in every tile it touches; see [`Slicer::line`].
656#[derive(Debug, Clone)]
657pub struct LineSlices<'a, V> {
658    grid: Grid,
659    pts: &'a [V],
660    cursor: Option<LineCursor>,
661    /// [`ClipMode::Unclipped`]: the tiles already given the whole line.
662    seen: Option<BTreeSet<TileId>>,
663}
664
665impl<V: Vertex> LineSlices<'_, V> {
666    /// Route the segment `a`-`c`, with `la` the tile owning `a`.
667    fn route(&self, a: usize, c: usize, la: Located) -> (SegTiles, Located) {
668        let (pa, pc) = (self.pts[a].position(), self.pts[c].position());
669        if la.contains_inner(pa) && la.contains_inner(pc) {
670            return (SegTiles::One(la.owner), la);
671        }
672        let loc_c = if la.contains_core(pc) {
673            la
674        } else {
675            self.grid.locate_fit(pc)
676        };
677        (SegTiles::Walk(SegmentTiles::new(self.grid, pa, pc)), loc_c)
678    }
679
680    /// Move to the next segment; `false` when there is none.
681    fn advance(&mut self) -> bool {
682        let pts = self.pts;
683        // The next segment: its first vertex, second vertex, the segments before it, and the tile
684        // owning the first vertex if the walk already knows it (everywhere but at the start).
685        let next = match &self.cursor {
686            None => next_distinct(pts, 0).map(|c| (0, c, Prev::default(), None)),
687            Some(cur) => next_distinct(pts, cur.c).map(|c| {
688                let seg = (pts[cur.a].position(), pts[cur.c].position());
689                (cur.c, c, cur.prev.pushed(seg), Some(cur.loc_c))
690            }),
691        };
692        let Some((a, c, prev, known)) = next else {
693            return false;
694        };
695        let la = known.unwrap_or_else(|| self.grid.locate_fit(pts[a].position()));
696        let (tiles, loc_c) = self.route(a, c, la);
697        let mut cur = LineCursor {
698            a,
699            c,
700            prev,
701            tiles,
702            loc_c,
703        };
704        if matches!(cur.tiles, SegTiles::One(_)) {
705            skip_inside(self.grid, pts, &mut cur);
706        }
707        self.cursor = Some(cur);
708        true
709    }
710
711    /// Where the next run lies, if there is one.
712    #[cfg_attr(feature = "hotpath", hotpath::measure)]
713    fn next_run(&mut self) -> Option<RunAt> {
714        loop {
715            let Some(cur) = &mut self.cursor else {
716                if !self.advance() {
717                    return None;
718                }
719                continue;
720            };
721            // A segment in one tile's inner box touches only that tile, whose box is cached.
722            let (tile, fast) = match &mut cur.tiles {
723                SegTiles::One(tile) => {
724                    let tile = *tile;
725                    cur.tiles = SegTiles::Done;
726                    (Some(tile), true)
727                }
728                SegTiles::Walk(walk) => (walk.next(), false),
729                SegTiles::Done => (None, false),
730            };
731            let Some(tile) = tile else {
732                if !self.advance() {
733                    return None;
734                }
735                continue;
736            };
737            let (min, max) = if fast {
738                self.grid.box_of(&cur.loc_c)
739            } else {
740                self.grid.tile_box(tile)
741            };
742            if cur.prev.run_started(min, max) {
743                continue;
744            }
745            return Some(RunAt {
746                tile,
747                min,
748                max,
749                first: cur.a,
750                second: cur.c,
751            });
752        }
753    }
754}
755
756impl<'a, V: Vertex> Iterator for LineSlices<'a, V> {
757    type Item = LineSlice<'a, V>;
758
759    fn next(&mut self) -> Option<Self::Item> {
760        loop {
761            let at = self.next_run()?;
762            let run = match &mut self.seen {
763                None => &self.pts[at.first..=extend_run(self.pts, at.second, at.min, at.max)],
764                Some(seen) => {
765                    if !seen.insert(at.tile) {
766                        continue; // a later run of a tile that already has the whole line
767                    }
768                    self.pts
769                }
770            };
771            return Some(LineSlice {
772                tile: at.tile,
773                run: Local::run(run, self.grid.origin_of(at.min)),
774            });
775        }
776    }
777}
778
779impl<V: Vertex> FusedIterator for LineSlices<'_, V> {}
780
781/// Lazy iterator over the runs of a line in one tile; see [`Slicer::tile_line`].
782#[derive(Debug, Clone)]
783pub struct TileLines<'a, V> {
784    tile: TileId,
785    min: Coord<i32>,
786    max: Coord<i32>,
787    origin: Coord<i32>,
788    pts: &'a [V],
789    /// The vertex the scan resumes from.
790    next: usize,
791    /// [`ClipMode::Unclipped`]: the first run found is the whole line, and the last.
792    whole: bool,
793}
794
795impl<'a, V: Vertex> Iterator for TileLines<'a, V> {
796    type Item = LineSlice<'a, V>;
797
798    #[cfg_attr(feature = "hotpath", hotpath::measure)]
799    fn next(&mut self) -> Option<Self::Item> {
800        let (pts, min, max) = (self.pts, self.min, self.max);
801        // Find the next segment touching the box; the run starts at its first vertex.
802        let mut a = self.next;
803        while a < pts.len() {
804            let Some(c) = next_distinct(pts, a) else {
805                break;
806            };
807            if segment_intersects(pts[a].position(), pts[c].position(), min, max) {
808                let run = if self.whole {
809                    self.next = pts.len();
810                    pts
811                } else {
812                    let end = extend_run(pts, c, min, max);
813                    self.next = end;
814                    &pts[a..=end]
815                };
816                return Some(LineSlice {
817                    tile: self.tile,
818                    run: Local::run(run, self.origin),
819                });
820            }
821            a = c;
822        }
823        self.next = pts.len();
824        None
825    }
826}
827
828impl<V: Vertex> FusedIterator for TileLines<'_, V> {}
829
830/// One axis of a point's tiles: its own, and the neighbor within `buffer` of an edge (the buffer is
831/// under half a tile, so at most one per axis). The point lies `rem` past its own tile's origin; the
832/// tile at offset `d` from its own (`-1`, `0` or `1`) has the point `rem - d · extent` past its
833/// origin.
834#[derive(Debug, Clone, Copy)]
835struct AxisTiles {
836    /// The point's own tile, and its offset from that tile's origin.
837    tile: i32,
838    rem: i32,
839    /// The first offset `d` (`-1` when the previous tile holds the point too, else `0`), and how many
840    /// tiles there are.
841    first: i32,
842    len: u8,
843}
844
845impl AxisTiles {
846    /// One division. A neighbor needs `buffer > 0`, so `extent >= 3` and the neighbor's index stays in
847    /// `i32`; the offsets fit because [`Slicer::point`] proved the neighbor's whole buffered box does.
848    fn new(v: i32, extent: i32, buffer: i32) -> Self {
849        // Floor division with one `/` and `%` (`div_euclid` + `rem_euclid` would divide twice).
850        let (mut tile, mut rem) = (v / extent, v % extent);
851        if rem < 0 {
852            (tile, rem) = (tile - 1, rem + extent);
853        }
854        // In the first `buffer` units of its tile the point is in the previous tile's buffer, in the
855        // last `buffer` units in the next one's (with `buffer == 0` neither).
856        let (before, after) = (rem < buffer, rem >= extent - buffer);
857        Self {
858            tile,
859            rem,
860            first: -i32::from(before),
861            len: 1 + u8::from(before) + u8::from(after),
862        }
863    }
864}
865
866/// A point in one tile, in the tile's local frame.
867#[derive(Debug, Clone, Copy, PartialEq, Eq)]
868pub struct PointSlice<V> {
869    tile: TileId,
870    point: V,
871}
872
873impl<V: Vertex> PointSlice<V> {
874    /// The tile this point lands in.
875    #[must_use]
876    #[inline]
877    pub fn tile(&self) -> TileId {
878        self.tile
879    }
880
881    /// The point in the tile's local frame: `position - tile · extent`, the payload unchanged.
882    #[must_use]
883    #[inline]
884    pub fn point(&self) -> V {
885        self.point
886    }
887}
888
889/// The tiles a point lands in, with the point in each; see [`Slicer::point`]. One to four items, columns
890/// first, computed with a single division per axis.
891#[derive(Debug, Clone)]
892pub struct PointSlices<V> {
893    point: V,
894    extent: i32,
895    x: AxisTiles,
896    y: AxisTiles,
897    /// The next item, `0..x.len * y.len`.
898    next: u8,
899}
900
901impl<V: Vertex> PointSlices<V> {
902    fn new(grid: Grid, point: V) -> Self {
903        let p = point.position();
904        let (extent, buffer) = (grid.extent_i32(), grid.buffer_i32());
905        Self {
906            point,
907            extent,
908            x: AxisTiles::new(p.x, extent, buffer),
909            y: AxisTiles::new(p.y, extent, buffer),
910            next: 0,
911        }
912    }
913}
914
915impl<V: Vertex> Iterator for PointSlices<V> {
916    type Item = PointSlice<V>;
917
918    fn next(&mut self) -> Option<Self::Item> {
919        if self.next >= self.x.len * self.y.len {
920            return None;
921        }
922        // Columns first: the column is `next / y.len` and the row `next % y.len`, with `y.len` 1 or 2.
923        let shift = self.y.len - 1;
924        let (i, j) = (self.next >> shift, self.next & shift);
925        self.next += 1;
926        let (dx, dy) = (self.x.first + i32::from(i), self.y.first + i32::from(j));
927        Some(PointSlice {
928            tile: TileId::new(self.x.tile + dx, self.y.tile + dy),
929            point: self.point.with_position(Coord {
930                x: self.x.rem - dx * self.extent,
931                y: self.y.rem - dy * self.extent,
932            }),
933        })
934    }
935
936    fn size_hint(&self) -> (usize, Option<usize>) {
937        let left = usize::from(self.x.len * self.y.len - self.next);
938        (left, Some(left))
939    }
940}
941
942impl<V: Vertex> ExactSizeIterator for PointSlices<V> {}
943
944impl<V: Vertex> FusedIterator for PointSlices<V> {}