mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 07:17:00 +00:00
Merge main into fix/image-cache-follows-memory
This commit is contained in:
@@ -46,9 +46,9 @@ fn shows_definitions(brush: &Brush, st: &StrokeLayer) -> bool {
|
||||
matches!(st.paint, vectorcraft_color::Paint::Pattern { .. }) || crate::fx::Reads::of_all(art.into_iter()).shows_definitions()
|
||||
}
|
||||
|
||||
/// The art of `doc`'s patterns and symbols, in order.
|
||||
fn definitions(doc: &Document) -> impl Iterator<Item = &Arc<Node>> {
|
||||
doc.patterns.iter().flat_map(|p| &p.art).chain(doc.symbols.iter().map(|s| &s.art))
|
||||
/// The names and art of `doc`'s patterns and symbols, in order.
|
||||
fn definitions(doc: &Document) -> impl Iterator<Item = (&str, &Arc<Node>)> {
|
||||
doc.patterns.iter().flat_map(|p| p.art.iter().map(|a| (p.name.as_str(), a))).chain(doc.symbols.iter().map(|s| (s.name.as_str(), &s.art)))
|
||||
}
|
||||
|
||||
/// Parsed brush library and generated brush art.
|
||||
@@ -61,9 +61,9 @@ pub(crate) struct BrushCache {
|
||||
/// (frame stamp, document address) the library was last validated for.
|
||||
checked: (u64, usize),
|
||||
lib: HashMap<String, Arc<Brush>>,
|
||||
/// The art of the document's patterns and symbols ([`definitions`]) when the library was last
|
||||
/// validated, held weakly as the pattern tiles hold theirs.
|
||||
definitions: Vec<Weak<Node>>,
|
||||
/// The names and art of the document's patterns and symbols ([`definitions`]) when the library
|
||||
/// was last validated, the art held weakly as the pattern tiles hold theirs.
|
||||
definitions: Vec<(String, Weak<Node>)>,
|
||||
/// Brush art per (node id, stroke item index, [`path_key`] of the stroked path).
|
||||
pub(crate) entries: FrameCache<(u64, usize, u64), Entry>,
|
||||
/// How many times [`Renderer::draw_brush`] made brush art.
|
||||
@@ -93,8 +93,8 @@ impl BrushCache {
|
||||
return;
|
||||
}
|
||||
self.checked = key;
|
||||
if !self.definitions.iter().map(Weak::as_ptr).eq(definitions(doc).map(Arc::as_ptr)) {
|
||||
self.definitions = definitions(doc).map(Arc::downgrade).collect();
|
||||
if !self.definitions.iter().map(|(n, a)| (n.as_str(), a.as_ptr())).eq(definitions(doc).map(|(n, a)| (n, Arc::as_ptr(a)))) {
|
||||
self.definitions = definitions(doc).map(|(n, a)| (n.to_string(), Arc::downgrade(a))).collect();
|
||||
self.entries.retain(|e| !e.definitions);
|
||||
}
|
||||
let cur = doc.unknown.get(vectorcraft_brush::DOC_KEY);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! What draws differently after an edit, so a view can draw again only there.
|
||||
//! What draws differently after an edit, or once placed documents' bitmaps are ready, so a view
|
||||
//! can draw again only there.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes};
|
||||
@@ -14,6 +16,66 @@ pub enum Changed {
|
||||
Everything,
|
||||
}
|
||||
|
||||
impl Changed {
|
||||
/// What may draw differently after this change and `other`: everything when either is,
|
||||
/// else both areas.
|
||||
pub fn and(self, other: Changed) -> Changed {
|
||||
match (self, other) {
|
||||
(Changed::Everything, _) | (_, Changed::Everything) => Changed::Everything,
|
||||
(Changed::Area(a), Changed::Area(b)) => Changed::Area(a.union(b)),
|
||||
(Changed::Area(a), Changed::Nothing) | (Changed::Nothing, Changed::Area(a)) => Changed::Area(a),
|
||||
(Changed::Nothing, Changed::Nothing) => Changed::Nothing,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What draws differently in `doc` once the bitmaps of the placed documents' `files` are ready
|
||||
/// ([`crate::placed_document::made_between`]): the bounds of everything the objects that show
|
||||
/// them paint, measured as [`changed`] measures an object that changed. Everything when the art
|
||||
/// of a symbol, a graph design, a pattern or a brush shows one of them (it draws wherever it is
|
||||
/// used), or while a pattern is edited.
|
||||
pub fn placed_area(doc: &Document, files: &HashSet<String>) -> Changed {
|
||||
if files.is_empty() {
|
||||
return Changed::Nothing;
|
||||
}
|
||||
let mut elsewhere =
|
||||
doc.symbols.iter().map(|s| &s.art).chain(doc.graph_designs.iter().map(|g| &g.art)).chain(doc.patterns.iter().flat_map(|p| &p.art));
|
||||
if doc.pattern_edit.is_some()
|
||||
|| elsewhere.any(|n| shows(n, files))
|
||||
|| vectorcraft_brush::library(doc).iter().any(|b| b.art().into_iter().any(|n| shows(n, files)))
|
||||
{
|
||||
return Changed::Everything;
|
||||
}
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut area = None;
|
||||
for layer in &doc.layers {
|
||||
add_placed(&symbols, layer, files, &mut area);
|
||||
}
|
||||
area.map_or(Changed::Nothing, Changed::Area)
|
||||
}
|
||||
|
||||
/// Does `n`, a member of it or the art of an opacity mask in it show one of `files`?
|
||||
fn shows(n: &Node, files: &HashSet<String>) -> bool {
|
||||
matches!(&n.kind, NodeKind::PlacedDocument(p) if files.contains(&p.key))
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| shows(&m.art, files))
|
||||
|| n.children().is_some_and(|c| c.iter().any(|c| shows(c, files)))
|
||||
}
|
||||
|
||||
/// Add to `area` what `n` paints where it shows one of `files`: each member of a group or layer
|
||||
/// whose members draw each on their own (unless its opacity mask shows one), and any other object
|
||||
/// whole.
|
||||
fn add_placed(symbols: &SymbolBoxes, n: &Node, files: &HashSet<String>, area: &mut Option<Rect>) {
|
||||
match members(n) {
|
||||
Some(children) if !n.extras().mask.as_ref().is_some_and(|m| shows(&m.art, files)) => {
|
||||
for c in children {
|
||||
add_placed(symbols, c, files, area);
|
||||
}
|
||||
}
|
||||
_ if shows(n, files) => *area = vectorcraft_geom::union_opt(*area, crate::brush_fx::cull_bounds(symbols, n)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// What may draw differently in `new` than in `old`, the version before an edit: the bounds of
|
||||
/// everything the objects that changed paint, before and after the edit ([`crate::painted_bounds`]),
|
||||
/// or everything when more than the art in the layers changed, or while a pattern is edited (its
|
||||
|
||||
+98
-29
@@ -687,7 +687,8 @@ fn linear_key(view: Affine) -> [u64; 4] {
|
||||
}
|
||||
|
||||
/// The pan of the view a raster was cropped for, or made at a lower resolution than the view's, and
|
||||
/// the device-pixel rect of the frame it was made in ([`PixelEntry::view`], [`ShadowEntry::view`]).
|
||||
/// the device-pixel rect it was made for in that view: the frame's, or around it the margin of
|
||||
/// [`pan_margin`] ([`PixelEntry::view`], [`ShadowEntry::view`]).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ViewCrop {
|
||||
pan: Vec2,
|
||||
@@ -701,7 +702,7 @@ impl ViewCrop {
|
||||
|
||||
/// Does the raster draw in a frame through `view` (of the same zoom and rotation) onto
|
||||
/// `screen`? When the view is panned by whole pixels and the frame's rect, panned back, lies
|
||||
/// within the one the raster was made in: the same pixels in the same places, as when a frame
|
||||
/// within the one the raster was made for: the same pixels in the same places, as when a frame
|
||||
/// is drawn again only in a part of it.
|
||||
fn serves(&self, view: Affine, screen: Rect) -> bool {
|
||||
let d = view.translation() - self.pan;
|
||||
@@ -709,6 +710,30 @@ impl ViewCrop {
|
||||
let s = screen - whole;
|
||||
(d - whole).hypot() < 1e-6 && s.x0 >= self.screen.x0 && s.y0 >= self.screen.y0 && s.x1 <= self.screen.x1 && s.y1 <= self.screen.y1
|
||||
}
|
||||
|
||||
/// The rect the raster was made for, in the device pixels of a frame through `view` that it
|
||||
/// serves ([`Self::serves`]).
|
||||
fn served(&self, view: Affine) -> Rect {
|
||||
let d = view.translation() - self.pan;
|
||||
self.screen + Vec2::new(d.x.round(), d.y.round())
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (device pixels, on each side) past a `w` × `h` view a raster cropped to it, and `m`
|
||||
/// pixels around that, is made when it is made again at the same zoom and rotation, so that later
|
||||
/// pans of up to that many pixels draw it: the most that keeps the raster within `budget` pixels and
|
||||
/// `side` pixels a side, with two pixels to spare for rounding, and at most half the view's longer
|
||||
/// side. 0 when the view and the `m` pixels around it alone leave no room.
|
||||
fn pan_margin((w, h): (f64, f64), m: f64, budget: f64, side: f64) -> f64 {
|
||||
let (a, b) = (w + 2.0 * m, h + 2.0 * m);
|
||||
// The largest `e` with (a + 2e) × (b + 2e) within the budget, less two pixels for the rounding
|
||||
// of the raster's edges to whole pixels.
|
||||
let e = (((a - b).powi(2) + 4.0 * budget).sqrt() - (a + b)) / 4.0 - 2.0;
|
||||
// (Also for a view or spread that isn't a number.)
|
||||
if !e.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
e.min((side - a.max(b)) / 2.0 - 2.0).min(w.max(h) / 2.0).floor().max(0.0)
|
||||
}
|
||||
|
||||
/// Most pixels a raster of [`Renderer::pixel_content`] or [`Renderer::with_filters`] holds while
|
||||
@@ -816,8 +841,9 @@ struct Shadow {
|
||||
mode: vectorcraft_doc::color::BlendMode,
|
||||
/// Made before its object moved ([`ShadowEntry::moved`]).
|
||||
moved: bool,
|
||||
/// Cropped to the view, or made over a raster that is ([`ShadowEntry::view`]).
|
||||
cropped: bool,
|
||||
/// For a raster cropped to the view, or made over a raster that is ([`ShadowEntry::view`]), the
|
||||
/// rect it was made for, in this frame's device pixels ([`ViewCrop::served`]).
|
||||
cropped: Option<Rect>,
|
||||
}
|
||||
|
||||
impl ShadowEntry {
|
||||
@@ -1099,9 +1125,12 @@ impl Renderer {
|
||||
/// what can show in the `screen` (device pixels): the view, and around it the blur's spread and
|
||||
/// `around` (document units: how far the shadows and glows stacked over this one look), made
|
||||
/// coarser to fit the budget where the blur hides the coarser grid. Such a raster, and one
|
||||
/// made over it (`over_cropped`), is reused only in the same view. `None` when the effect isn't
|
||||
/// a shadow/glow or the raster would still be too large (caller falls back to
|
||||
/// [`Self::draw_shadow_filter`]).
|
||||
/// made over it, is reused while a pan keeps the view inside the rect it was made for: the
|
||||
/// view, and when the raster kept for the object was made at the same zoom and rotation and no
|
||||
/// drag is on, the view with [`pan_margin`] around it, within `over` (the rect, in device
|
||||
/// pixels, that the cropped rasters of the shadows and glows it is made over were made for;
|
||||
/// `None` when it is made over none). `None` when the effect isn't a shadow/glow or the raster
|
||||
/// would still be too large (caller falls back to [`Self::draw_shadow_filter`]).
|
||||
/// While dragging on a multithreaded context, a raster that has to be made again counts as too
|
||||
/// large when it would hold more than [`DRAG_PIXEL_BUDGET`] pixels.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -1113,7 +1142,7 @@ impl Renderer {
|
||||
fx: &RasterFx,
|
||||
reach: Rect,
|
||||
owner: Option<&Arc<Node>>,
|
||||
(screen, around, over_cropped): (Rect, f64, bool),
|
||||
(screen, around, over): (Rect, f64, Option<Rect>),
|
||||
paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame),
|
||||
) -> Option<Shadow> {
|
||||
let (mode, opacity, dx, dy, blur, color, darkness) = match fx {
|
||||
@@ -1128,7 +1157,6 @@ impl Renderer {
|
||||
// What the silhouette reads: as the raster kept for `n` found it, else found now.
|
||||
let reads = self.shadows.get(&key).filter(|e| e.node.is(n)).map_or_else(|| Reads::of(n), |e| e.inputs.reads);
|
||||
let inputs = self.raster_inputs(f, n, reads);
|
||||
let in_view = ViewCrop::of(f.view, screen);
|
||||
let exact = |e: &ShadowEntry| {
|
||||
e.linear == linear && e.node.is(n) && e.inputs == inputs && (interacting || !e.moved) && e.view.is_none_or(|v| v.serves(f.view, screen))
|
||||
};
|
||||
@@ -1141,7 +1169,7 @@ impl Renderer {
|
||||
e.stamp = stamp;
|
||||
self.stats.moved += usize::from(e.moved);
|
||||
let p = f.view * e.anchor;
|
||||
(e.image.clone(), (p.x + e.rel.0).round(), (p.y + e.rel.1).round(), e.scale, e.moved, e.view.is_some())
|
||||
(e.image.clone(), (p.x + e.rel.0).round(), (p.y + e.rel.1).round(), e.scale, e.moved, e.view.map(|v| v.served(f.view)))
|
||||
}
|
||||
None => {
|
||||
// An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first.
|
||||
@@ -1162,18 +1190,23 @@ impl Renderer {
|
||||
};
|
||||
// A glow too large for the budget is made coarser, where its blur hides the coarser grid: the filter
|
||||
// layer the caller falls back to can't make its silhouette solid.
|
||||
let full = region(whole, matches!(fx, RasterFx::OuterGlow { .. }), 4.0e6).filter(|_| !over_cropped);
|
||||
let full = region(whole, matches!(fx, RasterFx::OuterGlow { .. }), 4.0e6).filter(|_| over.is_none());
|
||||
// Else it is cropped to what can show in the view, within the budget of the filter
|
||||
// layer it would otherwise be drawn through, and made coarser in the same way.
|
||||
// layer it would otherwise be drawn through, and made coarser in the same way. Made
|
||||
// again at this zoom and rotation (after a pan), it covers a margin around the view
|
||||
// too, so that later pans within the margin draw it.
|
||||
let ((x0, y0, w, h, scale), cropped) = match full {
|
||||
Some(r) => (r, false),
|
||||
Some(r) => (r, None),
|
||||
None => {
|
||||
let m = spread + around / f.px;
|
||||
let r = whole.intersect(screen.inflate(m, m));
|
||||
let again = self.shadows.get(&key).is_some_and(|e| e.linear == linear) && !f.opts.dragging;
|
||||
let e = if again { pan_margin((screen.width(), screen.height()), m, PIXEL_BUDGET, 8192.0) } else { 0.0 };
|
||||
let room = over.map_or(screen.inflate(e, e), |o| screen.inflate(e, e).intersect(o));
|
||||
let r = whole.intersect(room.inflate(m, m));
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
(region(r, true, PIXEL_BUDGET)?, true)
|
||||
(region(r, true, PIXEL_BUDGET)?, Some(room))
|
||||
}
|
||||
};
|
||||
// During a drag, a larger shadow on a multithreaded context is filtered within the
|
||||
@@ -1185,7 +1218,10 @@ impl Renderer {
|
||||
// Silhouette (the object's painted alpha, and its colors under Darkness), offset by
|
||||
// the shadow distance.
|
||||
let mut off = f.offscreen_context(w, h);
|
||||
let crop = Frame { mt: false, view: Affine::scale(1.0 / scale) * Affine::translate((-x0, -y0)) * f.view, ..*f };
|
||||
let view = Affine::scale(1.0 / scale) * Affine::translate((-x0, -y0)) * f.view;
|
||||
// Art is culled against the raster's own area: members of a group outside the view cast their shadows in it.
|
||||
let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h)));
|
||||
let crop = Frame { mt: false, view, visible, ..*f };
|
||||
let before = self.stats.moved;
|
||||
self.inside_layer(|r| paint(r, &mut off, &shifted(&crop, dx, dy)));
|
||||
// A silhouette drawn over moved rasters makes a moved shadow.
|
||||
@@ -1234,7 +1270,7 @@ impl Renderer {
|
||||
let p = f.view * anchor;
|
||||
let node = Drawn::of(n, owner);
|
||||
let rel = (x0 - p.x, y0 - p.y);
|
||||
let view = cropped.then_some(in_view);
|
||||
let view = cropped.map(|room| ViewCrop::of(f.view, room));
|
||||
self.shadows.insert(key, ShadowEntry { node, linear, anchor, rel, image: image.clone(), scale, view, made, inputs, moved, stamp });
|
||||
self.trim_fx_rasters(FX_RASTER_BUDGET);
|
||||
(image, x0, y0, scale, moved, cropped)
|
||||
@@ -1345,7 +1381,10 @@ impl Renderer {
|
||||
let anchor = reach.origin();
|
||||
let p = f.view * anchor;
|
||||
let mut off = f.offscreen_context(w, h);
|
||||
let crop = Frame { mt: false, view: Affine::scale(1.0 / scale) * Affine::translate((-(p.x + rel.0), -(p.y + rel.1))) * f.view, ..*f };
|
||||
let view = Affine::scale(1.0 / scale) * Affine::translate((-(p.x + rel.0), -(p.y + rel.1))) * f.view;
|
||||
// Culled against the raster's area, as `shadow_raster` draws the silhouette.
|
||||
let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h)));
|
||||
let crop = Frame { mt: false, view, visible, ..*f };
|
||||
self.inside_layer(|r| paint(r, &mut off, &shifted(&crop, dx, dy)));
|
||||
off.flush();
|
||||
let mut pm = vello_cpu::Pixmap::new(w, h);
|
||||
@@ -1684,7 +1723,8 @@ impl Renderer {
|
||||
for (i, fx) in rfx.iter().enumerate().filter(|(_, x)| x.is_below()) {
|
||||
// A raster cropped to the view covers what the shadows and glows stacked over it read.
|
||||
let around: f64 = rfx.iter().skip(i + 1).filter(|x| x.is_below()).map(looks).sum();
|
||||
let over_cropped = made.iter().any(|(_, s)| s.as_ref().is_some_and(|s| s.cropped));
|
||||
// The rect that the cropped rasters of the earlier ones (drawn into this one's silhouette) were all made for.
|
||||
let over = made.iter().filter_map(|(_, s)| s.as_ref()?.cropped).reduce(|a, b| a.intersect(b));
|
||||
let shadow = {
|
||||
let earlier = &made;
|
||||
let view = f.view;
|
||||
@@ -1701,7 +1741,7 @@ impl Renderer {
|
||||
}
|
||||
paint(r, c, fr);
|
||||
};
|
||||
let view = (screen, around, over_cropped);
|
||||
let view = (screen, around, over);
|
||||
content.cache.and_then(|slot| self.shadow_raster(f, content.node, slot + i, fx, stacked, owner.as_ref(), view, &mut art))
|
||||
};
|
||||
stacked = match fx {
|
||||
@@ -1773,9 +1813,11 @@ impl Renderer {
|
||||
/// resolution. A whole raster at full resolution is cached while the object, the
|
||||
/// zoom and what the content reads ([`Inputs`]) stay the same (panning only moves it), and
|
||||
/// while interacting after the content only moved ([`Self::move_pixel_content`]). A cropped or
|
||||
/// lower-resolution raster is cached while the object, the view (its pan included) and what the
|
||||
/// content reads stay the same ([`PixelEntry::view`]); a lower-resolution one is kept resampled to
|
||||
/// the view's pixels ([`Self::resampled`]).
|
||||
/// lower-resolution raster is cached while the object, the zoom and what the content reads stay
|
||||
/// the same and a pan keeps the view inside the rect it was made for ([`PixelEntry::view`]): the
|
||||
/// view, and for a raster cropped to it that is made again at the same zoom and rotation, outside
|
||||
/// a drag and for content without a [`Kept`] image, the view with [`pan_margin`] around it. A
|
||||
/// lower-resolution one is kept resampled to the view's pixels ([`Self::resampled`]).
|
||||
/// While dragging, content without such a raster to draw renders within [`DRAG_PIXEL_BUDGET`]
|
||||
/// pixels and is not cached.
|
||||
fn pixel_content(
|
||||
@@ -1815,8 +1857,20 @@ impl Renderer {
|
||||
let fits = full.area() <= PIXEL_BUDGET;
|
||||
// Device pixels from a pixel to the content deciding it (`None`: anywhere).
|
||||
let margin = chain.iter().try_fold(2.0, |m, fx| looks_around(fx).map(|d| m + d / f.px));
|
||||
let linear = linear_key(f.view);
|
||||
let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink));
|
||||
// Made again at this zoom and rotation (after a pan), a raster cropped to the view covers a
|
||||
// margin around the view too, so that later pans within the margin draw it.
|
||||
let again = key.and_then(|key| self.pixel_fx.get(&key)).is_some_and(|e| e.linear == linear) && content.kept.is_none() && !f.opts.dragging;
|
||||
let room = match margin {
|
||||
Some(m) if !fits && again => {
|
||||
let e = pan_margin((screen.width(), screen.height()), m, PIXEL_BUDGET, f64::from(crate::MAX_RASTER_SIDE));
|
||||
screen.inflate(e, e)
|
||||
}
|
||||
_ => screen,
|
||||
};
|
||||
let region = match margin {
|
||||
Some(m) if !fits => full.intersect(screen.inflate(m, m)),
|
||||
Some(m) if !fits => full.intersect(room.inflate(m, m)),
|
||||
_ => full,
|
||||
};
|
||||
let (x0, y0) = (region.x0.floor(), region.y0.floor());
|
||||
@@ -1825,11 +1879,10 @@ impl Renderer {
|
||||
let side = f64::from(crate::MAX_RASTER_SIDE);
|
||||
let k = (PIXEL_BUDGET / (rw * rh)).sqrt().min(side / rw).min(side / rh).min(1.0);
|
||||
let (w, h) = ((rw * k).ceil().clamp(1.0, side), (rh * k).ceil().clamp(1.0, side));
|
||||
// The cached raster: of the whole content at full size at this zoom, else of this view.
|
||||
let linear = linear_key(f.view);
|
||||
// The cached raster: of the whole content at full size at this zoom, else of this view (and
|
||||
// the margin around it).
|
||||
let whole = fits && k >= 1.0;
|
||||
let in_view = (!whole).then(|| ViewCrop::of(f.view, screen));
|
||||
let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink));
|
||||
let in_view = (!whole).then(|| ViewCrop::of(f.view, room));
|
||||
let stamp = self.stamp;
|
||||
let channels = match f.ink {
|
||||
Ink::Cmy => effects::pixel::Channels::CmyPlane,
|
||||
@@ -2131,6 +2184,7 @@ impl Renderer {
|
||||
let o = f.opts;
|
||||
(doc.images, self.dim_images.map(f32::to_bits), o.smooth_images, o.image_mips, o.trace_views, o.progressive_placed).hash(&mut h);
|
||||
o.trace_source.as_deref().hash(&mut h);
|
||||
o.mark_undecoded_images.hash(&mut h);
|
||||
}
|
||||
if reads.brushes {
|
||||
self.brushes.library_key(f.doc, self.stamp).hash(&mut h);
|
||||
@@ -2413,7 +2467,7 @@ mod tests {
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, filter_region_within};
|
||||
use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, filter_region_within, pan_margin};
|
||||
use crate::tests_fontchange::fonts_steady;
|
||||
use crate::{RenderOptions, Rendered, Renderer};
|
||||
|
||||
@@ -2458,6 +2512,21 @@ mod tests {
|
||||
assert_eq!(filter_region_within(small, (1600, 1000), 4.0, DRAG_PIXEL_BUDGET), filter_region(small, (1600, 1000), 4.0));
|
||||
}
|
||||
|
||||
/// The margin a raster cropped to the view is made again with keeps it within the pixel budget,
|
||||
/// a pixel of rounding on each edge included, and within the side limit; it is at most half the
|
||||
/// view's longer side, and 0 when the view and its spread alone fill the budget.
|
||||
#[test]
|
||||
fn the_margin_for_pans_stays_within_the_pixel_budget() {
|
||||
for ((w, h), m, want) in [((2560.0, 1440.0), 32.0, 441.0), ((640.0, 360.0), 32.0, 320.0), ((3840.0, 2160.0), 32.0, 0.0)] {
|
||||
let e = pan_margin((w, h), m, PIXEL_BUDGET, 8192.0);
|
||||
assert_eq!(e, want, "{w} × {h}");
|
||||
let (rw, rh) = (w + 2.0 * (m + e) + 2.0, h + 2.0 * (m + e) + 2.0);
|
||||
assert!(e == 0.0 || rw * rh <= PIXEL_BUDGET, "{w} × {h}: {rw} × {rh}");
|
||||
}
|
||||
assert_eq!(pan_margin((2000.0, 10.0), 0.0, 1e9, 3000.0), 498.0, "within the side limit");
|
||||
assert_eq!(pan_margin((2000.0, 10.0), f64::NAN, PIXEL_BUDGET, 8192.0), 0.0);
|
||||
}
|
||||
|
||||
fn doc_with(r: Rect, fill: Color, effects: Vec<(&str, serde_json::Value)>) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let id = d.alloc_id();
|
||||
|
||||
@@ -63,7 +63,13 @@ fn physical_memory() -> Option<u64> {
|
||||
fn physical_memory() -> Option<u64> {
|
||||
let (sysctl, name) = if cfg!(target_os = "macos") { ("/usr/sbin/sysctl", "hw.memsize") } else { ("/sbin/sysctl", "hw.physmem") };
|
||||
let out = std::process::Command::new(sysctl).args(["-n", name]).output().ok().filter(|o| o.status.success())?;
|
||||
String::from_utf8(out.stdout).ok()?.trim().parse().ok()
|
||||
sysctl_bytes(&out.stdout)
|
||||
}
|
||||
|
||||
/// The byte count `sysctl -n` prints for a memory size.
|
||||
#[cfg(any(target_os = "macos", target_os = "freebsd", test))]
|
||||
fn sysctl_bytes(out: &[u8]) -> Option<u64> {
|
||||
std::str::from_utf8(out).ok()?.trim().parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", windows, target_os = "macos", target_os = "freebsd", target_arch = "wasm32")))]
|
||||
@@ -114,6 +120,11 @@ pub(crate) struct ImageStore {
|
||||
tick: u64,
|
||||
/// [`BlobId`]s per blob byte buffer, by address (the `Weak` keeps it from being reused).
|
||||
ids: HashMap<usize, (Weak<Vec<u8>>, BlobId)>,
|
||||
/// The content keys of images whose pixels can't be decoded ([`Undecoded::Unreadable`]), so
|
||||
/// they aren't decoded again, each with whether [`newly_undecodable`] has counted it.
|
||||
///
|
||||
/// [`Undecoded::Unreadable`]: crate::paint::Undecoded::Unreadable
|
||||
undecodable: HashMap<Arc<str>, bool>,
|
||||
}
|
||||
|
||||
fn pixmap_bytes(pm: &Pixmap) -> usize {
|
||||
@@ -122,7 +133,21 @@ fn pixmap_bytes(pm: &Pixmap) -> usize {
|
||||
|
||||
impl ImageStore {
|
||||
pub(crate) fn new(budget: usize) -> Self {
|
||||
Self { entries: HashMap::new(), bytes: 0, budget, tick: 0, ids: HashMap::new() }
|
||||
Self { entries: HashMap::new(), bytes: 0, budget, tick: 0, ids: HashMap::new(), undecodable: HashMap::new() }
|
||||
}
|
||||
|
||||
/// Whether the image with content key `content` is known not to decode.
|
||||
pub(crate) fn is_undecodable(&self, content: &str) -> bool {
|
||||
self.undecodable.contains_key(content)
|
||||
}
|
||||
|
||||
/// Note that the image with content key `content` can't be decoded. Past 1024 such images the
|
||||
/// notes are dropped and those images are tried again.
|
||||
pub(crate) fn set_undecodable(&mut self, content: Arc<str>) {
|
||||
if self.undecodable.len() >= 1024 {
|
||||
self.undecodable.clear();
|
||||
}
|
||||
self.undecodable.entry(content).or_insert(false);
|
||||
}
|
||||
|
||||
/// The pixels of `key`, marked as just used.
|
||||
@@ -252,6 +277,27 @@ pub(crate) fn remember_size(blob: &ImageBlob, size: (u16, u16)) {
|
||||
store().remember_size(&blob.bytes, size);
|
||||
}
|
||||
|
||||
/// How many of `blobs` a renderer has found it can't decode (they draw nothing, or a crossed box
|
||||
/// with [`RenderOptions::mark_undecoded_images`](crate::RenderOptions::mark_undecoded_images)) that
|
||||
/// no earlier call counted: each such image is counted once in the process.
|
||||
pub fn newly_undecodable<'a>(blobs: impl IntoIterator<Item = &'a ImageBlob>) -> usize {
|
||||
let mut s = store();
|
||||
if s.undecodable.values().all(|counted| *counted) {
|
||||
return 0;
|
||||
}
|
||||
let mut n = 0;
|
||||
for blob in blobs {
|
||||
let Some(id) = s.known_id(&blob.bytes) else { continue };
|
||||
if let Some(counted) = s.undecodable.get_mut(&id.content)
|
||||
&& !*counted
|
||||
{
|
||||
*counted = true;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// `pm` at half the size (rounded up), each pixel the mean of the 2×2 it covers (the last row and
|
||||
/// column repeat on odd sizes).
|
||||
pub(crate) fn half(pm: &Pixmap) -> Pixmap {
|
||||
@@ -339,6 +385,13 @@ mod tests {
|
||||
assert_eq!(s.bytes(), 2 * 640 * 640 * 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sysctl_prints_the_memory_size_in_bytes() {
|
||||
assert_eq!(sysctl_bytes(b"17179869184\n"), Some(16 << 30));
|
||||
assert_eq!(sysctl_bytes(b""), None);
|
||||
assert_eq!(sysctl_bytes(b"unknown oid 'hw.memsize'\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_averages_and_rounds_up_odd_sizes() {
|
||||
let px = |v: u8| PremulRgba8 { r: v, g: v, b: v, a: 255 };
|
||||
|
||||
@@ -18,7 +18,7 @@ mod ink;
|
||||
mod live;
|
||||
mod lru;
|
||||
mod paint;
|
||||
pub use paint::decode_failures;
|
||||
pub use paint::{decode_failures, reduced_size};
|
||||
mod pattern;
|
||||
pub mod placed_document;
|
||||
pub mod proof;
|
||||
@@ -37,9 +37,9 @@ use ink::Ink;
|
||||
use lru::FrameCache;
|
||||
|
||||
pub use brush_fx::instance_art;
|
||||
pub use changed::{Changed, changed, view_pixels};
|
||||
pub use changed::{Changed, changed, placed_area, view_pixels};
|
||||
pub use effects::stroke::width_outline;
|
||||
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, set_image_cache_budget};
|
||||
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, newly_undecodable, set_image_cache_budget};
|
||||
pub use live::expand_live;
|
||||
pub use pattern::render_pattern_swatch;
|
||||
pub use vectorcraft_effects as effects;
|
||||
@@ -186,6 +186,9 @@ pub struct RenderOptions {
|
||||
/// (box-filtered from the full image, kept with the decoded images), so the full image needn't
|
||||
/// stay in memory or be sampled. Off, images always sample their full pixels (exports).
|
||||
pub image_mips: bool,
|
||||
/// Screen views: an image whose pixels can't be decoded draws as a light gray box crossed
|
||||
/// from corner to corner. Off, it draws nothing (exports, which report it instead).
|
||||
pub mark_undecoded_images: bool,
|
||||
/// Screen views while an interaction is in progress (a drag, a dialog's preview): an object
|
||||
/// whose content only moved since an earlier frame draws its cached drop shadows, outer glows
|
||||
/// and filtered content from the rasters made then, at the nearest whole pixel, without
|
||||
@@ -281,6 +284,7 @@ impl Default for RenderOptions {
|
||||
precise: false,
|
||||
supersample: false,
|
||||
image_mips: false,
|
||||
mark_undecoded_images: false,
|
||||
interacting: false,
|
||||
dragging: false,
|
||||
rich_black: false,
|
||||
@@ -539,6 +543,9 @@ pub struct Renderer {
|
||||
fx_arts: FrameCache<usize, FxArtEntry>,
|
||||
/// Symbol art as instances and inline graphics draw it (see [`Self::placed_art`]).
|
||||
placed_arts: FrameCache<PlacedKey, PlacedEntry>,
|
||||
/// The bitmap clock of [`placed_document`] when this frame first drew a placed document from
|
||||
/// a bitmap: the bitmaps drawn since then are not dropped to make room for those it asks for.
|
||||
placed_frame: Option<u64>,
|
||||
/// Layers open around the drawing point in the current context: a non-isolated group can copy
|
||||
/// its backdrop only when there are none (see [`Self::group`]).
|
||||
nested: u32,
|
||||
@@ -688,6 +695,7 @@ impl Renderer {
|
||||
shape_of: 0,
|
||||
fx_arts: FrameCache::new(lru::FX_ART_BUDGET, 256),
|
||||
placed_arts: FrameCache::new(lru::PLACED_ART_BUDGET, 256),
|
||||
placed_frame: None,
|
||||
nested: 0,
|
||||
backdrop: None,
|
||||
blends: PtrMap::default(),
|
||||
@@ -788,6 +796,7 @@ impl Renderer {
|
||||
(self.offscreen_live, self.offscreen_budget) = (0, 0);
|
||||
self.symbol_nodes = 0;
|
||||
self.twice_drawn = 0;
|
||||
self.placed_frame = None;
|
||||
}
|
||||
|
||||
/// End a frame: drop cache entries not used for a few frames (every render, thumbnails too,
|
||||
@@ -2151,6 +2160,8 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if f.opts.mark_undecoded_images && (!outline || f.doc.setup.outline_images) {
|
||||
self.draw_undecoded_mark(ctx, f, im, area);
|
||||
}
|
||||
if outline {
|
||||
let mut p = rect.to_path(0.1);
|
||||
@@ -2159,6 +2170,32 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the mark of image `im` whose pixels can't be had ([`RenderOptions::mark_undecoded_images`]):
|
||||
/// a light gray box over its frame, crossed from corner to corner with a gray hairline, and
|
||||
/// with `area` (see [`Self::draw_image_in`]) only inside that region.
|
||||
fn draw_undecoded_mark(&mut self, ctx: &mut RenderContext, f: &Frame, im: &vectorcraft_doc::ImageObject, area: Option<&(BezPath, FillRule)>) {
|
||||
let (w, h) = (im.width as f64, im.height as f64);
|
||||
if let Some((bp, rule)) = area {
|
||||
ctx.set_transform(f.view);
|
||||
ctx.set_fill_rule(fill_rule(*rule));
|
||||
ctx.push_clip_layer(bp);
|
||||
}
|
||||
let rect = Rect::new(0.0, 0.0, w, h);
|
||||
ctx.set_transform(f.view * im.xf);
|
||||
ctx.set_paint(f.ink.fixed([128, 128, 128, 40]));
|
||||
ctx.fill_rect(&rect);
|
||||
let mut cross = rect.to_path(0.1);
|
||||
cross.move_to((0.0, 0.0));
|
||||
cross.line_to((w, h));
|
||||
cross.move_to((w, 0.0));
|
||||
cross.line_to((0.0, h));
|
||||
cross.apply_affine(im.xf);
|
||||
self.hairline(ctx, f, &cross, [128, 128, 128, 255]);
|
||||
if area.is_some() {
|
||||
ctx.pop_layer();
|
||||
}
|
||||
}
|
||||
|
||||
/// Name image `key` recoloured by `map` (its hash `hash`) as `derived` (the key the adjusted
|
||||
/// art's image takes): drawing `derived` draws the recoloured pixels, made when first drawn and
|
||||
/// kept with the decoded images. Names past a limit drop the art made with them too, so it is
|
||||
@@ -2276,16 +2313,30 @@ fn blob_key(blob: &vectorcraft_doc::ImageBlob) -> (images::ImageKey, Option<Arc<
|
||||
}
|
||||
|
||||
/// The decoded pixels of `blob` (a CMYK image's inks shown through the working CMYK profile, again
|
||||
/// when the colour settings change), from the shared store, and their key there.
|
||||
/// when the colour settings change), from the shared store, and their key there. An image whose
|
||||
/// pixels can't be decoded is noted in the store and not decoded again; each request for it counts
|
||||
/// a failure in [`decode_failures`].
|
||||
fn blob_pixmap(blob: &vectorcraft_doc::ImageBlob, touch: bool) -> Option<(images::ImageKey, Arc<Pixmap>)> {
|
||||
let (key, lut, size) = blob_key(blob);
|
||||
let pm = match lookup(&key, touch) {
|
||||
Some(pm) => pm,
|
||||
None => {
|
||||
if images::store().is_undecodable(&key.content) {
|
||||
paint::add_decode_failures(1);
|
||||
return None;
|
||||
}
|
||||
// Decoded outside the lock: other renderers carry on meanwhile.
|
||||
let pm = match lut.and_then(|lut| ink::cmyk_pixmap(blob, &lut)) {
|
||||
Some(pm) => pm,
|
||||
None => paint::decode_pixmap(&blob.bytes)?,
|
||||
None => match paint::decode_pixmap_or_why(&blob.bytes) {
|
||||
Ok(pm) => pm,
|
||||
Err(why) => {
|
||||
if why == paint::Undecoded::Unreadable {
|
||||
images::store().set_undecodable(key.content.clone());
|
||||
}
|
||||
return None;
|
||||
}
|
||||
},
|
||||
};
|
||||
images::store().insert(key.clone(), Arc::new(pm))
|
||||
}
|
||||
|
||||
+342
-24
@@ -73,6 +73,38 @@ thread_local! {
|
||||
static DECODE_FAILURES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The decode allowance of one image on this thread in place of [`MAX_DECODE_ALLOC`], so a
|
||||
/// test can draw an image past it without decoding gigabytes.
|
||||
pub(crate) static TEST_ALLOWANCE: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// The bytes [`fits_beside_pinned`] finds room for on this thread, in place of what the images
|
||||
/// paints hold in the shared store leave.
|
||||
pub(crate) static TEST_ROOM: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// The images [`decode_or_reduction`] has tried to decode on this thread.
|
||||
pub(crate) static DECODE_ATTEMPTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The most memory decoding one image may take on this thread: [`MAX_DECODE_ALLOC`].
|
||||
fn allowance() -> u64 {
|
||||
#[cfg(test)]
|
||||
if let Some(a) = TEST_ALLOWANCE.with(std::cell::Cell::get) {
|
||||
return a;
|
||||
}
|
||||
MAX_DECODE_ALLOC
|
||||
}
|
||||
|
||||
/// Why an image has no pixels to draw ([`decode_pixmap_or_why`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Undecoded {
|
||||
/// Its pixels can't be read, at their own size or at [`reduced_size`]: decoding them again
|
||||
/// fails again.
|
||||
Unreadable,
|
||||
/// The images being painted leave no room for it within twice [`MAX_DECODE_ALLOC`]: it may
|
||||
/// be decoded once they are done.
|
||||
NoRoom,
|
||||
}
|
||||
|
||||
/// How many images have failed to decode on this thread so far: an export compares the count
|
||||
/// before and after it draws to say it left images out. Images that other threads (another export,
|
||||
/// the canvas, thumbnails) fail to decode meanwhile are not counted.
|
||||
@@ -80,36 +112,262 @@ pub fn decode_failures() -> u64 {
|
||||
DECODE_FAILURES.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// `bytes` decoded within [`MAX_DECODE_ALLOC`] ([`decode_within_allowance`]); a failure is counted
|
||||
/// in [`decode_failures`].
|
||||
fn decode(bytes: &[u8]) -> Option<image::DynamicImage> {
|
||||
let img = decode_within_allowance(bytes).ok();
|
||||
if img.is_none() {
|
||||
add_decode_failures(1);
|
||||
}
|
||||
img
|
||||
/// [`decode_in_room`]'s image or error.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn decode_within_allowance(bytes: &[u8]) -> image::ImageResult<image::DynamicImage> {
|
||||
decode_in_room(bytes).map_err(|(e, _)| e)
|
||||
}
|
||||
|
||||
/// `bytes` decoded within [`MAX_DECODE_ALLOC`], counted as RGBA: the image's size is read from its
|
||||
/// header first, and an image of more than that as RGBA gets a limit error before anything is
|
||||
/// decoded (#1717).
|
||||
pub(crate) fn decode_within_allowance(bytes: &[u8]) -> image::ImageResult<image::DynamicImage> {
|
||||
/// decoded (#1717). A failure comes with why the image gave no pixels ([`room_for`]).
|
||||
fn decode_in_room(bytes: &[u8]) -> Result<image::DynamicImage, (image::ImageError, Undecoded)> {
|
||||
let allowance = allowance();
|
||||
let unreadable = |e| (e, Undecoded::Unreadable);
|
||||
let reader = || -> image::ImageResult<_> {
|
||||
let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(MAX_DECODE_ALLOC);
|
||||
limits.max_alloc = Some(allowance);
|
||||
r.limits(limits);
|
||||
Ok(r)
|
||||
};
|
||||
let (w, h) = reader()?.into_dimensions()?;
|
||||
let (w, h) = reader().and_then(|r| r.into_dimensions()).map_err(unreadable)?;
|
||||
let bytes = (u64::from(w) * u64::from(h)).saturating_mul(4);
|
||||
// The images paints hold can't be evicted from the cache, so a document of many images held
|
||||
// them all at once: a new one is decoded only while those and it fit twice the allowance.
|
||||
let pinned = crate::images::store().pinned_bytes() as u64;
|
||||
if bytes > MAX_DECODE_ALLOC || bytes.saturating_add(pinned) > 2 * MAX_DECODE_ALLOC {
|
||||
return Err(image::ImageError::Limits(image::error::LimitError::from_kind(image::error::LimitErrorKind::InsufficientMemory)));
|
||||
if let Err(why) = room_for(bytes, pinned) {
|
||||
return Err((image::ImageError::Limits(image::error::LimitError::from_kind(image::error::LimitErrorKind::InsufficientMemory)), why));
|
||||
}
|
||||
reader().and_then(|r| r.decode()).map_err(unreadable)
|
||||
}
|
||||
|
||||
/// Whether an image of `rgba` bytes may be decoded while the images being painted hold `pinned`
|
||||
/// bytes: within the allowance itself, and within twice [`MAX_DECODE_ALLOC`] with them. An image
|
||||
/// over the allowance may still be decoded at [`reduced_size`].
|
||||
fn room_for(rgba: u64, pinned: u64) -> Result<(), Undecoded> {
|
||||
if rgba > allowance() {
|
||||
Err(Undecoded::Unreadable)
|
||||
} else if rgba.saturating_add(pinned) > 2 * MAX_DECODE_ALLOC {
|
||||
Err(Undecoded::NoRoom)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `bytes` of decoded pixels fit beside the images paints hold, which can't be evicted from
|
||||
/// the cache: a new image is decoded only while those and it fit twice [`MAX_DECODE_ALLOC`].
|
||||
fn fits_beside_pinned(bytes: u64) -> bool {
|
||||
#[cfg(test)]
|
||||
if let Some(room) = TEST_ROOM.with(std::cell::Cell::get) {
|
||||
return bytes <= room;
|
||||
}
|
||||
let pinned = crate::images::store().pinned_bytes() as u64;
|
||||
bytes.saturating_add(pinned) <= 2 * MAX_DECODE_ALLOC
|
||||
}
|
||||
|
||||
/// The size at which [`decode_pixmap_or_why`] decodes encoded image `bytes` that take more than
|
||||
/// [`MAX_DECODE_ALLOC`] as RGBA, or whose decoded samples do (16 bits a sample): the largest that
|
||||
/// fits it as RGBA, keeping its proportions, at most the image's own size, with sides of at most
|
||||
/// `u16::MAX` pixels. `None` for an image within the allowance and for one that isn't decoded at
|
||||
/// all: an image that isn't a PNG, JPEG, GIF or WebP; an image of more pixels than the allowance
|
||||
/// has bytes (2,147,483,648 pixels, or 536,870,912 in the web app; 46,341 × 46,341 is more); and an
|
||||
/// image whose decoded samples take more than the allowance, unless it is a PNG that isn't
|
||||
/// interlaced and is at most the allowance divided by [`ROW_SCRATCH`] pixels wide (read a row at a
|
||||
/// time).
|
||||
pub fn reduced_size(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
reduction(bytes, allowance()).map(|r| r.to)
|
||||
}
|
||||
|
||||
/// How [`decode_pixmap_or_why`] reads an image past the decode allowance ([`reduced_size`]).
|
||||
struct Reduction {
|
||||
/// The image's size in pixels.
|
||||
size: (u32, u32),
|
||||
/// The size it is decoded at.
|
||||
to: (u32, u32),
|
||||
/// Read a row at a time (a PNG that isn't interlaced) rather than decoded whole first.
|
||||
rows: bool,
|
||||
/// The bytes reading the image takes besides the result: the PNG reader's row buffers, or the
|
||||
/// image decoded whole and a band of its rows as RGBA.
|
||||
scratch: u64,
|
||||
}
|
||||
|
||||
/// [`reduced_size`]'s reading of `bytes` within `allowance`.
|
||||
fn reduction(bytes: &[u8], allowance: u64) -> Option<Reduction> {
|
||||
use image::ImageDecoder as _;
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let format = reader.format()?;
|
||||
if !matches!(format, image::ImageFormat::Png | image::ImageFormat::Jpeg | image::ImageFormat::Gif | image::ImageFormat::WebP) {
|
||||
return None;
|
||||
}
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(allowance);
|
||||
reader.limits(limits);
|
||||
let d = reader.into_decoder().ok()?;
|
||||
let (w, h) = d.dimensions();
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
// An image of more pixels than the allowance has bytes (four times what it holds as RGBA) is
|
||||
// not read.
|
||||
if pixels == 0 || pixels > allowance || (pixels.saturating_mul(4) <= allowance && d.total_bytes() <= allowance) {
|
||||
return None;
|
||||
}
|
||||
let to = fitted_dims(w, h, allowance)?;
|
||||
// The PNG reader's row buffers take at most `ROW_SCRATCH` bytes a column, also within the allowance.
|
||||
let rows = format == image::ImageFormat::Png
|
||||
&& u64::from(w).saturating_mul(ROW_SCRATCH) <= allowance
|
||||
&& png_reader(bytes).is_some_and(|r| !r.info().interlaced);
|
||||
let scratch = if rows {
|
||||
u64::from(w) * ROW_SCRATCH
|
||||
} else {
|
||||
let band = u64::from(BAND) * u64::from(w) * (u64::from(d.color_type().bytes_per_pixel()) + 4);
|
||||
d.total_bytes().saturating_add(band)
|
||||
};
|
||||
(rows || d.total_bytes() <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch })
|
||||
}
|
||||
|
||||
/// How many rows of an image decoded whole [`reduced_pixmap`] converts to RGBA at a time.
|
||||
const BAND: u32 = 16;
|
||||
|
||||
/// The most memory a column of a PNG read a row at a time takes in the reader's row buffers: the
|
||||
/// row as stored (up to 8 bytes a pixel and a filter byte), the row before it, and the row given
|
||||
/// out (up to 4 bytes a pixel).
|
||||
const ROW_SCRATCH: u64 = 32;
|
||||
|
||||
/// The largest size of at most `w`×`h` pixels, keeping their proportions, whose pixels take at most
|
||||
/// `allowance` bytes as RGBA, with sides of at most `u16::MAX` pixels.
|
||||
fn fitted_dims(w: u32, h: u32, allowance: u64) -> Option<(u32, u32)> {
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
let s = ((allowance / 4) as f64 / pixels as f64).sqrt().min(u16::MAX as f64 / w.max(h) as f64).min(1.0);
|
||||
let side = |n: u32| ((n as f64 * s).floor() as u32).clamp(1, u16::MAX as u32);
|
||||
let (mut nw, mut nh) = (side(w), side(h));
|
||||
// Rounding can leave the product a pixel over: take a pixel off the longer side.
|
||||
while u64::from(nw) * u64::from(nh) * 4 > allowance && (nw > 1 || nh > 1) {
|
||||
if nw >= nh { nw -= 1 } else { nh -= 1 }
|
||||
}
|
||||
(u64::from(nw) * u64::from(nh) * 4 <= allowance).then_some((nw, nh))
|
||||
}
|
||||
|
||||
/// A PNG reader of `bytes` that gives 8-bit gray, gray with alpha, RGB or RGBA rows, with its
|
||||
/// header and the chunks before the pixels read.
|
||||
fn png_reader(bytes: &[u8]) -> Option<png::Reader<std::io::Cursor<&[u8]>>> {
|
||||
let mut d = png::Decoder::new(std::io::Cursor::new(bytes));
|
||||
d.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
d.read_info().ok()
|
||||
}
|
||||
|
||||
/// `bytes` decoded at the size [`reduction`] gives. Each pixel of the result is the mean of the
|
||||
/// image's pixels it covers. [`Undecoded::Unreadable`] when they can't be read, and
|
||||
/// [`Undecoded::NoRoom`] when the result and what reading takes ([`Reduction::scratch`]) don't fit
|
||||
/// beside the images paints hold.
|
||||
fn reduced_pixmap(bytes: &[u8], r: &Reduction) -> Result<vello_cpu::Pixmap, Undecoded> {
|
||||
let (tw, th) = r.to;
|
||||
if !fits_beside_pinned((u64::from(tw) * u64::from(th) * 4).saturating_add(r.scratch)) {
|
||||
return Err(Undecoded::NoRoom);
|
||||
}
|
||||
shrunk(bytes, r).ok_or(Undecoded::Unreadable)
|
||||
}
|
||||
|
||||
/// `bytes` read and shrunk as [`reduced_pixmap`] says.
|
||||
fn shrunk(bytes: &[u8], r: &Reduction) -> Option<vello_cpu::Pixmap> {
|
||||
let mut shrink = Shrink::new(r.size, r.to);
|
||||
if r.rows {
|
||||
let mut reader = png_reader(bytes)?;
|
||||
let (color, _) = reader.output_color_type();
|
||||
while let Some(row) = reader.next_row().ok()? {
|
||||
let data = row.data();
|
||||
match color {
|
||||
png::ColorType::Grayscale => shrink.row(data.iter().map(|&g| [g, g, g, 255])),
|
||||
png::ColorType::GrayscaleAlpha => shrink.row(data.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])),
|
||||
png::ColorType::Rgb => shrink.row(data.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])),
|
||||
png::ColorType::Rgba => shrink.row(data.as_chunks::<4>().0.iter().copied()),
|
||||
png::ColorType::Indexed => return None,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(allowance());
|
||||
reader.limits(limits);
|
||||
let img = reader.decode().ok()?;
|
||||
let (w, h) = (img.width(), img.height());
|
||||
for y in (0..h).step_by(BAND as usize) {
|
||||
let band = img.crop_imm(0, y, w, BAND.min(h - y)).to_rgba8();
|
||||
band.as_raw().as_chunks::<4>().0.chunks_exact(w as usize).for_each(|row| shrink.row(row.iter().copied()));
|
||||
}
|
||||
}
|
||||
shrink.finish()
|
||||
}
|
||||
|
||||
/// An image shrunk as its RGBA rows are given ([`Shrink::row`]): each pixel of the result is the
|
||||
/// mean of the image's pixels it covers, premultiplied.
|
||||
struct Shrink {
|
||||
/// The image's size.
|
||||
size: (u32, u32),
|
||||
/// The result's size.
|
||||
to: (u32, u32),
|
||||
/// The sums of the result row being made, a pixel each: red, green and blue times alpha, and
|
||||
/// alpha.
|
||||
sums: Vec<[u64; 4]>,
|
||||
/// How many of the image's pixels each pixel of that row has.
|
||||
counts: Vec<u64>,
|
||||
/// The result row being made, and the next row of the image.
|
||||
at: (u32, u32),
|
||||
/// The finished rows.
|
||||
out: Vec<vello_cpu::color::PremulRgba8>,
|
||||
}
|
||||
|
||||
impl Shrink {
|
||||
fn new(size: (u32, u32), to: (u32, u32)) -> Self {
|
||||
let n = to.0 as usize;
|
||||
Self { size, to, sums: vec![[0; 4]; n], counts: vec![0; n], at: (0, 0), out: Vec::with_capacity(n * to.1 as usize) }
|
||||
}
|
||||
|
||||
/// Add the image's next row of RGBA pixels (pixels past its width are left out).
|
||||
fn row(&mut self, rgba: impl IntoIterator<Item = [u8; 4]>) {
|
||||
if self.at.1 >= self.size.1 {
|
||||
return;
|
||||
}
|
||||
let ty = (u64::from(self.at.1) * u64::from(self.to.1) / u64::from(self.size.1)) as u32;
|
||||
if ty != self.at.0 {
|
||||
self.flush();
|
||||
self.at.0 = ty;
|
||||
}
|
||||
let (w, tw) = (u64::from(self.size.0), u64::from(self.to.0));
|
||||
for (x, p) in (0..w).zip(rgba) {
|
||||
// `tx` is the result column that the image's column `x` falls in.
|
||||
let tx = (x * tw / w) as usize;
|
||||
let a = u64::from(p[3]);
|
||||
if let Some(s) = self.sums.get_mut(tx) {
|
||||
s[0] += u64::from(p[0]) * a;
|
||||
s[1] += u64::from(p[1]) * a;
|
||||
s[2] += u64::from(p[2]) * a;
|
||||
s[3] += a;
|
||||
}
|
||||
if let Some(c) = self.counts.get_mut(tx) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
self.at.1 += 1;
|
||||
}
|
||||
|
||||
/// Finish the result row being made.
|
||||
fn flush(&mut self) {
|
||||
for (s, n) in self.sums.iter_mut().zip(&mut self.counts) {
|
||||
let k = (*n).max(1);
|
||||
let mean = |v: u64, d: u64| ((v + d / 2) / d).min(255) as u8;
|
||||
self.out.push(vello_cpu::color::PremulRgba8 { r: mean(s[0], 255 * k), g: mean(s[1], 255 * k), b: mean(s[2], 255 * k), a: mean(s[3], k) });
|
||||
*s = [0; 4];
|
||||
*n = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The shrunk image once every row of the image was given.
|
||||
fn finish(mut self) -> Option<vello_cpu::Pixmap> {
|
||||
if self.at.1 < self.size.1 {
|
||||
return None;
|
||||
}
|
||||
self.flush();
|
||||
let (w, h) = (u16::try_from(self.to.0).ok()?, u16::try_from(self.to.1).ok()?);
|
||||
(self.out.len() == w as usize * h as usize).then(|| vello_cpu::Pixmap::from_parts(self.out, w, h))
|
||||
}
|
||||
reader()?.decode()
|
||||
}
|
||||
|
||||
/// `img` shrunk, keeping its proportions, to fit a pixmap's sides (at most `u16::MAX` pixels).
|
||||
@@ -124,14 +382,59 @@ fn fit_pixmap(img: image::DynamicImage) -> image::DynamicImage {
|
||||
img.resize_exact(nw, nh, image::imageops::FilterType::Triangle)
|
||||
}
|
||||
|
||||
/// Decode encoded image bytes into a premultiplied pixmap (shrunk to fit a pixmap's sides).
|
||||
/// [`decode_pixmap_or_why`]'s pixels.
|
||||
#[cfg(test)]
|
||||
pub fn decode_pixmap(bytes: &[u8]) -> Option<vello_cpu::Pixmap> {
|
||||
pixmap_of(fit_pixmap(decode(bytes)?).to_rgba8())
|
||||
decode_pixmap_or_why(bytes).ok()
|
||||
}
|
||||
|
||||
/// [`decode_pixmap`] shrunk to `w`×`h` pixels when the image is larger (never enlarged).
|
||||
/// Decode encoded image bytes into a premultiplied pixmap (shrunk to fit a pixmap's sides), or say
|
||||
/// why there are no pixels. An image that takes more than the allowance as RGBA is decoded at
|
||||
/// [`reduced_size`] when it has one; a failure is counted in [`decode_failures`].
|
||||
pub(crate) fn decode_pixmap_or_why(bytes: &[u8]) -> Result<vello_cpu::Pixmap, Undecoded> {
|
||||
counted(match decode_or_reduction(bytes) {
|
||||
Ok(img) => pixmap_of(fit_pixmap(img).to_rgba8()).ok_or(Undecoded::Unreadable),
|
||||
Err(r) => r.and_then(|r| reduced_pixmap(bytes, &r)),
|
||||
})
|
||||
}
|
||||
|
||||
/// `bytes` decoded within the allowance ([`decode_in_room`]), or, when it refuses them for their
|
||||
/// size, how [`reduced_pixmap`] reads them past it; otherwise why there is no image.
|
||||
fn decode_or_reduction(bytes: &[u8]) -> Result<image::DynamicImage, Result<Reduction, Undecoded>> {
|
||||
#[cfg(test)]
|
||||
DECODE_ATTEMPTS.with(|n| n.set(n.get() + 1));
|
||||
match decode_in_room(bytes) {
|
||||
Ok(img) => Ok(img),
|
||||
Err((image::ImageError::Limits(_), Undecoded::Unreadable)) => Err(reduction(bytes, allowance()).ok_or(Undecoded::Unreadable)),
|
||||
Err((_, why)) => Err(Err(why)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `pm`, with a failure counted in [`decode_failures`] when there is none.
|
||||
fn counted(pm: Result<vello_cpu::Pixmap, Undecoded>) -> Result<vello_cpu::Pixmap, Undecoded> {
|
||||
if pm.is_err() {
|
||||
add_decode_failures(1);
|
||||
}
|
||||
pm
|
||||
}
|
||||
|
||||
/// [`decode_pixmap_or_why`] shrunk to `w`×`h` pixels when the image is larger (never enlarged). An
|
||||
/// image past the decode allowance is decoded straight at `w`×`h` when that is no larger on either
|
||||
/// side and fits the allowance, otherwise at [`reduced_size`].
|
||||
pub fn decode_pixmap_fit(bytes: &[u8], w: u16, h: u16) -> Option<vello_cpu::Pixmap> {
|
||||
let img = decode(bytes)?;
|
||||
let img = match decode_or_reduction(bytes) {
|
||||
Ok(img) => img,
|
||||
Err(r) => {
|
||||
return counted(r.and_then(|mut r| {
|
||||
let fit = (u32::from(w).max(1), u32::from(h).max(1));
|
||||
if fit.0 <= r.to.0 && fit.1 <= r.to.1 {
|
||||
r.to = fit;
|
||||
}
|
||||
reduced_pixmap(bytes, &r)
|
||||
}))
|
||||
.ok();
|
||||
}
|
||||
};
|
||||
let img = if img.width() > w as u32 || img.height() > h as u32 {
|
||||
img.resize_exact(w as u32, h as u32, image::imageops::FilterType::Triangle)
|
||||
} else {
|
||||
@@ -140,9 +443,9 @@ pub fn decode_pixmap_fit(bytes: &[u8], w: u16, h: u16) -> Option<vello_cpu::Pixm
|
||||
pixmap_of(img.to_rgba8())
|
||||
}
|
||||
|
||||
/// Count `n` images that couldn't be decoded on this thread ([`decode_failures`]). [`decode`]
|
||||
/// counts each failure, and a raster kept in a cache counts the failures it was drawn with again
|
||||
/// each time it is drawn.
|
||||
/// Count `n` images that couldn't be decoded on this thread ([`decode_failures`]).
|
||||
/// [`decode_pixmap_or_why`] and [`decode_pixmap_fit`] count each failure, and a raster kept in a cache
|
||||
/// counts the failures it was drawn with again each time it is drawn.
|
||||
pub(crate) fn add_decode_failures(n: u64) {
|
||||
DECODE_FAILURES.with(|c| c.set(c.get() + n));
|
||||
}
|
||||
@@ -163,3 +466,18 @@ fn pixmap_of(img: image::RgbaImage) -> Option<vello_cpu::Pixmap> {
|
||||
.collect();
|
||||
Some(vello_cpu::Pixmap::from_parts(data, w as u16, h as u16))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An image over the allowance as RGBA never fits, so it is noted as undecodable; one that only
|
||||
/// the images being painted leave no room for is not, and is tried again later.
|
||||
#[test]
|
||||
fn only_the_room_painted_images_take_is_tried_again() {
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC + 1, 0), Err(Undecoded::Unreadable));
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC + 1, 2 * MAX_DECODE_ALLOC), Err(Undecoded::Unreadable));
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC + 1), Err(Undecoded::NoRoom));
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC), Ok(()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,12 @@
|
||||
//! it shows is cached as a bitmap per file and zoom step (a power of two, in device pixels per
|
||||
//! point), shared by every object showing that file. A bitmap not made yet is made on a
|
||||
//! background worker while the frame shows another step's bitmap, or a light placeholder;
|
||||
//! [`generation`] changes when one is ready and [`busy`] says whether any is coming, so the screen
|
||||
//! can draw again. Past [`MAX_SIDE`] pixels, and in outline, proofing and ink frames, it is drawn
|
||||
//! exactly.
|
||||
//! [`generation`] changes when one is ready, [`made_between`] says for which files, and [`busy`]
|
||||
//! says whether any is coming, so the screen can draw again where those files show
|
||||
//! ([`crate::placed_area`]). Bitmaps drawn since a frame began are not dropped to make room for
|
||||
//! the ones it asks for, up to [`MAX_BYTES`], and a bitmap that can't be made is not asked for
|
||||
//! again. Past [`MAX_SIDE`] pixels, past [`MAX_BYTES`], and in outline, proofing and ink frames,
|
||||
//! it is drawn exactly.
|
||||
//!
|
||||
//! A document opened with only its placed documents' previews ([`ImageBlob::is_proxy`]) shows them
|
||||
//! up to their resolution; past it the file is read again in the background
|
||||
@@ -19,7 +22,7 @@
|
||||
//! same way, up to [`MAX_DEPTH`] deep; deeper ones show their previews.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
@@ -33,8 +36,12 @@ use crate::{Frame, Renderer};
|
||||
|
||||
/// The longest side of a cached bitmap (pixels); larger steps draw exactly.
|
||||
pub const MAX_SIDE: f64 = 4096.0;
|
||||
/// The most bytes of bitmaps kept.
|
||||
/// The bytes of bitmaps kept, past which those not drawn since the frame that asks for another
|
||||
/// one began are dropped.
|
||||
const BUDGET: usize = 512 << 20;
|
||||
/// The most bytes of bitmaps kept, those drawn in the frame included: a bitmap that would take
|
||||
/// them past it is not kept, and its file draws exactly at that zoom step.
|
||||
const MAX_BYTES: usize = 4 * BUDGET;
|
||||
/// The smallest zoom step (device pixels per point).
|
||||
const MIN_STEP: f64 = 1.0 / 64.0;
|
||||
|
||||
@@ -57,7 +64,19 @@ struct Bitmaps {
|
||||
static BITMAPS: LazyLock<Mutex<Bitmaps>> = LazyLock::new(Default::default);
|
||||
/// Bitmaps being made.
|
||||
static PENDING: LazyLock<Mutex<HashSet<BitmapKey>>> = LazyLock::new(Default::default);
|
||||
/// Bitmaps that could not be made (neither the file nor a preview could be read): not asked for
|
||||
/// again.
|
||||
static FAILED: LazyLock<Mutex<HashSet<BitmapKey>>> = LazyLock::new(Default::default);
|
||||
/// Bitmaps made but not kept, past [`MAX_BYTES`]: their files draw exactly at those zoom steps.
|
||||
static UNKEPT: LazyLock<Mutex<HashSet<BitmapKey>>> = LazyLock::new(Default::default);
|
||||
static GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
/// The files of the last [`MADE_KEPT`] bitmaps made, each with the [`generation`] it gave.
|
||||
static MADE: LazyLock<Mutex<VecDeque<(u64, String)>>> = LazyLock::new(Default::default);
|
||||
/// How many bitmaps [`MADE`] keeps.
|
||||
const MADE_KEPT: usize = 256;
|
||||
/// How many bitmaps of each file were asked for (tests).
|
||||
#[cfg(test)]
|
||||
static SCHEDULED: LazyLock<Mutex<HashMap<String, usize>>> = LazyLock::new(Default::default);
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
// The caches stay whole if a holder panicked (entries are only inserted and removed).
|
||||
@@ -65,11 +84,35 @@ fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
}
|
||||
|
||||
/// Changes whenever a bitmap made in the background is ready: a screen showing placed documents
|
||||
/// draws again when it does.
|
||||
/// draws again when it does, where [`made_between`] says.
|
||||
pub fn generation() -> u64 {
|
||||
GENERATION.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The files whose bitmaps were made after [`generation`] `from`, up to `to`: a screen drawn at
|
||||
/// `from` draws again where they show ([`crate::placed_area`]). None when they are no longer
|
||||
/// known (more than [`MADE_KEPT`] bitmaps were made since).
|
||||
pub fn made_between(from: u64, to: u64) -> Option<HashSet<String>> {
|
||||
let made = lock(&MADE);
|
||||
let oldest = made.front().map_or(u64::MAX, |(g, _)| *g);
|
||||
if to > from && oldest > from.saturating_add(1) {
|
||||
return None;
|
||||
}
|
||||
Some(made.iter().filter(|(g, _)| *g > from && *g <= to).map(|(_, key)| key.clone()).collect())
|
||||
}
|
||||
|
||||
/// A bitmap of file `key` is ready: the generation changes, and [`MADE`] records which file
|
||||
/// changed it. Both happen under [`MADE`]'s lock, so a generation read is in [`MADE`] by the time
|
||||
/// [`made_between`] reads it.
|
||||
fn made(key: &str) {
|
||||
let mut made = lock(&MADE);
|
||||
let g = GENERATION.fetch_add(1, Ordering::Relaxed).wrapping_add(1);
|
||||
made.push_back((g, key.to_owned()));
|
||||
while made.len() > MADE_KEPT {
|
||||
made.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// Are bitmaps being made in the background?
|
||||
pub fn busy() -> bool {
|
||||
!lock(&PENDING).is_empty()
|
||||
@@ -81,6 +124,18 @@ pub(crate) fn pending_for(key: &str) -> bool {
|
||||
lock(&PENDING).iter().any(|k| k.0 == key)
|
||||
}
|
||||
|
||||
/// How many bitmaps of file `key` were asked for.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn scheduled(key: &str) -> usize {
|
||||
lock(&SCHEDULED).get(key).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Mark the bitmap of file `key` at zoom `step` as not kept past [`MAX_BYTES`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn mark_unkept(key: &str, step: f64) {
|
||||
lock(&UNKEPT).insert((key.to_string(), step.to_bits()));
|
||||
}
|
||||
|
||||
/// The zoom step for `scale` device pixels per point: the power of two at or above it.
|
||||
pub(crate) fn step(scale: f64) -> Option<f64> {
|
||||
(scale.is_finite() && scale > 0.0).then(|| 2f64.powf(scale.log2().ceil()).max(MIN_STEP))
|
||||
@@ -104,19 +159,33 @@ impl Bitmaps {
|
||||
.map(|(_, b)| (b.pm.clone(), b.step))
|
||||
}
|
||||
|
||||
fn insert(&mut self, k: BitmapKey, pm: Pixmap, step: f64) {
|
||||
/// Keep `pm` as bitmap `k`, and past `budget` bytes drop the bitmaps drawn least recently,
|
||||
/// but not those drawn or made since clock `keep` (when the frame that asked for `k` began),
|
||||
/// which stay even past it. When the bitmaps would still be past `max` bytes, `k` is not kept:
|
||||
/// false.
|
||||
fn insert(&mut self, k: BitmapKey, pm: Pixmap, step: f64, keep: u64, (budget, max): (usize, usize)) -> bool {
|
||||
self.clock += 1;
|
||||
let size = pm.width() as usize * pm.height() as usize * 4;
|
||||
self.bytes += size;
|
||||
if let Some(old) = self.map.insert(k, Bitmap { pm: Arc::new(pm), step, used: self.clock }) {
|
||||
if let Some(old) = self.map.insert(k.clone(), Bitmap { pm: Arc::new(pm), step, used: self.clock }) {
|
||||
self.bytes = self.bytes.saturating_sub(old.pm.width() as usize * old.pm.height() as usize * 4);
|
||||
}
|
||||
while self.bytes > BUDGET && self.map.len() > 1 {
|
||||
let Some(k) = self.map.iter().min_by_key(|(_, b)| b.used).map(|(k, _)| k.clone()) else { break };
|
||||
while self.bytes > budget {
|
||||
let Some(k) = self.map.iter().filter(|(key, b)| b.used <= keep && **key != k).min_by_key(|(_, b)| b.used).map(|(key, _)| key.clone())
|
||||
else {
|
||||
break;
|
||||
};
|
||||
if let Some(b) = self.map.remove(&k) {
|
||||
self.bytes = self.bytes.saturating_sub(b.pm.width() as usize * b.pm.height() as usize * 4);
|
||||
}
|
||||
}
|
||||
if self.bytes <= max {
|
||||
return true;
|
||||
}
|
||||
if self.map.remove(&k).is_some() {
|
||||
self.bytes = self.bytes.saturating_sub(size);
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,6 +206,8 @@ struct Job {
|
||||
object: PlacedDocument,
|
||||
blob: ImageBlob,
|
||||
step: f64,
|
||||
/// The bitmap clock when the frame that asked for it began ([`Bitmaps::insert`]).
|
||||
keep: u64,
|
||||
/// The scheduler's file-access scope, which the worker runs the job in.
|
||||
scope: Option<Scoped>,
|
||||
}
|
||||
@@ -204,15 +275,24 @@ fn pixels(v: f64) -> u16 {
|
||||
v.round().clamp(1.0, MAX_SIDE) as u16
|
||||
}
|
||||
|
||||
/// Make `job`'s bitmap and keep it.
|
||||
/// Make `job`'s bitmap and keep it (or remember that it was not kept), or remember that it can't
|
||||
/// be made. The generation changes before the job stops being pending, so a screen that sees
|
||||
/// nothing pending sees the change.
|
||||
fn run(r: &mut Renderer, mut job: Job) {
|
||||
let scope = job.scope.take();
|
||||
let mut body = || {
|
||||
if let Some(pm) = make(r, &job.object, &job.blob, job.step) {
|
||||
lock(&BITMAPS).insert(job.key.clone(), pm, job.step);
|
||||
match make(r, &job.object, &job.blob, job.step) {
|
||||
Some(pm) => {
|
||||
if !lock(&BITMAPS).insert(job.key.clone(), pm, job.step, job.keep, (BUDGET, MAX_BYTES)) {
|
||||
lock(&UNKEPT).insert(job.key.clone());
|
||||
}
|
||||
made(&job.key.0);
|
||||
}
|
||||
None => {
|
||||
lock(&FAILED).insert(job.key.clone());
|
||||
}
|
||||
}
|
||||
lock(&PENDING).remove(&job.key);
|
||||
GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
};
|
||||
match scope {
|
||||
Some(scoped) => scoped(&mut body),
|
||||
@@ -241,9 +321,10 @@ mod workers {
|
||||
loop {
|
||||
let job = super::lock(&rx).recv();
|
||||
let Ok(job) = job else { break };
|
||||
// A panic loses this bitmap, not the worker.
|
||||
// A panic loses this bitmap, not the worker; it is not asked for again.
|
||||
let key = job.key.clone();
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::run(&mut r, *job))).is_err() {
|
||||
super::lock(&super::FAILED).insert(key.clone());
|
||||
super::lock(&super::PENDING).remove(&key);
|
||||
}
|
||||
}
|
||||
@@ -267,6 +348,10 @@ fn schedule(job: Job) {
|
||||
if !lock(&PENDING).insert(job.key.clone()) {
|
||||
return;
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
*lock(&SCHEDULED).entry(job.key.0.clone()).or_default() += 1;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let job = match workers::submit(Box::new(job)) {
|
||||
Ok(()) => return,
|
||||
@@ -318,8 +403,9 @@ impl Renderer {
|
||||
self.draw_arc(ctx, &inner, &e.art);
|
||||
}
|
||||
|
||||
/// Draw `p` from its bitmap at this zoom step, or (while that is made) another step's, or a
|
||||
/// placeholder. False when bitmaps don't suit (too large).
|
||||
/// Draw `p` from its bitmap at this zoom step, or (while that is made, or when it can't be)
|
||||
/// another step's, or a placeholder. False when bitmaps don't suit (too large, or not kept
|
||||
/// past [`MAX_BYTES`]).
|
||||
fn draw_placed_bitmap(&mut self, ctx: &mut RenderContext, f: &Frame, p: &PlacedDocument) -> bool {
|
||||
let m = f.view * p.xf;
|
||||
let Some(step) = step(mean_scale(m)) else { return false };
|
||||
@@ -328,16 +414,24 @@ impl Renderer {
|
||||
}
|
||||
let Some(blob) = f.doc.images.get(&p.key).cloned() else { return true };
|
||||
let key = (p.key.clone(), step.to_bits());
|
||||
let (found, nearest) = {
|
||||
// Not kept past [`MAX_BYTES`]: drawn exactly.
|
||||
if lock(&UNKEPT).contains(&key) {
|
||||
return false;
|
||||
}
|
||||
let (found, nearest, keep) = {
|
||||
let mut b = lock(&BITMAPS);
|
||||
// The clock when this frame first drew a placed document's bitmap.
|
||||
let keep = *self.placed_frame.get_or_insert(b.clock);
|
||||
let found = b.get(&key);
|
||||
let nearest = if found.is_none() { b.nearest(&p.key, step) } else { None };
|
||||
(found, nearest)
|
||||
(found, nearest, keep)
|
||||
};
|
||||
let shown = match found {
|
||||
Some(pm) => Some(pm),
|
||||
// It can't be made: another step's, or the placeholder.
|
||||
None if lock(&FAILED).contains(&key) => nearest.map(|n| n.0),
|
||||
None => {
|
||||
schedule(Job { key, object: p.clone(), blob, step, scope: SCOPE_CAPTURE.get().map(|capture| capture()) });
|
||||
schedule(Job { key, object: p.clone(), blob, step, keep, scope: SCOPE_CAPTURE.get().map(|capture| capture()) });
|
||||
// Made here and now (no threads) or meanwhile another step's.
|
||||
let mut b = lock(&BITMAPS);
|
||||
b.get(&(p.key.clone(), step.to_bits())).or(nearest.map(|n| n.0))
|
||||
@@ -354,7 +448,7 @@ impl Renderer {
|
||||
ctx.reset_paint_transform();
|
||||
}
|
||||
None => {
|
||||
// Coming: a light box where it will be.
|
||||
// Coming, or it can't be made: a light box where it shows.
|
||||
ctx.set_transform(m);
|
||||
ctx.set_paint(peniko::Color::from_rgba8(128, 128, 128, 40));
|
||||
ctx.fill_rect(&kurbo::Rect::new(rect.x0, rect.y0, rect.x1, rect.y1));
|
||||
@@ -378,4 +472,31 @@ mod tests {
|
||||
assert_eq!(step(f64::NAN), None);
|
||||
assert_eq!(step(0.0), None);
|
||||
}
|
||||
|
||||
/// Past the budget, the bitmaps drawn least recently are dropped, but not those drawn since
|
||||
/// the frame that asked for the new one began; past the most, the new one is not kept.
|
||||
#[test]
|
||||
fn bitmaps_drawn_in_the_frame_stay_up_to_the_most_kept() {
|
||||
let mut b = Bitmaps::default();
|
||||
// 400 bytes each: a budget of 1,000 bytes and at most 2,000.
|
||||
let limits = (1000, 2000);
|
||||
let key = |name: &str| (name.to_string(), 1f64.to_bits());
|
||||
for name in ["a", "b", "c"] {
|
||||
assert!(b.insert(key(name), Pixmap::new(10, 10), 1.0, 0, limits));
|
||||
}
|
||||
assert_eq!(b.bytes, 1200, "all made in the frame: kept past the budget");
|
||||
// The next frame begins and draws "a", then asks for "d".
|
||||
let frame = b.clock;
|
||||
assert!(b.get(&key("a")).is_some());
|
||||
assert!(b.insert(key("d"), Pixmap::new(10, 10), 1.0, frame, limits));
|
||||
let mut kept: Vec<&str> = b.map.keys().map(|(name, _)| name.as_str()).collect();
|
||||
kept.sort_unstable();
|
||||
assert_eq!((kept, b.bytes), (vec!["a", "d"], 800), "b and c, not drawn since, are dropped");
|
||||
for name in ["e", "f", "g"] {
|
||||
assert!(b.insert(key(name), Pixmap::new(10, 10), 1.0, frame, limits), "{name}");
|
||||
}
|
||||
assert_eq!(b.bytes, 2000);
|
||||
assert!(!b.insert(key("h"), Pixmap::new(10, 10), 1.0, frame, limits), "past the most: not kept");
|
||||
assert!(!b.map.contains_key(&key("h")) && b.bytes == 2000);
|
||||
}
|
||||
}
|
||||
|
||||
+202
-1
@@ -930,7 +930,9 @@ fn tiff_header(w: u32, h: u32) -> Vec<u8> {
|
||||
|
||||
/// The decode allowance (2 GB) counts an image's pixels as RGBA, read from its header (#1717): a
|
||||
/// 1-bit gray image whose 8-bit gray pixels are within it but whose RGBA is over it is not decoded
|
||||
/// and draws nothing, counted for an export to report; one a column narrower goes on to decoding.
|
||||
/// whole, and one a column narrower goes on to decoding. `decode_pixmap` reads the larger one at
|
||||
/// reduced size; this header has no rows to read, so it draws nothing, counted for an export to
|
||||
/// report.
|
||||
#[test]
|
||||
fn an_image_too_large_as_rgba_is_not_decoded() {
|
||||
let over = paint::decode_within_allowance(&png_header(23_171, 23_170));
|
||||
@@ -946,6 +948,87 @@ fn an_image_too_large_as_rgba_is_not_decoded() {
|
||||
assert!(matches!(huge, Err(image::ImageError::Limits(_))), "{huge:?}");
|
||||
}
|
||||
|
||||
/// A PNG of `w` × `h` noisy pixels cut off halfway through its bytes: its header reads, and its
|
||||
/// pixels can't be decoded.
|
||||
fn truncated_png(w: u32, h: u32) -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_fn(w, h, |x, y| {
|
||||
let v = (x * 7919 + y * 104_729).wrapping_mul(2_654_435_761).to_le_bytes();
|
||||
image::Rgba([v[0], v[1], v[2], 255])
|
||||
});
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
png.truncate(png.len() / 2);
|
||||
png
|
||||
}
|
||||
|
||||
/// An image whose pixels can't be decoded is tried once: later renders find the store's note of it,
|
||||
/// and each render counts it in `decode_failures` for an export to report. On screen
|
||||
/// (`mark_undecoded_images`) it draws as a crossed gray box; an export draws nothing there.
|
||||
#[test]
|
||||
fn an_undecodable_image_is_tried_once_and_marked_on_screen() {
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind};
|
||||
let png = truncated_png(61, 47);
|
||||
assert_eq!(image::ImageReader::new(std::io::Cursor::new(&png)).with_guessed_format().unwrap().into_dimensions().unwrap(), (61, 47));
|
||||
let mut d = Document::new(80.0, 60.0);
|
||||
d.images.insert("cut".into(), ImageBlob::new("image/png", png));
|
||||
let id = d.alloc_id();
|
||||
let im = ImageObject {
|
||||
key: "cut".into(),
|
||||
width: 61,
|
||||
height: 47,
|
||||
xf: Affine::translate((10.0, 5.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
// The alpha summed over the image's frame.
|
||||
let alpha = |r: &Rendered| (10..71).flat_map(|x| (5..52).map(move |y| u64::from(r.pixel(x, y)[3]))).sum::<u64>();
|
||||
let attempts = || paint::DECODE_ATTEMPTS.with(std::cell::Cell::get);
|
||||
let (tried, failed) = (attempts(), decode_failures());
|
||||
let screen = RenderOptions { mark_undecoded_images: true, ..Default::default() };
|
||||
let mut r = Renderer::new();
|
||||
for render in 1..=2 {
|
||||
let shown = r.render(&d, 80, 60, Affine::IDENTITY, &screen);
|
||||
assert!(alpha(&shown) > 0, "render {render}: the crossed box shows");
|
||||
assert_eq!(decode_failures() - failed, render, "render {render}: counted");
|
||||
}
|
||||
assert_eq!(attempts() - tried, 1, "tried once");
|
||||
let export = Renderer::new().render(&d, 80, 60, Affine::IDENTITY, &RenderOptions::default());
|
||||
assert_eq!(alpha(&export), 0, "an export draws nothing there");
|
||||
assert_eq!((attempts() - tried, decode_failures() - failed), (1, 3), "and counts it without decoding it again");
|
||||
}
|
||||
|
||||
/// The rasters a renderer keeps of an object's raster effects are made again when
|
||||
/// `mark_undecoded_images` changes: a blurred image whose pixels can't be decoded shows its blurred
|
||||
/// mark only while the option is on.
|
||||
#[test]
|
||||
fn raster_effects_follow_the_undecoded_image_mark() {
|
||||
use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind};
|
||||
let mut d = Document::new(80.0, 60.0);
|
||||
d.images.insert("cut".into(), ImageBlob::new("image/png", truncated_png(43, 31)));
|
||||
let id = d.alloc_id();
|
||||
let im = ImageObject {
|
||||
key: "cut".into(),
|
||||
width: 43,
|
||||
height: 31,
|
||||
xf: Affine::translate((15.0, 12.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let mut n = Node::new(id, NodeKind::Image(Box::new(im)));
|
||||
n.appearance.effects.push(Effect { id: "blur.gaussian".into(), params: serde_json::json!({"radius": 2.0}), visible: true });
|
||||
d.insert(Some(d.layers[0].id), 0, n).unwrap();
|
||||
let alpha = |r: &Rendered| r.pixels.chunks(4).map(|p| u64::from(p[3])).sum::<u64>();
|
||||
let mut r = Renderer::new();
|
||||
for mark in [true, false, true] {
|
||||
let opts = RenderOptions { mark_undecoded_images: mark, ..Default::default() };
|
||||
let a = alpha(&r.render(&d, 80, 60, Affine::IDENTITY, &opts));
|
||||
assert_eq!(a > 0, mark, "mark_undecoded_images {mark}: alpha {a}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A gray image within the allowance draws its gray levels.
|
||||
#[test]
|
||||
fn a_gray_image_draws_its_gray_levels() {
|
||||
@@ -963,6 +1046,124 @@ fn a_gray_image_draws_its_gray_levels() {
|
||||
assert_eq!((r.pixel(5, 10), r.pixel(35, 10)), ([40, 40, 40, 255], [200, 200, 200, 255]));
|
||||
}
|
||||
|
||||
/// Runs `f` with the decode allowance of one image on this thread set to `bytes`.
|
||||
fn with_allowance<T>(bytes: u64, f: impl FnOnce() -> T) -> T {
|
||||
paint::TEST_ALLOWANCE.with(|c| c.set(Some(bytes)));
|
||||
let out = f();
|
||||
paint::TEST_ALLOWANCE.with(|c| c.set(None));
|
||||
out
|
||||
}
|
||||
|
||||
/// `img` encoded as `format`.
|
||||
fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// A 16-bit PNG past the decode allowance is read a row at a time at the largest size within the
|
||||
/// allowance and draws its colors; the file's own size is kept.
|
||||
#[test]
|
||||
fn a_png_past_the_allowance_draws_at_reduced_size() {
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind};
|
||||
let img = image::ImageBuffer::<image::Rgba<u16>, _>::from_fn(64, 48, |x, _| {
|
||||
if x < 32 { image::Rgba([51400, 10280, 10280, 65535]) } else { image::Rgba([10280, 10280, 51400, 65535]) }
|
||||
});
|
||||
let png = encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png);
|
||||
// 64 × 48 is 12,288 bytes as RGBA; 36 × 27 is the largest within 4,096.
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&png)), Some((36, 27)));
|
||||
assert_eq!(paint::reduced_size(&png), None, "within the 2 GB allowance");
|
||||
let mut d = Document::new(64.0, 48.0);
|
||||
d.images.insert("over".into(), ImageBlob::new("image/png", png));
|
||||
let id = d.alloc_id();
|
||||
let im = ImageObject { key: "over".into(), width: 64, height: 48, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
let failed = decode_failures();
|
||||
// As on screen, where an image that can't be decoded draws as a crossed box.
|
||||
let screen = RenderOptions { smooth_images: false, mark_undecoded_images: true, ..Default::default() };
|
||||
let r = with_allowance(4096, || Renderer::new().render(&d, 64, 48, Affine::IDENTITY, &screen));
|
||||
assert_eq!(decode_failures(), failed);
|
||||
assert_eq!((r.pixel(8, 24), r.pixel(56, 24)), ([200, 40, 40, 255], [40, 40, 200, 255]));
|
||||
// 16 × 16 at 16 bits a sample is 2,048 bytes decoded and 1,024 as RGBA: past 1,500 as decoded
|
||||
// and within it as RGBA, it is read a row at a time at its own size.
|
||||
let small = image::ImageBuffer::<image::Rgba<u16>, _>::from_pixel(16, 16, image::Rgba([51400, 10280, 10280, 65535]));
|
||||
let small = encoded(image::DynamicImage::ImageRgba16(small), image::ImageFormat::Png);
|
||||
assert_eq!(with_allowance(1500, || paint::reduced_size(&small)), Some((16, 16)));
|
||||
let pm = with_allowance(1500, || paint::decode_pixmap(&small)).expect("read a row at a time");
|
||||
let c = pm.sample(3, 3);
|
||||
assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (16, 16, [200, 40, 40, 255]));
|
||||
// A row is read only while the reader's row buffers, 32 bytes a column, fit the allowance:
|
||||
// 128 columns do within 4,096 bytes, and 129 columns are not decoded (their samples, 8 bytes a
|
||||
// pixel, are past it too).
|
||||
let wide = |w: u32| {
|
||||
let img = image::ImageBuffer::<image::Rgba<u16>, _>::from_pixel(w, 6, image::Rgba([51400, 10280, 10280, 65535]));
|
||||
encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png)
|
||||
};
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&wide(128))), Some((128, 6)));
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&wide(129))), None);
|
||||
// An image of more pixels than the allowance has bytes is not read: 128 × 32 8-bit gray pixels
|
||||
// are drawn at 64 × 16 within 4,096 bytes, and 128 × 33 are not.
|
||||
let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(128, h, image::Luma([90]))), image::ImageFormat::Png);
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&gray(32))), Some((64, 16)));
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&gray(33))), None);
|
||||
}
|
||||
|
||||
/// A JPEG whose RGB samples are within the allowance but whose RGBA is past it is decoded whole
|
||||
/// and shrunk to the largest size within the allowance; an image whose decoded samples are past it
|
||||
/// and can't be read a row at a time (a GIF, 4 bytes a pixel) is still not decoded, counted, and
|
||||
/// noted as undecodable.
|
||||
#[test]
|
||||
fn a_jpeg_past_the_allowance_as_rgba_is_shrunk_and_a_gif_past_it_is_not_decoded() {
|
||||
let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg);
|
||||
// 14,400 bytes of RGB, 19,200 as RGBA: 73 × 54 is the largest within 16,000.
|
||||
let pm = with_allowance(16_000, || paint::decode_pixmap(&jpeg)).expect("decoded at reduced size");
|
||||
assert_eq!((pm.width(), pm.height()), (73, 54));
|
||||
let c = pm.sample(36, 27);
|
||||
assert!(c.r.abs_diff(30) <= 4 && c.g.abs_diff(120) <= 4 && c.b.abs_diff(200) <= 4 && c.a == 255, "{c:?}");
|
||||
// A placed document's preview asks for 20 × 15: decoded straight at that size.
|
||||
let pm = with_allowance(16_000, || paint::decode_pixmap_fit(&jpeg, 20, 15)).expect("decoded at the size asked for");
|
||||
assert_eq!((pm.width(), pm.height()), (20, 15));
|
||||
let gif =
|
||||
encoded(image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(80, 60, image::Rgba([30, 120, 200, 255]))), image::ImageFormat::Gif);
|
||||
assert_eq!(with_allowance(16_000, || paint::reduced_size(&gif)), None);
|
||||
let failed = decode_failures();
|
||||
let why = with_allowance(16_000, || paint::decode_pixmap_or_why(&gif)).err();
|
||||
assert_eq!(why, Some(paint::Undecoded::Unreadable), "noted as undecodable");
|
||||
assert_eq!(decode_failures(), failed + 1);
|
||||
}
|
||||
|
||||
/// An image past the allowance is decoded at reduced size only while the result and what reading
|
||||
/// it takes (the image decoded whole, or the PNG reader's row buffers) fit beside the images
|
||||
/// paints hold; when they don't, it isn't decoded and is not noted as undecodable, and it is
|
||||
/// decoded once there is room.
|
||||
#[test]
|
||||
fn a_reduced_decode_counts_what_reading_takes_beside_the_images_paints_hold() {
|
||||
/// Runs `f` with room for `bytes` beside the images paints hold.
|
||||
fn with_room<T>(bytes: u64, f: impl FnOnce() -> T) -> T {
|
||||
paint::TEST_ROOM.with(|c| c.set(Some(bytes)));
|
||||
let out = f();
|
||||
paint::TEST_ROOM.with(|c| c.set(None));
|
||||
out
|
||||
}
|
||||
// Decoded whole: 14,400 bytes of RGB and a 16-row band of 8,960 bytes, beside a 73 × 54 result
|
||||
// of 15,768 bytes.
|
||||
let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg);
|
||||
// Read a row at a time: 64 columns of 32 bytes in the reader's row buffers, beside a 36 × 27
|
||||
// result of 3,888 bytes.
|
||||
let png = encoded(
|
||||
image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(64, 48, image::Rgba([51400, 10280, 10280, 65535]))),
|
||||
image::ImageFormat::Png,
|
||||
);
|
||||
for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 4_096, 3_888 + 2_048, (36, 27))] {
|
||||
let failed = decode_failures();
|
||||
let none = with_allowance(allowance, || with_room(room - 1, || paint::decode_pixmap_or_why(bytes)));
|
||||
assert_eq!(none.err(), Some(paint::Undecoded::NoRoom), "not decoded with a byte too few, and tried again later");
|
||||
assert_eq!(decode_failures(), failed + 1);
|
||||
let pm = with_allowance(allowance, || with_room(room, || paint::decode_pixmap(bytes))).expect("decoded once there is room");
|
||||
assert_eq!((pm.width(), pm.height()), size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Art Optimized exports are supersampled (#983): two red shapes meeting along a diagonal leave no
|
||||
/// seam of the white background between them, where shape-by-shape smoothing shows one; the outer
|
||||
/// edges stay smooth.
|
||||
|
||||
@@ -801,6 +801,68 @@ fn brush_art_draws_edits_of_the_symbols_and_patterns_it_shows() {
|
||||
}
|
||||
}
|
||||
|
||||
/// As above, with symbols `Dot` (a blue square) and `Other` (a red square with a brushed line),
|
||||
/// and patterns `Fill` (a green square) and `Spare` (a red square with a brushed line). After a
|
||||
/// frame, the next one draws as a new renderer does when two symbols or two patterns swap names,
|
||||
/// their art left as it is: the brush art's instance of `Dot` or its square painted with `Fill`
|
||||
/// then shows art that draws a brushed stroke.
|
||||
#[test]
|
||||
fn brush_art_draws_renamed_symbols_and_patterns_it_shows() {
|
||||
let _fonts = fonts_steady();
|
||||
use vectorcraft_brush::{Brush, BrushKind, Scatter};
|
||||
use vectorcraft_doc::pattern::{PatternDef, pattern_paint};
|
||||
use vectorcraft_geom::shapes::{line, rectangle};
|
||||
let square = |d: &mut Document, paint: Paint| filled(d, rectangle(Rect::new(-4.0, -4.0, 4.0, 4.0)), paint, vec![]);
|
||||
let art = |d: &mut Document, paint: Paint, brushed: bool| {
|
||||
let mut members = vec![Arc::new(square(d, paint))];
|
||||
if brushed {
|
||||
members.push(Arc::new(brushed_line(d)));
|
||||
}
|
||||
Node::group(d.alloc_id(), members)
|
||||
};
|
||||
let doc = || {
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
for (name, paint, brushed) in
|
||||
[("Dot", Paint::solid(Color::rgb(0.0, 0.0, 1.0)), false), ("Other", Paint::solid(Color::rgb(1.0, 0.0, 0.0)), true)]
|
||||
{
|
||||
let a = art(&mut d, paint, brushed);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: name.into(), art: Arc::new(a) });
|
||||
}
|
||||
for (name, paint, brushed) in
|
||||
[("Fill", Paint::solid(Color::rgb(0.0, 0.6, 0.0)), false), ("Spare", Paint::solid(Color::rgb(1.0, 0.0, 0.0)), true)]
|
||||
{
|
||||
let a = art(&mut d, paint, brushed);
|
||||
let mut def = PatternDef::new(name, vec![Arc::new(a)]);
|
||||
def.tile = Rect::new(-6.0, -6.0, 6.0, 6.0);
|
||||
d.patterns.push(def);
|
||||
}
|
||||
let id = d.alloc_id();
|
||||
let instance = Node::new(id, NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((0.0, -8.0)) });
|
||||
let mut painted = square(&mut d, pattern_paint("Fill"));
|
||||
painted.transform(Affine::translate((0.0, 8.0)), true);
|
||||
let scatter = Node::group(d.alloc_id(), vec![Arc::new(instance), Arc::new(painted)]);
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
lib.push(Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art: scatter, spacing: (150.0, 150.0), ..Default::default() }) });
|
||||
vectorcraft_brush::store(&mut d, &lib);
|
||||
let mut ap = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
if let Some(s) = ap.stroke_mut() {
|
||||
s.brush = Some("Dots".into());
|
||||
}
|
||||
let path = Node::path(d.alloc_id(), line((20.0, 50.0).into(), (180.0, 50.0).into()), ap);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), usize::MAX, path).unwrap();
|
||||
d
|
||||
};
|
||||
edit_draws_as_new(doc(), |d| {
|
||||
d.symbols[0].name = "Other".into();
|
||||
d.symbols[1].name = "Dot".into();
|
||||
});
|
||||
edit_draws_as_new(doc(), |d| {
|
||||
d.patterns[0].name = "Spare".into();
|
||||
d.patterns[1].name = "Fill".into();
|
||||
});
|
||||
}
|
||||
|
||||
/// A path of the document and an instance of symbol `Wave` (a group holding another path) are
|
||||
/// stroked with scatter brush `Bent`, whose art is an arc envelope around a green band: the second
|
||||
/// frame evaluates none of the envelopes in their brush art again, and draws what the first drew
|
||||
|
||||
@@ -8,8 +8,11 @@ use vectorcraft_geom::shapes;
|
||||
use super::*;
|
||||
|
||||
/// Every file reads as a 40×20 artboard filled blue; a file whose bytes start with `loop` also
|
||||
/// places itself (the same key) in its middle.
|
||||
/// places itself (the same key) in its middle, and one whose bytes start with `bad` can't be read.
|
||||
fn blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
|
||||
if bytes.starts_with(b"bad") {
|
||||
return None;
|
||||
}
|
||||
let mut d = Document::new(40.0, 20.0);
|
||||
d.layers.clear();
|
||||
let blue = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0);
|
||||
@@ -27,19 +30,32 @@ fn doc_with(key: &str, bytes: &[u8]) -> Document {
|
||||
vectorcraft_doc::placed_document::set_loader(blue_page);
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.images.insert(key.into(), ImageBlob::new("application/json", bytes.to_vec()));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, placed_node(50, key, 40.0, 20.0, Affine::translate((10.0, 10.0)) * Affine::scale(2.0))).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// Object `id` showing file `key` in a `width`×`height` box placed by `xf`.
|
||||
fn placed_node(id: u64, key: &str, width: f64, height: f64, xf: Affine) -> Node {
|
||||
let p = PlacedDocument {
|
||||
link: LinkInfo::new("/art/card.vectorcraft"),
|
||||
key: key.into(),
|
||||
bounding: false,
|
||||
page_box: Default::default(),
|
||||
width: 40.0,
|
||||
height: 20.0,
|
||||
xf: Affine::translate((10.0, 10.0)) * Affine::scale(2.0),
|
||||
width,
|
||||
height,
|
||||
xf,
|
||||
placement: Default::default(),
|
||||
};
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, Node::new(NodeId(50), NodeKind::PlacedDocument(Box::new(p)))).unwrap();
|
||||
d
|
||||
Node::new(NodeId(id), NodeKind::PlacedDocument(Box::new(p)))
|
||||
}
|
||||
|
||||
/// Held by the tests that draw placed documents from bitmaps, which share the bitmaps, their
|
||||
/// generation and the jobs being made: one test's bitmaps don't push out another's, and
|
||||
/// [`settle`] waits for its own.
|
||||
fn serial() -> std::sync::MutexGuard<'static, ()> {
|
||||
static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn doc(key: &str) -> Document {
|
||||
@@ -117,6 +133,7 @@ fn a_placed_document_with_a_drop_shadow_shows_its_file_once_read() {
|
||||
|
||||
#[test]
|
||||
fn on_screen_a_placed_document_shows_a_placeholder_then_its_bitmap() {
|
||||
let _serial = serial();
|
||||
let d = doc("progressive-1");
|
||||
let generation = placed_document::generation();
|
||||
let first = render(&d, true);
|
||||
@@ -135,6 +152,7 @@ fn on_screen_a_placed_document_shows_a_placeholder_then_its_bitmap() {
|
||||
|
||||
#[test]
|
||||
fn copies_of_one_placed_document_share_its_bitmap() {
|
||||
let _serial = serial();
|
||||
let mut d = doc("shared-1");
|
||||
let n = d.node(NodeId(50)).unwrap().clone();
|
||||
let l = d.layers[0].id;
|
||||
@@ -150,8 +168,126 @@ fn copies_of_one_placed_document_share_its_bitmap() {
|
||||
assert_eq!(&r.pixel(50, 75)[..3], &[0, 0, 255]);
|
||||
}
|
||||
|
||||
/// Nine files on screen, each drawn from a 4096 × 4096 bitmap (576 MiB together, past the 512 MiB
|
||||
/// the bitmaps keep): once made, the next frames draw all nine and ask for none again.
|
||||
#[test]
|
||||
fn nine_large_bitmaps_on_screen_are_not_made_again() {
|
||||
let _serial = serial();
|
||||
vectorcraft_doc::placed_document::set_loader(blue_page);
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let keys: Vec<String> = (0..9).map(|i| format!("nine-{i}")).collect();
|
||||
for (i, key) in keys.iter().enumerate() {
|
||||
d.images.insert(key.clone(), ImageBlob::new("application/json", format!("{{\"doc\": \"{key}\"}}").into_bytes()));
|
||||
// A 1 × 1 point box at 4096 pixels a point: a 4096-pixel bitmap.
|
||||
d.insert(Some(l), i, placed_node(100 + i as u64, key, 1.0, 1.0, Affine::translate((i as f64 * 0.001, 0.0)))).unwrap();
|
||||
}
|
||||
let (view, opts) = (Affine::scale(4096.0), RenderOptions { progressive_placed: true, ..Default::default() });
|
||||
let mut r = Renderer::new();
|
||||
r.render(&d, 32, 32, view, &opts);
|
||||
settle();
|
||||
let asked = || keys.iter().map(|k| placed_document::scheduled(k)).collect::<Vec<_>>();
|
||||
assert_eq!(asked(), vec![1; 9], "each asked for once");
|
||||
for frame in 1..=2 {
|
||||
let shown = r.render(&d, 32, 32, view, &opts);
|
||||
assert_eq!(asked(), vec![1; 9], "frame {frame} asks for none again");
|
||||
assert_eq!(&shown.pixel(16, 16)[..3], &[0, 0, 255], "frame {frame} draws the art");
|
||||
}
|
||||
}
|
||||
|
||||
/// A bitmap that was not kept (it would have taken the bitmaps past the most they may hold) is
|
||||
/// not asked for again: its file draws exactly at that zoom step, at once.
|
||||
#[test]
|
||||
fn a_bitmap_not_kept_draws_exactly_without_being_asked_for() {
|
||||
let _serial = serial();
|
||||
let d = doc("unkept-1");
|
||||
// The box is drawn at 2 pixels a point: zoom step 2.
|
||||
placed_document::mark_unkept("unkept-1", 2.0);
|
||||
let shown = render(&d, true);
|
||||
assert_eq!(&shown.pixel(50, 30)[..3], &[0, 0, 255], "the art, drawn exactly");
|
||||
assert_eq!(placed_document::scheduled("unkept-1"), 0, "not asked for");
|
||||
}
|
||||
|
||||
/// A file that can't be read, without a preview: its bitmap is asked for once, the screen is
|
||||
/// not told to draw again, and later frames draw the placeholder without asking again.
|
||||
#[test]
|
||||
fn a_bitmap_that_cant_be_made_is_not_asked_for_again() {
|
||||
let _serial = serial();
|
||||
let d = doc_with("unreadable-1", b"bad");
|
||||
let generation = placed_document::generation();
|
||||
render(&d, true);
|
||||
settle();
|
||||
assert_eq!(placed_document::generation(), generation, "nothing new to draw");
|
||||
let later = render(&d, true);
|
||||
assert_eq!(placed_document::scheduled("unreadable-1"), 1, "asked for once");
|
||||
let shown = &later.pixel(50, 30)[..3];
|
||||
assert!(shown != [255, 255, 255] && shown != [0, 0, 255], "the placeholder: {shown:?}");
|
||||
}
|
||||
|
||||
/// Once bitmaps are ready, drawing again where [`placed_area`] says gives what drawing the whole
|
||||
/// frame again gives. The area of a file covers every object showing it (a group's member and
|
||||
/// an object with a drop shadow too) and no object showing another file; art of a brush or a
|
||||
/// symbol showing it makes it everything.
|
||||
#[test]
|
||||
fn a_ready_bitmap_draws_again_where_its_file_shows() {
|
||||
let _serial = serial();
|
||||
vectorcraft_doc::placed_document::set_loader(blue_page);
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
for key in ["area-a", "area-b"] {
|
||||
d.images.insert(key.into(), ImageBlob::new("application/json", format!("{{\"doc\": \"{key}\"}}").into_bytes()));
|
||||
}
|
||||
let l = d.layers[0].id;
|
||||
// 20 × 10 point boxes: A loose at (5, 5), with a shadow at (30, 40) and in a group at (5, 80);
|
||||
// B at (75, 5). Only the shadow reaches past x = 50, and only the group's member past y = 50.
|
||||
let at = |x: f64, y: f64| Affine::translate((x, y)) * Affine::scale(0.5);
|
||||
d.insert(Some(l), 0, placed_node(60, "area-a", 40.0, 20.0, at(5.0, 5.0))).unwrap();
|
||||
let group = NodeKind::Group { children: vec![Arc::new(placed_node(61, "area-a", 40.0, 20.0, at(5.0, 80.0)))], clip: false };
|
||||
d.insert(Some(l), 1, Node::new(NodeId(62), group)).unwrap();
|
||||
let mut shadowed = placed_node(63, "area-a", 40.0, 20.0, at(30.0, 40.0));
|
||||
let params = serde_json::json!({"x": 4, "y": 4, "blur": 1, "opacity": 100});
|
||||
shadowed.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params, visible: true });
|
||||
d.insert(Some(l), 2, shadowed).unwrap();
|
||||
d.insert(Some(l), 3, placed_node(64, "area-b", 40.0, 20.0, at(75.0, 5.0))).unwrap();
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, ..Default::default() };
|
||||
let mut r = Renderer::new();
|
||||
let generation = placed_document::generation();
|
||||
let before = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
|
||||
settle();
|
||||
let made = placed_document::made_between(generation, placed_document::generation()).expect("known");
|
||||
let files = |keys: &[&str]| keys.iter().map(|k| k.to_string()).collect::<std::collections::HashSet<_>>();
|
||||
assert_eq!(made, files(&["area-a", "area-b"]), "both files' bitmaps");
|
||||
let only_a = files(&["area-a"]);
|
||||
let Changed::Area(a) = placed_area(&d, &only_a) else { panic!("an area") };
|
||||
for (x, y) in [(6.0, 6.0), (24.0, 14.0), (31.0, 41.0), (53.0, 53.0), (6.0, 81.0), (24.0, 89.0)] {
|
||||
assert!(a.contains(vectorcraft_geom::Point::new(x, y)), "({x}, {y}) in {a:?}");
|
||||
}
|
||||
assert!(a.x1 < 75.0, "not B: {a:?}");
|
||||
// Drawn again only there, it is what the whole frame drawn again shows.
|
||||
let Changed::Area(area) = placed_area(&d, &made) else { panic!("an area") };
|
||||
let after = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts);
|
||||
let [x0, y0, x1, y1] = view_pixels(area, Affine::IDENTITY, 100, 100).expect("on screen");
|
||||
let part = r.render(&d, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))), &opts);
|
||||
let mut patched = before.pixels.clone();
|
||||
for y in 0..y1 - y0 {
|
||||
let (from, to, n) = ((y * (x1 - x0) * 4) as usize, (((y0 + y) * 100 + x0) * 4) as usize, ((x1 - x0) * 4) as usize);
|
||||
patched[to..to + n].copy_from_slice(&part.pixels[from..from + n]);
|
||||
}
|
||||
assert!(patched == after.pixels, "drawn again in {area:?}, it differs from drawing it all");
|
||||
assert!(before.pixels != after.pixels, "the bitmaps show");
|
||||
// Other files change nothing; art of a brush or a symbol showing the file changes everything.
|
||||
assert_eq!(placed_area(&d, &files(&["area-z"])), Changed::Nothing);
|
||||
let mut brushed = d.clone();
|
||||
let scatter = vectorcraft_brush::Scatter { art: placed_node(66, "area-a", 40.0, 20.0, Affine::IDENTITY), ..Default::default() };
|
||||
let brush = vectorcraft_brush::Brush { name: "Cards".into(), kind: vectorcraft_brush::BrushKind::Scatter(scatter) };
|
||||
vectorcraft_brush::store(&mut brushed, &[brush]);
|
||||
assert_eq!(placed_area(&brushed, &only_a), Changed::Everything);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: "Card".into(), art: Arc::new(placed_node(65, "area-a", 40.0, 20.0, Affine::IDENTITY)) });
|
||||
assert_eq!(placed_area(&d, &only_a), Changed::Everything);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_document_kept_as_its_preview_draws_the_preview() {
|
||||
let _serial = serial();
|
||||
let mut d = doc("preview-1");
|
||||
// Only the preview (a 20×10 green PNG) is there, and the file can't be read here.
|
||||
let img = image::RgbaImage::from_pixel(20, 10, image::Rgba([0, 200, 0, 255]));
|
||||
@@ -172,6 +308,7 @@ fn a_placed_document_kept_as_its_preview_draws_the_preview() {
|
||||
|
||||
#[test]
|
||||
fn a_document_that_places_itself_draws_a_few_levels_deep_then_stops() {
|
||||
let _serial = serial();
|
||||
let d = doc_with("loop-1", b"loop");
|
||||
let t = std::time::Instant::now();
|
||||
let r = render(&d, false);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Effect rasters cropped to the view, or made at a lower resolution, are kept while the view
|
||||
//! stays as it is: dragging other art over an object whose effects reach far past the view (a wide
|
||||
//! blur, or any blur zoomed in) draws its raster from the last frame.
|
||||
//! blur, or any blur zoomed in) draws its raster from the last frame. A cropped raster made again
|
||||
//! after a pan is kept while later pans stay within the margin it is made with.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use crate::{RenderOptions, Renderer};
|
||||
@@ -110,6 +111,209 @@ fn rasters_cropped_to_the_view_follow_a_pan_and_a_zoom() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A 6000 × 4000 pt image (300 × 200 pixels, 20 pt a pixel) under `effects`.
|
||||
fn large_image(effects: &[(&str, serde_json::Value)]) -> Document {
|
||||
let img = image::RgbaImage::from_fn(300, 200, |x, y| image::Rgba([(x * 7) as u8, (y * 13) as u8, ((x + y) * 3) as u8, 255]));
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut d = Document::new(6000.0, 4000.0);
|
||||
d.images.insert("viewraster-pan".into(), ImageBlob::new("image/png", png));
|
||||
let im = ImageObject {
|
||||
key: "viewraster-pan".into(),
|
||||
width: 300,
|
||||
height: 200,
|
||||
xf: Affine::scale(20.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
|
||||
n.appearance.effects = effects.iter().map(|(id, p)| Effect { id: (*id).into(), params: p.clone(), visible: true }).collect();
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// At 100 %, the Drop Shadow, Gaussian Blur and Feather rasters of a large image are cropped to the view. The pan
|
||||
/// that makes one again at the same zoom makes it with a margin around the view, and later pans within the margin
|
||||
/// (by up to 259 pixels from the frame that made them, and back) draw it without making any offscreen raster: each
|
||||
/// such frame makes as many offscreen pixels as the same view drawn again, and draws as a fresh renderer draws it,
|
||||
/// within a level a channel: an image sampled into a raster that starts at another pixel rounds by up to a level, as it
|
||||
/// does in the frames of two fresh renderers whose views differ in size.
|
||||
#[test]
|
||||
fn pans_within_a_cropped_rasters_margin_draw_it_kept() {
|
||||
let size = (640, 360);
|
||||
let cases: Vec<Case> = vec![
|
||||
("Drop Shadow", vec![("stylize.dropShadow", json!({"blur": 20, "x": 7, "y": 7}))], 1.0),
|
||||
("Gaussian Blur", vec![("blur.gaussian", json!({"radius": 20}))], 1.0),
|
||||
("Feather", vec![("stylize.feather", json!({"radius": 20}))], 1.0),
|
||||
(
|
||||
"Drop Shadow over a Drop Shadow",
|
||||
vec![("stylize.dropShadow", json!({"blur": 20, "x": 7, "y": 7})), ("stylize.dropShadow", json!({"blur": 10, "x": -5, "y": 9}))],
|
||||
1.0,
|
||||
),
|
||||
];
|
||||
let counted = |r: &mut Renderer, d: &Document, xf: Affine, opts: &RenderOptions| {
|
||||
crate::OFFSCREEN_PIXELS.with(|n| n.set(0));
|
||||
let image = r.render(d, size.0, size.1, xf, opts);
|
||||
(image, crate::OFFSCREEN_PIXELS.with(|n| n.get()))
|
||||
};
|
||||
for (name, effects, zoom) in cases {
|
||||
let d = large_image(&effects);
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let at = |dx: f64, dy: f64| Affine::translate((320.0 + dx, 180.0 + dy)) * Affine::scale(zoom) * Affine::translate((-3000.0, -2000.0));
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&d, size.0, size.1, at(0.0, 0.0), &opts);
|
||||
// The pan that makes the rasters again, and the same view drawn again.
|
||||
r.render(&d, size.0, size.1, at(37.0, 0.0), &opts);
|
||||
let (_, kept) = counted(&mut r, &d, at(37.0, 0.0), &opts);
|
||||
for (dx, dy) in [(74.0, 0.0), (74.0, -37.0), (296.0, -37.0), (0.0, 0.0), (-222.0, 37.0)] {
|
||||
let (image, made) = counted(&mut r, &d, at(dx, dy), &opts);
|
||||
assert_eq!(made, kept, "{name}: the pan to ({dx}, {dy}) drew the rasters kept");
|
||||
let mut fresh = Renderer::new();
|
||||
fresh.threads = 2;
|
||||
let still = fresh.render(&d, size.0, size.1, at(dx, dy), &opts);
|
||||
let worst = image.pixels.iter().zip(&still.pixels).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
|
||||
assert!(worst <= 1, "{name}: ({dx}, {dy}): a channel differs by {worst}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Scrolls by amounts that are not whole pixels, as the wheel and a trackpad give them, moved in whole pixels with the part left
|
||||
/// over carried to the next, as the canvas moves them: after the scroll that makes the Drop Shadow's cropped raster
|
||||
/// again with its margin, every later scroll draws it kept. The same scrolls moved as given make it again in every
|
||||
/// frame.
|
||||
#[test]
|
||||
fn fractional_scrolls_moved_in_whole_pixels_draw_a_cropped_raster_kept() {
|
||||
let size = (640, 360);
|
||||
let d = large_image(&[("stylize.dropShadow", json!({"blur": 20, "x": 7, "y": 7}))]);
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let at = |dx: f64, dy: f64| Affine::translate((320.0 + dx, 180.0 + dy)) * Affine::translate((-3000.0, -2000.0));
|
||||
let counted = |r: &mut Renderer, xf: Affine| {
|
||||
crate::OFFSCREEN_PIXELS.with(|n| n.set(0));
|
||||
r.render(&d, size.0, size.1, xf, &opts);
|
||||
crate::OFFSCREEN_PIXELS.with(|n| n.get())
|
||||
};
|
||||
let scrolls = [(0.37, 1.13), (-2.71, 0.0), (0.0, 0.45), (1.9, -0.83), (0.21, 0.21), (13.6, -4.4), (-0.5, 0.5), (7.77, 2.22)];
|
||||
for whole in [true, false] {
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&d, size.0, size.1, at(0.0, 0.0), &opts);
|
||||
// The scroll that makes the raster again with its margin, and the same view drawn again.
|
||||
r.render(&d, size.0, size.1, at(37.0, 0.0), &opts);
|
||||
let kept = counted(&mut r, at(37.0, 0.0));
|
||||
let (mut given, mut moved): ((f64, f64), (f64, f64)) = ((37.0, 0.0), (37.0, 0.0));
|
||||
let mut made_again = 0;
|
||||
for (k, (x, y)) in scrolls.into_iter().enumerate() {
|
||||
given = (given.0 + x, given.1 + y);
|
||||
moved = if whole { (given.0.round(), given.1.round()) } else { given };
|
||||
let made = counted(&mut r, at(moved.0, moved.1));
|
||||
if whole {
|
||||
assert_eq!(made, kept, "scroll {k} to {moved:?} drew the raster kept");
|
||||
} else if made > kept {
|
||||
made_again += 1;
|
||||
}
|
||||
}
|
||||
assert!((moved.0 - given.0).abs() <= 0.5 && (moved.1 - given.1).abs() <= 0.5, "moved {moved:?} for {given:?}");
|
||||
if !whole {
|
||||
assert_eq!(made_again, scrolls.len(), "scrolls by amounts that are not whole pixels make the raster again");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's shadow raster holds the shadows of the members outside the view: a pan that brings a member into view
|
||||
/// draws its shadow from the raster kept as a fresh renderer draws it, for a raster of the group's whole reach (two
|
||||
/// 100 pt squares) and for one cropped to the view and the margin a pan adds (two 3000 × 2000 pt rectangles).
|
||||
#[test]
|
||||
fn a_groups_shadow_raster_holds_the_members_outside_the_view() {
|
||||
let size = (640, 360);
|
||||
let blue = || Appearance::basic(Paint::solid(Color::rgb(0.1, 0.3, 0.9)), Paint::None, 0.0);
|
||||
// The two members, the point the view is centered on, and the pans after the first frame.
|
||||
let cases = [
|
||||
("whole", [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(600.0, 0.0, 700.0, 100.0)], (220.0, 50.0), vec![-300.0]),
|
||||
("cropped", [Rect::new(0.0, 0.0, 3000.0, 2000.0), Rect::new(3400.0, 0.0, 6400.0, 2000.0)], (3000.0, 1000.0), vec![-37.0, -237.0]),
|
||||
];
|
||||
let mut wrong = vec![];
|
||||
for (name, members, (cx, cy), pans) in cases {
|
||||
let mut d = Document::new(6400.0, 2000.0);
|
||||
let members = members.iter().map(|r| std::sync::Arc::new(Node::path(d.alloc_id(), shapes::rectangle(*r), blue()))).collect();
|
||||
let mut group = Node::group(d.alloc_id(), members);
|
||||
group.appearance.effects.push(Effect { id: "stylize.dropShadow".into(), params: json!({"blur": 20, "x": 7, "y": 7}), visible: true });
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, group).unwrap();
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let at = |dx: f64| Affine::translate((320.0 + dx, 180.0)) * Affine::translate((-cx, -cy));
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&d, size.0, size.1, at(0.0), &opts);
|
||||
for dx in pans {
|
||||
let image = r.render(&d, size.0, size.1, at(dx), &opts);
|
||||
let mut fresh = Renderer::new();
|
||||
fresh.threads = 2;
|
||||
if image.pixels != fresh.render(&d, size.0, size.1, at(dx), &opts).pixels {
|
||||
wrong.push(format!("{name}: panned by {dx}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
/// While interacting, a group with a member outside the view that only moved draws its shadow from the raster of the
|
||||
/// frame before, where a fresh renderer draws it: the moved silhouette holds that member too.
|
||||
#[test]
|
||||
fn a_moved_group_with_a_member_outside_the_view_draws_its_shadow_kept() {
|
||||
let size = (640, 360);
|
||||
let blue = || Appearance::basic(Paint::solid(Color::rgb(0.1, 0.3, 0.9)), Paint::None, 0.0);
|
||||
let mut base = Document::new(700.0, 100.0);
|
||||
let members = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(600.0, 0.0, 700.0, 100.0)]
|
||||
.iter()
|
||||
.map(|r| std::sync::Arc::new(Node::path(base.alloc_id(), shapes::rectangle(*r), blue())))
|
||||
.collect();
|
||||
let mut group = Node::group(base.alloc_id(), members);
|
||||
group.appearance.effects.push(Effect { id: "stylize.dropShadow".into(), params: json!({"blur": 20, "x": 7, "y": 7}), visible: true });
|
||||
let (id, layer) = (group.id, base.layers[0].id);
|
||||
base.insert(Some(layer), 0, group).unwrap();
|
||||
let view = Affine::translate((100.0, 130.0));
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let live = RenderOptions { interacting: true, ..opts.clone() };
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&base, size.0, size.1, view, &opts);
|
||||
let mut moved = base.clone();
|
||||
moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 2.0)), false);
|
||||
let frame = r.render(&moved, size.0, size.1, view, &live);
|
||||
assert!(r.stats.moved > 0, "drawn from the raster of the frame before");
|
||||
let mut fresh = Renderer::new();
|
||||
fresh.threads = 2;
|
||||
assert!(frame.pixels == fresh.render(&moved, size.0, size.1, view, &opts).pixels);
|
||||
}
|
||||
|
||||
/// A shadow made over an earlier cropped shadow covers only the rect the earlier one was made for. In a 2000 × 1200
|
||||
/// view of the image's right edge, the pixel budget gives the earlier shadow, which also covers what the later one
|
||||
/// reads 60 pixels below, a margin of 548 pixels and the later one 643: a pan of 600 pixels past the first makes both
|
||||
/// again, and the frame draws as a fresh renderer draws it.
|
||||
#[test]
|
||||
fn a_shadow_over_a_cropped_shadow_keeps_to_the_earlier_ones_margin() {
|
||||
let size = (2000, 1200);
|
||||
let effects = [("stylize.dropShadow", json!({"blur": 20, "x": 7, "y": 7})), ("stylize.dropShadow", json!({"blur": 10, "x": -5, "y": -60}))];
|
||||
let d = large_image(&effects);
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let at = |dy: f64| Affine::translate((1000.0, 600.0 + dy)) * Affine::translate((-6000.0, -2000.0));
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&d, size.0, size.1, at(0.0), &opts);
|
||||
r.render(&d, size.0, size.1, at(37.0), &opts);
|
||||
for dy in [37.0 - 600.0, 37.0 + 600.0] {
|
||||
let image = r.render(&d, size.0, size.1, at(dy), &opts);
|
||||
let mut fresh = Renderer::new();
|
||||
fresh.threads = 2;
|
||||
let still = fresh.render(&d, size.0, size.1, at(dy), &opts);
|
||||
let worst = image.pixels.iter().zip(&still.pixels).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
|
||||
assert_eq!(worst, 0, "panned to {dy}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Time a drag of the square over each backdrop in a 2560 × 1440 view: the first frame renders as
|
||||
/// before a drag, the next eight as a drag's frames (`interacting` and `dragging`, as the canvas
|
||||
/// renders them), then the frame after the drag. The hashes of that frame and of a fresh renderer's
|
||||
|
||||
Reference in New Issue
Block a user