From dd5bec4cade457c2bc4636c907e70c7f5606b172 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 11:38:01 -0800 Subject: [PATCH 1/2] Thumbnails: node renders and swatch previews become images without a copy Every thumbnail and preview rendered a node, a region or a pattern swatch into a byte buffer, and canvas::color_image then copied those bytes into a new Vec for the egui image. The Layers rows, Graphic Styles large preview, Asset Export tiles, Graph Design preview, Navigator, Transparency object and mask thumbnails, pattern swatches, Symbols panel pictures and the Composite Fonts sample each paid that copy, and a supersampled render allocated a second full-size buffer to downsample into. The renderer now renders these in words as well, as the canvas frame already does: render_node_words, render_node_thumbnail_words(_with), render_thumbnail_words, render_region_with_words and render_pattern_swatch_words. node_pixels and the pattern swatch are generic over the frame pixel type, and a supersampled render downsamples straight into the buffer it returns. Each caller hands the words to color_image_owned, which keeps the buffer. canvas::color_image has no callers left and is removed. Each moved path has a test that checks the image holds the buffer the pixels were rendered into, and the render tests check that the words hold the same bytes as the byte renders. --- crates/render/src/lib.rs | 2 +- crates/render/src/options.rs | 9 +- crates/render/src/pattern.rs | 32 ++++++- crates/render/src/renderer.rs | 88 +++++++++++++++-- crates/render/src/tests/words.rs | 94 ++++++++++++++++++- crates/ui-egui/Cargo.toml | 2 +- crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/canvas/raster.rs | 34 ++++--- crates/ui-egui/src/canvas/tests.rs | 2 +- .../src/dialogs/composite_fonts/sample.rs | 31 ++++-- .../src/dialogs/composite_fonts/tests.rs | 1 + crates/ui-egui/src/dialogs/graph_design.rs | 16 +++- crates/ui-egui/src/panels/asset_export.rs | 28 +++--- crates/ui-egui/src/panels/graphic_styles.rs | 8 +- crates/ui-egui/src/panels/layers/thumbs.rs | 24 ++++- crates/ui-egui/src/panels/navigator.rs | 18 +++- crates/ui-egui/src/panels/swatches.rs | 11 ++- crates/ui-egui/src/panels/swatches/tests.rs | 15 +++ crates/ui-egui/src/panels/symbols.rs | 10 +- crates/ui-egui/src/panels/symbols/tests.rs | 25 ++++- .../ui-egui/src/panels/tests_asset_export.rs | 18 +++- crates/ui-egui/src/panels/transparency.rs | 23 ++++- 22 files changed, 411 insertions(+), 84 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f2b76c525d..2ffbee36b2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -47,7 +47,7 @@ pub use effects::stroke::width_outline; pub use fx::pinned_appearance_for_geometry_edit; pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, installed_memory, newly_undecodable, set_image_cache_budget}; pub use live::expand_live; -pub use pattern::render_pattern_swatch; +pub use pattern::{render_pattern_swatch, render_pattern_swatch_words}; pub use vectorcraft_effects as effects; pub use vello_cpu; diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index e185504d05..6a9736c85c 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -243,11 +243,11 @@ pub fn supersample_factor(w: u32, h: u32) -> Option { }) } -/// Average each `k`×`k` block of `src` (`w`×`h` pixels of 4 premultiplied bytes) into one pixel. -pub(crate) fn downsample(src: &[u8], w: usize, h: usize, k: usize) -> Vec { - let (ow, oh) = (w / k.max(1), h / k.max(1)); +/// Average each `k`×`k` block of `src` (pixels of 4 premultiplied bytes in rows `w` wide) into one +/// pixel of `out`, whose rows are `w` / `k` pixels wide. +pub(crate) fn downsample(src: &[u8], w: usize, k: usize, out: &mut [u8]) { + let ow = w / k.max(1); let n = (k * k).max(1) as u32; - let mut out = vec![0u8; ow * oh * 4]; for (o, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { let (ox, oy) = (o % ow.max(1), o / ow.max(1)); let mut acc = [0u32; 4]; @@ -263,7 +263,6 @@ pub(crate) fn downsample(src: &[u8], w: usize, h: usize, k: usize) -> Vec { *d = ((a + n / 2) / n).min(255) as u8; } } - out } /// For each of `to` pixels spread over `from` (both above 0), the `from` pixels under it and the diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 9e44f5c655..076e80d2e1 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -28,6 +28,7 @@ use vello_cpu::{Pixmap, RenderContext}; use crate::ink::Ink; use crate::lru::{self, FrameCache}; +use crate::renderer::FramePixels; use crate::{Frame, RenderOptions, Rendered, Renderer}; /// Largest super-tile raster side (pixels). @@ -179,6 +180,21 @@ fn rasterize( ink: Ink, mark_undecoded_images: bool, ) -> (Pixmap, bool) { + rasterize_as(r, doc, def, region, size, ink, mark_undecoded_images, |r, ctx| r.finish(ctx, r.raster)) +} + +/// [`rasterize`], with the pixels taken from the context by `finish`. +#[allow(clippy::too_many_arguments)] +fn rasterize_as( + r: &mut Renderer, + doc: &Document, + def: &PatternDef, + region: Rect, + size: (u16, u16), + ink: Ink, + mark_undecoded_images: bool, + finish: impl FnOnce(&mut Renderer, &mut RenderContext) -> T, +) -> (T, bool) { let (w, h) = (size.0.max(1), size.1.max(1)); let mut ctx = crate::single_threaded_context(w, h); let view = Affine::scale_non_uniform(w as f64 / region.width().max(1e-9), h as f64 / region.height().max(1e-9)) @@ -213,7 +229,7 @@ fn rasterize( r.draw_arc(&mut ctx, &frame, a); } } - (r.finish(&mut ctx, r.raster), r.image_left_out.take().unwrap_or(false) || images_left_out() > pattern_images_left_out) + (finish(r, &mut ctx), r.image_left_out.take().unwrap_or(false) || images_left_out() > pattern_images_left_out) } /// Run `f` with the shared off-screen renderer (None when nested too deep: a pattern whose art @@ -333,13 +349,23 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine, /// A swatch thumbnail of pattern `name`: the tiling around the tile, fitted into `size`². pub fn render_pattern_swatch(doc: &Document, name: &str, size: u32) -> Option { + pattern_swatch(doc, name, size) +} + +/// [`render_pattern_swatch`] with the pixels in words of four bytes, as +/// [`Renderer::render_words`] returns them. +pub fn render_pattern_swatch_words(doc: &Document, name: &str, size: u32) -> Option>> { + pattern_swatch(doc, name, size) +} + +fn pattern_swatch(doc: &Document, name: &str, size: u32) -> Option> { let def = doc.pattern(name)?; let (w, h) = (def.width(), def.height()); let side = w.max(h); let region = Rect::from_center_size((w / 2.0, h / 2.0), (side, side)); let px = size.clamp(1, 1024) as u16; - let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, (px, px), Ink::Display, false))?; - Some(Rendered { width: px as u32, height: px as u32, pixels: crate::group::into_bytes(pm) }) + let (pixels, _) = with_tile_renderer(|r| rasterize_as(r, doc, def, region, (px, px), Ink::Display, false, P::finish))?; + Some(Rendered { width: px as u32, height: px as u32, pixels }) } impl Renderer { diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 1e32c3657b..c2a10b37a4 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -189,9 +189,11 @@ impl Renderer { let hairline = std::mem::replace(&mut self.hairline, f64::from(k)); let big: Rendered = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch); self.hairline = hairline; - let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize); + let mut pixels = P::blank(w as usize * h as usize); + downsample(&big.pixels, big.width as usize, k as usize, pixels.bytes_mut()); + #[cfg(test)] + group::FINISHED.with(|p| p.set(pixels.bytes_mut().as_ptr() as usize)); drop(big); - let pixels = P::from_bytes(pixels); self.stats.micros = now().saturating_sub(start); return Rendered { width: w, height: h, pixels }; } @@ -455,6 +457,12 @@ impl Renderer { self.region(doc, region, scale, opts) } + /// [`Self::render_region_with`] with the pixels in words of four bytes, as + /// [`Self::render_words`] returns them. + pub fn render_region_with_words(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered> { + self.region(doc, region, scale, opts) + } + fn region(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered

{ let (w, h) = region_pixels(region, scale); let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0)); @@ -485,6 +493,16 @@ impl Renderer { /// [`Self::render_node`] with `opts` (e.g. [`RenderOptions::mark_undecoded_images`]). pub fn render_node_with(&mut self, doc: &Document, n: &Arc, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option { + self.node(doc, n, w, h, view, opts) + } + + /// [`Self::render_node`] with the pixels in words of four bytes, as [`Self::render_words`] + /// returns them. + pub fn render_node_words(&mut self, doc: &Document, n: &Arc, w: u16, h: u16, view: Affine) -> Option>> { + self.node(doc, n, w, h, view, &RenderOptions::default()) + } + + fn node(&mut self, doc: &Document, n: &Arc, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option> { let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); self.check_plugins(doc); self.check_symbols(doc); @@ -499,7 +517,7 @@ impl Renderer { /// averaged down, and [`RenderOptions::precise`] picks the quality render mode, as in a page /// render ([`Self::render_as`], [`Self::draw_frame`]). `cell` is as in [`Self::render_as`]. #[allow(clippy::too_many_arguments)] - fn node_pixels( + fn node_pixels( &mut self, doc: &Document, n: &Arc, @@ -509,7 +527,7 @@ impl Renderer { opts: &RenderOptions, forced: bool, cell: u32, - ) -> Vec { + ) -> P { if opts.supersample && opts.anti_alias == AntiAlias::Art && let Some(k) = supersample_factor(u32::from(w), u32::from(h)) @@ -518,9 +536,13 @@ impl Renderer { // `supersample_factor` keeps each side within MAX_CONTEXT_SIDE, so it fits in a u16. let (bw, bh) = (u32::from(w) * k, u32::from(h) * k); let hairline = std::mem::replace(&mut self.hairline, f64::from(k)); - let big = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k); + let big: Vec = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k); self.hairline = hairline; - return downsample(&big, bw as usize, bh as usize, k as usize); + let mut pixels = P::blank(usize::from(w) * usize::from(h)); + downsample(&big, bw as usize, k as usize, pixels.bytes_mut()); + #[cfg(test)] + group::FINISHED.with(|p| p.set(pixels.bytes_mut().as_ptr() as usize)); + return pixels; } let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); let mut ctx = single_threaded_context(w, h); @@ -538,10 +560,10 @@ impl Renderer { } else { self.draw_arc(&mut ctx, &frame, n); } - let pm = self.finish(&mut ctx, self.raster); + let pixels = P::finish(self, &mut ctx); self.end_frame(); self.raster = raster; - group::into_bytes(pm) + pixels } /// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into @@ -565,6 +587,42 @@ impl Renderer { background: Option<[u8; 4]>, opts: &RenderOptions, ) -> Option { + self.node_thumbnail(doc, n, size, background, opts) + } + + /// [`Self::render_node_thumbnail`] with the pixels in words of four bytes, as + /// [`Self::render_words`] returns them. + pub fn render_node_thumbnail_words(&mut self, doc: &Document, n: &Node, size: u32, background: Option<[u8; 4]>) -> Option>> { + self.node_thumbnail(doc, n, size, background, &RenderOptions::default()) + } + + /// [`Self::render_thumbnail`] with the pixels in words of four bytes, as + /// [`Self::render_words`] returns them. + pub fn render_thumbnail_words(&mut self, doc: &Document, id: NodeId, size: u32) -> Option>> { + self.node_thumbnail(doc, doc.node(id)?, size, None, &RenderOptions::default()) + } + + /// [`Self::render_node_thumbnail_with`] with the pixels in words of four bytes, as + /// [`Self::render_words`] returns them. + pub fn render_node_thumbnail_words_with( + &mut self, + doc: &Document, + n: &Node, + size: u32, + background: Option<[u8; 4]>, + opts: &RenderOptions, + ) -> Option>> { + self.node_thumbnail(doc, n, size, background, opts) + } + + fn node_thumbnail( + &mut self, + doc: &Document, + n: &Node, + size: u32, + background: Option<[u8; 4]>, + opts: &RenderOptions, + ) -> Option> { let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); self.check_plugins(doc); self.check_symbols(doc); @@ -573,9 +631,9 @@ impl Renderer { // A 1-pixel margin on each side, unless the thumbnail is too small to keep one. let s = (w as f64 - 2.0).max(1.0) / b.width().max(b.height()).max(1e-6); let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2()); - let mut pixels = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1); + let mut pixels: P = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1); if let Some(bg) = background { - over_background(&mut pixels, bg); + over_background(pixels.bytes_mut(), bg); } Some(Rendered { width: w as u32, height: w as u32, pixels }) } @@ -605,6 +663,8 @@ pub(crate) trait FramePixels: Sized { fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self; /// The pixels in `bytes` (four a pixel). fn from_bytes(bytes: Vec) -> Self; + /// `pixels` transparent pixels, to be written through [`Self::bytes_mut`]. + fn blank(pixels: usize) -> Self; /// The pixels as bytes, four a pixel. fn bytes_mut(&mut self) -> &mut [u8]; } @@ -618,6 +678,10 @@ impl FramePixels for Vec { bytes } + fn blank(pixels: usize) -> Self { + vec![0; pixels * 4] + } + fn bytes_mut(&mut self) -> &mut [u8] { self } @@ -646,6 +710,10 @@ impl FramePixels for Vec { bytes.as_chunks::<4>().0.iter().map(|p| u32::from_ne_bytes(*p)).collect() } + fn blank(pixels: usize) -> Self { + vec![0; pixels] + } + fn bytes_mut(&mut self) -> &mut [u8] { bytemuck::cast_slice_mut(self) } diff --git a/crates/render/src/tests/words.rs b/crates/render/src/tests/words.rs index 27b30d9961..70df3bf590 100644 --- a/crates/render/src/tests/words.rs +++ b/crates/render/src/tests/words.rs @@ -1,10 +1,12 @@ //! A frame rendered in words ([`Renderer::render_words`]): the bytes [`Renderer::render`] returns, -//! rendered straight into the words. +//! rendered straight into the words. Node renders, thumbnails, regions with options and pattern +//! swatches render in words the same way. use std::cell::Cell; use vectorcraft_color::{BlendMode as Blend, Color, Paint}; -use vectorcraft_doc::{Appearance, ColorMode, Node}; +use vectorcraft_doc::pattern::pattern_paint; +use vectorcraft_doc::{Appearance, ColorMode, Node, PatternDef}; use vectorcraft_geom::shapes; use crate::group::FINISHED; @@ -95,3 +97,91 @@ fn a_region_in_words_holds_the_bytes_of_the_region_in_bytes() { let words = Renderer::new().render_region_words(&plain, region, 1.3, false); assert_eq!(words.pixels.as_ptr() as usize, finished(), "a region's words are returned without a copy"); } + +/// The page of [`page`] with [`square`], [`blending_group`] and a square filled with the pattern +/// "Checks" (a red square in a 20 pt tile) on it. +fn patterned() -> Document { + page(ColorMode::Rgb, |d| { + let red = rect(d, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(1.0, 0.0, 0.0)); + let mut def = PatternDef::new("Checks", vec![Arc::new(red)]); + def.tile = Rect::new(0.0, 0.0, 20.0, 20.0); + d.patterns.push(def); + let filled = Appearance::basic(pattern_paint("Checks"), Paint::None, 0.0); + let filled = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 90.0, 90.0)), filled); + vec![square(d), blending_group(d), filled] + }) +} + +fn same_bytes(words: &Rendered>, bytes: &Rendered, what: &str) { + assert_eq!((words.width, words.height), (bytes.width, bytes.height), "{what}: the size"); + assert!(bytemuck::cast_slice::(&words.pixels) == bytes.pixels.as_slice(), "{what}: the same bytes"); +} + +#[test] +fn nodes_thumbnails_and_swatches_in_words_hold_the_bytes_of_the_same_renders_in_bytes() { + let d = patterned(); + let nodes = d.layers[0].children().expect("a layer").to_vec(); + let view = Affine::scale(0.7) * Affine::translate((-4.0, -9.0)); + let supersampled = RenderOptions { supersample: true, precise: true, image_mips: true, ..Default::default() }; + for (i, n) in nodes.iter().enumerate() { + let bytes = Renderer::new().render_node(&d, n, 53, 41, view).expect("a node render"); + let words = Renderer::new().render_node_words(&d, n, 53, 41, view).expect("a node render"); + same_bytes(&words, &bytes, &format!("node {i}")); + for (what, background, opts) in [ + ("transparent", None, RenderOptions::default()), + ("on white", Some([255; 4]), RenderOptions::default()), + ("on a translucent color", Some([10, 200, 90, 128]), RenderOptions::default()), + ("supersampled", None, supersampled.clone()), + ("supersampled on white", Some([255; 4]), supersampled.clone()), + ] { + let bytes = Renderer::new().render_node_thumbnail_with(&d, n, 37, background, &opts).expect("a thumbnail"); + let words = Renderer::new().render_node_thumbnail_words_with(&d, n, 37, background, &opts).expect("a thumbnail"); + same_bytes(&words, &bytes, &format!("node {i}'s thumbnail, {what}")); + } + let bytes = Renderer::new().render_node_thumbnail(&d, n, 31, Some([255; 4])).expect("a thumbnail"); + let words = Renderer::new().render_node_thumbnail_words(&d, n, 31, Some([255; 4])).expect("a thumbnail"); + same_bytes(&words, &bytes, &format!("node {i}'s thumbnail on white, default options")); + let bytes = Renderer::new().render_thumbnail(&d, n.id, 29).expect("a thumbnail"); + let words = Renderer::new().render_thumbnail_words(&d, n.id, 29).expect("a thumbnail"); + same_bytes(&words, &bytes, &format!("node {i}'s thumbnail by id")); + } + let region = Rect::new(5.0, 15.0, 70.0, 90.0); + for (what, opts) in [("outline", RenderOptions { outline: true, ..Default::default() }), ("supersampled", supersampled)] { + let bytes = Renderer::new().render_region_with(&d, region, 1.3, &opts); + let words = Renderer::new().render_region_with_words(&d, region, 1.3, &opts); + same_bytes(&words, &bytes, &format!("the region, {what}")); + } + let bytes = render_pattern_swatch(&d, "Checks", 23).expect("a swatch"); + let words = render_pattern_swatch_words(&d, "Checks", 23).expect("a swatch"); + same_bytes(&words, &bytes, "the pattern swatch"); + assert!(render_pattern_swatch_words(&d, "Missing", 23).is_none(), "a pattern the document lacks has no swatch"); + assert!(Renderer::new().render_thumbnail_words(&d, NodeId(u64::MAX), 29).is_none(), "a node the document lacks has no thumbnail"); +} + +#[test] +fn nodes_thumbnails_and_swatches_in_words_are_returned_in_the_buffer_they_rendered_into() { + let d = patterned(); + let n = d.layers[0].children().expect("a layer")[1].clone(); + let mut r = Renderer::new(); + let out = r.render_node_words(&d, &n, 40, 40, Affine::IDENTITY).expect("a node render"); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "a node's words are returned without a copy"); + let supersampled = RenderOptions { supersample: true, ..Default::default() }; + for background in [None, Some([255; 4])] { + for (what, opts) in [("", RenderOptions::default()), (" supersampled", supersampled.clone())] { + let out = r.render_node_thumbnail_words_with(&d, &n, 48, background, &opts).expect("a thumbnail"); + let at = out.pixels.as_ptr() as usize; + assert_eq!(at, finished(), "background {background:?}{what}: a thumbnail's words are returned without a copy"); + } + } + let out = r.render_node_thumbnail_words(&d, &n, 48, Some([255; 4])).expect("a thumbnail"); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "a thumbnail on a color's words are returned without a copy"); + let out = r.render_words(&d, 64, 48, Affine::IDENTITY, &supersampled); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "a supersampled frame's words are returned without a copy"); + let out = r.render_thumbnail_words(&d, n.id, 32).expect("a thumbnail"); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "a thumbnail's words by id are returned without a copy"); + let plain = page(ColorMode::Rgb, |d| vec![square(d)]); + let out = r.render_region_with_words(&plain, Rect::new(5.0, 15.0, 70.0, 90.0), 1.3, &RenderOptions::default()); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "a region's words with options are returned without a copy"); + let out = render_pattern_swatch_words(&d, "Checks", 20).expect("a swatch"); + assert_eq!(out.pixels.as_ptr() as usize, finished(), "a swatch's words are returned without a copy"); +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 49fad8d56f..9dd168c0eb 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -64,7 +64,7 @@ vectorcraft-cad = { workspace = true } vectorcraft-eps = { workspace = true } vectorcraft-format = { workspace = true } egui = { workspace = true, features = ["bytemuck", "default_fonts", "monochrome_emoji_fonts"] } -# With egui's `bytemuck`: copies rendered rasters into egui images whole (`canvas::color_image`). +# With egui's `bytemuck`: hands rendered rasters to egui images in their own buffers (`canvas::color_image_owned`). # `default_fonts`: egui 0.37 makes its bundled faces opt-in, and a dependency's dev-features do not # reach our tests; `theme::install_fonts` starts from `FontDefinitions::default()`, which is empty # without them (production would lay out tofu, and the no-interface-fonts tests would bind nothing). diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 73b97bce0f..752d3930b5 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -51,7 +51,9 @@ pub use fill::Fill; use home::home; pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, pane, tile, tiled_area}; -pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; +pub(crate) use raster::{KeptFrame, color_image_owned, render_job}; +#[cfg(test)] +pub(crate) use raster::{assert_handed_over, clear_handed_over}; pub(crate) use rulers::{general_lengths, stroke_lengths}; pub use selection::HoverObjectKey; pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, has_colors, is_task_bar_action, read_hidden_task_bar_actions}; diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index c204df83f7..c1a17eddc8 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -18,25 +18,13 @@ use super::{BodyKind, in_gesture}; use crate::doc_windows::Win; use crate::{CacheKey, VectorcraftApp}; -/// The rendered raster `img` as an egui image. Both are premultiplied RGBA8, so its bytes are copied -/// over whole instead of pixel by pixel, which costs milliseconds for a canvas on a large screen. -/// A raster whose bytes don't match its size gives an empty image of that size. -pub(crate) fn color_image(img: &vectorcraft_render::Rendered) -> egui::ColorImage { - let size = [img.width as usize, img.height as usize]; - let expected = size[0].saturating_mul(size[1]).saturating_mul(4); - if expected == img.pixels.len() { - let pixels: Vec = bytemuck::cast_slice(&img.pixels).to_vec(); - egui::ColorImage::new(size, pixels) - } else { - egui::ColorImage::new(size, vec![egui::Color32::TRANSPARENT; size[0].saturating_mul(size[1])]) - } -} - /// The raster `img` rendered in words ([`vectorcraft_render::Renderer::render_words`]) as an egui /// image, in the buffer `img` holds: a word and a [`egui::Color32`] are both four bytes aligned to /// four, so the pixels are not copied. A raster whose pixels don't match its size gives an empty /// image of that size. pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered>) -> egui::ColorImage { + #[cfg(test)] + HANDED_OVER.with(|p| p.set(img.pixels.as_ptr() as usize)); let size = [img.width as usize, img.height as usize]; if size[0].saturating_mul(size[1]) == img.pixels.len() { let pixels: Vec = bytemuck::allocation::try_cast_vec(img.pixels).unwrap_or_else(|(_, v)| bytemuck::cast_slice(&v).to_vec()); @@ -757,6 +745,24 @@ thread_local! { /// frame the test finished before it lands in the wait. A test that answers the job from /// another thread sets [`std::time::Duration::MAX`] to wait for that answer. pub(crate) static TEST_FIRST_FRAME_GRACE: std::cell::Cell = const { std::cell::Cell::new(std::time::Duration::ZERO) }; + /// The address of the words the last [`color_image_owned`] on this thread was given. + static HANDED_OVER: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Clears what [`assert_handed_over`] checks, before the image it checks is made. +#[cfg(test)] +pub(crate) fn clear_handed_over() { + HANDED_OVER.with(|p| p.set(0)); +} + +/// Asserts that `image` was made by [`color_image_owned`] on this thread since +/// [`clear_handed_over`], in the words it was given: the pixels were handed over, not copied. +#[cfg(test)] +#[track_caller] +pub(crate) fn assert_handed_over(image: &egui::ColorImage, what: &str) { + let given = HANDED_OVER.with(std::cell::Cell::get); + assert!(given != 0, "{what}: the image is made from words handed over"); + assert_eq!(image.pixels.as_ptr() as usize, given, "{what}: the image holds the words it was given, not a copy"); } /// [`render_ms`] in unit tests: the time [`TEST_RENDER_MS`] holds. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 7be7f49dc2..3fedcc557d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6975,7 +6975,7 @@ fn the_worker_s_frame_reaches_its_texture_image_in_the_buffer_it_was_rendered_in let color = color_image_owned(frame); assert_eq!(color.pixels.as_ptr() as usize, at, "the frame's pixels are handed to the image, not copied"); let bytes = vectorcraft_render::Renderer::new().render(&doc, job.w, job.h, job.view, &job.opts); - assert!(color.pixels == color_image(&bytes).pixels, "the image holds the frame's pixels"); + assert!(bytemuck::cast_slice::(&color.pixels) == bytes.pixels.as_slice(), "the image holds the frame's pixels"); assert_eq!(color.size, [256, 128]); // A raster whose pixels don't match its size gives an empty image of that size. let short = vectorcraft_render::Rendered { width: 3, height: 2, pixels: vec![u32::MAX; 5] }; diff --git a/crates/ui-egui/src/dialogs/composite_fonts/sample.rs b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs index 6b7f24ac6f..f9ad9e7d5f 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/sample.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs @@ -349,22 +349,21 @@ fn image(f: &CompositeFont, zoom: u64, marks: &[Mark], ppp: f32, ink: Color32) - mark_line(&mut rendered, ((base - y) as f32 * ppp).round(), ppp.ceil().max(1.0) as usize, m.color()); } } - crate::canvas::color_image(&rendered) + crate::canvas::color_image_owned(rendered) } /// Draws a horizontal line `thickness` pixels thick from row `y` across `image`; a row outside it draws nothing. -fn mark_line(image: &mut vectorcraft_render::Rendered, y: f32, thickness: usize, color: Color32) { +fn mark_line(image: &mut vectorcraft_render::Rendered>, y: f32, thickness: usize, color: Color32) { if !y.is_finite() || y < 0.0 { return; } let (width, height) = (image.width as usize, image.height as usize); let first = y as usize; + let word = u32::from_ne_bytes(color.to_array()); for row in first..first.saturating_add(thickness).min(height) { - let start = row.saturating_mul(width).saturating_mul(4); - if let Some(line) = image.pixels.get_mut(start..start.saturating_add(width.saturating_mul(4))) { - for pixel in line.as_chunks_mut::<4>().0 { - pixel.copy_from_slice(&color.to_array()); - } + let start = row.saturating_mul(width); + if let Some(line) = image.pixels.get_mut(start..start.saturating_add(width)) { + line.fill(word); } } } @@ -372,7 +371,7 @@ fn mark_line(image: &mut vectorcraft_render::Rendered, y: f32, thickness: usize, /// The sample of `f` set at `size` points in `ink`, its baseline `baseline` points down from the /// top, drawn by the renderer as the canvas draws type (color and bitmap glyphs in their own /// colors) into `px` pixels at `ppp` pixels per point. -pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered { +pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered> { let (w, h) = px; let mut doc = vectorcraft_doc::Document::new(f64::from(w) / f64::from(ppp), f64::from(h) / f64::from(ppp)); let font = sample_font(f); @@ -384,8 +383,8 @@ pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), let t = TextObject::point(Point::new(INSET, baseline), &sample, style); let node = std::sync::Arc::new(vectorcraft_doc::Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::Text(Box::new(t)))); let view = Affine::scale(f64::from(ppp)); - let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h) * 4] }; - RENDERER.with(|r| r.borrow_mut().render_node(&doc, &node, w, h, view)).unwrap_or_else(empty) + let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h)] }; + RENDERER.with(|r| r.borrow_mut().render_node_words(&doc, &node, w, h, view)).unwrap_or_else(empty) } #[cfg(test)] @@ -477,4 +476,16 @@ mod zoom_tests { assert_eq!(fields(&panel)["zoom"], json!(400), "canceling an older popup must not undo the later automation edit"); assert_eq!(panel.value_role("Zoom", Role::COMBO_BOX).as_deref(), Some("400%")); } + + /// The sample's image holds the pixels the sample was rendered into, with its lines drawn in. + #[test] + fn the_sample_image_is_handed_over_with_its_lines_drawn_in() { + let f = CompositeFont::new("Sample draft", "Source Sans 3", "Regular"); + crate::canvas::clear_handed_over(); + let image = image(&f, 100, &[Mark::Baseline], 1.0, Color32::BLACK); + crate::canvas::assert_handed_over(&image, "the sample"); + let [w, _] = image.size; + let line = image.pixels.chunks(w).any(|row| row.iter().all(|p| *p == Mark::Baseline.color())); + assert!(line, "the baseline is drawn across the sample"); + } } diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index be02c8046c..44eebcdb49 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -585,6 +585,7 @@ fn the_sample_draws_color_glyphs_in_their_colors() { colr.size = 300.0; f.custom = vec![CustomCharSet { name: "Color".into(), characters: COLOUR_CHAR.to_string(), part: colr }]; let img = sample::draw(&f, 36.0, 120.0, (900, 160), 1.0, egui::Color32::BLACK); + let img = vectorcraft_render::Rendered { width: img.width, height: img.height, pixels: bytemuck::cast_slice::(&img.pixels).to_vec() }; let red = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).any(|(x, y)| { let p = img.pixel(x, y); p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200 diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 07c585bd50..c036f4fb7d 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -672,8 +672,8 @@ fn thumbnail(doc: &Document, art: &Node) -> egui::ColorImage { static RENDERER: RefCell = RefCell::new(vectorcraft_render::Renderer::new()); } RENDERER - .with(|r| r.borrow_mut().render_node_thumbnail(doc, art, PREVIEW_PX, Some([255, 255, 255, 255]))) - .map_or_else(blank, |img| crate::canvas::color_image(&img)) + .with(|r| r.borrow_mut().render_node_thumbnail_words(doc, art, PREVIEW_PX, Some([255, 255, 255, 255]))) + .map_or_else(blank, crate::canvas::color_image_owned) } /// The designs among `selection`'s rows. @@ -909,6 +909,18 @@ mod tests { app.run("select.set", json!({"ids": [g]})).unwrap(); } + /// A design's preview holds the pixels it was rendered into. + #[test] + fn a_designs_preview_is_handed_to_its_image_without_a_copy() { + let (app, _ctx) = app_with_design(); + let doc = &app.session.active().unwrap().doc; + let design = doc.graph_designs.first().expect("the new design"); + crate::canvas::clear_handed_over(); + let image = super::thumbnail(doc, &design.art); + assert_eq!(image.size, [super::PREVIEW_PX as usize; 2], "the preview's size"); + crate::canvas::assert_handed_over(&image, "the design's preview"); + } + /// The open dialog's fields, as automation lists them. fn fields(app: &VectorcraftApp) -> Value { app.dialogs().unwrap().with(|host| host.open_dialogs()).last().unwrap().fields.clone().unwrap() diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index af614e819f..1864fff211 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -143,17 +143,7 @@ pub(crate) fn paint_thumb(painter: &egui::Painter, revision: Revision, doc: &Doc let key = (nodes, px); let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| { let art: Vec<&Node> = ids().iter().filter_map(|id| doc.node(*id)).collect(); - // Same Art Optimized supersample as assets.export (#983): abutting fills leave no seam in - // the tile (Layers row thumbs stay cheap without it). - let opts = vectorcraft_render::RenderOptions { image_mips: true, precise: true, supersample: true, ..Default::default() }; - let img = RENDERER.with(|rr| match art.as_slice() { - [one] => rr.borrow_mut().render_node_thumbnail_with(doc, one, px, None, &opts), - many => { - let group = Node::group(NodeId(0), many.iter().map(|n| Arc::new((*n).clone())).collect()); - rr.borrow_mut().render_node_thumbnail_with(doc, &group, px, None, &opts) - } - })?; - let color = crate::canvas::color_image(&img); + let color = RENDERER.with(|rr| thumb_image(&mut rr.borrow_mut(), doc, &art, px))?; let tex = painter.ctx().load_texture(format!("asset-thumb-{}", a.id), color, egui::TextureOptions::LINEAR); CACHE.with(|c| { let mut c = c.borrow_mut(); @@ -169,6 +159,22 @@ pub(crate) fn paint_thumb(painter: &egui::Painter, revision: Revision, doc: &Doc } } +/// The objects `art` of `doc` (back to front) fitted into `px` pixels square, transparent: the +/// image of an asset's tile. `None` when they have no bounds. +pub(super) fn thumb_image(r: &mut vectorcraft_render::Renderer, doc: &Document, art: &[&Node], px: u32) -> Option { + // Same Art Optimized supersample as assets.export (#983): abutting fills leave no seam in + // the tile (Layers row thumbs stay cheap without it). + let opts = vectorcraft_render::RenderOptions { image_mips: true, precise: true, supersample: true, ..Default::default() }; + let img = match art { + [one] => r.render_node_thumbnail_words_with(doc, one, px, None, &opts), + many => { + let group = Node::group(NodeId(0), many.iter().map(|n| Arc::new((*n).clone())).collect()); + r.render_node_thumbnail_words_with(doc, &group, px, None, &opts) + } + }?; + Some(crate::canvas::color_image_owned(img)) +} + /// The document's assets as the tile grid's items. struct Assets { ids: Vec, diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index d85933f8cf..64a45b963e 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -384,8 +384,8 @@ fn render_object(app: &VectorcraftApp, doc: &Document, n: &Node, g: &GraphicStyl } else { styled_node(n, g, app.session.prefs.override_char_color) }; - let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail(doc, &styled, px, Some([255; 4])))?; - let mut img = crate::canvas::color_image(&img); + let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_words(doc, &styled, px, Some([255; 4])))?; + let mut img = crate::canvas::color_image_owned(img); if empty { slash(&mut img); } @@ -1321,13 +1321,17 @@ mod tests { // The large preview on the selected rectangle. let st = app.session.active().unwrap(); let n = st.doc.node(st.selection.objects[0]).unwrap(); + crate::canvas::clear_handed_over(); let img = render_object(&app, &st.doc, n, &empty, 60).unwrap(); + crate::canvas::assert_handed_over(&img, "the large preview with the slash"); assert!(red(px(&img, 30, 30))); assert!(dark(px(&img, 1, 30)), "{:?}", px(&img, 1, 30)); assert_eq!(px(&img, 10, 10), Color32::WHITE); // A style that paints keeps its own look there, without the slash. let blue = GraphicStyle::new("Blue", Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 1.0)); + crate::canvas::clear_handed_over(); let img = render_object(&app, &st.doc, n, &blue, 60).unwrap(); + crate::canvas::assert_handed_over(&img, "the large preview"); assert_eq!(px(&img, 30, 30), Color32::from_rgb(0, 0, 255)); } diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index fe3bab7649..2900815237 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -128,7 +128,7 @@ pub(crate) fn render(node: Arc, doc: Arc, request: &ThumbRequest static RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); } return match RENDERER.with(|r| render_thumb(&mut r.borrow_mut(), &doc, &node, side)) { - Some(img) => ThumbRender::Ready(crate::canvas::color_image(&img)), + Some(img) => ThumbRender::Ready(crate::canvas::color_image_owned(img)), None => ThumbRender::Blank, }; } @@ -141,7 +141,7 @@ pub(crate) fn render(node: Arc, doc: Arc, request: &ThumbRequest if cancel.is_cancelled() { return Err(cancelled()); } - Ok(img.map_or(LoadedPicture::Blank, |img| LoadedPicture::Image(crate::canvas::color_image(&img)))) + Ok(img.map_or(LoadedPicture::Blank, |img| LoadedPicture::Image(crate::canvas::color_image_owned(img)))) })) } @@ -309,8 +309,8 @@ fn light_row(n: &Node, quick: Option, doc: &Document) -> bool { } /// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or a lane. -fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option { - r.render_node_thumbnail_with(doc, n, px, None, &thumb_options()) +fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option>> { + r.render_node_thumbnail_words_with(doc, n, px, None, &thumb_options()) } #[cfg(test)] @@ -598,7 +598,7 @@ mod tests { let ThumbRender::Later(job) = rendered(doc, n, &request) else { panic!("a heavy node is made on a lane") }; let Ok(LoadedPicture::Image(there)) = job(&Cancel::new()) else { panic!("the job draws the node") }; let here = render_thumb(&mut vectorcraft_render::Renderer::new(), doc, n, request.side).expect("this thread draws the node"); - let here = crate::canvas::color_image(&here); + let here = crate::canvas::color_image_owned(here); assert!(here.pixels.iter().any(|p| p.a() > 0), "the thumbnail shows the art"); assert_eq!((there.size, &there.pixels), (here.size, &here.pixels), "the same pixels"); } @@ -642,4 +642,18 @@ mod tests { assert!(matches!(before.render(&key, &request), ThumbRender::Ready(_))); assert!(matches!(after.render(&key, &request), ThumbRender::Later(_)), "and a long path is made on a lane"); } + + #[test] + fn a_rows_thumbnail_is_handed_to_its_image_without_a_copy() { + let request = ThumbRequest::for_cell(24.0, 1.0); + let (doc, n) = doc_with(|id| rect(id.0)); + crate::canvas::clear_handed_over(); + let ThumbRender::Ready(here) = rendered(&doc, &n, &request) else { panic!("a small object's thumbnail is made at once") }; + crate::canvas::assert_handed_over(&here, "a thumbnail made here"); + let (doc, n) = doc_with(|id| path(id.0, 50_000)); + let ThumbRender::Later(job) = rendered(&doc, &n, &request) else { panic!("a long path is made on a lane") }; + crate::canvas::clear_handed_over(); + let Ok(LoadedPicture::Image(there)) = job(&Cancel::new()) else { panic!("the job draws the node") }; + crate::canvas::assert_handed_over(&there, "a thumbnail made on a lane"); + } } diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index c1f6bcc537..9cf9345191 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -173,8 +173,8 @@ impl ThumbSource for NavThumbs { ThumbRender::Later(Box::new(move |_cancel| { let options = image_options(key); let renderer = if key.solid_dashes { &SOLID_RENDERER } else { &NAV_RENDERER }; - let image = renderer.with(|r| r.borrow_mut().render_region_with(&doc, region, scale, &options)); - Ok(LoadedPicture::Image(crate::canvas::color_image(&image))) + let image = renderer.with(|r| r.borrow_mut().render_region_with_words(&doc, region, scale, &options)); + Ok(LoadedPicture::Image(crate::canvas::color_image_owned(image))) })) } } @@ -293,6 +293,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { mod tests { use super::*; + /// The navigator's picture, with and without solid dashes, holds the pixels it was rendered into. + #[test] + fn the_navigator_picture_is_handed_to_its_image_without_a_copy() { + let doc = Arc::new(vectorcraft_doc::Document::new(200.0, 100.0)); + let source = NavThumbs::new(&doc, 1, DRect::new(-10.0, -10.0, 210.0, 110.0)); + for solid_dashes in [false, true] { + let key = NavKey { uid: 1, artboard_only: false, solid_dashes }; + let ThumbRender::Later(job) = source.render(&key, &ThumbRequest::for_cell(60.0, 1.0)) else { panic!("the picture is made on a lane") }; + crate::canvas::clear_handed_over(); + let Ok(LoadedPicture::Image(image)) = job(&craft::host::queue::Cancel::new()) else { panic!("the job draws the document") }; + crate::canvas::assert_handed_over(&image, if solid_dashes { "with solid dashes" } else { "with dashes" }); + } + } + #[test] fn navigator_reports_a_malformed_zoom_entry() { assert_malformed_zoom_entry_reported(show); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index bea36866bb..c821dd9614 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -649,10 +649,8 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: & px, ); let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).unwrap_or_else(|| { - let tex = vectorcraft_render::render_pattern_swatch(doc, pattern, px).map(|img| { - let color = crate::canvas::color_image(&img); - ctx.load_texture(format!("pattern-swatch-{pattern}-{px}"), color, egui::TextureOptions::LINEAR) - }); + let tex = pattern_image(doc, pattern, px) + .map(|color| ctx.load_texture(format!("pattern-swatch-{pattern}-{px}"), color, egui::TextureOptions::LINEAR)); CACHE.with(|c| { let mut c = c.borrow_mut(); if c.len() > 256 { @@ -668,6 +666,11 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: & true } +/// The swatch image of pattern `name` in `doc`, `px` pixels square; `None` when `doc` has no such pattern. +fn pattern_image(doc: &Document, name: &str, px: u32) -> Option { + vectorcraft_render::render_pattern_swatch_words(doc, name, px).map(crate::canvas::color_image_owned) +} + /// The red of None's slash on a swatch tile and of a disabled opacity mask's cross, drawn on the document's white or /// black paper. It is the same in every theme. pub(super) const OFF_MARK: Color32 = Color32::from_rgb(0xe0, 0x20, 0x20); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 9f0d992276..a24a7fab2d 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -1715,3 +1715,18 @@ fn idle_frames_replay_the_swatch_rows() { assert!(panel.shows(red), "and they show the swatch again"); idle(&mut panel, "after an undo"); } + +/// A pattern swatch's image holds the pixels the swatch was rendered into; a pattern the document +/// lacks has no image. +#[test] +fn a_pattern_swatch_image_is_handed_over_without_a_copy() { + let mut app = app(); + let square = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.run("object.pattern.make", json!({"ids": [square], "name": "Dots", "edit": false})).unwrap(); + let doc = doc(&app); + crate::canvas::clear_handed_over(); + let image = pattern_image(&doc, "Dots", 24).expect("the pattern draws"); + assert_eq!(image.size, [24, 24], "the swatch's size"); + crate::canvas::assert_handed_over(&image, "the pattern swatch"); + assert!(pattern_image(&doc, "Missing", 24).is_none(), "no image for a pattern the document lacks"); +} diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index f985e31c65..13eb90bc0d 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -100,7 +100,7 @@ impl ThumbSource for SymbolPictures<'_> { render_art(&mut renderer, self.doc, self.name, vectorcraft_geom::Rect::new(x0, y0, x1, y1), (*w, *h)) } }; - img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image(&img))) + img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image_owned(img))) } } @@ -198,7 +198,7 @@ pub(crate) mod counters { /// Symbol `name` of `doc` rendered `px` pixels wide: an instance at its natural size, alone on a /// copy of `doc` that keeps its resources (the symbols it nests, patterns, images, swatches, /// brushes, graphic styles) but none of its art. -fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str, px: u32) -> Option { +fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str, px: u32) -> Option>> { let (w, h) = symbol_size(doc, name); let mut d = doc.clone(); let layer = d.alloc_id(); @@ -206,7 +206,7 @@ fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str let id = d.alloc_id(); let xf = vectorcraft_geom::Affine::scale_non_uniform(w / 20.0, h / 20.0); d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf })).ok()?; - r.render_thumbnail(&d, id, px) + r.render_thumbnail_words(&d, id, px) } /// Symbol `name` of `doc` (an instance at its natural size, as [`render_thumb`] places it) drawn @@ -218,7 +218,7 @@ fn render_art( name: &str, art: vectorcraft_geom::Rect, (w, h): (u32, u32), -) -> Option { +) -> Option>> { let (aw, ah) = (art.width(), art.height()); if !(aw.is_finite() && ah.is_finite() && aw > 0.0 && ah > 0.0) { return None; @@ -232,7 +232,7 @@ fn render_art( let n = Arc::new(Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf })); let view = vectorcraft_geom::Affine::scale_non_uniform(f64::from(w) / aw, f64::from(h) / ah) * vectorcraft_geom::Affine::translate((-art.x0, -art.y0)); - r.render_node(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view) + r.render_node_words(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view) } /// The active document's current symbol (`symbol.list`'s `current`), read without running a diff --git a/crates/ui-egui/src/panels/symbols/tests.rs b/crates/ui-egui/src/panels/symbols/tests.rs index 23bd444373..2ed6b8d628 100644 --- a/crates/ui-egui/src/panels/symbols/tests.rs +++ b/crates/ui-egui/src/panels/symbols/tests.rs @@ -13,8 +13,9 @@ fn symbols(app: &mut VectorcraftApp) -> Vec { } /// Pixels of `img` that something paints opaquely, and those of them that are red. -fn painted(img: &vectorcraft_render::Rendered) -> (usize, usize) { - let painted: Vec<&[u8; 4]> = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[3] > 200).collect(); +fn painted(img: &vectorcraft_render::Rendered>) -> (usize, usize) { + let bytes: &[u8] = bytemuck::cast_slice(&img.pixels); + let painted: Vec<&[u8; 4]> = bytes.as_chunks::<4>().0.iter().filter(|p| p[3] > 200).collect(); let red = painted.iter().filter(|p| p[0] > 150 && p[1] < 80 && p[2] < 80).count(); (painted.len(), red) } @@ -1199,6 +1200,26 @@ fn an_imported_symbols_thumbnail_frames_its_whole_art() { assert!(orange(inset_x, inset_y) && orange(w - 1 - inset_x, h - 1 - inset_y), "{w} × {h}"); } +/// Both pictures of a symbol become images in the pixels they were rendered into. +#[test] +fn a_symbols_pictures_are_handed_to_their_images_without_a_copy() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Wide"})).unwrap(); + let doc = &*s.doc().unwrap().doc; + let art = vectorcraft_effects::graphic_bounds(doc, "Wide").expect("the art's bounds"); + let pictures = SymbolPictures { doc, name: "Wide" }; + for (what, key) in [ + ("the symbol", SymbolThumb::Symbol { key: 1 }), + ("its art", SymbolThumb::Art { key: 1, w: 40, h: 30, art: [art.x0, art.y0, art.x1, art.y1].map(f64::to_bits) }), + ] { + crate::canvas::clear_handed_over(); + let ThumbRender::Ready(image) = pictures.render(&key, &ThumbRequest::for_cell(40.0, 1.0)) else { panic!("{what} renders at once") }; + crate::canvas::assert_handed_over(&image, what); + } +} + /// A document with symbol "Leaf", whose instance stands where its rectangle was, and symbol /// "Dot", which no instance uses; "Dot" is current. fn leaf_and_dot() -> VectorcraftApp { diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index f0539d5df8..cf1ed1817a 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -11,7 +11,7 @@ use craft::ui::runtime::commands::CommandStates; use serde_json::{Value, json}; use vectorcraft_engine::Session; -use super::asset_export::{menu_rows, menu_states}; +use super::asset_export::{menu_rows, menu_states, thumb_image}; use crate::dialogs::ExportForScreensDialog; use crate::tests::panel_harness::Panel; use crate::{Services, VectorcraftApp}; @@ -1158,3 +1158,19 @@ fn tile_menu_collects_canvas_art_as_one_or_multiple_assets_and_disables_empty_se assert_eq!(picked(&p).len(), if single { 1 } else { 2 }); } } + +/// A tile's image is made in the words its objects were rendered into, for one object and for several. +#[test] +fn an_assets_tile_image_holds_the_rendered_words_without_a_copy() { + let (app, _, [a, b]) = app(false); + let doc = &app.session.active().unwrap().doc; + let node = |id: u64| doc.node(vectorcraft_doc::NodeId(id)).expect("the square"); + let mut r = vectorcraft_render::Renderer::new(); + for (what, art) in [("one object", vec![node(a)]), ("two objects", vec![node(a), node(b)])] { + crate::canvas::clear_handed_over(); + let image = thumb_image(&mut r, doc, &art, 40).expect("the squares draw"); + assert_eq!(image.size, [40, 40], "{what}: the tile's size"); + assert!(image.pixels.iter().any(|p| p.a() > 0), "{what}: the tile shows the art"); + crate::canvas::assert_handed_over(&image, what); + } +} diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 565f56da75..e1265d6e16 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -122,8 +122,8 @@ fn thumb_image(doc: &Arc, obj: &Node, own_mask: bool, px: u32, bg: Opt } else { obj }; - let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_with(doc, n, px.max(8), bg, &super::layers::thumb_options()))?; - Some(crate::canvas::color_image(&img)) + let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_words_with(doc, n, px.max(8), bg, &super::layers::thumb_options()))?; + Some(crate::canvas::color_image_owned(img)) } impl ThumbSource for MaskThumbs<'_> { @@ -786,6 +786,25 @@ mod tests { assert!(Arc::ptr_eq(&undone, &held(&app, n.id)), "the node Undo put back"); } + /// The object and mask thumbnails, on a background or none, hold the pixels they were rendered into. + #[test] + fn object_and_mask_thumbnails_are_handed_to_their_images_without_a_copy() { + let mut app = new_app(); + let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let b = run_cmd(&mut app, "shape.ellipse", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone(); + run_cmd(&mut app, "select.set", json!({"ids": [a, b]})); + run_cmd(&mut app, "transparency.makeOpacityMask", json!({})); + let n = state(&mut app).1.expect("the masked object"); + let doc = app.session.active().unwrap().doc.clone(); + for own_mask in [false, true] { + for bg in [None, Some([255; 4])] { + crate::canvas::clear_handed_over(); + let image = thumb_image(&doc, &n, own_mask, 44, bg).expect("the thumbnail draws"); + crate::canvas::assert_handed_over(&image, &format!("mask {own_mask}, background {bg:?}")); + } + } + } + #[test] fn a_highlighted_blend_mode_applies_only_once_it_is_chosen() { use egui::{Key, Modifiers}; From 7645a787b0b3b582ad59a5e245a63a0d227504f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 07:28:29 -0800 Subject: [PATCH 2/2] Render: a pattern raster takes its region and size as one argument rasterize_as took eight arguments and carried an allow for Clippy's too_many_arguments lint. The region and the pixel size it fills now go in as one pair, so the function stays within the limit without the allow. --- crates/render/src/pattern.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 6f3bb4be78..75d783e8a8 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -172,17 +172,16 @@ pub(crate) fn raster_scale(s: f64, period: (f64, f64)) -> f64 { /// Rasterize `region` (pattern space) of the infinite tiling into a `w`×`h` pixmap, colours as /// `ink` paints them. fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, size: (u16, u16), ink: Ink, images: (bool, bool)) -> (Pixmap, bool) { - rasterize_as(r, doc, def, region, size, ink, images, |r, ctx| r.finish(ctx, r.raster)) + rasterize_as(r, doc, def, (region, size), ink, images, |r, ctx| r.finish(ctx, r.raster)) } -/// [`rasterize`], with the pixels taken from the context by `finish`. -#[allow(clippy::too_many_arguments)] +/// [`rasterize`] of `region` into `size` pixels, with the pixels taken from the context by +/// `finish`. fn rasterize_as( r: &mut Renderer, doc: &Document, def: &PatternDef, - region: Rect, - size: (u16, u16), + (region, size): (Rect, (u16, u16)), ink: Ink, (mark_undecoded_images, smooth_images): (bool, bool), finish: impl FnOnce(&mut Renderer, &mut RenderContext) -> T, @@ -357,7 +356,7 @@ fn pattern_swatch(doc: &Document, name: &str, size: u32) -> Opti let side = w.max(h); let region = Rect::from_center_size((w / 2.0, h / 2.0), (side, side)); let px = size.clamp(1, 1024) as u16; - let (pixels, _) = with_tile_renderer(|r| rasterize_as(r, doc, def, region, (px, px), Ink::Display, (false, true), P::finish))?; + let (pixels, _) = with_tile_renderer(|r| rasterize_as(r, doc, def, (region, (px, px)), Ink::Display, (false, true), P::finish))?; Some(Rendered { width: px as u32, height: px as u32, pixels }) }