mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
Merge pull request #2706 from brytoncooper/perf/render-navigation-1250
M8: page-scoped retained scan, zoom reuse, and reciprocal multiply-shift box blur (#1250)
This commit is contained in:
5 files changed
+814
-61
No files matched your search
+84
-1
@@ -48,6 +48,32 @@ fn row_jobs(src: &[[u8; 4]], dst: &mut [[u8; 4]], w: usize, job: impl Fn(&[[u8;
|
||||
src.chunks(n).zip(dst.chunks_mut(n)).for_each(|(s, d)| job(s, d));
|
||||
}
|
||||
|
||||
/// Division by a box's width `d` as a multiply and a shift, exact for every sum of `d` bytes (at
|
||||
/// most 255 × `d`, under `2^n` for `n` = 8 + ⌈log₂ d⌉): with `m` = ⌈2^(n + ⌈log₂ d⌉) / d⌉, the
|
||||
/// product overshoots the quotient by less than 1/d, which never reaches the next whole number.
|
||||
/// A divide per channel per pixel took about a third of a blur's time on one thread.
|
||||
#[derive(Clone, Copy)]
|
||||
struct ByWidth {
|
||||
m: u64,
|
||||
shift: u32,
|
||||
}
|
||||
|
||||
impl ByWidth {
|
||||
/// `None` for widths whose products could pass 64 bits (over 2^23 pixels: no box is that wide).
|
||||
fn new(d: u32) -> Option<ByWidth> {
|
||||
let log = u32::BITS - d.checked_sub(1)?.leading_zeros();
|
||||
if log > 23 {
|
||||
return None;
|
||||
}
|
||||
let shift = 8 + 2 * log;
|
||||
Some(ByWidth { m: (1u64 << shift).div_ceil(u64::from(d)), shift })
|
||||
}
|
||||
|
||||
fn of(self, sum: u32) -> u8 {
|
||||
((u64::from(sum) * self.m) >> self.shift) as u8
|
||||
}
|
||||
}
|
||||
|
||||
/// One row box-blurred by radius `r` (transparent past its ends) into `dst`, the same length.
|
||||
fn box_blur_row(src: &[[u8; 4]], dst: &mut [[u8; 4]], r: usize) {
|
||||
if r == 0 {
|
||||
@@ -55,6 +81,14 @@ fn box_blur_row(src: &[[u8; 4]], dst: &mut [[u8; 4]], r: usize) {
|
||||
return;
|
||||
}
|
||||
let div = (2 * r + 1) as u32;
|
||||
match ByWidth::new(div) {
|
||||
Some(by) => box_sums(src, dst, r, |a| by.of(a)),
|
||||
None => box_sums(src, dst, r, |a| (a / div) as u8),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`box_blur_row`] with each window's sum divided by its width by `quotient`.
|
||||
fn box_sums(src: &[[u8; 4]], dst: &mut [[u8; 4]], r: usize, quotient: impl Fn(u32) -> u8) {
|
||||
let mut acc = [0u32; 4];
|
||||
for p in src.iter().take(r + 1) {
|
||||
for (a, c) in acc.iter_mut().zip(p) {
|
||||
@@ -62,7 +96,7 @@ fn box_blur_row(src: &[[u8; 4]], dst: &mut [[u8; 4]], r: usize) {
|
||||
}
|
||||
}
|
||||
for (x, d) in dst.iter_mut().enumerate() {
|
||||
*d = acc.map(|a| (a / div) as u8);
|
||||
*d = acc.map("ient);
|
||||
if let Some(p) = src.get(x + r + 1) {
|
||||
for (a, c) in acc.iter_mut().zip(p) {
|
||||
*a += u32::from(*c);
|
||||
@@ -586,6 +620,55 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Blur timings, the best of several runs: in parallel (a full render's blur) and on one
|
||||
/// thread (a band of a parallel render, the browser). Run in release:
|
||||
/// `cargo test --release -p figcraft-render --lib blur_timings -- --ignored --nocapture`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
#[ignore = "timing: run in release with --ignored --nocapture"]
|
||||
fn blur_timings() {
|
||||
let one = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap();
|
||||
let best = |src: &Pixmap, sigma: f64, runs: u32, on_one: bool| {
|
||||
(0..runs)
|
||||
.map(|_| {
|
||||
let mut p = src.clone();
|
||||
let t = std::time::Instant::now();
|
||||
if on_one {
|
||||
one.install(|| blur(&mut p, sigma));
|
||||
} else {
|
||||
blur(&mut p, sigma);
|
||||
}
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
})
|
||||
.fold(f64::MAX, f64::min)
|
||||
};
|
||||
println!("| pixmap | sigma | parallel ms | one thread ms |\n|---|---:|---:|---:|");
|
||||
for (w, h, sigma) in [(1700u32, 1200u32, 48.0), (1700, 1200, 12.0), (600, 400, 6.0)] {
|
||||
let src = noise(w, h, 5);
|
||||
println!("| {w} × {h} | {sigma} | {:.2} | {:.2} |", best(&src, sigma, 15, false), best(&src, sigma, 5, true));
|
||||
}
|
||||
}
|
||||
|
||||
/// The multiply and shift give every quotient a box's sums can have, for every box width up
|
||||
/// to 4,001 pixels (radius 2,000) and for the widest ones.
|
||||
#[test]
|
||||
fn division_by_a_box_width_is_exact() {
|
||||
let widths = (1..=4001u32).step_by(2).chain([65_535, 1_000_001, 2_000_001, (1 << 23) - 1, 1 << 23]);
|
||||
for d in widths {
|
||||
let by = ByWidth::new(d).unwrap();
|
||||
let sums: Box<dyn Iterator<Item = u32>> = if d <= 4001 {
|
||||
Box::new(0..=255 * d)
|
||||
} else {
|
||||
Box::new((0..=255u32).flat_map(move |q| [q * d, (q * d).saturating_sub(1), q * d + d - 1]).filter(move |s| *s <= 255 * d))
|
||||
};
|
||||
for s in sums {
|
||||
assert_eq!(u32::from(by.of(s)), s / d, "{s} / {d}");
|
||||
}
|
||||
}
|
||||
assert!(ByWidth::new((1 << 23) + 1).is_none());
|
||||
assert!(ByWidth::new(0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blur_spreads_and_conserves() {
|
||||
let mut p = Pixmap::new(64, 64).unwrap();
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
//! Navigation timings in a large file: five pages of 20,000 layers each (100,000 in the file), seen
|
||||
//! through a 1600 × 1100 device-pixel view. Run in release:
|
||||
//! `cargo test --release -p figcraft-render --lib large_doc_timings -- --ignored --nocapture`.
|
||||
//!
|
||||
//! Columns, by what the pages hold:
|
||||
//! - "cards": 400 cards a page (frames with a drop shadow), each holding 49 rectangles;
|
||||
//! - "blur here": the cards, and a background blur and a glass pane on the page shown;
|
||||
//! - "blur elsewhere": the cards, and a background blur and a glass pane on another page;
|
||||
//! - "flat": 20,000 rectangles straight on each page.
|
||||
//!
|
||||
//! Rows go through `Retained` as the canvas does: "scan" is what the retained renderer works out
|
||||
//! about a page after an edit (the layers to redraw whole, the largest backdrop blur); "edit"
|
||||
//! moves one rectangle each frame; "zoom" renders a new scale each frame; "pan" moves the view by
|
||||
//! 60 device pixels each frame.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{Blur, Document, Effect, EffectKind, Glass, NodeId, NodeKind, Shadow};
|
||||
use figcraft_geom::Affine;
|
||||
|
||||
use crate::{Options, Retained, View, Work};
|
||||
|
||||
const PAGES: u32 = 5;
|
||||
const RUNS: u32 = 12;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Scene {
|
||||
Cards,
|
||||
BlurHere,
|
||||
BlurElsewhere,
|
||||
Flat,
|
||||
}
|
||||
|
||||
/// The file, the page shown and a rectangle on it.
|
||||
struct File {
|
||||
doc: Document,
|
||||
page: NodeId,
|
||||
target: NodeId,
|
||||
}
|
||||
|
||||
/// A background blur and a glass pane on `page`.
|
||||
fn backdrops(d: &mut Document, page: NodeId) {
|
||||
let pane = d.create(page, NodeKind::Rectangle, "Frosted", 1100.0, 1100.0, 500.0, 300.0).unwrap();
|
||||
let n = d.get_mut(pane).unwrap();
|
||||
n.fills = vec![Paint::solid(Color { a: 0.2, ..Color::WHITE })];
|
||||
n.effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur { radius: 24.0, ..Blur::default() }), visible: true }];
|
||||
let glass = d.create(page, NodeKind::Rectangle, "Glass", 1700.0, 1300.0, 400.0, 260.0).unwrap();
|
||||
let n = d.get_mut(glass).unwrap();
|
||||
n.corners.radii = [32.0; 4];
|
||||
n.fills = vec![Paint::solid(Color { a: 0.1, ..Color::WHITE })];
|
||||
n.effects = vec![Effect { kind: EffectKind::Glass(Glass::default()), visible: true }];
|
||||
}
|
||||
|
||||
fn file(scene: Scene) -> File {
|
||||
let mut d = Document::new("large file");
|
||||
let first = d.first_page().unwrap();
|
||||
let pages: Vec<NodeId> = std::iter::once(first).chain((1..PAGES).map(|i| d.add_page(&format!("Page {}", i + 1)))).collect();
|
||||
let mut target = None;
|
||||
let colour = |x: u32, y: u32, n: u32| Paint::solid(Color::new(x as f32 / n as f32, y as f32 / n as f32, 0.6, 1.0));
|
||||
for &p in &pages {
|
||||
if scene == Scene::Flat {
|
||||
for y in 0..100u32 {
|
||||
for x in 0..200u32 {
|
||||
let r = d.create(p, NodeKind::Rectangle, "Cell", f64::from(x) * 30.0, f64::from(y) * 30.0, 26.0, 26.0).unwrap();
|
||||
d.get_mut(r).unwrap().fills = vec![colour(x, y, 200)];
|
||||
if p == first && x == 50 && y == 50 {
|
||||
target = Some(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for cy in 0..20u32 {
|
||||
for cx in 0..20u32 {
|
||||
let card = d.create(p, NodeKind::Frame, "Card", f64::from(cx) * 400.0, f64::from(cy) * 400.0, 360.0, 360.0).unwrap();
|
||||
let n = d.get_mut(card).unwrap();
|
||||
n.fills = vec![Paint::solid(Color::WHITE)];
|
||||
n.effects =
|
||||
vec![Effect { kind: EffectKind::DropShadow(Shadow { radius: 12.0, offset: (0.0, 4.0), ..Shadow::default() }), visible: true }];
|
||||
for y in 0..7u32 {
|
||||
for x in 0..7u32 {
|
||||
let r =
|
||||
d.create(card, NodeKind::Rectangle, "Cell", 8.0 + f64::from(x) * 50.0, 8.0 + f64::from(y) * 50.0, 44.0, 44.0).unwrap();
|
||||
d.get_mut(r).unwrap().fills = vec![colour(x, y, 7)];
|
||||
if p == first && cx == 3 && cy == 3 && x == 3 && y == 3 {
|
||||
target = Some(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match scene {
|
||||
Scene::BlurHere => backdrops(&mut d, first),
|
||||
Scene::BlurElsewhere => backdrops(&mut d, pages[2]),
|
||||
Scene::Cards | Scene::Flat => {}
|
||||
}
|
||||
File { doc: d, page: first, target: target.unwrap() }
|
||||
}
|
||||
|
||||
fn view(origin: (f64, f64), scale: f64) -> View {
|
||||
View { origin, scale, width: 1600, height: 1100 }
|
||||
}
|
||||
|
||||
fn opts() -> Options {
|
||||
Options { lod: true, ..Options::default() }
|
||||
}
|
||||
|
||||
fn mean_ms(t: Instant, runs: u32) -> f64 {
|
||||
t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs)
|
||||
}
|
||||
|
||||
/// Move the target a unit right.
|
||||
fn nudge(d: &mut Document, target: NodeId) {
|
||||
let n = d.get_mut(target).unwrap();
|
||||
let c = n.transform.as_coeffs();
|
||||
n.transform = Affine::translate((c[4] + 1.0, c[5]));
|
||||
}
|
||||
|
||||
/// Mean milliseconds of the retained renderer's look at the page after an edit.
|
||||
fn scan(f: &File) -> f64 {
|
||||
let mut doc = f.doc.clone();
|
||||
let t = Instant::now();
|
||||
for _ in 0..RUNS {
|
||||
nudge(&mut doc, f.target);
|
||||
std::hint::black_box(crate::retained::bench_scan(&doc, f.page));
|
||||
}
|
||||
mean_ms(t, RUNS)
|
||||
}
|
||||
|
||||
/// Mean milliseconds of a canvas frame after moving the target a unit.
|
||||
fn edits(f: &File) -> f64 {
|
||||
let v = view((1000.0, 1000.0), 1.0);
|
||||
let mut r = Retained::default();
|
||||
let mut doc = Arc::new(f.doc.clone());
|
||||
r.render(&doc, f.page, &v, &opts()).unwrap();
|
||||
let t = Instant::now();
|
||||
for _ in 0..RUNS {
|
||||
let mut next = (*doc).clone();
|
||||
nudge(&mut next, f.target);
|
||||
doc = Arc::new(next);
|
||||
let (_, _, work) = r.render(&doc, f.page, &v, &opts()).unwrap();
|
||||
assert!(matches!(work, Work::Partial { .. }), "{work:?}");
|
||||
}
|
||||
mean_ms(t, RUNS)
|
||||
}
|
||||
|
||||
/// Mean milliseconds of a canvas frame at a new zoom around `scale`.
|
||||
fn zooms(f: &File, scale: f64) -> f64 {
|
||||
let doc = Arc::new(f.doc.clone());
|
||||
let mut r = Retained::default();
|
||||
r.render(&doc, f.page, &view((1000.0, 1000.0), scale), &opts()).unwrap();
|
||||
let t = Instant::now();
|
||||
for i in 1..=RUNS {
|
||||
let (_, _, work) = r.render(&doc, f.page, &view((1000.0, 1000.0), scale * (1.0 + 0.02 * f64::from(i))), &opts()).unwrap();
|
||||
assert_eq!(work, Work::Full);
|
||||
}
|
||||
mean_ms(t, RUNS)
|
||||
}
|
||||
|
||||
/// Mean milliseconds of a canvas frame after a pan of 60 device pixels.
|
||||
fn pans(f: &File) -> f64 {
|
||||
let doc = Arc::new(f.doc.clone());
|
||||
let mut r = Retained::default();
|
||||
let mut at = (1000.0, 1000.0);
|
||||
r.render(&doc, f.page, &view(at, 1.0), &opts()).unwrap();
|
||||
let t = Instant::now();
|
||||
for _ in 0..RUNS {
|
||||
at.0 += 60.0;
|
||||
let (_, _, work) = r.render(&doc, f.page, &view(at, 1.0), &opts()).unwrap();
|
||||
assert!(matches!(work, Work::Partial { .. }), "{work:?}");
|
||||
}
|
||||
mean_ms(t, RUNS)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "timing: run in release with --ignored --nocapture"]
|
||||
fn large_doc_timings() {
|
||||
let scenes = [Scene::Cards, Scene::BlurHere, Scene::BlurElsewhere, Scene::Flat].map(file);
|
||||
println!(
|
||||
"large file timings ({} build, {} layers, 1600 × 1100 px, mean of {RUNS}, ms)",
|
||||
if cfg!(debug_assertions) { "debug" } else { "release" },
|
||||
scenes[0].doc.node_count()
|
||||
);
|
||||
println!("| frame | cards | blur here | blur elsewhere | flat |\n|---|---:|---:|---:|---:|");
|
||||
let row = |name: &str, f: &dyn Fn(&File) -> f64| {
|
||||
let cells: Vec<String> = scenes.iter().map(|s| format!("{:.2}", f(s))).collect();
|
||||
println!("| {name} | {} |", cells.join(" | "));
|
||||
};
|
||||
row("scan after an edit", &scan);
|
||||
row("edit one layer", &edits);
|
||||
row("zoom (100%)", &|f| zooms(f, 1.0));
|
||||
row("zoom (400%)", &|f| zooms(f, 4.0));
|
||||
row("pan 60 px", &pans);
|
||||
}
|
||||
|
||||
/// The cards with, on the page shown, a grainy card, a layer filled with a pattern whose source
|
||||
/// lies on another page, a background blur and a glass pane.
|
||||
fn mixed() -> File {
|
||||
let mut f = file(Scene::BlurHere);
|
||||
let d = &mut f.doc;
|
||||
let other = d.pages[3];
|
||||
let source = d.create(other, NodeKind::Frame, "Source", 0.0, 0.0, 30.0, 30.0).unwrap();
|
||||
d.get_mut(source).unwrap().fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())];
|
||||
let dot = d.create(source, NodeKind::Rectangle, "Dot", 8.0, 8.0, 12.0, 12.0).unwrap();
|
||||
d.get_mut(dot).unwrap().fills = vec![Paint::solid(Color::from_hex("2040E0").unwrap())];
|
||||
let filled = d.create(f.page, NodeKind::Rectangle, "Filled", 1300.0, 1500.0, 300.0, 200.0).unwrap();
|
||||
let pt = figcraft_color::PatternPaint::new(source.0);
|
||||
d.get_mut(filled).unwrap().fills = vec![Paint { kind: figcraft_color::PaintKind::Pattern(pt), ..Paint::solid(Color::BLACK) }];
|
||||
let grainy = d.create(f.page, NodeKind::Rectangle, "Grain", 1500.0, 1150.0, 200.0, 120.0).unwrap();
|
||||
let n = d.get_mut(grainy).unwrap();
|
||||
n.fills = vec![Paint::solid(Color::from_hex("20C060").unwrap())];
|
||||
n.effects = vec![Effect {
|
||||
kind: EffectKind::Noise(figcraft_doc::Noise { size: 0.5, density: 0.4, color: Color::BLACK, ..Default::default() }),
|
||||
visible: true,
|
||||
}];
|
||||
f
|
||||
}
|
||||
|
||||
/// Prints a digest of every frame of a run of pans, edits and zooms through `Retained`, to tell
|
||||
/// that two builds draw the same pixels: run in release on each and compare.
|
||||
#[test]
|
||||
#[ignore = "digests: run in release with --ignored --nocapture on two builds and compare"]
|
||||
fn large_doc_digests() {
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
let scenes = [
|
||||
("cards", file(Scene::Cards)),
|
||||
("blur here", file(Scene::BlurHere)),
|
||||
("blur elsewhere", file(Scene::BlurElsewhere)),
|
||||
("flat", file(Scene::Flat)),
|
||||
("mixed", mixed()),
|
||||
];
|
||||
let mut all = DefaultHasher::new();
|
||||
for (name, f) in &scenes {
|
||||
let mut r = Retained::default();
|
||||
let mut doc = Arc::new(f.doc.clone());
|
||||
let mut frames = Vec::new();
|
||||
let mut at = (1000.0, 1000.0);
|
||||
let mut scale = 1.0;
|
||||
let steps = ["pan", "pan", "edit", "edit", "zoom 1.37", "pan", "edit", "zoom 4", "pan", "edit", "zoom 0.5", "pan"];
|
||||
let mut draw = |r: &mut Retained, doc: &Arc<Document>, at: (f64, f64), scale: f64, frames: &mut Vec<String>| {
|
||||
let (_, pix, work) = r.render(doc, f.page, &view(at, scale), &opts()).unwrap();
|
||||
let mut h = DefaultHasher::new();
|
||||
pix.data().hash(&mut h);
|
||||
let w = match work {
|
||||
Work::Full => "F",
|
||||
Work::Partial { .. } => "P",
|
||||
Work::Reused => "R",
|
||||
};
|
||||
frames.push(format!("{w}{:04x}", h.finish() & 0xffff));
|
||||
pix.data().hash(&mut all);
|
||||
};
|
||||
draw(&mut r, &doc, at, scale, &mut frames);
|
||||
for s in steps {
|
||||
match s {
|
||||
"pan" => at = (at.0 + 60.0 / scale, at.1 + 24.0 / scale),
|
||||
"edit" => {
|
||||
let mut next = (*doc).clone();
|
||||
nudge(&mut next, f.target);
|
||||
doc = Arc::new(next);
|
||||
}
|
||||
z => scale = z.trim_start_matches("zoom ").parse().unwrap(),
|
||||
}
|
||||
draw(&mut r, &doc, at, scale, &mut frames);
|
||||
}
|
||||
println!("{name}: {}", frames.join(" "));
|
||||
}
|
||||
println!("all: {:016x}", all.finish());
|
||||
}
|
||||
+57
-17
@@ -123,6 +123,13 @@ pub(crate) fn render_number() -> u64 {
|
||||
|
||||
/// Render a page region, splitting it into horizontal bands rendered in parallel (desktop).
|
||||
pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option<Pixmap> {
|
||||
render_view_with(doc, page, view, opts, max_backdrop_blur(doc))
|
||||
}
|
||||
|
||||
/// [`render_view`], where `backdrop` is at least the largest backdrop radius of what it draws (a
|
||||
/// retained render works it out for the page: a blur on another page then widens no band's
|
||||
/// overlap).
|
||||
pub(crate) fn render_view_with(doc: &Document, page: NodeId, view: &View, opts: &Options, backdrop: f64) -> Option<Pixmap> {
|
||||
start_render();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(pool) = band_pool() {
|
||||
@@ -130,43 +137,60 @@ pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) ->
|
||||
let bands = threads.min(view.height / 96).max(1);
|
||||
if bands > 1
|
||||
&& view.width.saturating_mul(view.height) > 300_000
|
||||
&& let Some(p) = pool.install(|| render_bands(doc, page, view, opts, bands))
|
||||
&& let Some(p) = pool.install(|| render_bands_with(doc, page, view, opts, bands, backdrop))
|
||||
{
|
||||
return Some(p);
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = backdrop;
|
||||
render_one(doc, page, view, opts)
|
||||
}
|
||||
|
||||
/// [`render_part_with`] for backdrop radii up to the file's largest.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn render_part(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option<Pixmap> {
|
||||
render_part_with(doc, page, view, opts, max_backdrop_blur(doc))
|
||||
}
|
||||
|
||||
/// [`render_view`] for a part of a view a retained render redraws (the strips a pan uncovers, the
|
||||
/// area of an edit): in parallel bands however few pixels it has, along its longer side (rows of a
|
||||
/// tall strip, columns of a wide one), since what it costs is the layers it crosses (a shadow is
|
||||
/// drawn whole for a sliver of it), not its pixels.
|
||||
pub(crate) fn render_part(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option<Pixmap> {
|
||||
/// drawn whole for a sliver of it), not its pixels. `backdrop` is at least the largest backdrop
|
||||
/// radius of what it draws.
|
||||
pub(crate) fn render_part_with(doc: &Document, page: NodeId, view: &View, opts: &Options, backdrop: f64) -> Option<Pixmap> {
|
||||
start_render();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(pool) = band_pool() {
|
||||
let threads = pool.current_num_threads().clamp(1, 16) as u32;
|
||||
let rendered = if view.height >= view.width {
|
||||
let bands = threads.min(view.height / 96);
|
||||
(bands > 1).then(|| pool.install(|| render_bands(doc, page, view, opts, bands))).flatten()
|
||||
(bands > 1).then(|| pool.install(|| render_bands_with(doc, page, view, opts, bands, backdrop))).flatten()
|
||||
} else {
|
||||
let bands = threads.min(view.width / 96);
|
||||
(bands > 1).then(|| pool.install(|| render_columns(doc, page, view, opts, bands))).flatten()
|
||||
(bands > 1).then(|| pool.install(|| render_columns_with(doc, page, view, opts, bands, backdrop))).flatten()
|
||||
};
|
||||
if rendered.is_some() {
|
||||
return rendered;
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = backdrop;
|
||||
render_one(doc, page, view, opts)
|
||||
}
|
||||
|
||||
/// [`render_bands`] across: `bands` columns, overlapping by what background blurs read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// [`render_columns_with`] for backdrop radii up to the file's largest.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
fn render_columns(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option<Pixmap> {
|
||||
render_columns_with(doc, page, view, opts, bands, max_backdrop_blur(doc))
|
||||
}
|
||||
|
||||
/// [`render_bands_with`] across: `bands` columns, overlapping by what background blurs read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn render_columns_with(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32, backdrop: f64) -> Option<Pixmap> {
|
||||
use rayon::prelude::*;
|
||||
let band_w = view.width.div_ceil(bands.max(1));
|
||||
let overlap = band_overlap(doc, view, band_w)?;
|
||||
let overlap = overlap_for(backdrop, view, band_w)?;
|
||||
let s = view.scale.max(1e-9);
|
||||
let parts: Vec<(u32, Option<Pixmap>)> = (0..bands)
|
||||
.into_par_iter()
|
||||
@@ -205,15 +229,21 @@ fn band_pool() -> Option<&'static rayon::ThreadPool> {
|
||||
POOL.get_or_init(|| rayon::ThreadPoolBuilder::new().thread_name(|i| format!("figcraft-band-{i}")).stack_size(RENDER_STACK).build().ok()).as_ref()
|
||||
}
|
||||
|
||||
/// Render `view` as `bands` horizontal bands in parallel. Bands overlap by what background blurs
|
||||
/// read and each keeps only its own rows, so a backdrop never ends at a band's edge. `None` when a
|
||||
/// blur reaches past a whole band (every band would render most of the view: render it in one
|
||||
/// piece instead).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// [`render_bands_with`] for backdrop radii up to the file's largest.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
fn render_bands(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option<Pixmap> {
|
||||
render_bands_with(doc, page, view, opts, bands, max_backdrop_blur(doc))
|
||||
}
|
||||
|
||||
/// Render `view` as `bands` horizontal bands in parallel. Bands overlap by what background blurs
|
||||
/// read (`backdrop` is at least the largest backdrop radius of what they draw) and each keeps only
|
||||
/// its own rows, so a backdrop never ends at a band's edge. `None` when a blur reaches past a whole
|
||||
/// band (every band would render most of the view: render it in one piece instead).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn render_bands_with(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32, backdrop: f64) -> Option<Pixmap> {
|
||||
use rayon::prelude::*;
|
||||
let band_h = view.height.div_ceil(bands.max(1));
|
||||
let overlap = band_overlap(doc, view, band_h)?;
|
||||
let overlap = overlap_for(backdrop, view, band_h)?;
|
||||
let parts: Vec<(u32, Option<Pixmap>)> = (0..bands)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
@@ -230,10 +260,16 @@ fn render_bands(doc: &Document, page: NodeId, view: &View, opts: &Options, bands
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// How many rows bands of `band_h` rows of `view` overlap (what background blurs read); `None`
|
||||
/// when that is more than a band.
|
||||
/// [`overlap_for`] for backdrop radii up to the file's largest.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn band_overlap(doc: &Document, view: &View, band_h: u32) -> Option<u32> {
|
||||
let overlap = backdrop_reach(max_backdrop_blur(doc), view.scale).ceil();
|
||||
overlap_for(max_backdrop_blur(doc), view, band_h)
|
||||
}
|
||||
|
||||
/// How many rows bands of `band_h` rows of `view` overlap (what background blurs of radii up to
|
||||
/// `backdrop` read); `None` when that is more than a band.
|
||||
pub(crate) fn overlap_for(backdrop: f64, view: &View, band_h: u32) -> Option<u32> {
|
||||
let overlap = backdrop_reach(backdrop, view.scale).ceil();
|
||||
(overlap.is_finite() && overlap <= f64::from(band_h)).then_some(overlap as u32)
|
||||
}
|
||||
|
||||
@@ -705,6 +741,8 @@ mod join_tests;
|
||||
#[cfg(test)]
|
||||
mod jpeg_sampling_tests;
|
||||
#[cfg(test)]
|
||||
mod large_doc_bench_tests;
|
||||
#[cfg(test)]
|
||||
mod large_image_tests;
|
||||
#[cfg(test)]
|
||||
mod lod_tests;
|
||||
@@ -725,6 +763,8 @@ mod render_depth_tests;
|
||||
#[cfg(test)]
|
||||
mod retained_edit_tests;
|
||||
#[cfg(test)]
|
||||
mod retained_page_tests;
|
||||
#[cfg(test)]
|
||||
mod retained_tests;
|
||||
#[cfg(test)]
|
||||
mod rtl_list_tests;
|
||||
|
||||
+134
-43
@@ -4,15 +4,15 @@
|
||||
//! Views are snapped to whole device pixels so that, at one zoom, the pixels of every render line
|
||||
//! up and a pan is an integer shift of the previous image. Anything the partial path can't vouch
|
||||
//! for (another zoom, page or set of options, new fonts, a page-level edit, a large change) is a
|
||||
//! full render, the same as [`render_view`].
|
||||
//! full render, the same as [`render_view`](crate::render_view).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_doc::{Document, EffectKind, NodeId, NodeKind};
|
||||
use figcraft_doc::{Document, Effect, EffectKind, Node, NodeId, NodeKind};
|
||||
use figcraft_geom::Rect;
|
||||
use tiny_skia::Pixmap;
|
||||
|
||||
use crate::{Options, View, draw, render_view};
|
||||
use crate::{Options, View, draw};
|
||||
|
||||
/// What a render had to do.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -68,19 +68,111 @@ struct Sensitive {
|
||||
pattern_sources: Vec<NodeId>,
|
||||
}
|
||||
|
||||
/// Grain effects (noise, texture) work on their layer's pixels, which end where a render cuts the
|
||||
/// layer (texture scatters pixels from across the cut): grainy layers are redrawn whole.
|
||||
fn sensitive(doc: &Document) -> Sensitive {
|
||||
let noisy = doc.nodes().filter(|n| n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::Noise(_) | EffectKind::Texture(_))));
|
||||
let pattern_sources = doc
|
||||
.nodes()
|
||||
.flat_map(|n| n.fills.iter().chain(&n.strokes))
|
||||
.filter_map(|p| match &p.kind {
|
||||
figcraft_color::PaintKind::Pattern(pt) => Some(NodeId(pt.source)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Sensitive { areas: noisy.filter_map(|n| draw::paint_bounds(doc, n.id)).collect(), backdrop_blur: crate::max_backdrop_blur(doc), pattern_sources }
|
||||
/// The paints a vector's regions or a text's runs draw with besides the layer's own fills.
|
||||
fn own_paints(n: &Node) -> impl Iterator<Item = &figcraft_color::Paint> {
|
||||
let regions = match &n.kind {
|
||||
NodeKind::Vector { network } => network.regions.as_slice(),
|
||||
_ => &[],
|
||||
};
|
||||
let text = match &n.kind {
|
||||
NodeKind::Text(t) => Some(t),
|
||||
_ => None,
|
||||
};
|
||||
let styles = text.into_iter().flat_map(|t| std::iter::once(&t.style).chain(t.runs.iter().map(|r| &r.style)));
|
||||
regions.iter().filter_map(|r| r.fills.as_deref()).chain(styles.filter_map(|s| s.fills.as_deref())).flatten()
|
||||
}
|
||||
|
||||
/// The pattern source `p` draws, when it is a pattern.
|
||||
fn pattern_source(p: &figcraft_color::Paint) -> Option<NodeId> {
|
||||
match &p.kind {
|
||||
figcraft_color::PaintKind::Pattern(pt) => Some(NodeId(pt.source)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern sources of every paint `n` draws with: its fills and strokes, its vector regions'
|
||||
/// own fills and its text runs' own fills.
|
||||
fn pattern_sources_of(n: &Node) -> impl Iterator<Item = NodeId> + '_ {
|
||||
let more = matches!(n.kind, NodeKind::Vector { .. } | NodeKind::Text(_)).then(|| own_paints(n));
|
||||
n.fills.iter().chain(&n.strokes).filter_map(pattern_source).chain(more.into_iter().flatten().filter_map(pattern_source))
|
||||
}
|
||||
|
||||
/// Whether `n`'s look depends on where a render cuts it: grain effects (noise, texture) work on
|
||||
/// its pixels, which end at the cut (texture scatters pixels from across it).
|
||||
fn grainy(n: &Node) -> bool {
|
||||
n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::Noise(_) | EffectKind::Texture(_)))
|
||||
}
|
||||
|
||||
/// What a render of `page` must know: grainy layers are redrawn whole, an edit inside a pattern
|
||||
/// source shows wherever the pattern does, and backdrop blurs read around them.
|
||||
///
|
||||
/// Only what the page draws counts: its layers, and the pattern sources they fill with wherever
|
||||
/// those are (and the sources those fill with in turn), whose edits show on the page and whose
|
||||
/// backdrop blurs count too. A source's grain is drawn in its cells, not where the source lies, so
|
||||
/// only the page's own grainy layers give areas. One walk down the page rather than passes over
|
||||
/// every page of the file: in a large file those passes took most of an edit's frame, and a blur
|
||||
/// on another page widened every pan's strips and every band's overlap.
|
||||
fn sensitive(doc: &Document, page: NodeId) -> Sensitive {
|
||||
page_walk(doc, page).unwrap_or_else(|| whole_file(doc))
|
||||
}
|
||||
|
||||
/// [`sensitive`] from a walk down `page`; `None` when the walk runs out of its budget.
|
||||
fn page_walk(doc: &Document, page: NodeId) -> Option<Sensitive> {
|
||||
let mut noisy: Vec<(NodeId, Rect)> = Vec::new();
|
||||
let mut backdrop_blur = 0.0f64;
|
||||
let mut pattern_sources = Vec::new();
|
||||
let mut sources = std::collections::BTreeSet::new();
|
||||
// Layers walked as part of a source: sources inside sources are walked once.
|
||||
let mut in_sources = std::collections::BTreeSet::new();
|
||||
// A tree takes at most three visits a layer: on the page, in a source and as a source's root
|
||||
// met again. Child lists that repeat (a hostile file) run out the budget: then what the page
|
||||
// draws can't be told, and [`sensitive`] counts the whole file.
|
||||
let mut left = doc.node_count().saturating_mul(3).saturating_add(8);
|
||||
// Each layer with whether it is drawn where it lies on the page (a source's layers are drawn
|
||||
// in its cells).
|
||||
let mut stack = vec![(page, true)];
|
||||
while let Some((id, on_page)) = stack.pop() {
|
||||
left = left.checked_sub(1)?;
|
||||
if !on_page && !in_sources.insert(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(n) = doc.node(id) else { continue };
|
||||
if on_page
|
||||
&& grainy(n)
|
||||
&& let Some(r) = draw::paint_bounds(doc, id)
|
||||
{
|
||||
noisy.push((id, r));
|
||||
}
|
||||
backdrop_blur = n.effects.iter().map(Effect::backdrop_radius).fold(backdrop_blur, f64::max);
|
||||
for src in pattern_sources_of(n) {
|
||||
if sources.insert(src) {
|
||||
pattern_sources.push(src);
|
||||
// A page as a source draws nothing.
|
||||
if doc.node(src).is_some_and(|s| !s.is_page()) {
|
||||
stack.push((src, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
stack.extend(n.children.iter().map(|c| (*c, on_page)));
|
||||
}
|
||||
// In id order, as a pass over the file finds them.
|
||||
noisy.sort_by_key(|(id, _)| *id);
|
||||
Some(Sensitive { areas: noisy.into_iter().map(|(_, r)| r).collect(), backdrop_blur, pattern_sources })
|
||||
}
|
||||
|
||||
/// [`sensitive`] for every layer of the file, whatever page it is on.
|
||||
fn whole_file(doc: &Document) -> Sensitive {
|
||||
Sensitive {
|
||||
areas: doc.nodes().filter(|n| grainy(n)).filter_map(|n| draw::paint_bounds(doc, n.id)).collect(),
|
||||
backdrop_blur: crate::max_backdrop_blur(doc),
|
||||
pattern_sources: doc.nodes().flat_map(pattern_sources_of).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`sensitive`] for the large-file timings: how many areas it found.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn bench_scan(doc: &Document, page: NodeId) -> usize {
|
||||
sensitive(doc, page).areas.len()
|
||||
}
|
||||
|
||||
/// Whether `id` is a pattern source or inside one in `doc`.
|
||||
@@ -132,8 +224,8 @@ enum Prepared {
|
||||
/// The previous render patched (or reused as is), now kept.
|
||||
Patched(View, Work),
|
||||
/// Only a full render will do: the snapped view, its top-left device pixel, the font
|
||||
/// generation and what [`sensitive`] found when the previous render's document was checked.
|
||||
Full { snapped: View, px: (i64, i64), fonts: u64, sensitive: Option<Arc<Sensitive>> },
|
||||
/// generation and what [`sensitive`] finds on the page.
|
||||
Full { snapped: View, px: (i64, i64), fonts: u64, sensitive: Arc<Sensitive> },
|
||||
}
|
||||
|
||||
/// What [`Retained::begin`] did.
|
||||
@@ -153,7 +245,7 @@ pub struct Steps {
|
||||
px: (i64, i64),
|
||||
fonts: u64,
|
||||
opts: Options,
|
||||
sensitive: Option<Arc<Sensitive>>,
|
||||
sensitive: Arc<Sensitive>,
|
||||
pix: Pixmap,
|
||||
/// The first row not drawn yet.
|
||||
next: u32,
|
||||
@@ -225,9 +317,8 @@ impl Retained {
|
||||
match self.prepare(doc, page, view, opts)? {
|
||||
Prepared::Patched(snapped, work) => Some((snapped, &self.last.as_ref()?.pix, work)),
|
||||
Prepared::Full { snapped, px, fonts, sensitive } => {
|
||||
let pix = render_view(doc, page, &snapped, opts)?;
|
||||
let s = sensitive.unwrap_or_else(|| Arc::new(self::sensitive(doc)));
|
||||
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
|
||||
let pix = crate::render_view_with(doc, page, &snapped, opts, sensitive.backdrop_blur)?;
|
||||
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, sensitive);
|
||||
Some((snapped, &frame.pix, Work::Full))
|
||||
}
|
||||
}
|
||||
@@ -242,13 +333,12 @@ impl Retained {
|
||||
Prepared::Full { snapped, px, fonts, sensitive } => {
|
||||
// Bands at least twice what they overlap (each draws its overlap again both ways),
|
||||
// so a background blur reaching past `band_h` makes the bands taller.
|
||||
let overlap = crate::band_overlap(doc, &snapped, u32::MAX).map(|o| o.min(snapped.height));
|
||||
let overlap = crate::overlap_for(sensitive.backdrop_blur, &snapped, u32::MAX).map(|o| o.min(snapped.height));
|
||||
let band_h = band_h.max(1).max(overlap.unwrap_or(0).saturating_mul(2));
|
||||
// A blur that can't be measured: one piece.
|
||||
let Some(overlap) = overlap else {
|
||||
let pix = render_view(doc, page, &snapped, opts)?;
|
||||
let s = sensitive.unwrap_or_else(|| Arc::new(self::sensitive(doc)));
|
||||
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
|
||||
let pix = crate::render_view_with(doc, page, &snapped, opts, sensitive.backdrop_blur)?;
|
||||
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, sensitive);
|
||||
return Some(Begun::Done(snapped, &frame.pix, Work::Full));
|
||||
};
|
||||
let pix = crate::new_pixmap(snapped.width, snapped.height)?;
|
||||
@@ -275,8 +365,7 @@ impl Retained {
|
||||
/// Keep the image `steps` drew (all its bands: see [`Steps::step`]) as a full render.
|
||||
pub fn finish(&mut self, steps: Steps) -> (View, &Pixmap) {
|
||||
let Steps { doc, page, view, px, fonts, opts, sensitive, pix, .. } = steps;
|
||||
let s = sensitive.unwrap_or_else(|| Arc::new(self::sensitive(&doc)));
|
||||
let frame = self.keep(&doc, page, (&view, px, fonts), &opts, pix, s);
|
||||
let frame = self.keep(&doc, page, (&view, px, fonts), &opts, pix, sensitive);
|
||||
(view, &frame.pix)
|
||||
}
|
||||
|
||||
@@ -290,8 +379,12 @@ impl Retained {
|
||||
return None;
|
||||
};
|
||||
let fonts = figcraft_text::layout_generation();
|
||||
let mut sens = None;
|
||||
if let Some(last) = self.last.take()
|
||||
let last = self.last.take();
|
||||
// What the previous render found on the page holds while the document, the page and the
|
||||
// fonts (text's ink bounds) stay the same: a zoom works none of it out again.
|
||||
let kept = last.as_ref().filter(|l| Arc::ptr_eq(&l.doc, doc) && l.page == page && l.fonts == fonts).map(|l| l.sensitive.clone());
|
||||
let s = kept.unwrap_or_else(|| Arc::new(sensitive(doc, page)));
|
||||
if let Some(last) = last
|
||||
&& last.page == page
|
||||
&& last.outline == opts.outline_mode
|
||||
&& last.outline_extras == opts.outline
|
||||
@@ -310,18 +403,14 @@ impl Retained {
|
||||
&& last.fonts == fonts
|
||||
// Images are decoded into the file's colour space: a new profile redraws everything.
|
||||
&& last.doc.color_profile == doc.color_profile
|
||||
&& let Some((pix, pixels, areas)) = patch(last, doc, page, &snapped, px, opts, &s)
|
||||
{
|
||||
let same_doc = Arc::ptr_eq(&last.doc, doc);
|
||||
let s = if same_doc { last.sensitive.clone() } else { Arc::new(sensitive(doc)) };
|
||||
if let Some((pix, pixels, areas)) = patch(last, doc, page, &snapped, px, opts, &s) {
|
||||
let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } };
|
||||
self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
|
||||
self.patched = areas;
|
||||
return Some(Prepared::Patched(snapped, work));
|
||||
}
|
||||
sens = Some(s);
|
||||
let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } };
|
||||
self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
|
||||
self.patched = areas;
|
||||
return Some(Prepared::Patched(snapped, work));
|
||||
}
|
||||
Some(Prepared::Full { snapped, px, fonts, sensitive: sens })
|
||||
Some(Prepared::Full { snapped, px, fonts, sensitive: s })
|
||||
}
|
||||
|
||||
/// Keep `pix`, the render of `at`: the snapped view, its top-left device pixel and the font
|
||||
@@ -642,7 +731,7 @@ fn patch(
|
||||
let mut pix = last.pix;
|
||||
shift(&mut pix, dx, dy)?;
|
||||
for d in &damage {
|
||||
render_into(FrameRender { doc, page, view, px, opts }, d, margin, &mut pix)?;
|
||||
render_into(FrameRender { doc, page, view, px, opts, backdrop: s.backdrop_blur }, d, margin, &mut pix)?;
|
||||
}
|
||||
let area =
|
||||
|d: &Px| Some([u32::try_from(d.x0).ok()?, u32::try_from(d.y0).ok()?, u32::try_from(d.x1 - d.x0).ok()?, u32::try_from(d.y1 - d.y0).ok()?]);
|
||||
@@ -706,13 +795,15 @@ struct FrameRender<'a> {
|
||||
view: &'a View,
|
||||
px: (i64, i64),
|
||||
opts: &'a Options,
|
||||
/// The largest backdrop radius on the page.
|
||||
backdrop: f64,
|
||||
}
|
||||
|
||||
/// Render the frame pixels `d` (with `margin` more around, discarded) into `pix`. The margin stops
|
||||
/// at the frame's edge: background blurs and glass read what is drawn under them, and a full
|
||||
/// render's backdrops end where the frame does.
|
||||
fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) -> Option<()> {
|
||||
let FrameRender { doc, page, view, px, opts } = frame;
|
||||
let FrameRender { doc, page, view, px, opts, backdrop } = frame;
|
||||
let s = view.scale;
|
||||
let (w, h) = (i64::from(pix.width()), i64::from(pix.height()));
|
||||
let (ox, oy) = ((d.x0 - margin).max(0), (d.y0 - margin).max(0));
|
||||
@@ -720,7 +811,7 @@ fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) ->
|
||||
let (rw, rh) = (u32::try_from(ex - ox).ok()?, u32::try_from(ey - oy).ok()?);
|
||||
// The same pixel grid as the frame: origin (px + offset) / scale.
|
||||
let sub = View { origin: ((px.0 + ox) as f64 / s, (px.1 + oy) as f64 / s), scale: s, width: rw, height: rh };
|
||||
let part = crate::render_part(doc, page, &sub, opts)?;
|
||||
let part = crate::render_part_with(doc, page, &sub, opts, backdrop)?;
|
||||
// The rows of `d` in `part`, straight into their place (a copy of the part and a draw of the
|
||||
// copy took longer than rendering a simple part).
|
||||
let (skip_x, skip_y) = (usize::try_from(d.x0 - ox).ok()?, usize::try_from(d.y0 - oy).ok()?);
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
//! What the retained renderer works out about a page (grainy layers, pattern sources, the largest
|
||||
//! backdrop blur) comes from that page and the pattern sources it draws, not from the whole file.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_color::{Color, Paint, PaintKind, PatternPaint};
|
||||
use figcraft_doc::{Blur, Document, Effect, EffectKind, NodeId, NodeKind};
|
||||
use figcraft_geom::Affine;
|
||||
|
||||
use crate::retained_tests::assert_same;
|
||||
use crate::{Begun, Options, Pixmap, Retained, View, Work, render_view};
|
||||
|
||||
fn solid(d: &mut Document, id: NodeId, hex: &str) {
|
||||
d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex(hex).unwrap())];
|
||||
}
|
||||
|
||||
fn pattern(d: &mut Document, id: NodeId, source: NodeId) {
|
||||
let pt = PatternPaint::new(source.0);
|
||||
d.get_mut(id).unwrap().fills = vec![Paint { kind: PaintKind::Pattern(pt), ..Paint::solid(Color::BLACK) }];
|
||||
}
|
||||
|
||||
fn edit(doc: &Arc<Document>, f: impl FnOnce(&mut Document)) -> Arc<Document> {
|
||||
let mut d = (**doc).clone();
|
||||
f(&mut d);
|
||||
Arc::new(d)
|
||||
}
|
||||
|
||||
/// Render through `r`; the image, the view drawn and what it took.
|
||||
fn render(r: &mut Retained, doc: &Arc<Document>, page: NodeId, v: &View) -> (Pixmap, View, Work) {
|
||||
let (shown, pix, work) = r.render(doc, page, v, &Options::default()).unwrap();
|
||||
(pix.clone(), shown, work)
|
||||
}
|
||||
|
||||
/// Render through `r` and check the image against a full render of the same view: the same
|
||||
/// pixels for a full render, the same up to anti-aliasing for a patched one.
|
||||
fn check(r: &mut Retained, doc: &Arc<Document>, page: NodeId, v: &View) -> Work {
|
||||
let (pix, shown, work) = render(r, doc, page, v);
|
||||
let full = render_view(doc, page, &shown, &Options::default()).unwrap();
|
||||
if work == Work::Full {
|
||||
assert!(pix.data() == full.data(), "a full retained render differs from render_view");
|
||||
} else {
|
||||
assert_same(&pix, &full, &format!("{work:?}"));
|
||||
}
|
||||
work
|
||||
}
|
||||
|
||||
/// Shapes on the first page, and a background blur reaching far past any patch's margin on the
|
||||
/// second: (document, first page, a shape on it).
|
||||
fn blur_elsewhere() -> (Arc<Document>, NodeId, NodeId) {
|
||||
let mut d = Document::new("blur elsewhere");
|
||||
let p = d.first_page().unwrap();
|
||||
let mut shape = None;
|
||||
for i in 0..12u32 {
|
||||
let r = d.create(p, NodeKind::Rectangle, "R", f64::from(i % 4) * 160.0 + 20.0, f64::from(i / 4) * 150.0 + 20.0, 120.0, 100.0).unwrap();
|
||||
solid(&mut d, r, ["E03030", "2040E0", "20C060", "F0C830"][i as usize % 4]);
|
||||
shape.get_or_insert(r);
|
||||
}
|
||||
let other = d.add_page("Other");
|
||||
let frosted = d.create(other, NodeKind::Rectangle, "Frosted", 0.0, 0.0, 400.0, 300.0).unwrap();
|
||||
d.get_mut(frosted).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(1000.0)), visible: true }];
|
||||
(Arc::new(d), p, shape.unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blur_on_another_page_leaves_pans_and_edits_partial() {
|
||||
let (doc, p, shape) = blur_elsewhere();
|
||||
let v = |x: f64| View { origin: (x, 0.0), scale: 1.0, width: 700, height: 500 };
|
||||
let mut r = Retained::default();
|
||||
assert_eq!(check(&mut r, &doc, p, &v(0.0)), Work::Full);
|
||||
assert!(matches!(check(&mut r, &doc, p, &v(30.0)), Work::Partial { .. }), "a pan");
|
||||
let moved = edit(&doc, |d| d.get_mut(shape).unwrap().transform = Affine::translate((60.0, 40.0)));
|
||||
assert!(matches!(check(&mut r, &moved, p, &v(30.0)), Work::Partial { .. }), "an edit");
|
||||
// A new zoom renders in bands as wide apart as the page's own blurs need (none here).
|
||||
assert_eq!(check(&mut r, &moved, p, &View { scale: 1.5, ..v(30.0) }), Work::Full);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blur_on_the_page_still_renders_full_when_it_reaches_past_a_patch() {
|
||||
let (doc, p, shape) = blur_elsewhere();
|
||||
// The same blur on the page shown.
|
||||
let doc = edit(&doc, |d| {
|
||||
let frosted = d.create(p, NodeKind::Rectangle, "Frosted", 300.0, 200.0, 200.0, 150.0).unwrap();
|
||||
d.get_mut(frosted).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(1000.0)), visible: true }];
|
||||
});
|
||||
let v = View { origin: (0.0, 0.0), scale: 1.0, width: 700, height: 500 };
|
||||
let mut r = Retained::default();
|
||||
check(&mut r, &doc, p, &v);
|
||||
let moved = edit(&doc, |d| d.get_mut(shape).unwrap().transform = Affine::translate((60.0, 40.0)));
|
||||
assert_eq!(check(&mut r, &moved, p, &v), Work::Full);
|
||||
}
|
||||
|
||||
/// A rectangle on the first page filled with a pattern whose source is a frame on the second
|
||||
/// page; inside the source, a child and a layer filled with a second pattern, whose source is on
|
||||
/// a third page. (document, first page, filled rectangle, source, child, nested source)
|
||||
fn patterns() -> (Arc<Document>, NodeId, [NodeId; 4]) {
|
||||
let mut d = Document::new("patterns");
|
||||
let p = d.first_page().unwrap();
|
||||
let filled = d.create(p, NodeKind::Rectangle, "Filled", 20.0, 20.0, 260.0, 200.0).unwrap();
|
||||
let plain = d.create(p, NodeKind::Rectangle, "Plain", 300.0, 40.0, 60.0, 60.0).unwrap();
|
||||
solid(&mut d, plain, "202020");
|
||||
let second = d.add_page("Sources");
|
||||
let source = d.create(second, NodeKind::Frame, "Source", 0.0, 0.0, 40.0, 40.0).unwrap();
|
||||
solid(&mut d, source, "E03030");
|
||||
let child = d.create(source, NodeKind::Rectangle, "Child", 4.0, 4.0, 14.0, 14.0).unwrap();
|
||||
solid(&mut d, child, "2040E0");
|
||||
let inner = d.create(source, NodeKind::Rectangle, "Inner", 20.0, 20.0, 18.0, 18.0).unwrap();
|
||||
let third = d.add_page("More sources");
|
||||
let nested = d.create(third, NodeKind::Rectangle, "Nested", 0.0, 0.0, 6.0, 6.0).unwrap();
|
||||
solid(&mut d, nested, "20C060");
|
||||
pattern(&mut d, inner, nested);
|
||||
pattern(&mut d, filled, source);
|
||||
(Arc::new(d), p, [filled, source, child, nested])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_to_pattern_sources_on_other_pages_show_on_the_page() {
|
||||
let (doc, p, [_, source, child, nested]) = patterns();
|
||||
let v = View { origin: (0.0, 0.0), scale: 1.0, width: 400, height: 260 };
|
||||
let mut r = Retained::default();
|
||||
check(&mut r, &doc, p, &v);
|
||||
let mut doc = doc;
|
||||
for (what, id, hex) in
|
||||
[("the source", source, "F0C830"), ("a layer in the source", child, "FFFFFF"), ("a source the source fills with", nested, "000000")]
|
||||
{
|
||||
doc = edit(&doc, |d| solid(d, id, hex));
|
||||
assert_ne!(check(&mut r, &doc, p, &v), Work::Reused, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grainy_layer_patches_as_it_renders_after_a_zoom() {
|
||||
let mut d = Document::new("grain");
|
||||
let p = d.first_page().unwrap();
|
||||
let grainy = d.create(p, NodeKind::Rectangle, "Grain", 60.0, 50.0, 120.0, 90.0).unwrap();
|
||||
solid(&mut d, grainy, "E03030");
|
||||
let noise = figcraft_doc::Noise { size: 0.5, density: 0.4, color: Color::BLACK, ..Default::default() };
|
||||
d.get_mut(grainy).unwrap().effects = vec![Effect { kind: EffectKind::Noise(noise), visible: true }];
|
||||
let other = d.add_page("Other");
|
||||
let far = d.create(other, NodeKind::Rectangle, "Far", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
solid(&mut d, far, "2040E0");
|
||||
let doc = Arc::new(d);
|
||||
let v = |x: f64, scale: f64| View { origin: (x, 0.0), scale, width: 400, height: 300 };
|
||||
let mut r = Retained::default();
|
||||
check(&mut r, &doc, p, &v(0.0, 1.0));
|
||||
assert_eq!(check(&mut r, &doc, p, &v(0.0, 1.7)), Work::Full);
|
||||
// Pans across the grainy layer at the new zoom: it is redrawn whole each time.
|
||||
for i in 1..=4 {
|
||||
let (pix, shown, work) = render(&mut r, &doc, p, &v(f64::from(i) * 13.0, 1.7));
|
||||
let full = render_view(&doc, p, &shown, &Options::default()).unwrap();
|
||||
let worst = pix.data().iter().zip(full.data()).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
|
||||
assert!(matches!(work, Work::Partial { .. }), "{work:?}");
|
||||
assert!(worst <= 2, "pan {i}: {worst} levels off a full render");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_shown_again_after_another_matches() {
|
||||
let (doc, p, [filled, ..]) = patterns();
|
||||
let other = doc.pages[1];
|
||||
let v = |x: f64| View { origin: (x, 0.0), scale: 1.0, width: 400, height: 260 };
|
||||
let mut r = Retained::default();
|
||||
check(&mut r, &doc, p, &v(0.0));
|
||||
assert_eq!(check(&mut r, &doc, other, &v(0.0)), Work::Full);
|
||||
assert_eq!(check(&mut r, &doc, p, &v(0.0)), Work::Full);
|
||||
assert!(matches!(check(&mut r, &doc, p, &v(24.0)), Work::Partial { .. }));
|
||||
let moved = edit(&doc, |d| d.get_mut(filled).unwrap().transform = Affine::translate((40.0, 30.0)));
|
||||
assert!(matches!(check(&mut r, &moved, p, &v(24.0)), Work::Partial { .. }));
|
||||
}
|
||||
|
||||
/// A render drawn band by band through [`Retained::begin`], kept with [`Retained::finish`].
|
||||
fn stepped(r: &mut Retained, doc: &Arc<Document>, page: NodeId, v: &View, band_h: u32) -> (Pixmap, View) {
|
||||
match r.begin(doc, page, v, &Options::default(), band_h).unwrap() {
|
||||
Begun::Done(shown, pix, _) => (pix.clone(), shown),
|
||||
Begun::Steps(mut steps) => {
|
||||
while !steps.step() {}
|
||||
let (shown, pix) = r.finish(*steps);
|
||||
(pix.clone(), shown)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stripes under a glass pane and a background blur on the first page, a much wider blur on the
|
||||
/// second: (document, first page, a stripe beside the pane).
|
||||
fn backdrops_here_and_wider_elsewhere() -> (Arc<Document>, NodeId, NodeId) {
|
||||
let mut d = Document::new("backdrops");
|
||||
let p = d.first_page().unwrap();
|
||||
let mut stripes = Vec::new();
|
||||
for i in 0..16u32 {
|
||||
let s = d.create(p, NodeKind::Rectangle, "Stripe", f64::from(i) * 40.0, 0.0, 40.0, 500.0).unwrap();
|
||||
solid(&mut d, s, ["E03030", "2040E0", "20C060", "F0C830"][i as usize % 4]);
|
||||
stripes.push(s);
|
||||
}
|
||||
let pane = d.create(p, NodeKind::Rectangle, "Glass", 120.0, 100.0, 240.0, 160.0).unwrap();
|
||||
let n = d.get_mut(pane).unwrap();
|
||||
n.corners.radii = [24.0; 4];
|
||||
n.fills = vec![Paint::solid(Color { a: 0.1, ..Color::WHITE })];
|
||||
n.effects = vec![Effect { kind: EffectKind::Glass(figcraft_doc::Glass::default()), visible: true }];
|
||||
let frosted = d.create(p, NodeKind::Rectangle, "Frosted", 420.0, 260.0, 160.0, 120.0).unwrap();
|
||||
d.get_mut(frosted).unwrap().fills = vec![Paint::solid(Color { a: 0.2, ..Color::WHITE })];
|
||||
d.get_mut(frosted).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(6.0)), visible: true }];
|
||||
let other = d.add_page("Other");
|
||||
let wide = d.create(other, NodeKind::Rectangle, "Wide", 0.0, 0.0, 300.0, 200.0).unwrap();
|
||||
d.get_mut(wide).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(400.0)), visible: true }];
|
||||
(Arc::new(d), p, stripes[9])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backdrops_on_the_page_draw_as_render_view_does_with_a_wider_blur_elsewhere() {
|
||||
let (doc, p, beside) = backdrops_here_and_wider_elsewhere();
|
||||
let v = |x: f64, scale: f64| View { origin: (x, 0.0), scale, width: 640, height: 480 };
|
||||
let mut r = Retained::default();
|
||||
assert_eq!(check(&mut r, &doc, p, &v(0.0, 1.0)), Work::Full);
|
||||
// A new zoom: bands overlapping by the page's own blurs, the same pixels as render_view's
|
||||
// (whose bands overlap by the other page's blur).
|
||||
assert_eq!(check(&mut r, &doc, p, &v(0.0, 1.5)), Work::Full);
|
||||
assert!(matches!(check(&mut r, &doc, p, &v(30.0, 1.5)), Work::Partial { .. }), "a pan");
|
||||
let moved = edit(&doc, |d| d.get_mut(beside).unwrap().transform = Affine::translate((372.0, 12.0)));
|
||||
assert!(matches!(check(&mut r, &moved, p, &v(30.0, 1.5)), Work::Partial { .. }), "an edit beside the glass");
|
||||
// The browser's render, a band at a time.
|
||||
for band_h in [24, 64, 200] {
|
||||
let mut r = Retained::default();
|
||||
let (pix, shown) = stepped(&mut r, &moved, p, &v(10.0, 1.37), band_h);
|
||||
let full = render_view(&moved, p, &shown, &Options::default()).unwrap();
|
||||
assert!(pix.data() == full.data(), "bands of {band_h} rows");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_list_that_loops_counts_the_whole_file() {
|
||||
let (doc, p, _) = backdrops_here_and_wider_elsewhere();
|
||||
// On top of the page: a frame listed as its own child, whose walk never ends. The blurs
|
||||
// under it are still counted.
|
||||
let doc = edit(&doc, |d| {
|
||||
let f = d.create(p, NodeKind::Frame, "Loop", 600.0, 420.0, 20.0, 20.0).unwrap();
|
||||
solid(d, f, "202020");
|
||||
d.get_mut(f).unwrap().children.push(f);
|
||||
});
|
||||
let v = |x: f64| View { origin: (x, 0.0), scale: 1.0, width: 640, height: 480 };
|
||||
let mut r = Retained::default();
|
||||
assert_eq!(check(&mut r, &doc, p, &v(0.0)), Work::Full);
|
||||
for i in 1..=3 {
|
||||
check(&mut r, &doc, p, &v(f64::from(i) * 50.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_to_a_pattern_a_vector_region_fills_with_show_on_the_page() {
|
||||
use figcraft_doc::{Region, Segment, VectorNetwork, Vertex, WindingRule};
|
||||
let mut d = Document::new("region pattern");
|
||||
let p = d.first_page().unwrap();
|
||||
let other = d.add_page("Sources");
|
||||
let source = d.create(other, NodeKind::Rectangle, "Source", 0.0, 0.0, 20.0, 20.0).unwrap();
|
||||
solid(&mut d, source, "E03030");
|
||||
let tile = Paint { kind: PaintKind::Pattern(PatternPaint::new(source.0)), ..Paint::solid(Color::BLACK) };
|
||||
let network = VectorNetwork {
|
||||
vertices: [(0.0, 0.0), (200.0, 0.0), (200.0, 160.0), (0.0, 160.0)].into_iter().map(|(x, y)| Vertex::new(x, y)).collect(),
|
||||
segments: (0..4).map(|i| Segment::line(i, (i + 1) % 4)).collect(),
|
||||
regions: vec![Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(vec![tile]), ..Default::default() }],
|
||||
};
|
||||
let v = d.create(p, NodeKind::Vector { network: network.into() }, "V", 20.0, 20.0, 200.0, 160.0).unwrap();
|
||||
d.get_mut(v).unwrap().fills.clear();
|
||||
let doc = Arc::new(d);
|
||||
let view = View { origin: (0.0, 0.0), scale: 1.0, width: 260, height: 220 };
|
||||
let mut r = Retained::default();
|
||||
check(&mut r, &doc, p, &view);
|
||||
let recoloured = edit(&doc, |d| solid(d, source, "2040E0"));
|
||||
assert_ne!(check(&mut r, &recoloured, p, &view), Work::Reused);
|
||||
}
|
||||
Reference in new issue
Block a user