Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/render/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ fn draw_page(
let grid = grid.as_ref().map(|g| (g, layout.decimal_comma));
let sections: Vec<_> =
sections.iter().filter_map(|s| Some((s, section_ends(map, &cam, (fw, fh), shape, s.line).ok()?))).collect();
let over = FrameOver { grid, sections: &sections };
let over = FrameOver { grid, sections: &sections, shape: Some(shape) };
let mut failed_source = None;
let Some(mut frame_pm) = frame_canvas(map, &view, pm.is_recording(), &mut pending.frames, over, &mut failed_source, env)
else {
Expand Down
91 changes: 88 additions & 3 deletions crates/render/src/layout/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ pub(super) struct FrameOver<'a> {
pub(super) grid: Option<(&'a Grid, bool)>,
/// The section lines drawn, each with its ends ([`section_ends`]).
pub(super) sections: &'a [(&'a Section, SectionEnds)],
/// The frame's shape, which the attribution stays inside; none for its whole box.
pub(super) shape: Option<&'a FrameShape>,
}

/// [`frame_map`] on a canvas: one that records (see [`crate::canvas`]) when `record` and the
Expand All @@ -43,7 +45,7 @@ pub(super) fn frame_canvas(
let img = img?;
*pending |= img.tiles_pending || img.data_pending || shadows;
let grid = over.grid.map(|(g, comma)| (&*map, view, g, comma));
Some(finish_frame(img, view.pixels_per_point, grid, over.sections))
Some(finish_frame(img, view.pixels_per_point, grid, over.sections, over.shape))
}

/// [`frame_map`] without waiting for tiles still on their way, for a preview drawn while the
Expand All @@ -56,7 +58,7 @@ pub fn frame_map_preview(map: &mut Map, camera: rustgis_map::Camera, w: f64, h:
/// Map preview during a layout pan, using the same expression context as its page.
pub fn frame_map_preview_with(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp: f64, env: &Env) -> Option<Pixmap> {
let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false };
crate::render_cpu(map, &view, false, false, &mut None, env).map(|img| finish_frame(img, ppp, None, &[]).into_pixmap())
crate::render_cpu(map, &view, false, false, &mut None, env).map(|img| finish_frame(img, ppp, None, &[], None).into_pixmap())
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}

/// A rendered frame map with its labels, its `grid` (drawn on `map` in `view`, with a decimal
Expand All @@ -68,6 +70,7 @@ pub(super) fn finish_frame(
ppp: f64,
grid: Option<(&Map, &View, &Grid, bool)>,
sections: &[(&Section, SectionEnds)],
shape: Option<&FrameShape>,
) -> Canvas {
let crate::Rendered { pixmap, recorded, labels, unplaced, label_layers, attribution, .. } = img;
let mut pm = recorded.unwrap_or_else(|| Canvas::from_pixmap(pixmap));
Expand All @@ -80,7 +83,10 @@ pub(super) fn finish_frame(
kept_clear.extend(draw_sections(&mut pm, sections, ppp));
pm.layer(None);
let (w, h) = (pm.width() as f32 / ppp as f32, pm.height() as f32 / ppp as f32);
let inset = crate::attribution_text(&attribution).map_or((0.0, 0.0), |(_, tw)| attribution_inset((w, h), tw, &kept_clear));
let inset = crate::attribution_text(&attribution).map_or((0.0, 0.0), |(_, tw)| match shape {
Some(s) if !matches!(s, FrameShape::Rectangle) => attribution_in_shape((w, h), tw, s, &kept_clear),
_ => attribution_inset((w, h), tw, &kept_clear),
});
crate::draw_attribution(&mut pm, &attribution, ppp as f32, inset);
pm
}
Expand Down Expand Up @@ -125,6 +131,85 @@ pub(super) fn attribution_inset((w, h): (f32, f32), tw: f32, labels: &[(Edge, [f
(bottom, right)
}

/// The most cells a shape is searched in for the attribution's place: a 5000 mm page's frame has
/// some 200 million points.
pub(super) const ATTRIBUTION_MASK_CELLS: f32 = 4_000_000.0;

/// Cells a point of that search on a `w` × `h` point frame.
pub(super) fn attribution_mask_scale((w, h): (f32, f32)) -> f32 {
(ATTRIBUTION_MASK_CELLS / (w * h)).sqrt().min(1.0)
}

/// [`attribution_inset`] on a frame of another `shape` than a rectangle, whose box's corner the
/// shape cuts off: the credit goes on the lowest row of the shape that holds all of it clear of
/// every one of the `labels`, against the right end of its room there. One that no row holds so
/// is centred on the widest room clear of them (of rows with none, on the widest inside the
/// shape), the lowest of those as wide; on a shape lower than the credit everywhere, which has
/// no such row, it lies across the shape's middle.
pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]) -> (f32, f32) {
let size = crate::ATTRIBUTION_SIZE;
// The shape at a cell a point (fewer on a huge frame), cut as the frame's drawing is
// ([`shape_path`]).
let scale = attribution_mask_scale((w, h));
let (cols, rows) = ((w * scale).ceil().max(1.0) as u32, (h * scale).ceil().max(1.0) as u32);
let Some(mut mask) = Mask::new(cols, rows) else { return (0.0, 0.0) };
let Some(path) = Rect::from_xywh(0.0, 0.0, w, h).and_then(|r| shape_path(shape, r)) else { return (0.0, 0.0) };
mask.fill_path(&path, FillRule::Winding, true, Transform::from_scale(scale, scale));
// The rows the credit takes, its halo included, and the gaps at its right and from a label.
let band = ((size * 1.6 * scale).ceil() as u32).min(rows);
let (margin, gap) = (crate::ATTRIBUTION_MARGIN, 2.0);
// The room it needs across, in cells.
let room = (tw + margin) * scale;
// Per column, how many rows up to this one are inside the shape.
let mut inside = vec![0u32; cols as usize];
// The credit's right end and its foot on the lowest row holding it; of the widest room, its
// length clear of the labels (with none, inside the shape), its middle and its foot.
let middle = path.bounds();
let across = ((middle.left() + middle.right()) / 2.0 * scale, (middle.top() + middle.bottom()) / 2.0 * scale + band as f32 / 2.0);
let (mut lowest, mut widest) = (None, ((0u32, 0u32), across.0, across.1));
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
for (y, line) in mask.data().chunks_exact(cols as usize).enumerate() {
for (n, &a) in inside.iter_mut().zip(line) {
// Wholly inside: a cell half covered would let the credit past the edge by half a cell.
*n = if a == u8::MAX { *n + 1 } else { 0 };
}
let foot = y as u32 + 1;
if foot < band {
continue;
}
let (top, foot) = ((foot - band) as f32, foot as f32);
// Each label's box with its gap, in cells.
let in_row: Vec<[f32; 4]> = labels
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
.iter()
.map(|(_, b)| [b[0] - gap, b[1] - gap, b[2] + gap, b[3] + gap].map(|v| v * scale))
.filter(|b| b[1] < foot && top < b[3])
.collect();
// The columns in a row inside the shape, and those of them clear of the labels.
let (mut run, mut free) = (0u32, 0u32);
for (x, &n) in inside.iter().enumerate() {
let full = n >= band;
let x = x as f32;
run = if full { run + 1 } else { 0 };
free = if full && !in_row.iter().any(|b| x < b[2] && b[0] < x + 1.0) { free + 1 } else { 0 };
let found = (free, if free == 0 { run } else { 0 });
if run > 0 && (found > widest.0 || (found == widest.0 && foot > widest.2)) {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
let length = if free > 0 { free } else { run };
widest = (found, x + 1.0 - length as f32 / 2.0, foot);
}
// The rightmost room of the lowest row wins.
if free as f32 >= room {
lowest = Some((x + 1.0, foot));
}
}
}
// Where [`crate::draw_attribution`] centres a credit this far in and up.
let (cx, foot) = match lowest {
Some((end, foot)) => (end / scale - margin - tw / 2.0, foot),
None => (widest.1 / scale, widest.2),
};
let cy = (foot - band as f32 / 2.0) / scale;
(h - size * 0.9 - cy, w - cx - tw.min(w) / 2.0 - margin)
}

pub(super) fn shape_path(shape: &FrameShape, r: Rect) -> Option<tiny_skia::Path> {
match shape {
FrameShape::Rectangle => Some(PathBuilder::from_rect(r)),
Expand Down
129 changes: 128 additions & 1 deletion crates/render/src/layout/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6164,7 +6164,7 @@ fn a_frames_attribution_keeps_clear_of_its_grid_labels() {
recorded: None,
label_layers: Vec::new(),
};
let framed = finish_frame(img, ppp, Some((&map, &view, &all, false)), &[]);
let framed = finish_frame(img, ppp, Some((&map, &view, &all, false)), &[], None);
let (a, b) = (labels_pm.pixmap(), framed.pixmap());
assert_ne!(a.data(), b.data(), "the credit is drawn");
for (_, [x0, y0, x1, y1]) in &labels {
Expand All @@ -6175,6 +6175,133 @@ fn a_frames_attribution_keeps_clear_of_its_grid_labels() {
}
}

/// The pixels of a `w` × `h` point frame its credit darkens once finished in `shape`, and
/// whether each lies inside that shape.
fn credit_pixels((w, h): (f32, f32), credit: &str, shape: &FrameShape) -> Vec<(u32, u32, bool)> {
let ppp = 2.0f32;
let mut pm = Pixmap::new((w * ppp) as u32, (h * ppp) as u32).unwrap();
pm.fill(tiny_skia::Color::WHITE);
let img = crate::Rendered {
pixmap: pm,
labels: Vec::new(),
unplaced: Vec::new(),
attribution: vec![credit.to_string()],
tiles_pending: false,
data_pending: false,
tile_errors: Vec::new(),
absent: Vec::new(),
partial: Vec::new(),
pending_in_place: Vec::new(),
recorded: None,
label_layers: Vec::new(),
};
let framed = finish_frame(img, f64::from(ppp), None, &[], Some(shape));
let pm = framed.pixmap();
let mut mask = Mask::new(pm.width(), pm.height()).unwrap();
let path = shape_path(shape, Rect::from_xywh(0.0, 0.0, w * ppp, h * ppp).unwrap()).unwrap();
mask.fill_path(&path, FillRule::Winding, true, tiny_skia::Transform::identity());
(0..pm.height())
.flat_map(|y| (0..pm.width()).map(move |x| (x, y)))
.filter(|&(x, y)| pm.pixel(x, y).is_some_and(|p| p.red() < 150))
.map(|(x, y)| (x, y, mask.data()[(y * pm.width() + x) as usize] >= 128))
.collect()
}

/// A round, elliptical, polygon or lasso frame writes its whole credit inside its shape (#3470):
/// in its box's corner, the shape cut it off.
#[test]
fn a_shaped_frames_attribution_stays_inside_its_shape() {
let credit = "© OpenStreetMap contributors";
// A lasso with a notch reaching in from the bottom right.
let notched = FrameShape::Polygon(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 0.4), (0.4, 0.6), (0.9, 1.0), (0.0, 1.0)]);
// Wide at the top, a point at the foot.
let down = FrameShape::Polygon(vec![(0.0, 0.0), (1.0, 0.0), (0.5, 1.0)]);
for (size, shape) in [
((227.0, 227.0), FrameShape::Circle),
((340.0, 142.0), FrameShape::Ellipse),
((340.0, 210.0), FrameShape::Circle),
((227.0, 227.0), down),
((227.0, 227.0), notched),
] {
let whole = credit_pixels(size, credit, &FrameShape::Rectangle).len();
let drawn = credit_pixels(size, credit, &shape);
let outside = drawn.iter().filter(|p| !p.2).count();
assert_eq!(outside, 0, "{shape:?} {size:?}: credit pixels outside the shape");
// The whole text, give or take its antialiasing at another place.
assert!(drawn.len() * 10 >= whole * 9, "{shape:?} {size:?}: {} of {whole}", drawn.len());
}
}

/// On a shaped frame the credit sits as low as its shape lets it, clear of the labels in its way;
/// one wider than every row of the shape is centred on the widest.
#[test]
fn a_shaped_frames_attribution_takes_the_lowest_row_that_holds_it() {
let size = crate::ATTRIBUTION_SIZE;
let place = |(w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]| {
let (bottom, right) = attribution_in_shape((w, h), tw, shape, labels);
(crate::attribution_center(w, tw, right), h - bottom - size * 0.9)
};
let (_, circle) = place((142.0, 142.0), 100.0, &FrameShape::Circle, &[]);
let (_, ellipse) = place((340.0, 142.0), 100.0, &FrameShape::Ellipse, &[]);
assert!(ellipse > circle && circle > 71.0, "ellipse {ellipse}, circle {circle}");
// A label where the credit would go: the credit keeps off it.
let (cx, cy) = place((227.0, 227.0), 100.0, &FrameShape::Circle, &[]);
let label = [(Edge::Bottom, [cx - 10.0, cy - 5.0, cx + 10.0, cy + 5.0])];
let (x, y) = place((227.0, 227.0), 100.0, &FrameShape::Circle, &label);
let (b, half) = (label[0].1, size * 0.8);
assert!(!(x - 50.0 < b[2] && b[0] < x + 50.0 && y - half < b[3] && b[1] < y + half), "({x}, {y}) covers {b:?}");
// Wider than the circle: its middle on the circle's middle.
let (x, y) = place((142.0, 142.0), 300.0, &FrameShape::Circle, &[]);
// The lowest of the rows as wide, a few points under the centre.
assert!((y - 71.0).abs() <= 6.0, "{y}");
assert!((x - 71.0).abs() <= 1.0, "{x}");
// Wider than every row, with a label on the widest: it goes on the widest row clear of it.
let across = [(Edge::Right, [0.0, 50.0, 142.0, 90.0])];
let (_, y) = place((142.0, 142.0), 300.0, &FrameShape::Circle, &across);
assert!(y - size * 0.8 >= 90.0 || y + size * 0.8 <= 50.0, "{y} covers the label");
// The same for one narrower than the frame that the labels leave no row wide enough: a
// label down the middle splits every row of the lower half.
let split = [(Edge::Bottom, [60.0, 40.0, 82.0, 142.0])];
let (x, y) = place((142.0, 142.0), 130.0, &FrameShape::Circle, &split);
assert!(y + size * 0.8 <= 40.0, "({x}, {y}) covers the label");
// Of rooms clear of the labels as wide as each other, the lowest, though the shape is
// narrower there.
let step = FrameShape::Polygon(
[(0.0, 0.0), (142.0, 0.0), (142.0, 60.0), (142.0, 142.0), (20.0, 142.0), (20.0, 60.0), (0.0, 60.0)]
.map(|(x, y): (f64, f64)| (x / 142.0, y / 142.0))
.to_vec(),
);
let bar = [(Edge::Bottom, [40.0, 0.0, 82.0, 142.0])];
let (x, y) = place((142.0, 142.0), 58.0, &step, &bar);
assert!(y > 120.0, "({x}, {y}) is not on the lowest of the rooms");
// A shape lower than the credit in a tall box: the credit lies across it.
let strip = FrameShape::Polygon(vec![(0.0, 0.4), (1.0, 0.4), (1.0, 0.42), (0.0, 0.42)]);
let (x, y) = place((227.0, 227.0), 100.0, &strip, &[]);
assert!((x - 113.5).abs() <= 1.0 && (y - 0.41 * 227.0).abs() <= 1.0, "({x}, {y})");
// A frame lower than the credit.
let (x, y) = place((20.0, 6.0), 100.0, &FrameShape::Circle, &[]);
assert!(x.is_finite() && y.is_finite());
}

/// A shape is searched for the credit's place within a fixed number of cells, however large the
/// frame: on one of a 5000 mm page the credit still goes inside the shape.
#[test]
fn a_huge_shaped_frames_attribution_is_placed_within_the_cell_budget() {
let side = 5000.0 * PT_PER_MM as f32;
let scale = attribution_mask_scale((side, side));
assert!((side * scale).ceil().powi(2) <= 1.01 * ATTRIBUTION_MASK_CELLS, "{scale}");
assert_eq!(attribution_mask_scale((227.0, 227.0)), 1.0, "a point a cell on an ordinary frame");
let (tw, size) = (175.0, crate::ATTRIBUTION_SIZE);
let (bottom, right) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &[]);
let (cx, cy) = (crate::attribution_center(side, tw, right), side - bottom - size * 0.9);
let r = side / 2.0;
for (dx, dy) in [(-0.5, -0.8), (0.5, -0.8), (-0.5, 0.8), (0.5, 0.8)] {
let (x, y) = (cx + dx * tw, cy + dy * size);
assert!((x - r).hypot(y - r) <= r, "({x}, {y}) leaves the circle");
}
assert!(cy > side * 0.95, "near the circle's foot: {cy}");
}

/// The credit stays in the corner with nothing under it, goes up above a bottom label and left
/// of a right one (above it, when going left would take it out of the frame), and pays no heed
/// to the top and left labels.
Expand Down
4 changes: 3 additions & 1 deletion crates/render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9485,6 +9485,8 @@ fn render_exported(map: &mut Map, view: &View) -> Result<Rendered, String> {

/// The size of the tile layers' credits, in points.
pub(crate) const ATTRIBUTION_SIZE: f32 = 9.0;
/// How far in from the right edge they end, in points.
pub(crate) const ATTRIBUTION_MARGIN: f32 = 4.0;

/// The tile layers' credits as [`draw_attribution`] writes them, and their whole width in points;
/// none when there are none.
Expand All @@ -9501,7 +9503,7 @@ pub(crate) fn attribution_text(attribution: &[String]) -> Option<(String, f32)>
/// `right` points further in from its right edge: one wider than the canvas is centred as if it
/// were the canvas's width, so it runs past both edges.
pub(crate) fn attribution_center(w: f32, tw: f32, right: f32) -> f32 {
w - right - tw.min(w) / 2.0 - 4.0
w - right - tw.min(w) / 2.0 - ATTRIBUTION_MARGIN
}

/// The tile layers' credits, small, in the bottom-right corner: `inset` points further in (up
Expand Down
12 changes: 7 additions & 5 deletions docs/user-guide/layouts.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,11 +299,13 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu
paper colour to match a coloured page.

- **Map frames**: rectangle, circle and ellipse frames, or polygon and lasso frames drawn on the
page. Each frame shows a map of the project at its own centre and scale. Turn on **Pan/Zoom
Map** (Map Frames group, or a frame's properties) to drag inside frames to pan their maps and
turn the wheel to zoom them about the pointer; Esc turns it off. Without it, Shift-drag a frame
to pan its map. Double-click a frame to match the map view, or set the scale in its properties:
from the whole world down to site plans at 1:20, finds at 1:1 and 2:1 (a scale of 1:0.5).
page. The credits of a frame's tile layers are written inside its shape, their ends cut only
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
when they are wider than it. Each frame shows a map of the project at its own centre and
scale. Turn on **Pan/Zoom Map** (Map Frames group, or a frame's properties) to drag inside
frames to pan their maps and turn the wheel to zoom them about the pointer; Esc turns it off.
Without it, Shift-drag a frame to pan its map. Double-click a frame to match the map view, or
set the scale in its properties: from the whole world down to site plans at 1:20, finds at 1:1
and 2:1 (a scale of 1:0.5).
A frame can be turned and tilted like the map view: a new frame, or one matched to the view,
takes the view's bearing and pitch, and **Bearing** and **Pitch** in its properties (or
`layout.update` with `bearing` and `pitch`) set them. Its north arrows turn with it. **Grid** draws a labelled graticule over a frame; **Section Lines** draws the traces of cross-sections; **Extent Indicator** outlines another frame's
Expand Down
Loading