diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index c2d781f9c..77063befe 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -151,6 +151,27 @@ fn pixels_when_magnified(prep: Prepared, device_scale: f64) -> Prepared { Prepared::Pattern { pixmap, mode, quality, opacity, transform } } +/// An image pattern shown smaller than its pixels, straight, drawn into `path` under `xf` (local +/// → device) on a `limit`-sized pixmap: replaced by the device pixels it covers, each the average +/// of the image under it (see [`crate::resample`]), laid on the pixel grid. Others as they are. +fn averaged_when_shrunk(prep: Prepared, path: &tiny_skia::Path, xf: Affine, limit: (u32, u32)) -> Prepared { + let Prepared::Pattern { pixmap, mode: tiny_skia::SpreadMode::Pad, opacity, transform, .. } = &prep else { return prep }; + let device = ts_transform(xf); + let area = path + .bounds() + .transform(device) + .and_then(|b| int_rect(Rect::new(b.left().into(), b.top().into(), b.right().into(), b.bottom().into()), limit)); + let (Some(area), Some(back)) = (area, device.invert()) else { return prep }; + let Some(avg) = crate::resample::area_averaged(pixmap, device.pre_concat(*transform), area) else { return prep }; + Prepared::Pattern { + pixmap: std::sync::Arc::new(avg), + mode: tiny_skia::SpreadMode::Pad, + quality: FilterQuality::Nearest, + opacity: *opacity, + transform: back.pre_translate(area.x() as f32, area.y() as f32), + } +} + /// Paint `paints` over `path`, bottom first. Each blends by its own mode with what lies under it: /// within a layer that isn't pass-through (`isolate`), only with the paints below it in the list, /// the list then laid over the canvas as one (the reference tool's: a shape's fills on a @@ -205,6 +226,7 @@ fn paint_each( for p in paints { let Some(prep) = prepare_at(p, w, h, scale, ctx.doc, ctx.time, ctx.preview) else { continue }; let prep = if ctx.magnified_image_pixels && matches!(p.kind, PaintKind::Image(_)) { pixels_when_magnified(prep, scale) } else { prep }; + let prep = if matches!(p.kind, PaintKind::Image(_)) { averaged_when_shrunk(prep, path, xf, (pix.width(), pix.height())) } else { prep }; let paint = tiny_skia::Paint { shader: prep.shader(), anti_alias: true, blend_mode: ts_blend(p.blend), ..Default::default() }; if crate::paint::own_blend(p.blend) { // No tiny-skia mode: the paint alone over its pixels, then blended in. diff --git a/crates/render/src/export_framing_tests.rs b/crates/render/src/export_framing_tests.rs index 6edecf023..31336db69 100644 --- a/crates/render/src/export_framing_tests.rs +++ b/crates/render/src/export_framing_tests.rs @@ -1,12 +1,16 @@ -//! How an export frames a layer, as the reference tool's exports do (measured on its renders of the -//! same scenes): a drop shadow counts as far as its blur radius (its faint tail past that stays -//! out), and a layer inside that draws nothing doesn't count. +//! How an export frames and samples a layer, as the reference tool's exports do (measured on its +//! renders of the same scenes): a drop shadow counts as far as its blur radius (its faint tail past +//! that stays out), a layer inside that draws nothing doesn't count, and an image shown smaller +//! than its pixels comes out as the average of the image under each pixel, wherever it falls +//! between pixels. -use figcraft_color::{BlendMode, Color, Paint}; -use figcraft_doc::{Effect, EffectKind, NodeKind, Shadow}; +use std::sync::Arc; + +use figcraft_color::{BlendMode, Color, ImageScaleMode, Paint}; +use figcraft_doc::{Document, Effect, EffectKind, ImageData, NodeKind, Shadow}; use super::paint_behaviour_tests::page; -use crate::export_bounds; +use crate::{Pixmap, encode_png, export_bounds, render_node}; fn shadow(radius: f64, offset: (f64, f64)) -> Effect { let color = Color { a: 0.3, ..Color::BLACK }; @@ -39,3 +43,33 @@ fn a_layer_that_draws_nothing_stays_out_of_the_export() { d.get_mut(ph).unwrap().fills = vec![Paint::solid(Color::BLACK)]; assert!(export_bounds(&d, f).unwrap().width() > 1000.0); } + +/// A 400 × 400 white image with one black column of pixels (x = 201), on a 100 × 100 layer at +/// `(x, 0)`. +fn line_at(x: f64) -> (Document, figcraft_doc::NodeId) { + let mut img = Pixmap::new(400, 400).unwrap(); + for (i, c) in img.data_mut().chunks_exact_mut(4).enumerate() { + let v = if i % 400 == 201 { 0 } else { 255 }; + c.copy_from_slice(&[v, v, v, 255]); + } + let (mut d, p) = page(); + d.images.insert("line".into(), ImageData { bytes: Arc::new(encode_png(&img).unwrap()), width: 400, height: 400 }); + let r = d.create(p, NodeKind::Rectangle, "Image", x, 0.0, 100.0, 100.0).unwrap(); + d.get_mut(r).unwrap().fills = vec![Paint::image("line", ImageScaleMode::Fill)]; + (d, r) +} + +#[test] +fn an_image_shown_smaller_exports_the_average_of_what_each_pixel_covers() { + // Shown at a quarter of its size, the line is a quarter of a pixel wide: wherever it falls, + // the pixels it crosses hold a quarter pixel's worth of black between them (sampled at pixel + // centres instead, it vanishes or comes out a whole pixel dark). + for at in [0.0, 10.5, 7.3, 3.9] { + let (d, r) = line_at(at); + let pix = render_node(&d, r, 1.0).unwrap(); + let w = pix.width() as usize; + let y = 50; + let ink: f64 = (0..w).map(|x| 255.0 - f64::from(pix.data()[(y * w + x) * 4])).sum(); + assert!((ink - 255.0 / 4.0).abs() < 6.0, "layer at x {at}: {ink} of black in the row"); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index df1a2e04e..7d8e3a314 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -20,6 +20,7 @@ mod layer_budget; pub mod lod; pub mod paint; pub mod pattern; +mod resample; pub mod retained; pub mod shadow; diff --git a/crates/render/src/resample.rs b/crates/render/src/resample.rs new file mode 100644 index 000000000..9a194a14d --- /dev/null +++ b/crates/render/src/resample.rs @@ -0,0 +1,107 @@ +//! Images drawn smaller than their pixels, on the canvas and in exports: each device pixel is the +//! average of the image area it covers, wherever the image falls between pixels (the reference +//! tool's exports; sampling the image at pixel centres instead keeps every edge and fine line +//! aliased, and a copy scaled down first then shifted a fraction of a pixel comes out blurred). +//! Past its edges the image extends its edge pixels, as the pattern it replaces does. + +use tiny_skia::{IntRect, Pixmap, Transform}; + +/// The most weights the two passes may work through (device pixels times the image pixels each +/// averages), so one huge image shown small doesn't hold up an export: past it the image is +/// sampled as before. +const MAX_WORK: u64 = 1 << 28; + +/// `src` (premultiplied) as it shows over device area `area` under `m` (image pixels → device), +/// averaged per device pixel; its pixel (0, 0) lies at the area's top-left. `None` unless `m` is +/// axis-aligned and makes the image smaller along both axes. +pub(crate) fn area_averaged(src: &Pixmap, m: Transform, area: IntRect) -> Option { + let (sx, sy) = (f64::from(m.sx), f64::from(m.sy)); + let (tx, ty) = (f64::from(m.tx), f64::from(m.ty)); + let straight = m.kx.abs() < 1e-6 && m.ky.abs() < 1e-6; + if !straight || !(sx.abs() < 1.0 && sy.abs() < 1.0 && sx.abs() > 1e-6 && sy.abs() > 1e-6) || !tx.is_finite() || !ty.is_finite() { + return None; + } + let (sw, sh) = (src.width() as usize, src.height() as usize); + let (dw, dh) = (area.width() as usize, area.height() as usize); + let cols = spans(area.x(), dw, tx, sx, sw); + let rows = spans(area.y(), dh, ty, sy, sh); + // Only the image rows some device row reads are averaged across. + let (r0, r1) = rows.iter().fold((usize::MAX, 0), |(a, b), s| (a.min(s.first), b.max(s.first + s.weights.len()))); + let r1 = r1.min(sh); + if r0 >= r1 { + return None; + } + let work = |s: &[Span]| s.iter().map(|s| s.weights.len() as u64).sum::(); + if work(&cols).saturating_mul((r1 - r0) as u64).saturating_add(work(&rows).saturating_mul(dw as u64)) > MAX_WORK { + return None; + } + let data = src.data(); + // Across: each image row in use, averaged into the device columns. + let mut across = vec![[0.0_f32; 4]; (r1 - r0) * dw]; + for (r, out) in (r0..r1).zip(across.chunks_mut(dw)) { + let row = data.get(r * sw * 4..(r + 1) * sw * 4)?; + for (c, o) in cols.iter().zip(out.iter_mut()) { + for (k, w) in c.weights.iter().enumerate() { + let px = row.get((c.first + k) * 4..(c.first + k) * 4 + 4)?; + for (acc, v) in o.iter_mut().zip(px) { + *acc += w * f32::from(*v); + } + } + } + } + // Down: the device rows from those. + let mut out = Pixmap::new(area.width(), area.height())?; + for (y, s) in rows.iter().enumerate() { + for x in 0..dw { + let mut acc = [0.0_f32; 4]; + for (k, w) in s.weights.iter().enumerate() { + let px = across.get((s.first + k - r0) * dw + x)?; + for (a, v) in acc.iter_mut().zip(px) { + *a += w * v; + } + } + let to = |v: f32| v.round().clamp(0.0, 255.0) as u8; + let alpha = to(acc[3]); + let dst = out.data_mut().get_mut((y * dw + x) * 4..(y * dw + x) * 4 + 4)?; + // Premultiplied: no channel above the alpha, whatever rounding did. + dst.copy_from_slice(&[to(acc[0]).min(alpha), to(acc[1]).min(alpha), to(acc[2]).min(alpha), alpha]); + } + } + Some(out) +} + +/// The image pixels one device column (or row) averages: the first, and each one's weight. +struct Span { + first: usize, + weights: Vec, +} + +/// For `n` device pixels from `start`, the image pixels each covers along an axis where image +/// pixel `u` lies at `t + u * s` (device): the overlap of each with the pixel, as a share of the +/// pixel's width in image pixels. What lies past the image's `len` pixels counts as its edge +/// pixel. +fn spans(start: i32, n: usize, t: f64, s: f64, len: usize) -> Vec { + let last = len.saturating_sub(1); + (0..n) + .map(|i| { + let d = f64::from(start) + i as f64; + let (a, b) = ((d - t) / s, (d + 1.0 - t) / s); + let (a, b) = (a.min(b), a.max(b)); + let total = b - a; + let clamp = |u: f64| u.clamp(0.0, last as f64) as usize; + let (first, end) = (clamp(a.floor()), clamp(b.ceil() - 1.0)); + let mut weights = vec![0.0_f32; end - first + 1]; + // Each image pixel's own overlap; what lies before the image goes to the first and + // past it to the last. + let mut u = a.floor(); + while u < b { + let w = (b.min(u + 1.0) - a.max(u)) / total; + if let Some(slot) = weights.get_mut(clamp(u) - first) { + *slot += w as f32; + } + u += 1.0; + } + Span { first, weights } + }) + .collect() +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2753e7cea..81f0139d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-20 · **Change:** minor (an export frames a drop shadow to its blur radius and leaves out layers that draw nothing; a line height in pixels keeps its fraction, as the reference tool lays text out; paint blend modes checked against the reference tool's renders: a layer that isn't pass-through blends its fills among themselves only, a pass-through frame's fills blend with the backdrop under its shadows, drop shadows blend among themselves, inner shadows with the fills, plus lighter adds colours with source-over alpha; M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-20 · **Change:** minor (an image shown smaller than its pixels is drawn as the average of what each pixel covers; an export frames a drop shadow to its blur radius and leaves out layers that draw nothing; a line height in pixels keeps its fraction, as the reference tool lays text out; paint blend modes checked against the reference tool's renders: a layer that isn't pass-through blends its fills among themselves only, a pass-through frame's fills blend with the backdrop under its shadows, drop shadows blend among themselves, inner shadows with the fills, plus lighter adds colours with source-over alpha; M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -651,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Images shown smaller than their pixels (M3, paint): on the canvas and in exports each device pixel is now the average of the image area it covers, wherever the image falls between pixels, as the reference tool's exports come out (a 1 254 px illustration shown at 265 px matches its export pixel for pixel). It was sampled bicubically at pixel centres from the full image (exports) or from a copy at the next of 256…8192 px (canvas), which kept edges and fine lines aliased and, an image at a fractional position, dropped that fraction. Straight (unrotated) images scaled down along both axes; rotated or skewed ones and tiles are sampled as before, and the work is capped (a huge image shown small falls back too). Found on an iOS kit's illustrations: differing pixels 1–2% → 0–0.4%. Test: `export_framing_tests::an_image_shown_smaller_exports_the_average_of_what_each_pixel_covers`. Percentages and hours unchanged at this rounding | | 2026-11-20 | minor | Export area as the reference tool frames it (M3, export): a drop shadow reaches into a PNG/JPG/SVG/PDF export's area as far as its blur radius (plus spread, toward its offset), as the tool's exports and render bounds take it (a 44 px button with a 16 px shadow exports 76 × 76; it was 92 × 92, three standard deviations), and a layer that draws nothing (no visible fill, stroke, effect or children: a placeholder whose image was taken out) no longer widens its parent's export (a 300 × 225 illustration holding an empty 1 448 × 1 086 box exported at that size). The canvas's culling and redraw areas keep the whole blur. Found on an iOS kit's glass buttons, switches and illustrations: differing pixels 20–42% → under 1% each. Tests: `crates/render/src/export_framing_tests.rs`. Percentages and hours unchanged at this rounding | | 2026-11-20 | minor | Text line heights given in pixels keep their fraction (M3, text metrics): lines 22.5 px apart stay 22.5 apart, the glyphs centred in each, and a self-sizing box rounds the lines' total up to a whole pixel (three lines of 22.5 make a 68 px box, three of 18.4 a 56 px one), as the reference tool's own saved layouts show (`derivedTextData` of 1 486 text layers in one `.fig`, 470 of them with pixel line heights from 15 to 38.5: those keep their pitch; Auto and percentages round, as before). They were rounded to whole pixels (22.5 → 23), so every paragraph drifted half a pixel a line. Found on an iOS kit: four-line paragraphs ended 1.5 px low; differing pixels on those screens 3% → 1.7%. Test: `metrics_tests::pixel_line_heights_keep_their_fraction` (the pinned "pixel values round too, not measured" case is replaced). Percentages and hours unchanged at this rounding | | 2026-11-20 | minor | Paint blend modes checked against renders of a synthetic file by the reference tool (9 scenes; differing pixels before → after: up to 39% → under 0.2% each) and fixed on the canvas and in PNG exports: a layer in a blend mode of its own (Normal included) blends its fills with each other only, then lays them over the canvas as one, with or without effects (they blended with the backdrop until a layer had an effect, then not); a pass-through frame's fills blend with the backdrop also when it has drop or inner shadows (it was drawn as an isolated layer); drop shadows blend by their modes among themselves, then lie under the layer as one (two linear-burn shadows darkened the backdrop); inner shadows blend with the fills under them by their own mode (they were drawn normally); plus lighter adds the premultiplied colours and combines the alphas as source-over does (tiny-skia's sum made a translucent stack opaque). Found on iOS kit buttons and alerts imported from a `.fig`: their fill stacks (plus lighter, luminosity) drew mid grey instead of near white. Tests: `crates/render/src/fill_blend_tests.rs`. SVG and PDF exports unchanged. Percentages and hours unchanged at this rounding |