Skip to main content

dfui_map/
lib.rs

1//! Vector maps for dfui: the app projects its geometry (e.g.
2//! from OpenStreetMap) with a [`MapBuilder`], which packs it into tiled
3//! [`Shape`]s at a few levels of detail, and [`map`] pans and zooms them.
4//! Shapes are stored on the GPU as they come into view, so moving the map
5//! mostly moves the rects they're drawn into.
6
7use std::cell::{Cell, OnceCell};
8use std::collections::HashMap;
9use std::ops::Range;
10use std::rc::Rc;
11use std::time::Duration;
12
13use dfui::path::{CAP_STEPS, Point, Quad, Stroke, stroke};
14use dfui::taffy::{Dimension, Size, Style};
15use dfui::widgets::Styled;
16use dfui::{
17    Color, Element, Event, EventCx, Font, Instant, PaintCx, Path, Rect, Shape, Text, Widget,
18};
19
20/// Most segments in one shape: the shader walks a band's segments per pixel.
21const MAX_QUADS: usize = 128;
22/// Cells aren't split below this side, metres.
23const MIN_CELL: f32 = 16.0;
24/// How far past its cell a tile's geometry is cut, metres, so the cut edge
25/// stays outside the cell's clip and never antialiases into a seam. Exact
26/// while it is half a px or more: from 0.25 px per metre.
27const MARGIN: f32 = 2.0;
28const EARTH_RADIUS: f64 = 6_371_000.0;
29/// Font size, logical px, at which a label starts to show.
30const MIN_LABEL_PX: f32 = 7.0;
31/// Least screen distance between labels with the same text, logical px.
32const LABEL_SPACING_PX: f32 = 300.0;
33/// Sharpest turn between neighbouring glyphs of a label, radians.
34const MAX_LABEL_TURN: f32 = 0.35;
35/// Pointer travel before a press becomes a pan, logical px.
36const SLOP: f32 = 6.0;
37/// Scales, logical px per metre, where a finer level of detail takes over;
38/// from the last one up the map draws at full detail.
39const LEVELS: [f32; 6] = [1.0 / 32.0, 1.0 / 16.0, 1.0 / 8.0, 0.25, 0.5, 1.0];
40const FULL: usize = LEVELS.len();
41/// How far a simplified line may stray, px at the largest scale of its level.
42const TOLERANCE_PX: f32 = 0.25;
43/// Features smaller than this, px, are left out of a level.
44const MIN_FEATURE_PX: f32 = 0.75;
45/// Narrower lines get no caps or bevels in a level, px.
46const JOIN_PX: f32 = 1.5;
47/// Largest tile side, px at the largest scale of its level: a tile costs
48/// every pixel it covers, so a sparse layer (a single bus line) mustn't
49/// spread few segments over a large cell.
50const MAX_CELL_PX: f32 = 256.0;
51/// Scale [`MAX_CELL_PX`] is measured at for full detail, px per metre.
52const FULL_CELL_SCALE: f32 = 4.0;
53/// How long the view takes to move to a new focus or fit.
54const GLIDE: Duration = Duration::from_millis(450);
55/// Time a frame spends storing new tiles before leaving the rest for the
56/// next frames, coarser levels standing in.
57const BUDGET: Duration = Duration::from_millis(4);
58
59/// Collects areas and lines in metres around an origin and packs them into
60/// [`MapData`]. Layers draw in the order they were added.
61pub struct MapBuilder {
62    origin: (f64, f64),
63    cos: f64,
64    layers: Vec<LayerData>,
65    /// One tile each, drawn over every layer.
66    labels: Vec<Tile>,
67    /// Centres of the labels placed so far, by text.
68    placed: HashMap<String, Vec<Point>>,
69}
70
71struct LayerData {
72    color: Color,
73    min_scale: f32,
74    /// Closed rings, outlines wound positive and holes negative, so they
75    /// fill by nonzero winding however they're cut into tiles.
76    rings: Vec<Vec<Point>>,
77    lines: Vec<Run>,
78}
79
80/// A line by its middle, stroked when its tile is drawn.
81#[derive(Clone, Debug, PartialEq)]
82struct Run {
83    points: Vec<Point>,
84    width: f32,
85    /// Round caps at the first and last point; none where a tile cut it.
86    caps: [bool; 2],
87    /// Fill the outside of each bend.
88    bevels: bool,
89}
90
91impl Run {
92    /// The line as outlines, see [`stroke`].
93    fn stroke(&self) -> Vec<Vec<Point>> {
94        let style = Stroke {
95            width: self.width,
96            caps: self.caps,
97            bevels: self.bevels,
98        };
99        stroke(&self.points, style)
100    }
101}
102
103/// One of a [`MapBuilder`]'s layers.
104#[derive(Clone, Copy, Debug)]
105pub struct Layer(usize);
106
107impl MapBuilder {
108    /// A map centred on `lat`, `lon` in degrees.
109    pub fn new(lat: f64, lon: f64) -> Self {
110        MapBuilder {
111            origin: (lat, lon),
112            cos: lat.to_radians().cos(),
113            layers: Vec::new(),
114            labels: Vec::new(),
115            placed: HashMap::new(),
116        }
117    }
118
119    /// `lat`, `lon` in metres east and south of the origin; an
120    /// equirectangular projection, fine for a city.
121    pub fn point(&self, lat: f64, lon: f64) -> Point {
122        let x = (lon - self.origin.1).to_radians() * self.cos * EARTH_RADIUS;
123        let y = (self.origin.0 - lat).to_radians() * EARTH_RADIUS;
124        [x as f32, y as f32]
125    }
126
127    /// A layer drawn in `color`, hidden while zoomed out below `min_scale`
128    /// logical px per metre (0 always shows it).
129    pub fn layer(&mut self, color: Color, min_scale: f32) -> Layer {
130        self.layers.push(LayerData {
131            color,
132            min_scale,
133            rings: Vec::new(),
134            lines: Vec::new(),
135        });
136        Layer(self.layers.len() - 1)
137    }
138
139    /// A filled area, e.g. an OSM multipolygon: `outers` filled, `holes` cut
140    /// out of them. Rings may wind either way.
141    pub fn area(&mut self, layer: Layer, outers: &[Vec<Point>], holes: &[Vec<Point>]) {
142        let rings = &mut self.layers[layer.0].rings;
143        let all = outers.iter().map(|r| (r, true));
144        rings.extend(
145            all.chain(holes.iter().map(|r| (r, false)))
146                .filter_map(|(r, outer)| orient(r.clone(), outer)),
147        );
148    }
149
150    /// A line `width` metres wide through `points`, with round caps and
151    /// bevelled joins.
152    pub fn line(&mut self, layer: Layer, points: &[Point], width: f32) {
153        let mut points = points.to_vec();
154        points.dedup();
155        if points.len() >= 2 {
156            self.layers[layer.0].lines.push(Run {
157                points,
158                width,
159                caps: [true, true],
160                bevels: true,
161            });
162        }
163    }
164
165    /// `s` at `size` metres along the polyline, e.g. a street's name inside
166    /// it: centred, reading left to right, each glyph turned to the line
167    /// under its middle. Shows once `size` reaches 7 logical px on screen and
168    /// the same text placed earlier is 300 px away; false,
169    /// adding nothing, when the text is longer than the line or the line
170    /// bends too sharply under it.
171    pub fn label(
172        &mut self,
173        layer: Layer,
174        points: &[Point],
175        text: &Text,
176        font: Font,
177        s: &str,
178        size: f32,
179    ) -> bool {
180        let mut pts = points.to_vec();
181        pts.dedup();
182        if pts.len() < 2 {
183            return false;
184        }
185        if pts[pts.len() - 1][0] < pts[0][0] {
186            pts.reverse();
187        }
188        let mut along = vec![0.0];
189        for w in pts.windows(2) {
190            along.push(along[along.len() - 1] + (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1]));
191        }
192        let length = along[along.len() - 1];
193        let layout = text.layout(s, font, size, None);
194        if layout.width + size > length {
195            return false;
196        }
197        let start = (length - layout.width) / 2.0;
198        // Point and unit direction at distance `d` along the line.
199        let at = |d: f32| {
200            let i = along.partition_point(|&a| a <= d).clamp(1, pts.len() - 1);
201            let (a, b) = (pts[i - 1], pts[i]);
202            let len = along[i] - along[i - 1];
203            let t = [(b[0] - a[0]) / len, (b[1] - a[1]) / len];
204            let k = d - along[i - 1];
205            ([a[0] + t[0] * k, a[1] + t[1] * k], t)
206        };
207        let mid_y = layout.height / 2.0;
208        let mut contours = Vec::new();
209        let mut last: Option<f32> = None;
210        for g in text.glyph_paths(s, font, size) {
211            let xs = g.contours.iter().flatten().flatten().map(|p| p[0]);
212            let (lo, hi) = xs.fold((f32::MAX, f32::MIN), |(l, h), x| (l.min(x), h.max(x)));
213            let mid_x = (lo + hi) / 2.0;
214            let (o, t) = at(start + mid_x);
215            let angle = t[1].atan2(t[0]);
216            if let Some(a) = last {
217                let turn = (angle - a + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU);
218                if (turn - std::f32::consts::PI).abs() > MAX_LABEL_TURN {
219                    return false;
220                }
221            }
222            last = Some(angle);
223            // Glyph x runs along the line and y (down) to its right.
224            let place = |[x, y]: Point| {
225                let (u, v) = (x - mid_x, y - mid_y);
226                [o[0] + u * t[0] - v * t[1], o[1] + u * t[1] + v * t[0]]
227            };
228            contours.extend(
229                g.contours
230                    .into_iter()
231                    .map(|c| c.into_iter().map(|q| q.map(place)).collect::<Vec<_>>()),
232            );
233        }
234        let glyphs = Path { contours };
235        let Some(view) = bounds(glyphs.contours.iter().flatten().flatten()) else {
236            return false;
237        };
238        let (c, _) = at(length / 2.0);
239        let near = self.placed.entry(s.to_owned()).or_default();
240        let d = near.iter().map(|p| (p[0] - c[0]).hypot(p[1] - c[1]));
241        let spaced = LABEL_SPACING_PX / d.fold(f32::MAX, f32::min);
242        near.push(c);
243        let l = &self.layers[layer.0];
244        let pad = size / 4.0;
245        let cell = Rect::new(
246            view.x - pad,
247            view.y - pad,
248            view.w + 2.0 * pad,
249            view.h + 2.0 * pad,
250        );
251        let min_scale = l.min_scale.max(MIN_LABEL_PX / size).max(spaced);
252        let geo = Geometry {
253            glyphs,
254            ..Geometry::default()
255        };
256        self.labels.push(Tile::new(
257            cell,
258            l.color,
259            min_scale,
260            (layer.0 as u32, LABELS),
261            geo,
262        ));
263        true
264    }
265
266    /// Cuts every layer at each level of detail into quadtree cells of at
267    /// most 128 segments.
268    pub fn build(self) -> MapData {
269        let (mut tiles, mut table) = (Vec::new(), Vec::new());
270        for (i, l) in self.layers.iter().enumerate() {
271            let mut serve = [FULL as u8; FULL + 1];
272            let mut finer = usize::MAX;
273            for level in (level_of(l.min_scale)..=FULL).rev() {
274                let (rings, runs) = detail(l, level);
275                // Not worth a level unless it halves what the finer one draws.
276                let c = cost(&rings, &runs);
277                if c.saturating_mul(2) > finer {
278                    serve[level] = serve[level + 1];
279                    continue;
280                }
281                (serve[level], finer) = (level as u8, c);
282                let lines = runs.iter().flat_map(|r| {
283                    let h = r.width / 2.0;
284                    r.points
285                        .iter()
286                        .flat_map(move |p| [[p[0] - h, p[1] - h], [p[0] + h, p[1] + h]])
287                });
288                let all: Vec<Point> = rings.iter().flatten().copied().chain(lines).collect();
289                if let Some(b) = bounds(all.iter()) {
290                    let from = tiles.len();
291                    split(l, (i as u32, level as u32), b, rings, runs, &mut tiles);
292                    tiles[from..].sort_by(|a, b| a.cell.x.total_cmp(&b.cell.x));
293                }
294            }
295            table.push((l.color, serve));
296        }
297        let full = tiles.iter().filter(|t| t.level == FULL as u32);
298        let bounds = full.map(|t| t.cell).reduce(|a, b| a.union(&b));
299        let mut labels = self.labels;
300        labels.sort_by(|a, b| a.cell.x.total_cmp(&b.cell.x));
301        tiles.extend(labels);
302        MapData::new(tiles, table, bounds.unwrap_or_default(), &[])
303    }
304}
305
306/// Which level draws at `scale`.
307fn level_of(scale: f32) -> usize {
308    LEVELS.iter().filter(|&&s| s <= scale).count()
309}
310
311/// A layer's rings and lines as drawn at `level`: simplified, small features
312/// left out, thin lines without caps or bevels.
313fn detail(l: &LayerData, level: usize) -> (Vec<Vec<Point>>, Vec<Run>) {
314    let Some(&px) = LEVELS.get(level) else {
315        return (l.rings.clone(), l.lines.clone());
316    };
317    let tol = TOLERANCE_PX / px;
318    let big = |pts: &[Point], pad: f32| {
319        bounds(pts.iter()).is_some_and(|b| (b.w.max(b.h) + pad) * px >= MIN_FEATURE_PX)
320    };
321    let rings = l.rings.iter().filter(|r| big(r, 0.0)).filter_map(|r| {
322        let mut closed = r.clone();
323        closed.push(r[0]);
324        let mut s = simplify(&closed, tol);
325        s.pop();
326        let outer = signed_area(r) > 0.0;
327        (s.len() >= 3 && (signed_area(&s) > 0.0) == outer && signed_area(&s) != 0.0).then_some(s)
328    });
329    let runs = l.lines.iter().filter(|r| big(&r.points, r.width)).map(|r| {
330        let fine = r.width * px >= JOIN_PX;
331        Run {
332            points: simplify(&r.points, tol),
333            width: r.width,
334            caps: r.caps.map(|c| c && fine),
335            bevels: r.bevels && fine,
336        }
337    });
338    (rings.collect(), runs.collect())
339}
340
341/// `pts` with the points that move it by no more than `tol` left out
342/// (Douglas–Peucker); the ends stay.
343fn simplify(pts: &[Point], tol: f32) -> Vec<Point> {
344    let n = pts.len();
345    if n < 3 {
346        return pts.to_vec();
347    }
348    let mut keep = vec![false; n];
349    (keep[0], keep[n - 1]) = (true, true);
350    let mut todo = vec![(0, n - 1)];
351    while let Some((a, b)) = todo.pop() {
352        let (mut far, mut most) = (0, tol);
353        for (i, &p) in pts.iter().enumerate().take(b).skip(a + 1) {
354            let d = distance(p, pts[a], pts[b]);
355            if d > most {
356                (far, most) = (i, d);
357            }
358        }
359        if far != 0 {
360            keep[far] = true;
361            todo.extend([(a, far), (far, b)]);
362        }
363    }
364    pts.iter()
365        .zip(keep)
366        .filter(|(_, k)| *k)
367        .map(|(p, _)| *p)
368        .collect()
369}
370
371/// From `p` to the segment `a`–`b`.
372fn distance(p: Point, a: Point, b: Point) -> f32 {
373    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
374    let len2 = dx * dx + dy * dy;
375    let t = match len2 > 0.0 {
376        true => (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len2).clamp(0.0, 1.0),
377        false => 0.0,
378    };
379    (p[0] - a[0] - t * dx).hypot(p[1] - a[1] - t * dy)
380}
381
382/// `ring` wound positive for an outline, negative for a hole; `None` when
383/// it encloses nothing.
384fn orient(mut ring: Vec<Point>, outer: bool) -> Option<Vec<Point>> {
385    let area = signed_area(&ring);
386    if ring.len() < 3 || area == 0.0 {
387        return None;
388    }
389    if (area > 0.0) != outer {
390        ring.reverse();
391    }
392    Some(ring)
393}
394
395/// Twice the ring's area, positive when it winds clockwise on screen (y down).
396fn signed_area(ring: &[Point]) -> f32 {
397    let n = ring.len();
398    (0..n)
399        .map(|i| {
400            let (a, b) = (ring[i], ring[(i + 1) % n]);
401            a[0] * b[1] - b[0] * a[1]
402        })
403        .sum()
404}
405
406fn bounds<'a>(points: impl Iterator<Item = &'a Point>) -> Option<Rect> {
407    let (mut lo, mut hi) = ([f32::MAX; 2], [f32::MIN; 2]);
408    for p in points {
409        lo = [lo[0].min(p[0]), lo[1].min(p[1])];
410        hi = [hi[0].max(p[0]), hi[1].max(p[1])];
411    }
412    (lo[0] <= hi[0]).then(|| Rect::new(lo[0], lo[1], hi[0] - lo[0], hi[1] - lo[1]))
413}
414
415fn grow(r: Rect, by: f32) -> Rect {
416    Rect::new(r.x - by, r.y - by, r.w + 2.0 * by, r.h + 2.0 * by)
417}
418
419/// Segments the shape of these rings and runs will have, roughly.
420fn cost(rings: &[Vec<Point>], runs: &[Run]) -> usize {
421    let lines = runs.iter().map(|r| {
422        let n = r.points.len() - 1;
423        let caps = r.caps.iter().filter(|c| **c).count();
424        4 * n + if r.bevels { 3 * (n - 1) } else { 0 } + caps * (CAP_STEPS + 1)
425    });
426    rings.iter().map(Vec::len).sum::<usize>() + lines.sum::<usize>()
427}
428
429/// One tile for `rings` and `runs` (already cut to `cell` plus [`MARGIN`]),
430/// or four for its quarters while it holds too many segments.
431fn split(
432    l: &LayerData,
433    at: (u32, u32),
434    cell: Rect,
435    rings: Vec<Vec<Point>>,
436    runs: Vec<Run>,
437    tiles: &mut Vec<Tile>,
438) {
439    if rings.is_empty() && runs.is_empty() {
440        return;
441    }
442    let px = LEVELS
443        .get(at.1 as usize)
444        .copied()
445        .unwrap_or(FULL_CELL_SCALE);
446    let side = cell.w.max(cell.h);
447    if (cost(&rings, &runs) <= MAX_QUADS && side * px <= MAX_CELL_PX) || side < MIN_CELL {
448        let geo = Geometry {
449            rings,
450            runs,
451            glyphs: Path::default(),
452        };
453        tiles.push(Tile::new(cell, l.color, l.min_scale, at, geo));
454        return;
455    }
456    let (w, h) = (cell.w / 2.0, cell.h / 2.0);
457    for (i, j) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] {
458        let c = Rect::new(cell.x + i * w, cell.y + j * h, w, h);
459        let m = grow(c, MARGIN);
460        let cut = rings.iter().filter_map(|r| clip(r, m)).collect();
461        // Past the margin by half the width, a segment's outline can't reach it.
462        let pieces = runs.iter().flat_map(|r| cut_run(r, grow(m, r.width / 2.0)));
463        split(l, at, c, cut, pieces.collect(), tiles);
464    }
465}
466
467/// `ring` cut to `r` (Sutherland–Hodgman): for a concave ring the pieces stay
468/// joined along `r`'s edges, by edges that cancel out when filled.
469fn clip(ring: &[Point], r: Rect) -> Option<Vec<Point>> {
470    let b = bounds(ring.iter())?;
471    let inside = b.x >= r.x && b.y >= r.y && b.x + b.w <= r.x + r.w && b.y + b.h <= r.y + r.h;
472    if inside {
473        return Some(ring.to_vec());
474    }
475    let hit = r.intersect(&b);
476    if hit.w <= 0.0 || hit.h <= 0.0 {
477        return None;
478    }
479    let edges = [
480        (0, r.x, 1.0),
481        (0, r.x + r.w, -1.0),
482        (1, r.y, 1.0),
483        (1, r.y + r.h, -1.0),
484    ];
485    let mut out = ring.to_vec();
486    for (axis, at, side) in edges {
487        let keep = |p: Point| (p[axis] - at) * side >= 0.0;
488        let input = std::mem::take(&mut out);
489        for (k, &a) in input.iter().enumerate() {
490            let b = input[(k + 1) % input.len()];
491            if keep(a) {
492                out.push(a);
493            }
494            if keep(a) != keep(b) {
495                let t = (at - a[axis]) / (b[axis] - a[axis]);
496                out.push([a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]);
497            }
498        }
499        if out.is_empty() {
500            return None;
501        }
502    }
503    (out.len() >= 3 && signed_area(&out) != 0.0).then_some(out)
504}
505
506/// The pieces of `run` inside `r`; ends made by the cut get no cap.
507fn cut_run(run: &Run, r: Rect) -> Vec<Run> {
508    let Some(b) = bounds(run.points.iter()) else {
509        return Vec::new();
510    };
511    if b.x >= r.x && b.y >= r.y && b.x + b.w <= r.x + r.w && b.y + b.h <= r.y + r.h {
512        return vec![run.clone()];
513    }
514    let (mut out, mut cur, mut cap) = (Vec::new(), Vec::new(), false);
515    let mut flush = |cur: &mut Vec<Point>, caps: [bool; 2]| {
516        let mut points = std::mem::take(cur);
517        points.dedup();
518        if points.len() >= 2 {
519            out.push(Run {
520                points,
521                caps,
522                ..*run
523            });
524        }
525    };
526    let last = run.points.len() - 2;
527    for (i, w) in run.points.windows(2).enumerate() {
528        let Some((a, z, t0, t1)) = clip_segment(w[0], w[1], r) else {
529            flush(&mut cur, [cap, false]);
530            continue;
531        };
532        if cur.is_empty() {
533            cur.push(a);
534            cap = run.caps[0] && i == 0 && t0 == 0.0;
535        }
536        cur.push(z);
537        if t1 < 1.0 {
538            flush(&mut cur, [cap, false]);
539        } else if i == last {
540            flush(&mut cur, [cap, run.caps[1]]);
541        }
542    }
543    out
544}
545
546/// The part of `a`–`b` inside `r` and where it starts and ends along it
547/// (Liang–Barsky).
548fn clip_segment(a: Point, b: Point, r: Rect) -> Option<(Point, Point, f32, f32)> {
549    let d = [b[0] - a[0], b[1] - a[1]];
550    let (mut t0, mut t1) = (0.0f32, 1.0f32);
551    for (p, q) in [
552        (-d[0], a[0] - r.x),
553        (d[0], r.x + r.w - a[0]),
554        (-d[1], a[1] - r.y),
555        (d[1], r.y + r.h - a[1]),
556    ] {
557        if p == 0.0 {
558            if q < 0.0 {
559                return None;
560            }
561        } else if p < 0.0 {
562            t0 = t0.max(q / p);
563        } else {
564            t1 = t1.min(q / p);
565        }
566    }
567    let at = |t: f32| [a[0] + t * d[0], a[1] + t * d[1]];
568    (t0 <= t1).then(|| (at(t0), at(t1), t0, t1))
569}
570
571/// What a tile draws: areas cut to its cell, lines by their middle and,
572/// for a label, glyph outlines.
573#[derive(Default, Debug, PartialEq)]
574struct Geometry {
575    rings: Vec<Vec<Point>>,
576    runs: Vec<Run>,
577    glyphs: Path,
578}
579
580impl Geometry {
581    /// Everything as one path, lines stroked and cut to `margin`.
582    fn path(&self, margin: Rect) -> Path {
583        let mut stroked = Vec::new();
584        for r in &self.runs {
585            stroked.extend(r.stroke());
586        }
587        let cut = stroked.iter().filter_map(|r| clip(r, margin));
588        let rings = self.rings.iter().cloned().chain(cut);
589        let mut contours: Vec<Vec<Quad>> = rings.flat_map(|r| Path::polygon(&r).contours).collect();
590        contours.extend(self.glyphs.contours.iter().cloned());
591        Path { contours }
592    }
593}
594
595/// The level of label tiles, drawn over every layer at every scale.
596const LABELS: u32 = u32::MAX;
597
598struct Tile {
599    /// What the tile covers and is clipped to when drawn, metres.
600    cell: Rect,
601    color: Color,
602    min_scale: f32,
603    layer: u32,
604    /// Index into [`LEVELS`], [`FULL`], or [`LABELS`].
605    level: u32,
606    /// Set for a built map; a map read from bytes decodes it from `at`.
607    geo: Option<Geometry>,
608    at: Range<usize>,
609    /// The shape and its view box, made on first use.
610    shape: OnceCell<Option<(Shape, Rect)>>,
611    /// Drawn at least once, so its shape is on the GPU.
612    stored: Cell<bool>,
613}
614
615impl Tile {
616    fn new(
617        cell: Rect,
618        color: Color,
619        min_scale: f32,
620        (layer, level): (u32, u32),
621        geo: Geometry,
622    ) -> Tile {
623        Tile {
624            cell,
625            color,
626            min_scale,
627            layer,
628            level,
629            geo: Some(geo),
630            at: 0..0,
631            shape: OnceCell::new(),
632            stored: Cell::new(false),
633        }
634    }
635}
636
637/// Tiles of one layer at one level, or the labels, sorted by their cell's
638/// left edge.
639#[derive(Clone, Debug, Default, PartialEq)]
640struct Group {
641    tiles: Range<usize>,
642    /// The widest cell, to find the tiles that may reach into a view.
643    widest: f32,
644}
645
646/// Geometry ready to draw, from [`MapBuilder::build`] or
647/// [`MapData::from_bytes`]. Make it once and share it, e.g. in the `App`.
648pub struct MapData {
649    /// By layer then level, labels last.
650    tiles: Vec<Tile>,
651    /// Each layer's tiles at each level.
652    layers: Vec<[Group; FULL + 1]>,
653    /// Each layer's color and the level that draws in place of each.
654    table: Vec<(Color, [u8; FULL + 1])>,
655    labels: Group,
656    bounds: Rect,
657    /// What [`MapData::from_bytes`] read; the tiles' geometry lies in it.
658    bytes: &'static [u8],
659}
660
661/// Coordinates are stored on this grid, metres: fine enough at the deepest zoom.
662const GRID: f32 = 0.001;
663
664/// Zigzag varints of grid coordinates, as deltas from the previous point.
665struct Writer {
666    out: Vec<u8>,
667    origin: Point,
668    at: [i64; 2],
669}
670
671impl Writer {
672    fn put(&mut self, v: i64) {
673        let mut u = ((v << 1) ^ (v >> 63)) as u64;
674        while u >= 0x80 {
675            self.out.push(u as u8 | 0x80);
676            u >>= 7;
677        }
678        self.out.push(u as u8);
679    }
680
681    fn grid(&self, p: Point) -> [i64; 2] {
682        let g = |v: f32, o: f32| ((v - o) / GRID).round() as i64;
683        [g(p[0], self.origin[0]), g(p[1], self.origin[1])]
684    }
685
686    fn point(&mut self, p: Point) {
687        let q = self.grid(p);
688        self.put(q[0] - self.at[0]);
689        self.put(q[1] - self.at[1]);
690        self.at = q;
691    }
692
693    fn points(&mut self, pts: &[Point]) {
694        self.put(pts.len() as i64);
695        for &p in pts {
696            self.point(p);
697        }
698    }
699}
700
701struct Reader<'a> {
702    bytes: std::slice::Iter<'a, u8>,
703    origin: Point,
704    at: [i64; 2],
705}
706
707impl Reader<'_> {
708    fn get(&mut self) -> Option<i64> {
709        let (mut u, mut shift) = (0u64, 0);
710        loop {
711            let b = *self.bytes.next()?;
712            u |= u64::from(b & 0x7f) << shift.min(63);
713            if b < 0x80 {
714                return Some((u >> 1) as i64 ^ -((u & 1) as i64));
715            }
716            shift += 7;
717        }
718    }
719
720    fn count(&mut self) -> Option<usize> {
721        usize::try_from(self.get()?).ok()
722    }
723
724    fn pos(&self, q: [i64; 2]) -> Point {
725        [
726            self.origin[0] + q[0] as f32 * GRID,
727            self.origin[1] + q[1] as f32 * GRID,
728        ]
729    }
730
731    fn point(&mut self) -> Option<Point> {
732        self.at = [self.at[0] + self.get()?, self.at[1] + self.get()?];
733        Some(self.pos(self.at))
734    }
735
736    fn points(&mut self) -> Option<Vec<Point>> {
737        (0..self.count()?).map(|_| self.point()).collect()
738    }
739}
740
741/// A tile's geometry, compactly: its rings as counted point lists; its
742/// runs each with a width in grid steps, a flags varint (caps at either
743/// end, bevels) and the points; then the glyph contours, each a count of
744/// quads, its start point and each quad's end point and, for a curve, its
745/// control point. Points are grid steps from the cell's corner, stored as
746/// zigzag varint deltas; a straight glyph edge, whose control point is its
747/// middle, stores none and flags that in the low bit of its first delta.
748fn encode(geo: &Geometry, origin: Point) -> Vec<u8> {
749    let mut w = Writer {
750        out: Vec::new(),
751        origin,
752        at: [0, 0],
753    };
754    w.put(geo.rings.len() as i64);
755    for r in &geo.rings {
756        w.points(r);
757    }
758    w.put(geo.runs.len() as i64);
759    for r in &geo.runs {
760        w.put((r.width / GRID).round() as i64);
761        let flags = [r.caps[0], r.caps[1], r.bevels];
762        w.put(flags.iter().rev().fold(0, |f, &b| f << 1 | i64::from(b)));
763        w.points(&r.points);
764    }
765    w.put(geo.glyphs.contours.len() as i64);
766    for c in &geo.glyphs.contours {
767        w.put(c.len() as i64);
768        w.point(c.first().map_or(origin, |s| s[0]));
769        for &[a, ctl, b] in c {
770            let curve = ctl != [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0];
771            let (e, k) = (w.grid(b), w.grid(ctl));
772            let at = w.at;
773            w.put((e[0] - at[0]) * 2 + i64::from(curve));
774            w.put(e[1] - at[1]);
775            if curve {
776                w.put(k[0] - at[0]);
777                w.put(k[1] - at[1]);
778            }
779            w.at = e;
780        }
781    }
782    w.out
783}
784
785/// The geometry [`encode`] wrote; `None` if `bytes` are truncated.
786fn decode(bytes: &[u8], origin: Point) -> Option<Geometry> {
787    let mut r = Reader {
788        bytes: bytes.iter(),
789        origin,
790        at: [0, 0],
791    };
792    let rings = (0..r.count()?).map(|_| r.points()).collect::<Option<_>>()?;
793    let mut runs = Vec::new();
794    for _ in 0..r.count()? {
795        let width = r.get()? as f32 * GRID;
796        let f = r.get()?;
797        runs.push(Run {
798            width,
799            caps: [f & 1 != 0, f & 2 != 0],
800            bevels: f & 4 != 0,
801            points: r.points()?,
802        });
803    }
804    let mut contours = Vec::new();
805    for _ in 0..r.count()? {
806        let n = r.count()?;
807        r.point()?;
808        let mut quads = Vec::new();
809        for _ in 0..n {
810            let (dx, dy) = (r.get()?, r.get()?);
811            let (a, curve) = (r.pos(r.at), dx & 1 == 1);
812            let e = [r.at[0] + (dx - i64::from(curve)) / 2, r.at[1] + dy];
813            let ctl = match curve {
814                true => {
815                    let k = [r.at[0] + r.get()?, r.at[1] + r.get()?];
816                    r.pos(k)
817                }
818                false => [(a[0] + r.pos(e)[0]) / 2.0, (a[1] + r.pos(e)[1]) / 2.0],
819            };
820            quads.push([a, ctl, r.pos(e)]);
821            r.at = e;
822        }
823        contours.push(quads);
824    }
825    Some(Geometry {
826        rings,
827        runs,
828        glyphs: Path { contours },
829    })
830}
831
832/// Words per tile in the index: cell, min_scale, layer and level, and the
833/// length of its geometry.
834const INDEX_WORDS: usize = 7;
835
836impl MapData {
837    fn new(
838        tiles: Vec<Tile>,
839        table: Vec<(Color, [u8; FULL + 1])>,
840        bounds: Rect,
841        bytes: &'static [u8],
842    ) -> MapData {
843        let mut layers: Vec<[Group; FULL + 1]> = vec![Default::default(); table.len()];
844        let mut labels = Group::default();
845        let span = |g: &mut Group, i: usize| {
846            let r = &mut g.tiles;
847            *r = if r.start == r.end {
848                i..i + 1
849            } else {
850                r.start.min(i)..r.end.max(i + 1)
851            };
852            g.widest = g.widest.max(tiles[i].cell.w);
853        };
854        for (i, t) in tiles.iter().enumerate() {
855            if t.level == LABELS {
856                span(&mut labels, i);
857                continue;
858            }
859            if let Some(l) = layers.get_mut(t.layer as usize) {
860                span(&mut l[(t.level as usize).min(FULL)], i);
861            }
862        }
863        for (l, (_, serve)) in layers.iter_mut().zip(&table) {
864            *l = serve.map(|k| l[(k as usize).min(FULL)].clone());
865        }
866        MapData {
867            tiles,
868            layers,
869            table,
870            labels,
871            bounds,
872            bytes,
873        }
874    }
875
876    /// The map as [`MapData::from_bytes`] reads it, little-endian: `DFM2`,
877    /// the bounds as four f32; a u32 count of layers and for each its color
878    /// as four f32 and a u32 of the level drawn in place of each, four bits
879    /// a level; a u32 count of tiles and for each its cell as four f32,
880    /// min_scale, a u32 of its layer and (high byte, 255 for labels) level
881    /// and a u32 length of its geometry; then each tile's geometry as
882    /// the crate's `encode` writes it.
883    pub fn to_bytes(&self) -> Vec<u8> {
884        let geos: Vec<Vec<u8>> = self
885            .tiles
886            .iter()
887            .map(|t| match &t.geo {
888                Some(g) => encode(g, [t.cell.x, t.cell.y]),
889                None => self.bytes[t.at.clone()].to_vec(),
890            })
891            .collect();
892        let b = self.bounds;
893        let bits = f32::from_bits;
894        let mut words = vec![b.x, b.y, b.w, b.h, bits(self.table.len() as u32)];
895        for (k, serve) in &self.table {
896            let packed = serve.iter().rev().fold(0, |p, &l| p << 4 | u32::from(l));
897            words.extend([k.r, k.g, k.b, k.a, bits(packed)]);
898        }
899        words.push(bits(self.tiles.len() as u32));
900        for (t, geo) in self.tiles.iter().zip(&geos) {
901            let c = t.cell;
902            let at = t.layer | t.level.min(255) << 24;
903            words.extend([
904                c.x,
905                c.y,
906                c.w,
907                c.h,
908                t.min_scale,
909                bits(at),
910                bits(geo.len() as u32),
911            ]);
912        }
913        let mut out = b"DFM2".to_vec();
914        out.extend(words.iter().flat_map(|w| w.to_le_bytes()));
915        out.extend(geos.concat());
916        out
917    }
918
919    /// A map written by [`MapData::to_bytes`], usually `include_bytes!`d.
920    /// Only the index is read here; each tile is decoded the first time
921    /// it's drawn. `None` if `bytes` aren't one or are truncated.
922    pub fn from_bytes(bytes: &'static [u8]) -> Option<MapData> {
923        let body = bytes.strip_prefix(b"DFM2")?;
924        let word = |i: usize| {
925            let w = body.get(i * 4..i * 4 + 4)?;
926            Some(f32::from_le_bytes(w.try_into().ok()?))
927        };
928        let rect = |i: usize| {
929            Some(Rect::new(
930                word(i)?,
931                word(i + 1)?,
932                word(i + 2)?,
933                word(i + 3)?,
934            ))
935        };
936        let bits = |i: usize| Some(word(i)?.to_bits());
937        let (bounds, layers) = (rect(0)?, bits(4)? as usize);
938        let mut table = Vec::new();
939        for i in (0..layers).map(|i| 5 + i * 5) {
940            let (k, packed) = (rect(i)?, bits(i + 4)?);
941            let color = Color {
942                r: k.x,
943                g: k.y,
944                b: k.w,
945                a: k.h,
946            };
947            let serve: [u8; FULL + 1] = std::array::from_fn(|l| (packed >> (4 * l) & 15) as u8);
948            table.push((color, serve));
949        }
950        let first = 5 + layers.checked_mul(5)? + 1;
951        let n = bits(first - 1)? as usize;
952        let mut at = 4 + (first + n.checked_mul(INDEX_WORDS)?) * 4;
953        let mut tiles = Vec::with_capacity(n.min(bytes.len()));
954        for i in (0..n).map(|i| first + i * INDEX_WORDS) {
955            let (packed, len) = (bits(i + 5)?, bits(i + 6)? as usize);
956            let layer = packed & 0xff_ffff;
957            let level = match packed >> 24 {
958                255 => LABELS,
959                l => l,
960            };
961            tiles.push(Tile {
962                cell: rect(i)?,
963                color: table.get(layer as usize)?.0,
964                min_scale: word(i + 4)?,
965                layer,
966                level,
967                geo: None,
968                at: at..at + len,
969                shape: OnceCell::new(),
970                stored: Cell::new(false),
971            });
972            at += len;
973        }
974        (at <= bytes.len()).then(|| MapData::new(tiles, table, bounds, bytes))
975    }
976
977    /// The tile's shape and view box, made on first use; `None` if it has
978    /// nothing to draw or its bytes are corrupt.
979    fn shape<'a>(&self, t: &'a Tile) -> Option<&'a (Shape, Rect)> {
980        t.shape
981            .get_or_init(|| {
982                let decoded;
983                let geo = match &t.geo {
984                    Some(g) => g,
985                    None => {
986                        decoded = decode(&self.bytes[t.at.clone()], [t.cell.x, t.cell.y])?;
987                        &decoded
988                    }
989                };
990                let path = geo.path(grow(t.cell, MARGIN));
991                let view = bounds(path.contours.iter().flatten().flatten())?;
992                Some((Shape::new(path, view), view))
993            })
994            .as_ref()
995    }
996
997    /// The group's tiles whose cells may overlap `view`.
998    fn near(&self, g: &Group, view: Rect) -> &[Tile] {
999        let tiles = &self.tiles[g.tiles.clone()];
1000        let lo = tiles.partition_point(|t| t.cell.x + g.widest < view.x);
1001        let hi = tiles.partition_point(|t| t.cell.x <= view.x + view.w);
1002        &tiles[lo..hi.max(lo)]
1003    }
1004
1005    /// The tiles across every level, for gauging how heavy a map is.
1006    pub fn tiles(&self) -> usize {
1007        self.tiles.len()
1008    }
1009
1010    /// The segments across all tiles, each 32 bytes on the GPU once drawn.
1011    pub fn segments(&self) -> usize {
1012        let quads = self
1013            .tiles
1014            .iter()
1015            .filter_map(|t| self.shape(t))
1016            .map(|(s, _)| s.path().contours.iter().map(Vec::len).sum::<usize>());
1017        quads.sum()
1018    }
1019}
1020
1021#[derive(Default)]
1022struct View {
1023    /// Metres at the widget's centre.
1024    center: Point,
1025    /// Logical px per metre; 0 until fitted to the widget.
1026    scale: f32,
1027    /// Where the press began and the last pointer position.
1028    press: Option<(Point, Point)>,
1029    panning: bool,
1030    /// The last [`Map::focus`] applied.
1031    focused: Option<(Point, f32)>,
1032    /// The last [`Map::fit`] applied.
1033    fitted: Option<Rect>,
1034    /// A move to a new focus or fit under way.
1035    glide: Option<Glide>,
1036}
1037
1038/// From a centre and scale to another, starting at a time.
1039#[derive(Clone, Copy)]
1040struct Glide {
1041    from: (Point, f32),
1042    to: (Point, f32),
1043    start: Instant,
1044}
1045
1046impl View {
1047    /// Applies a new start, focus or fit: the start at once, the others
1048    /// gliding there from `now`.
1049    fn fit(&mut self, map: &Map, r: Rect, now: Instant) {
1050        let b = map.data.bounds;
1051        let first = self.scale <= 0.0;
1052        if first && b.w > 0.0 {
1053            (self.center, self.scale) = map.start.unwrap_or((
1054                [b.x + b.w / 2.0, b.y + b.h / 2.0],
1055                (r.w / b.w).min(r.h / b.h),
1056            ));
1057        }
1058        let mut to = None;
1059        if map.focus != self.focused {
1060            if let Some((center, scale)) = map.focus {
1061                to = Some((center, self.scale.max(scale)));
1062            }
1063            self.focused = map.focus;
1064        }
1065        if map.fit.is_some() && map.fit != self.fitted {
1066            if let Some(b) = map.fit.filter(|b| b.w > 0.0 && b.h > 0.0) {
1067                to = Some((
1068                    [b.x + b.w / 2.0, b.y + b.h / 2.0],
1069                    (r.w / b.w).min(r.h / b.h),
1070                ));
1071            }
1072            self.fitted = map.fit;
1073        }
1074        match to {
1075            Some(to) if first => (self.center, self.scale) = to,
1076            Some(to) => {
1077                let from = (self.center, self.scale);
1078                self.glide = Some(Glide {
1079                    from,
1080                    to,
1081                    start: now,
1082                });
1083            }
1084            None => {}
1085        }
1086    }
1087
1088    /// Moves along the glide to `now`; true while it hasn't arrived.
1089    fn step(&mut self, now: Instant) -> bool {
1090        let Some(g) = self.glide else { return false };
1091        let t =
1092            (now.saturating_duration_since(g.start).as_secs_f32() / GLIDE.as_secs_f32()).min(1.0);
1093        // Ease in and out (cubic).
1094        let e = if t < 0.5 {
1095            4.0 * t * t * t
1096        } else {
1097            1.0 - (2.0 - 2.0 * t).powi(3) / 2.0
1098        };
1099        let ((c0, s0), (c1, s1)) = (g.from, g.to);
1100        // ponytail: centre lerps while scale moves geometrically, so long hops
1101        // curve slightly; van Wijk–Nuij's zoom path if that ever shows.
1102        self.scale = s0 * (s1 / s0).powf(e);
1103        self.center = [c0[0] + (c1[0] - c0[0]) * e, c0[1] + (c1[1] - c0[1]) * e];
1104        if t >= 1.0 {
1105            self.glide = None;
1106        }
1107        self.glide.is_some()
1108    }
1109
1110    /// Zooms by `k` keeping the metre under `(x, y)` in place.
1111    fn zoom(&mut self, data: &MapData, r: Rect, x: f32, y: f32, k: f32) {
1112        self.glide = None;
1113        let fit = (r.w / data.bounds.w).min(r.h / data.bounds.h);
1114        let to = (self.scale * k).clamp(fit / 4.0, 200.0);
1115        let (dx, dy) = (x - r.x - r.w / 2.0, y - r.y - r.h / 2.0);
1116        let d = 1.0 / self.scale - 1.0 / to;
1117        self.center = [self.center[0] + dx * d, self.center[1] + dy * d];
1118        self.scale = to;
1119    }
1120}
1121/// A pannable, zoomable map of `data`: drag to pan; wheel, ctrl+wheel or
1122/// pinch to zoom. Fills its parent's space by default.
1123pub fn map(data: &Rc<MapData>) -> Map {
1124    Map {
1125        data: data.clone(),
1126        style: Style {
1127            size: Size {
1128                width: Dimension::percent(1.0),
1129                height: Dimension::percent(1.0),
1130            },
1131            ..Style::default()
1132        },
1133        start: None,
1134        focus: None,
1135        fit: None,
1136        on_tap: None,
1137        overlay: None,
1138    }
1139}
1140
1141type TapFn = dyn Fn(&mut EventCx, Point, f32);
1142type OverlayFn = dyn Fn(&mut PaintCx, &dyn Fn(Point) -> Point);
1143
1144/// See [`map`].
1145pub struct Map {
1146    data: Rc<MapData>,
1147    style: Style,
1148    start: Option<(Point, f32)>,
1149    focus: Option<(Point, f32)>,
1150    fit: Option<Rect>,
1151    on_tap: Option<Rc<TapFn>>,
1152    overlay: Option<Rc<OverlayFn>>,
1153}
1154
1155impl Map {
1156    /// Opens centred on `center` (from [`MapBuilder::point`]) at `scale`
1157    /// logical px per metre, instead of fitting the whole map.
1158    pub fn start(mut self, center: Point, scale: f32) -> Self {
1159        self.start = Some((center, scale));
1160        self
1161    }
1162
1163    /// Centres on `center` and zooms in to at least `scale` whenever this
1164    /// differs from the focus of the last build, e.g. to show a search result.
1165    pub fn focus(mut self, focus: Option<(Point, f32)>) -> Self {
1166        self.focus = focus;
1167        self
1168    }
1169
1170    /// Fits `bounds` (in [`MapBuilder::point`] units) to the widget, zooming
1171    /// in or out, whenever they differ from the last build's, e.g. to show
1172    /// one region and then the whole map again.
1173    pub fn fit(mut self, bounds: Rect) -> Self {
1174        self.fit = Some(bounds);
1175        self
1176    }
1177
1178    /// Paints over the map, given a function from map points to logical px,
1179    /// e.g. to draw markers that keep their size while zooming.
1180    pub fn overlay(mut self, f: impl Fn(&mut PaintCx, &dyn Fn(Point) -> Point) + 'static) -> Self {
1181        self.overlay = Some(Rc::new(f));
1182        self
1183    }
1184
1185    /// Runs on a tap that didn't pan or pinch, with the map point under it
1186    /// in [`MapBuilder::point`] metres.
1187    pub fn on_tap(self, f: impl Fn(&mut EventCx, Point) + 'static) -> Self {
1188        self.on_tap_scaled(move |cx, p, _| f(cx, p))
1189    }
1190
1191    /// [`Map::on_tap`], also given the scale in logical px per metre, e.g. to
1192    /// take taps within a few px of a marker.
1193    pub fn on_tap_scaled(mut self, f: impl Fn(&mut EventCx, Point, f32) + 'static) -> Self {
1194        self.on_tap = Some(Rc::new(f));
1195        self
1196    }
1197}
1198
1199impl From<Map> for Element {
1200    fn from(w: Map) -> Self {
1201        Element::new(w)
1202    }
1203}
1204
1205impl Styled for Map {
1206    fn style_mut(&mut self) -> &mut Style {
1207        &mut self.style
1208    }
1209}
1210
1211impl Widget for Map {
1212    fn style(&self) -> Style {
1213        self.style.clone()
1214    }
1215
1216    fn paint(&self, cx: &mut PaintCx) {
1217        let (r, now) = (cx.rect, cx.now);
1218        let v = cx.state.get::<View>();
1219        v.fit(self, r, now);
1220        let gliding = v.step(now);
1221        let (s, c) = (v.scale, v.center);
1222        if gliding {
1223            cx.request_frame();
1224        }
1225        let visible = Rect::new(c[0] - r.w / 2.0 / s, c[1] - r.h / 2.0 / s, r.w / s, r.h / s);
1226        let screen = |b: Rect| {
1227            let x = r.x + r.w / 2.0 + (b.x - c[0]) * s;
1228            let y = r.y + r.h / 2.0 + (b.y - c[1]) * s;
1229            Rect::new(x, y, b.w * s, b.h * s)
1230        };
1231        let data = &*self.data;
1232        let (level, start) = (level_of(s), Instant::now());
1233        let mut pending = false;
1234        let seen = |c: Rect| {
1235            let hit = visible.intersect(&c);
1236            hit.w > 0.0 && hit.h > 0.0
1237        };
1238        let draw = |cx: &mut PaintCx, t: &Tile, clip: Rect| {
1239            if let Some((shape, view)) = data.shape(t) {
1240                cx.with_clip(screen(clip), |cx| cx.shape(shape, screen(*view), t.color));
1241            }
1242            t.stored.set(true);
1243        };
1244        cx.with_clip(r, |cx| {
1245            for levels in &data.layers {
1246                let tiles = data.near(&levels[level], visible);
1247                if tiles.first().is_none_or(|t| s < t.min_scale) {
1248                    continue;
1249                }
1250                let mut holes = Vec::new();
1251                for t in tiles.iter().filter(|t| seen(t.cell)) {
1252                    if t.stored.get() || start.elapsed() < BUDGET {
1253                        draw(cx, t, t.cell);
1254                    } else {
1255                        holes.push(t.cell);
1256                    }
1257                }
1258                if holes.is_empty() {
1259                    continue;
1260                }
1261                pending = true;
1262                // Coarser levels in view, finest first, skipping ones that
1263                // reuse a finer level's tiles.
1264                let mut coarser: Vec<Vec<&Tile>> = Vec::new();
1265                let mut used = vec![levels[level].clone()];
1266                for l in (0..level).rev() {
1267                    if !used.contains(&levels[l]) {
1268                        used.push(levels[l].clone());
1269                        let tiles = data.near(&levels[l], visible);
1270                        coarser.push(tiles.iter().filter(|t| seen(t.cell)).collect());
1271                    }
1272                }
1273                // The finest that has all it needs stored stands in, else the coarsest.
1274                for hole in holes {
1275                    let over = |t: &&&Tile| {
1276                        let hit = t.cell.intersect(&hole);
1277                        hit.w > 0.0 && hit.h > 0.0
1278                    };
1279                    let mut cover: Vec<&Tile> = Vec::new();
1280                    for tiles in &coarser {
1281                        let here: Vec<&Tile> = tiles.iter().filter(over).copied().collect();
1282                        if here.is_empty() {
1283                            continue;
1284                        }
1285                        cover = here;
1286                        if cover.iter().all(|t| t.stored.get()) {
1287                            break;
1288                        }
1289                    }
1290                    for t in cover {
1291                        draw(cx, t, t.cell.intersect(&hole));
1292                    }
1293                }
1294            }
1295            for t in data.near(&data.labels, visible) {
1296                if s < t.min_scale || !seen(t.cell) {
1297                    continue;
1298                }
1299                if t.stored.get() || start.elapsed() < BUDGET {
1300                    draw(cx, t, t.cell);
1301                } else {
1302                    pending = true;
1303                }
1304            }
1305            if let Some(f) = &self.overlay {
1306                let at = |p: Point| {
1307                    [
1308                        r.x + r.w / 2.0 + (p[0] - c[0]) * s,
1309                        r.y + r.h / 2.0 + (p[1] - c[1]) * s,
1310                    ]
1311                };
1312                f(cx, &at);
1313            }
1314        });
1315        if pending {
1316            cx.request_frame();
1317        }
1318    }
1319
1320    fn event(&self, ev: &Event, cx: &mut EventCx) {
1321        let (r, data, now) = (cx.rect, &*self.data, cx.now);
1322        let inside = |x, y| cx.rect.contains(x, y) && cx.clip.contains(x, y);
1323        let (mut capture, mut stop, mut tap) = (false, false, None);
1324        let v = cx.state.get::<View>();
1325        v.fit(self, r, now);
1326        match *ev {
1327            Event::PointerDown { x, y } if inside(x, y) => {
1328                v.press = Some(([x, y], [x, y]));
1329                v.panning = false;
1330            }
1331            Event::PointerMove { x, y } => {
1332                let Some((start, last)) = v.press else { return };
1333                v.panning |= (x - start[0]).hypot(y - start[1]) > SLOP;
1334                if v.panning {
1335                    v.glide = None;
1336                    let s = v.scale;
1337                    v.center = [
1338                        v.center[0] - (x - last[0]) / s,
1339                        v.center[1] - (y - last[1]) / s,
1340                    ];
1341                    v.press = Some((start, [x, y]));
1342                    capture = true;
1343                }
1344            }
1345            Event::PointerUp { x, y } => {
1346                if v.press.take().is_some() && !v.panning && inside(x, y) {
1347                    let s = v.scale;
1348                    let c = v.center;
1349                    let at = [
1350                        c[0] + (x - r.x - r.w / 2.0) / s,
1351                        c[1] + (y - r.y - r.h / 2.0) / s,
1352                    ];
1353                    tap = Some((at, s));
1354                }
1355            }
1356            Event::Cancel => v.press = None,
1357            Event::Wheel { x, y, dy, .. } if inside(x, y) => {
1358                v.zoom(data, r, x, y, (-dy / 200.0).exp());
1359                stop = true;
1360            }
1361            Event::Pinch { x, y, scale } if inside(x, y) || v.press.is_some() => {
1362                v.zoom(data, r, x, y, scale);
1363                // Two fingers held still are a pinch, not a tap.
1364                (v.panning, capture, stop) = (true, true, true);
1365            }
1366            _ => return,
1367        }
1368        if capture {
1369            cx.capture();
1370        }
1371        if stop {
1372            cx.stop();
1373        }
1374        if let (Some((p, s)), Some(f)) = (tap, &self.on_tap) {
1375            f(cx, p, s);
1376        }
1377        cx.request_redraw();
1378    }
1379}
1380
1381#[cfg(test)]
1382mod tests {
1383    use super::*;
1384
1385    fn square(x: f32, y: f32, side: f32) -> Vec<Point> {
1386        vec![[x, y], [x + side, y], [x + side, y + side], [x, y + side]]
1387    }
1388
1389    /// Nonzero winding of `rings` around `p`.
1390    fn covers(rings: &[Vec<Point>], p: Point) -> bool {
1391        let mut w = 0;
1392        for r in rings {
1393            for (k, &a) in r.iter().enumerate() {
1394                let b = r[(k + 1) % r.len()];
1395                let side = (b[0] - a[0]) * (p[1] - a[1]) - (p[0] - a[0]) * (b[1] - a[1]);
1396                if a[1] <= p[1] && b[1] > p[1] && side > 0.0 {
1397                    w += 1;
1398                } else if a[1] > p[1] && b[1] <= p[1] && side < 0.0 {
1399                    w -= 1;
1400                }
1401            }
1402        }
1403        w != 0
1404    }
1405
1406    fn empty() -> Rc<MapData> {
1407        Rc::new(MapData::new(
1408            Vec::new(),
1409            Vec::new(),
1410            Rect::new(0.0, 0.0, 100.0, 100.0),
1411            &[],
1412        ))
1413    }
1414
1415    #[test]
1416    fn lines_and_holes_wind_by_role() {
1417        let mut b = MapBuilder::new(48.0, 11.0);
1418        let l = b.layer(Color::BLACK, 0.0);
1419        let mut hole = square(0.0, 0.0, 5.0);
1420        hole.reverse();
1421        b.area(l, &[square(0.0, 0.0, 10.0)], &[hole]);
1422        b.line(l, &[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]], 2.0);
1423        let signs: Vec<bool> = b.layers[0]
1424            .rings
1425            .iter()
1426            .map(|r| signed_area(r) > 0.0)
1427            .collect();
1428        assert_eq!(signs, [true, false]);
1429        let mut stroked = Vec::new();
1430        stroked.extend(b.layers[0].lines[0].stroke());
1431        // Two caps, two segments and a bevel outside the bend.
1432        assert_eq!(stroked.len(), 5);
1433        assert!(stroked.iter().all(|r| signed_area(r) > 0.0));
1434    }
1435
1436    #[test]
1437    fn clip_cuts_contains_and_drops() {
1438        let sq = square(0.0, 0.0, 10.0);
1439        let half = clip(&sq, Rect::new(5.0, -1.0, 10.0, 12.0)).unwrap();
1440        assert_eq!(signed_area(&half), 100.0);
1441        let inner = clip(&sq, Rect::new(2.0, 2.0, 2.0, 2.0)).unwrap();
1442        assert_eq!(signed_area(&inner), 8.0);
1443        assert!(clip(&sq, Rect::new(20.0, 0.0, 5.0, 5.0)).is_none());
1444    }
1445
1446    #[test]
1447    fn cut_lines_stroke_the_same_inside_the_margin() {
1448        let run = Run {
1449            points: vec![
1450                [-30.0, 5.0],
1451                [12.0, 18.0],
1452                [3.0, 26.0],
1453                [40.0, 31.0],
1454                [9.0, -20.0],
1455            ],
1456            width: 6.0,
1457            caps: [true, true],
1458            bevels: true,
1459        };
1460        let margin = Rect::new(0.0, 0.0, 30.0, 30.0);
1461        let pieces = cut_run(&run, grow(margin, run.width / 2.0));
1462        assert!(pieces.len() > 1);
1463        assert!(
1464            pieces.iter().all(|p| p.caps == [false, false]),
1465            "every end is a cut"
1466        );
1467        let (mut whole, mut cut) = (Vec::new(), Vec::new());
1468        whole.extend(run.stroke());
1469        for p in &pieces {
1470            cut.extend(p.stroke());
1471        }
1472        let cut: Vec<_> = cut.iter().filter_map(|r| clip(r, margin)).collect();
1473        for i in 0..60 {
1474            for j in 0..60 {
1475                let p = [0.25 + i as f32 * 0.5, 0.25 + j as f32 * 0.5];
1476                assert_eq!(covers(&whole, p), covers(&cut, p), "at {p:?}");
1477            }
1478        }
1479        let inside = cut_run(&run, Rect::new(-100.0, -100.0, 200.0, 200.0));
1480        assert_eq!(inside, [run]);
1481    }
1482
1483    #[test]
1484    fn simplify_keeps_the_ends_and_the_corners() {
1485        let pts = [[0.0, 0.0], [5.0, 0.1], [10.0, 0.0], [10.0, 10.0]];
1486        assert_eq!(
1487            simplify(&pts, 0.25),
1488            [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]
1489        );
1490        assert_eq!(simplify(&pts, 0.05), pts);
1491    }
1492
1493    #[test]
1494    fn coarse_levels_are_lighter() {
1495        let mut b = MapBuilder::new(48.0, 11.0);
1496        let l = b.layer(Color::BLACK, 0.0);
1497        let wiggle: Vec<Point> = (0..400)
1498            .map(|i| [i as f32 * 5.0, (i % 2) as f32 * 0.5])
1499            .collect();
1500        b.line(l, &wiggle, 3.0);
1501        b.area(l, &[square(0.0, 50.0, 2.0)], &[]);
1502        let data = b.build();
1503        let weight = |level: usize| {
1504            let tiles = &data.tiles[data.layers[0][level].tiles.clone()];
1505            let shapes = tiles.iter().filter_map(|t| data.shape(t));
1506            shapes
1507                .map(|(s, _)| s.path().contours.iter().map(Vec::len).sum::<usize>())
1508                .sum::<usize>()
1509        };
1510        assert!(
1511            weight(0) * 10 < weight(FULL),
1512            "{} vs {}",
1513            weight(0),
1514            weight(FULL)
1515        );
1516        let coarse = &data.tiles[data.layers[0][0].tiles.clone()];
1517        let geo = coarse.iter().map(|t| t.geo.as_ref().unwrap());
1518        assert!(
1519            geo.clone().all(|g| g.rings.is_empty()),
1520            "the 2 m square is too small"
1521        );
1522        assert!(
1523            geo.flat_map(|g| &g.runs)
1524                .all(|r| r.caps == [false, false] && !r.bevels)
1525        );
1526        assert_eq!(
1527            (level_of(0.01), level_of(0.25), level_of(5.0)),
1528            (0, 4, FULL)
1529        );
1530    }
1531
1532    #[test]
1533    fn dense_layers_split_into_small_tiles() {
1534        let mut b = MapBuilder::new(48.0, 11.0);
1535        let l = b.layer(Color::BLACK, 0.0);
1536        for i in 0..20 {
1537            for j in 0..20 {
1538                b.area(l, &[square(i as f32 * 20.0, j as f32 * 20.0, 10.0)], &[]);
1539            }
1540        }
1541        let data = b.build();
1542        assert!(data.layers[0][FULL].tiles.len() > 1);
1543        for t in &data.tiles {
1544            let (shape, _) = data.shape(t).unwrap();
1545            let n: usize = shape.path().contours.iter().map(Vec::len).sum();
1546            assert!(n <= MAX_QUADS, "{n} segments");
1547        }
1548        assert_eq!(data.bounds, Rect::new(0.0, 0.0, 390.0, 390.0));
1549        // Too small for the coarsest level, too plain to simplify in between.
1550        assert!(data.layers[0][0].tiles.is_empty());
1551        assert_eq!(data.layers[0][3], data.layers[0][FULL]);
1552    }
1553
1554    #[test]
1555    fn labels_run_along_upright_and_spaced() {
1556        let text = Text::default();
1557        let mut b = MapBuilder::new(48.0, 11.0);
1558        let l = b.layer(Color::BLACK, 0.0);
1559        let label =
1560            |b: &mut MapBuilder, pts: &[Point]| b.label(l, pts, &text, Font::DEFAULT, "Hi", 10.0);
1561        assert!(!label(&mut b, &[[0.0, 0.0], [10.0, 0.0]]), "too short");
1562        let bend = [[0.0, 0.0], [50.0, 0.0], [50.0, 50.0]];
1563        assert!(!label(&mut b, &bend), "turns under the text");
1564        // Drawn right to left, still read left to right: 'H' comes first.
1565        assert!(label(&mut b, &[[100.0, 0.0], [0.0, 0.0]]));
1566        let t = &b.labels[0];
1567        let glyphs = &t.geo.as_ref().unwrap().glyphs;
1568        let v = bounds(glyphs.contours.iter().flatten().flatten()).unwrap();
1569        assert!((v.x + v.w / 2.0 - 50.0).abs() < 2.0);
1570        assert!((v.y + v.h / 2.0).abs() < 4.0, "centred on the line");
1571        assert!(glyphs.contours[0][0][0][0] < 50.0);
1572        assert_eq!(t.min_scale, MIN_LABEL_PX / 10.0);
1573        // The same text 100 m on waits until they're far enough apart on screen.
1574        assert!(label(&mut b, &[[100.0, 0.0], [200.0, 0.0]]));
1575        assert_eq!(b.labels[1].min_scale, LABEL_SPACING_PX / 100.0);
1576    }
1577
1578    #[test]
1579    fn maps_round_trip_through_bytes() {
1580        let mut b = MapBuilder::new(52.37, 4.89);
1581        let roads = b.layer(Color::WHITE, 0.0);
1582        let names = b.layer(Color::BLACK, 0.5);
1583        b.line(roads, &[[0.0, 0.0], [300.0, 40.0], [600.0, 0.0]], 10.0);
1584        b.area(roads, &[square(100.0, 100.0, 50.0)], &[]);
1585        b.label(
1586            names,
1587            &[[0.0, 0.0], [600.0, 0.0]],
1588            &Text::default(),
1589            Font::DEFAULT,
1590            "Damrak",
1591            8.0,
1592        );
1593        let built = b.build();
1594        let bytes: &'static [u8] = Vec::leak(built.to_bytes());
1595        let read = MapData::from_bytes(bytes).unwrap();
1596        assert_eq!(read.to_bytes(), bytes);
1597        assert_eq!(
1598            (read.tiles(), read.segments()),
1599            (built.tiles(), built.segments())
1600        );
1601        assert_eq!(
1602            (read.layers.clone(), read.labels.clone()),
1603            (built.layers.clone(), built.labels.clone())
1604        );
1605        for (a, z) in built.tiles.iter().zip(&read.tiles) {
1606            assert_eq!(
1607                (a.cell, a.min_scale, a.level),
1608                (z.cell, z.min_scale, z.level)
1609            );
1610            let (va, vz) = (data_view(&built, a), data_view(&read, z));
1611            // Grid rounding moves edges met at a shallow angle by more.
1612            assert!((va.x - vz.x).abs() < 1e-2 && (va.w - vz.w).abs() < 1e-2);
1613        }
1614        assert!(MapData::from_bytes(&bytes[..bytes.len() - 1]).is_none());
1615    }
1616
1617    fn data_view(d: &MapData, t: &Tile) -> Rect {
1618        d.shape(t).unwrap().1
1619    }
1620
1621    #[test]
1622    fn panning_in_stores_the_tiles_in_view() {
1623        struct App(Rc<MapData>);
1624        impl dfui::App for App {
1625            fn view(&self) -> Element {
1626                map(&self.0).start([200.0, 200.0], 4.0).into()
1627            }
1628        }
1629        let mut b = MapBuilder::new(48.0, 11.0);
1630        let l = b.layer(Color::BLACK, 0.0);
1631        for i in 0..40 {
1632            b.line(
1633                l,
1634                &[[0.0, i as f32 * 10.0], [400.0, i as f32 * 10.0 + 3.0]],
1635                2.0,
1636            );
1637        }
1638        let data = Rc::new(b.build());
1639        let mut bench = dfui::Bench::new(App(data.clone()), (100.0, 100.0));
1640        bench.settle();
1641        let view = Rect::new(187.5, 187.5, 25.0, 25.0);
1642        let stored = |t: &Tile| t.stored.get();
1643        let shown = data.tiles[data.layers[0][FULL].tiles.clone()]
1644            .iter()
1645            .filter(|t| {
1646                let hit = t.cell.intersect(&view);
1647                hit.w > 0.0 && hit.h > 0.0
1648            });
1649        assert!(shown.clone().count() > 0 && shown.clone().all(stored));
1650        let off = data
1651            .tiles
1652            .iter()
1653            .filter(|t| t.cell.intersect(&view).w <= 0.0 || t.cell.intersect(&view).h <= 0.0);
1654        assert!(!off.clone().any(stored), "nothing out of view is stored");
1655    }
1656
1657    #[test]
1658    fn zoom_keeps_the_point_under_the_pointer() {
1659        let data = empty();
1660        let r = Rect::new(0.0, 0.0, 100.0, 100.0);
1661        let mut v = View::default();
1662        v.fit(&map(&data), r, Instant::now());
1663        let at = |v: &View| {
1664            [
1665                v.center[0] + (80.0 - 50.0) / v.scale,
1666                v.center[1] + (20.0 - 50.0) / v.scale,
1667            ]
1668        };
1669        let before = at(&v);
1670        v.zoom(&data, r, 80.0, 20.0, 3.0);
1671        assert_eq!(v.scale, 3.0);
1672        let after = at(&v);
1673        assert!((before[0] - after[0]).abs() < 1e-4 && (before[1] - after[1]).abs() < 1e-4);
1674    }
1675
1676    #[test]
1677    fn taps_report_the_map_point_and_pans_dont() {
1678        use std::cell::RefCell;
1679
1680        struct App(Rc<MapData>, Rc<RefCell<Vec<(Point, f32)>>>);
1681        impl dfui::App for App {
1682            fn view(&self) -> Element {
1683                let taps = self.1.clone();
1684                map(&self.0)
1685                    .on_tap_scaled(move |_, p, s| taps.borrow_mut().push((p, s)))
1686                    .into()
1687            }
1688        }
1689        let taps = Rc::new(RefCell::new(Vec::new()));
1690        let mut b = dfui::Bench::new(App(empty(), taps.clone()), (100.0, 100.0));
1691        b.settle();
1692        b.event(Event::PointerDown { x: 80.0, y: 20.0 });
1693        b.event(Event::PointerUp { x: 80.0, y: 20.0 });
1694        b.event(Event::PointerDown { x: 50.0, y: 50.0 });
1695        b.event(Event::PointerMove { x: 10.0, y: 50.0 });
1696        b.event(Event::PointerUp { x: 10.0, y: 50.0 });
1697        assert_eq!(*taps.borrow(), [([80.0, 20.0], 1.0)]);
1698    }
1699
1700    #[test]
1701    fn focus_moves_the_view_once_per_change() {
1702        let data = empty();
1703        let r = Rect::new(0.0, 0.0, 100.0, 100.0);
1704        let mut v = View::default();
1705        let t = Instant::now();
1706        let focused = map(&data).focus(Some(([10.0, 20.0], 5.0)));
1707        v.fit(&focused, r, t);
1708        v.step(t + GLIDE);
1709        assert_eq!((v.center, v.scale), ([10.0, 20.0], 5.0));
1710        v.center = [0.0, 0.0];
1711        v.fit(&focused, r, t);
1712        assert!(!v.step(t + GLIDE));
1713        assert_eq!(v.center, [0.0, 0.0]);
1714    }
1715
1716    #[test]
1717    fn fit_zooms_out_as_well_as_in() {
1718        let data = empty();
1719        let r = Rect::new(0.0, 0.0, 100.0, 50.0);
1720        let mut v = View::default();
1721        let t = Instant::now();
1722        v.fit(&map(&data).fit(Rect::new(0.0, 0.0, 10.0, 10.0)), r, t);
1723        v.step(t + GLIDE);
1724        assert_eq!((v.center, v.scale), ([5.0, 5.0], 5.0));
1725        v.fit(&map(&data).fit(Rect::new(0.0, 0.0, 400.0, 100.0)), r, t);
1726        // Halfway in time is halfway in zoom, geometrically.
1727        assert!(v.step(t + GLIDE / 2));
1728        assert!((v.scale - (5.0f32 * 0.25).sqrt()).abs() < 1e-4);
1729        assert!(!v.step(t + GLIDE));
1730        assert_eq!((v.center, v.scale), ([200.0, 50.0], 0.25));
1731    }
1732}