mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-30 10:16:46 +01:00
Follows the page-only scan of the retained canvas: - Pattern sources come from every paint a layer draws with: its fills and strokes, and also its vector regions' own fills and its text runs' own fills. Before, the scan read only fills and strokes, so an edit to the source of a region's or a run's pattern left the canvas stale unless that source also filled an ordinary layer somewhere in the file. - A layer inside pattern sources is walked once, so a real tree stays within the walk's budget of three visits a layer. - A child list that repeats (a hostile file) runs out the budget; the scan then counts every layer of the file, as it did before the page scan, instead of what it had reached. New tests: glass and a small blur on the page with a wider blur on another page (full renders, a pan, an edit and band-by-band renders against render_view), a looping child list over blurs, and a vector region filled with a pattern from another page. Each fails with its part of this change taken out. The explanations of render_part, render_bands, render_columns and band_overlap now sit on the functions the canvas calls. large_doc_digests prints the same digests as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
829 lines
36 KiB
Rust
829 lines
36 KiB
Rust
//! Retained canvas rendering: keep the last rendered view and, for the next one, re-render only
|
||
//! what changed: the strips a pan uncovers and the areas of layers that were edited.
|
||
//!
|
||
//! 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`](crate::render_view).
|
||
|
||
use std::sync::Arc;
|
||
|
||
use figcraft_doc::{Document, Effect, EffectKind, Node, NodeId, NodeKind};
|
||
use figcraft_geom::Rect;
|
||
use tiny_skia::Pixmap;
|
||
|
||
use crate::{Options, View, draw};
|
||
|
||
/// What a render had to do.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum Work {
|
||
/// Nothing changed: the previous image as is.
|
||
Reused,
|
||
/// The previous image, shifted and/or patched where things changed.
|
||
Partial {
|
||
/// Device pixels rendered afresh.
|
||
pixels: u64,
|
||
},
|
||
/// The whole view.
|
||
Full,
|
||
}
|
||
|
||
/// Re-rendered areas beyond this many get merged into their bounding box.
|
||
const MAX_RECTS: usize = 8;
|
||
/// A change covering more than this share of the view renders it whole.
|
||
const MAX_PARTIAL_SHARE: f64 = 0.6;
|
||
/// More changed layers than this render the view whole.
|
||
const MAX_CHANGED: usize = 4096;
|
||
/// Effect margins beyond this many device pixels render the view whole.
|
||
const MAX_MARGIN_PX: f64 = 1024.0;
|
||
|
||
/// What a retained image was rendered from.
|
||
struct Frame {
|
||
doc: Arc<Document>,
|
||
page: NodeId,
|
||
outline: bool,
|
||
outline_extras: crate::Outline,
|
||
outlined: Vec<NodeId>,
|
||
lod: bool,
|
||
magnified_image_pixels: bool,
|
||
skip: Vec<NodeId>,
|
||
solo: Option<NodeId>,
|
||
background: Option<figcraft_color::Color>,
|
||
dots: Option<crate::Dots>,
|
||
scale: u64,
|
||
/// The view's top-left in device pixels (page origin × scale).
|
||
px: (i64, i64),
|
||
fonts: u64,
|
||
/// Areas (page coordinates) of layers whose look depends on where a render cuts them, and the
|
||
/// largest background blur (what backdrops read around).
|
||
sensitive: Arc<Sensitive>,
|
||
pix: Pixmap,
|
||
}
|
||
|
||
#[derive(Default)]
|
||
struct Sensitive {
|
||
areas: Vec<Rect>,
|
||
backdrop_blur: f64,
|
||
/// Pattern fill sources: an edit inside one shows wherever the pattern does.
|
||
pattern_sources: Vec<NodeId>,
|
||
}
|
||
|
||
/// 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`.
|
||
fn in_pattern_source(doc: &Document, s: &Sensitive, id: NodeId) -> bool {
|
||
s.pattern_sources.iter().any(|src| *src == id || doc.is_ancestor(*src, id))
|
||
}
|
||
|
||
/// A view snapped outwards to whole device pixels: the origin on its zoom's pixel grid and one
|
||
/// more pixel each way. Returns the view and its origin in device pixels.
|
||
pub fn snap(view: &View) -> Option<(View, (i64, i64))> {
|
||
let s = view.scale;
|
||
let (fx, fy) = ((view.origin.0 * s).floor(), (view.origin.1 * s).floor());
|
||
if !(s.is_finite() && s > 0.0 && fx.is_finite() && fy.is_finite() && fx.abs() < 1e15 && fy.abs() < 1e15) {
|
||
return None;
|
||
}
|
||
let v = View {
|
||
origin: (fx / s, fy / s),
|
||
scale: s,
|
||
width: view.width.saturating_add(1).clamp(1, 16_384),
|
||
height: view.height.saturating_add(1).clamp(1, 16_384),
|
||
};
|
||
Some((v, (fx as i64, fy as i64)))
|
||
}
|
||
|
||
/// Device-pixel rectangle `[x0, x1) × [y0, y1)` in the frame.
|
||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||
struct Px {
|
||
x0: i64,
|
||
y0: i64,
|
||
x1: i64,
|
||
y1: i64,
|
||
}
|
||
|
||
impl Px {
|
||
fn area(&self) -> u64 {
|
||
(self.x1 - self.x0).max(0) as u64 * (self.y1 - self.y0).max(0) as u64
|
||
}
|
||
fn union(&self, o: &Px) -> Px {
|
||
Px { x0: self.x0.min(o.x0), y0: self.y0.min(o.y0), x1: self.x1.max(o.x1), y1: self.y1.max(o.y1) }
|
||
}
|
||
fn clamp(&self, w: i64, h: i64) -> Option<Px> {
|
||
let r = Px { x0: self.x0.max(0), y0: self.y0.max(0), x1: self.x1.min(w), y1: self.y1.min(h) };
|
||
(r.x1 > r.x0 && r.y1 > r.y0).then_some(r)
|
||
}
|
||
}
|
||
|
||
/// What [`Retained::prepare`] found.
|
||
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`] finds on the page.
|
||
Full { snapped: View, px: (i64, i64), fonts: u64, sensitive: Arc<Sensitive> },
|
||
}
|
||
|
||
/// What [`Retained::begin`] did.
|
||
pub enum Begun<'a> {
|
||
/// The view drawn, its image and what it took.
|
||
Done(View, &'a Pixmap, Work),
|
||
/// A full render to draw band by band (boxed: it holds the image).
|
||
Steps(Box<Steps>),
|
||
}
|
||
|
||
/// A full render drawn a band at a time ([`Retained::begin`]): bands overlap by what background
|
||
/// blurs read and keep only their own rows, as the desktop's parallel bands do.
|
||
pub struct Steps {
|
||
doc: Arc<Document>,
|
||
page: NodeId,
|
||
view: View,
|
||
px: (i64, i64),
|
||
fonts: u64,
|
||
opts: Options,
|
||
sensitive: Arc<Sensitive>,
|
||
pix: Pixmap,
|
||
/// The first row not drawn yet.
|
||
next: u32,
|
||
band_h: u32,
|
||
overlap: u32,
|
||
}
|
||
|
||
impl Steps {
|
||
/// Draw the next band; `true` once every row is drawn.
|
||
pub fn step(&mut self) -> bool {
|
||
if self.done() {
|
||
return true;
|
||
}
|
||
let y0 = self.next;
|
||
if let Some(part) = crate::render_band(&self.doc, self.page, &self.view, &self.opts, y0, self.band_h, self.overlap) {
|
||
crate::put_band(&mut self.pix, y0, &part);
|
||
}
|
||
self.next = y0.saturating_add(self.band_h);
|
||
self.done()
|
||
}
|
||
|
||
/// Whether every row is drawn.
|
||
pub fn done(&self) -> bool {
|
||
self.next >= self.view.height
|
||
}
|
||
|
||
/// The view drawn (snapped to device pixels).
|
||
pub fn view(&self) -> &View {
|
||
&self.view
|
||
}
|
||
|
||
/// The page drawn.
|
||
pub fn page(&self) -> NodeId {
|
||
self.page
|
||
}
|
||
}
|
||
|
||
/// Keeps the last rendered view; see the module docs.
|
||
#[derive(Default)]
|
||
pub struct Retained {
|
||
last: Option<Frame>,
|
||
/// See [`Self::patched`].
|
||
patched: Option<Vec<[u32; 4]>>,
|
||
}
|
||
|
||
impl Retained {
|
||
/// Forget the kept image (the next render is full).
|
||
pub fn clear(&mut self) {
|
||
self.last = None;
|
||
self.patched = None;
|
||
}
|
||
|
||
/// The image kept from the last render.
|
||
pub fn image(&self) -> Option<&Pixmap> {
|
||
self.last.as_ref().map(|f| &f.pix)
|
||
}
|
||
|
||
/// Where the last render's image differs from the one before it, when it is that image with
|
||
/// some areas drawn again in place (`[x, y, width, height]` in its pixels; none for a render
|
||
/// reused as it was): whoever holds the image before needs only these to have this one.
|
||
/// `None` after a full render and after a pan, which moves every pixel.
|
||
pub fn patched(&self) -> Option<&[[u32; 4]]> {
|
||
self.patched.as_deref()
|
||
}
|
||
|
||
/// Render `view` of `page`, reusing the previous render where nothing changed. Returns the
|
||
/// view actually drawn (snapped to device pixels, see [`snap`]), the image and what it took.
|
||
pub fn render(&mut self, doc: &Arc<Document>, page: NodeId, view: &View, opts: &Options) -> Option<(View, &Pixmap, Work)> {
|
||
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 = 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))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// [`Self::render`], except that a full render comes back as [`Steps`] to draw `band_h` rows
|
||
/// at a time (the browser, whose renders block the page: input is handled between bands) and
|
||
/// keep with [`Self::finish`]. A render that is reused or patched is done at once.
|
||
pub fn begin(&mut self, doc: &Arc<Document>, page: NodeId, view: &View, opts: &Options, band_h: u32) -> Option<Begun<'_>> {
|
||
match self.prepare(doc, page, view, opts)? {
|
||
Prepared::Patched(snapped, work) => Some(Begun::Done(snapped, &self.last.as_ref()?.pix, work)),
|
||
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::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 = 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)?;
|
||
// One render, as the desktop's parallel bands are: glass keeps the shapes a
|
||
// later render asks for again, and the bands of this one are not later renders.
|
||
crate::start_render();
|
||
Some(Begun::Steps(Box::new(Steps {
|
||
doc: doc.clone(),
|
||
page,
|
||
view: snapped,
|
||
px,
|
||
fonts,
|
||
opts: opts.clone(),
|
||
sensitive,
|
||
pix,
|
||
next: 0,
|
||
band_h,
|
||
overlap,
|
||
})))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 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 frame = self.keep(&doc, page, (&view, px, fonts), &opts, pix, sensitive);
|
||
(view, &frame.pix)
|
||
}
|
||
|
||
/// The previous render patched where it could be (kept, see [`Self::keep`]), or what a full
|
||
/// render of `view` needs.
|
||
fn prepare(&mut self, doc: &Arc<Document>, page: NodeId, view: &View, opts: &Options) -> Option<Prepared> {
|
||
self.patched = None;
|
||
// A view that can't be put on a pixel grid (non-finite or absurd) draws nothing.
|
||
let Some((snapped, px)) = snap(view) else {
|
||
self.last = None;
|
||
return None;
|
||
};
|
||
let fonts = figcraft_text::layout_generation();
|
||
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
|
||
// Hidden layers drawn as outlines aren't in the bounds patches are cut from.
|
||
&& !opts.outline.hidden
|
||
&& last.outlined == opts.outlined
|
||
&& last.lod == opts.lod
|
||
&& last.magnified_image_pixels == opts.magnified_image_pixels
|
||
&& last.skip == opts.skip
|
||
&& last.solo == opts.solo
|
||
&& last.background == opts.background
|
||
&& last.dots == opts.dots
|
||
&& last.scale == snapped.scale.to_bits()
|
||
&& last.pix.width() == snapped.width
|
||
&& last.pix.height() == snapped.height
|
||
&& 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 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: s })
|
||
}
|
||
|
||
/// Keep `pix`, the render of `at`: the snapped view, its top-left device pixel and the font
|
||
/// generation the render started with (fonts arriving meanwhile leave it stale).
|
||
fn keep(
|
||
&mut self,
|
||
doc: &Arc<Document>,
|
||
page: NodeId,
|
||
at: (&View, (i64, i64), u64),
|
||
opts: &Options,
|
||
pix: Pixmap,
|
||
sensitive: Arc<Sensitive>,
|
||
) -> &Frame {
|
||
let (view, px, fonts) = at;
|
||
self.last.insert(Frame {
|
||
doc: doc.clone(),
|
||
page,
|
||
outline: opts.outline_mode,
|
||
outline_extras: opts.outline,
|
||
outlined: opts.outlined.clone(),
|
||
lod: opts.lod,
|
||
magnified_image_pixels: opts.magnified_image_pixels,
|
||
skip: opts.skip.clone(),
|
||
solo: opts.solo,
|
||
background: opts.background,
|
||
dots: opts.dots,
|
||
scale: view.scale.to_bits(),
|
||
px,
|
||
fonts,
|
||
sensitive,
|
||
pix,
|
||
})
|
||
}
|
||
}
|
||
|
||
/// Page rectangle → device pixels of a frame whose top-left is `px`, rounded outwards plus a pixel
|
||
/// of anti-aliasing.
|
||
fn to_px(r: Rect, scale: f64, px: (i64, i64)) -> Option<Px> {
|
||
let (x0, y0, x1, y1) = ((r.x0 * scale).floor() - 1.0, (r.y0 * scale).floor() - 1.0, (r.x1 * scale).ceil() + 1.0, (r.y1 * scale).ceil() + 1.0);
|
||
if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite())
|
||
|| x0.abs() > 1e15
|
||
|| y0.abs() > 1e15
|
||
|| x1.abs() > 1e15
|
||
|| y1.abs() > 1e15
|
||
{
|
||
return None;
|
||
}
|
||
Some(Px { x0: x0 as i64 - px.0, y0: y0 as i64 - px.1, x1: x1 as i64 - px.0, y1: y1 as i64 - px.1 })
|
||
}
|
||
|
||
/// Page areas a change to `id` in `doc` affects on `page`; `None` when only a full render will do.
|
||
fn changed_areas(doc: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>) -> Option<()> {
|
||
let Some(n) = doc.node(id) else { return Some(()) };
|
||
if n.is_page() {
|
||
// Page background, page order or top-level layers.
|
||
return if id == page { None } else { Some(()) };
|
||
}
|
||
if doc.page_of(id) != Some(page) {
|
||
return Some(());
|
||
}
|
||
out.push(draw::paint_bounds(doc, id)?);
|
||
// A mask clips the layers above it.
|
||
if n.is_mask {
|
||
let parent = n.parent?;
|
||
if parent == page {
|
||
return None;
|
||
}
|
||
out.push(draw::paint_bounds(doc, parent)?);
|
||
}
|
||
ancestor_areas(doc, id, out)
|
||
}
|
||
|
||
/// The areas of the ancestors of `id` that a change to it affects, beyond its own.
|
||
fn ancestor_areas(doc: &Document, id: NodeId, out: &mut Vec<Rect>) -> Option<()> {
|
||
// Ancestors that paint from their children's pixels (booleans, effects, masks): all of them.
|
||
for a in doc.ancestors(id) {
|
||
let Some(an) = doc.node(a) else { break };
|
||
if an.is_page() {
|
||
break;
|
||
}
|
||
if matches!(an.kind, NodeKind::BooleanOp { .. }) || an.is_mask || an.effects.iter().any(|e| e.visible) {
|
||
out.push(draw::paint_bounds(doc, a)?);
|
||
}
|
||
}
|
||
Some(())
|
||
}
|
||
|
||
/// Page areas in which `id` looks different in `after` than in `before` (where it was and where
|
||
/// it is now, and what of its ancestors follows); `None` when only a full render will do.
|
||
fn edited_areas(before: &Document, after: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>) -> Option<()> {
|
||
// A vector whose points moved looks different only around them.
|
||
if let Some(area) = moved_points_area(before, after, page, id) {
|
||
out.push(area);
|
||
ancestor_areas(before, id, out)?;
|
||
return ancestor_areas(after, id, out);
|
||
}
|
||
changed_areas(before, page, id, out)?;
|
||
changed_areas(after, page, id, out)
|
||
}
|
||
|
||
/// Vectors with more points than this are drawn again whole when they change.
|
||
const MAX_MOVED_POINTS: usize = 4096;
|
||
|
||
/// Whether every visible paint of `paints` is one colour: it looks the same wherever the layer's
|
||
/// box lies (a gradient or an image is laid out in the box).
|
||
fn plain(paints: &[figcraft_color::Paint]) -> bool {
|
||
paints.iter().filter(|p| p.visible).all(|p| matches!(p.kind, figcraft_color::PaintKind::Solid { .. }))
|
||
}
|
||
|
||
/// The page area in which vector `id` looks different in `after` than in `before`, when all that
|
||
/// changed is where its points and handles are (a point dragged in the vector editor): around the
|
||
/// segments that moved and their neighbours (whose joins and rounded corners follow them), as far
|
||
/// out as the stroke reaches. The rest of a large shape keeps its pixels, however much of the
|
||
/// view it fills. `None` when anything else changed or the look depends on the whole outline
|
||
/// (dashes, a width profile, a brush, gradients and images laid out in the box, effects, a mask):
|
||
/// the layer is then drawn again whole.
|
||
fn moved_points_area(before: &Document, after: &Document, page: NodeId, id: NodeId) -> Option<Rect> {
|
||
let (a, b) = (before.node(id)?, after.node(id)?);
|
||
let (NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) = (&a.kind, &b.kind) else { return None };
|
||
if after.page_of(id) != Some(page) || before.page_of(id) != Some(page) {
|
||
return None;
|
||
}
|
||
let simple = |n: &figcraft_doc::Node, net: &figcraft_doc::VectorNetwork| {
|
||
!n.is_mask
|
||
&& n.visible
|
||
&& !n.effects.iter().any(|e| e.visible)
|
||
&& n.stroke.dashes.is_empty()
|
||
&& n.stroke.width_profile.is_none()
|
||
&& n.stroke.brush.is_none()
|
||
&& plain(&n.fills)
|
||
&& plain(&n.strokes)
|
||
&& net.regions.iter().all(|r| r.fills.as_deref().is_none_or(plain))
|
||
};
|
||
let same_shape = na.vertices.len() == nb.vertices.len()
|
||
&& na.vertices.len() <= MAX_MOVED_POINTS
|
||
&& na.segments.len() == nb.segments.len()
|
||
&& na.segments.iter().zip(&nb.segments).all(|(x, y)| (x.a, x.b) == (y.a, y.b))
|
||
&& na.regions.len() == nb.regions.len()
|
||
&& na.regions.iter().zip(&nb.regions).all(|(x, y)| x.loops == y.loops && x.winding == y.winding && x.fills == y.fills);
|
||
if !(simple(a, na) && simple(b, nb) && same_shape) {
|
||
return None;
|
||
}
|
||
// A fill closes an open path with a line between its ends that is no segment: it moves
|
||
// with either end, across the whole shape.
|
||
let mut ends = vec![0u8; na.vertices.len()];
|
||
for s in &na.segments {
|
||
for i in [s.a, s.b] {
|
||
let n = ends.get_mut(i)?;
|
||
*n = n.saturating_add(1);
|
||
}
|
||
}
|
||
let filled = a.fills.iter().any(|f| f.visible) || !na.regions.is_empty();
|
||
if filled && ends.contains(&1) {
|
||
return None;
|
||
}
|
||
// Nothing but the geometry differs: the box follows the points, and with it the transform.
|
||
let mut as_after = a.clone();
|
||
as_after.kind = b.kind.clone();
|
||
(as_after.transform, as_after.width, as_after.height) = (b.transform, b.width, b.height);
|
||
if as_after != *b {
|
||
return None;
|
||
}
|
||
let (wa, wb) = (before.world_transform(id), after.world_transform(id));
|
||
// The box following the points moves the layer; anything else a transform does (a scale, a
|
||
// turn) changes every stroke's width or direction on the page, whether its path moved or not.
|
||
let (ca, cb) = (wa.as_coeffs(), wb.as_coeffs());
|
||
if ca.iter().zip(&cb).take(4).any(|(x, y)| (x - y).abs() > 1e-12 * x.abs().max(1.0)) {
|
||
return None;
|
||
}
|
||
// A segment on the page: its ends and handles.
|
||
let hull = |w: figcraft_geom::Affine, net: &figcraft_doc::VectorNetwork, s: &figcraft_doc::Segment| {
|
||
let (pa, pb) = (net.vertices.get(s.a)?.point(), net.vertices.get(s.b)?.point());
|
||
let pts = [pa, pa + figcraft_geom::Vec2::new(s.ta.0, s.ta.1), pb + figcraft_geom::Vec2::new(s.tb.0, s.tb.1), pb].map(|p| w * p);
|
||
pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()).then_some(pts)
|
||
};
|
||
let mut moved = vec![false; na.vertices.len()];
|
||
let mut hulls = Vec::with_capacity(na.segments.len());
|
||
for (sa, sb) in na.segments.iter().zip(&nb.segments) {
|
||
let (ha, hb) = (hull(wa, na, sa)?, hull(wb, nb, sb)?);
|
||
// Apart by more than float noise. When the box follows a moved point every local
|
||
// coordinate shifts and the transform shifts back: a point that stayed put comes out a
|
||
// few ulps from where it was. 64 of them is far above that and far under a pixel at any
|
||
// zoom, wherever on the page the vector lies (a tenth of a millionth of a unit at
|
||
// coordinates of ten million).
|
||
let near = |x: f64, y: f64| (x - y).abs() <= 64.0 * f64::EPSILON * x.abs().max(y.abs()).max(1.0);
|
||
let apart = ha.iter().zip(&hb).any(|(p, q)| !(near(p.x, q.x) && near(p.y, q.y)));
|
||
let styled =
|
||
|i: usize| na.vertices.get(i).zip(nb.vertices.get(i)).is_none_or(|(x, y)| (x.radius, x.cap, x.join) != (y.radius, y.cap, y.join));
|
||
if apart || styled(sa.a) || styled(sa.b) {
|
||
for i in [sa.a, sa.b] {
|
||
*moved.get_mut(i)? = true;
|
||
}
|
||
}
|
||
hulls.push((ha, hb));
|
||
}
|
||
// Every segment at a point of a segment that moved: its join or rounded corner there follows.
|
||
let mut area: Option<Rect> = None;
|
||
for (s, (ha, hb)) in na.segments.iter().zip(&hulls) {
|
||
if moved.get(s.a).copied().unwrap_or(true) || moved.get(s.b).copied().unwrap_or(true) {
|
||
for p in ha.iter().chain(hb) {
|
||
let r = Rect::from_points(*p, *p);
|
||
area = Some(area.map_or(r, |a| a.union(r)));
|
||
}
|
||
}
|
||
}
|
||
let area = area?;
|
||
// As far as the stroke reaches from the path, on the page.
|
||
// The most the transform stretches a length in any direction (its largest singular value):
|
||
// under a skew that is more than either axis is stretched.
|
||
let stretch = |w: figcraft_geom::Affine| {
|
||
let c = w.as_coeffs();
|
||
let sum = c[0] * c[0] + c[1] * c[1] + c[2] * c[2] + c[3] * c[3];
|
||
let det = c[0] * c[3] - c[1] * c[2];
|
||
((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
|
||
};
|
||
let reach = (a.outline_reach() * stretch(wa)).max(b.outline_reach() * stretch(wb));
|
||
reach.is_finite().then(|| area.inflate(reach, reach))
|
||
}
|
||
|
||
/// The previous frame brought up to date for `doc` at `px`, rendering only what changed; `None`
|
||
/// when a full render is the better (or only correct) choice. Also returns the pixels rendered,
|
||
/// and the areas they are in when nothing else of the image changed (it didn't move).
|
||
#[allow(clippy::type_complexity)]
|
||
fn patch(
|
||
last: Frame,
|
||
doc: &Arc<Document>,
|
||
page: NodeId,
|
||
view: &View,
|
||
px: (i64, i64),
|
||
opts: &Options,
|
||
s: &Sensitive,
|
||
) -> Option<(Pixmap, u64, Option<Vec<[u32; 4]>>)> {
|
||
let (w, h) = (i64::from(view.width), i64::from(view.height));
|
||
let (dx, dy) = (px.0.checked_sub(last.px.0)?, px.1.checked_sub(last.px.1)?);
|
||
if dx.abs() >= w || dy.abs() >= h {
|
||
return None;
|
||
}
|
||
// Background blurs read the backdrop around them, so a change shows that far off: under a blur
|
||
// beside a changed layer, and at the old view's edge (where the backdrop used to end).
|
||
let reach = crate::backdrop_reach(s.backdrop_blur.max(last.sensitive.backdrop_blur), view.scale).ceil();
|
||
if !reach.is_finite() || reach > MAX_MARGIN_PX {
|
||
return None;
|
||
}
|
||
let reach = reach as i64;
|
||
let mut damage: Vec<Px> = Vec::new();
|
||
// Strips a pan uncovers.
|
||
if dx > 0 {
|
||
damage.push(Px { x0: w - dx - reach, y0: 0, x1: w, y1: h });
|
||
} else if dx < 0 {
|
||
damage.push(Px { x0: 0, y0: 0, x1: reach - dx, y1: h });
|
||
}
|
||
if dy > 0 {
|
||
damage.push(Px { x0: 0, y0: h - dy - reach, x1: w, y1: h });
|
||
} else if dy < 0 {
|
||
damage.push(Px { x0: 0, y0: 0, x1: w, y1: reach - dy });
|
||
}
|
||
// And at the edges that moved in: a backdrop there read what is now past the edge.
|
||
if reach > 0 {
|
||
if dx > 0 {
|
||
damage.push(Px { x0: 0, y0: 0, x1: reach, y1: h });
|
||
} else if dx < 0 {
|
||
damage.push(Px { x0: w - reach, y0: 0, x1: w, y1: h });
|
||
}
|
||
if dy > 0 {
|
||
damage.push(Px { x0: 0, y0: 0, x1: w, y1: reach });
|
||
} else if dy < 0 {
|
||
damage.push(Px { x0: 0, y0: h - reach, x1: w, y1: h });
|
||
}
|
||
}
|
||
// Layers that changed, where they were and where they are now.
|
||
if !Arc::ptr_eq(&last.doc, doc) {
|
||
let mut areas = Vec::new();
|
||
for id in doc.changed_ids(&last.doc, MAX_CHANGED)? {
|
||
// shortcut: an edited pattern source redraws the whole view; patch the patterned layers' areas when that shows up in profiles.
|
||
if in_pattern_source(doc, s, id) || in_pattern_source(&last.doc, &last.sensitive, id) {
|
||
return None;
|
||
}
|
||
edited_areas(&last.doc, doc, page, id, &mut areas)?;
|
||
}
|
||
for r in areas {
|
||
if let Some(p) = to_px(r, view.scale, px) {
|
||
damage.push(Px { x0: p.x0 - reach, y0: p.y0 - reach, x1: p.x1 + reach, y1: p.y1 + reach });
|
||
}
|
||
}
|
||
}
|
||
let mut damage: Vec<Px> = damage.iter().filter_map(|d| d.clamp(w, h)).collect();
|
||
if damage.is_empty() && dx == 0 && dy == 0 {
|
||
return Some((last.pix, 0, Some(Vec::new())));
|
||
}
|
||
// Layers whose look depends on where they are cut are redrawn whole.
|
||
let sensitive: Vec<Px> = s.areas.iter().chain(last.sensitive.areas.iter()).filter_map(|r| to_px(*r, view.scale, px)).collect();
|
||
for _ in 0..4 {
|
||
let mut grew = false;
|
||
for d in damage.iter_mut() {
|
||
for a in &sensitive {
|
||
let hits = a.x0 < d.x1 && d.x0 < a.x1 && a.y0 < d.y1 && d.y0 < a.y1;
|
||
if hits && a.union(d) != *d {
|
||
*d = a.union(d);
|
||
grew = true;
|
||
}
|
||
}
|
||
}
|
||
if !grew {
|
||
break;
|
||
}
|
||
}
|
||
let mut damage = merge(damage.iter().filter_map(|d| d.clamp(w, h)).collect());
|
||
if damage.len() > MAX_RECTS {
|
||
let all = damage.iter().skip(1).fold(*damage.first()?, |a, b| a.union(b));
|
||
damage = vec![all];
|
||
}
|
||
let pixels: u64 = damage.iter().map(Px::area).sum();
|
||
if pixels as f64 > MAX_PARTIAL_SHARE * (w * h) as f64 {
|
||
return None;
|
||
}
|
||
// Render with the backdrop reach as a margin (so blurs see their whole backdrop), keep the inside.
|
||
let margin = reach + 1;
|
||
let mut pix = last.pix;
|
||
shift(&mut pix, dx, dy)?;
|
||
for d in &damage {
|
||
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()?]);
|
||
let areas = if dx == 0 && dy == 0 { damage.iter().map(area).collect() } else { None };
|
||
Some((pix, pixels, areas))
|
||
}
|
||
|
||
/// Move the image's content by `(-dx, -dy)` pixels in place (what was at `(x, y)` goes to
|
||
/// `(x - dx, y - dy)`); the uncovered strips keep stale pixels for the caller to re-render.
|
||
fn shift(pix: &mut Pixmap, dx: i64, dy: i64) -> Option<()> {
|
||
if dx == 0 && dy == 0 {
|
||
return Some(());
|
||
}
|
||
let (w, h) = (i64::from(pix.width()), i64::from(pix.height()));
|
||
let row = usize::try_from(w * 4).ok()?;
|
||
let data = pix.data_mut();
|
||
// Columns that survive the horizontal move, as byte ranges within a row.
|
||
let (src_x, dst_x, n) = if dx >= 0 { (dx, 0, w - dx) } else { (0, -dx, w + dx) };
|
||
let (src_x, dst_x, n) = (usize::try_from(src_x * 4).ok()?, usize::try_from(dst_x * 4).ok()?, usize::try_from(n * 4).ok()?);
|
||
let ys: Box<dyn Iterator<Item = i64>> = if dy >= 0 { Box::new(0..h - dy) } else { Box::new((-dy..h).rev()) };
|
||
for y in ys {
|
||
let (src, dst) = (usize::try_from(y + dy).ok()? * row, usize::try_from(y).ok()? * row);
|
||
if src + src_x + n > data.len() || dst + dst_x + n > data.len() {
|
||
return None;
|
||
}
|
||
data.copy_within(src + src_x..src + src_x + n, dst + dst_x);
|
||
}
|
||
Some(())
|
||
}
|
||
|
||
/// Merge rectangles that overlap so much that their bounding box is no bigger than the two
|
||
/// (where a layer was and where it is now, a frame and its child…): no pixel renders twice.
|
||
fn merge(mut rects: Vec<Px>) -> Vec<Px> {
|
||
let mut i = 0;
|
||
while i < rects.len() {
|
||
let mut j = i + 1;
|
||
let mut merged = false;
|
||
while j < rects.len() {
|
||
let (Some(a), Some(b)) = (rects.get(i).copied(), rects.get(j).copied()) else { break };
|
||
let u = a.union(&b);
|
||
if u.area() <= a.area() + b.area() {
|
||
if let Some(slot) = rects.get_mut(i) {
|
||
*slot = u;
|
||
}
|
||
rects.swap_remove(j);
|
||
merged = true;
|
||
} else {
|
||
j += 1;
|
||
}
|
||
}
|
||
if !merged {
|
||
i += 1;
|
||
}
|
||
}
|
||
rects
|
||
}
|
||
|
||
struct FrameRender<'a> {
|
||
doc: &'a Document,
|
||
page: NodeId,
|
||
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, 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));
|
||
let (ex, ey) = ((d.x1 + margin).min(w), (d.y1 + margin).min(h));
|
||
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_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()?);
|
||
let (cols, rows) = (usize::try_from(d.x1 - d.x0).ok()?, usize::try_from(d.y1 - d.y0).ok()?);
|
||
let (at_x, at_y) = (usize::try_from(d.x0).ok()?, usize::try_from(d.y0).ok()?);
|
||
let (src_w, dst_w) = (part.width() as usize, pix.width() as usize);
|
||
let dst = pix.data_mut();
|
||
for (r, row) in part.data().chunks_exact(src_w.max(1) * 4).skip(skip_y).take(rows).enumerate() {
|
||
let from = row.get(skip_x * 4..(skip_x + cols) * 4)?;
|
||
let start = ((at_y + r) * dst_w + at_x) * 4;
|
||
dst.get_mut(start..start + cols * 4)?.copy_from_slice(from);
|
||
}
|
||
Some(())
|
||
}
|