Send "SVG Preview" mode images once, at a resolution suited to the zoom (#4856)

* Send SVG Preview images once, at a resolution suited to the zoom

* Avoid copying unhalved canvas images and tolerate float noise in their scale
This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-10-29 23:28:16 -07:00
1 parent cddd828842
commit 0b20fd7869
13 files changed
+270 -99

No files matched your search

Generated
+1
View File
@@ -2470,6 +2470,7 @@ dependencies = [
name = "graphite-wasm-wrapper"
version = "0.0.0"
dependencies = [
"base64",
"graph-craft",
"graphene-std",
"graphite-editor",
@@ -263,8 +263,11 @@ pub enum FrontendMessage {
UpdateRenderStatus {
status: RenderStatus,
},
/// Gives the frontend the canvas images it lacks, and names every canvas the latest render uses so it can drop the rest.
UpdateImageData {
image_data: Vec<RasterizedImage>,
#[serde(rename = "canvasIdsInUse")]
canvas_ids_in_use: Vec<u64>,
},
UpdateDocumentLayerDetails {
data: LayerPanelEntry,
@@ -141,6 +141,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Messages
PortfolioMessage::Init => {
self.executor.forget_canvas_images();
// Tell frontend to load persistent preferences
responses.add(FrontendMessage::TriggerLoadPreferences);
+25 -7
View File
@@ -104,6 +104,8 @@ pub struct NodeGraphExecutor {
/// Documents whose gradient migration pass already ran this session, so entries that failed to measure
/// (kept pending for a retry on the next open) don't re-run the pass on every render request.
gradient_migration_attempted: HashSet<DocumentId>,
/// The canvas images the frontend holds, so a render sends only those it lacks.
canvas_images_sent: HashSet<u64>,
}
#[derive(Debug, Clone)]
@@ -148,10 +150,16 @@ impl NodeGraphExecutor {
gradient_migration: None,
gradient_migration_attempted: HashSet::new(),
pending: None,
canvas_images_sent: HashSet::new(),
};
(node_executor, node_runtime)
}
/// Forgets which canvas images the frontend holds, for a frontend that started over without them.
pub fn forget_canvas_images(&mut self) {
self.canvas_images_sent.clear();
}
/// Allows the test runner to see if any more executions have been queued.
#[cfg(test)]
pub fn current_execution_id(&self) -> u64 {
@@ -861,18 +869,28 @@ impl NodeGraphExecutor {
match render_output.data {
RenderOutputType::Svg { svg, image_data } => {
// Convert each linear-light `Image<Color>` into gamma sRGB bytes (the DOM boundary form) before dispatching.
// The frontend keeps the canvases it was sent until a render stops using them, so only the images it lacks are sent
let canvas_ids_in_use: Vec<u64> = image_data.iter().map(|(id, _)| *id).collect();
let in_use: HashSet<u64> = canvas_ids_in_use.iter().copied().collect();
self.canvas_images_sent.retain(|id| in_use.contains(id));
// Convert each linear-light image, at its display resolution, into gamma sRGB bytes (the DOM boundary form)
let rgba8_bytes = |&color: &_| <[u8; 4]>::from(SRGBA8::from(color));
let image_data = image_data
.into_iter()
.map(|(id, image)| RasterizedImage {
id,
width: image.width,
height: image.height,
pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
.filter(|(id, _)| self.canvas_images_sent.insert(*id))
.map(|(id, canvas_image)| {
let image = canvas_image.raster.halved(canvas_image.halvings);
RasterizedImage {
id,
width: image.width,
height: image.height,
pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
}
})
.collect();
responses.add(FrontendMessage::UpdateImageData { image_data });
responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use });
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
#[cfg(target_family = "wasm")]
@@ -192,6 +192,7 @@
if (!canvasName) return;
// Get the canvas element from the global storage
let canvas = window.imageCanvases[canvasName];
if (!canvas) return;
// Get logical dimensions from foreignObject parent (set by backend)
const foreignObject = placeholder.parentElement;
+1
View File
@@ -28,6 +28,7 @@ graphite-proc-macros = { workspace = true }
graphene-std = { workspace = true, optional = true }
# Workspace dependencies
base64 = { workspace = true }
graph-craft = { workspace = true, optional = true }
log = { workspace = true }
serde = { workspace = true }
+10 -13
View File
@@ -7,12 +7,12 @@ use crate::EDITOR;
use crate::MESSAGE_BUFFER;
#[cfg(all(feature = "native", target_family = "wasm"))]
use crate::editor_commands::EditorCommand;
#[cfg(feature = "editor")]
use crate::helpers::render_image_data_to_canvases;
#[cfg(not(feature = "native"))]
use crate::helpers::run_node_runtime;
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
use crate::helpers::wrapper;
#[cfg(feature = "editor")]
use crate::helpers::{calculate_hash, render_image_data_to_canvases};
use crate::helpers::{request_animation_frame, set_timeout};
use crate::{EDITOR_HAS_CRASHED, FRONTEND_READY};
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
@@ -22,12 +22,10 @@ use editor::messages::prelude::*;
#[cfg(feature = "editor")]
use serde::Serialize;
use std::cell::RefCell;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::Ordering;
use std::time::Duration;
use wasm_bindgen::prelude::*;
pub(crate) static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
#[wasm_bindgen]
#[derive(Clone)]
pub struct EditorWrapper {
@@ -128,14 +126,13 @@ impl EditorWrapper {
#[cfg(feature = "editor")]
pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) {
if let FrontendMessage::UpdateImageData { ref image_data } = message {
let new_hash = calculate_hash(image_data);
let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed);
if new_hash != prev_hash {
render_image_data_to_canvases(image_data.iter());
IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed);
}
if let FrontendMessage::UpdateImageData {
ref image_data,
ref canvas_ids_in_use,
} = message
{
let images = image_data.iter().map(|image| (image.id, image.width, image.height, image.pixels.as_slice()));
render_image_data_to_canvases(images, canvas_ids_in_use);
return;
}
+20 -25
View File
@@ -2,7 +2,6 @@
use crate::EDITOR_HAS_CRASHED;
use crate::EDITOR_WRAPPER;
use crate::editor_wrapper::EditorWrapper;
use crate::native_communication::RasterizedImage;
#[cfg(feature = "editor")]
use editor::messages::input_mapper::utility_types::keyboard::Key;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
@@ -86,12 +85,15 @@ pub(crate) fn wake_runtime() {
}
thread_local! {
// The placeholder IDs of the last rendered artwork's images, each with its canvas on `window.imageCanvases`
static SHOWN_IMAGE_IDS: RefCell<HashSet<u64>> = RefCell::new(HashSet::new());
/// The canvases put on `window.imageCanvases` for images, the only ones dropped from it here, since other canvases share it.
static IMAGE_CANVAS_IDS: RefCell<HashSet<u64>> = RefCell::new(HashSet::new());
}
/// Blits each rasterized image to a canvas registered on `window.imageCanvases`
pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator<Item = &'a RasterizedImage>) {
/// A canvas image's ID, width, height, and RGBA8 pixels.
pub(crate) type CanvasImagePixels<'a> = (u64, u32, u32, &'a [u8]);
/// Blits each new image to a canvas registered on `window.imageCanvases`, and drops the image canvases no render uses anymore.
pub(crate) fn render_image_data_to_canvases<'a>(images: impl IntoIterator<Item = CanvasImagePixels<'a>>, canvas_ids_in_use: &[u64]) {
let window = match window() {
Some(window) => window,
None => {
@@ -116,19 +118,18 @@ pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator<It
};
let canvases_obj = Object::from(canvases_obj);
// The canvases of images the previous render showed and this one doesn't are freed
let image_data = image_data.into_iter().collect::<Vec<_>>();
let shown = image_data.iter().map(|image| image.id).collect::<HashSet<_>>();
let previously_shown = SHOWN_IMAGE_IDS.replace(shown.clone());
for stale in previously_shown.difference(&shown) {
if Reflect::delete_property(&canvases_obj, &JsValue::from_str(&format!("image-{stale}"))).is_err() {
error!("Failed to free the canvas of image {stale}");
}
}
IMAGE_CANVAS_IDS.with_borrow_mut(|registered| {
let in_use: HashSet<u64> = canvas_ids_in_use.iter().copied().collect();
registered.retain(|id| {
let used = in_use.contains(id);
if !used {
let _ = Reflect::delete_property(&canvases_obj, &JsValue::from_str(&format!("image-{id}")));
}
used
});
});
for image in image_data {
let (placeholder_id, width, height) = (image.id, image.width, image.height);
let pixels = image.pixels.as_slice();
for (placeholder_id, width, height, pixels) in images {
// Matches the renderer's `data-canvas-placeholder` value
let canvas_name = format!("image-{placeholder_id}");
let js_key = JsValue::from_str(&canvas_name);
@@ -168,18 +169,12 @@ pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator<It
if Reflect::set(&canvases_obj, &js_key, &js_value).is_err() {
error!("Failed to set canvas '{canvas_name}' on imageCanvases object");
continue;
}
IMAGE_CANVAS_IDS.with_borrow_mut(|registered| registered.insert(placeholder_id));
}
}
pub(crate) fn calculate_hash<T: std::hash::Hash>(t: &T) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
let mut hasher = DefaultHasher::new();
t.hash(&mut hasher);
hasher.finish()
}
/// Translate a keyboard key from its JS name to its Rust `Key` enum
#[cfg(feature = "editor")]
pub(crate) fn translate_key(name: &str) -> Key {
+64 -36
View File
@@ -1,13 +1,29 @@
//! Messaging with the native process. Serialized `FrontendMessage`s come in and are forwarded to JS,
//! `EditorCommand`s go back out. Encoding and decoding both live here so the wire format stays in one place.
use crate::editor_wrapper::{EditorWrapper, IMAGE_DATA_HASH};
use crate::helpers::{calculate_hash, render_image_data_to_canvases, wrapper};
use crate::editor_wrapper::EditorWrapper;
use crate::helpers::{render_image_data_to_canvases, wrapper};
use crate::wasm_value::WasmValue;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use js_sys::{ArrayBuffer, Uint8Array};
use std::sync::atomic::Ordering;
use wasm_bindgen::prelude::*;
/// An `UpdateImageData` message as it crosses to the native frontend, with pixels in base64 since JSON would spell out each byte as a number.
#[derive(serde::Serialize, serde::Deserialize)]
struct EncodedImageData {
images: Vec<EncodedImage>,
canvas_ids_in_use: Vec<u64>,
}
#[derive(serde::Serialize, serde::Deserialize)]
struct EncodedImage {
id: u64,
width: u32,
height: u32,
pixels: String,
}
#[wasm_bindgen(js_name = "receiveNativeMessage")]
pub fn receive_native_message(buffer: ArrayBuffer) {
let buffer = Uint8Array::new(buffer.as_ref()).to_vec();
@@ -16,17 +32,21 @@ pub fn receive_native_message(buffer: ArrayBuffer) {
wrapper(move |wrapper: &mut EditorWrapper| {
for (name, data) in messages {
match name.as_str() {
"UpdateImageData" => {
let new_hash = calculate_hash(&data);
if IMAGE_DATA_HASH.swap(new_hash, Ordering::Relaxed) == new_hash {
continue;
"UpdateImageData" => match serde_json::from_str::<EncodedImageData>(&data) {
Ok(encoded) => {
let images: Vec<_> = encoded
.images
.iter()
.filter_map(|image| {
let pixels = BASE64.decode(&image.pixels).inspect_err(|e| error!("Failed to decode image {}: {e}", image.id)).ok()?;
Some((image.id, image.width, image.height, pixels))
})
.collect();
let images = images.iter().map(|(id, width, height, pixels)| (*id, *width, *height, pixels.as_slice()));
render_image_data_to_canvases(images, &encoded.canvas_ids_in_use);
}
match serde_json::from_str::<Vec<RasterizedImage>>(&data) {
Ok(image_data) => render_image_data_to_canvases(image_data.iter()),
Err(e) => error!("Failed to deserialize image data: {e:?}"),
}
}
Err(e) => error!("Failed to deserialize image data: {e:?}"),
},
_ => match serde_json::from_str::<WasmValue>(&data) {
Ok(value) => wrapper.forward_serialized_frontend_message_to_js(&name, value),
Err(e) => log::error!("Failed to deserialize frontend message {name}: {e:?}"),
@@ -49,7 +69,20 @@ pub fn encode_frontend_messages(messages: Vec<editor::messages::prelude::Fronten
.map(|message| {
let name = message.to_discriminant().local_name();
let data = match message {
FrontendMessage::UpdateImageData { image_data } => serde_json::to_string(&image_data).inspect_err(|e| log::error!("Failed to serialize {name} payload: {e}")).ok()?,
FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use } => {
let images = image_data
.into_iter()
.map(|image| EncodedImage {
id: image.id,
width: image.width,
height: image.height,
pixels: BASE64.encode(&image.pixels),
})
.collect();
serde_json::to_string(&EncodedImageData { images, canvas_ids_in_use })
.inspect_err(|e| log::error!("Failed to serialize {name} payload: {e}"))
.ok()?
}
message => crate::wasm_value::encode(&message)
.inspect_err(|e| log::error!("Failed to serialize FrontendMessage {name}: {e}"))
.ok()?,
@@ -97,37 +130,32 @@ pub fn send_message_to_cef(message: String) {
func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed");
}
#[cfg(feature = "editor")]
pub(crate) use editor::messages::frontend::utility_types::RasterizedImage;
#[cfg(not(feature = "editor"))]
pub(crate) use RasterizedImageCopy as RasterizedImage;
#[cfg(any(not(feature = "editor"), test))]
#[derive(serde::Deserialize)]
pub(crate) struct RasterizedImageCopy {
pub(crate) id: u64,
pub(crate) width: u32,
pub(crate) height: u32,
pub(crate) pixels: Vec<u8>,
}
#[cfg(all(test, feature = "editor"))]
mod tests {
use super::*;
use editor::messages::frontend::utility_types::RasterizedImage;
use editor::messages::prelude::FrontendMessage;
#[test]
fn rasterized_image_copy_matches_editor_shape() {
let editor_image = RasterizedImage {
fn image_data_crosses_to_the_native_frontend_intact() {
let image = RasterizedImage {
id: 7,
width: 2,
height: 1,
pixels: serde_bytes::ByteBuf::from(vec![1, 2, 3, 4, 5, 6, 7, 8]),
};
let json = serde_json::to_string(&vec![editor_image]).unwrap();
let decoded: Vec<RasterizedImageCopy> = serde_json::from_str(&json).unwrap();
assert_eq!(decoded[0].id, 7);
assert_eq!((decoded[0].width, decoded[0].height), (2, 1));
assert_eq!(decoded[0].pixels, [1, 2, 3, 4, 5, 6, 7, 8]);
let message = FrontendMessage::UpdateImageData {
image_data: vec![image],
canvas_ids_in_use: vec![7, 9],
};
let encoded = encode_frontend_messages(vec![message]).unwrap();
let messages: Vec<(String, String)> = serde_json::from_slice(&encoded).unwrap();
let decoded: EncodedImageData = serde_json::from_str(&messages[0].1).unwrap();
assert_eq!(messages[0].0, "UpdateImageData");
assert_eq!(decoded.canvas_ids_in_use, [7, 9]);
assert_eq!((decoded.images[0].id, decoded.images[0].width, decoded.images[0].height), (7, 2, 1));
assert_eq!(BASE64.decode(&decoded.images[0].pixels).unwrap(), [1, 2, 3, 4, 5, 6, 7, 8]);
}
}
+5 -11
View File
@@ -19,7 +19,7 @@ use graphic_types::vector_types::vector::style::DashPattern;
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
use graphic_types::vector_types::vector::{self, ReferencePoint};
use graphic_types::{Artboard, Graphic, Vector};
use rendering::RenderMetadata;
use rendering::{CanvasImage, RenderMetadata};
use std::fmt::Display;
use std::hash::Hash;
use std::str::FromStr;
@@ -933,20 +933,14 @@ pub enum RenderOutputType {
#[serde(skip)]
Texture(graphene_application_io::Texture),
#[serde(skip)]
Buffer {
data: Vec<u8>,
width: u32,
height: u32,
},
Buffer { data: Vec<u8>, width: u32, height: u32 },
Svg {
svg: String,
image_data: Vec<(u64, Image<Color>)>,
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
image_data: Vec<(u64, CanvasImage)>,
},
#[cfg(target_family = "wasm")]
CanvasFrame {
canvas_id: u64,
resolution: DVec2,
},
CanvasFrame { canvas_id: u64, resolution: DVec2 },
}
impl CacheHash for RenderOutputType {
@@ -5,6 +5,7 @@ use core_types::color::float_to_srgb_u8;
use core_types::color::*;
use dyn_any::StaticType;
use glam::{DAffine2, DVec2};
use std::borrow::Cow;
use std::vec::Vec;
mod base64_serde {
@@ -198,6 +199,42 @@ impl Image<Color> {
decode(data).map(|image| (image.width(), image.height()))
}
/// The image shrunk by half along each axis `times` times, averaging each block of pixels with their colors weighted by their alpha.
/// Blocks at the right and bottom edges average only the pixels they have. O(width × height), or O(1) borrowing the image as it is when `times` is zero.
pub fn halved(&self, times: u32) -> Cow<'_, Self> {
if times == 0 {
return Cow::Borrowed(self);
}
let factor = 1_u32 << times.min(31);
let (width, height) = (self.width.div_ceil(factor), self.height.div_ceil(factor));
let mut data = Vec::with_capacity((width * height) as usize);
for block_y in 0..height {
for block_x in 0..width {
let (mut red, mut green, mut blue, mut alpha, mut count) = (0., 0., 0., 0., 0.);
for y in (block_y * factor)..((block_y + 1) * factor).min(self.height) {
for x in (block_x * factor)..((block_x + 1) * factor).min(self.width) {
let pixel = self.data[(y * self.width + x) as usize];
red += pixel.r() * pixel.a();
green += pixel.g() * pixel.a();
blue += pixel.b() * pixel.a();
alpha += pixel.a();
count += 1.;
}
}
data.push(match alpha > 0. {
true => Color::from_rgbaf32_unchecked(red / alpha, green / alpha, blue / alpha, alpha / count),
false => Color::TRANSPARENT,
});
}
}
Cow::Owned(Image { width, height, data })
}
pub fn to_png(&self) -> Vec<u8> {
use ::image::ImageEncoder;
let (data, width, height) = self.to_flat_u8();
@@ -360,6 +397,26 @@ mod test {
assert!(Image::from_encoded(b"not an image").is_none());
}
#[test]
fn halving_averages_blocks_weighted_by_alpha() {
use super::*;
// An opaque red and a transparent green beside it average to red at half alpha, with no green showing through
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
let clear_green = Color::from_rgbaf32_unchecked(0., 1., 0., 0.);
let image = Image {
width: 3,
height: 1,
data: vec![red, clear_green, red],
};
let halved = image.halved(1);
assert_eq!((halved.width, halved.height), (2, 1), "the odd column becomes a block of its own");
assert_eq!(halved.data[0], Color::from_rgbaf32_unchecked(1., 0., 0., 0.5));
assert_eq!(halved.data[1], red);
assert!(matches!(image.halved(0), Cow::Borrowed(borrowed) if *borrowed == image));
}
#[test]
fn eight_bit_decoding_matches_the_gamma_curve() {
use super::*;
+73 -6
View File
@@ -247,9 +247,10 @@ impl MaskType {
pub struct SvgRender {
pub svg: Vec<SvgSegment>,
pub svg_defs: String,
/// Maps the user space of the content being rendered into the document's space.
pub transform: DAffine2,
/// The rasters drawn to canvases rather than embedded, by the buffer ID their placeholders name.
pub image_data: HashMap<u64, Raster<CPU>>,
/// The images drawn to canvases rather than embedded, by the canvas ID their placeholders name.
pub image_data: HashMap<u64, CanvasImage>,
indent: usize,
}
@@ -343,7 +344,7 @@ impl SvgRender {
pub struct SvgRenderOutput {
pub svg: String,
pub svg_defs: String,
pub image_data: HashMap<u64, Raster<CPU>>,
pub image_data: HashMap<u64, CanvasImage>,
}
impl From<&SvgRenderOutput> for SvgRender {
@@ -404,6 +405,9 @@ pub struct RenderParams {
pub artboard_background: Option<Color>,
/// Viewport zoom level (document-space scale). Used to compute constant viewport-pixel stroke widths in Outline mode.
pub viewport_zoom: Option<f64>,
/// Screen pixels per document unit for sizing the images drawn to canvases, rounded up to a power of two so the render reruns only when it doubles or halves.
/// Zero sends them at full resolution.
pub canvas_image_scale: f64,
/// The nearest ancestor's appearance, cascading to items that lack their own.
pub inherited_appearance: Option<Appearance>,
}
@@ -872,7 +876,12 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st
attributes.push("style", blend_mode.render());
}
},
|render| element.render_svg(render, render_params),
|render| {
let parent_transform = render.transform;
render.transform = parent_transform * transform;
element.render_svg(render, render_params);
render.transform = parent_transform;
},
);
};
@@ -1345,7 +1354,11 @@ impl Render for List<Artboard> {
|render| {
let mut render_params = render_params.clone();
render_params.artboard_background = Some(background);
let parent_transform = render.transform;
render.transform = parent_transform * DAffine2::from_translation(location);
content.render_svg(render, &render_params);
render.transform = parent_transform;
},
);
}
@@ -2357,6 +2370,23 @@ fn extend_free_point_targets<'a>(vector: &'a Vector, geometry_paths: &List<Path>
})
}
/// The most times an image drawn to a canvas is halved, which is when 4096 of its pixels fit on one screen pixel.
const MAX_CANVAS_HALVINGS: u32 = 12;
/// An image the frontend draws to a canvas rather than an SVG embedding it, at a resolution to suit how large it appears.
#[derive(Clone, Debug, PartialEq, CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CanvasImage {
pub raster: Raster<CPU>,
/// How many times the pixels are halved along each axis for display.
pub halvings: u32,
}
/// Names the canvas for one resolution of an image's pixels, staying the same while the pixels do.
fn canvas_image_id(buffer_id: u64, halvings: u32) -> u64 {
(buffer_id << 4) | halvings as u64
}
/// Emits one item of CPU raster content as SVG, as a canvas placeholder or an embedded base64 image.
fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster<CPU>>, render: &mut SvgRender, render_params: &RenderParams) {
let Some(image) = item.element() else { return };
@@ -2371,8 +2401,18 @@ fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster<CPU>>, render: &mut SvgRe
}
if render_params.to_canvas() {
let id = image.buffer_id();
render.image_data.entry(id).or_insert_with(|| image.clone());
// An image drawn smaller than its pixels is sent at a resolution halved enough times to still cover each screen pixel
let document_to_screen = DAffine2::from_scale(DVec2::splat(render_params.canvas_image_scale));
let image_to_screen = document_to_screen * render.transform * transform * DAffine2::from_scale(1. / DVec2::new(image.width as f64, image.height as f64));
let (largest_scale, _) = singular_values(image_to_screen);
let halvings = if largest_scale > 0. {
(1. / largest_scale).log2().floor().clamp(0., MAX_CANVAS_HALVINGS as f64) as u32
} else {
0
};
let id = canvas_image_id(image.buffer_id(), halvings);
render.image_data.entry(id).or_insert_with(|| CanvasImage { raster: image.clone(), halvings });
render.parent_tag(
"foreignObject",
@@ -3505,4 +3545,31 @@ mod tests {
let colors: Vec<Color> = samples.iter().map(|&(_, color, _)| color).collect();
assert_eq!(colors, vec![Color::TRANSPARENT, Color::BLACK, Color::BLACK, Color::TRANSPARENT]);
}
#[test]
fn canvas_images_are_halved_to_suit_the_canvas_image_scale() {
use graphic_types::raster_types::Image;
// An image placed at one pixel per document unit
let image = Raster::new_cpu(Image::new(64, 64, Color::WHITE));
let list = List::new_from_item(Item::new_from_element(image).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.))));
let halvings = |canvas_image_scale| {
let mut render = SvgRender::new();
list.render_svg(
&mut render,
&RenderParams {
canvas_image_scale,
..Default::default()
},
);
render.image_data.values().map(|canvas_image| canvas_image.halvings).collect::<Vec<_>>()
};
// Zoomed out to a quarter, two halvings still cover each screen pixel
assert_eq!(halvings(0.25), [2]);
// Zoomed in, or without a scale as in thumbnails, the full resolution is sent
assert_eq!(halvings(4.), [0]);
assert_eq!(halvings(0.), [0]);
}
}
+8 -1
View File
@@ -101,7 +101,7 @@ fn render(
RenderOutputType::Svg {
svg: output.svg,
image_data: output.image_data.into_iter().map(|(id, raster)| (id, raster.into_data())).collect(),
image_data: output.image_data.into_iter().collect(),
}
}
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
@@ -149,12 +149,19 @@ fn create_context(
..logical_viewport
};
// Rounded up so no image is sent below its on-screen resolution, with a tolerance for float noise at exact powers of two
let canvas_image_scale = match render_output_type {
RenderOutputTypeRequest::Svg => (footprint.scale_magnitudes().max_element().log2() - 1e-9).ceil().exp2(),
RenderOutputTypeRequest::Vello => 0.,
};
let render_params = RenderParams {
render_mode: render_config.render_mode,
for_export: render_config.for_export,
render_output_type,
scale: render_config.scale,
viewport_zoom: Some(logical_viewport.scale_magnitudes().x),
canvas_image_scale,
..Default::default()
};