Merge branch 'main' into codex/native-corner-styles

The ring stroke moved into draw::ring on main; its round-corner guard keeps this
branch's corner-style check. pt-BR.toml goes back to main's: translations are
added in storytold/craft-i18n, and this branch had renamed "Individual corners"
to "Ajustes da borda" (edge settings).
This commit is contained in:
FredApps committed 2026-11-28 07:47:21 +01:00
commit add4e27b4b
775 files changed
+71571 -11353

No files matched your search

+16
View File
@@ -117,6 +117,22 @@ pub(crate) fn replace(dst: &mut Pixmap, at: (i32, i32), src: &Pixmap, clip: Opti
fx::overlap_rows(dst, at, src, |dp, sp, r, c0| {
let Some((m, (mx, my))) = clip else { return dp.copy_from_slice(sp) };
let (mw, mh, my) = (i64::from(m.width()), i64::from(m.height()), r + i64::from(my));
// Most rows of a clip lie wholly inside it (or outside): copied (or kept) in one piece.
let cols = (dp.len() / 4) as i64;
let first = c0 + i64::from(mx);
if my >= 0
&& my < mh
&& first >= 0
&& first + cols <= mw
&& let Some(row) = m.data().get((my * mw + first) as usize..(my * mw + first + cols) as usize)
{
if row.iter().all(|k| *k == 255) {
return dp.copy_from_slice(sp);
}
if row.iter().all(|k| *k == 0) {
return;
}
}
for (c, (d, s)) in (c0..).zip(dp.chunks_exact_mut(4).zip(sp.chunks_exact(4))) {
let mx = c + i64::from(mx);
let k = if mx >= 0 && my >= 0 && mx < mw && my < mh { u32::from(m.data().get((my * mw + mx) as usize).copied().unwrap_or(0)) } else { 0 };
+126 -16
View File
@@ -56,20 +56,61 @@ fn view(scale: f64) -> View {
View { origin: (-10.0, -10.0), scale, width: (440.0 * scale) as u32, height: (240.0 * scale) as u32 }
}
/// Per row: the mean channel difference and how many pixels differ by more than 2. A band artifact
/// differs along a whole row; edge antialiasing may differ in a few pixels per edge (a curve
/// clipped at a band's edge rasterises a hair differently, most where it runs nearly level).
/// A pixel whose largest channel differs by at most this much between two renders is edge
/// antialiasing noise (a curve clipped at a band's edge rasterises a hair differently, most where
/// it runs level, as at the top of an ellipse), not a band artifact.
const NOISE: u8 = 24;
/// One row of two renders: the channel differences of the pixels above noise (see `NOISE`) summed
/// and divided by the whole row's channel count, so noise pixels add nothing but still count in
/// the denominator; and how many pixels differ by more than 2 at all. A band artifact differs along
/// a whole row, by more than noise.
fn row_stats(x: &[u8], y: &[u8]) -> (f64, usize) {
let mut sum = 0.0;
let mut off = 0;
for (p, q) in x.chunks(4).zip(y.chunks(4)) {
let worst = p.iter().zip(q).map(|(c, d)| c.abs_diff(*d)).max().unwrap_or(0);
if worst > 2 {
off += 1;
}
if worst > NOISE {
sum += p.iter().zip(q).map(|(c, d)| f64::from(c.abs_diff(*d))).sum::<f64>();
}
}
(sum / x.len().max(1) as f64, off)
}
fn row_diffs(a: &Pixmap, b: &Pixmap) -> Vec<(f64, usize)> {
let row = a.width() as usize * 4;
a.data()
.chunks(row)
.zip(b.data().chunks(row))
.map(|(x, y)| {
let sum: f64 = x.iter().zip(y).map(|(p, q)| f64::from(p.abs_diff(*q))).sum();
let off = x.chunks(4).zip(y.chunks(4)).filter(|(p, q)| p.iter().zip(*q).any(|(c, d)| c.abs_diff(*d) > 2)).count();
(sum / row as f64, off)
})
.collect()
a.data().chunks(row).zip(b.data().chunks(row)).map(|(x, y)| row_stats(x, y)).collect()
}
/// Whether a row passes: the original 0.25 limit on the mean from `row_stats`, and at most a
/// twentieth of the row differing at all.
fn row_ok(mean: f64, off: usize, width: usize) -> bool {
mean < 0.25 && off * 20 <= width
}
#[test]
fn a_real_band_artifact_fails_but_edge_noise_passes() {
let width = 880; // scale 2
let flat = vec![100u8; width * 4];
// 44 pixels whose colour channels differ by 60 (alpha unchanged): the mean is
// 44 * 3 * 60 / (880 * 4) = 2.25, and the count, 44, is within a twentieth of the row. A real
// artifact, so it fails on the mean.
let mut artifact = flat.clone();
for px in artifact.chunks_mut(4).take(44) {
px.iter_mut().take(3).for_each(|c| *c += 60);
}
let (mean, off) = row_stats(&flat, &artifact);
assert!(!row_ok(mean, off, width), "{mean} {off}");
// 8 pixels differing by 16 (the ellipse top's antialiasing): forgiven.
let mut noise = flat.clone();
for px in noise.chunks_mut(4).take(8) {
px.iter_mut().for_each(|c| *c += 16);
}
let (mean, off) = row_stats(&flat, &noise);
assert!(row_ok(mean, off, width), "{mean} {off}");
}
#[test]
@@ -82,10 +123,7 @@ fn bands_match_one_piece_rendering() {
let banded = render_bands(&d, p, &v, &Options::default(), bands).unwrap();
assert_eq!((banded.width(), banded.height()), (one.width(), one.height()));
for (y, (mean, off)) in row_diffs(&one, &banded).into_iter().enumerate() {
assert!(
mean < 0.25 && off * 20 <= v.width as usize,
"scale {scale}, {bands} bands: row {y} differs ({off} pixels, {mean:.2} on average)"
);
assert!(row_ok(mean, off, v.width as usize), "scale {scale}, {bands} bands: row {y} differs ({off} pixels, {mean:.2} on average)");
}
}
}
@@ -125,3 +163,75 @@ fn huge_backdrop_blur_renders_in_one_piece() {
assert!(render_bands(&d, p, &view(1.0), &Options::default(), 4).is_none());
assert!(render_view(&d, p, &view(1.0), &Options::default()).is_some());
}
/// [`row_diffs`] down the columns: an artifact of column bands runs down a whole column.
fn col_diffs(a: &Pixmap, b: &Pixmap) -> Vec<(f64, usize)> {
let (w, h) = (a.width() as usize, a.height() as usize);
let column = |p: &Pixmap, x: usize| -> Vec<u8> { (0..h).flat_map(|y| p.data()[(y * w + x) * 4..(y * w + x) * 4 + 4].to_vec()).collect() };
(0..w).map(|x| row_stats(&column(a, x), &column(b, x))).collect()
}
#[test]
fn columns_match_one_piece_rendering() {
let (d, p) = scene(true, true);
for scale in [1.0, 2.0] {
let v = view(scale);
let one = render_view_single(&d, p, &v, &Options::default()).unwrap();
for bands in [2, 3, 7] {
let banded = render_columns(&d, p, &v, &Options::default(), bands).unwrap();
assert_eq!((banded.width(), banded.height()), (one.width(), one.height()));
for (x, (mean, off)) in col_diffs(&one, &banded).into_iter().enumerate() {
assert!(
row_ok(mean, off, v.height as usize),
"scale {scale}, {bands} columns: column {x} differs ({off} pixels, {mean:.2} on average)"
);
}
}
}
let (mut d, p) = scene(true, true);
let g = d.find_by_name("Glass", None)[0];
d.get_mut(g).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(figcraft_doc::Blur::uniform(1e6)), visible: true }];
assert!(render_columns(&d, p, &view(1.0), &Options::default(), 4).is_none(), "a blur past a whole column: in one piece");
}
/// The strips a pan uncovers render in bands along their longer side, and match one piece: no row
/// or column where a band's edge shows (a seam differs along all of it). A strip is too narrow for
/// [`row_ok`]'s mean: the edge antialiasing every band render has (a few pixels along a curve)
/// outweighs it there, so this counts the pixels that differ at all.
#[test]
fn a_tall_or_wide_part_of_a_view_matches_one_piece_rendering() {
let (d, p) = scene(true, true);
for (w, h) in [(60, 480), (880, 60), (200, 200)] {
let v = View { origin: (35.0, -10.0), scale: 2.0, width: w, height: h };
let one = render_view_single(&d, p, &v, &Options::default()).unwrap();
let part = render_part(&d, p, &v, &Options::default()).unwrap();
assert_eq!((part.width(), part.height()), (w, h));
for (y, (_, off)) in row_diffs(&one, &part).into_iter().enumerate() {
assert!(off * 20 <= w as usize, "{w} x {h}: row {y} differs in {off} pixels");
}
for (x, (_, off)) in col_diffs(&one, &part).into_iter().enumerate() {
assert!(off * 20 <= h as usize, "{w} x {h}: column {x} differs in {off} pixels");
}
}
}
/// A textured layer scatters its pixels up to the texture's radius, past where a band cuts the
/// view; it is drawn off screen whole before it is cut, so column and row bands show it exactly as
/// one piece does, clipped to its shape or not.
#[test]
fn a_textured_layer_renders_the_same_in_bands() {
for clip_to_shape in [false, true] {
let mut d = Document::new("texture");
let p = d.first_page().unwrap();
let r = d.create(p, NodeKind::Rectangle, "T", 20.0, 20.0, 400.0, 200.0).unwrap();
let n = d.get_mut(r).unwrap();
n.fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())];
let texture = figcraft_doc::Texture { size: 0.5, radius: 12.0, clip_to_shape, ..Default::default() };
n.effects = vec![Effect { kind: EffectKind::Texture(texture), visible: true }];
let v = View { origin: (0.0, 0.0), scale: 1.7, width: 760, height: 400 };
let one = render_view_single(&d, p, &v, &Options::default()).unwrap();
for bands in [2, 3, 7] {
assert!(render_columns(&d, p, &v, &Options::default(), bands).unwrap().data() == one.data(), "{bands} columns");
assert!(render_bands(&d, p, &v, &Options::default(), bands).unwrap().data() == one.data(), "{bands} rows");
}
}
}
+29
View File
@@ -7,6 +7,11 @@
//! edited one are never recombined, and groups whose operands didn't change aren't recomputed at
//! all. The caches drop their least recently used half when full, so a long drag doesn't evict
//! every other group's result.
//!
//! The group's own corner radius is applied to the finished fold ([`result_cached`]) and cached in a
//! separate, smaller map keyed by the folded path plus the radius and smoothing: the fold's caches
//! are keyed by the operands alone, so scrubbing the radius never redoes the fold or evicts its
//! prefixes, and a rounded path is never stored where a fold would find it.
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
@@ -109,6 +114,30 @@ pub fn fold_cached(operands: &[(BezPath, BoolOp)]) -> Option<BezPath> {
}
}
fn rounded() -> &'static Mutex<PathCache> {
static C: OnceLock<Mutex<PathCache>> = OnceLock::new();
C.get_or_init(|| Mutex::new(PathCache::new(512)))
}
/// A boolean group's result as it is drawn: the fold of `operands` ([`fold_cached`]), then the
/// group's corner `radius` and `smoothing` on every corner still sharp.
pub fn result_cached(operands: &[(BezPath, BoolOp)], radius: f64, smoothing: f64) -> Option<BezPath> {
let folded = fold_cached(operands)?;
if !(radius.is_finite() && radius > 0.0) {
return Some(folded);
}
let mut h = DefaultHasher::new();
hash_path(&folded, &mut h);
(radius.to_bits(), smoothing.to_bits(), 0x52u8).hash(&mut h);
let key = h.finish();
if let Some(p) = locked(rounded()).get(key) {
return Some((*p).clone());
}
let out = figcraft_pathops::round_corners(&folded, radius, smoothing);
locked(rounded()).insert(key, Arc::new(out.clone()));
Some(out)
}
/// `keys[i]`: the cache key of the fold of operands `0..=i`.
fn fold_keys(operands: &[(BezPath, BoolOp)]) -> Vec<u64> {
let mut h = DefaultHasher::new();
+3 -3
View File
@@ -7,12 +7,12 @@ use figcraft_color::{Color, Paint};
use figcraft_doc::{BoolOp, Document, NodeId, NodeKind, WidthPoint, WidthProfile};
use figcraft_geom::kurbo::{BezPath, Shape};
fn dark(p: &Pixmap, x: u32, y: u32) -> bool {
pub(crate) fn dark(p: &Pixmap, x: u32, y: u32) -> bool {
let i = ((y * p.width() + x) * 4) as usize;
p.data().get(i).is_some_and(|r| *r < 40)
}
fn render(d: &Document, p: NodeId) -> Pixmap {
pub(crate) fn render(d: &Document, p: NodeId) -> Pixmap {
render_view(d, p, &View { origin: (0.0, 0.0), scale: 1.0, width: 200, height: 200 }, &Options::default()).unwrap()
}
@@ -28,7 +28,7 @@ fn row_of_squares(op: BoolOp, n: usize) -> (Document, NodeId, NodeId, Vec<NodeId
(d, p, b, kids)
}
fn outline(d: &Document, id: NodeId) -> BezPath {
pub(crate) fn outline(d: &Document, id: NodeId) -> BezPath {
node_outline(d, d.node(id).unwrap()).unwrap().0
}
+60
View File
@@ -0,0 +1,60 @@
//! A boolean group's corner radius: it rounds the result the canvas draws, and keys a cache of its
//! own so the fold underneath is not redone.
use crate::boolean::boolean_steps;
use crate::boolean_cache_tests::{dark, outline, render};
use figcraft_color::{Color, Paint};
use figcraft_doc::{BoolOp, Document, NodeId, NodeKind};
use figcraft_geom::kurbo::Shape;
/// The L of the measurement: a union of 200 by 100 and 100 by 200 rectangles, on a page of its own.
fn l_group() -> (Document, NodeId, NodeId, NodeId) {
let mut d = Document::new("t");
let p = d.first_page().unwrap();
let g = d.create(p, NodeKind::BooleanOp { op: BoolOp::Union }, "G", 0.0, 0.0, 0.0, 0.0).unwrap();
d.get_mut(g).unwrap().fills = vec![Paint::solid(Color::BLACK)];
d.create(g, NodeKind::Rectangle, "A", 0.0, 0.0, 200.0, 100.0).unwrap();
let b = d.create(g, NodeKind::Rectangle, "B", 150.0, 0.0, 100.0, 200.0).unwrap();
d.fit_to_children(g).unwrap();
(d, p, g, b)
}
fn set_radius(d: &mut Document, g: NodeId, r: f64) {
d.get_mut(g).unwrap().corners.radii = [r; 4];
}
fn area(d: &Document, g: NodeId) -> f64 {
outline(d, g).area().abs()
}
#[test]
fn a_boolean_groups_radius_rounds_what_the_canvas_draws() {
let (mut d, p, g, _) = l_group();
let pix = render(&d, p);
assert!(dark(&pix, 1, 1) && !dark(&pix, 148, 102));
set_radius(&mut d, g, 20.0);
let pix = render(&d, p);
assert!(!dark(&pix, 1, 1), "the corner is cut off");
assert!(dark(&pix, 148, 102), "the concave corner is filled in");
assert!(dark(&pix, 100, 50));
assert!((area(&d, g) - 34656.6).abs() < 1.0, "{}", area(&d, g));
}
#[test]
fn the_radius_keys_the_result_and_the_fold_is_not_redone() {
let (mut d, _, g, b) = l_group();
let sharp = outline(&d, g);
set_radius(&mut d, g, 20.0);
let _ = outline(&d, g);
let before = boolean_steps();
set_radius(&mut d, g, 40.0);
// Four net corners of 343.36 each, plus the cubic arcs' own slight excess over a circle.
assert!((area(&d, g) - 33626.6).abs() < 2.0, "{}", area(&d, g));
assert_eq!(boolean_steps(), before, "a new radius reuses the fold");
set_radius(&mut d, g, 0.0);
assert_eq!(outline(&d, g), sharp, "radius 0 draws the fold itself");
set_radius(&mut d, g, 20.0);
let rounded = area(&d, g);
d.get_mut(b).unwrap().transform = figcraft_geom::Affine::translate((10.0, 0.0)) * d.node(b).unwrap().transform;
assert!((area(&d, g) - rounded).abs() > 1.0, "moving an operand does not draw a stale rounded path");
}
+8
View File
@@ -91,3 +91,11 @@ fn kept_splat_answers_are_the_answers_worked_out_afresh() {
}
}
}
#[test]
fn ids_chosen_to_differ_only_in_high_bits_still_spread_over_buckets() {
use std::hash::BuildHasher;
let state = crate::draw::IdState::default();
let buckets: std::collections::HashSet<u64> = (0..4096u64).map(|k| state.hash_one(NodeId(k << 40)) & 0xfff).collect();
assert!(buckets.len() > 2000, "{}", buckets.len());
}
+119
View File
@@ -0,0 +1,119 @@
//! A clipping frame that takes in the whole pixmap cuts nothing off there: its children draw
//! without a layer, a mask or a copy back, and look the same.
use figcraft_color::{Color, Paint};
use figcraft_doc::{Document, NodeId, NodeKind};
use figcraft_geom::Affine;
use crate::draw::{NO_COVER_SHORTCUTS, clip_covers};
use crate::retained_tests::assert_same;
use crate::{Options, Pixmap, View, render_view_single};
fn white() -> Options {
Options { background: Some(Color::WHITE), ..Default::default() }
}
/// A screen (clipping) > a list (clipping) > a card (rounded, clipping) > a picture (rounded,
/// clipping) > a shape; the document, its page and the shape.
fn card() -> (Document, NodeId, NodeId) {
let fill = |d: &mut Document, id: NodeId, hex: &str| d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex(hex).unwrap())];
let mut d = Document::new("clips");
let page = d.first_page().unwrap();
let screen = d.create(page, NodeKind::Frame, "Screen", 470.0, 0.0, 390.0, 844.0).unwrap();
fill(&mut d, screen, "F4F6F5");
let list = d.create(screen, NodeKind::Frame, "List", 24.0, 261.0, 342.0, 312.0).unwrap();
let card = d.create(list, NodeKind::Frame, "Card", 0.0, 108.0, 342.0, 96.0).unwrap();
fill(&mut d, card, "FFFFFF");
d.get_mut(card).unwrap().corners.radii = [20.0; 4];
let picture = d.create(card, NodeKind::Frame, "Picture", 12.0, 12.0, 72.0, 72.0).unwrap();
fill(&mut d, picture, "CFE3DA");
d.get_mut(picture).unwrap().corners.radii = [14.0; 4];
let shape = d.create(picture, NodeKind::Polygon { count: 5 }, "Shape", 0.0, 23.0, 72.0, 49.0).unwrap();
fill(&mut d, shape, "7FAE9C");
(d, page, shape)
}
/// A `width` × `height` view at `scale` with the shape in the middle.
fn close_up(d: &Document, shape: NodeId, scale: f64, width: u32, height: u32) -> View {
let b = crate::draw::paint_bounds(d, shape).unwrap();
let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
View { origin: (cx - f64::from(width) / scale / 2.0, cy - f64::from(height) / scale / 2.0), scale, width, height }
}
/// The view rendered with and without the shortcut for clips that cut nothing.
fn both(d: &Document, page: NodeId, v: &View) -> (Pixmap, Pixmap) {
let new = render_view_single(d, page, v, &white()).unwrap();
NO_COVER_SHORTCUTS.with(|f| f.set(true));
let old = render_view_single(d, page, v, &white());
NO_COVER_SHORTCUTS.with(|f| f.set(false));
(new, old.unwrap())
}
#[test]
fn views_inside_and_across_clipping_frames_look_the_same() {
let (d, page, shape) = card();
let views = [
// Inside the card and its picture; across the picture's round corner; across the card's
// edge and the list's; the whole screen; on fractional pixels.
close_up(&d, shape, 38.66, 300, 200),
View { origin: (504.0, 440.0), scale: 9.0, width: 300, height: 260 },
View { origin: (480.0, 440.0), scale: 6.0, width: 400, height: 300 },
View { origin: (460.0, -10.0), scale: 0.5, width: 220, height: 440 },
View { origin: (500.37, 381.21), scale: 3.3, width: 300, height: 260 },
];
for v in &views {
let (new, old) = both(&d, page, v);
assert_same(&new, &old, &format!("{:?} at {}", v.origin, v.scale));
}
}
#[test]
fn a_rotated_frame_clips_as_it_did() {
let mut d = Document::new("rotated");
let page = d.first_page().unwrap();
let f = d.create(page, NodeKind::Frame, "F", 100.0, 100.0, 300.0, 200.0).unwrap();
d.get_mut(f).unwrap().fills = vec![Paint::solid(Color::from_hex("FFE0B0").unwrap())];
d.get_mut(f).unwrap().transform = figcraft_geom::set_rotation_about_center(d.node(f).unwrap().transform, 300.0, 200.0, 25.0);
let c = d.create(f, NodeKind::Rectangle, "C", -40.0, 40.0, 420.0, 60.0).unwrap();
d.get_mut(c).unwrap().fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())];
// The frame's middle (inside it whole), and its corner (cut by two edges).
for v in
[View { origin: (220.0, 170.0), scale: 4.0, width: 200, height: 160 }, View { origin: (60.0, 60.0), scale: 2.0, width: 300, height: 300 }]
{
let (new, old) = both(&d, page, &v);
assert_same(&new, &old, &format!("{:?}", v.origin));
}
}
#[test]
fn a_pixmap_in_a_round_corner_is_not_taken_in() {
let mut d = Document::new("corner");
let page = d.first_page().unwrap();
let f = d.create(page, NodeKind::Frame, "F", 0.0, 0.0, 200.0, 100.0).unwrap();
d.get_mut(f).unwrap().corners.radii = [40.0, 0.0, 0.0, 0.0];
let at = |d: &Document, x: f64, y: f64| clip_covers(d.node(f).unwrap(), Affine::translate((-x, -y)), (10, 10));
assert!(at(&d, 100.0, 40.0), "the middle");
assert!(at(&d, 190.0, 0.0), "a square corner, up to the edges");
assert!(!at(&d, 195.0, 0.0), "across the right edge");
assert!(!at(&d, 2.0, 2.0), "outside the arc of the round corner");
assert!(at(&d, 20.0, 20.0), "inside the arc");
assert!(!at(&d, 5.0, 20.0), "across the arc");
// A smoothed corner turns further along its edges: its whole square counts as cut off.
d.get_mut(f).unwrap().corners.smoothing = 0.6;
assert!(!at(&d, 20.0, 20.0), "smoothed: the corner's square is left out");
assert!(at(&d, 100.0, 40.0), "smoothed: the middle");
}
#[test]
fn a_view_inside_clipping_frames_holds_no_layer_for_them() {
let (d, page, shape) = card();
let v = close_up(&d, shape, 38.66, 600, 300);
let held = || crate::layer_budget::within(crate::layer_budget::BUDGET, || render_view_single(&d, page, &v, &Options::default())).1;
// The view lies inside the screen, the list, the card and the picture: none of their clips
// cuts it. Each held a copy of the view while its children drew.
assert_eq!(held(), 0, "no layer for a clip that cuts nothing");
NO_COVER_SHORTCUTS.with(|f| f.set(true));
let before = held();
NO_COVER_SHORTCUTS.with(|f| f.set(false));
assert!(before >= u64::from(v.width) * u64::from(v.height) * 4, "as it was: {before} bytes held");
}
+239 -53
View File
@@ -69,16 +69,37 @@ impl<'a> Bounds<'a> {
}
/// A hash map keyed by node ids, which need no SipHash: they are counters (or a peer's range of
/// them), and SipHash took a good part of a render.
type IdMap<K, V> = HashMap<K, V, std::hash::BuildHasherDefault<IdHash>>;
/// them), and SipHash took a good part of a render. A file can choose its ids, so each map is
/// seeded at random and the hash mixes its high bits down (ids differing only up high would
/// otherwise share a bucket).
type IdMap<K, V> = HashMap<K, V, IdState>;
/// Builds [`IdHash`]es from a per-map random seed.
#[derive(Clone)]
pub(crate) struct IdState(u64);
impl Default for IdState {
fn default() -> Self {
use std::hash::BuildHasher;
IdState(std::collections::hash_map::RandomState::new().hash_one(0u8))
}
}
impl std::hash::BuildHasher for IdState {
type Hasher = IdHash;
fn build_hasher(&self) -> IdHash {
IdHash(self.0)
}
}
/// Mixes each word in with a multiply (Fibonacci hashing), so ids that differ in low bits spread.
#[derive(Default)]
pub(crate) struct IdHash(u64);
impl Hasher for IdHash {
fn finish(&self) -> u64 {
self.0
// The multiply's low bits depend only on the input's low bits: mix the high ones down.
let h = (self.0 ^ (self.0 >> 32)).wrapping_mul(0xFF51_AFD7_ED55_8CCD);
h ^ (h >> 29)
}
fn write(&mut self, bytes: &[u8]) {
for b in bytes {
@@ -188,6 +209,48 @@ fn side_strokes(n: &Node) -> Option<Arc<BezPath>> {
}))
}
/// A plain stroke: no dashes, width profile or brush.
fn plain_stroke(n: &Node) -> bool {
let props = &n.stroke;
props.dashes.is_empty() && props.profile().is_none() && props.brush.is_none()
}
/// Whether a closed node's inside/outside stroke is an even-odd ring of two outlines ([`ring`]).
fn ring_stroke(n: &Node, closed: bool) -> bool {
let props = &n.stroke;
plain_stroke(n) && closed && props.align != StrokeAlign::Center
// An outside ring grows square corners as miters; other joins take the generic outline.
&& !(props.align == StrokeAlign::Outside && props.join != StrokeJoin::Miter && n.corners.radii.contains(&0.0))
}
/// A rect's or full ellipse's outline moved `inset` inwards (outwards when negative), `None` for
/// other shapes or one inset to nothing.
fn ring(n: &Node, inset: f64) -> Option<BezPath> {
let (x0, y0, ww, hh) = (inset, inset, n.width - 2.0 * inset, n.height - 2.0 * inset);
if ww <= 0.0 || hh <= 0.0 {
return None;
}
match n.kind {
NodeKind::Rectangle
| NodeKind::Frame
| NodeKind::Component { .. }
| NodeKind::ComponentSet { .. }
| NodeKind::Instance { .. }
| NodeKind::Section { .. }
if n.corners.style.is_round() && n.corners.smoothing == 0.0 =>
{
let radii = n.corners.radii.map(|r| if r > 0.0 { (r - inset).max(0.0) } else { 0.0 });
let mut p = figcraft_geom::rounded_rect(ww, hh, radii, 0.0);
p.apply_affine(Affine::translate((x0, y0)));
Some(p)
}
NodeKind::Ellipse { sweep, inner, .. } if figcraft_geom::full_sweep(sweep) && inner == 0.0 => {
Some(figcraft_geom::kurbo::Ellipse::from_rect(Rect::new(x0, y0, x0 + ww, y0 + hh)).to_path(0.05))
}
_ => None,
}
}
/// Stroke each side at its own weight, meeting its neighbours on the corner bisectors.
fn cut_side_strokes(n: &Node, path: &BezPath, sides: [f64; 4]) -> BezPath {
let band = |weight| figcraft_pathops::stroke_outline(path, &figcraft_doc::StrokeProps { weight, sides: None, ..n.stroke.clone() }, true);
@@ -219,44 +282,15 @@ fn cut_side_strokes(n: &Node, path: &BezPath, sides: [f64; 4]) -> BezPath {
/// The stroke area of a node in local coordinates.
pub fn stroke_area(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath> {
let props = &n.stroke;
if let Some(p) = side_strokes(n) {
return p;
}
// Rect/ellipse inside/outside strokes without booleans: an even-odd ring of two outlines.
if props.dashes.is_empty() && props.profile().is_none() && props.brush.is_none() && closed && props.align != StrokeAlign::Center
// An outside ring grows square corners as miters; other joins take the generic outline.
&& !(props.align == StrokeAlign::Outside && props.join != StrokeJoin::Miter && n.corners.radii.contains(&0.0))
{
let w = props.weight;
let ring = |inset: f64| -> Option<BezPath> {
let (x0, y0, ww, hh) = (inset, inset, n.width - 2.0 * inset, n.height - 2.0 * inset);
if ww <= 0.0 || hh <= 0.0 {
return None;
}
match n.kind {
NodeKind::Rectangle
| NodeKind::Frame
| NodeKind::Component { .. }
| NodeKind::ComponentSet { .. }
| NodeKind::Instance { .. }
| NodeKind::Section { .. }
if n.corners.style.is_round() && n.corners.smoothing == 0.0 =>
{
let radii = n.corners.radii.map(|r| if r > 0.0 { (r - inset).max(0.0) } else { 0.0 });
let mut p = figcraft_geom::rounded_rect(ww, hh, radii, 0.0);
p.apply_affine(Affine::translate((x0, y0)));
Some(p)
}
NodeKind::Ellipse { sweep, inner, .. } if figcraft_geom::full_sweep(sweep) && inner == 0.0 => {
Some(figcraft_geom::kurbo::Ellipse::from_rect(Rect::new(x0, y0, x0 + ww, y0 + hh)).to_path(0.05))
}
_ => None,
}
};
let (outer, inner) = match props.align {
StrokeAlign::Inside => (ring(0.0), ring(w)),
_ => (ring(-w), ring(0.0)),
if ring_stroke(n, closed) {
let w = n.stroke.weight;
let (outer, inner) = match n.stroke.align {
StrokeAlign::Inside => (ring(n, 0.0), ring(n, w)),
_ => (ring(n, -w), ring(n, 0.0)),
};
if let Some(mut o) = outer {
if let Some(i) = inner {
@@ -268,6 +302,54 @@ pub fn stroke_area(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath> {
cached_stroke_outline(n, path, closed)
}
/// What a closed node with outline `path` (filled by `rule`) fills under an inside or outside
/// stroke that hides what is under it: out to the middle of the stroke, so the fill neither shows
/// at the stroke's outer edge (a light fringe on an inside stroke) nor leaves a gap at its inner
/// edge (what is behind showing between an outside stroke and the fill) (#2635). `None`: fill
/// `path` as it is.
pub(crate) fn fill_to_stroke_middle(n: &Node, path: &BezPath, rule: FillRule) -> Option<(Arc<BezPath>, FillRule)> {
let props = &n.stroke;
let opaque = n
.strokes
.iter()
.rev()
.find(|p| p.visible && p.opacity > 0.0)
.is_some_and(|p| p.blend == BlendMode::Normal && p.opacity >= 1.0 && matches!(p.kind, PaintKind::Solid { color } if color.a >= 1.0));
if !(opaque && plain_stroke(n) && props.sides.is_none() && props.align != StrokeAlign::Center && n.has_visible_stroke()) {
return None;
}
let half = match props.align {
StrokeAlign::Inside => props.weight / 2.0,
_ => -props.weight / 2.0,
};
if ring_stroke(n, true)
&& let Some(r) = ring(n, half)
{
return Some((Arc::new(r), FillRule::Winding));
}
// shortcut: even-odd outlines (booleans, even-odd networks) keep filling as they are, until
// the boolean below reads them by their own rule.
if rule != FillRule::Winding {
return None;
}
let mut h = std::collections::hash_map::DefaultHasher::new();
hash_path(path, &mut h);
("fill to stroke middle", props.weight.to_bits(), props.align as u8, props.join as u8, props.miter_limit.to_bits()).hash(&mut h);
let key = h.finish();
let cached = locked(stroke_cache()).get(key);
let out = match cached {
Some(p) => p,
None => {
let centre = figcraft_pathops::stroke_center(path, props.weight, props);
let op = if half > 0.0 { figcraft_doc::BoolOp::Subtract } else { figcraft_doc::BoolOp::Union };
let p = Arc::new(figcraft_pathops::boolean_step(path, &centre, op).ok()?);
locked(stroke_cache()).insert(key, p.clone());
p
}
};
Some((out, FillRule::EvenOdd))
}
/// The stroke a boolean operand contributes: like [`stroke_area`], but never an even-odd ring
/// (boolean folding uses non-zero winding).
fn operand_stroke(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath> {
@@ -357,8 +439,9 @@ fn node_outline_at(doc: &Document, n: &Node, depth: usize) -> Option<(BezPath, F
Some((p, c.bool_op.unwrap_or(*op)))
})
.collect();
// Past the path operations' caps the group has no outline: it draws without its result.
crate::boolean::fold_cached(&operands).map(|p| (p, FillRule::EvenOdd))
// Past the path operations' caps the group has no outline: it draws without its result. The
// group's corner radius rounds what is still sharp in the fold.
crate::boolean::result_cached(&operands, n.corners.radii[0], n.corners.smoothing).map(|p| (p, FillRule::EvenOdd))
}
NodeKind::Text(_) => {
let (l, dy) = figcraft_text::layout_node(n)?;
@@ -559,6 +642,12 @@ pub(crate) const MAX_REACH: f64 = 1e12;
/// result (drop shadows from the blurred layer, a backdrop blurred with it), so the largest of
/// those reaches comes on top. Each reach counts up to [`MAX_REACH`], so the sum stays finite.
pub fn effect_margin(n: &Node) -> f64 {
margin_of(n, true)
}
/// [`effect_margin`], with or without what drop shadows reach (`drops`): shadows cast from the
/// layer's outline ([`shadow::outline_caster`]) read none of its pixels.
fn margin_of(n: &Node, drops: bool) -> f64 {
let visible = || n.effects.iter().filter(|e| e.visible);
let finite = |m: f64| if m.is_finite() { m.clamp(0.0, MAX_REACH) } else { 0.0 };
let layer: f64 = visible()
@@ -572,7 +661,9 @@ pub fn effect_margin(n: &Node) -> f64 {
let others = visible()
.map(|e| match &e.kind {
EffectKind::BackgroundBlur { .. } | EffectKind::Glass(_) => e.backdrop_radius() * 2.0,
EffectKind::DropShadow(s) => s.radius * 2.0 + s.spread.abs() * figcraft_doc::SPREAD_MITER_LIMIT + s.offset.0.abs() + s.offset.1.abs(),
EffectKind::DropShadow(s) if drops => {
s.radius * 2.0 + s.spread.abs() * figcraft_doc::SPREAD_MITER_LIMIT + s.offset.0.abs() + s.offset.1.abs()
}
// Inner shadows cast from around a layer's pixels (groups, image fills with alpha; any
// image counts here): a layer cut off at the view would cast one from the cut.
EffectKind::InnerShadow(s)
@@ -720,6 +811,16 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u
// Isolated layer covering the node's paint bounds, clipped to the visible area + margin. Its
// origin can be negative (inside the margin); the size counts from there, or a layer starting
// above or left of the pixmap came out short by the margin (a band missing at its far edge).
// Drop shadows cast from the layer's outline need none of its pixels: the layer then ends
// where the pixmap does (plus what its other effects read), however far the shadows reach.
let cast_outline = if ctx.lod || backdrop::has_effects(n) { None } else { shadow::outline_caster(ctx.doc, n) };
let view = match &cast_outline {
Some(_) => {
let m = (margin_of(n, false) * ctx.scale).min(MAX_EFFECT_MARGIN_PX);
Rect::new(0.0, 0.0, f64::from(pw), f64::from(ph)).inflate(m, m)
}
None => view,
};
let vis = dev.intersect(view);
let (x0, y0) = (vis.x0.floor(), vis.y0.floor());
let (w, h) = (vis.x1.ceil() - x0, vis.y1.ceil() - y0);
@@ -791,7 +892,16 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u
layer_effects(ctx, &mut layer, n, id, lxf);
}
// Drop shadows go under the layer, in effect-list order.
{
if let Some(outlines) = &cast_outline {
let cover = shadow::hiding_cover(ctx.doc, n);
for e in n.effects.iter().filter(|e| e.visible) {
if let EffectKind::DropShadow(s) = &e.kind
&& let Some((sh, at)) = shadow::outline_drop_shadow(outlines, cover.as_deref().unwrap_or(outlines), s, xf, ctx.scale, (pw, ph), op)
{
composite(pix, at, &sh, op, s.blend);
}
}
} else {
// Kept apart, the backdrop isn't in the layer yet: the shadows are cast from the content
// with the layer effects it will get (a copy only when it gets some).
let layer_fx =
@@ -896,6 +1006,16 @@ fn fill_vector_regions(ctx: &Ctx, pix: &mut Pixmap, n: &Node, network: &figcraft
}
}
/// Fills `n`'s closed outline `path` (by `rule`, drawn at `xf`) with `paints`, out to the middle of
/// a stroke that hides it ([`fill_to_stroke_middle`]).
fn fill_outline(ctx: &Ctx, pix: &mut Pixmap, n: &Node, paints: &[Paint], path: &BezPath, rule: FillRule, xf: Affine) {
let under = fill_to_stroke_middle(n, path, rule);
let (path, rule) = under.as_ref().map_or((path, rule), |(p, r)| (&**p, *r));
if let Some(tp) = ts_path(path) {
fill_with(pix, &tp, paints, n.width, n.height, xf, rule, ctx, None);
}
}
/// Fills, `over_fills`, children (clipped), strokes and text of a node, without opacity/effects.
fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize, over_fills: OverFills) {
let doc = ctx.doc;
@@ -942,8 +1062,8 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize,
// strokes on top.
for k in &keys {
let fills = layout.styles.get(*k).and_then(|s| s.fills.as_ref()).unwrap_or(&n.fills);
if let Some(tp) = by_style.get(k).and_then(ts_path) {
fill_with(pix, &tp, fills, w, h, gxf, FillRule::Winding, ctx, None);
if let Some(path) = by_style.get(k) {
fill_outline(ctx, pix, n, fills, path, FillRule::Winding, gxf);
}
for (_, item) in ink.iter().filter(|(style, _)| style == k) {
match item {
@@ -984,10 +1104,8 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize,
if !splatted && closed {
if let Some(network) = styled_network {
fill_vector_regions(ctx, pix, n, network, xf);
} else if let Some((path, rule)) = &outline
&& let Some(tp) = ts_path(path)
{
fill_with(pix, &tp, &n.fills, w, h, xf, *rule, ctx, None);
} else if let Some((path, rule)) = &outline {
fill_outline(ctx, pix, n, &n.fills, path, *rule, xf);
}
}
if let Some(f) = over_fills {
@@ -1127,6 +1245,12 @@ fn draw_children_clipped(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, dept
let (pw, ph) = (pix.width(), pix.height());
let dev = device_rect(xf, n.local_rect());
let Some(ir) = int_rect(dev, (pw, ph)) else { return };
// A clip that takes in the whole pixmap cuts nothing off here (a frame larger than the view,
// or than the band or patch of it being drawn): the children draw as they are.
if clip_covers(n, xf, (pw, ph)) {
draw_children(ctx, pix, n, xf, depth);
return;
}
let Some(_held) = crate::layer_budget::Held::take(ir.width(), ir.height(), 1) else { return };
let (lx, ly) = (ir.x(), ir.y());
// The layer starts as what lies under it and goes back in its place through the clip:
@@ -1135,7 +1259,7 @@ fn draw_children_clipped(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, dept
let Some(mut layer) = pix.clone_rect(ir) else { return };
let lxf = Affine::translate((-f64::from(lx), -f64::from(ly))) * xf;
let square_aligned = n.corners.uniform() == Some(0.0) && is_axis_aligned(xf);
let rect_clip = square_aligned && on_whole_pixels(dev);
let rect_clip = square_aligned && on_whole_pixels(dev, (pw, ph));
// The clip (a rectangular one on whole pixels is the layer's own box) is known before the
// children draw, so their backdrops are clipped the way the layer will be. An axis-aligned
// square frame with fractional edges gets an anti-aliased mask of its box so its edge pixels
@@ -1186,8 +1310,70 @@ fn fract_ok(_v: f64) -> bool {
true
}
/// Whether all four edges of the device rectangle `r` lie on whole pixels, up to the float noise
/// `snap_px` forgives.
fn on_whole_pixels(r: Rect) -> bool {
[r.x0, r.y0, r.x1, r.y1].into_iter().all(|v| (snap_px(v) - v.round()).abs() < 1e-9)
#[cfg(test)]
thread_local! {
/// Tests: no clip or shadow is skipped for taking in the whole pixmap ([`clip_covers`]).
pub(crate) static NO_COVER_SHORTCUTS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Whether the edges of the device rectangle `r` that cross a `size` pixmap lie on whole pixels,
/// up to the float noise `snap_px` forgives. An edge at or past the pixmap's own cuts no pixel
/// of it in part, wherever it lies.
fn on_whole_pixels(r: Rect, size: (u32, u32)) -> bool {
let whole = |v: f64| (snap_px(v) - v.round()).abs() < 1e-9;
let (w, h) = (f64::from(size.0), f64::from(size.1));
(r.x0 <= 0.0 || whole(r.x0)) && (r.y0 <= 0.0 || whole(r.y0)) && (r.x1 >= w || whole(r.x1)) && (r.y1 >= h || whole(r.y1))
}
/// Whether the box of frame `n` (its rounded corners cut off), drawn at `xf`, takes in every
/// pixel of a `size` pixmap: its clip then cuts nothing there. Errs towards `false`: smoothed
/// corners count as cut off square.
pub(crate) fn clip_covers(n: &Node, xf: Affine, size: (u32, u32)) -> bool {
#[cfg(test)]
if NO_COVER_SHORTCUTS.with(std::cell::Cell::get) {
return false;
}
let (w, h) = (n.width, n.height);
let det = xf.determinant();
if !(det.is_finite() && det.abs() > 1e-12 && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
return false;
}
let max_r = w.min(h) / 2.0;
let smooth = if n.corners.smoothing > 0.0 || !n.corners.smoothing.is_finite() { 1.0 } else { 0.0 };
// Top-left, top-right, bottom-right, bottom-left: the corner and its radius.
let r = n.corners.radii.map(|r| if r.is_finite() { r.clamp(0.0, max_r) } else { max_r });
let corners = [(0.0, 0.0, r[0]), (w, 0.0, r[1]), (w, h, r[2]), (0.0, h, r[3])];
let inside = |p: figcraft_geom::Point| {
if !(p.x >= 0.0 && p.y >= 0.0 && p.x <= w && p.y <= h) {
return false;
}
corners.iter().all(|(cx, cy, r)| {
let (dx, dy) = ((p.x - cx).abs(), (p.y - cy).abs());
let zone = r * (1.0 + smooth);
// Outside the corner's square, or (a round corner) within its arc.
dx >= zone || dy >= zone || (smooth == 0.0 && (r - dx).powi(2) + (r - dy).powi(2) <= r * r)
})
};
let inv = xf.inverse();
let (pw, ph) = (f64::from(size.0), f64::from(size.1));
[(0.0, 0.0), (pw, 0.0), (pw, ph), (0.0, ph)].into_iter().all(|p| inside(inv * figcraft_geom::Point::new(p.0, p.1)))
}
/// Whether point `p` (local) lies in the box of `n`, its rounded corners cut off. Errs towards
/// `false`: smoothed corners count as cut off square.
pub(crate) fn in_box(n: &Node, p: figcraft_geom::Point) -> bool {
let (w, h) = (n.width, n.height);
if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0 && p.x >= 0.0 && p.y >= 0.0 && p.x <= w && p.y <= h) {
return false;
}
let max_r = w.min(h) / 2.0;
let smooth = if n.corners.smoothing > 0.0 || !n.corners.smoothing.is_finite() { 1.0 } else { 0.0 };
// Top-left, top-right, bottom-right, bottom-left: the corner and its radius.
let r = n.corners.radii.map(|r| if r.is_finite() { r.clamp(0.0, max_r) } else { max_r });
[(0.0, 0.0, r[0]), (w, 0.0, r[1]), (w, h, r[2]), (0.0, h, r[3])].iter().all(|(cx, cy, r)| {
let (dx, dy) = ((p.x - cx).abs(), (p.y - cy).abs());
let zone = r * (1.0 + smooth);
// Outside the corner's square, or (a round corner) within its arc.
dx >= zone || dy >= zone || (smooth == 0.0 && (r - dx).powi(2) + (r - dy).powi(2) <= r * r)
})
}
+100
View File
@@ -242,6 +242,90 @@ pub fn tint(p: &mut Pixmap, color: [f32; 4]) {
}
}
/// What [`tint`] makes of each alpha: the premultiplied pixel of `color` at that coverage.
pub fn tints(color: [f32; 4]) -> [[u8; 4]; 256] {
let [r, g, b, a] = color;
let mut out = [[0u8; 4]; 256];
for (i, px) in out.iter_mut().enumerate() {
let alpha = i as f32 / 255.0 * a;
let q = |c: f32| (c * alpha * 255.0).round().clamp(0.0, 255.0) as u8;
*px = [q(r), q(g), q(b), (alpha * 255.0).round().clamp(0.0, 255.0) as u8];
}
out
}
/// `dst` from the alpha of `src`, tinted (see [`tints`]): `dst`'s pixel (0, 0) is `src`'s pixel
/// `at`; past `src`'s edges is empty.
pub fn copy_alpha(src: &Pixmap, dst: &mut Pixmap, at: (i32, i32), tints: &[[u8; 4]; 256]) {
let (sw, sh, dw) = (i64::from(src.width()), i64::from(src.height()), dst.width() as usize);
let s = src.data().as_chunks::<4>().0;
for (y, row) in dst.data_mut().as_chunks_mut::<4>().0.chunks_mut(dw.max(1)).enumerate() {
let sy = y as i64 + i64::from(at.1);
for (x, px) in row.iter_mut().enumerate() {
let sx = x as i64 + i64::from(at.0);
let a = if (0..sw).contains(&sx) && (0..sh).contains(&sy) { s.get((sy * sw + sx) as usize).map_or(0, |p| p[3]) } else { 0 };
*px = tints.get(usize::from(a)).copied().unwrap_or_default();
}
}
}
/// Steps between two samples of [`enlarge_alpha`] (a power of two: weights are whole numbers).
const LERP_STEPS: i64 = 256;
/// Where on a line of `len` samples position `at` lies: the sample before it and how far on to
/// the next it is, in [`LERP_STEPS`]; `None` further than a sample past either end.
fn lerp_at(at: f64, len: usize) -> Option<(i64, u32)> {
// Rounded to a step first: positions a float's noise apart then weigh the same.
let steps = (at * LERP_STEPS as f64).round();
if !(steps.is_finite() && steps >= -(LERP_STEPS as f64) && steps <= (len as f64) * LERP_STEPS as f64) {
return None;
}
let steps = steps as i64;
Some((steps.div_euclid(LERP_STEPS), steps.rem_euclid(LERP_STEPS) as u32))
}
/// `dst` from the alpha of `src` drawn larger, between its samples (bilinear), tinted (see
/// [`tints`]): `dst`'s pixel (0, 0) lies at position `at` among `src`'s pixel centres and each
/// pixel on is `step` of a `src` pixel further. Past `src`'s edges is empty.
pub fn enlarge_alpha(src: &Pixmap, dst: &mut Pixmap, at: (f64, f64), step: f64, tints: &[[u8; 4]; 256]) {
let (sw, sh, dw) = (src.width() as usize, src.height() as usize, dst.width() as usize);
if sw == 0 || sh == 0 || dw == 0 {
return;
}
let s = src.data().as_chunks::<4>().0;
let cols: Vec<Option<(i64, u32)>> = (0..dw).map(|x| lerp_at(at.0 + x as f64 * step, sw)).collect();
// One row of `src` between its samples, for every column of `dst`, in 1/256ths of 255.
let line = |y: i64, out: &mut [u32]| {
let row = usize::try_from(y).ok().filter(|y| *y < sh).and_then(|y| s.get(y * sw..(y + 1) * sw));
let a = |x: i64| row.and_then(|r| usize::try_from(x).ok().and_then(|x| r.get(x))).map_or(0, |p| u32::from(p[3]));
for (o, c) in out.iter_mut().zip(&cols) {
*o = c.map_or(0, |(x, t)| a(x) * (LERP_STEPS as u32 - t) + a(x + 1) * t);
}
};
let (mut top, mut bottom) = (vec![0u32; dw], vec![0u32; dw]);
let mut held: Option<i64> = None;
for (y, row) in dst.data_mut().as_chunks_mut::<4>().0.chunks_mut(dw).enumerate() {
let Some((sy, t)) = lerp_at(at.1 + y as f64 * step, sh) else {
row.fill([0; 4]);
continue;
};
if held != Some(sy) {
if held == Some(sy - 1) {
std::mem::swap(&mut top, &mut bottom);
} else {
line(sy, &mut top);
}
line(sy + 1, &mut bottom);
held = Some(sy);
}
let half = (LERP_STEPS * LERP_STEPS / 2) as u32;
for ((px, a), b) in row.iter_mut().zip(&top).zip(&bottom) {
let v = (a * (LERP_STEPS as u32 - t) + b * t + half) / (LERP_STEPS * LERP_STEPS) as u32;
*px = tints.get(v.min(255) as usize).copied().unwrap_or_default();
}
}
}
/// Invert the alpha (premultiplied white with alpha 1-a): used for inner shadows.
pub fn invert_alpha(p: &mut Pixmap) {
for px in p.data_mut().as_chunks_mut::<4>().0 {
@@ -261,6 +345,22 @@ pub fn mask_by(p: &mut Pixmap, m: &Pixmap, invert: bool) {
}
}
/// Hide the drop shadow `p` behind a layer that covers `cover` and draws `over` (alpha, times
/// `opacity`) on top of it, all the same size: a pixel keeps the part of the shadow outside the
/// cover, scaled up by what the layer lets through there. The layer's own pixel already shows its
/// share of a pixel along its edge, so cutting that share from the shadow as well would count the
/// edge twice: a light line where the edge lies over the shadow.
pub fn hide_behind(p: &mut Pixmap, cover: &Pixmap, over: &Pixmap, opacity: f32) {
let alpha = |px: &[u8]| f32::from(px.get(3).copied().unwrap_or(0)) / 255.0;
for ((px, c), o) in p.data_mut().as_chunks_mut::<4>().0.iter_mut().zip(cover.data().chunks_exact(4)).zip(over.data().chunks_exact(4)) {
let through = 1.0 - alpha(o) * opacity;
let keep = if through > 0.0 { ((1.0 - alpha(c)) / through).min(1.0) } else { 0.0 };
for v in px.iter_mut() {
*v = (f32::from(*v) * keep).round() as u8;
}
}
}
/// Call `f(dst_row, src_row, row, first_col)` for each row where `src`, with its top-left at `at`
/// on `dst`, overlaps it (premultiplied RGBA bytes of the overlapping columns; `row` and
/// `first_col` in `src`'s pixels). Nothing past either edge is visited.
+33
View File
@@ -125,3 +125,36 @@ fn a_frame_descriptor_bigger_than_the_canvas_is_refused_before_it_is_allocated()
assert!(images::decode_frames(&bytes).is_none());
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
}
#[test]
fn animated_gif_preserves_alpha_and_converts_to_display_p3() {
let bytes = gif(&[([0, 0, 0, 0], 100), (RED, 100)], 4, 4);
let frames = images::decode_frames(&bytes).unwrap();
assert_eq!(frames.len(), 2);
assert_eq!(frames[0].0.pixel(2, 2).unwrap().alpha(), 0);
assert_eq!(frames[1].0.pixel(2, 2).unwrap().alpha(), 255);
let anim = images::animation("gif-alpha-p3", Some(&data(bytes)), &ImageFilters::default(), ColorProfile::DisplayP3).unwrap();
assert_eq!(anim.len(), 2);
let mut d = Document::new("t");
d.color_profile = ColorProfile::DisplayP3;
let page = d.add_page("Page 1");
let id = d.create(page, NodeKind::Rectangle, "GIF", 0.0, 0.0, 4.0, 4.0).unwrap();
let p3_bytes = gif(&[([0, 0, 0, 0], 100), (RED, 100)], 4, 4);
d.images.insert("gif-alpha-p3-doc".to_string(), data(p3_bytes));
d.get_mut(id).unwrap().fills = vec![Paint::image("gif-alpha-p3-doc", ImageScaleMode::Fill)];
let f0 = crate::render_node(&d, id, 1.0).unwrap();
assert_eq!(f0.pixel(2, 2).unwrap().alpha(), 0);
let f1 = crate::render_node_at(&d, id, 1.0, 0.15).unwrap();
let px = f1.pixel(2, 2).unwrap();
assert!(px.red() < 250 && px.green() > 30 && px.alpha() == 255, "converted to P3: {px:?}");
}
#[test]
fn zero_size_gif_is_refused() {
let mut bytes = gif(&[(RED, 100), (GREEN, 100)], 4, 4);
bytes[6..10].copy_from_slice(&[0, 0, 0, 0]);
assert!(images::dimensions(&bytes).is_none());
assert!(images::decode(&bytes).is_none());
assert!(images::decode_frames(&bytes).is_none());
}
+83
View File
@@ -16,6 +16,61 @@ fn png(w: u32, h: u32) -> Vec<u8> {
out
}
fn asymmetric_jpeg() -> Vec<u8> {
let img = image::RgbImage::from_fn(24, 16, |x, y| {
image::Rgb(match (x < 12, y < 8) {
(true, true) => [220, 30, 40],
(false, true) => [20, 190, 50],
(true, false) => [30, 60, 210],
(false, false) => [230, 200, 20],
})
});
let mut out = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Jpeg).unwrap();
out
}
/// Add one EXIF orientation tag without changing the JPEG's compressed pixels.
fn jpeg_with_orientation(jpeg: &[u8], orientation: u16) -> Vec<u8> {
assert_eq!(&jpeg[..2], &[0xff, 0xd8]);
// EXIF header, little-endian TIFF header, and an IFD containing one SHORT orientation.
let mut exif = b"Exif\0\0II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0".to_vec();
exif.extend_from_slice(&orientation.to_le_bytes());
exif.extend_from_slice(&[0; 6]); // Inline value padding, then no next IFD.
let mut out = jpeg[..2].to_vec();
out.extend_from_slice(&[0xff, 0xe1]);
out.extend_from_slice(&u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
out.extend_from_slice(&exif);
out.extend_from_slice(&jpeg[2..]);
out
}
fn assert_jpeg_keeps_stored_pixels(orientation: u16) {
let jpeg = asymmetric_jpeg();
let oriented = jpeg_with_orientation(&jpeg, orientation);
let expected = images::decode(&jpeg).unwrap();
let actual = images::decode(&oriented).unwrap();
assert_eq!((expected.width(), expected.height()), (24, 16));
assert_eq!((actual.width(), actual.height()), (expected.width(), expected.height()));
assert_eq!(actual.data(), expected.data(), "EXIF orientation {orientation} must leave stored pixels in place");
let (expected, _) = images::decode_within(&jpeg, ColorProfile::Srgb, 12, u64::MAX).unwrap();
let (actual, _) = images::decode_within(&oriented, ColorProfile::Srgb, 12, u64::MAX).unwrap();
assert_eq!((expected.width(), expected.height()), (12, 8));
assert_eq!((actual.width(), actual.height()), (expected.width(), expected.height()));
assert_eq!(actual.data(), expected.data(), "thumbnail must keep stored pixels for EXIF orientation {orientation}");
}
#[test]
fn a_jpeg_with_exif_rotation_keeps_its_stored_pixels() {
assert_jpeg_keeps_stored_pixels(6);
}
#[test]
fn a_jpeg_with_exif_mirroring_keeps_its_stored_pixels() {
assert_jpeg_keeps_stored_pixels(2);
}
/// A PNG whose header claims `w` × `h` but which holds no pixel data at all.
fn png_header_only(w: u32, h: u32) -> Vec<u8> {
let mut ihdr = Vec::new();
@@ -137,3 +192,31 @@ fn filter_and_profile_variants_count_against_one_budget() {
}
}
}
#[test]
fn zero_size_and_corrupt_inputs_are_refused() {
let corrupt: [&[u8]; 6] = [b"", b"not an image", b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff\xe0", b"RIFF\x00\x00\x00\x00WEBP", b"GIF89a"];
for bytes in corrupt {
assert!(images::dimensions(bytes).is_none());
assert!(images::decode(bytes).is_none());
assert!(images::decode_within(bytes, ColorProfile::Srgb, 256, u64::MAX).is_none());
assert!(crate::image_profile::Source::of(bytes).name.is_none());
}
for (w, h) in [(0, 0), (0, 4), (4, 0)] {
let bad_png = png_header_only(w, h);
assert!(images::dimensions(&bad_png).is_none(), "{w}x{h}");
assert!(images::decode(&bad_png).is_none(), "{w}x{h}");
assert!(images::decode_within(&bad_png, ColorProfile::Srgb, 256, u64::MAX).is_none(), "{w}x{h}");
}
}
#[test]
fn dimensions_reads_valid_formats() {
let p = Pixmap::new(12, 7).unwrap();
let png_bytes = crate::encode_png(&p).unwrap();
let jpg_bytes = crate::encode_jpeg(&p, figcraft_color::Color::WHITE, 85).unwrap();
let webp_bytes = crate::encode_webp(&p).unwrap();
for bytes in [png_bytes, jpg_bytes, webp_bytes] {
assert_eq!(images::dimensions(&bytes), Some((12, 7)));
}
}
+42 -26
View File
@@ -7,7 +7,6 @@
use std::io::Cursor;
use figcraft_color::ColorProfile;
use image::{DynamicImage, ImageDecoder, ImageFormat, RgbaImage};
use moxcms::{Chromaticity, ColorPrimaries, DataColorSpace, Layout, ParsingOptions, ProfileText, ToneReprCurve, TransformOptions, XyY};
/// The most bytes an embedded profile may have; bigger ones are ignored.
@@ -30,41 +29,58 @@ impl Source {
Source { name: Some("sRGB".into()), profile: None }
}
/// The colour space of encoded image `bytes` (reads the headers only).
/// The colour space of encoded image `bytes` (reads the headers or embedded profile).
pub fn of(bytes: &[u8]) -> Source {
image::ImageReader::new(Cursor::new(bytes))
.with_guessed_format()
.ok()
.and_then(|r| r.into_decoder().ok())
.map(|mut dec| Source::read(bytes, &mut dec))
.unwrap_or_default()
}
/// The colour space `dec`, a decoder of `bytes`, says the image is in.
/// shortcut: GIF and BMP profiles and a PNG `cICP` without `iCCP` are ignored (taken as sRGB);
/// read them if such files turn up.
pub(crate) fn read(bytes: &[u8], dec: &mut impl ImageDecoder) -> Source {
let format = image::guess_format(bytes).ok();
if !matches!(format, Some(ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP | ImageFormat::Tiff)) {
let Some(format) = craft_image_codecs::detect(bytes) else {
return Source::default();
};
if !matches!(
format,
craft_image_codecs::Format::Png | craft_image_codecs::Format::Jpeg | craft_image_codecs::Format::WebP | craft_image_codecs::Format::Tiff
) {
return Source::default();
}
match dec.icc_profile() {
Ok(Some(icc)) => from_icc(&icc),
_ if format == Some(ImageFormat::Png) => png_chunks(bytes),
_ => Source::default(),
let icc = craft_image_codecs::embedded_icc(bytes).ok().flatten();
Source::from_decoded(bytes, icc.as_deref())
}
/// The colour space of `bytes` given the ICC profile returned by `craft-image-codecs`.
/// shortcut: GIF and BMP profiles and a PNG `cICP` without `iCCP` are ignored (taken as sRGB);
/// read them if such files turn up.
pub(crate) fn from_decoded(bytes: &[u8], icc: Option<&[u8]>) -> Source {
let Some(format) = craft_image_codecs::detect(bytes) else {
return Source::default();
};
if !matches!(
format,
craft_image_codecs::Format::Png | craft_image_codecs::Format::Jpeg | craft_image_codecs::Format::WebP | craft_image_codecs::Format::Tiff
) {
return Source::default();
}
match icc {
Some(icc) => from_icc(icc),
None if format == craft_image_codecs::Format::Png => png_chunks(bytes),
None => Source::default(),
}
}
/// `img` (decoded from this source) converted into `target`; `None` when it's taken as sRGB.
pub(crate) fn convert(&self, img: &DynamicImage, target: ColorProfile) -> Option<RgbaImage> {
/// Whether this source uses a greyscale ICC profile.
pub(crate) fn is_gray(&self) -> bool {
self.profile.as_ref().is_some_and(|p| p.color_space == DataColorSpace::Gray)
}
/// `pixels` (8-bit `GrayAlpha` when `is_gray`, else `Rgba`) converted into `target`; `None`
/// when it's taken as sRGB.
pub(crate) fn convert_u8(&self, w: u32, h: u32, is_gray: bool, pixels: &[u8], target: ColorProfile) -> Option<Vec<u8>> {
let src = self.profile.as_ref()?;
let grey = src.color_space == DataColorSpace::Gray;
if grey && img.color().has_color() {
if grey && !is_gray {
return None;
}
let (layout, pixels) = if grey { (Layout::GrayAlpha, img.to_luma_alpha8().into_raw()) } else { (Layout::Rgba, img.to_rgba8().into_raw()) };
let mut out = RgbaImage::new(img.width(), img.height());
src.create_transform_8bit(layout, &working(target), Layout::Rgba, TransformOptions::default()).ok()?.transform(&pixels, &mut out).ok()?;
let layout = if grey { Layout::GrayAlpha } else { Layout::Rgba };
let len = usize::try_from(w).ok()?.checked_mul(usize::try_from(h).ok()?)?.checked_mul(4)?;
let mut out = vec![0u8; len];
src.create_transform_8bit(layout, &working(target), Layout::Rgba, TransformOptions::default()).ok()?.transform(pixels, &mut out).ok()?;
Some(out)
}
}
+125
View File
@@ -237,6 +237,91 @@ fn grey_profiles() {
assert!(near(px[0], [188.0; 3], 2.0) && near(px[1], [255.0; 3], 1.0), "{px:?}");
}
/// A procedural 2 × 2 PNG; confirm the encoder and shared decoder keep every 16-bit sample.
fn png16(samples: &[u16], kind: ExtendedColorType, profile: Option<Vec<u8>>) -> Vec<u8> {
let raw: Vec<u8> = samples.iter().flat_map(|v| v.to_ne_bytes()).collect();
let mut bytes = Vec::new();
encode(image::codecs::png::PngEncoder::new(&mut bytes), &raw, 2, 2, kind, profile);
let decoded = craft_image_codecs::decode(&bytes).unwrap();
assert_eq!(decoded.sample_type(), craft_image_codecs::SampleType::U16);
assert_eq!(decoded.to_u16_samples().unwrap(), samples);
bytes
}
#[test]
fn rgba16_thumbnail_averages_before_quantizing() {
let bytes = png16(&[0, 0, 0, 65535, 256, 256, 256, 65535].repeat(2), ExtendedColorType::Rgba16, None);
let (p, _) = images::decode_within(&bytes, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert_eq!((p.width(), p.height()), (1, 1));
// Average 128 rounds to U8 zero. Quantizing first gives 0 and 1, whose average rounds to 1.
assert_eq!(p.data(), &[0, 0, 0, 255]);
}
#[test]
fn gray_alpha16_thumbnail_averages_before_quantizing_and_profile_conversion() {
let bytes = png16(&[0, 65535, 256, 65535].repeat(2), ExtendedColorType::La16, Some(icc(b"GRAY", "Linear grey", SRGB_D50, &Trc::Gamma(1.0))));
let source = Source::of(&bytes);
assert_eq!(source.name.as_deref(), Some("Linear grey"));
assert!(source.is_gray());
let (p, fallback) = images::decode_within(&bytes, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert!(!fallback, "the greyscale ICC profile must be used");
assert_eq!((p.width(), p.height()), (1, 1));
// Resize to grey 128, quantize to zero, then apply the existing 8-bit ICC transform.
assert_eq!(p.data(), &[0, 0, 0, 255]);
}
#[test]
fn gray_alpha16_thumbnail_keeps_alpha_precision_until_after_scaling() {
let bytes = png16(&[65535, 0, 65535, 256].repeat(2), ExtendedColorType::La16, Some(icc(b"GRAY", "Linear grey", SRGB_D50, &Trc::Gamma(1.0))));
assert!(Source::of(&bytes).is_gray());
let (p, fallback) = images::decode_within(&bytes, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert!(!fallback);
assert_eq!((p.width(), p.height()), (1, 1));
// Alpha averages to 128 and quantizes to zero, so premultiplication clears the white RGB.
assert_eq!(p.data(), &[0, 0, 0, 0]);
}
#[test]
fn u16_thumbnail_matches_previous_box_sampling_at_nonintegral_ratio() {
// For 16→14, the legacy floating-point edge includes source pixel 8 in output pixel 6.
for (w, h, limit) in [(7, 5, 4), (16, 1, 14)] {
let source = image::ImageBuffer::from_fn(w, h, |x, y| image::Rgb([if x == 8 { u16::MAX } else { 0 }, 1500 * y as u16, 4000 * x as u16]));
let raw: Vec<u8> = source.as_raw().iter().flat_map(|sample| sample.to_ne_bytes()).collect();
let mut bytes = Vec::new();
encode(image::codecs::png::PngEncoder::new(&mut bytes), &raw, w, h, ExtendedColorType::Rgb16, None);
let expected = image::DynamicImage::ImageRgb16(source).thumbnail(limit, limit).to_rgba8();
let (p, _) = images::decode_within(&bytes, ColorProfile::Srgb, limit, u64::MAX).unwrap();
assert_eq!((p.width(), p.height()), expected.dimensions());
assert_eq!(p.data(), expected.as_raw(), "{w}×{h} with side limit {limit}");
}
}
#[test]
fn u16_thumbnail_handles_a_source_rectangle_larger_than_a_u32_sum() {
let (w, h) = (257, 257);
let samples = vec![u8::MAX; w as usize * h as usize * 2];
let mut bytes = Vec::new();
encode(image::codecs::png::PngEncoder::new(&mut bytes), &samples, w, h, ExtendedColorType::L16, None);
let (p, _) = images::decode_within(&bytes, ColorProfile::Srgb, 1, 512 << 20).unwrap();
assert_eq!((p.width(), p.height()), (1, 1));
assert_eq!(p.data(), &[255; 4]);
}
#[test]
fn full_size_u16_images_keep_the_existing_quantization() {
let rgba = png16(&[0, 256, 32768, 65535].repeat(4), ExtendedColorType::Rgba16, None);
let p = images::decode(&rgba).unwrap();
assert_eq!((p.width(), p.height()), (2, 2));
assert_eq!(p.data(), &[0, 1, 128, 255].repeat(4));
let grey = png16(&[0, 256].repeat(4), ExtendedColorType::La16, Some(icc(b"GRAY", "Linear grey", SRGB_D50, &Trc::Gamma(1.0))));
let p = images::decode(&grey).unwrap();
assert_eq!((p.width(), p.height()), (2, 2));
assert_eq!(p.data(), &[0, 0, 0, 1].repeat(4));
}
#[test]
fn unusable_profiles_fall_back_to_srgb() {
let img = samples();
@@ -334,3 +419,43 @@ fn profile_parser_survives_junk() {
let _ = Source::of(b"");
let _ = Source::of(&[0x89, b'P', b'N', b'G']);
}
#[test]
fn f32_thumbnail_averages_before_quantizing() {
let samples = [0.0_f32, 0.0, 0.0, 1.0, 0.002, 0.002, 0.002, 1.0].repeat(2);
let raw: Vec<u8> = samples.iter().flat_map(|v| v.to_ne_bytes()).collect();
let img = craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::F32, raw).unwrap();
let exr = craft_image_codecs::encode(&img, craft_image_codecs::Format::OpenExr, &craft_image_codecs::EncodeOptions::default()).unwrap();
let (p, _) = images::decode_within(&exr, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert_eq!((p.width(), p.height()), (1, 1));
// Average 0.001 * 255 = 0.255 rounds to 0; quantizing first rounds 0.002 * 255 = 0.51 to 1,
// whose 8-bit average rounds to 1.
assert_eq!(p.data(), &[0, 0, 0, 255]);
}
#[test]
fn non_finite_f32_and_f16_thumbnails_clamp_like_full_size_decode() {
let samples = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 1.0, 1.0, f32::NEG_INFINITY, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0];
let raw: Vec<u8> = samples.iter().flat_map(|v| v.to_ne_bytes()).collect();
let f32_img =
craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::F32, raw).unwrap();
let f16_img = f32_img.convert(craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::F16);
for (label, img) in [("f32", f32_img), ("f16", f16_img)] {
let exr = craft_image_codecs::encode(&img, craft_image_codecs::Format::OpenExr, &craft_image_codecs::EncodeOptions::default()).unwrap();
let (full, _) = images::decode_within(&exr, ColorProfile::Srgb, 2, u64::MAX).unwrap();
assert_eq!(&full.data()[..4], &[0, 255, 0, 255], "{label} full-size pixel 0");
let (thumb, _) = images::decode_within(&exr, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert_eq!((thumb.width(), thumb.height()), (1, 1), "{label} thumb dimensions");
assert_eq!(thumb.data(), &[191, 64, 64, 255], "{label} thumb pixels");
}
let nan_alpha = [1.0_f32, 1.0, 1.0, f32::NAN, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0];
let alpha_raw: Vec<u8> = nan_alpha.iter().flat_map(|v| v.to_ne_bytes()).collect();
let alpha_img =
craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::F32, alpha_raw).unwrap();
let alpha_exr =
craft_image_codecs::encode(&alpha_img, craft_image_codecs::Format::OpenExr, &craft_image_codecs::EncodeOptions::default()).unwrap();
let (alpha_thumb, _) = images::decode_within(&alpha_exr, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert_eq!(alpha_thumb.data(), &[191, 191, 191, 191]);
}
+171 -46
View File
@@ -13,6 +13,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
use craft_image_codecs::{ChannelLayout, SampleType};
use figcraft_color::{ColorProfile, ImageFilters, PaintKind};
use figcraft_doc::{Document, ImageData, NodeId};
use tiny_skia::Pixmap;
@@ -33,7 +34,7 @@ const MAX_CACHED_IMAGES: usize = 256;
/// The largest sides of the copies the canvas draws larger images from while they show smaller
/// (device pixels): two 16 000 × 10 000 images take 640 MB each in full, past the cache's budget
/// together, and 42 MB each at 4096 (168 MB at 8192).
pub const DISPLAY_SIDES: [u32; 2] = [4096, 8192];
pub const DISPLAY_SIDES: [u32; 6] = [256, 512, 1024, 2048, 4096, 8192];
/// Decoded pixmaps by image, filters and profile, holding at most a byte budget of pixels: adding
/// one past the budget (or past [`MAX_CACHED_IMAGES`]) drops the least recently used first, so
@@ -117,28 +118,167 @@ fn decode_in(bytes: &[u8], target: ColorProfile) -> Option<(Pixmap, bool)> {
/// from their header, before any pixels are decoded), scaled down to at most `max_side` wide and
/// tall.
pub(crate) fn decode_within(bytes: &[u8], target: ColorProfile, max_side: u32, max_bytes: u64) -> Option<(Pixmap, bool)> {
use image::ImageDecoder;
if figcraft_format::jpeg::finer_than_first(bytes) {
return None;
}
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(max_bytes);
reader.limits(limits);
let mut dec = reader.into_decoder().ok()?;
if dec.total_bytes() > max_bytes {
let opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits::new(u32::MAX, u32::MAX, u64::MAX, max_bytes),
keep_orientation: true,
};
let img = craft_image_codecs::decode_with(bytes, &opts).ok()?;
let source = crate::image_profile::Source::from_decoded(bytes, img.icc.as_deref());
let is_gray = source.is_gray() && img.layout().is_gray();
let layout = if is_gray { ChannelLayout::GrayA } else { ChannelLayout::Rgba };
let original = img.dimensions();
let (w, h) = thumbnail_size(original.0, original.1, max_side)?;
let pixels =
if original != (w, h) && matches!(img.layout(), ChannelLayout::Gray | ChannelLayout::GrayA | ChannelLayout::Rgb | ChannelLayout::Rgba) {
match img.sample_type() {
SampleType::U16 => {
let thumbnail = thumbnail_u16(&img, w, h)?;
drop(img);
thumbnail.convert(layout, SampleType::U8).into_data()
}
SampleType::F16 | SampleType::F32 => {
let f32_img = (img.sample_type() == SampleType::F16).then(|| img.converted(img.layout(), SampleType::F32).into_owned());
let src = f32_img.as_ref().unwrap_or(&img);
let thumbnail = thumbnail_f32(src, w, h)?;
drop(f32_img);
drop(img);
thumbnail.convert(layout, SampleType::U8).into_data()
}
SampleType::U8 => {
let converted = img.converted(layout, SampleType::U8);
thumbnail_u8(original, (w, h), is_gray, converted.into_owned().into_data())?
}
}
} else {
let converted = img.converted(layout, SampleType::U8);
thumbnail_u8(original, (w, h), is_gray, converted.into_owned().into_data())?
};
if is_gray {
let rgba = source.convert_u8(w, h, true, &pixels, target)?;
return Some((premultiplied_rgba(w, h, &rgba)?, false));
}
match source.convert_u8(w, h, false, &pixels, target) {
Some(rgba) => Some((premultiplied_rgba(w, h, &rgba)?, false)),
None => Some((premultiplied_rgba(w, h, &pixels)?, true)),
}
}
/// Dimensions of a nonempty, aspect-fit thumbnail within the requested side limit.
fn thumbnail_size(w: u32, h: u32, max_side: u32) -> Option<(u32, u32)> {
if w == 0 || h == 0 {
return None;
}
let source = crate::image_profile::Source::read(bytes, &mut dec);
let mut img = image::DynamicImage::from_decoder(dec).ok()?;
if img.width() > max_side || img.height() > max_side {
// `thumbnail` keeps the aspect ratio and works in integers (no float copy of the pixels).
img = img.thumbnail(max_side, max_side);
if w <= max_side && h <= max_side {
return Some((w, h));
}
match source.convert(&img, target) {
Some(rgba) => Some((premultiplied(&rgba)?, false)),
None => Some((premultiplied(&img.to_rgba8())?, true)),
let ratio = (f64::from(max_side) / f64::from(w)).min(f64::from(max_side) / f64::from(h));
let nw = (f64::from(w) * ratio).round().max(1.0) as u32;
let nh = (f64::from(h) * ratio).round().max(1.0) as u32;
Some((nw, nh))
}
/// Scale `pixels` in GrayA or RGBA layout.
fn thumbnail_u8((w, h): (u32, u32), (nw, nh): (u32, u32), is_gray: bool, pixels: Vec<u8>) -> Option<Vec<u8>> {
if (w, h) == (nw, nh) {
return Some(pixels);
}
if is_gray {
let buf = image::ImageBuffer::<image::LumaA<u8>, _>::from_raw(w, h, pixels)?;
Some(image::imageops::thumbnail(&buf, nw, nh).into_raw())
} else {
let buf = image::RgbaImage::from_raw(w, h, pixels)?;
Some(image::imageops::thumbnail(&buf, nw, nh).into_raw())
}
}
/// Keep the old thumbnail's floating-point box boundaries. Every axis scales down, so
/// a rounding edge case still needs at least one source sample.
fn source_span(index: u32, input: u32, ratio: f32) -> std::ops::Range<usize> {
let offset = index as f32 * ratio;
let start = (offset.ceil() as u32).min(input - 1);
let end = ((offset + ratio).ceil() as u32).clamp(start + 1, input);
start as usize..end as usize
}
/// Average native samples within each thumbnail pixel's source rectangle. Use wide sums
/// because a large reduction can overflow the image crate's U16 thumbnail accumulator.
fn thumbnail_u16(img: &craft_image_codecs::Image, nw: u32, nh: u32) -> Option<craft_image_codecs::Image> {
let (w, h) = img.dimensions();
let layout = img.layout();
let channels = layout.channels();
let pixel_bytes = channels * 2;
let row_bytes = (w as usize).checked_mul(pixel_bytes)?;
let output_bytes = (nw as usize).checked_mul(nh as usize)?.checked_mul(pixel_bytes)?;
let mut data = Vec::new();
data.try_reserve_exact(output_bytes).ok()?;
let rows = img.data().chunks_exact(row_bytes);
let x_ratio = w as f32 / nw as f32;
let y_ratio = h as f32 / nh as f32;
for y in 0..nh {
let y_span = source_span(y, h, y_ratio);
let band = rows.clone().skip(y_span.start).take(y_span.len());
for x in 0..nw {
let x_span = source_span(x, w, x_ratio);
let bytes = x_span.start * pixel_bytes..x_span.end * pixel_bytes;
let count = x_span.len() as u64 * y_span.len() as u64;
let mut sums = [0_u64; 4];
for row in band.clone() {
for pixel in row.get(bytes.clone())?.chunks_exact(pixel_bytes) {
for (sum, sample) in sums.iter_mut().zip(pixel.as_chunks::<2>().0) {
*sum += u64::from(u16::from_ne_bytes(*sample));
}
}
}
for sum in sums.iter().take(channels) {
let sample = ((sum + count / 2) / count) as u16;
data.extend_from_slice(&sample.to_ne_bytes());
}
}
}
craft_image_codecs::Image::from_raw(nw, nh, layout, SampleType::U16, data).ok()
}
/// Average native `f32` samples within each thumbnail pixel's source rectangle before
/// quantizing to 8-bit, clamping non-finite and out-of-range samples to `[0, 1]` like full-size
/// decode so `NaN` or cancelling infinities cannot poison a block.
fn thumbnail_f32(img: &craft_image_codecs::Image, nw: u32, nh: u32) -> Option<craft_image_codecs::Image> {
let (w, h) = img.dimensions();
let layout = img.layout();
let channels = layout.channels();
let pixel_bytes = channels * 4;
let row_bytes = (w as usize).checked_mul(pixel_bytes)?;
let output_bytes = (nw as usize).checked_mul(nh as usize)?.checked_mul(pixel_bytes)?;
let mut data = Vec::new();
data.try_reserve_exact(output_bytes).ok()?;
let rows = img.data().chunks_exact(row_bytes);
let x_ratio = w as f32 / nw as f32;
let y_ratio = h as f32 / nh as f32;
for y in 0..nh {
let y_span = source_span(y, h, y_ratio);
let band = rows.clone().skip(y_span.start).take(y_span.len());
for x in 0..nw {
let x_span = source_span(x, w, x_ratio);
let bytes = x_span.start * pixel_bytes..x_span.end * pixel_bytes;
let count = (x_span.len() * y_span.len()) as f64;
let mut sums = [0.0_f64; 4];
for row in band.clone() {
for pixel in row.get(bytes.clone())?.chunks_exact(pixel_bytes) {
for (sum, sample) in sums.iter_mut().zip(pixel.as_chunks::<4>().0) {
let v = f32::from_ne_bytes(*sample);
*sum += if v.is_nan() { 0.0 } else { f64::from(v.clamp(0.0, 1.0)) };
}
}
}
for sum in sums.iter().take(channels) {
let sample = (sum / count) as f32;
data.extend_from_slice(&sample.to_ne_bytes());
}
}
}
craft_image_codecs::Image::from_raw(nw, nh, layout, SampleType::F32, data).ok()
}
/// Whether image `hash`, decoded as `pm`, has no transparent pixels (filters and colour profiles
@@ -178,14 +318,13 @@ pub fn profile_name(hash: &str, data: Option<&ImageData>) -> Option<String> {
name
}
/// Straight RGBA → a premultiplied pixmap (max 16k per side).
fn premultiplied(rgba: &image::RgbaImage) -> Option<Pixmap> {
let (w, h) = rgba.dimensions();
/// Straight RGBA8 → a premultiplied pixmap (max 16k per side).
fn premultiplied_rgba(w: u32, h: u32, rgba: &[u8]) -> Option<Pixmap> {
if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE {
return None;
}
let mut p = Pixmap::new(w, h)?;
for (dst, src) in p.data_mut().as_chunks_mut::<4>().0.iter_mut().zip(rgba.as_raw().chunks_exact(4)) {
for (dst, src) in p.data_mut().as_chunks_mut::<4>().0.iter_mut().zip(rgba.chunks_exact(4)) {
let a = u32::from(src.get(3).copied().unwrap_or(255));
let pm = |c: u8| ((u32::from(c) * a + 127) / 255) as u8;
dst.copy_from_slice(&[
@@ -289,33 +428,20 @@ pub fn frame_secs(numer: u32, denom: u32) -> f64 {
/// big for one frame within [`MAX_ANIMATION_BYTES`]. A damaged frame ends the animation there.
/// shortcut: GIFs always loop (their repeat count is ignored); read it if a one-shot GIF matters.
pub fn decode_frames(bytes: &[u8]) -> Option<Vec<(Pixmap, f64)>> {
use image::{AnimationDecoder, ImageDecoder};
if image::guess_format(bytes).ok()? != image::ImageFormat::Gif {
let mut limits = craft_gif::frames::FrameLimits::default();
limits.max_frames = MAX_FRAMES;
limits.max_bytes = MAX_ANIMATION_BYTES;
limits.max_canvas_bytes = MAX_ANIMATION_BYTES;
let anim = craft_gif::frames::read_frames(bytes, &limits).ok()?;
if anim.frames.len() <= 1 || anim.width > MAX_SIDE || anim.height > MAX_SIDE {
return None;
}
let mut dec = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(bytes)).ok()?;
let (w, h) = dec.dimensions();
let frame_bytes = u64::from(w) * u64::from(h) * 4;
if frame_bytes == 0 || w > MAX_SIDE || h > MAX_SIDE {
return None;
let mut out = Vec::with_capacity(anim.frames.len());
for f in anim.frames {
let pm = premultiplied_rgba(anim.width, anim.height, &f.rgba)?;
out.push((pm, frame_secs(f.delay_ms, 1)));
}
// A frame's own descriptor can ask for a far larger buffer than the canvas: the decoder
// reserves each frame and canvas buffer against these limits before allocating it.
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_SIDE);
limits.max_image_height = Some(MAX_SIDE);
// The decoder charges its canvas, its composited output and the partial frame against this
// together, besides the frames kept (capped by `most` below): one frame of working room.
limits.max_alloc = Some(MAX_ANIMATION_BYTES.saturating_add(frame_bytes));
dec.set_limits(limits).ok()?;
let most = (MAX_ANIMATION_BYTES / frame_bytes).min(MAX_FRAMES as u64) as usize;
let mut out = Vec::new();
for f in dec.into_frames().take(most) {
let Ok(f) = f else { break };
let (n, d) = f.delay().numer_denom_ms();
out.push((premultiplied(f.buffer())?, frame_secs(n, d)));
}
(out.len() > 1).then_some(out)
Some(out)
}
type AnimKey = (String, [i32; 7], ColorProfile);
@@ -432,8 +558,7 @@ pub fn apply_filters(p: &mut Pixmap, f: &ImageFilters) {
/// Read an image's pixel size without keeping the decode.
pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
let reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
reader.into_dimensions().ok()
craft_image_codecs::probe_size(bytes).ok()
}
/// `pm` with a transparent 1-pixel border.
+7 -6
View File
@@ -8,7 +8,7 @@ use figcraft_color::{ImageScaleMode, Paint};
use figcraft_doc::{Document, ImageData, NodeId, NodeKind};
use tiny_skia::Pixmap;
use crate::images::{self, DISPLAY_SIDES, MAX_CACHED_BYTES};
use crate::images::{self, MAX_CACHED_BYTES};
use crate::{Options, View, render_view};
const W: u32 = 6000;
@@ -63,12 +63,11 @@ fn sharp_stripes(p: &Pixmap, y: u32, black_first: bool, each: u32) -> bool {
#[test]
fn zoomed_out_the_canvas_draws_both_images_from_copies_that_stay_decoded() {
let (d, page, keys) = doc("zoomed-out");
// At 25% each shows 1500 px long: drawn from 4096 px copies, not decoded in full.
render_view(&d, page, &view(0.25), &canvas()).unwrap();
let first = keys.each_ref().map(|k| shown(&d, k, 1500.0));
for (k, p) in keys.iter().zip(&first) {
assert_eq!((p.width(), p.height()), (DISPLAY_SIDES[0], 5), "{k}");
assert_eq!(images::cached_sides(k), vec![DISPLAY_SIDES[0]], "{k}: only its copy is decoded");
assert_eq!((p.width(), p.height()), (2048, 3), "{k}");
assert_eq!(images::cached_sides(k), vec![2048], "{k}: only its copy is decoded");
}
// Drawn again (a drag, a pan), both are still the copies decoded the first time.
render_view(&d, page, &view(0.25), &canvas()).unwrap();
@@ -93,13 +92,15 @@ fn exports_and_close_ups_draw_from_the_image_itself() {
#[test]
fn the_copy_is_the_smallest_that_holds_what_shows() {
let side = |long, shown| images::display_side(long, shown);
assert_eq!(side(6000, 1500.0), 4096);
assert_eq!(side(6000, 1500.0), 2048);
assert_eq!(side(16_000, 4096.0), 4096);
assert_eq!(side(16_000, 4097.0), 8192);
assert_eq!(side(4096, 100.0), 256);
assert_eq!(side(3000, 20.0), 256);
// Shown at more than the largest copy, or an image no larger than the copy: the image itself.
assert_eq!(side(16_000, 9000.0), 16_384);
assert_eq!(side(6000, 5000.0), 16_384);
assert_eq!(side(4096, 100.0), 16_384);
assert_eq!(side(200, 100.0), 16_384);
// An unknown size or a meaningless scale: the image itself.
assert_eq!(side(0, 100.0), 16_384);
assert_eq!(side(16_000, f64::NAN), 16_384);
+203 -36
View File
@@ -138,6 +138,58 @@ pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) ->
render_one(doc, page, view, opts)
}
/// [`render_view`] for a part of a view a retained render redraws (the strips a pan uncovers, the
/// area of an edit): in parallel bands however few pixels it has, along its longer side (rows of a
/// tall strip, columns of a wide one), since what it costs is the layers it crosses (a shadow is
/// drawn whole for a sliver of it), not its pixels.
pub(crate) fn render_part(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option<Pixmap> {
start_render();
#[cfg(not(target_arch = "wasm32"))]
if let Some(pool) = band_pool() {
let threads = pool.current_num_threads().clamp(1, 16) as u32;
let rendered = if view.height >= view.width {
let bands = threads.min(view.height / 96);
(bands > 1).then(|| pool.install(|| render_bands(doc, page, view, opts, bands))).flatten()
} else {
let bands = threads.min(view.width / 96);
(bands > 1).then(|| pool.install(|| render_columns(doc, page, view, opts, bands))).flatten()
};
if rendered.is_some() {
return rendered;
}
}
render_one(doc, page, view, opts)
}
/// [`render_bands`] across: `bands` columns, overlapping by what background blurs read.
#[cfg(not(target_arch = "wasm32"))]
fn render_columns(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option<Pixmap> {
use rayon::prelude::*;
let band_w = view.width.div_ceil(bands.max(1));
let overlap = band_overlap(doc, view, band_w)?;
let s = view.scale.max(1e-9);
let parts: Vec<(u32, Option<Pixmap>)> = (0..bands)
.into_par_iter()
.map(|i| {
let x0 = i * band_w;
let w = band_w.min(view.width.saturating_sub(x0)).max(1);
let left = x0.saturating_sub(overlap);
let right = (x0 + w + overlap).min(view.width).max(x0 + w);
let v =
View { origin: (view.origin.0 + f64::from(left) / s, view.origin.1), scale: view.scale, width: right - left, height: view.height };
let own = tiny_skia::IntRect::from_xywh((x0 - left) as i32, 0, w, view.height.clamp(1, 16_384));
(x0, render_one(doc, page, &v, opts).zip(own).and_then(|(p, r)| p.clone_rect(r)))
})
.collect();
let mut out = new_pixmap(view.width, view.height)?;
let copy = tiny_skia::PixmapPaint { blend_mode: tiny_skia::BlendMode::Source, ..Default::default() };
for (x0, part) in parts {
let part = part?;
out.draw_pixmap(x0 as i32, 0, part.as_ref(), &copy, tiny_skia::Transform::identity(), None);
}
Some(out)
}
/// The stack a thread that renders needs (#1082). A level of the layer tree takes about 6.5 KB of
/// stack in a render (6.8 KB in a debug build), so the deepest render [`MAX_EXPORT_DEPTH`] allows,
/// pattern sources included, needs about 1.7 MB: more than the 2 MiB threads get by default once
@@ -266,11 +318,11 @@ fn render_one(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Opti
/// Render several nodes (in z-order) into an existing pixmap through `view`.
pub fn render_nodes_into(doc: &Document, ids: &[NodeId], view: &View, pix: &mut Pixmap) {
nodes_into(doc, ids, view, pix, 0.0);
nodes_into(doc, ids, view, pix, 0.0, None);
}
/// [`render_nodes_into`] `time` seconds into animated GIFs.
fn nodes_into(doc: &Document, ids: &[NodeId], view: &View, pix: &mut Pixmap, time: f64) {
fn nodes_into(doc: &Document, ids: &[NodeId], view: &View, pix: &mut Pixmap, time: f64, under: Option<&backdrop::Under>) {
let bounds = draw::Bounds::default();
let ctx = draw::Ctx {
doc,
@@ -282,7 +334,7 @@ fn nodes_into(doc: &Document, ids: &[NodeId], view: &View, pix: &mut Pixmap, tim
lod: false,
preview: false,
magnified_image_pixels: false,
under: None,
under,
time,
bounds: &bounds,
};
@@ -341,9 +393,47 @@ pub fn raster_bounds(doc: &Document, id: NodeId) -> Option<Rect> {
}
/// The page-space rectangle a node exports: a clipping frame's box (plus its own effects), else
/// everything it paints.
/// everything it paints. Each layer counts the fill and stroke outlines it draws (see
/// [`drawn_bounds`]), so a stroke inside its frame leaves the export the frame's size; the
/// renderer's own bounds ([`Document::world_render_bounds`]) only bound how far a stroke can reach.
pub fn export_bounds(doc: &Document, id: NodeId) -> Option<Rect> {
doc.world_render_bounds(id)
doc.world_render_bounds_with(id, &|n, world| drawn_bounds(doc, n, world).unwrap_or_else(|| n.own_paint_bounds(world)))
}
/// The page area `n` paints itself under `world` (its children aside), measured on the outlines
/// it draws: its fill's and its stroke's (joins, caps and alignment as drawn), grown by its
/// effects. A dashed stroke counts as a solid one too, so where the dashes fall doesn't change the
/// size, and as its dashes, whose square ends can stand out past it round a curve. `None` where
/// those outlines don't cover what it paints: text (glyphs and their
/// strokes), a layer without an outline of its own, and drop shadows whose spread grows the
/// outline (see [`figcraft_doc::Node::outline_spreads`]).
fn drawn_bounds(doc: &Document, n: &figcraft_doc::Node, world: Affine) -> Option<Rect> {
if matches!(n.kind, NodeKind::Text(_)) || n.outline_spreads().next().is_some() {
return None;
}
let shape = match n.kind {
NodeKind::BooleanOp { .. } => node_outline(doc, n).map(|(p, _)| p),
_ => figcraft_doc::geometry::shape_path(n),
};
let stroke = stroke_fill(doc, n).map(|(p, _)| p);
let solid = (!n.stroke.dashes.is_empty())
.then(|| {
let mut undashed = n.clone();
undashed.stroke.dashes.clear();
stroke_fill(doc, &undashed).map(|(p, _)| p)
})
.flatten();
let placed = |p: &figcraft_geom::BezPath| {
use figcraft_geom::kurbo::Shape;
let mut p = p.clone();
p.apply_affine(world);
(!p.elements().is_empty()).then(|| p.bounding_box())
};
let drawn = [shape.as_ref().and_then(placed), stroke.as_deref().and_then(placed), solid.as_deref().and_then(placed)]
.into_iter()
.flatten()
.reduce(|a, b| a.union(b))?;
Some(n.grow_by_effects(drawn))
}
/// Rasterise one node at `scale` (export). Transparent background.
@@ -353,16 +443,29 @@ pub fn render_node(doc: &Document, id: NodeId, scale: f64) -> Option<Pixmap> {
/// [`render_node`] `time` seconds into animated GIFs (the presenter plays them).
pub fn render_node_at(doc: &Document, id: NodeId, scale: f64, time: f64) -> Option<Pixmap> {
area_at(doc, &[id], export_bounds(doc, id)?, scale, time)
area_at(doc, &[id], None, export_bounds(doc, id)?, scale, time)
}
/// Rasterise `ids` (bottom to top) over page area `b` at `scale` (export): the image starts at the
/// area's top-left and its sides round up to whole pixels. `None` past 16384 pixels a side.
pub fn render_area(doc: &Document, ids: &[NodeId], b: Rect, scale: f64) -> Option<Pixmap> {
area_at(doc, ids, b, scale, 0.0)
area_at(doc, ids, None, b, scale, 0.0)
}
fn area_at(doc: &Document, ids: &[NodeId], b: Rect, scale: f64, time: f64) -> Option<Pixmap> {
/// [`render_area`] `time` seconds into animated GIFs (the presenter plays them).
pub fn render_area_at(doc: &Document, ids: &[NodeId], b: Rect, scale: f64, time: f64) -> Option<Pixmap> {
area_at(doc, ids, None, b, scale, time)
}
/// [`render_area`] for an export of layers that sit among `page_layers` (the page's top-level
/// layers, in z-order): a background blur or glass in `ids` reads what lies under the first of
/// them on that page, clipped to the area (#2213). Only `ids` are drawn; the layers above stay
/// out. Without such an effect it is [`render_area`].
pub fn render_area_over(doc: &Document, ids: &[NodeId], page_layers: &[NodeId], b: Rect, scale: f64) -> Option<Pixmap> {
area_at(doc, ids, Some(page_layers), b, scale, 0.0)
}
fn area_at(doc: &Document, ids: &[NodeId], page_layers: Option<&[NodeId]>, b: Rect, scale: f64, time: f64) -> Option<Pixmap> {
let scale = if scale.is_finite() && scale > 0.0 { scale.min(64.0) } else { 1.0 };
let w = (b.width() * scale - 1e-6).ceil().max(1.0);
let h = (b.height() * scale - 1e-6).ceil().max(1.0);
@@ -371,7 +474,31 @@ fn area_at(doc: &Document, ids: &[NodeId], b: Rect, scale: f64, time: f64) -> Op
}
let view = View { origin: (b.x0, b.y0), scale, width: w as u32, height: h as u32 };
let mut pix = new_pixmap(view.width, view.height)?;
nodes_into(doc, ids, &view, &mut pix, time);
// What the backdrop effects read: the page under the first layer, with the margin they reach.
let reach = page_layers.and_then(|_| {
ids.iter()
.flat_map(|i| doc.subtree(*i))
.filter_map(|i| doc.node(i))
.filter(|n| n.visible && backdrop::has_effects(n))
.map(|n| backdrop::pad(n, scale))
.max()
});
let beneath = match (page_layers, ids.first(), reach) {
(Some(layers), Some(first), Some(m)) => {
let m = i32::try_from(m).unwrap_or(0);
let p = f64::from(m) / scale;
let around = View {
origin: (b.x0 - p, b.y0 - p),
scale,
width: view.width.saturating_add(m.unsigned_abs() * 2),
height: view.height.saturating_add(m.unsigned_abs() * 2),
};
backdrop::render_beneath(doc, layers, *first, &around).map(|back| (back, m))
}
_ => None,
};
let under = beneath.as_ref().map(|(back, m)| backdrop::Under::new(back, (*m, *m), None));
nodes_into(doc, ids, &view, &mut pix, time, under.as_ref());
Some(pix)
}
@@ -401,25 +528,35 @@ pub fn to_srgb(pix: &mut Pixmap, profile: ColorProfile) {
profile.conversion_to(ColorProfile::Srgb).apply_pixels(pix.data_mut());
}
/// Write `pixels` with `enc`, embedding `icc` when given.
fn write_encoded(
mut enc: impl image::ImageEncoder,
pixels: &[u8],
p: &Pixmap,
kind: image::ExtendedColorType,
icc: Option<Vec<u8>>,
) -> Result<(), String> {
if let Some(icc) = icc {
enc.set_icc_profile(icc).map_err(|e| e.to_string())?;
}
enc.write_image(pixels, p.width(), p.height(), kind).map_err(|e| e.to_string())
/// Encode `img` with `craft_image_codecs` into `format`.
fn encode_with_codec(
img: &craft_image_codecs::Image,
format: craft_image_codecs::Format,
opts: &craft_image_codecs::EncodeOptions,
) -> Result<Vec<u8>, String> {
craft_image_codecs::encode(img, format, opts).map_err(|e| e.to_string())
}
/// Encode as PNG, with an `iCCP` chunk when `icc` is given.
fn png_with(p: &Pixmap, icc: Option<Vec<u8>>) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
write_encoded(image::codecs::png::PngEncoder::new(&mut out), &to_rgba8(p), p, image::ExtendedColorType::Rgba8, icc)?;
Ok(out)
/// Build a `craft_image_codecs::Image` from straight RGBA8 or RGB8 bytes.
fn codec_image(
p: &Pixmap,
layout: craft_image_codecs::ChannelLayout,
data: Vec<u8>,
icc: Option<Vec<u8>>,
cicp: Option<craft_image_codecs::Cicp>,
) -> Result<craft_image_codecs::Image, String> {
let mut img = craft_image_codecs::Image::from_u8(p.width(), p.height(), layout, data).map_err(|e| e.to_string())?;
img.icc = icc;
img.cicp = cicp;
Ok(img)
}
/// Encode as PNG, with an `iCCP` chunk (and optional `cICP` chunk) when given.
fn png_with(p: &Pixmap, icc: Option<Vec<u8>>, cicp: Option<craft_image_codecs::Cicp>) -> Result<Vec<u8>, String> {
let embed_icc = icc.is_some();
let img = codec_image(p, craft_image_codecs::ChannelLayout::Rgba, to_rgba8(p), icc, cicp)?;
let opts = craft_image_codecs::EncodeOptions { embed_icc, embed_metadata: false, ..Default::default() };
encode_with_codec(&img, craft_image_codecs::Format::Png, &opts)
}
/// Encode as JPEG over `background` (JPEG has no alpha), with an ICC profile when given.
@@ -435,22 +572,29 @@ fn jpeg_with(p: &Pixmap, background: Color, quality: u8, icc: Option<Vec<u8>>) -
rgb.push(((s * a + b * (255 - a) + 127) / 255) as u8);
}
}
let mut out = Vec::new();
let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100));
write_encoded(enc, &rgb, p, image::ExtendedColorType::Rgb8, icc)?;
Ok(out)
let embed_icc = icc.is_some();
let img = codec_image(p, craft_image_codecs::ChannelLayout::Rgb, rgb, icc, None)?;
let opts = craft_image_codecs::EncodeOptions {
jpeg_quality: quality.clamp(1, 100),
jpeg_chroma_subsampling: false, // Preserve full chroma resolution from before the shared codec cutover.
embed_icc,
embed_metadata: false,
..Default::default()
};
encode_with_codec(&img, craft_image_codecs::Format::Jpeg, &opts)
}
/// Encode as lossless WebP, with an ICC profile when given.
fn webp_with(p: &Pixmap, icc: Option<Vec<u8>>) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
write_encoded(image::codecs::webp::WebPEncoder::new_lossless(&mut out), &to_rgba8(p), p, image::ExtendedColorType::Rgba8, icc)?;
Ok(out)
let embed_icc = icc.is_some();
let img = codec_image(p, craft_image_codecs::ChannelLayout::Rgba, to_rgba8(p), icc, None)?;
let opts = craft_image_codecs::EncodeOptions { webp_lossless: true, embed_icc, embed_metadata: false, ..Default::default() };
encode_with_codec(&img, craft_image_codecs::Format::WebP, &opts)
}
/// Encode as PNG (untagged).
pub fn encode_png(p: &Pixmap) -> Result<Vec<u8>, String> {
png_with(p, None)
png_with(p, None, None)
}
/// Encode as JPEG over `background` (JPEG has no alpha).
@@ -477,8 +621,17 @@ pub fn encode_export_with(p: &Pixmap, format: ExportFormat, profile: ColorProfil
let icc = (!profile.is_srgb()).then(|| profile.icc());
match format {
ExportFormat::Png => {
let png = png_with(p, icc)?;
Ok(if profile.is_srgb() { png_insert_chunk(png, b"sRGB", &[0]) } else { png_insert_chunk(png, b"cICP", &profile.cicp()) })
let cicp = (!profile.is_srgb()).then(|| {
let [primaries, transfer, matrix, full_range] = profile.cicp();
craft_image_codecs::Cicp {
primaries: u16::from(primaries),
transfer: u16::from(transfer),
matrix: u16::from(matrix),
full_range: full_range != 0,
}
});
let png = png_with(p, icc, cicp)?;
Ok(if profile.is_srgb() { png_insert_chunk(png, b"sRGB", &[0]) } else { png })
}
ExportFormat::Jpg => jpeg_with(p, Color::WHITE, quality, Some(profile.icc())),
ExportFormat::Webp => webp_with(p, icc),
@@ -518,8 +671,12 @@ mod boolean_budget_tests;
#[cfg(test)]
mod boolean_cache_tests;
#[cfg(test)]
mod boolean_radius_tests;
#[cfg(test)]
mod bounds_memo_tests;
#[cfg(test)]
mod clip_cover_tests;
#[cfg(test)]
mod dots_tests;
#[cfg(test)]
mod effect_order_tests;
@@ -554,8 +711,12 @@ mod magnified_image_tests;
#[cfg(test)]
mod mask_bounds_tests;
#[cfg(test)]
mod outline_shadow_tests;
#[cfg(test)]
mod paint_behaviour_tests;
#[cfg(test)]
mod pan_bench_tests;
#[cfg(test)]
mod progressive_tests;
#[cfg(test)]
mod render_depth_tests;
@@ -566,12 +727,18 @@ mod retained_tests;
#[cfg(test)]
mod rtl_list_tests;
#[cfg(test)]
mod shadow_silhouette_tests;
#[cfg(test)]
mod solo_tests;
#[cfg(test)]
mod spread_tests;
#[cfg(test)]
mod stroke_fringe_tests;
#[cfg(test)]
mod stroke_reach_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod width_tests;
#[cfg(test)]
mod zoom_bench_tests;
+212
View File
@@ -0,0 +1,212 @@
//! Drop shadows cast from a layer's outline ([`crate::shadow::outline_caster`]) look as the ones
//! cast from its pixels do, in every piece a view is rendered in, and cost what shows of them.
use figcraft_color::{Color, Paint};
use figcraft_doc::{EffectKind, NodeId, Shadow};
use crate::shadow::FROM_PIXELS;
use crate::zoom_bench_tests::{Card, SCALE, card, close_up};
use crate::{Options, Pixmap, View, render_band, render_view_single};
fn white() -> Options {
Options { background: Some(Color::WHITE), ..Default::default() }
}
/// The view rendered with shadows cast from outlines, and from pixels (as they all were).
fn both(c: &Card, v: &View) -> (Pixmap, Pixmap) {
let new = render_view_single(&c.doc, c.page, v, &white()).unwrap();
FROM_PIXELS.with(|f| f.set(true));
let old = render_view_single(&c.doc, c.page, v, &white());
FROM_PIXELS.with(|f| f.set(false));
(new, old.unwrap())
}
/// The largest difference of a channel between two renders of view `v`, under the card: where
/// only its shadow paints. (The card's own edges differ a little with where a layer's pixmap
/// ends, whatever casts the shadow: curves are flattened from where the pixmap cuts them.)
fn furthest(v: &View, a: &Pixmap, b: &Pixmap) -> u8 {
let from = (((CARD_BOTTOM - v.origin.1) * v.scale).ceil() as usize + 2) * v.width as usize * 4;
assert!(from < a.data().len(), "the view shows what is under the card");
a.data().iter().zip(b.data()).skip(from).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0)
}
/// The card's bottom edge on the page.
const CARD_BOTTOM: f64 = 465.0;
fn shadow_of(c: &mut Card, f: impl FnOnce(&mut Shadow)) {
for e in &mut c.doc.get_mut(c.card).unwrap().effects {
if let EffectKind::DropShadow(s) = &mut e.kind {
f(s);
return;
}
}
}
/// The card's bottom-left corner and the shadow under it, `scale` device pixels a unit.
fn corner(scale: f64) -> View {
View { origin: (480.0, 440.0), scale, width: (50.0 * scale) as u32, height: (40.0 * scale) as u32 }
}
fn darkest(p: &Pixmap) -> u8 {
p.data().as_chunks::<4>().0.iter().map(|c| c[0]).min().unwrap_or(255)
}
#[test]
fn a_shadow_blurred_little_is_the_one_cast_from_the_layers_pixels() {
let mut c = card(true);
// A blur of 3 device pixels: drawn at full resolution, a dark shadow so it shows.
shadow_of(&mut c, |s| (s.radius, s.color) = (6.0, Color { a: 0.8, ..Color::BLACK }));
for scale in [1.0, 1.37] {
let (new, old) = both(&c, &corner(scale));
assert!(darkest(&new) < 120, "a shadow shows at {scale}");
assert_eq!(furthest(&corner(scale), &new, &old), 0, "at {scale}");
}
}
#[test]
fn a_shadow_blurred_widely_looks_as_the_one_cast_from_the_layers_pixels() {
for (spread, offset, behind) in [(0.0, (0.0, 4.0), false), (3.0, (2.5, 4.0), false), (-2.0, (0.0, 6.0), false), (0.0, (0.0, 4.0), true)] {
let mut c = card(true);
shadow_of(&mut c, |s| {
(s.spread, s.offset, s.show_behind, s.color) = (spread, offset, behind, Color { a: 0.8, ..Color::BLACK });
});
// A frame's shadow spreads from its outline when it clips (from its pixels otherwise).
c.doc.get_mut(c.card).unwrap().clip = spread != 0.0;
if behind {
// What shows of a shadow behind its layer: through a see-through picture, not the card.
let n = c.doc.get_mut(c.card).unwrap();
n.fills = vec![Paint::solid(Color::WHITE)];
}
// Blurs of 16 to 309 device pixels: drawn 4 to 64 times smaller.
for scale in [4.0, 9.3, SCALE] {
let v = if scale == SCALE { View { origin: (488.0, 452.0), scale, width: 700, height: 900 } } else { corner(scale) };
let (new, old) = both(&c, &v);
assert!(darkest(&new) < 200, "a shadow shows at {scale}");
let d = furthest(&v, &new, &old);
assert!(d <= 4, "spread {spread}, offset {offset:?}, behind {behind}, at {scale}: {d} apart");
}
}
}
#[test]
fn bands_and_one_piece_draw_the_same_wide_shadow() {
let mut c = card(true);
shadow_of(&mut c, |s| s.color = Color { a: 0.8, ..Color::BLACK });
for scale in [9.3, SCALE] {
let v = View { origin: (488.3, 452.7), scale, width: 640, height: 600 };
let whole = render_view_single(&c.doc, c.page, &v, &white()).unwrap();
let mut bands = Pixmap::new(v.width, v.height).unwrap();
for y0 in (0..v.height).step_by(75) {
let part = render_band(&c.doc, c.page, &v, &white(), y0, 75, 0).unwrap();
crate::put_band(&mut bands, y0, &part);
}
assert_eq!(furthest(&v, &bands, &whole), 0, "at {scale}");
}
}
#[test]
fn a_layer_with_a_shadow_holds_no_more_than_the_view() {
let c = card(true);
let v = close_up(&c, 1200, 800);
let view_bytes = u64::from(v.width) * u64::from(v.height) * 4;
let (pix, peak) = crate::layer_budget::within(crate::layer_budget::BUDGET, || render_view_single(&c.doc, c.page, &v, &Options::default()));
assert!(pix.is_some());
// The card's layer, and the clips inside and around it: each the view at most. Cast from the
// layer's pixels, the layer alone was the view and 1,392 pixels more each way.
assert!(peak <= view_bytes * 6, "{} MB held for a view of {} MB", peak >> 20, view_bytes >> 20);
}
#[test]
fn layers_that_are_not_their_outline_cast_from_their_pixels() {
let caster = |f: fn(&mut Card) -> NodeId| {
let mut c = card(true);
let id = f(&mut c);
crate::shadow::outline_caster(&c.doc, c.doc.node(id).unwrap()).is_some()
};
assert!(caster(|c| c.card), "an opaque frame whose children stay inside it");
assert!(caster(|c| {
c.doc.get_mut(c.card).unwrap().clip = true;
c.card
}));
assert!(!caster(|c| {
c.doc.get_mut(c.card).unwrap().fills = vec![Paint::solid(Color { a: 0.5, ..Color::WHITE })];
c.card
}));
// A child past the card's edge, or in the corner its rounding cuts off, casts a shadow too.
assert!(!caster(|c| {
let picture = c.doc.node(c.shape).unwrap().parent.unwrap();
c.doc.get_mut(picture).unwrap().transform = figcraft_geom::Affine::translate((300.0, 12.0));
c.card
}));
assert!(!caster(|c| {
shadow_of(c, |s| s.spread = 2.0);
c.card
}));
assert!(!caster(|c| {
let picture = c.doc.node(c.shape).unwrap().parent.unwrap();
c.doc.get_mut(picture).unwrap().transform = figcraft_geom::Affine::translate((1.0, 1.0));
c.card
}));
assert!(caster(|c| {
let picture = c.doc.node(c.shape).unwrap().parent.unwrap();
c.doc.get_mut(picture).unwrap().transform = figcraft_geom::Affine::translate((1.0, 1.0));
c.doc.get_mut(c.card).unwrap().clip = true;
c.card
}));
assert!(!caster(|c| {
c.doc
.get_mut(c.card)
.unwrap()
.effects
.push(figcraft_doc::Effect { kind: EffectKind::LayerBlur(figcraft_doc::Blur::uniform(2.0)), visible: true });
c.card
}));
}
/// A rectangle with a dark shadow of `radius` and `spread`, drawn through `transform`.
fn slab(transform: figcraft_geom::Affine, size: (f64, f64), radius: f64, spread: f64) -> (figcraft_doc::Document, NodeId) {
let mut d = figcraft_doc::Document::new("slab");
let page = d.first_page().unwrap();
let r = d.create(page, figcraft_doc::NodeKind::Rectangle, "Slab", 0.0, 0.0, size.0, size.1).unwrap();
let n = d.get_mut(r).unwrap();
n.transform = transform;
n.fills = vec![Paint::solid(Color::WHITE)];
n.effects.push(figcraft_doc::Effect {
kind: EffectKind::DropShadow(Shadow { radius, spread, offset: (0.0, 0.0), color: Color::BLACK, ..Shadow::default() }),
visible: true,
});
(d, page)
}
/// A spread grows the outline in the layer's own units: stretched six times one way and squeezed
/// as much the other, it reaches six times as far that way, not as far as the scale of an area
/// (here 1) says.
#[test]
fn a_spread_reaches_as_far_as_the_layer_is_stretched() {
let stretched = figcraft_geom::Affine::translate((120.0, 60.0)) * figcraft_geom::Affine::scale_non_uniform(6.0, 1.0 / 6.0);
let (d, page) = slab(stretched, (20.0, 240.0), 0.0, 10.0);
let v = View { origin: (0.0, 0.0), scale: 1.0, width: 360, height: 160 };
let new = render_view_single(&d, page, &v, &white()).unwrap();
FROM_PIXELS.with(|f| f.set(true));
let old = render_view_single(&d, page, &v, &white()).unwrap();
FROM_PIXELS.with(|f| f.set(false));
// Black 50 pixels left of the slab (its spread is 60 there), in both.
let at = |p: &Pixmap, x: usize, y: usize| p.data()[(y * 360 + x) * 4];
assert_eq!((at(&new, 70, 80), at(&old, 70, 80)), (0, 0), "the shadow 50 pixels out");
let apart = new.data().iter().zip(old.data()).filter(|(a, b)| a.abs_diff(**b) > 8).count();
assert!(apart < 400, "{apart} channels apart");
}
/// A shadow across a view as wide as a pixmap gets is drawn: the pixmap it is blurred in is a
/// blur's reach wider still.
#[test]
fn a_shadow_shows_across_the_widest_view() {
let (d, page) = slab(figcraft_geom::Affine::translate((-100.0, 4.0)), (17_000.0, 10.0), 6.0, 0.0);
let v = View { origin: (0.0, 0.0), scale: 1.0, width: 16_384, height: 30 };
let pix = render_view_single(&d, page, &v, &white()).unwrap();
// Two rows under the slab (white without a shadow), at both ends and in the middle.
for x in [10usize, 8_000, 16_370] {
let red = pix.data()[(16 * 16_384 + x) * 4];
assert!(red < 245, "a shadow under the slab at {x}: {red}");
}
}
+62
View File
@@ -0,0 +1,62 @@
//! Pan render timings: a page of 60 × 60 cards, each with a drop shadow and an inner shadow, seen
//! at 100% through a 1600 × 1100 device-pixel view. Run in release:
//! `cargo test --release -p figcraft-render --lib pan_render_timings -- --ignored --nocapture`.
//!
//! "full" renders the whole view; "pan" rows go through `Retained` as the canvas does, each step
//! moving the view by `step` device pixels and redrawing only the strips it uncovers.
use std::sync::Arc;
use std::time::Instant;
use figcraft_color::{Color, Paint};
use figcraft_doc::{Document, Effect, EffectKind, NodeId, NodeKind, Shadow};
use crate::{Options, Retained, View, render_view};
const STEPS: u32 = 12;
/// The cards: (document, page).
fn cards() -> (Arc<Document>, NodeId) {
let mut d = Document::new("pan bench");
let p = d.first_page().unwrap();
for y in 0..60u32 {
for x in 0..60u32 {
let c = d.create(p, NodeKind::Rectangle, "Card", f64::from(x) * 140.0, f64::from(y) * 110.0, 120.0, 90.0).unwrap();
let n = d.get_mut(c).unwrap();
n.fills = vec![Paint::solid(Color::new(x as f32 / 60.0, y as f32 / 60.0, 0.7, 1.0))];
n.corners.radii = [12.0; 4];
n.effects = vec![
Effect { kind: EffectKind::DropShadow(Shadow { radius: 18.0, offset: (0.0, 6.0), ..Shadow::default() }), visible: true },
Effect { kind: EffectKind::InnerShadow(Shadow { radius: 8.0, ..Shadow::default() }), visible: true },
];
}
}
(Arc::new(d), p)
}
fn view(origin: (f64, f64)) -> View {
View { origin, scale: 1.0, width: 1600, height: 1100 }
}
#[test]
#[ignore = "timing; run in release with --ignored --nocapture"]
fn pan_render_timings() {
let (d, p) = cards();
let opts = Options { lod: true, ..Options::default() };
let t0 = Instant::now();
for _ in 0..4 {
render_view(&d, p, &view((1000.0, 1000.0)), &opts).unwrap();
}
println!("full: {:.1} ms", t0.elapsed().as_secs_f64() * 1000.0 / 4.0);
for (name, step) in [("pan right", (60.0, 0.0)), ("pan down", (0.0, 60.0)), ("pan diagonally", (60.0, 24.0)), ("pan right fast", (240.0, 0.0))] {
let mut r = Retained::default();
let mut at = (1000.0, 1000.0);
r.render(&d, p, &view(at), &opts).unwrap();
let t0 = Instant::now();
for _ in 0..STEPS {
at = (at.0 + step.0, at.1 + step.1);
r.render(&d, p, &view(at), &opts).unwrap();
}
println!("{name} ({:?} px a step): {:.1} ms a step", step, t0.elapsed().as_secs_f64() * 1000.0 / f64::from(STEPS));
}
}
+4
View File
@@ -39,6 +39,10 @@ pub fn nested<T>(f: impl FnOnce() -> Option<T>) -> Option<T> {
/// the pixmap, the cell and the pixmap's pixels per unit on each axis (whole pixels per cell, so
/// the repeat lines up exactly).
pub fn cell_pixmap(doc: &Document, pt: &PatternPaint, w: f64, h: f64, scale: f64, time: f64) -> Option<(Pixmap, PatternCell, (f64, f64))> {
// Past the nesting limit nothing is drawn, so don't allocate a cell first.
if DEPTH.with(Cell::get) >= MAX_DEPTH {
return None;
}
let src = doc.node(NodeId(pt.source)).filter(|n| !n.is_page())?;
let cell = pt.cell(src.width, src.height, w, h)?;
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
+152 -13
View File
@@ -10,7 +10,7 @@ use std::sync::Arc;
use figcraft_doc::{Document, EffectKind, NodeId, NodeKind};
use figcraft_geom::Rect;
use tiny_skia::{IntRect, Pixmap, PixmapPaint, Transform};
use tiny_skia::Pixmap;
use crate::{Options, View, draw, render_view};
@@ -373,6 +373,11 @@ fn changed_areas(doc: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>)
}
out.push(draw::paint_bounds(doc, parent)?);
}
ancestor_areas(doc, id, out)
}
/// The areas of the ancestors of `id` that a change to it affects, beyond its own.
fn ancestor_areas(doc: &Document, id: NodeId, out: &mut Vec<Rect>) -> Option<()> {
// Ancestors that paint from their children's pixels (booleans, effects, masks): all of them.
for a in doc.ancestors(id) {
let Some(an) = doc.node(a) else { break };
@@ -386,6 +391,138 @@ fn changed_areas(doc: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>)
Some(())
}
/// Page areas in which `id` looks different in `after` than in `before` (where it was and where
/// it is now, and what of its ancestors follows); `None` when only a full render will do.
fn edited_areas(before: &Document, after: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>) -> Option<()> {
// A vector whose points moved looks different only around them.
if let Some(area) = moved_points_area(before, after, page, id) {
out.push(area);
ancestor_areas(before, id, out)?;
return ancestor_areas(after, id, out);
}
changed_areas(before, page, id, out)?;
changed_areas(after, page, id, out)
}
/// Vectors with more points than this are drawn again whole when they change.
const MAX_MOVED_POINTS: usize = 4096;
/// Whether every visible paint of `paints` is one colour: it looks the same wherever the layer's
/// box lies (a gradient or an image is laid out in the box).
fn plain(paints: &[figcraft_color::Paint]) -> bool {
paints.iter().filter(|p| p.visible).all(|p| matches!(p.kind, figcraft_color::PaintKind::Solid { .. }))
}
/// The page area in which vector `id` looks different in `after` than in `before`, when all that
/// changed is where its points and handles are (a point dragged in the vector editor): around the
/// segments that moved and their neighbours (whose joins and rounded corners follow them), as far
/// out as the stroke reaches. The rest of a large shape keeps its pixels, however much of the
/// view it fills. `None` when anything else changed or the look depends on the whole outline
/// (dashes, a width profile, a brush, gradients and images laid out in the box, effects, a mask):
/// the layer is then drawn again whole.
fn moved_points_area(before: &Document, after: &Document, page: NodeId, id: NodeId) -> Option<Rect> {
let (a, b) = (before.node(id)?, after.node(id)?);
let (NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) = (&a.kind, &b.kind) else { return None };
if after.page_of(id) != Some(page) || before.page_of(id) != Some(page) {
return None;
}
let simple = |n: &figcraft_doc::Node, net: &figcraft_doc::VectorNetwork| {
!n.is_mask
&& n.visible
&& !n.effects.iter().any(|e| e.visible)
&& n.stroke.dashes.is_empty()
&& n.stroke.width_profile.is_none()
&& n.stroke.brush.is_none()
&& plain(&n.fills)
&& plain(&n.strokes)
&& net.regions.iter().all(|r| r.fills.as_deref().is_none_or(plain))
};
let same_shape = na.vertices.len() == nb.vertices.len()
&& na.vertices.len() <= MAX_MOVED_POINTS
&& na.segments.len() == nb.segments.len()
&& na.segments.iter().zip(&nb.segments).all(|(x, y)| (x.a, x.b) == (y.a, y.b))
&& na.regions.len() == nb.regions.len()
&& na.regions.iter().zip(&nb.regions).all(|(x, y)| x.loops == y.loops && x.winding == y.winding && x.fills == y.fills);
if !(simple(a, na) && simple(b, nb) && same_shape) {
return None;
}
// A fill closes an open path with a line between its ends that is no segment: it moves
// with either end, across the whole shape.
let mut ends = vec![0u8; na.vertices.len()];
for s in &na.segments {
for i in [s.a, s.b] {
let n = ends.get_mut(i)?;
*n = n.saturating_add(1);
}
}
let filled = a.fills.iter().any(|f| f.visible) || !na.regions.is_empty();
if filled && ends.contains(&1) {
return None;
}
// Nothing but the geometry differs: the box follows the points, and with it the transform.
let mut as_after = a.clone();
as_after.kind = b.kind.clone();
(as_after.transform, as_after.width, as_after.height) = (b.transform, b.width, b.height);
if as_after != *b {
return None;
}
let (wa, wb) = (before.world_transform(id), after.world_transform(id));
// The box following the points moves the layer; anything else a transform does (a scale, a
// turn) changes every stroke's width or direction on the page, whether its path moved or not.
let (ca, cb) = (wa.as_coeffs(), wb.as_coeffs());
if ca.iter().zip(&cb).take(4).any(|(x, y)| (x - y).abs() > 1e-12 * x.abs().max(1.0)) {
return None;
}
// A segment on the page: its ends and handles.
let hull = |w: figcraft_geom::Affine, net: &figcraft_doc::VectorNetwork, s: &figcraft_doc::Segment| {
let (pa, pb) = (net.vertices.get(s.a)?.point(), net.vertices.get(s.b)?.point());
let pts = [pa, pa + figcraft_geom::Vec2::new(s.ta.0, s.ta.1), pb + figcraft_geom::Vec2::new(s.tb.0, s.tb.1), pb].map(|p| w * p);
pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()).then_some(pts)
};
let mut moved = vec![false; na.vertices.len()];
let mut hulls = Vec::with_capacity(na.segments.len());
for (sa, sb) in na.segments.iter().zip(&nb.segments) {
let (ha, hb) = (hull(wa, na, sa)?, hull(wb, nb, sb)?);
// Apart by more than float noise. When the box follows a moved point every local
// coordinate shifts and the transform shifts back: a point that stayed put comes out a
// few ulps from where it was. 64 of them is far above that and far under a pixel at any
// zoom, wherever on the page the vector lies (a tenth of a millionth of a unit at
// coordinates of ten million).
let near = |x: f64, y: f64| (x - y).abs() <= 64.0 * f64::EPSILON * x.abs().max(y.abs()).max(1.0);
let apart = ha.iter().zip(&hb).any(|(p, q)| !(near(p.x, q.x) && near(p.y, q.y)));
let styled =
|i: usize| na.vertices.get(i).zip(nb.vertices.get(i)).is_none_or(|(x, y)| (x.radius, x.cap, x.join) != (y.radius, y.cap, y.join));
if apart || styled(sa.a) || styled(sa.b) {
for i in [sa.a, sa.b] {
*moved.get_mut(i)? = true;
}
}
hulls.push((ha, hb));
}
// Every segment at a point of a segment that moved: its join or rounded corner there follows.
let mut area: Option<Rect> = None;
for (s, (ha, hb)) in na.segments.iter().zip(&hulls) {
if moved.get(s.a).copied().unwrap_or(true) || moved.get(s.b).copied().unwrap_or(true) {
for p in ha.iter().chain(hb) {
let r = Rect::from_points(*p, *p);
area = Some(area.map_or(r, |a| a.union(r)));
}
}
}
let area = area?;
// As far as the stroke reaches from the path, on the page.
// The most the transform stretches a length in any direction (its largest singular value):
// under a skew that is more than either axis is stretched.
let stretch = |w: figcraft_geom::Affine| {
let c = w.as_coeffs();
let sum = c[0] * c[0] + c[1] * c[1] + c[2] * c[2] + c[3] * c[3];
let det = c[0] * c[3] - c[1] * c[2];
((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
};
let reach = (a.outline_reach() * stretch(wa)).max(b.outline_reach() * stretch(wb));
reach.is_finite().then(|| area.inflate(reach, reach))
}
/// The previous frame brought up to date for `doc` at `px`, rendering only what changed; `None`
/// when a full render is the better (or only correct) choice. Also returns the pixels rendered.
fn patch(last: Frame, doc: &Arc<Document>, page: NodeId, view: &View, px: (i64, i64), opts: &Options, s: &Sensitive) -> Option<(Pixmap, u64)> {
@@ -434,8 +571,7 @@ fn patch(last: Frame, doc: &Arc<Document>, page: NodeId, view: &View, px: (i64,
if in_pattern_source(doc, s, id) || in_pattern_source(&last.doc, &last.sensitive, id) {
return None;
}
changed_areas(&last.doc, page, id, &mut areas)?;
changed_areas(doc, page, id, &mut areas)?;
edited_areas(&last.doc, doc, page, id, &mut areas)?;
}
for r in areas {
if let Some(p) = to_px(r, view.scale, px) {
@@ -553,15 +689,18 @@ fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) ->
let (rw, rh) = (u32::try_from(ex - ox).ok()?, u32::try_from(ey - oy).ok()?);
// The same pixel grid as the frame: origin (px + offset) / scale.
let sub = View { origin: ((px.0 + ox) as f64 / s, (px.1 + oy) as f64 / s), scale: s, width: rw, height: rh };
let part = render_view(doc, page, &sub, opts)?;
let inner = IntRect::from_xywh(
i32::try_from(d.x0 - ox).ok()?,
i32::try_from(d.y0 - oy).ok()?,
u32::try_from(d.x1 - d.x0).ok()?,
u32::try_from(d.y1 - d.y0).ok()?,
)?;
let inner = part.clone_rect(inner)?;
let copy = PixmapPaint { blend_mode: tiny_skia::BlendMode::Source, ..Default::default() };
pix.draw_pixmap(i32::try_from(d.x0).ok()?, i32::try_from(d.y0).ok()?, inner.as_ref(), &copy, Transform::identity(), None);
let part = crate::render_part(doc, page, &sub, opts)?;
// The rows of `d` in `part`, straight into their place (a copy of the part and a draw of the
// copy took longer than rendering a simple part).
let (skip_x, skip_y) = (usize::try_from(d.x0 - ox).ok()?, usize::try_from(d.y0 - oy).ok()?);
let (cols, rows) = (usize::try_from(d.x1 - d.x0).ok()?, usize::try_from(d.y1 - d.y0).ok()?);
let (at_x, at_y) = (usize::try_from(d.x0).ok()?, usize::try_from(d.y0).ok()?);
let (src_w, dst_w) = (part.width() as usize, pix.width() as usize);
let dst = pix.data_mut();
for (r, row) in part.data().chunks_exact(src_w.max(1) * 4).skip(skip_y).take(rows).enumerate() {
let from = row.get(skip_x * 4..(skip_x + cols) * 4)?;
let start = ((at_y + r) * dst_w + at_x) * 4;
dst.get_mut(start..start + cols * 4)?.copy_from_slice(from);
}
Some(())
}
+133
View File
@@ -65,3 +65,136 @@ fn a_clip_edge_on_a_pixel_boundary_clips_the_same_in_every_render() {
assert_same(&pix, &render_view(&smaller, page, &shown, &opts).unwrap(), &format!("lod {lod}"));
}
}
/// A closed zigzag of `2 * teeth + 2` points, 240 × 120 units at (20, 20): a ridge.
fn ridge(d: &mut Document, page: NodeId, teeth: usize) -> NodeId {
let mut pts = vec![figcraft_geom::Point::new(0.0, 120.0)];
for i in 0..=teeth * 2 {
pts.push(figcraft_geom::Point::new(240.0 * i as f64 / (teeth * 2) as f64, if i % 2 == 0 { 60.0 } else { 10.0 }));
}
pts.push(figcraft_geom::Point::new(240.0, 120.0));
let network = figcraft_doc::VectorNetwork::from_points(&pts, true);
let id = d.create(page, NodeKind::Vector { network }, "Ridge", 20.0, 20.0, 240.0, 120.0).unwrap();
d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex("7FAE9C").unwrap())];
id
}
fn move_point(d: &mut Document, id: NodeId, point: usize, by: (f64, f64)) {
if let NodeKind::Vector { network } = &mut d.get_mut(id).unwrap().kind {
network.vertices[point].x += by.0;
network.vertices[point].y += by.1;
}
}
/// A point of a vector dragged while the vector fills the view (zoomed to it, as the vector
/// editor does): the shape looks different only around the point's segments, and only that is
/// drawn again. (Its whole box was, and past 60 % of the view that made every frame of the
/// drag a full render.)
#[test]
fn a_moved_point_redraws_the_vector_around_it_only() {
type Style = fn(&mut figcraft_doc::Node);
let styles: [(&str, Style); 4] = [
("filled", |_| {}),
("stroked, mitred", |n| {
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 6.0;
n.stroke.miter_limit = 4.0;
}),
("rounded points", |n| {
if let NodeKind::Vector { network } = &mut n.kind {
network.vertices.iter_mut().for_each(|v| v.radius = 9.0);
}
}),
("stroked only", |n| {
n.fills.clear();
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 3.0;
}),
];
for (what, style) in styles {
let mut d = Document::new("ridge");
let page = d.first_page().unwrap();
let id = ridge(&mut d, page, 6);
style(d.get_mut(id).unwrap());
let doc = Arc::new(d);
// The ridge is 720 × 360 of the view's 780 × 420 pixels.
let v = View { origin: (10.0, 10.0), scale: 3.0, width: 780, height: 420 };
let mut r = Retained::default();
check(&mut r, &doc, page, &v, what);
let mut d2 = (*doc).clone();
move_point(&mut d2, id, 6, (4.0, -7.0));
let d2 = Arc::new(d2);
let (_, _, work) = r.render(&d2, page, &v, &Options::default()).unwrap();
let Work::Partial { pixels } = work else { panic!("{what}: a full render ({work:?})") };
// A tooth of six each way from the point, and what the stroke adds (36 pixels each way
// for the mitred one); the ridge's box is 259,200 pixels.
assert!(pixels < 780 * 420 * 2 / 5, "{what}: {pixels} pixels drawn again");
check(&mut r, &d2, page, &v, what);
// And back: the same again.
let (_, _, work) = r.render(&doc, page, &v, &Options::default()).unwrap();
assert!(matches!(work, Work::Partial { .. }), "{what}: {work:?}");
check(&mut r, &doc, page, &v, what);
}
}
/// What depends on the whole outline is drawn again whole: a gradient laid out in the vector's
/// box, dashes that run on from the moved point, an open path's closing line.
#[test]
fn a_moved_point_redraws_a_vector_whole_when_its_look_depends_on_all_of_it() {
type Style = fn(&mut figcraft_doc::Node);
let styles: [(&str, Style); 3] = [
("dashed", |n| {
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 3.0;
n.stroke.dashes = vec![8.0, 5.0];
}),
("a shadow", |n| n.effects.push(Effect::inner_shadow())),
("an open path", |n| {
if let NodeKind::Vector { network } = &mut n.kind {
network.segments.pop();
}
}),
];
for (what, style) in styles {
let mut d = Document::new("ridge");
let page = d.first_page().unwrap();
let id = ridge(&mut d, page, 6);
style(d.get_mut(id).unwrap());
let doc = Arc::new(d);
let v = View { origin: (10.0, 10.0), scale: 3.0, width: 780, height: 420 };
let mut r = Retained::default();
check(&mut r, &doc, page, &v, what);
let mut d2 = (*doc).clone();
move_point(&mut d2, id, 6, (4.0, -7.0));
let d2 = Arc::new(d2);
assert_eq!(r.render(&d2, page, &v, &Options::default()).unwrap().2, Work::Full, "{what}");
check(&mut r, &d2, page, &v, what);
}
}
/// A vector's strokes are as wide on the page as its transform makes them. Scaled up with its
/// points scaled down to match, its paths stay where they were and every stroke doubles: with a
/// point moved too, all of it is drawn again, not the area around that point.
#[test]
fn a_moved_point_with_a_scaled_vector_redraws_all_of_it() {
let mut d = Document::new("ridge");
let page = d.first_page().unwrap();
let id = ridge(&mut d, page, 6);
let n = d.get_mut(id).unwrap();
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 3.0;
let doc = Arc::new(d);
let v = View { origin: (10.0, 10.0), scale: 3.0, width: 780, height: 420 };
let mut r = Retained::default();
check(&mut r, &doc, page, &v, "first");
let mut d2 = (*doc).clone();
let n = d2.get_mut(id).unwrap();
n.transform *= Affine::scale(2.0);
(n.width, n.height) = (n.width / 2.0, n.height / 2.0);
if let NodeKind::Vector { network } = &mut n.kind {
for p in &mut network.vertices {
(p.x, p.y) = (p.x / 2.0, p.y / 2.0);
}
}
move_point(&mut d2, id, 6, (2.0, -3.5));
check(&mut r, &Arc::new(d2), page, &v, "scaled, a point moved");
}
+170 -10
View File
@@ -17,7 +17,7 @@ use figcraft_doc::{Document, EffectKind, Node, NodeKind, SPREAD_MITER_LIMIT, Sha
use figcraft_geom::{Affine, BezPath};
use tiny_skia::{FillRule, Pixmap, PixmapPaint, Transform};
use crate::draw::{hash_path, node_outline, stroke_area, stroke_rule, ts_path, ts_transform};
use crate::draw::{fill_to_stroke_middle, hash_path, node_outline, stroke_area, stroke_rule, ts_path, ts_transform};
use crate::fx;
/// The largest spread drawn, in device pixels.
@@ -28,8 +28,8 @@ pub type Outline = (BezPath, FillRule);
/// The outlines a node's shadows are cast by when they spread, in local space: its fill outline
/// (when a fill shows) and its stroke area. `None` when the layer's pixels aren't those outlines:
/// groups, frames that don't clip their children or show no fill, text with a stroke, layers
/// filled only with images or patterns (whose transparent pixels cast no shadow).
/// groups, frames that don't clip their children or show no fill, layers filled only with images
/// or patterns (whose transparent pixels cast no shadow).
pub fn silhouette(doc: &Document, n: &Node) -> Option<Vec<Outline>> {
outlines(doc, n, |f| f.visible && f.opacity > 0.0)
}
@@ -61,13 +61,17 @@ pub fn inner_from_pixels(doc: &Document, n: &Node) -> bool {
}
fn outlines(doc: &Document, n: &Node, fill_counts: fn(&Paint) -> bool) -> Option<Vec<Outline>> {
outlines_with(doc, n, fill_counts, false)
}
/// [`outlines`]; `kids_within`: the caller knows the children paint nothing outside the outline.
fn outlines_with(doc: &Document, n: &Node, fill_counts: fn(&Paint) -> bool, kids_within: bool) -> Option<Vec<Outline>> {
let has_fill = n.fills.iter().any(fill_counts);
let is_bool = matches!(n.kind, NodeKind::BooleanOp { .. });
let is_text = matches!(n.kind, NodeKind::Text(_));
let kids = !is_bool && n.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.visible));
let kids = !is_bool && !kids_within && n.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.visible));
if matches!(n.kind, NodeKind::Group | NodeKind::Page { .. })
|| (kids && !(n.kind.is_frame_like() && n.clip && has_fill))
|| (is_text && n.has_visible_stroke())
|| alpha_fills(doc, n, fill_counts)
{
return None;
@@ -77,12 +81,15 @@ fn outlines(doc: &Document, n: &Node, fill_counts: fn(&Paint) -> bool) -> Option
let mut out = Vec::new();
if has_fill
&& closed
&& let Some(o) = outline.clone()
&& let Some((path, rule)) = outline.clone()
{
out.push(o);
// As the layer fills it: out to the middle of a stroke that hides it, so the fill and the
// stroke share no anti-aliased edge that would count twice.
out.push(fill_to_stroke_middle(n, &path, rule).map_or((path, rule), |(p, r)| ((*p).clone(), r)));
}
if n.has_visible_stroke() {
let geom = if is_bool { outline.map(|(p, _)| p) } else { figcraft_doc::geometry::stroke_geometry(n) };
// Booleans and text are stroked along the outline they fill.
let geom = if is_bool || is_text { outline.map(|(p, _)| p) } else { figcraft_doc::geometry::stroke_geometry(n) };
if let Some(g) = geom {
out.push(((*stroke_area(n, &g, closed)).clone(), stroke_rule(n, closed)));
}
@@ -179,6 +186,8 @@ pub struct Caster<'a> {
pub silhouette: Option<Vec<Outline>>,
/// The node's [`cover`] in the layer's pixels; only when a shadow hides behind the layer.
pub cover: Option<Pixmap>,
/// The node's opacity, which the layer is drawn over its shadows at.
pub opacity: f32,
}
fn drop_shadows(n: &Node) -> impl Iterator<Item = &Shadow> {
@@ -201,7 +210,7 @@ impl<'a> Caster<'a> {
pub fn new(doc: &Document, n: &Node, layer: &'a Pixmap, xf: Affine, scale: f64) -> Self {
let silhouette = if drop_shadows(n).any(|s| s.spread != 0.0) { silhouette(doc, n) } else { None };
let cover = hiding_cover(doc, n).and_then(|c| spread_alpha(&c, 0.0, xf, layer.width(), layer.height()));
Caster { layer, xf, scale, silhouette, cover }
Caster { layer, xf, scale, silhouette, cover, opacity: n.opacity.clamp(0.0, 1.0) }
}
}
@@ -225,7 +234,10 @@ pub fn drop_shadow(c: &Caster, s: &Shadow) -> Option<Pixmap> {
fx::blur(&mut sh, s.radius / 2.0 * c.scale);
fx::tint(&mut sh, color4(s.color));
if !s.show_behind {
fx::mask_by(&mut sh, c.cover.as_ref().unwrap_or(c.layer), true);
match &c.cover {
Some(cover) => fx::hide_behind(&mut sh, cover, c.layer, c.opacity),
None => fx::mask_by(&mut sh, c.layer, true),
}
}
Some(sh)
}
@@ -286,3 +298,151 @@ fn inner_from(mut big: Pixmap, pad: u32, cover: &Pixmap, scale: f64, s: &Shadow)
fx::tint(&mut out, color4(s.color));
Some(out)
}
/// Whether `p` paints every pixel it covers at full alpha: a visible, opaque solid colour.
fn opaque(p: &Paint) -> bool {
p.visible && p.opacity >= 1.0 && p.blend == figcraft_color::BlendMode::Normal && matches!(&p.kind, PaintKind::Solid { color } if color.a >= 1.0)
}
/// The outlines node `n`'s drop shadows are cast from when its pixels are those outlines, filled:
/// a shape or a clipping frame whose paints are opaque colours and that has no effect that moves
/// its pixels. Such a shadow needs none of the layer's pixels, so it is drawn only where it
/// shows and blurred at the resolution its radius needs ([`outline_drop_shadow`]), not from a
/// copy of the layer reaching past the view. `None`: the shadows come from the layer's pixels.
pub fn outline_caster(doc: &Document, n: &Node) -> Option<Vec<Outline>> {
#[cfg(test)]
if FROM_PIXELS.with(std::cell::Cell::get) {
return None;
}
let shape =
n.kind.is_frame_like() || matches!(n.kind, NodeKind::Rectangle | NodeKind::Ellipse { .. } | NodeKind::Polygon { .. } | NodeKind::Star { .. });
let plain = n.effects.iter().filter(|e| e.visible).all(|e| matches!(e.kind, EffectKind::DropShadow(_) | EffectKind::InnerShadow(_)));
let fills = n.fills.iter().any(opaque);
let strokes = !n.has_visible_stroke() || n.strokes.iter().filter(|s| s.visible).all(opaque);
if !(shape && plain && fills && strokes && figcraft_doc::geometry::is_closed(n)) {
return None;
}
// A frame that doesn't clip is its outline too while its children stay inside it. Its
// shadows spread as its pixels do (see the module docs), not as an outline: those stay.
let within = n.kind.is_frame_like() && !n.clip && drop_shadows(n).all(|s| s.spread == 0.0) && children_within(doc, n);
outlines_with(doc, n, |f| f.visible && f.opacity > 0.0, within)
}
/// Whether everything the children of frame `n` paint (effects and all) lies inside its box, its
/// rounded corners cut off: they then add nothing to the pixels its fill covers.
fn children_within(doc: &Document, n: &Node) -> bool {
let world = doc.world_transform(n.id);
let det = world.determinant();
if !(det.is_finite() && det.abs() > 1e-12) {
return false;
}
let to_local = world.inverse();
n.children.iter().filter(|c| doc.node(**c).is_some_and(|c| c.visible)).all(|c| {
crate::draw::paint_bounds(doc, *c).is_some_and(|b| {
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)]
.into_iter()
.all(|p| crate::draw::in_box(n, to_local * figcraft_geom::Point::new(p.0, p.1)))
})
})
}
#[cfg(test)]
thread_local! {
/// Tests: every drop shadow is cast from its layer's pixels, as before [`outline_caster`].
pub(crate) static FROM_PIXELS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Shadows blurred by less than this many device pixels (standard deviation) are drawn at full
/// resolution, as they always were.
const FULL_RES_SIGMA: f64 = 8.0;
/// The most a shadow is drawn smaller by before its blur: a blur of 4 to 8 small pixels.
const MAX_SMALLER: u32 = 256;
/// The longest side of a pixmap.
const MAX_SIDE: u32 = 16_384;
/// What the pixmap a shadow is blurred in may have more than [`MAX_SIDE`] a side: the blur's
/// reach both ways at full resolution (under [`FULL_RES_SIGMA`]: 34 pixels) and a pixel's slack.
/// Drawn smaller, it is far under the limit.
const BLUR_ROOM: u32 = 128;
/// A whole pixel range `[lo, hi)` as `(start, length)`; `None` when empty or longer than `most`.
fn span(lo: f64, hi: f64, most: u32) -> Option<(i32, u32)> {
if !(lo.is_finite() && hi.is_finite() && hi > lo && lo.abs() < 1e9 && hi.abs() < 1e9) {
return None;
}
let len = (hi - lo) as u32;
(1..=most).contains(&len).then_some((lo as i32, len))
}
/// The most `xf` stretches a length, in any direction (its largest singular value): how far a
/// distance in local units can reach on the pixmap.
fn stretch(xf: Affine) -> f64 {
let c = xf.as_coeffs();
let sum = c[0] * c[0] + c[1] * c[1] + c[2] * c[2] + c[3] * c[3];
let det = c[0] * c[3] - c[1] * c[2];
((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
}
/// The drop shadow `s` cast by `outlines` (local space, drawn at `xf` into a `size` pixmap), where
/// it shows on that pixmap: the shadow's pixels and where their top-left goes. Unless it shows
/// behind the layer, it is hidden behind `cover`, which the layer paints opaque at `opacity`.
///
/// A shadow blurred widely is drawn `k` times smaller, blurred there and scaled back up: a wide
/// blur has no detail a pixel across. The small pixels line up with the shape, not with the
/// pixmap, so every render of a view (a band, a patch, the whole of it) draws the same shadow.
pub fn outline_drop_shadow(
outlines: &[Outline],
cover: &[Outline],
s: &Shadow,
xf: Affine,
scale: f64,
size: (u32, u32),
opacity: f32,
) -> Option<(Pixmap, (i32, i32))> {
let spread = if s.spread.is_finite() { s.spread } else { 0.0 };
let sigma = (s.radius / 2.0 * scale).min(fx::MAX_SIGMA);
let sigma = if sigma.is_finite() && sigma > 0.3 { sigma } else { 0.0 };
// As from the layer's pixels: without a spread the offset is whole pixels.
let (dx, dy) = (s.offset.0 * scale, s.offset.1 * scale);
let (dx, dy) = if spread != 0.0 && dx.is_finite() && dy.is_finite() { (dx, dy) } else { (f64::from(whole_px(dx)), f64::from(whole_px(dy))) };
let cast = Affine::translate((dx, dy)) * xf;
// Where the shadow can show: its outlines, spread and blurred, on the pixmap.
let reach = (sigma * 4.0).ceil() + 2.0;
// A spread grows the outline in local units: on the pixmap, as far as the transform
// stretches them the most (it need not scale both ways alike).
let px = stretch(xf);
let grown = if px.is_finite() { (spread.abs() * px * SPREAD_MITER_LIMIT).min(MAX_SPREAD_PX) } else { 0.0 };
let shape =
outlines.iter().map(|(p, _)| figcraft_geom::transform_rect_bbox(cast, figcraft_geom::Shape::bounding_box(p))).reduce(|a, b| a.union(b))?;
let shows = shape.inflate(grown + reach, grown + reach).intersect(figcraft_geom::Rect::new(0.0, 0.0, f64::from(size.0), f64::from(size.1)));
let (x0, w) = span(shows.x0.floor(), shows.x1.ceil(), MAX_SIDE)?;
let (y0, h) = span(shows.y0.floor(), shows.y1.ceil(), MAX_SIDE)?;
let smaller = if sigma >= FULL_RES_SIGMA { (2f64.powi((sigma / 4.0).log2().floor() as i32) as u32).clamp(1, MAX_SMALLER) } else { 1 };
let k = f64::from(smaller);
// The small pixmap's pixels are `k` device pixels a side, counted from the shape's origin
// (the pixmap's own pixels when nothing is drawn smaller): those the shadow's area and
// what blurs into it take in.
let c = cast.as_coeffs();
let (ax, ay) = if smaller > 1 { (c[4], c[5]) } else { (0.0, 0.0) };
let (i0, lw) =
span(((f64::from(x0) - reach - ax) / k).floor() - 1.0, ((f64::from(x0) + f64::from(w) + reach - ax) / k).ceil() + 1.0, MAX_SIDE + BLUR_ROOM)?;
let (j0, lh) =
span(((f64::from(y0) - reach - ay) / k).floor() - 1.0, ((f64::from(y0) + f64::from(h) + reach - ay) / k).ceil() + 1.0, MAX_SIDE + BLUR_ROOM)?;
let small = Affine::new([c[0] / k, c[1] / k, c[2] / k, c[3] / k, (c[4] - ax) / k - f64::from(i0), (c[5] - ay) / k - f64::from(j0)]);
let mut low = spread_alpha(outlines, spread, small, lw, lh)?;
fx::blur(&mut low, sigma / k);
let mut out = Pixmap::new(w, h)?;
let tints = fx::tints(color4(s.color));
if smaller > 1 {
// Device pixel centre → small pixel centres.
let at = |v: i32, a: f64, first: i32| (f64::from(v) + 0.5 - a) / k - 0.5 - f64::from(first);
fx::enlarge_alpha(&low, &mut out, (at(x0, ax, i0), at(y0, ay, j0)), 1.0 / k, &tints);
} else {
fx::copy_alpha(&low, &mut out, (x0 - i0, y0 - j0), &tints);
}
if !s.show_behind {
let hides = spread_alpha(cover, 0.0, Affine::translate((-f64::from(x0), -f64::from(y0))) * xf, w, h)?;
fx::hide_behind(&mut out, &hides, &hides, opacity);
}
Some((out, (x0, y0)))
}
@@ -0,0 +1,72 @@
//! A sharp drop shadow under a stroked layer is one solid silhouette: where the layer's edge lies
//! over its own shadow, nothing lighter than the shadow shows between them (#2631).
use figcraft_color::Paint;
use figcraft_doc::{Document, Effect, EffectKind, NodeKind, Shadow, StrokeAlign, VectorNetwork};
use figcraft_geom::Point;
use super::paint_behaviour_tests::{hex, page, px, render};
const OFFSET: (i64, i64) = (5, 7);
/// The page with `kind` at a fractional position, filled pink with a black 3-unit `align` stroke
/// and, with `shadow`, a black unblurred drop shadow at [`OFFSET`]; `None` without a font for text.
fn scene(kind: &NodeKind, align: StrokeAlign, shadow: bool) -> Option<Document> {
let (mut d, p) = page();
let id = d.create(p, kind.clone(), "L", 40.3, 30.6, 60.0, 60.0).ok()?;
let n = d.get_mut(id).ok()?;
n.fills = vec![Paint::solid(hex("#EC4899"))];
n.strokes = vec![Paint::solid(hex("#000000"))];
(n.stroke.weight, n.stroke.align) = (3.0, align);
if shadow {
let offset = (OFFSET.0 as f64, OFFSET.1 as f64);
n.effects =
vec![Effect { kind: EffectKind::DropShadow(Shadow { color: hex("#000000"), offset, radius: 0.0, ..Shadow::default() }), visible: true }];
}
if matches!(kind, NodeKind::Text(_)) {
(n.width, n.height) = figcraft_text::auto_size(n)?;
}
Some(d)
}
#[test]
fn a_sharp_shadow_under_a_stroked_layer_has_no_light_line_along_the_layers_edge() {
let mut letter = figcraft_doc::TextData::new("B");
letter.style.font_size = 80.0;
// A letter-like outline with a notch (cast from the layer's pixels), an ellipse (cast from
// its outline) and, where a font loads, a letter.
let notch = [(0.0, 0.0), (60.0, 0.0), (60.0, 60.0), (40.0, 60.0), (30.0, 20.0), (20.0, 60.0), (0.0, 60.0)].map(|(x, y)| Point::new(x, y));
let kinds = [
("notch", NodeKind::Vector { network: VectorNetwork::from_points(&notch, true) }),
("ellipse", NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }),
("letter", NodeKind::Text(letter)),
];
let shadow = hex("#000000").to_rgba8();
for (name, kind) in &kinds {
for align in [StrokeAlign::Inside, StrokeAlign::Center, StrokeAlign::Outside] {
let (Some(plain), Some(shadowed)) = (scene(kind, align, false), scene(kind, align, true)) else { continue };
let (plain, shadowed) = (render(&plain), render(&shadowed));
// The layer's paints cover a pixel fully when every neighbour is pink or black.
let solid = |x: i64, y: i64| {
(-1..=1).all(|i| {
(-1..=1).all(|j| {
u32::try_from(x + i)
.ok()
.zip(u32::try_from(y + j).ok())
.is_some_and(|(x, y)| x < 200 && y < 200 && px(&plain, x, y)[1] < 0x48 + 8)
})
})
};
let mut checked = 0;
for (x, y) in (0..200).flat_map(|y| (0..200).map(move |x| (x, y))) {
// Inside the shadow, away from its edge, wherever the layer doesn't hide it whole.
if solid(x - OFFSET.0, y - OFFSET.1) && !solid(x, y) {
checked += 1;
let c = px(&shadowed, x as u32, y as u32);
assert!(c.iter().zip(shadow).all(|(v, s)| *v <= s + 2), "{name} {align:?}: ({x}, {y}) is {c:?}, lighter than the shadow");
}
}
assert!(checked > 100, "{name} {align:?}: the shadow shows past the layer");
}
}
}
+60
View File
@@ -0,0 +1,60 @@
//! An opaque stroke meets what lies on each side of it with nothing else showing between: no
//! light fill fringe along an inside stroke's outer edge, no background gap along an outside
//! stroke's inner edge (#2635).
use figcraft_color::{Color, Paint};
use figcraft_doc::{Document, NodeKind, StrokeAlign};
use super::*;
const DARK: Color = Color { r: 30.0 / 255.0, g: 27.0 / 255.0, b: 75.0 / 255.0, a: 1.0 };
/// The red channel along the middle row of a 40-unit `kind` at (`at`, `at`) with a black 4-unit
/// stroke, its fill `fill`, over `background`.
fn middle_row(kind: &NodeKind, smoothing: f64, align: StrokeAlign, at: f64, fill: Color, background: Color) -> Vec<u8> {
let mut d = Document::new("fringe");
let p = d.first_page().unwrap();
let n = d.create(p, kind.clone(), "S", at, at, 40.0, 40.0).unwrap();
let node = d.get_mut(n).unwrap();
node.fills = vec![Paint::solid(fill)];
node.strokes = vec![Paint::solid(Color::BLACK)];
(node.stroke.weight, node.stroke.align, node.corners.smoothing) = (4.0, align, smoothing);
if smoothing > 0.0 {
node.corners.radii = [8.0; 4];
}
let mut pix = Pixmap::new(80, 80).unwrap();
let c = |v: f32| (v * 255.0).round() as u8;
pix.fill(tiny_skia::Color::from_rgba8(c(background.r), c(background.g), c(background.b), 255));
render_nodes_into(&d, &[n], &View { origin: (0.0, 0.0), scale: 1.0, width: 80, height: 80 }, &mut pix);
let y = (at + 20.0) as u32;
(0..80).map(|x| pix.pixel(x, y).unwrap().red()).collect()
}
#[test]
fn an_opaque_stroke_shows_nothing_lighter_than_its_dark_neighbour_at_either_edge() {
let dark = (DARK.r * 255.0).round() as u8;
let ellipse = NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 };
// Smoothed corners take the general outline rather than the rect ring.
let shapes = [(&NodeKind::Frame, 0.0), (&NodeKind::Rectangle, 0.0), (&ellipse, 0.0), (&NodeKind::Rectangle, 0.6)];
for (kind, smoothing) in shapes {
for align in [StrokeAlign::Inside, StrokeAlign::Center, StrokeAlign::Outside] {
for at in [20.4, 20.7] {
let middle = at
+ match align {
StrokeAlign::Inside => 2.0,
StrokeAlign::Center => 0.0,
StrokeAlign::Outside => -2.0,
};
let centre = (at + 20.0) as usize;
// Outside the stroke's middle on a dark page under a white fill, then inside it
// under a dark fill on a white page: no pixel lighter than the dark side.
let outer = middle_row(kind, smoothing, align, at, Color::WHITE, DARK);
let outer = &outer[..middle.floor() as usize];
let inner = middle_row(kind, smoothing, align, at, DARK, Color::WHITE);
let inner = &inner[middle.ceil() as usize..centre];
assert!(outer.iter().all(|&r| r <= dark), "{kind:?} smoothing {smoothing}, {align:?} at {at}: outer edge {outer:?}");
assert!(inner.iter().all(|&r| r <= dark), "{kind:?} smoothing {smoothing}, {align:?} at {at}: inner edge {inner:?}");
}
}
}
}
+92
View File
@@ -609,3 +609,95 @@ fn rect_clip_frame_matches_same_rect_fill_on_fractional_edges() {
}
}
}
#[test]
fn jpeg_export_keeps_full_chroma() {
let mut pix = Pixmap::new(8, 8).unwrap();
pix.fill(tiny_skia::Color::from_rgba8(160, 64, 192, 255));
let jpeg = encode_export_with(&pix, ExportFormat::Jpg, ColorProfile::Srgb, 90).unwrap();
// SOF0 for the generated 8-bit, three-component baseline JPEG.
let header = [0xff, 0xc0, 0, 17, 8, 0, 8, 0, 8, 3];
let frame = jpeg.windows(19).find(|segment| segment.starts_with(&header)).expect("RGB JPEG frame");
assert_eq!([frame[11], frame[14], frame[17]], [0x11; 3], "JPEG component sampling factors");
}
#[test]
fn export_output_and_icc_parity() {
use figcraft_color::ColorProfile;
use figcraft_doc::ExportFormat;
use image::ImageDecoder;
let has_png_chunk = |bytes: &[u8], kind: &[u8; 4], payload: &[u8]| {
bytes.windows(4).enumerate().any(|(i, w)| w == kind && bytes.get(i + 4..i + 4 + payload.len()) == Some(payload))
};
let mut pix = Pixmap::new(8, 8).unwrap();
// Premultiplied 50% alpha: `(100*255+64)/128 = 199`, `(50*255+64)/128 = 100`, `(25*255+64)/128 = 50`.
let straight = [199u8, 100, 50, 128];
let pm = tiny_skia::PremultipliedColorU8::from_rgba(100, 50, 25, 128).unwrap();
pix.pixels_mut().fill(pm);
// Untagged PNG and WebP preserve alpha and carry no ICC profile.
let raw_png = encode_png(&pix).unwrap();
assert!(image::codecs::png::PngDecoder::new(std::io::Cursor::new(&raw_png)).unwrap().icc_profile().unwrap().is_none());
assert_eq!(image::load_from_memory(&raw_png).unwrap().to_rgba8().get_pixel(4, 4).0, straight);
let raw_webp = encode_webp(&pix).unwrap();
assert!(image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&raw_webp)).unwrap().icc_profile().unwrap().is_none());
assert_eq!(image::load_from_memory(&raw_webp).unwrap().to_rgba8().get_pixel(4, 4).0, straight);
// JPEG composites alpha over the given background and clamps quality to 1..=100.
let blue_bg = Color::from_hex("0000FF").unwrap();
let jpg_min = encode_jpeg(&pix, blue_bg, 0).unwrap();
assert_eq!(jpg_min, encode_jpeg(&pix, blue_bg, 1).unwrap());
let jpg_max = encode_jpeg(&pix, blue_bg, 200).unwrap();
assert_eq!(jpg_max, encode_jpeg(&pix, blue_bg, 100).unwrap());
let jpg_px = image::load_from_memory(&jpg_max).unwrap().to_rgb8().get_pixel(4, 4).0;
assert!(jpg_px[2] > 140 && jpg_px[0] > 80, "expected red+blue composite, got {jpg_px:?}");
for profile in ColorProfile::ALL {
let png = encode_export(&pix, ExportFormat::Png, profile).unwrap();
let png_icc = image::codecs::png::PngDecoder::new(std::io::Cursor::new(&png)).unwrap().icc_profile().unwrap();
if profile.is_srgb() {
assert_eq!(png_icc, None);
assert!(has_png_chunk(&png, b"sRGB", &[0]));
assert!(!has_png_chunk(&png, b"cICP", &[]));
} else {
assert_eq!(png_icc, Some(profile.icc()));
assert!(has_png_chunk(&png, b"cICP", &profile.cicp()));
assert!(!has_png_chunk(&png, b"sRGB", &[]));
}
assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(4, 4).0, straight);
let webp = encode_export(&pix, ExportFormat::Webp, profile).unwrap();
let webp_icc = image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&webp)).unwrap().icc_profile().unwrap();
assert_eq!(webp_icc, (!profile.is_srgb()).then(|| profile.icc()));
assert_eq!(image::load_from_memory(&webp).unwrap().to_rgba8().get_pixel(4, 4).0, straight);
let jpg = encode_export_with(&pix, ExportFormat::Jpg, profile, 90).unwrap();
let jpg_icc = image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(&jpg)).unwrap().icc_profile().unwrap();
assert_eq!(jpg_icc, Some(profile.icc()));
}
}
#[test]
fn export_display_p3_roundtrips_icc_through_decode() {
use figcraft_color::ColorProfile;
use figcraft_doc::ExportFormat;
// Saturated Display P3 red: `ColorProfile::Srgb` red [255, 0, 0] converted to Display P3 values.
let p3_red = ColorProfile::Srgb.conversion_to(ColorProfile::DisplayP3).apply(Color::new(1.0, 0.0, 0.0, 1.0)).to_rgba8();
let mut pix = Pixmap::new(8, 8).unwrap();
pix.fill(tiny_skia::Color::from_rgba8(p3_red[0], p3_red[1], p3_red[2], 255));
for format in [ExportFormat::Png, ExportFormat::Jpg, ExportFormat::Webp] {
let encoded = encode_export(&pix, format, ColorProfile::DisplayP3).unwrap();
let source = crate::image_profile::Source::of(&encoded);
assert!(source.name.as_deref().is_some_and(|n| n.contains("P3")), "{format:?}: {:?}", source.name);
let decoded = images::decode(&encoded).unwrap();
let px = decoded.pixel(4, 4).unwrap();
// Converting the Display P3 export back into sRGB restores sRGB red [255, 0, 0].
assert!(px.red() >= 250 && px.green() <= 5 && px.blue() <= 5, "{format:?}: {px:?}");
}
}
+126
View File
@@ -0,0 +1,126 @@
//! Timings of a shadowed card seen close up: a small shape inside a rounded picture inside a
//! rounded card with a drop shadow, inside two stacks and a screen, at 1,933% on a 2× display
//! (38.66 device pixels a unit, 4112 × 2292 device pixels). The mobile app template's trail card,
//! where the browser took 16.6 s for one render and 2 s for each frame of an edit.
//!
//! Run in release, on one thread as the browser does:
//! `RAYON_NUM_THREADS=1 cargo test --release -p figcraft-render --lib zoomed_card_timings -- --ignored --nocapture`.
use std::sync::Arc;
use std::time::Instant;
use figcraft_color::{Color, Paint};
use figcraft_doc::{Document, Effect, EffectKind, NodeId, NodeKind, Shadow};
use crate::{Begun, Options, Retained, View, Work, render_view_single};
/// Device pixels a document unit: 1,933% at a pixel ratio of 2.
pub(crate) const SCALE: f64 = 38.66;
pub(crate) struct Card {
pub doc: Document,
pub page: NodeId,
pub card: NodeId,
/// The shape in the card's picture.
pub shape: NodeId,
}
/// The card: screen (clipping) > content > list > card (rounded, white, a drop shadow; like
/// the two stacks around it, not clipping) > picture (rounded, clipping) > shape.
pub(crate) fn card(shadow: bool) -> Card {
let fill = |d: &mut Document, id: NodeId, hex: &str| d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex(hex).unwrap())];
let mut d = Document::new("zoomed card");
let page = d.first_page().unwrap();
let screen = d.create(page, NodeKind::Frame, "Screen", 470.0, 0.0, 390.0, 844.0).unwrap();
fill(&mut d, screen, "F4F6F5");
let content = d.create(screen, NodeKind::Frame, "Content", 0.0, 81.0, 390.0, 763.0).unwrap();
let list = d.create(content, NodeKind::Frame, "List", 24.0, 180.0, 342.0, 312.0).unwrap();
let card = d.create(list, NodeKind::Frame, "Card", 0.0, 108.0, 342.0, 96.0).unwrap();
fill(&mut d, card, "FFFFFF");
let n = d.get_mut(card).unwrap();
n.corners.radii = [20.0; 4];
if shadow {
n.effects.push(Effect {
kind: EffectKind::DropShadow(Shadow { offset: (0.0, 4.0), radius: 16.0, color: Color { a: 0.08, ..Color::BLACK }, ..Shadow::default() }),
visible: true,
});
}
for stack in [content, list, card] {
d.get_mut(stack).unwrap().clip = false;
}
let picture = d.create(card, NodeKind::Frame, "Picture", 12.0, 12.0, 72.0, 72.0).unwrap();
fill(&mut d, picture, "CFE3DA");
d.get_mut(picture).unwrap().corners.radii = [14.0; 4];
let shape = d.create(picture, NodeKind::Polygon { count: 5 }, "Shape", 0.0, 23.0, 72.0, 49.0).unwrap();
fill(&mut d, shape, "7FAE9C");
Card { doc: d, page, card, shape }
}
/// The view the canvas has after zooming to the shape: the shape in the middle.
pub(crate) fn close_up(c: &Card, width: u32, height: u32) -> View {
let b = crate::draw::paint_bounds(&c.doc, c.shape).unwrap();
let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
View { origin: (cx - f64::from(width) / SCALE / 2.0, cy - f64::from(height) / SCALE / 2.0), scale: SCALE, width, height }
}
fn ms(t: Instant) -> f64 {
t.elapsed().as_secs_f64() * 1000.0
}
/// A full render drawn in the browser's bands: (all of it, the slowest band), in milliseconds.
fn banded(c: &Card, v: &View) -> (f64, f64) {
let doc = Arc::new(c.doc.clone());
let mut r = Retained::default();
let band_h = (v.height + 1).div_ceil(8).max(64);
let t = Instant::now();
let mut slowest = 0.0f64;
match r.begin(&doc, c.page, v, &Options::default(), band_h).unwrap() {
Begun::Done(..) => {}
Begun::Steps(mut steps) => loop {
let b = Instant::now();
let done = steps.step();
slowest = slowest.max(ms(b));
if done {
break;
}
},
}
(ms(t), slowest)
}
/// Mean milliseconds of a canvas frame after an edit of the shape, and what the last one took.
fn edits(c: &Card, v: &View) -> (f64, Work) {
const RUNS: u32 = 6;
let mut r = Retained::default();
let mut doc = Arc::new(c.doc.clone());
let _ = r.render(&doc, c.page, v, &Options::default());
let mut work = Work::Reused;
let t = Instant::now();
for i in 1..=RUNS {
let mut next = (*doc).clone();
next.get_mut(c.shape).unwrap().height = 49.0 - f64::from(i);
doc = Arc::new(next);
work = r.render(&doc, c.page, v, &Options::default()).unwrap().2;
}
(ms(t) / f64::from(RUNS), work)
}
#[test]
#[ignore = "timing: run in release with --ignored --nocapture"]
fn zoomed_card_timings() {
println!("zoomed card timings ({} build, 4112 × 2292 px, ms)", if cfg!(debug_assertions) { "debug" } else { "release" });
println!("| render | shadow | no shadow |\n|---|---:|---:|");
let (with, without) = (card(true), card(false));
let v = close_up(&with, 4112, 2292);
let piece = |c: &Card| {
let t = Instant::now();
assert!(render_view_single(&c.doc, c.page, &v, &Options::default()).is_some());
ms(t)
};
println!("| the view in one piece | {:.0} | {:.0} |", piece(&with), piece(&without));
let (a, b) = (banded(&with, &v), banded(&without, &v));
println!("| the view in 8 bands | {:.0} | {:.0} |", a.0, b.0);
println!("| the slowest band | {:.0} | {:.0} |", a.1, b.1);
let (a, b) = (edits(&with, &v), edits(&without, &v));
println!("| a frame after an edit of the shape | {:.0} ({:?}) | {:.0} ({:?}) |", a.0, a.1, b.0, b.1);
}