RasterDisplay extent: tiled copies and a region past the document, for source and painted pictures

This commit is contained in:
aiongg
2026-11-13 01:44:11 +00:00
parent 0748cf6634
commit dbd8ec10c6
6 changed files with 294 additions and 48 deletions
+1 -1
View File
@@ -246,7 +246,7 @@ impl Detail {
px(seen.max.y, page.min.y, true),
);
// One page pixel is one device pixel, so the plan's zoom is 1.
let plan = DetailPlan::of(size, side, 1.0, visible)?;
let plan = DetailPlan::of(PixelRect::of_size(size), side, 1.0, visible)?;
let r = plan.region;
let (w, h) = (size.width as f32, size.height as f32);
let part = Rect::from_min_max(pos2(r.x0 as f32 / w, r.y0 as f32 / h), pos2(r.x1 as f32 / w, r.y1 as f32 / h));
+1 -1
View File
@@ -51,7 +51,7 @@ pub use words::SplitWords;
mod app_paint;
mod raster;
pub use app_paint::AppPaint;
pub use raster::{DetailPlan, RasterDisplay, RasterDisplayOutput, RasterStyle, snap_to_texels};
pub use raster::{DetailPlan, Extent, RasterDisplay, RasterDisplayOutput, RasterStyle, snap_to_texels};
// l4d-space
mod opacity_keys;
+12 -13
View File
@@ -3,7 +3,7 @@
use crate::canvas::PixelRect;
use crate::primitives::texture_factor;
use craft_behavior::{CanvasView, PixelSize};
use craft_behavior::CanvasView;
/// The detail region snaps outward to multiples of this many texels.
const DETAIL_QUANTUM: i32 = 256;
@@ -38,14 +38,13 @@ fn proxy_factor(device_zoom: f64) -> u32 {
impl DetailPlan {
/// The plan for a view at `device_zoom` (device pixels per document pixel) over `visible`, or `None` when the
/// base texture is already as fine as the screen or nothing is in view. `size` is the document and `side` the
/// device's texture side.
pub fn of(size: PixelSize, side: u32, device_zoom: f64, visible: PixelRect) -> Option<DetailPlan> {
/// base texture is already as fine as the screen or nothing is in view. `bounds` is what the base texture holds
/// (the document, or a region reaching past it) and `side` the device's texture side.
pub fn of(bounds: PixelRect, side: u32, device_zoom: f64, visible: PixelRect) -> Option<DetailPlan> {
if !device_zoom.is_finite() || device_zoom <= 0.0 {
return None;
}
let base = texture_factor(size, side);
let bounds = PixelRect::of_size(size);
let base = texture_factor(bounds.size(), side);
let seen = visible.intersect(&bounds);
if seen.is_empty() {
return None;
@@ -69,17 +68,17 @@ impl DetailPlan {
None
}
/// The plan for `view` over a document of `size`: the document pixels it shows, and the device zoom of its
/// finer axis at `pixels_per_point`.
pub fn in_view(view: &CanvasView, size: PixelSize, side: u32, pixels_per_point: f32) -> Option<DetailPlan> {
/// The plan for `view` over a base texture of `bounds`: the pixels of it the view shows, and the device zoom of
/// its finer axis at `pixels_per_point`.
pub fn in_view(view: &CanvasView, bounds: PixelRect, side: u32, pixels_per_point: f32) -> Option<DetailPlan> {
let device_zoom = view.zoom.max(view.zoom_x()) * f64::from(pixels_per_point);
Self::of(size, side, device_zoom, visible_pixels(view, size))
Self::of(bounds, side, device_zoom, visible_pixels(view, bounds))
}
}
/// The document pixels `view` shows (its bounding box when turned), rounded outward with a margin for filtering and
/// clipped to a document of `size`.
fn visible_pixels(view: &CanvasView, size: PixelSize) -> PixelRect {
/// clipped to `bounds`.
fn visible_pixels(view: &CanvasView, bounds: PixelRect) -> PixelRect {
let shown = view.visible();
let clamp = |n: f64| n.clamp(-1e9, 1e9) as i32;
let seen = PixelRect::new(
@@ -88,7 +87,7 @@ fn visible_pixels(view: &CanvasView, size: PixelSize) -> PixelRect {
clamp(shown.x1.ceil()) + FILTER_MARGIN,
clamp(shown.y1.ceil()) + FILTER_MARGIN,
);
seen.intersect(&PixelRect::of_size(size))
seen.intersect(&bounds)
}
/// `region` grown outward to whole texels of `factor` pixels counted from `origin`, the document pixel where the
+144 -30
View File
@@ -9,6 +9,9 @@
//! pixels at 100 percent and the cost follows the window, not the document. Pixels are drawn sharp (nearest) from
//! 100 percent up and filtered below.
//!
//! Past the document's edge the display shows nothing, the source's pixels out to a larger region (a crop preview of
//! layers past the canvas), or copies of the document around it (a pattern preview); see [`Extent`].
//!
//! The display takes no pointer and no keys and declares no parts: a press on it reaches the canvas's tool.
mod detail;
@@ -33,6 +36,7 @@ use detail::{texel_extent, texel_origin};
use egui::epaint::{Mesh, Vertex};
use egui::{Color32, ColorImage, Context, Id, Pos2, Response, Shape, TextureFilter, TextureOptions, Vec2, pos2};
use std::collections::HashMap;
use std::ops::RangeInclusive;
/// The style of a raster display: it has no look of its own.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
@@ -42,11 +46,100 @@ pub struct RasterStyle {
metrics: Metrics,
}
/// How far a display's picture reaches past the document's edge.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Extent {
/// The document alone.
#[default]
Document,
/// The document and the pixels around it out to this region (Crop's preview of layers past the canvas). A source
/// picture reads the region from the source; a painted picture is expected to paint it. The checkerboard covers
/// the region; the edge stays at the document's edge.
Region(PixelRect),
/// Copies of the document a whole document size apart, filling the canvas around it (Pattern Preview), at most
/// 31 along each axis, centred on the view. A source picture draws its textures again for each copy; a painted picture is
/// called once per copy with the view shifted by the copy's offset. The checkerboard covers the copies; the edge
/// stays at the document's edge.
Tiled,
}
/// Most copies a tiled display draws along each axis, the document included. A tiny document zoomed far out would
/// otherwise need thousands of copies per pass; past this the pattern stops, and the run is centred on the view.
const MOST_COPIES: i32 = 31;
/// The copies a tiled display draws, as columns and rows of whole document sizes from the document: copy `(i, j)` is
/// the document moved by `i` widths and `j` heights. The document itself is drawn whether or not it is in the run.
#[derive(Clone, Debug, PartialEq)]
struct Tiles {
columns: RangeInclusive<i32>,
rows: RangeInclusive<i32>,
}
impl Tiles {
/// The document alone.
fn document() -> Self {
Tiles { columns: 0..=0, rows: 0..=0 }
}
/// The copies of a document of `size` that cover `visible`, the document area a view shows.
fn covering(visible: Rect64, size: PixelSize) -> Self {
match (tile_run(visible.x0, visible.x1, size.width), tile_run(visible.y0, visible.y1, size.height)) {
(Some(columns), Some(rows)) => Tiles { columns, rows },
_ => Self::document(),
}
}
/// The offset in document pixels of each copy to draw, the document's own first.
fn offsets(&self, size: PixelSize) -> impl Iterator<Item = Vec2> + '_ {
let (width, height) = (size.width as f32, size.height as f32);
let copies = self.rows.clone().flat_map(move |j| self.columns.clone().map(move |i| (i, j))).filter(|&copy| copy != (0, 0));
std::iter::once((0, 0)).chain(copies).map(move |(i, j)| Vec2::new(i as f32 * width, j as f32 * height))
}
/// The area the copies and the document cover, in document pixels.
fn cover(&self, size: PixelSize) -> Rect64 {
let (width, height) = (f64::from(size.width), f64::from(size.height));
let (columns, rows) = ((*self.columns.start()).min(0)..=(*self.columns.end()).max(0), (*self.rows.start()).min(0)..=(*self.rows.end()).max(0));
Rect64::new(
f64::from(*columns.start()) * width,
f64::from(*rows.start()) * height,
f64::from(*columns.end() + 1) * width,
f64::from(*rows.end() + 1) * height,
)
}
}
/// The tiles `len` pixels long along one axis that overlap `lo..hi`, at most [`MOST_COPIES`] of them, centred on the
/// middle of `lo..hi` when more would fit; `None` for an empty or non-finite span.
fn tile_run(lo: f64, hi: f64, len: u32) -> Option<RangeInclusive<i32>> {
if len == 0 || !lo.is_finite() || !hi.is_finite() || hi <= lo {
return None;
}
let n = f64::from(len);
// Far past any real view; keeps the ± MOST_COPIES arithmetic inside i32.
let index = |v: f64| v.clamp(-1e9, 1e9) as i32;
let (first, last) = (index((lo / n).floor()), index((hi / n).ceil()) - 1);
if last.saturating_sub(first) < MOST_COPIES {
return Some(first..=last);
}
let middle = index(((lo + hi) / 2.0 / n).floor());
let half = MOST_COPIES / 2;
Some(middle - half..=middle + half)
}
/// `view` looking `offset` document pixels back, so the document drawn through it lands `offset` along on screen.
fn shifted(mut view: CanvasView, offset: Vec2) -> CanvasView {
view.center -= craft_behavior::kurbo::Vec2::new(f64::from(offset.x), f64::from(offset.y));
view
}
/// Which picture of a display a texture holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Level {
/// The whole document at one texel per `texture_factor` pixels.
Base,
/// What the picture covers (the document, or the region of [`Extent::Region`]) at one texel per `texture_factor`
/// pixels. A new region is a new key, so a texture never shows one region at another's place.
Base(PixelRect),
/// The part in view at the screen's resolution. A new plan is a new key, so a texture is never partly of
/// two plans.
Detail(DetailPlan),
@@ -76,10 +169,14 @@ struct Textures {
detail: Option<(CachedTexture, DetailPlan)>,
}
/// What `update` leaves for `paint` and `finish`: the view to draw through and, for a source picture, its textures.
/// What `update` leaves for `paint` and `finish`: the view to draw through, what the picture covers and where its
/// copies go, and, for a source picture, its textures.
struct Shown {
view: CanvasView,
size: PixelSize,
/// The document, or the region of [`Extent::Region`] around it.
bounds: PixelRect,
tiles: Tiles,
textures: Option<Textures>,
}
@@ -121,6 +218,8 @@ impl Outcome for RasterDisplayOutput {
/// - **Transparency.** [`checkerboard`](Self::checkerboard) draws a transparency grid under the document, holding
/// still while the document scrolls; the app's [`Checker`] sets its cells, and an empty one is the theme's.
/// Without it the document draws straight on the canvas (an opaque document, a video frame).
/// - **Extent.** [`extent`](Self::extent) lets the picture reach past the document's edge: out to a larger region,
/// or as copies around it ([`Extent`]).
/// - **Edge.** [`outlined`](Self::outlined) draws the divider rule just outside the document's edge, so an image
/// reads apart from the surface around it; a mapped display draws none.
/// - **Turned views.** A rotated or mirrored view draws each texture as one quad on the view's mapped corners.
@@ -138,6 +237,9 @@ pub struct RasterDisplay<'a> {
/// The divider rule just outside the document's edge.
#[prop(flag)]
outlined: bool,
/// How far the picture reaches past the document's edge.
#[prop]
extent: Extent,
read: PixelRect,
shown: Option<Shown>,
mapping: Option<Mapping>,
@@ -167,7 +269,7 @@ impl<'a> RasterDisplay<'a> {
}
fn of(label: impl Into<Label>, picture: Picture<'a>) -> Self {
RasterDisplay { common: Common::new(), picture, checkerboard: None, outlined: false, read: PixelRect::default(), shown: None, mapping: None }
RasterDisplay { common: Common::new(), picture, checkerboard: None, outlined: false, extent: Extent::Document, read: PixelRect::default(), shown: None, mapping: None }
.label(label)
}
@@ -175,7 +277,8 @@ impl<'a> RasterDisplay<'a> {
/// perspective frame shows the image foreshortened. The image fills the unit square unless
/// [`placed`](Self::placed) says otherwise; a cell whose centre lies outside the unit square is left out. A
/// mapped display draws its whole-document texture alone: the detail texture of a flat display has no place on
/// a mesh. A source display only: a painted one draws through the view as the app paints it.
/// a mesh, and neither has the region or the copies of an [`Extent`]: a mapped display shows the document alone.
/// A source display only: a painted one draws through the view as the app paints it.
#[must_use]
pub fn mapped(mut self, frame: Homography, cells: u32) -> Self {
let placed = self.mapping.map_or(Rect64::new(0.0, 0.0, 1.0, 1.0), |mapping| mapping.placed);
@@ -261,10 +364,10 @@ impl<'a> RasterDisplay<'a> {
}
}
/// Drops the detail textures of other plans than `plan`.
fn retain_plan(ctx: &Context, id: Id, held: &mut Held, plan: Option<DetailPlan>) {
/// Drops the textures of other regions than `bounds` and of other plans than `plan`.
fn retain(ctx: &Context, id: Id, held: &mut Held, bounds: PixelRect, plan: Option<DetailPlan>) {
let kept = |level: &Level| match level {
Level::Base => true,
Level::Base(kept) => *kept == bounds,
Level::Detail(kept) => Some(*kept) == plan,
};
for sharp in [true, false] {
@@ -301,32 +404,37 @@ impl Component for RasterDisplay<'_> {
let Some(space) = canvas_space(&cx.env) else { return };
let (ctx, id) = (cx.ctx.clone(), cx.id);
let size = self.picture.size();
let bounds = PixelRect::of_size(size);
let document = PixelRect::of_size(size);
let (bounds, tiles) = match (self.mapping, self.extent) {
(Some(_), _) | (None, Extent::Document) => (document, Tiles::document()),
(None, Extent::Region(region)) => (region.union(&document), Tiles::document()),
(None, Extent::Tiled) => (document, Tiles::covering(space.view.visible(), size)),
};
let mut held = std::mem::take(cx.keep::<Held>());
let source = match &self.picture {
Picture::Source(source) if !bounds.is_empty() => *source,
Picture::Source(source) if !document.is_empty() => *source,
// An empty document, or a picture the app paints: the display holds no textures.
_ => {
Self::release(&ctx, id);
if !bounds.is_empty() {
self.shown = Some(Shown { view: space.view, size, textures: None });
if !document.is_empty() {
self.shown = Some(Shown { view: space.view, size, bounds, tiles, textures: None });
}
return;
}
};
let side = texture_side(&ctx);
let factor = texture_factor(size, side);
let (base, base_read) = Self::bring_up_to_date(source, &ctx, id, &mut held, Level::Base, bounds, factor);
let plan = DetailPlan::in_view(&space.view, size, side, space.pixels_per_point).filter(|_| self.mapping.is_none());
let factor = texture_factor(bounds.size(), side);
let (base, base_read) = Self::bring_up_to_date(source, &ctx, id, &mut held, Level::Base(bounds), bounds, factor);
let plan = DetailPlan::in_view(&space.view, bounds, side, space.pixels_per_point).filter(|_| self.mapping.is_none());
let detail = plan.map(|plan| {
let (texture, read) = Self::bring_up_to_date(source, &ctx, id, &mut held, Level::Detail(plan), plan.region, plan.factor);
self.read = self.read.union(&read);
(texture, plan)
});
Self::retain_plan(&ctx, id, &mut held, plan);
Self::retain(&ctx, id, &mut held, bounds, plan);
*cx.keep::<Held>() = held;
self.read = self.read.union(&base_read);
self.shown = Some(Shown { view: space.view, size, textures: Some(Textures { base: (base, factor), detail }) });
self.shown = Some(Shown { view: space.view, size, bounds, tiles, textures: Some(Textures { base: (base, factor), detail }) });
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
@@ -334,22 +442,28 @@ impl Component for RasterDisplay<'_> {
let painter = ui.content_painter(cx);
let corners = shown.view.quad(Rect64::new(0.0, 0.0, f64::from(shown.size.width), f64::from(shown.size.height)));
if let Some(checker) = &self.checkerboard {
painter.painter.add(checker.shape(painter.painter.ctx(), &ui.env.tokens, CheckerArea::Quad(corners), shown.view.rect.min));
let bounds = shown.bounds;
let covered = Rect64::new(f64::from(bounds.x0), f64::from(bounds.y0), f64::from(bounds.x1), f64::from(bounds.y1)).union(shown.tiles.cover(shown.size));
painter.painter.add(checker.shape(painter.painter.ctx(), &ui.env.tokens, CheckerArea::Quad(shown.view.quad(covered)), shown.view.rect.min));
}
match (&mut self.picture, &shown.textures) {
(Picture::Painted { paint, .. }, _) => paint.paint(&painter, shown.view),
(Picture::Source(_), Some(textures)) => {
let (texture, factor) = textures.base;
if let Some(mapping) = &self.mapping {
painter.painter.add(mapped_mesh(&shown.view, texture, factor, shown.size, mapping));
return;
}
painter.painter.add(textured_quad(&shown.view, texture, factor, PixelRect::of_size(shown.size)));
if let Some((texture, plan)) = textures.detail {
painter.painter.add(textured_quad(&shown.view, texture, plan.factor, plan.region));
if let (Picture::Source(_), Some(textures), Some(mapping)) = (&self.picture, &shown.textures, &self.mapping) {
let (texture, factor) = textures.base;
painter.painter.add(mapped_mesh(&shown.view, texture, factor, shown.size, mapping));
return;
}
for offset in shown.tiles.offsets(shown.size) {
let view = shifted(shown.view, offset);
match (&mut self.picture, &shown.textures) {
(Picture::Painted { paint, .. }, _) => paint.paint(&painter, view),
(Picture::Source(_), Some(textures)) => {
let (texture, factor) = textures.base;
painter.painter.add(textured_quad(&view, texture, factor, shown.bounds));
if let Some((texture, plan)) = textures.detail {
painter.painter.add(textured_quad(&view, texture, plan.factor, plan.region));
}
}
(Picture::Source(_), None) => {}
}
(Picture::Source(_), None) => {}
}
if self.outlined {
painter.with_draw(|draw| edge(draw, corners));
+9 -1
View File
@@ -40,6 +40,11 @@ impl PixelRect {
(self.y1 - self.y0).max(0)
}
/// Width and height in pixels.
pub fn size(&self) -> PixelSize {
PixelSize::new(self.width().unsigned_abs(), self.height().unsigned_abs())
}
/// Whether the rectangle covers no pixel.
pub fn is_empty(&self) -> bool {
self.width() == 0 || self.height() == 0
@@ -81,6 +86,9 @@ pub trait RasterSource {
/// Writes the composite of `region` into `out` (sRGBA, unmultiplied), one texel per `factor` pixels each way
/// (`factor` is a power of two for a detail texture and `texture_factor` of `primitives::textures` for the base
/// one; 1 is full resolution). `out` is already `region / factor` texels, rounded up.
/// one; 1 is full resolution). `out` is already `region / factor` texels, rounded up. The region lies inside the
/// document unless the display reaches past it ([`Extent::Region`](super::Extent::Region)): then it may start
/// left of or above the origin and end past the size, and the source writes what it has there (layers' pixels
/// past the canvas, transparency elsewhere).
fn read(&self, region: PixelRect, factor: u32, out: &mut ColorImage);
}
+127 -2
View File
@@ -2,12 +2,12 @@
use craft_behavior::kurbo::{Point, Rect as Rect64};
use craft_behavior::{CanvasView, PixelSize};
use craft_ui::canvas::{AppPaint, Canvas, PageFrame, Pasteboard, PixelRect, RasterDisplay, RasterSource};
use craft_ui::canvas::{AppPaint, Canvas, Extent, PageFrame, Pasteboard, PixelRect, RasterDisplay, RasterSource};
use craft_ui::canvas_controls::PixelGrid;
use craft_ui::contract::{Show as _, ShowContainer as _};
use craft_ui::primitives::{Checker, Revision};
use craft_ui::testing::{Fixture, trial};
use egui::{Color32, ColorImage, PaintCallback, Pos2, Rect, Shape, Vec2};
use egui::{Color32, ColorImage, PaintCallback, Pos2, Rect, Shape, TextureId, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
@@ -193,3 +193,128 @@ fn a_painted_display_paints_once_a_frame() {
assert_eq!(paints.get(), 1, "one paint in a frame of {} passes", fixture.passes());
}
}
/// A canvas looking at `center` at `zoom` that shows a display of `document` with the checkerboard, the edge and
/// `extent`: a source display, or, while `painted` is set, a painted one whose paint adds a GPU paint callback and
/// records the view of each call in `paints`.
fn extent_canvas(document: Rc<Document>, center: Point, zoom: f64, extent: Rc<Cell<Extent>>, painted: bool, paints: Rc<RefCell<Vec<CanvasView>>>) -> Fixture {
let view = CanvasView::new(Rect::from_min_size(Pos2::ZERO, CANVAS), center, zoom);
let callback: Arc<dyn std::any::Any + Send + Sync> = Arc::new(());
let mut fixture = Fixture::new(move |ui| {
Canvas::new("Document").view(view).show(ui, |ui, body| {
let display = if painted {
let paint = AppPaint::new(|painter, view: CanvasView| {
paints.borrow_mut().push(view);
painter.painter.add(Shape::Callback(PaintCallback { rect: view.rect, callback: Arc::clone(&callback) }));
});
RasterDisplay::painted("Picture", document.size, paint)
} else {
RasterDisplay::new("Picture", &*document)
};
display.checkerboard(Checker::new()).outlined().extent(extent.get()).show_at(ui, body.rect);
});
});
fixture.room(CANVAS);
fixture.settle();
fixture
}
/// The screen bounds of each textured mesh in `shapes`, in paint order: the checkerboard, then a source's pictures.
fn textured(shapes: &[Shape]) -> Vec<Rect> {
shapes
.iter()
.filter_map(|shape| match shape {
Shape::Mesh(mesh) if mesh.texture_id != TextureId::default() => Some(mesh.calc_bounds()),
_ => None,
})
.collect()
}
fn doc_rect(view: &CanvasView, r: Rect64) -> Rect {
Rect::from_points(&view.quad(r))
}
fn near(a: Rect, b: Rect) -> bool {
(a.min - b.min).length() < 0.01 && (a.max - b.max).length() < 0.01
}
/// One frame of a display of `document` with `extent`, either picture: where each picture of the document went on
/// screen (a source's textured quads, or the document through each view the app's paint was given), the
/// checkerboard's bounds, and the bounds of everything painted after the pictures (the edge).
fn pictures(document: &Rc<Document>, center: Point, zoom: f64, extent: Extent, painted: bool) -> (Vec<Rect>, Rect, Rect) {
let paints = Rc::new(RefCell::new(Vec::new()));
let mut fixture = extent_canvas(Rc::clone(document), center, zoom, Rc::new(Cell::new(extent)), painted, Rc::clone(&paints));
paints.borrow_mut().clear();
let shapes = fixture.frame_shapes();
let meshes = textured(&shapes);
let whole = Rect64::new(0.0, 0.0, f64::from(document.size.width), f64::from(document.size.height));
let placed: Vec<Rect> = if painted { paints.borrow().iter().map(|view| doc_rect(view, whole)).collect() } else { meshes[1..].to_vec() };
let last_picture = shapes
.iter()
.rposition(|shape| matches!(shape, Shape::Callback(_)) || matches!(shape, Shape::Mesh(mesh) if mesh.texture_id != TextureId::default()))
.unwrap_or(0);
let after = shapes[last_picture + 1..].iter().fold(Rect::NOTHING, |all, shape| all.union(shape.visual_bounding_rect()));
(placed, meshes[0], after)
}
#[trial]
fn tiled_copies_fill_the_canvas_a_document_apart() {
// A 100 x 70 document at 50 percent: each copy is 50 x 35 points, and no copy's edge falls on the canvas's.
let document = Document::new(100, 70);
let center = Point::new(50.0, 35.0);
let view = CanvasView::new(Rect::from_min_size(Pos2::ZERO, CANVAS), center, 0.5);
let canvas = view.rect;
let at = |i: i32, j: i32| doc_rect(&view, Rect64::new(f64::from(i) * 100.0, f64::from(j) * 70.0, f64::from(i + 1) * 100.0, f64::from(j + 1) * 70.0));
let in_view: Vec<Rect> = (-40..40).flat_map(|j| (-40..40).map(move |i| (i, j))).map(|(i, j)| at(i, j)).filter(|r| r.intersects(canvas)).collect();
for painted in [false, true] {
let (placed, checker, edge) = pictures(&document, center, 0.5, Extent::Tiled, painted);
assert_eq!(placed.len(), in_view.len(), "painted {painted}: one picture for each document-sized tile the canvas shows");
assert!(in_view.iter().all(|tile| placed.iter().any(|r| near(*r, *tile))), "painted {painted}: every tile in view has its copy");
assert!(near(placed[0], at(0, 0)), "painted {painted}: the document draws first, in its place");
let all = in_view.iter().fold(Rect::NOTHING, |all, r| all.union(*r));
assert!(near(checker, all), "painted {painted}: the checkerboard lies under the copies: {checker:?} vs {all:?}");
assert!(edge.expand(-3.0).contains_rect(at(0, 0).expand(-6.0)) && at(0, 0).expand(3.0).contains_rect(edge), "painted {painted}: the edge stays on the document: {edge:?}");
let (filled, _, _) = pictures(&document, center, 20.0, Extent::Tiled, painted);
assert_eq!(filled.len(), 1, "painted {painted}: a document filling the canvas has no copies");
// A one-pixel document far out would need thousands of copies; the run stops at 31 a side, centred on the view.
let (capped, _, _) = pictures(&Document::new(1, 1), Point::new(0.5, 0.5), 0.5, Extent::Tiled, painted);
assert_eq!(capped.len(), 31 * 31, "painted {painted}: copies are capped");
let middle = capped.iter().fold(Rect::NOTHING, |all, r| all.union(*r)).center();
assert!((middle - canvas.center()).length() < 1.0, "painted {painted}: the capped run is centred on the view: {middle:?}");
}
}
#[trial]
fn a_region_past_the_document_draws_out_to_the_region() {
let document = Document::new(100, 70);
let region = PixelRect::new(-60, -30, 200, 120);
let center = Point::new(70.0, 45.0);
let view = CanvasView::new(Rect::from_min_size(Pos2::ZERO, CANVAS), center, 2.0);
let on_screen = |r: PixelRect| doc_rect(&view, Rect64::new(f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)));
let page = on_screen(PixelRect::new(0, 0, 100, 70));
for painted in [false, true] {
document.reads.borrow_mut().clear();
let (placed, checker, edge) = pictures(&document, center, 2.0, Extent::Region(region), painted);
assert!(near(checker, on_screen(region)), "painted {painted}: the checkerboard covers the region: {checker:?}");
assert!(edge.expand(-3.0).contains_rect(page.expand(-6.0)) && page.expand(3.0).contains_rect(edge), "painted {painted}: the edge stays on the document: {edge:?}");
if painted {
assert_eq!(placed.len(), 1, "the app paints once, through the view on screen");
assert!(document.reads.borrow().is_empty(), "a painted display reads nothing");
} else {
assert_eq!(placed.len(), 1, "one picture");
assert!(near(placed[0], on_screen(region)), "the source's picture spans the region: {:?}", placed[0]);
assert!(document.reads.borrow().contains(&(region, 1)), "the source is read past the document: {:?}", document.reads.borrow());
}
}
// The same size of region moved: read again, never shown from the texture of the old place.
let extent = Rc::new(Cell::new(Extent::Region(region)));
let mut fixture = extent_canvas(Rc::clone(&document), center, 2.0, Rc::clone(&extent), false, Rc::new(RefCell::new(Vec::new())));
let moved = PixelRect::new(-50, -30, 210, 120);
document.reads.borrow_mut().clear();
extent.set(Extent::Region(moved));
fixture.frame(Vec::new());
assert!(document.reads.borrow().contains(&(moved, 1)), "a moved region is read: {:?}", document.reads.borrow());
}