diff --git a/crates/map/src/diagram.rs b/crates/map/src/diagram.rs index e2e357c5f2..2f0c70881f 100644 --- a/crates/map/src/diagram.rs +++ b/crates/map/src/diagram.rs @@ -13,7 +13,7 @@ use rustgis_data::Dataset; use serde::{Deserialize, Serialize}; use crate::color::Rgba; -use crate::symbology::{LegendEntry, Marker, Symbol}; +use crate::symbology::{LegendEntry, LineMark, LineMarkers, LineStroke, Marker, Symbol}; /// The most categories one diagram lists (each is a slice or a bar). pub const MAX_CATEGORIES: usize = 16; @@ -108,6 +108,18 @@ pub struct DiagramCategory { pub colour: Rgba, } +/// A category's mark in a point layer's legend: its own, or the row would take the layer's stacked +/// marks and every category would look the same. +fn category_mark(colour: Rgba) -> LineStroke { + let markers = LineMarkers { + mark: LineMark::Marker(Marker::Circle), + size: 7.0, + outline: Some(Rgba::rgb(0xFF, 0xFF, 0xFF)), + ..LineMarkers::default() + }; + LineStroke { color: Some(colour), width: Some(1.0), markers: Some(markers), ..LineStroke::default() } +} + /// How big a diagram is: one size for every feature, or one grown with the categories' sum, as /// [`crate::Renderer::Proportional`] grows a marker (area-proportional square root scaling). #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] @@ -258,6 +270,7 @@ impl DiagramSettings { size: 7.0, marker: Marker::Circle, }, + strokes: vec![category_mark(c.colour)], fallback: false, }) .collect() @@ -432,6 +445,7 @@ mod tests { assert_eq!(l[0].symbol.fill, CATEGORY_COLORS[0]); assert_eq!(l[0].symbol.stroke, Rgba::rgb(0xFF, 0xFF, 0xFF), "a white outline on a polygon or point layer"); assert!(l.iter().all(|e| !e.fallback)); + assert_eq!(l[0].strokes[0].color, Some(CATEGORY_COLORS[0]), "its own mark, not the layer's stacked ones"); let line = settings().legend(true); assert_eq!(line[0].symbol.stroke, CATEGORY_COLORS[0], "a line's swatch draws its stroke, so the colour is there"); } diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 212b2059fb..10b5fae507 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -759,11 +759,20 @@ pub const MAX_LEGEND_STEPS: usize = 2_000_000; pub struct LegendEntry { pub label: String, pub symbol: Symbol, + /// The stacked strokes its class has of its own; empty, it takes the layer's `line_strokes`. + pub strokes: Vec, /// The Unique Values fallback row (``), told apart from a class whatever /// its label: a legend can leave it out without touching a class that bears the same name. pub fallback: bool, } +impl LegendEntry { + /// A class's row, with the stacked strokes it has of its own, if any. + fn class(label: String, symbol: Symbol, strokes: Option<&Vec>) -> Self { + LegendEntry { label, symbol, strokes: strokes.cloned().unwrap_or_default(), fallback: false } + } +} + /// Most unique-value classes created automatically. pub const MAX_UNIQUE: usize = 64; /// The most classes by an expression: a QGIS rule-based style's rules (one class each), kept when @@ -1408,7 +1417,19 @@ impl Renderer { /// Values by an expression reading `@map_scale` class by. One whose expression would take /// more than [`MAX_LEGEND_STEPS`] to class every kept feature lists all its classes. pub fn legend_at(&self, ds: &Dataset, rows: &[bool], map_scale: Option) -> Vec { - let Renderer::Unique { field, classes, other, class_labels, other_label, expression, other_fills, other_strokes, .. } = self else { + let Renderer::Unique { + field, + classes, + other, + class_labels, + other_label, + expression, + other_fills, + other_strokes, + class_strokes, + .. + } = self + else { return self.legend(); }; // A fallback that draws nothing has nothing to stand for in a legend: its own symbol as @@ -1469,10 +1490,15 @@ impl Renderer { .into_iter() .filter(|i| used.get(*i).copied().unwrap_or(false)) .filter_map(|i| classes.get(i)) - .map(|(k, s)| LegendEntry { label: unique_label(class_labels, k), symbol: *s, fallback: false }) + .map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k))) .collect(); if other_used && visible { - v.push(LegendEntry { label: other_label.clone().unwrap_or_else(|| OTHER_VALUES.into()), symbol: *other, fallback: true }); + v.push(LegendEntry { + label: other_label.clone().unwrap_or_else(|| OTHER_VALUES.into()), + symbol: *other, + strokes: other_strokes.clone(), + fallback: true, + }); } v } @@ -1502,21 +1528,28 @@ impl Renderer { rustgis_data::value::numeric_classes(classes.iter().map(|(k, _)| k.as_str())) } + /// Every row of its legend, whatever the features: the classes, then a Unique Values' + /// ``; none for a single symbol. pub fn legend(&self) -> Vec { match self { Renderer::Single(_) => Vec::new(), - Renderer::Unique { classes, other, class_labels, other_label, .. } => { + Renderer::Unique { classes, other, class_labels, other_label, class_strokes, other_strokes, .. } => { // Keep symbols attached to their classes in `class_order` and the fallback at the end. let mut v: Vec = self .class_order() .into_iter() .filter_map(|i| classes.get(i)) - .map(|(k, s)| LegendEntry { label: unique_label(class_labels, k), symbol: *s, fallback: false }) + .map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k))) .collect(); - v.push(LegendEntry { label: other_label.clone().unwrap_or_else(|| OTHER_VALUES.into()), symbol: *other, fallback: true }); + v.push(LegendEntry { + label: other_label.clone().unwrap_or_else(|| OTHER_VALUES.into()), + symbol: *other, + strokes: other_strokes.clone(), + fallback: true, + }); v } - Renderer::Graduated { breaks, symbols, min, class_labels, .. } => { + Renderer::Graduated { breaks, symbols, min, class_labels, class_strokes, .. } => { let mut lo = *min; breaks .iter() @@ -1525,18 +1558,19 @@ impl Renderer { .map(|(i, (b, s))| { let label = class_labels.get(&i).cloned().unwrap_or_else(|| range_label(lo, *b)); lo = *b; - LegendEntry { label, symbol: *s, fallback: false } + LegendEntry::class(label, *s, class_strokes.get(&i)) }) .collect() } Renderer::Proportional { base, min_size, max_size, min, max, .. } => vec![ - LegendEntry { label: fmt_num(*min), symbol: Symbol { size: *min_size, ..*base }, fallback: false }, + LegendEntry { label: fmt_num(*min), symbol: Symbol { size: *min_size, ..*base }, strokes: Vec::new(), fallback: false }, LegendEntry { label: fmt_num((min + max) / 2.0), symbol: Symbol { size: min_size + (max_size - min_size) * 0.707, ..*base }, + strokes: Vec::new(), fallback: false, }, - LegendEntry { label: fmt_num(*max), symbol: Symbol { size: *max_size, ..*base }, fallback: false }, + LegendEntry { label: fmt_num(*max), symbol: Symbol { size: *max_size, ..*base }, strokes: Vec::new(), fallback: false }, ], } } @@ -1582,7 +1616,7 @@ impl Renderer { // The class's row in `legend()`, which lists the classes and then `other`. Unique Values // rows are sorted by label, so that class's row is built here rather than looked up. let row = match (&mut *self, class) { - (Renderer::Unique { classes, class_labels, .. }, ClassRef::Value(v)) => { + (Renderer::Unique { classes, class_labels, class_strokes, .. }, ClassRef::Value(v)) => { let i = classes.iter().position(|(k, _)| k == v).ok_or_else(|| format!("no class with the value '{v}'"))?; if let Some((k, s)) = classes.get_mut(i) { restyle(s); @@ -1599,7 +1633,7 @@ impl Renderer { } return classes .get(i) - .map(|(k, s)| LegendEntry { label: unique_label(class_labels, k), symbol: *s, fallback: false }) + .map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k))) .ok_or_else(|| "the class has no legend row".into()); } (Renderer::Unique { classes, other, other_label, .. }, ClassRef::Other) => { @@ -3259,6 +3293,54 @@ mod tests { assert_eq!(r.legend().len(), 2); } + /// Each row keeps its class's strokes, its class stored in either order, in both renderers + /// with classes. + #[test] + fn a_legend_row_has_its_class_own_strokes() { + let mut d = Dataset::new("t", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + for g in ["a", "b", "z"] { + d.push(None, vec![Value::Text(g.into())]); + } + let s = |c| Symbol::default_for(GeometryType::Point, c); + let stroke = |width| LineStroke { width: Some(width), ..LineStroke::default() }; + // Stored in either order, the rows come by label and each keeps its class's strokes. + let (a, b) = (("a".to_string(), s(0)), ("b".to_string(), s(1))); + for classes in [vec![a.clone(), b.clone()], vec![b, a]] { + let r = Renderer::Unique { + field: "g".into(), + classes, + other: s(2), + ramp: Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: [("a".to_string(), vec![stroke(1.0)])].into_iter().collect(), + other_strokes: vec![stroke(2.0)], + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + // The whole list and the classes of the features kept. + for rows in [r.legend(), r.legend_for(&d, &[])] { + let strokes: Vec<_> = rows.iter().map(|e| e.strokes.clone()).collect(); + assert_eq!(strokes, [vec![stroke(1.0)], vec![], vec![stroke(2.0)]]); + } + } + let g = Renderer::Graduated { + field: "v".into(), + breaks: vec![1.0, 2.0], + symbols: vec![s(0), s(1)], + ramp: Ramp::Ember, + method: ClassMethod::Quantile, + min: 0.0, + classes: 2, + class_labels: Default::default(), + class_strokes: [(1, vec![stroke(1.0)])].into_iter().collect(), + class_fills: Default::default(), + }; + let strokes: Vec<_> = g.legend().into_iter().map(|e| e.strokes).collect(); + assert_eq!(strokes, [vec![], vec![stroke(1.0)]]); + } + #[test] fn categorical_children_sort_case_insensitively_without_changing_symbols() { let names = ["Zulu", "alpha", "Bravo", "ALPHA", "éclair", "École"]; diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 914b4e40e3..6a62af58aa 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -12,7 +12,7 @@ use rustgis_map::symbology::LegendEntry; use rustgis_map::{Map, Rgba}; use tiny_skia::{FillRule, Mask, PathBuilder, Pixmap, PixmapPaint, Rect, Stroke, Transform}; -use crate::{View, paint, text}; +use crate::{View, paint, point_marks, text}; /// Page values for dynamic text. #[derive(Clone, Debug, Default)] @@ -1243,20 +1243,47 @@ struct LegendOptions<'a> { enum LegendRow<'a> { Plain(&'a rustgis_map::Layer), Head(&'a str), - Class(GeometryType, LegendEntry), + Class(&'a rustgis_map::Layer, LegendEntry), Picture(std::sync::Arc), } impl LegendRow<'_> { - /// Its height, in points: a picture's a pixel a point, as the Layers pane shows it. - fn height(&self) -> f32 { + /// The side of the square its point symbol takes at 1:`scale`, in points, as far as its marks + /// reach ([`point_marks::reach`]); 0 for any other row. No larger than a legend picture. + fn symbol_side(&self, scale: f64) -> f32 { + let (LegendRow::Plain(l) | LegendRow::Class(l, _)) = self else { return 0.0 }; + if l.geometry_type() != GeometryType::Point { + return 0.0; + } + let (s, strokes) = match self { + LegendRow::Class(_, en) => (en.symbol, row_strokes(l, en)), + _ => (l.renderer.symbol_for(&l.dataset, 0), l.line_strokes.as_slice()), + }; + (2.0 * point_marks::reach(&s, strokes) * l.size_factor(scale)).min(MAX_LEGEND_SIDE as f32) + } + + /// Its height at 1:`scale`, in points: a picture's a pixel a point, as the Layers pane shows + /// it; a row grows to hold its point symbol. + fn height(&self, scale: f64) -> f32 { match self { LegendRow::Picture(p) => picture_size(p).1, - _ => LEGEND_ROW, + _ => LEGEND_ROW.max(self.symbol_side(scale)), } } } +/// The stacked strokes a legend's class row draws: its class's own, else its layer's, as +/// [`rustgis_map::Layer::strokes`] finds them for a feature. +fn row_strokes<'a>(l: &'a rustgis_map::Layer, en: &'a LegendEntry) -> &'a [rustgis_map::LineStroke] { + if en.strokes.is_empty() { &l.line_strokes } else { &en.strokes } +} + +/// The width of a legend's column of swatches at 1:`scale`, in points: it grows to hold the widest +/// point symbol, so the labels line up. +fn swatch_column(rows: &[LegendRow], scale: f64) -> f32 { + rows.iter().map(|row| row.symbol_side(scale)).fold(LEGEND_SWATCH, f32::max) +} + /// A legend picture's size in points (a pixel a point). fn picture_size(p: &rustgis_tiles::cache::Payload) -> (f32, f32) { match p { @@ -1333,7 +1360,8 @@ fn wait_for_tile_legends(map: &Map, scale: f64, exclude: &[String]) { } } -/// The widest and tallest legend picture shown, in pixels, as in the Layers pane. +/// The widest and tallest legend picture shown, in pixels, as in the Layers pane, and the largest +/// side of a legend's point symbol, in points. const MAX_LEGEND_SIDE: u32 = 2048; /// A legend row's height, in points. @@ -1396,8 +1424,7 @@ fn legend_rows<'a>(map: &'a Map, drawn: Option<&[(u32, Vec)]>, opts continue; } rows.push(LegendRow::Head(&l.name)); - let gt = l.geometry_type(); - rows.extend(entries.into_iter().map(|en| LegendRow::Class(gt, en))); + rows.extend(entries.into_iter().map(|en| LegendRow::Class(l, en))); } rows } @@ -1412,8 +1439,9 @@ fn legend(pm: &mut Canvas, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32 text::text_at(pm, title, r.x(), y + line / 2.0, 12.0 * 1.33 * ppp, dark, true, text::Align::Left, false); y += line * 1.3; } - let sw = LEGEND_SWATCH * ppp; - let mut rows = legend_rows(map, drawn, &opts).into_iter().peekable(); + let rows = legend_rows(map, drawn, &opts); + let sw = swatch_column(&rows, opts.scale) * ppp; + let mut rows = rows.into_iter().peekable(); while let Some(row) = rows.next() { if let LegendRow::Picture(p) = &row { match &**p { @@ -1428,7 +1456,8 @@ fn legend(pm: &mut Canvas, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32 } // The rectangle's own bottom, which a sum of its top and height can miss by a rounding, // and a thousandth of a row's slack: a legend sized to its rows keeps the last one. - if y + line > r.bottom() + line * 1e-3 { + let height = row.height(opts.scale) * ppp; + if y + height > r.bottom() + line * 1e-3 { break; } // A WMS or WMTS layer's name only with room for some of its picture under it. @@ -1440,19 +1469,30 @@ fn legend(pm: &mut Canvas, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32 } match row { LegendRow::Plain(l) => { - swatch(pm, r.x(), y, sw, line, l.geometry_type(), &l.renderer.symbol_for(&l.dataset, 0), ppp); - text::text_at(pm, &l.name, r.x() + sw + 6.0 * ppp, y + line / 2.0, 9.0 * 1.33 * ppp, dark, false, text::Align::Left, false); + let s = l.renderer.symbol_for(&l.dataset, 0); + swatch(pm, (r.x(), y, sw, height), l, (&s, l.line_strokes.as_slice()), map.layer_opacity(l), opts.scale, ppp); + text::text_at( + pm, + &l.name, + r.x() + sw + 6.0 * ppp, + y + height / 2.0, + 9.0 * 1.33 * ppp, + dark, + false, + text::Align::Left, + false, + ); } LegendRow::Head(name) => { text::text_at(pm, name, r.x(), y + line / 2.0, 9.0 * 1.33 * ppp, dark, true, text::Align::Left, false); } - LegendRow::Class(gt, en) => { - swatch(pm, r.x() + 6.0 * ppp, y, sw, line, gt, &en.symbol, ppp); + LegendRow::Class(l, en) => { + swatch(pm, (r.x() + 6.0 * ppp, y, sw, height), l, (&en.symbol, row_strokes(l, &en)), map.layer_opacity(l), opts.scale, ppp); text::text_at( pm, &en.label, r.x() + sw + 12.0 * ppp, - y + line / 2.0, + y + height / 2.0, 8.5 * 1.33 * ppp, dark, false, @@ -1462,7 +1502,7 @@ fn legend(pm: &mut Canvas, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32 } LegendRow::Picture(_) => {} } - y += line; + y += height; } } @@ -1512,17 +1552,18 @@ fn legend_picture(pm: &mut Canvas, r: Rect, y: f32, pic: &Pixmap, ppp: f32) -> O pub fn legend_size_mm(map: &mut Map, scale: f64, all_classes: bool, hide_other: bool, exclude: &[String]) -> Option<(f64, f64)> { let drawn = if all_classes { None } else { Some(complete_shown_legends(map, scale)?) }; let rows = legend_rows(map, drawn.as_deref(), &LegendOptions { hide_other, exclude, scale }); + let column = swatch_column(&rows, scale); let width = rows .iter() .map(|row| match row { - LegendRow::Plain(l) => LEGEND_SWATCH + 6.0 + text::measure(&l.name, 9.0, false), + LegendRow::Plain(l) => column + 6.0 + text::measure(&l.name, 9.0, false), LegendRow::Head(name) => text::measure(name, 9.0, true), - LegendRow::Class(_, en) => LEGEND_SWATCH + 12.0 + text::measure(&en.label, 8.5, false), + LegendRow::Class(_, en) => column + 12.0 + text::measure(&en.label, 8.5, false), LegendRow::Picture(p) => 6.0 + picture_size(p).0, }) .fold(0.0f32, f32::max); let mm = 25.4 / 96.0; - let height: f32 = rows.iter().map(LegendRow::height).sum(); + let height: f32 = rows.iter().map(|row| row.height(scale)).sum(); Some((f64::from(width) * mm, f64::from(height) * mm)) } @@ -1584,24 +1625,26 @@ pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: Some((gw, gh, drawn)) } -/// A legend entry's symbol for a layer of `gt`: a dot, a line or a filled box in the box -/// (`x`, `y`, `w`, `h`). -fn swatch(pm: &mut Canvas, x: f32, y: f32, w: f32, h: f32, gt: GeometryType, s: &rustgis_map::Symbol, ppp: f32) { +/// A legend entry's symbol `s` of the layer `l` in the box (`x`, `y`, `w`, `h`): a point as +/// [`point_swatch`] draws it with `strokes`, or a line or a filled box a swatch wide, in the middle +/// of the box. +fn swatch( + pm: &mut Canvas, + (x, y, w, h): (f32, f32, f32, f32), + l: &rustgis_map::Layer, + (s, strokes): (&rustgis_map::Symbol, &[rustgis_map::LineStroke]), + opacity: f32, + scale: f64, + ppp: f32, +) { + let gt = l.geometry_type(); + if gt == GeometryType::Point { + point_swatch(pm, (x, y, w, h), (s, strokes), opacity, ppp * l.size_factor(scale)); + return; + } + let (x, w) = (x + (w - LEGEND_SWATCH * ppp) / 2.0, LEGEND_SWATCH * ppp); let cy = y + h / 2.0; match gt { - GeometryType::Point => { - let rad = (s.size * ppp / 2.0).clamp(1.5 * ppp, h / 2.0 - 1.0); - if let Some(p) = PathBuilder::from_circle(x + w / 2.0, cy, rad) { - pm.fill_path(&p, &paint(s.fill, 1.0), FillRule::Winding, Transform::identity(), None); - pm.stroke_path( - &p, - &paint(s.stroke, 1.0), - &Stroke { width: s.stroke_width.max(0.5) * ppp, ..Stroke::default() }, - Transform::identity(), - None, - ); - } - } GeometryType::Polyline => { let mut pb = PathBuilder::new(); pb.move_to(x, cy + h * 0.2); @@ -1633,6 +1676,51 @@ fn swatch(pm: &mut Canvas, x: f32, y: f32, w: f32, h: f32, gt: GeometryType, s: } } +/// A point's symbol at (`x`, `y`), unturned, by the path the map takes for it: its marker, or +/// `strokes`' stacked marks. +fn draw_point(pm: &mut Canvas, (x, y): (f32, f32), s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], ppp: f32) { + if point_marks::plain(strokes, 0.0) { + crate::draw_marker(pm, x, y, s, 1.0, None, ppp); + } else { + point_marks::draw(pm, x, y, s, strokes, 0.0, None, ppp); + } +} + +/// A point layer's symbol in the middle of the box, as the map draws its points: `strokes`' stacked +/// marks or its marker, at `ppp` (with the layer's reference scale), unturned. See-through, the +/// marks are composited as one, as the map composites the layer, in a picture no larger than the +/// page. So are those too large for the box (past [`LegendRow::symbol_side`]'s limit), which the +/// picture cuts to it. +fn point_swatch( + pm: &mut Canvas, + (x, y, w, h): (f32, f32, f32, f32), + (s, strokes): (&rustgis_map::Symbol, &[rustgis_map::LineStroke]), + opacity: f32, + ppp: f32, +) { + let (cx, cy) = (x + w / 2.0, y + h / 2.0); + // A thousandth of slack: the box's size went through a rounding of its own. + let fits = 2.0 * point_marks::reach(s, strokes) * ppp <= w.min(h) * 1.001; + if opacity >= 0.999 && fits { + draw_point(pm, (cx, cy), s, strokes, ppp); + return; + } + // Kept on the canvas: a picture as large as the canvas then covers all of it that shows. + let (left, top) = (x.floor().max(0.0), y.floor().max(0.0)); + let (cw, ch) = (((x + w).ceil() - left) as u32, ((y + h).ceil() - top) as u32); + let (cw, ch) = (cw.min(pm.width()), ch.min(pm.height())); + if let Some(mut picture) = pm.sub(cw, ch) { + draw_point(&mut picture, (cx - left, cy - top), s, strokes, ppp); + // A recording keeps what lies past its picture's edge, so it is cut here, at the box. + let clip = Rect::from_xywh(x, y, w, h).map(|r| crate::vector::Clip { + path: PathBuilder::from_rect(r), + rule: FillRule::Winding, + transform: Transform::identity(), + }); + pm.place(picture, Transform::from_translate(left, top), opacity, rustgis_map::effects::Blend::Normal, clip); + } +} + /// How a colorbar is laid out. struct Bar<'a> { title: &'a str, @@ -2958,4 +3046,504 @@ mod tests { assert!(scale.starts_with("1:") && scale.contains(','), "{point}"); assert_eq!(comma, format!("Scale {}, page 1.", scale.replace(',', "."))); } + + /// A map of one point layer, one point, set by `edit`. + fn point_legend_map(edit: impl FnOnce(&mut rustgis_map::Layer)) -> Map { + use rustgis_data::{Dataset, Geometry}; + let mut map = Map::new("m"); + let mut d = Dataset::new("pts", GeometryType::Point, vec![]); + d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![]); + map.add_dataset(d); + if let Some(l) = map.layers.last_mut() { + edit(l); + } + map + } + + /// The legend of `map` at 1:1e6, every class, on white. + fn point_legend(map: &Map) -> Pixmap { + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), map, "", None, opts, 1.0)); + pm + } + + /// The legend of `map` at 1:1e6 recorded for a vector export, on a page of `side` pixels, drawn + /// back on white. + fn recorded_legend(map: &Map, side: u32) -> Pixmap { + let mut c = Canvas::recording(side, side).unwrap(); + let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; + legend(&mut c, Rect::from_xywh(0.0, 0.0, side as f32, side as f32).unwrap(), map, "", None, opts, 1.0); + let (_, _, items) = c.into_drawing().unwrap().finish(); + let mut pm = Pixmap::new(side, side).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::vector::replay(&items, &mut pm, Transform::identity()); + pm + } + + /// What the map's code draws for a point at (`x`, `y`) on white. + fn drawn_point(s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], (x, y): (f32, f32), ppp: f32) -> Pixmap { + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + if strokes.is_empty() { + crate::draw_marker(c, x, y, s, 1.0, None, ppp); + } else { + point_marks::draw(c, x, y, s, strokes, 0.0, None, ppp); + } + }); + pm + } + + /// What the map's code draws for a point at (`x`, `y`), composited as one at `opacity`, on + /// white. + fn drawn_see_through( + s: &rustgis_map::Symbol, + strokes: &[rustgis_map::LineStroke], + (x, y): (f32, f32), + ppp: f32, + opacity: f32, + ) -> Pixmap { + let mut own = Pixmap::new(200, 200).unwrap(); + crate::canvas::with_canvas(&mut own, |c| draw_point(c, (x, y), s, strokes, ppp)); + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + pm.draw_pixmap(0, 0, own.as_ref(), &PixmapPaint { opacity, ..PixmapPaint::default() }, Transform::identity(), None); + pm + } + + /// Whether two pictures differ by no more than a rounding over `w` × `h` from the top left + /// corner. + fn near_corner(a: &Pixmap, b: &Pixmap, w: u32, h: u32) -> bool { + (0..h).all(|y| { + (0..w).all(|x| match (a.pixel(x, y), b.pixel(x, y)) { + (Some(p), Some(q)) => p.red().abs_diff(q.red()).max(p.green().abs_diff(q.green())).max(p.blue().abs_diff(q.blue())) <= 2, + _ => false, + }) + }) + } + + /// Whether two pictures are the same over `w` × `h` from the top left corner. + fn same_corner(a: &Pixmap, b: &Pixmap, w: u32, h: u32) -> bool { + (0..h).all(|y| (0..w).all(|x| a.pixel(x, y) == b.pixel(x, y))) + } + + /// A stacked stroke: a square of `size` points in `color`, with no outline. + fn square_mark(color: Rgba, size: f32) -> rustgis_map::LineStroke { + let markers = rustgis_map::LineMarkers { + mark: rustgis_map::LineMark::Marker(rustgis_map::Marker::Square), + size, + ..rustgis_map::LineMarkers::default() + }; + rustgis_map::LineStroke { color: Some(color), width: Some(0.0), markers: Some(markers), ..rustgis_map::LineStroke::default() } + } + + /// Every marker, tiny and ordinary, with an outline and without, at the pixels the map's code + /// gives it. + #[test] + fn a_legend_draws_a_point_as_the_map_does() { + let red = Rgba::rgb(255, 0, 0); + let base = + rustgis_map::Symbol { fill: red, stroke: Rgba::rgb(0, 0, 255), ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + // Every shape, tiny and ordinary, with no outline and with one. + for marker in rustgis_map::Marker::ALL { + for (size, stroke_width) in [(2.0, 0.0), (10.0, 0.0), (10.0, 1.0)] { + let s = rustgis_map::Symbol { marker, size, stroke_width, ..base }; + let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); + // The first row, 15 points tall, its swatch 16 wide. + let want = drawn_point(&s, &[], (8.0, 7.5), 1.0); + assert!(same_corner(&point_legend(&map), &want, 16, 15), "{marker:?} of {size} pt, outline {stroke_width} pt"); + } + } + // A class's symbol too, indented under its layer's name. + let s = rustgis_map::Symbol { marker: rustgis_map::Marker::Triangle, size: 10.0, stroke_width: 0.0, ..base }; + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".to_string(), s)], + other: s, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + }); + let got = point_legend(&map); + let want = drawn_point(&s, &[], (6.0 + 8.0, 15.0 + 7.5), 1.0); + assert!((15..30).all(|y| (6..22).all(|x| got.pixel(x, y) == want.pixel(x, y))), "the class's triangle"); + } + + /// An outline under half a pixel is as thin in a legend as on the map. + #[test] + fn a_legend_draws_a_hairline_outline_as_the_map_does() { + // Thinner than half a pixel: the map's marker strokes it at its width, with no minimum. + let s = rustgis_map::Symbol { + size: 10.0, + stroke: Rgba::rgb(0, 0, 255), + stroke_width: 0.1, + ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) + }; + let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); + assert!(same_corner(&point_legend(&map), &drawn_point(&s, &[], (8.0, 7.5), 1.0), 16, 15)); + } + + /// A layer's stacked marks replace its marker, in a row that holds them. + #[test] + fn a_legend_draws_a_points_stacked_marks() { + let strokes = vec![square_mark(Rgba::rgb(255, 0, 0), 12.0), square_mark(Rgba::rgb(0, 0, 0), 4.0)]; + let s = rustgis_map::Symbol::default_for(GeometryType::Point, 0); + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.line_strokes = strokes.clone(); + }); + // 12 pt squares reach 7.2 pt: the row is 15 points tall still. + assert!(same_corner(&point_legend(&map), &drawn_point(&s, &strokes, (8.0, 7.5), 1.0), 16, 15)); + } + + /// Stacked marks at the opacity of a layer and its groups, on pixels and in a recording. + #[test] + fn a_see_through_point_is_composited_as_one_with_its_groups() { + let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let strokes = vec![square_mark(Rgba::rgb(255, 0, 0), 12.0), square_mark(Rgba::rgb(0, 0, 0), 12.0)]; + let mut map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.line_strokes = strokes.clone(); + l.transparency = 50.0; + }); + let middle = |map: &Map| point_legend(map).pixel(8, 7).map(|p| (p.red(), p.green(), p.blue())).unwrap(); + // Black at half over white: grey, with none of the red under it showing. + let (r, g, b) = middle(&map); + assert!((120..=135).contains(&r) && r == g && g == b, "{r} {g} {b}"); + // Its group's transparency applies too: half of half. + let id = map.layers[0].id; + let mut group = rustgis_map::LayerGroup::new("g"); + group.transparency = 50.0; + group.children.push(id); + map.add_group(group); + let (r, g, b) = middle(&map); + assert!((185..=197).contains(&r) && r == g && g == b, "{r} {g} {b}"); + // Recorded for a vector export, it is half of half too. + let p = recorded_legend(&map, 200).pixel(8, 7).unwrap(); + let (r, g, b) = (p.red(), p.green(), p.blue()); + assert!((185..=197).contains(&r) && r == g && g == b, "recorded: {r} {g} {b}"); + } + + /// A square turned by its own angle reaches past 0.6 of its size: its row holds its corners, + /// which the picture of a see-through symbol would cut. + #[test] + fn a_see_through_mark_with_its_own_angle_keeps_its_corners() { + let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let mut mark = square_mark(Rgba::rgb(0, 0, 255), 40.0); + if let Some(m) = &mut mark.markers { + m.angle = 45.0; + } + let strokes = vec![mark]; + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.line_strokes = strokes.clone(); + l.transparency = 50.0; + }); + let side = 2.0 * point_marks::reach(&s, &strokes); + assert!(side > 50.0, "{side}"); + let drawn = drawn_see_through(&s, &strokes, (side / 2.0, side / 2.0), 1.0, 0.5); + assert!(near_corner(&point_legend(&map), &drawn, side.ceil() as u32, side.ceil() as u32)); + } + + /// A plain point at half its opacity, its outline over its fill: composited as one, so the fill + /// doesn't show through the outline. + #[test] + fn a_see_through_plain_point_is_composited_as_the_map_composites_a_layer() { + let s = rustgis_map::Symbol { + fill: Rgba::rgb(255, 0, 0), + stroke: Rgba::rgb(0, 0, 255), + stroke_width: 1.0, + size: 8.0, + marker: rustgis_map::Marker::Square, + }; + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.transparency = 50.0; + }); + assert!(near_corner(&point_legend(&map), &drawn_see_through(&s, &[], (8.0, 7.5), 1.0, 0.5), 16, 15)); + } + + /// A large symbol takes a taller row and a wider column in a legend's size; an ordinary one + /// doesn't. + #[test] + fn a_legend_grows_to_hold_a_large_point() { + let mm = 25.4 / 96.0; + let s = |size| rustgis_map::Symbol { size, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let label = f64::from(6.0 + text::measure("pts", 9.0, false)); + // An ordinary symbol keeps the row and the swatch's column. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(10.0))); + let (w, h) = legend_size_mm(&mut map, 1e6, true, false, &[]).unwrap(); + assert!((h - f64::from(LEGEND_ROW) * mm).abs() < 1e-6, "{h} mm"); + // Its width within a rounding: it is summed in f32, past a name as wide as its font makes it. + assert!((w - (f64::from(LEGEND_SWATCH) + label) * mm).abs() < 1e-4, "{w} mm"); + // One of 40 pt reaches 24 pt from its point: 48 pt each way. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(40.0))); + let (w, h) = legend_size_mm(&mut map, 1e6, true, false, &[]).unwrap(); + assert!((h - 48.0 * mm).abs() < 1e-6, "{h} mm"); + assert!((w - (48.0 + label) * mm).abs() < 1e-4, "{w} mm"); + assert!(same_corner(&point_legend(&map), &drawn_point(&s(40.0), &[], (24.0, 24.0), 1.0), 48, 48)); + // A frame too short for the row draws no part of it. + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let blank = pm.clone(); + let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 47.0).unwrap(), &map, "", None, opts, 1.0)); + assert!(pm.data() == blank.data()); + // A size no page could hold stays a size a legend can take. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(f32::MAX))); + let (w, h) = legend_size_mm(&mut map, 1e6, true, false, &[]).unwrap(); + assert!(w.is_finite() && h.is_finite(), "{w} × {h} mm"); + } + + /// A layer's reference scale sizes its symbol at the frame's scale. + #[test] + fn a_legend_scales_a_point_with_its_reference_scale() { + let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + // Twice as large at 1:1e6: 10 pt reaches 12 pt from its point, in a row of 24. + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.reference_scale = Some(2e6); + }); + assert!(same_corner(&point_legend(&map), &drawn_point(&s, &[], (12.0, 12.0), 2.0), 24, 24)); + } + + /// A diagram's categories on a point layer with stacked marks: each row shows its own colour, + /// not the layer's marks. + #[test] + fn a_diagrams_rows_keep_their_own_mark_on_a_layer_with_stacked_marks() { + let (red, green) = (Rgba::rgb(255, 0, 0), Rgba::rgb(0, 255, 0)); + let category = |field: &str, colour| rustgis_map::DiagramCategory { field: field.into(), colour }; + let map = point_legend_map(|l| { + l.line_strokes = vec![square_mark(Rgba::rgb(0, 0, 0), 12.0)]; + l.diagram = Some(rustgis_map::DiagramSettings { + kind: rustgis_map::DiagramKind::Pie, + categories: vec![category("a", red), category("b", green)], + size: rustgis_map::DiagramSize::Fixed(12.0), + start_angle: 0.0, + background: None, + stroke: rustgis_map::DiagramSettings::default_stroke(), + stroke_width: 0.75, + labels: rustgis_map::DiagramLabel::None, + }); + }); + let pm = point_legend(&map); + let at = |x, y| pm.pixel(x, y).map(|p| (p.red(), p.green(), p.blue())); + // The layer's name, then a row each, the swatch 6 points in. + assert_eq!(at(14, 22), Some((255, 0, 0))); + assert_eq!(at(14, 37), Some((0, 255, 0))); + } + + /// A box off the pixel grid: a recording cuts its symbol at the box, not at the whole pixels + /// round it, so the pixel its edge crosses is half covered. + #[test] + fn a_recorded_point_is_cut_at_its_box() { + let s = rustgis_map::Symbol { + fill: Rgba::rgb(0, 0, 255), + size: 3000.0, + stroke_width: 0.0, + marker: rustgis_map::Marker::Square, + ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) + }; + let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); + let mut c = Canvas::recording(2100, 2100).unwrap(); + let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; + legend(&mut c, Rect::from_xywh(0.5, 0.5, 2099.0, 2099.0).unwrap(), &map, "", None, opts, 1.0); + let (_, _, items) = c.into_drawing().unwrap().finish(); + let mut pm = Pixmap::new(2100, 2100).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::vector::replay(&items, &mut pm, Transform::identity()); + // The box runs from 0.5 to 2048.5. + let red = |x, y| pm.pixel(x, y).map_or(0, |p| p.red()); + assert_eq!(red(10, 10), 0); + assert!((60..200).contains(&red(2048, 10)), "{}", red(2048, 10)); + assert!((60..200).contains(&red(10, 2048)), "{}", red(10, 2048)); + } + + /// An upright square's and triangle's corners lie further than 0.6 of their size from their + /// centre, but along each axis, which is what the box holds, they stay inside it. + #[test] + fn an_upright_mark_stays_in_its_row() { + let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + for marker in [rustgis_map::Marker::Square, rustgis_map::Marker::Triangle] { + let mut mark = square_mark(Rgba::rgb(0, 0, 255), 40.0); + if let Some(m) = &mut mark.markers { + m.mark = rustgis_map::LineMark::Marker(marker); + } + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.line_strokes = vec![mark]; + }); + let pm = point_legend(&map); + let white = |x, y| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 255, 255)); + // A box of 48 points: its edges are clear, and the mark is in it. + assert!((0..48).all(|i| white(i, 0) && white(i, 47) && white(0, i) && white(47, i)), "{marker:?}"); + assert!(!white(24, 24), "{marker:?}"); + } + } + + /// A class's row draws the marks the map gives its features, else its layer's. + #[test] + fn a_legend_draws_a_class_with_its_own_marks() { + let s = rustgis_map::Symbol::default_for(GeometryType::Point, 0); + let (own, others, layers) = ( + vec![square_mark(Rgba::rgb(255, 0, 0), 12.0)], + vec![square_mark(Rgba::rgb(0, 255, 0), 12.0)], + vec![square_mark(Rgba::rgb(0, 0, 255), 12.0)], + ); + let map = point_legend_map(|l| { + l.line_strokes = layers.clone(); + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".to_string(), s), ("b".to_string(), s)], + other: s, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: [("a".to_string(), own.clone())].into_iter().collect(), + other_strokes: others.clone(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + }); + let got = point_legend(&map); + // Under the layer's name, each row 15 points tall, its swatch 6 in: class a has its own, + // class b takes the layer's, and the fallback has its own. + for (row, strokes) in [(1u32, &own), (2, &layers), (3, &others)] { + let top = row * 15; + let want = drawn_point(&s, strokes, (14.0, top as f32 + 7.5), 1.0); + assert!((top..top + 15).all(|y| (6..22).all(|x| got.pixel(x, y) == want.pixel(x, y))), "row {row}"); + } + } + + /// A large point widens the column: a line or a box stays a swatch wide, and the names line up. + #[test] + fn a_wide_column_keeps_lines_and_boxes_a_swatch_wide_in_its_middle() { + use rustgis_data::Dataset; + let blue = Rgba::rgb(0, 0, 255); + let point = + rustgis_map::Symbol { fill: blue, size: 40.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + for gt in [GeometryType::Polyline, GeometryType::Polygon] { + // A point of 40 pt makes the column 48 wide: a swatch of 16 in its middle runs from 16 to 32. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(point)); + let id = map.add_dataset(Dataset::new("line", gt, vec![])); + let red = Rgba::rgb(255, 0, 0); + if let Some(l) = map.layer_mut(id) { + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { + fill: red, + stroke: red, + stroke_width: 2.0, + ..rustgis_map::Symbol::default_for(gt, 0) + }); + } + let pm = point_legend(&map); + let columns = |ink: &dyn Fn(u8, u8, u8) -> bool| -> Vec { + (0..pm.width()) + .filter(|&x| { + (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| p.alpha() > 0 && ink(p.red(), p.green(), p.blue()))) + }) + .collect() + }; + let swatch = columns(&|r, g, b| r > 200 && g < 60 && b < 60); + let (left, right) = (swatch.first().copied().unwrap_or(0), swatch.last().copied().unwrap_or(0)); + assert!((14..=17).contains(&left) && (31..=34).contains(&right), "{gt:?}: {left} to {right}"); + // Both names start past the column, where the blue point has no part in it. + let names = columns(&|r, g, b| r < 100 && g < 100 && b < 100); + assert!(names.first().is_some_and(|x| (53..60).contains(x)), "{gt:?}: {names:?}"); + } + } + + /// A symbol past the limit fills its box and stays in it, on pixels and in a recording. + #[test] + fn an_oversized_point_stays_in_its_row() { + let blue = Rgba::rgb(0, 0, 255); + let s = rustgis_map::Symbol { + fill: blue, + size: 3000.0, + stroke_width: 0.0, + marker: rustgis_map::Marker::Square, + ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) + }; + // Opaque and see-through: a row and a column of 2048 pt, which the square fills. + for transparency in [0.0, 50.0] { + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.transparency = transparency; + }); + let mut pm = Pixmap::new(2100, 2100).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, 2100.0, 2100.0).unwrap(), &map, "", None, opts, 1.0) + }); + // Drawn, and recorded for a vector export, where only its clip cuts it. + for pm in [pm, recorded_legend(&map, 2100)] { + let white = |x, y| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 255, 255)); + assert!(!white(10, 10) && !white(2040, 2040), "transparency {transparency}: it fills the box"); + assert!(white(10, 2060) && white(2060, 10), "transparency {transparency}: it stays in the box"); + } + } + } + + /// A legend starting off the canvas: a symbol larger than the canvas still covers all of it. + #[test] + fn a_see_through_point_larger_than_the_canvas_covers_it_from_off_its_edge() { + let s = rustgis_map::Symbol { + fill: Rgba::rgb(0, 0, 255), + size: 3000.0, + stroke_width: 0.0, + marker: rustgis_map::Marker::Square, + ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) + }; + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.transparency = 50.0; + }); + let mut pm = Pixmap::new(300, 300).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(-50.0, -50.0, 2100.0, 2100.0).unwrap(), &map, "", None, opts, 1.0) + }); + // Its box runs from -50 to 1998: every corner of the canvas is in it. + for (x, y) in [(5, 5), (295, 5), (5, 295), (295, 295)] { + let white = pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 255, 255)); + assert!(!white, "({x}, {y})"); + } + } + + /// A class's large symbol counts in a legend's size as a plain row's does. + #[test] + fn a_class_row_takes_the_wide_column_in_a_legends_size() { + let mm = 25.4 / 96.0; + let s = rustgis_map::Symbol { size: 40.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let mut map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".to_string(), s)], + other: s, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + }); + // The layer's name over the class: a row of 15 and one of 48, 6 + 48 + 6 before its label. + let (w, h) = legend_size_mm(&mut map, 1e6, true, true, &[]).unwrap(); + assert!((h - f64::from(LEGEND_ROW + 48.0) * mm).abs() < 1e-6, "{h} mm"); + assert!((w - f64::from(48.0 + 12.0 + text::measure("a", 8.5, false)) * mm).abs() < 1e-4, "{w} mm"); + } } diff --git a/crates/render/src/point_marks.rs b/crates/render/src/point_marks.rs index 6342274383..815a189aa7 100644 --- a/crates/render/src/point_marks.rs +++ b/crates/render/src/point_marks.rs @@ -114,13 +114,24 @@ pub(crate) fn draw(pm: &mut Canvas, x: f32, y: f32, sym: &Symbol, strokes: &[Lin } } +/// How far from its centre, in its sizes, a shape reaches at an angle: a square's and a triangle's +/// corners lie past the 0.6 that holds them upright. +fn turned_reach(shape: rustgis_map::Marker) -> f32 { + match shape { + rustgis_map::Marker::Square => 0.9 * std::f32::consts::FRAC_1_SQRT_2, + rustgis_map::Marker::Triangle => 0.625, + _ => 0.6, + } +} + /// How far from the point (points) any of the marks reaches, for culling: a mark's offset and its -/// size (a character as far as its outline). +/// size (a character as far as its outline; a mark with an angle of its own as far as its corners). pub(crate) fn reach(sym: &Symbol, strokes: &[LineStroke]) -> f32 { marks(sym, strokes) .iter() .map(|m| { let extent = match m.shape { + LineMark::Marker(shape) if m.angle % 90.0 != 0.0 => crate::marker_reach(shape).max(turned_reach(shape)), LineMark::Marker(shape) => crate::marker_reach(shape).max(0.6), LineMark::Hash => 0.5, }; @@ -194,4 +205,17 @@ mod tests { assert!(pm.pixels().iter().any(|p| p.alpha() > 200)); assert!(reach(&sym, &strokes) >= 23.0 && plain(&[], 0.0) && !plain(&strokes, 0.0) && !plain(&[], 1.0)); } + + #[test] + fn a_mark_with_its_own_angle_reaches_its_corners() { + let sym = Symbol { size: 6.0, ..Symbol::default_for(GeometryType::Point, 0) }; + let at = |shape, angle| reach(&sym, &[mark(shape, Rgba::rgb(0, 0, 0), 40.0, (0.0, 0.0), angle)]); + for angle in [0.0, 90.0, 180.0] { + assert!((at(Marker::Square, angle) - 24.0).abs() < 0.01, "upright at {angle}"); + } + assert!((at(Marker::Square, 45.0) - 25.456).abs() < 0.01); + assert!((at(Marker::Triangle, 45.0) - 25.0).abs() < 0.01); + // A shape that a circle of 0.6 holds whatever its angle. + assert!((at(Marker::Diamond, 45.0) - 24.0).abs() < 0.01); + } } diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index d227c4c5c7..2b3d645a4e 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -152,27 +152,38 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu and **Outline** colours (`"style":"compass","fill":"#B91C1C"`). A scale bar's pick its **Style** (alternating bar, stepped line or single line), its **Units** (metres or kilometres to suit the scale, or kilometres, metres, miles or feet) and its **Divisions** (1 to 10), each - labelled where there is room (`"style":"line","units":"miles","divisions":2`). A legend shows what - its frame draws: only layers with a feature at the frame's scale (through their definition - query, display filters and scale range) and, for Unique Values, only the classes those features - have, with `` only when some feature falls in it and its symbol is not fully - transparent. Graduated Colors and - Proportional Symbols list their classes as they are (they are taken from the kept features when - the symbology is applied). A layer that draws - nothing there, such as an empty one, is left out, in layouts saved before this too. Tick **All - classes** in its properties (`"allClasses": true`) to list every class of every visible layer - instead, and **Hide other values** (`"hideOther": true`) to leave `` out of - the legend in either mode (the features it stands for are still drawn). A visible WMS or WMTS - layer with a legend is listed by its name over its service's legend picture, the one for the - frame's scale (as the Layers pane shows it), a pixel a point and narrowed to fit the legend's - width, in the order the map draws its layers (as the Layers pane lists them); one whose picture - can't be loaded (or is wider or taller than 2048 pixels) is left out. Exporting waits up to - half a minute for the pictures, as it waits for the map's tiles; in the browser the page is - drawn with those that have arrived, and again as the others arrive. Its **Layers** section - has a checkbox for each layer of the frame's map (and each WMS or WMTS layer with a legend): untick one to leave it out of the legend - while the map still draws it (a mask, a highlight, a basemap-like layer). Scripts give the same - with `"exclude": ["Graticule"]` on `layout.addElement` or `layout.update` (`[]` lists every - layer again); a renamed layer stays left out. + labelled where there is room (`"style":"line","units":"miles","divisions":2`). A legend's + parts: + - **What a legend lists**: what its frame draws: only layers with a feature at the frame's + scale (through their definition query, display filters and scale range) and, for Unique + Values, only the classes those features have, with `` only when some + feature falls in it and its symbol is not fully transparent. Graduated Colors and + Proportional Symbols list their classes as they are (they are taken from the kept features + when the symbology is applied). A layer that draws nothing there, such as an empty one, is + left out, in layouts saved before this too. Tick **All classes** in its properties + (`"allClasses": true`) to list every class of every visible layer instead, and **Hide other + values** (`"hideOther": true`) to leave `` out of the legend in either + mode (the features it stands for are still drawn). + - **Point symbols**: a point layer's symbol is drawn as the map draws it: its marker or the + stacked marks of its class or layer, its size and outline, the transparency of the layer and + its groups, and its reference scale at the frame's scale, unturned. A row has one symbol, so + it leaves out what changes from feature to feature (a symbol by expression, a marker's + rotation by a field), and it doesn't take the layer's blend mode. The row and the column of + symbols grow to hold a large one, up to 2048 points, past which the symbol is cut. A legend + already on the page keeps its size, so with a larger symbol its last rows may be cut and its + labels run past its right edge: make it larger to fit. + - **Web layers**: a visible WMS or WMTS layer with a legend is listed by its name over its + service's legend picture, the one for the frame's scale (as the Layers pane shows it), a + pixel a point and narrowed to fit the legend's width, in the order the map draws its layers + (as the Layers pane lists them); one whose picture can't be loaded (or is wider or taller + than 2048 pixels) is left out. Exporting waits up to half a minute for the pictures, as it + waits for the map's tiles; in the browser the page is drawn with those that have arrived, + and again as the others arrive. + - **Its Layers section**: a checkbox for each layer of the frame's map (and each WMS or WMTS + layer with a legend): untick one to leave it out of the legend while the map still draws it + (a mask, a highlight, a basemap-like layer). Scripts give the same with + `"exclude": ["Graticule"]` on `layout.addElement` or `layout.update` (`[]` lists every layer + again); a renamed layer stays left out. - **Colorbar**: the colour scale of a raster layer in the frame's map, as the map draws it (its stretch, colour ramp and enhancement): a gradient bar for a stretch or a tinted hillshade, steps labelled at their breaks for Classify, and a block per value for Unique Values and colour