mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e23496e978 | ||
|
|
3704a954ca | ||
|
|
9ecbbb408b | ||
|
|
d743b22f1b | ||
|
|
b6459371a9 | ||
|
|
814c988592 |
No files matched your search
Generated
+145
-10
@@ -1238,7 +1238,7 @@ dependencies = [
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"tinyvec",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
@@ -2135,6 +2135,9 @@ name = "float-cmp"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
@@ -2154,6 +2157,15 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.7"
|
||||
@@ -2195,7 +2207,7 @@ dependencies = [
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"parlance",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -2432,6 +2444,21 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glifo"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"foldhash 0.2.0",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"peniko",
|
||||
"skrifa 0.44.0",
|
||||
"smallvec",
|
||||
"vello_common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
@@ -3039,7 +3066,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -3427,6 +3454,12 @@ dependencies = [
|
||||
"quick-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.15.0"
|
||||
@@ -3799,6 +3832,33 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
"flate2",
|
||||
"float-cmp",
|
||||
"gif",
|
||||
"image-webp",
|
||||
"imagesize 0.14.0",
|
||||
"indexmap",
|
||||
"pdf-writer",
|
||||
"png 0.18.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"siphasher",
|
||||
"skrifa 0.42.1",
|
||||
"smallvec",
|
||||
"subsetter",
|
||||
"tiny-skia-path",
|
||||
"xmp-writer",
|
||||
"yoke",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kurbo"
|
||||
version = "0.13.1"
|
||||
@@ -5032,7 +5092,7 @@ dependencies = [
|
||||
"parlance",
|
||||
"parley_data",
|
||||
"parley_emoji",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5063,6 +5123,18 @@ dependencies = [
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdf-writer"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peer-transport"
|
||||
version = "0.0.0"
|
||||
@@ -5865,6 +5937,16 @@ dependencies = [
|
||||
"yasna",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.39.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.41.0"
|
||||
@@ -5872,7 +5954,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
@@ -6015,16 +6097,19 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"glifo",
|
||||
"graphene-application-io",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"krilla",
|
||||
"kurbo",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
@@ -6602,6 +6687,12 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
@@ -6963,6 +7054,16 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.42.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
@@ -6970,7 +7071,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7149,6 +7250,18 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subsetter"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"rustc-hash 2.1.3",
|
||||
"skrifa 0.42.1",
|
||||
"write-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "substring"
|
||||
version = "1.4.5"
|
||||
@@ -7331,7 +7444,7 @@ dependencies = [
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"thiserror 2.0.21",
|
||||
"titlecase",
|
||||
"tsify",
|
||||
@@ -7931,14 +8044,14 @@ dependencies = [
|
||||
"flate2",
|
||||
"fontdb",
|
||||
"harfrust",
|
||||
"imagesize",
|
||||
"imagesize 0.15.0",
|
||||
"kurbo",
|
||||
"log",
|
||||
"pico-args",
|
||||
"roxmltree 0.21.2",
|
||||
"simplecss",
|
||||
"siphasher",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"strict-num",
|
||||
"svgtypes",
|
||||
"tiny-skia-path",
|
||||
@@ -8023,6 +8136,7 @@ dependencies = [
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
@@ -8099,6 +8213,7 @@ version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"glifo",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
@@ -8581,6 +8696,7 @@ dependencies = [
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"vello_gpu",
|
||||
"web-sys",
|
||||
@@ -9281,6 +9397,19 @@ dependencies = [
|
||||
"toml 0.5.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "write-fonts"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
|
||||
dependencies = [
|
||||
"font-types 0.11.3",
|
||||
"indexmap",
|
||||
"kurbo",
|
||||
"log",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
@@ -9421,6 +9550,12 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "xmp-writer"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "yansi"
|
||||
version = "1.0.1"
|
||||
|
||||
+4
-1
@@ -215,7 +215,9 @@ url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support", "text"] }
|
||||
glifo = { version = "0.4", default-features = false, features = ["std"] }
|
||||
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
|
||||
usvg = "0.49"
|
||||
simplecss = "0.2"
|
||||
parley = { version = "0.12", default-features = false, features = ["std"] }
|
||||
@@ -318,3 +320,4 @@ fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "2
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
glifo = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
@@ -103,22 +103,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
DialogMessage::RequestExportDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
let artboards = document
|
||||
.metadata()
|
||||
.all_layers()
|
||||
.filter(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = document
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.export_dialog.artboards = artboards;
|
||||
self.export_dialog.artboards = document.artboard_names().into_iter().collect();
|
||||
|
||||
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
|
||||
&& !self.export_dialog.artboards.contains_key(&layer)
|
||||
|
||||
@@ -94,9 +94,9 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
|
||||
impl LayoutHolder for ExportDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
// The vector type, then the raster ones
|
||||
// The vector types, then the raster ones
|
||||
let file_types = [
|
||||
vec![(FileType::Svg, "SVG")],
|
||||
vec![(FileType::Svg, "SVG"), (FileType::Pdf, "PDF")],
|
||||
vec![
|
||||
(FileType::Png, "PNG"),
|
||||
(FileType::Jpg, "JPG"),
|
||||
@@ -131,14 +131,25 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let scale_description = match self.file_type {
|
||||
FileType::Pdf => "Resolution of the images of effects and other content PDF can't draw itself, where 1 is 300 DPI.",
|
||||
_ => "Size of the exported image relative to the document's size.",
|
||||
};
|
||||
let resolution = vec![
|
||||
TextLabel::new("Scale Factor").table_align(true).sizing(WidgetSizing::fixed(100)).widget_instance(),
|
||||
TextLabel::new("Scale Factor")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(100))
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.scale_factor))
|
||||
.unit("")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.increment_step(0.5)
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.disabled(self.file_type == FileType::Svg)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
|
||||
@@ -78,6 +78,7 @@ pub enum FileType {
|
||||
Tga,
|
||||
Ico,
|
||||
Svg,
|
||||
Pdf,
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
@@ -91,9 +92,15 @@ impl FileType {
|
||||
FileType::Tga => "tga",
|
||||
FileType::Ico => "ico",
|
||||
FileType::Svg => "svg",
|
||||
FileType::Pdf => "pdf",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file holds vector content rather than an image of the export's area.
|
||||
pub fn is_vector(self) -> bool {
|
||||
matches!(self, FileType::Svg | FileType::Pdf)
|
||||
}
|
||||
|
||||
pub fn file_filter(self) -> FileFilter {
|
||||
let name = match self {
|
||||
FileType::Png => "PNG Image",
|
||||
@@ -104,6 +111,7 @@ impl FileType {
|
||||
FileType::Tga => "TGA Image",
|
||||
FileType::Ico => "ICO Image",
|
||||
FileType::Svg => "SVG Image",
|
||||
FileType::Pdf => "PDF Document",
|
||||
};
|
||||
FileFilter {
|
||||
name: name.into(),
|
||||
@@ -129,7 +137,7 @@ impl FileType {
|
||||
FileType::Bmp => ImageFormat::Bmp,
|
||||
FileType::Tga => ImageFormat::Tga,
|
||||
FileType::Ico => ImageFormat::Ico,
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
FileType::Svg | FileType::Pdf => return Err(format!("{} cannot be exported from an image buffer", self.extension().to_uppercase())),
|
||||
};
|
||||
if self == FileType::Ico && (width > 256 || height > 256) {
|
||||
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
|
||||
@@ -228,6 +236,7 @@ mod tests {
|
||||
#[test]
|
||||
fn file_types_that_cannot_hold_the_image_say_so() {
|
||||
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Pdf.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
|
||||
|
||||
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
|
||||
|
||||
@@ -2445,6 +2445,20 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
/// The document's artboards with their names, called "Artboard" while left unnamed.
|
||||
pub fn artboard_names(&self) -> Vec<(LayerNodeIdentifier, String)> {
|
||||
(self.metadata().all_layers())
|
||||
.filter(|&layer| self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = (self.network_interface.node_metadata(&layer.to_node(), &[]))
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
||||
&self.breadcrumb_network_path
|
||||
}
|
||||
|
||||
@@ -206,9 +206,6 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
]);
|
||||
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
|
||||
.expect("Text to Vector node does not exist")
|
||||
.default_node_template();
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
@@ -216,17 +213,13 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.expect("Fill node does not exist")
|
||||
.default_node_template();
|
||||
|
||||
// Build the chain `Text -> Text to Vector -> Transform -> Fill -> layer`
|
||||
// Build the chain `Text -> Transform -> Fill -> layer`, keeping the text native so backends lay out and draw its glyphs
|
||||
let text_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_id, text, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
|
||||
|
||||
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
|
||||
|
||||
let text_to_vector_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_to_vector_id, text_to_vector, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_to_vector_id, layer, &[], self.import);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
|
||||
@@ -27,7 +27,7 @@ mod recompile_tests;
|
||||
mod runtime;
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ExecutionRequest {
|
||||
execution_id: u64,
|
||||
render_config: RenderConfig,
|
||||
@@ -356,6 +356,7 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
metadata: None,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -423,6 +424,7 @@ impl NodeGraphExecutor {
|
||||
render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: true,
|
||||
metadata: None,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -447,10 +449,12 @@ impl NodeGraphExecutor {
|
||||
let previewed = document.network_interface.previewed_nodes();
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
let export_format = if export_config.file_type == FileType::Svg {
|
||||
graphene_std::application_io::ExportFormat::Svg
|
||||
} else {
|
||||
graphene_std::application_io::ExportFormat::Raster
|
||||
let export_format = match export_config.file_type {
|
||||
FileType::Svg => graphene_std::application_io::ExportFormat::Svg,
|
||||
FileType::Pdf => graphene_std::application_io::ExportFormat::Pdf {
|
||||
artboards_as_pages: export_config.bounds == ExportBounds::AllArtwork,
|
||||
},
|
||||
_ => graphene_std::application_io::ExportFormat::Raster,
|
||||
};
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
@@ -483,6 +487,10 @@ impl NodeGraphExecutor {
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
metadata: Some(graphene_std::application_io::ExportMetadata {
|
||||
title: export_config.name.clone(),
|
||||
artboard_names: (document.artboard_names().into_iter()).map(|(layer, name)| (layer.to_node(), name)).collect(),
|
||||
}),
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -924,6 +932,7 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
metadata: None,
|
||||
};
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
@@ -1055,6 +1064,11 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
return;
|
||||
}
|
||||
RenderOutputType::Pdf { data } => {
|
||||
log::error!("Invalid node graph output type: a PDF document of {} bytes", data.len());
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let RenderMetadata {
|
||||
@@ -1122,10 +1136,20 @@ impl NodeGraphExecutor {
|
||||
content: svg.into_bytes().into(),
|
||||
});
|
||||
}
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Pdf { data }, ..
|
||||
}) if file_type == FileType::Pdf => {
|
||||
responses.add(FrontendMessage::TriggerSaveFile {
|
||||
name,
|
||||
folder,
|
||||
filters,
|
||||
content: data.into(),
|
||||
});
|
||||
}
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Buffer { data, width, height },
|
||||
..
|
||||
}) if file_type != FileType::Svg => {
|
||||
}) if !file_type.is_vector() => {
|
||||
let content = match file_type.encode(width, height, data) {
|
||||
Ok(content) => content.into(),
|
||||
Err(description) => {
|
||||
|
||||
@@ -294,12 +294,12 @@ impl NodeRuntime {
|
||||
let dirty = self.dirty.swap(false, Ordering::Acquire);
|
||||
let mut texture = None;
|
||||
|
||||
if let Some(export) = self.pending_export {
|
||||
if let Some(export) = self.pending_export.clone() {
|
||||
if dirty {
|
||||
self.run_export(export).await;
|
||||
}
|
||||
} else {
|
||||
let viewport = if dirty { self.pending } else { None };
|
||||
let viewport = if dirty { self.pending.clone() } else { None };
|
||||
|
||||
if let Some(document_id) = self.pending_thumbnails.take()
|
||||
&& viewport.is_none()
|
||||
@@ -336,9 +336,10 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
|
||||
let execution_id = request.execution_id;
|
||||
self.thumbnails.set_scale(request.render_config.scale);
|
||||
|
||||
let mut result = self.evaluate(request)?;
|
||||
let mut result = self.evaluate(request.clone())?;
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
@@ -390,7 +391,7 @@ impl NodeRuntime {
|
||||
None
|
||||
};
|
||||
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
self.respond(execution_id, result, observations).await;
|
||||
texture
|
||||
}
|
||||
|
||||
@@ -435,6 +436,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
async fn run_export(&mut self, request: ExecutionRequest) {
|
||||
let execution_id = request.execution_id;
|
||||
let result = self.evaluate(request);
|
||||
if matches!(result, Some(ExecutionResult::Pending)) {
|
||||
return;
|
||||
@@ -451,12 +453,12 @@ impl NodeRuntime {
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
self.respond(execution_id, result, observations).await;
|
||||
}
|
||||
|
||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||
// Eyedropper should use the same time and pointer to not invalidate the cache
|
||||
if let Some(viewport) = self.pending {
|
||||
if let Some(viewport) = &self.pending {
|
||||
request.render_config.time = viewport.render_config.time;
|
||||
request.render_config.pointer = viewport.render_config.pointer;
|
||||
}
|
||||
@@ -484,10 +486,11 @@ impl NodeRuntime {
|
||||
render_config.export_format = ExportFormat::Svg;
|
||||
}
|
||||
|
||||
let for_export = render_config.for_export;
|
||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
|
||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
||||
Ok(Ok(Poll::Fallback(boxed))) => {
|
||||
@@ -788,7 +791,7 @@ mod tests {
|
||||
|
||||
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
|
||||
fn last_request(editor: &EditorTestUtils) -> Option<u64> {
|
||||
editor.runtime.pending.map(|request| request.execution_id)
|
||||
editor.runtime.pending.as_ref().map(|request| request.execution_id)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1080,6 +1083,60 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pdf_export_saves_a_pdf_document() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
send_export(&mut editor, FileType::Pdf);
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
|
||||
let saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveFile { name, content, .. } => Some((name, content)),
|
||||
_ => None,
|
||||
});
|
||||
let Some((name, content)) = saved else { panic!("the export should save a file") };
|
||||
|
||||
assert!(name.ends_with(".pdf"), "the file should be named as a PDF: {name}");
|
||||
assert!(content.starts_with(b"%PDF-"), "the file should hold a PDF document");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pdf_export_draws_effects_as_images_the_gpu_renders() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use graphene_std::blending_nodes::effects::drop_shadow;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
let node_type = DefinitionIdentifier::ProtoNode(drop_shadow::IDENTIFIER);
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
|
||||
// The export waits for the render node to read the image of the shadowed rectangle back into the PDF
|
||||
send_export(&mut editor, FileType::Pdf);
|
||||
let mut saved = None;
|
||||
for _ in 0..100 {
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
|
||||
_ => None,
|
||||
});
|
||||
if saved.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(saved) = saved else { panic!("the export never finished") };
|
||||
|
||||
assert!(saved.starts_with(b"%PDF-"), "the file should hold a PDF document");
|
||||
let embeds_image = saved.windows(b"/Subtype/Image".len()).any(|window| window == b"/Subtype/Image");
|
||||
assert!(embeds_image, "the shadowed rectangle should be an image the GPU rendered");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_svg_export_draws_effects_svg_filters_cannot_carry_out_as_images_the_gpu_renders() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
|
||||
@@ -924,6 +924,8 @@ pub enum RenderOutputType {
|
||||
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
|
||||
image_data: Vec<(u64, CanvasImage)>,
|
||||
},
|
||||
/// A PDF document's file contents.
|
||||
Pdf { data: Vec<u8> },
|
||||
#[cfg(target_family = "wasm")]
|
||||
CanvasFrame { canvas_id: u64, resolution: DVec2 },
|
||||
}
|
||||
@@ -942,6 +944,7 @@ impl CacheHash for RenderOutputType {
|
||||
svg.cache_hash(state);
|
||||
image_data.cache_hash(state);
|
||||
}
|
||||
Self::Pdf { data } => data.cache_hash(state),
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::CanvasFrame { canvas_id, resolution } => {
|
||||
canvas_id.cache_hash(state);
|
||||
|
||||
@@ -18,6 +18,7 @@ use std::time::Duration;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FileType {
|
||||
Svg,
|
||||
Pdf,
|
||||
Png,
|
||||
Jpg,
|
||||
Webp,
|
||||
@@ -29,7 +30,7 @@ pub enum FileType {
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
/// The image format of a file type encoded from a single image, which excludes SVG and GIF.
|
||||
/// The image format of a file type encoded from a single image, which excludes SVG, PDF, and GIF.
|
||||
fn raster_format(self) -> Option<ImageFormat> {
|
||||
match self {
|
||||
FileType::Png => Some(ImageFormat::Png),
|
||||
@@ -39,7 +40,7 @@ impl FileType {
|
||||
FileType::Bmp => Some(ImageFormat::Bmp),
|
||||
FileType::Tga => Some(ImageFormat::Tga),
|
||||
FileType::Ico => Some(ImageFormat::Ico),
|
||||
FileType::Svg | FileType::Gif => None,
|
||||
FileType::Svg | FileType::Pdf | FileType::Gif => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +48,7 @@ impl FileType {
|
||||
pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
||||
match path.extension().and_then(|s| s.to_str()) {
|
||||
Some("svg") => Ok(FileType::Svg),
|
||||
Some("pdf") => Ok(FileType::Pdf),
|
||||
Some("png") => Ok(FileType::Png),
|
||||
Some("jpg" | "jpeg") => Ok(FileType::Jpg),
|
||||
Some("webp") => Ok(FileType::Webp),
|
||||
@@ -55,13 +57,14 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
||||
Some("tga") => Ok(FileType::Tga),
|
||||
Some("ico") => Ok(FileType::Ico),
|
||||
Some("gif") => Ok(FileType::Gif),
|
||||
_ => Err("Unsupported file extension. Supported formats: .svg, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif".to_string()),
|
||||
_ => Err("Unsupported file extension. Supported formats: .svg, .pdf, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// One rendered frame of the document, as SVG text or as 8-bit RGBA pixels with straight alpha.
|
||||
/// One rendered frame of the document, as SVG text, a PDF document, or 8-bit RGBA pixels with straight alpha.
|
||||
pub enum RenderedFrame {
|
||||
Svg(String),
|
||||
Pdf(Vec<u8>),
|
||||
Raster { data: Vec<u8>, width: u32, height: u32 },
|
||||
}
|
||||
|
||||
@@ -165,7 +168,11 @@ pub(crate) async fn render_frame(
|
||||
size: (width, height),
|
||||
..
|
||||
} = settings;
|
||||
let export_format = if file_type == FileType::Svg { ExportFormat::Svg } else { ExportFormat::Raster };
|
||||
let export_format = match file_type {
|
||||
FileType::Svg => ExportFormat::Svg,
|
||||
FileType::Pdf => ExportFormat::Pdf { artboards_as_pages: false },
|
||||
_ => ExportFormat::Raster,
|
||||
};
|
||||
|
||||
// Create render config with export settings and the animation time
|
||||
let mut render_config = RenderConfig {
|
||||
@@ -190,6 +197,7 @@ pub(crate) async fn render_frame(
|
||||
match execute_until_settled(executor, runtime, spawner, render_config).await? {
|
||||
TaggedValue::RenderOutput(output) => match output.data {
|
||||
RenderOutputType::Svg { svg, .. } => Ok(RenderedFrame::Svg(svg)),
|
||||
RenderOutputType::Pdf { data } => Ok(RenderedFrame::Pdf(data)),
|
||||
RenderOutputType::Texture(texture) => {
|
||||
// Convert GPU texture to CPU buffer
|
||||
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
||||
@@ -199,7 +207,7 @@ pub(crate) async fn render_frame(
|
||||
}
|
||||
RenderOutputType::Buffer { data, width, height } => Ok(RenderedFrame::Raster { data, width, height }),
|
||||
#[cfg(target_family = "wasm")]
|
||||
other => Err(format!("Unexpected render output type: {other:?}. Expected Texture, Buffer for raster export or Svg for SVG export.").into()),
|
||||
other => Err(format!("Unexpected render output type: {other:?}. Expected Texture or Buffer for raster export, Svg for SVG export, or Pdf for PDF export.").into()),
|
||||
},
|
||||
other => Err(format!("Expected RenderOutput, got: {other:?}").into()),
|
||||
}
|
||||
@@ -209,6 +217,7 @@ pub(crate) async fn render_frame(
|
||||
fn write_frame(path: &Path, settings: ExportSettings, frame: RenderedFrame) -> Result<(), Box<dyn Error>> {
|
||||
let contents = match frame {
|
||||
RenderedFrame::Svg(svg) => svg.into_bytes(),
|
||||
RenderedFrame::Pdf(pdf) => pdf,
|
||||
RenderedFrame::Raster { data, width, height } => encode_raster(settings.file_type, data, width, height, settings.transparent)?,
|
||||
};
|
||||
std::fs::write(path, contents)?;
|
||||
@@ -391,7 +400,7 @@ pub async fn export_image_sequence(
|
||||
}
|
||||
|
||||
pub async fn execute_until_settled(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner, render_config: RenderConfig) -> Result<TaggedValue, Box<dyn Error>> {
|
||||
let execute = || executor.execute(render_config.into_context_with_generations(runtime.snapshot()));
|
||||
let execute = || executor.execute(render_config.clone().into_context_with_generations(runtime.snapshot()));
|
||||
let mut frame = execute()?;
|
||||
while spawner.join().await {
|
||||
frame = execute()?;
|
||||
@@ -469,6 +478,7 @@ mod tests {
|
||||
assert_eq!(detect_file_type(Path::new("frame.tif")), Ok(FileType::Tiff));
|
||||
assert_eq!(detect_file_type(Path::new("frame.jpeg")), Ok(FileType::Jpg));
|
||||
assert_eq!(detect_file_type(Path::new("frame.webp")), Ok(FileType::Webp));
|
||||
assert_eq!(detect_file_type(Path::new("frame.pdf")), Ok(FileType::Pdf));
|
||||
assert!(detect_file_type(Path::new("frame.exr")).is_err());
|
||||
assert!(detect_file_type(Path::new("frame")).is_err());
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ enum Command {
|
||||
/// Path to the .graphite document
|
||||
document: PathBuf,
|
||||
|
||||
/// Output file path (extension determines format: .svg, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif)
|
||||
/// Output file path (extension determines format: .svg, .pdf, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif)
|
||||
#[clap(long, short = 'o')]
|
||||
output: PathBuf,
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{Context, Generations, OwnedContextImpl};
|
||||
use dyn_any::{DynAny, StaticType, StaticTypeSized};
|
||||
use glam::DVec2;
|
||||
@@ -43,6 +44,19 @@ pub enum ExportFormat {
|
||||
#[default]
|
||||
Svg,
|
||||
Raster,
|
||||
Pdf {
|
||||
/// Puts each artboard on a page of its own, sized to it, rather than all of the export's area on one page.
|
||||
artboards_as_pages: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// What an exported document records about itself, where its format has a place for it.
|
||||
#[derive(Debug, Default, Clone, PartialEq, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ExportMetadata {
|
||||
pub title: String,
|
||||
/// The names of the artboards by the IDs of their layers, which a PDF's bookmarks of their pages take.
|
||||
pub artboard_names: Vec<(NodeId, String)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
@@ -52,7 +66,7 @@ pub struct TimingInformation {
|
||||
pub animation_time: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
#[derive(Debug, Default, Clone, PartialEq, DynAny, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct RenderConfig {
|
||||
pub viewport: Footprint,
|
||||
@@ -64,6 +78,9 @@ pub struct RenderConfig {
|
||||
pub export_format: ExportFormat,
|
||||
pub for_export: bool,
|
||||
pub for_eyedropper: bool,
|
||||
/// What an exported document records about itself.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub metadata: Option<ExportMetadata>,
|
||||
}
|
||||
|
||||
impl RenderConfig {
|
||||
|
||||
@@ -26,6 +26,7 @@ brush-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
graphene-application-io = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
@@ -38,6 +39,8 @@ vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
glifo = { workspace = true }
|
||||
krilla = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
parley = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
|
||||
@@ -21,7 +21,7 @@ pub enum PaintTarget {
|
||||
}
|
||||
|
||||
impl PaintTarget {
|
||||
fn paint_attr(self) -> &'static str {
|
||||
pub(crate) fn paint_attr(self) -> &'static str {
|
||||
match self {
|
||||
Self::Fill => "fill",
|
||||
Self::Stroke => "stroke",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -44,6 +44,30 @@ pub struct VelloSceneBuilder<'a> {
|
||||
effects_renderer: Option<&'a mut dyn EffectsRenderer>,
|
||||
/// The coverage the next effects group drawn outputs in place of its result, for an SVG map of it.
|
||||
effect_capture: Option<EffectCapture>,
|
||||
/// Caches the outlines of glyph runs drawn natively. A scene without it can't draw glyph runs.
|
||||
glyph_resources: Option<&'a dyn GlyphResources>,
|
||||
}
|
||||
|
||||
/// Lends out the renderer's resources that glyph runs cache their outlines in.
|
||||
pub trait GlyphResources: Sync {
|
||||
/// Calls `draw` with the resources, held exclusively until it returns.
|
||||
fn with_resources(&self, draw: &mut dyn FnMut(&mut vello_gpu::Resources));
|
||||
}
|
||||
|
||||
/// The font and styling shared by the glyphs of one glyph run.
|
||||
pub struct GlyphRunStyle<'b> {
|
||||
pub font: &'b peniko::FontData,
|
||||
pub font_size: f32,
|
||||
/// The variation coordinates of a variable font, empty for its default instance.
|
||||
pub normalized_coords: &'b [i16],
|
||||
/// Places each glyph's outline relative to its origin, like a skew for faux italics.
|
||||
pub glyph_transform: Affine,
|
||||
}
|
||||
|
||||
/// Whether a glyph run's outlines are filled or stroked.
|
||||
pub enum GlyphPaintMode<'b> {
|
||||
Fill,
|
||||
Stroke(&'b Stroke),
|
||||
}
|
||||
|
||||
/// Renders the content of a scene's effects groups offscreen and carries out their effects, while the scene is drawn.
|
||||
@@ -148,6 +172,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
pushed: Vec::new(),
|
||||
effects_renderer: None,
|
||||
effect_capture: None,
|
||||
glyph_resources: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +182,17 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Draws glyph runs natively, caching their outlines in `resources`.
|
||||
pub fn with_glyph_resources(mut self, resources: &'a dyn GlyphResources) -> Self {
|
||||
self.glyph_resources = Some(resources);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether [`Self::draw_glyphs`] can draw, which needs glyph resources.
|
||||
pub fn can_draw_glyphs(&self) -> bool {
|
||||
self.glyph_resources.is_some()
|
||||
}
|
||||
|
||||
/// Has the next effects group drawn output the coverage `capture` names in place of its result, leaving the groups drawn within it as they are.
|
||||
pub fn capture_next_effects(&mut self, capture: EffectCapture) {
|
||||
self.effect_capture = Some(capture);
|
||||
@@ -237,6 +273,42 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self.scene.stroke_path(&finite_path(&shape.to_path(SHAPE_TOLERANCE)));
|
||||
}
|
||||
|
||||
/// Draws a run of glyphs positioned in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
||||
/// Draws nothing without glyph resources, which [`Self::can_draw_glyphs`] tells.
|
||||
pub fn draw_glyphs<'b>(&mut self, style: &GlyphRunStyle, mode: GlyphPaintMode, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, glyphs: &[glifo::Glyph]) {
|
||||
let Some(glyph_resources) = self.glyph_resources else {
|
||||
log::error!("A scene without glyph resources was asked to draw glyphs");
|
||||
return;
|
||||
};
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(Fill::NonZero);
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
if let GlyphPaintMode::Stroke(stroke) = mode {
|
||||
self.scene.set_stroke(stroke.clone());
|
||||
}
|
||||
|
||||
let scene = &mut self.scene;
|
||||
glyph_resources.with_resources(&mut |resources| {
|
||||
// Unhinted, so outlines keep their shapes at every zoom like the rest of the artwork
|
||||
let glyph_run = (scene.glyph_run(resources, style.font))
|
||||
.font_size(style.font_size)
|
||||
.normalized_coords(style.normalized_coords)
|
||||
.glyph_transform(style.glyph_transform)
|
||||
.hint(false);
|
||||
|
||||
let drawn = match mode {
|
||||
GlyphPaintMode::Fill => glyph_run.fill_glyphs(glyphs.iter().copied()),
|
||||
GlyphPaintMode::Stroke(_) => glyph_run.stroke_glyphs(glyphs.iter().copied()),
|
||||
};
|
||||
if let Err(error) = drawn {
|
||||
log::warn!("Some glyphs failed to draw: {error:?}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
|
||||
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
|
||||
@@ -41,6 +41,7 @@ fastnoise-lite = { workspace = true, features = ["wgsl"] }
|
||||
[dev-dependencies]
|
||||
# Local dependencies
|
||||
graphene-resource = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
|
||||
# Required dependencies
|
||||
# Turns on the shader translators of every backend for the tests, whichever of them the platform's own backends build with
|
||||
|
||||
@@ -34,9 +34,9 @@ impl WgpuExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders images of the content an SVG of the view `footprint` describes defers to the GPU, with where the SVG draws each.
|
||||
/// Content out of view, or that fails to render, keeps the markup standing in for it.
|
||||
pub fn render_deferred_svg_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
|
||||
/// Renders images of the content an SVG or PDF of the view `footprint` defers to the GPU, with where each is drawn.
|
||||
/// Content out of view, or that fails to render, gets no image.
|
||||
pub fn render_deferred_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
|
||||
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
|
||||
|
||||
deferred_images
|
||||
@@ -56,9 +56,17 @@ impl WgpuExecutor {
|
||||
|
||||
/// Reads back the images of deferred content, putting each in `svg` in place of the markup standing in for its content.
|
||||
pub async fn resolve_deferred_svg_images(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, images: Vec<(DeferredImagePlacement, Texture)>) {
|
||||
for (placement, texture) in images {
|
||||
let image: Raster<CPU> = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await;
|
||||
for (placement, image) in self.read_back_deferred_images(images).await {
|
||||
substitute_deferred_image(svg, image_data, &placement, &image);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads back the images of deferred content into CPU memory, each with where it goes.
|
||||
pub async fn read_back_deferred_images(&self, images: Vec<(DeferredImagePlacement, Texture)>) -> Vec<(DeferredImagePlacement, Raster<CPU>)> {
|
||||
let mut read_back = Vec::with_capacity(images.len());
|
||||
for (placement, texture) in images {
|
||||
read_back.push((placement, Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await));
|
||||
}
|
||||
read_back
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use glam::{DAffine2, UVec2};
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster, WeakCPU};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, GlyphResources, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use vello_gpu::kurbo::Affine;
|
||||
@@ -38,7 +38,7 @@ pub const MAX_LAYER_RENDER_SIZE: u32 = 4096;
|
||||
|
||||
/// Vello GPU's renderer and GPU resources, shared by every [`VelloCanvas`] so their memory and pipelines exist once.
|
||||
pub(crate) struct VelloRenderer {
|
||||
/// Locked only while a scene is rendered and submitted, so one canvas drawing its scene on the CPU doesn't hold up another's render.
|
||||
/// Locked only while a scene is rendered and submitted or a glyph run is drawn, so one canvas drawing its scene on the CPU doesn't hold up another's render.
|
||||
gpu: Mutex<(Renderer, Resources)>,
|
||||
alpha_conversion: AlphaConversion,
|
||||
effect_passes: EffectPasses,
|
||||
@@ -258,7 +258,10 @@ impl RenderContext<'_> {
|
||||
// Draw the scene for this render's size and placement, which renders its effects groups as they're drawn
|
||||
let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height));
|
||||
scene.reset_and_resize(width, height);
|
||||
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size).with_effects_renderer(self);
|
||||
let glyph_resources: &VelloRenderer = self.renderer;
|
||||
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size)
|
||||
.with_glyph_resources(glyph_resources)
|
||||
.with_effects_renderer(self);
|
||||
draw(&mut builder);
|
||||
let (scene, images) = builder.finish();
|
||||
|
||||
@@ -356,6 +359,14 @@ impl RenderContext<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl GlyphResources for VelloRenderer {
|
||||
fn with_resources(&self, draw: &mut dyn FnMut(&mut Resources)) {
|
||||
// Glyph runs are drawn without the atlas cache, so they only touch the CPU-side outline caches the lock guards
|
||||
let mut gpu = self.gpu.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
draw(&mut gpu.1);
|
||||
}
|
||||
}
|
||||
|
||||
impl EffectsRenderer for RenderContext<'_> {
|
||||
fn renders_effects(&self) -> bool {
|
||||
self.renderer.effect_passes.renders_working_formats
|
||||
|
||||
@@ -2192,7 +2192,7 @@ fn svgs_draw_content_with_effects_svg_cannot_express_as_images_the_gpu_renders()
|
||||
resolution: UVec2::splat(32),
|
||||
..Default::default()
|
||||
};
|
||||
let rendered = executor.render_deferred_svg_images(&render.deferred_images, footprint);
|
||||
let rendered = executor.render_deferred_images(&render.deferred_images, footprint);
|
||||
|
||||
// The square comes out gray, with the shadow beside it
|
||||
let [(_, texture)] = &rendered[..] else { panic!("expected one image, got {}", rendered.len()) };
|
||||
@@ -2541,3 +2541,98 @@ fn new_generator_tiles_take_over_the_textures_of_freed_ones() {
|
||||
"the third pattern's tiles render into the textures of the first's"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_glyph_runs_match_outlined_text() {
|
||||
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
||||
use core_types::{ATTR_FONT_SIZE, ATTR_LETTER_TILT, ATTR_MAX_WIDTH, ATTR_TEXT_ALIGN, ATTR_TRANSFORM};
|
||||
use graphic_types::{Appearance, Coverage, Graphic};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(320, 120);
|
||||
|
||||
// Tilted, and wrapped into a justified last line so blank glyphs take the extra spacing
|
||||
let text = Item::new_from_element("Glyph runs\nspace out".to_string())
|
||||
.with_attribute(ATTR_FONT_SIZE, 36.)
|
||||
.with_attribute(ATTR_LETTER_TILT, 12.)
|
||||
.with_attribute(ATTR_MAX_WIDTH, 300.)
|
||||
.with_attribute(ATTR_TEXT_ALIGN, text_nodes::TextAlign::JustifyAll)
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(glam::DVec2::new(10., 10.)));
|
||||
|
||||
let mut outlined = text_nodes::shape_text_item(&text, false).expect("the fallback font shapes the text");
|
||||
let black_fill = Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(core_types::Color::BLACK)));
|
||||
for index in 0..outlined.len() {
|
||||
outlined.set_attribute(ATTR_APPEARANCE, index, black_fill.clone());
|
||||
}
|
||||
let text = List::new_from_item(text);
|
||||
|
||||
let render_params = RenderParams::default();
|
||||
let Some(native) = render(size, |scene| {
|
||||
assert!(scene.can_draw_glyphs(), "renders through the executor draw glyph runs natively");
|
||||
text.render_to_vello(scene, DAffine2::IDENTITY, &render_params);
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let Some(reference) = render(size, |scene| outlined.render_to_vello(scene, DAffine2::IDENTITY, &render_params)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let coverage = |pixels: &[[u8; 4]]| pixels.iter().filter(|pixel| pixel[3] > 127).count();
|
||||
assert!(coverage(&reference) > 500, "the reference draws the text");
|
||||
|
||||
// Both fill the same outlines, so only antialiasing along their edges may differ
|
||||
let differing = native.iter().zip(&reference).filter(|(a, b)| a[3].abs_diff(b[3]) > 64).count();
|
||||
assert!(differing * 50 < coverage(&reference), "{differing} pixels differ out of {} covered", coverage(&reference));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_glyph_runs_paint_like_outlined_text() {
|
||||
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
||||
use core_types::{ATTR_FONT_SIZE, ATTR_TRANSFORM};
|
||||
use graphic_types::appearance::{CoverPlacement, stamp_coverage};
|
||||
use graphic_types::vector_types::gradient::Gradient;
|
||||
use graphic_types::vector_types::vector::style::Stroke as VectorStroke;
|
||||
use graphic_types::{Appearance, Coverage, Graphic};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(320, 120);
|
||||
|
||||
// Scaled evenly, so the stroke's width is measured in a space the glyphs reach by a uniform scale
|
||||
let mut text = Item::new_from_element("Painted".to_string())
|
||||
.with_attribute(ATTR_FONT_SIZE, 40.)
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale_angle_translation(glam::DVec2::splat(1.5), 0.1, glam::DVec2::new(10., 5.)));
|
||||
|
||||
let gradient_placement = DAffine2::from_scale_angle_translation(glam::DVec2::new(160., 50.), 0., glam::DVec2::ZERO);
|
||||
let gradient = Item::new_from_element(Gradient::from(vec![
|
||||
core_types::Color::from_rgbaf32_unchecked(1., 0., 0., 1.),
|
||||
core_types::Color::from_rgbaf32_unchecked(0., 0., 1., 1.),
|
||||
]))
|
||||
.with_attribute(ATTR_TRANSFORM, gradient_placement);
|
||||
stamp_coverage(&mut text, Coverage::new_fill(), Graphic::Gradient(gradient), CoverPlacement::Above);
|
||||
|
||||
let stroke = VectorStroke { weight: 3., ..Default::default() };
|
||||
let stroke_paint = Graphic::ColorList(List::new_from_element(core_types::Color::from_rgbaf32_unchecked(0., 0.6, 0., 1.)));
|
||||
stamp_coverage(&mut text, Coverage::new_stroke(&stroke), stroke_paint, CoverPlacement::Above);
|
||||
|
||||
let appearance: Appearance = text.attribute_cloned_or_default(ATTR_APPEARANCE);
|
||||
let mut outlined = text_nodes::shape_text_item(&text, false).expect("the fallback font shapes the text");
|
||||
for index in 0..outlined.len() {
|
||||
outlined.set_attribute(ATTR_APPEARANCE, index, appearance.clone());
|
||||
}
|
||||
let text = List::new_from_item(text);
|
||||
|
||||
let render_params = RenderParams::default();
|
||||
let Some(native) = render(size, |scene| text.render_to_vello(scene, DAffine2::IDENTITY, &render_params)) else {
|
||||
return;
|
||||
};
|
||||
let Some(reference) = render(size, |scene| outlined.render_to_vello(scene, DAffine2::IDENTITY, &render_params)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let covered = reference.iter().filter(|pixel| pixel[3] > 127).count();
|
||||
assert!(covered > 500, "the reference draws the text");
|
||||
|
||||
// Strokes expand per glyph rather than along the compound outline, so only antialiasing along their edges may differ
|
||||
let differing = (native.iter().zip(&reference)).filter(|(a, b)| a.iter().zip(b.iter()).any(|(a, b)| a.abs_diff(*b) > 64)).count();
|
||||
assert!(differing * 50 < covered, "{differing} pixels differ out of {covered} covered");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
mod svg_readback;
|
||||
mod readback;
|
||||
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
@@ -9,10 +9,10 @@ use graphene_application_io::{ExportFormat, RenderConfig};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use readback::ReadbackSlot;
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::sync::Arc;
|
||||
use svg_readback::SvgReadbackSlot;
|
||||
use vector_types::Gradient;
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
@@ -23,6 +23,8 @@ pub enum RenderIntermediateType {
|
||||
Svg(Arc<SvgRenderOutput>),
|
||||
/// The content itself, for content that draws only the part of it in view, drawn as SVG at each render for its view
|
||||
SvgInView(Arc<dyn Render + Send + Sync>),
|
||||
/// The content itself, drawn onto a PDF page sized at each render
|
||||
Pdf(Arc<dyn Render + Send + Sync>),
|
||||
}
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub struct RenderIntermediate {
|
||||
@@ -62,6 +64,10 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
ty: RenderIntermediateType::Vello(Arc::new(data)),
|
||||
metadata,
|
||||
},
|
||||
RenderOutputTypeRequest::Pdf => RenderIntermediate {
|
||||
ty: RenderIntermediateType::Pdf(Arc::new(data)),
|
||||
metadata,
|
||||
},
|
||||
RenderOutputTypeRequest::Svg => {
|
||||
let render_params = RenderParams {
|
||||
view_wanted: Default::default(),
|
||||
@@ -90,7 +96,7 @@ fn render(
|
||||
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node<Context<'static>, Output = Item<WgpuExecutor>>,
|
||||
#[scope("runtime")] runtime: Item<RuntimeHandle>,
|
||||
#[source_id] source: Item<SourceId>,
|
||||
#[data] svg_readback: SvgReadbackSlot,
|
||||
#[data] readback: ReadbackSlot,
|
||||
) -> Poll<Item<RenderOutput>> {
|
||||
let footprint = ctx.footprint();
|
||||
let render_params = ctx
|
||||
@@ -131,11 +137,11 @@ fn render(
|
||||
assert!(output.svg_defs.is_empty());
|
||||
|
||||
let executor = executor.eval(&Context::default()).value().map(Item::into_element);
|
||||
svg_readback.poll(output, *footprint, executor, runtime.element(), *source.element())
|
||||
readback.poll(output, *footprint, executor, runtime.element(), *source.element())
|
||||
}
|
||||
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
|
||||
// The latest SVG render isn't needed anymore, and a finished one holds a whole SVG export
|
||||
svg_readback.clear();
|
||||
readback.clear();
|
||||
|
||||
let (executor, executor_partial, executor_error) = match executor.eval(&Context::default()) {
|
||||
Poll::Final(executor) => (executor.into_element(), false, None),
|
||||
@@ -169,6 +175,14 @@ fn render(
|
||||
(false, None) => Poll::Final(texture),
|
||||
}
|
||||
}
|
||||
(RenderOutputTypeRequest::Pdf, RenderIntermediateType::Pdf(content)) => {
|
||||
let logical_transform = glam::DAffine2::from_scale(glam::DVec2::splat(1.0 / render_params.scale)) * footprint.transform;
|
||||
let logical_resolution = footprint.resolution.as_dvec2() / render_params.scale;
|
||||
let page = rendering::pdf::PdfPage::new(logical_resolution, logical_transform, render_params.scale);
|
||||
|
||||
let executor = executor.eval(&Context::default()).value().map(Item::into_element);
|
||||
readback.poll_pdf(content, page, render_params.clone(), executor, runtime.element(), *source.element())
|
||||
}
|
||||
_ => unreachable!("Render node did not receive its requested data type"),
|
||||
};
|
||||
|
||||
@@ -181,7 +195,7 @@ fn create_context(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
|
||||
data: impl Node<Context<'static>, Output = Item<RenderOutput>>,
|
||||
) -> Result<Item<RenderOutput>, Interrupt> {
|
||||
let render_config = ctx.vararg(0).ok().and_then(|config| config.downcast_ref::<RenderConfig>()).copied().unwrap_or_else(|| {
|
||||
let render_config = ctx.vararg(0).ok().and_then(|config| config.downcast_ref::<RenderConfig>()).cloned().unwrap_or_else(|| {
|
||||
log::error!("The boundary context is missing its render config vararg");
|
||||
RenderConfig::default()
|
||||
});
|
||||
@@ -189,6 +203,7 @@ fn create_context(
|
||||
let render_output_type = match render_config.export_format {
|
||||
ExportFormat::Svg => RenderOutputTypeRequest::Svg,
|
||||
ExportFormat::Raster => RenderOutputTypeRequest::Vello,
|
||||
ExportFormat::Pdf { .. } => RenderOutputTypeRequest::Pdf,
|
||||
};
|
||||
|
||||
let logical_viewport = render_config.viewport;
|
||||
@@ -200,12 +215,16 @@ fn create_context(
|
||||
// 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.,
|
||||
RenderOutputTypeRequest::Vello | RenderOutputTypeRequest::Pdf => 0.,
|
||||
};
|
||||
|
||||
let render_params = RenderParams {
|
||||
render_mode: render_config.render_mode,
|
||||
for_export: render_config.for_export,
|
||||
// Exported SVG files keep their text as text, while the canvas and other SVG renders draw it as outlines
|
||||
embed_fonts: render_config.for_export && matches!(render_output_type, RenderOutputTypeRequest::Svg),
|
||||
artboards_as_pages: matches!(render_config.export_format, ExportFormat::Pdf { artboards_as_pages: true }),
|
||||
export_metadata: render_config.metadata.clone().map(Arc::new),
|
||||
render_output_type,
|
||||
scale: render_config.scale,
|
||||
viewport_zoom: Some(logical_viewport.scale_magnitudes().x),
|
||||
|
||||
+139
-24
@@ -1,33 +1,35 @@
|
||||
use core_types::WasmNotSend;
|
||||
use core_types::runtime::Runtime;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, Poll, RuntimeHandle, SourceId};
|
||||
use futures::future::{AbortHandle, Abortable};
|
||||
use graph_craft::document::value::RenderOutputType;
|
||||
use rendering::SvgRenderOutput;
|
||||
use rendering::pdf::{PdfPage, PdfRasters, render_pdf_document};
|
||||
use rendering::{Render, RenderParams, SvgRenderOutput};
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
/// The latest SVG render that needs maps and images from the GPU, kept across the render node's evaluations while a task reads them back.
|
||||
/// The latest SVG or PDF render that needs maps and images from the GPU, kept across the render node's evaluations while a task reads them back.
|
||||
/// A render of other content or for another view replaces it, cancelling the readback still underway for the one it replaced.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SvgReadbackSlot(Arc<Mutex<Option<SvgReadback>>>);
|
||||
pub struct ReadbackSlot(Arc<Mutex<Option<Readback>>>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SvgReadback {
|
||||
struct Readback {
|
||||
key: u64,
|
||||
finished: Option<RenderOutputType>,
|
||||
task: AbortHandle,
|
||||
}
|
||||
|
||||
impl Drop for SvgReadback {
|
||||
impl Drop for Readback {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
impl SvgReadbackSlot {
|
||||
fn lock(&self) -> MutexGuard<'_, Option<SvgReadback>> {
|
||||
impl ReadbackSlot {
|
||||
fn lock(&self) -> MutexGuard<'_, Option<Readback>> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
@@ -53,33 +55,105 @@ impl SvgReadbackSlot {
|
||||
footprint.cache_hash(&mut hasher);
|
||||
let key = hasher.finish();
|
||||
|
||||
if self.lock().as_ref().is_none_or(|readback| readback.key != key) {
|
||||
let Some(executor) = executor else {
|
||||
return Poll::Final(RenderOutputType::Svg { svg, image_data });
|
||||
};
|
||||
let partial = RenderOutputType::Svg {
|
||||
svg: svg.clone(),
|
||||
image_data: image_data.clone(),
|
||||
};
|
||||
self.poll_readback(key, partial, runtime, source, || {
|
||||
let executor = executor?;
|
||||
let effect_maps = executor.render_effect_maps(&output.effect_maps, footprint);
|
||||
let deferred_images = executor.render_deferred_svg_images(&output.deferred_images, footprint);
|
||||
let deferred_images = executor.render_deferred_images(&output.deferred_images, footprint);
|
||||
if effect_maps.is_empty() && deferred_images.is_empty() {
|
||||
self.clear();
|
||||
return Poll::Final(RenderOutputType::Svg { svg, image_data });
|
||||
return None;
|
||||
}
|
||||
|
||||
let (task, registration) = AbortHandle::new_pair();
|
||||
*self.lock() = Some(SvgReadback { key, finished: None, task });
|
||||
|
||||
let (mut svg, mut image_data) = (svg.clone(), image_data.clone());
|
||||
let readback = async move {
|
||||
let (mut svg, mut image_data) = (svg, image_data);
|
||||
Some(async move {
|
||||
executor.resolve_effect_maps(&mut svg, effect_maps).await;
|
||||
executor.resolve_deferred_svg_images(&mut svg, &mut image_data, deferred_images).await;
|
||||
RenderOutputType::Svg { svg, image_data }
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The PDF of `content` with the images the GPU renders of what the PDF can't draw itself, partial without them while a task reads them back.
|
||||
/// The task landing evaluates the render node again through its `source`.
|
||||
pub fn poll_pdf(
|
||||
&self,
|
||||
content: Arc<dyn Render + Send + Sync>,
|
||||
page: PdfPage,
|
||||
render_params: RenderParams,
|
||||
executor: Option<WgpuExecutor>,
|
||||
runtime: &RuntimeHandle,
|
||||
source: SourceId,
|
||||
) -> Poll<RenderOutputType> {
|
||||
let (pdf, deferred) = match render_pdf_document(content.as_ref(), &page, &render_params, PdfRasters::new()) {
|
||||
Ok(rendered) => rendered,
|
||||
Err(error) => return Poll::error(error),
|
||||
};
|
||||
if deferred.is_empty() {
|
||||
self.clear();
|
||||
return Poll::Final(RenderOutputType::Pdf { data: pdf });
|
||||
}
|
||||
|
||||
// The document without its images stands for its content, which sets the key apart from other renders
|
||||
let mut hasher = DefaultHasher::new();
|
||||
pdf.hash(&mut hasher);
|
||||
page.size.to_array().map(f64::to_bits).hash(&mut hasher);
|
||||
page.transform.to_cols_array().map(f64::to_bits).hash(&mut hasher);
|
||||
page.raster_scale.to_bits().hash(&mut hasher);
|
||||
let key = hasher.finish();
|
||||
|
||||
let partial = RenderOutputType::Pdf { data: pdf.clone() };
|
||||
self.poll_readback(key, partial, runtime, source, || {
|
||||
let executor = executor?;
|
||||
// Each image is rendered in the view of the page it's on
|
||||
let images: Vec<_> = (deferred.iter())
|
||||
.flat_map(|deferred| executor.render_deferred_images(std::slice::from_ref(&deferred.image), deferred.view))
|
||||
.collect();
|
||||
if images.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(async move {
|
||||
let rasters: PdfRasters = (executor.read_back_deferred_images(images).await.into_iter())
|
||||
.map(|(placement, raster)| (placement.id, (placement, raster)))
|
||||
.collect();
|
||||
|
||||
match render_pdf_document(content.as_ref(), &page, &render_params, rasters) {
|
||||
Ok((data, _)) => RenderOutputType::Pdf { data },
|
||||
// The document without the images is the most there is to export
|
||||
Err(error) => {
|
||||
log::error!("{error}");
|
||||
RenderOutputType::Pdf { data: pdf }
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The finished output of the render `key` names, starting its readback with `start` the first time it's polled, and `partial` until the readback lands.
|
||||
/// Without a readback to start, `partial` is all there is to the render.
|
||||
fn poll_readback<F>(&self, key: u64, partial: RenderOutputType, runtime: &RuntimeHandle, source: SourceId, start: impl FnOnce() -> Option<F>) -> Poll<RenderOutputType>
|
||||
where
|
||||
F: Future<Output = RenderOutputType> + WasmNotSend + 'static,
|
||||
{
|
||||
if self.lock().as_ref().is_none_or(|readback| readback.key != key) {
|
||||
let Some(readback) = start() else {
|
||||
self.clear();
|
||||
return Poll::Final(partial);
|
||||
};
|
||||
|
||||
let (task, registration) = AbortHandle::new_pair();
|
||||
*self.lock() = Some(Readback { key, finished: None, task });
|
||||
|
||||
// Held weakly, the slot is dropped along with the render node, which cancels the readback
|
||||
let slot = Arc::downgrade(&self.0);
|
||||
runtime.spawn(
|
||||
source,
|
||||
Box::pin(async move {
|
||||
if let Ok(finished) = Abortable::new(readback, registration).await
|
||||
&& let Some(slot) = slot.upgrade().map(SvgReadbackSlot)
|
||||
&& let Some(slot) = slot.upgrade().map(ReadbackSlot)
|
||||
&& let Some(readback) = slot.lock().as_mut().filter(|readback| readback.key == key)
|
||||
{
|
||||
readback.finished = Some(finished);
|
||||
@@ -91,7 +165,7 @@ impl SvgReadbackSlot {
|
||||
let finished = self.lock().as_ref().filter(|readback| readback.key == key).and_then(|readback| readback.finished.clone());
|
||||
match finished {
|
||||
Some(finished) => Poll::Final(finished),
|
||||
None => Poll::Partial(RenderOutputType::Svg { svg, image_data }),
|
||||
None => Poll::Partial(partial),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,7 +247,7 @@ mod tests {
|
||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
||||
let tasks = Arc::new(HeldTasks::default());
|
||||
let runtime = AsyncRuntime::new(tasks.clone());
|
||||
let slot = SvgReadbackSlot::default();
|
||||
let slot = ReadbackSlot::default();
|
||||
let output = deferred_svg();
|
||||
let poll = || slot.poll(again(&output), view(32), Some(executor.clone()), &runtime.handle(), SourceId(1));
|
||||
|
||||
@@ -194,12 +268,53 @@ mod tests {
|
||||
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pdf_render_embeds_images_of_effects_once_its_readback_lands() {
|
||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
||||
let tasks = Arc::new(HeldTasks::default());
|
||||
let runtime = AsyncRuntime::new(tasks.clone());
|
||||
let slot = ReadbackSlot::default();
|
||||
|
||||
// The orange square casting a shadow, which no PDF can draw itself
|
||||
let shadow = EffectOperation::DropShadow {
|
||||
color: Color::BLACK,
|
||||
angle: 180.,
|
||||
distance: 4.,
|
||||
spread: 0.,
|
||||
size: 0.,
|
||||
contour: Default::default(),
|
||||
knockout: true,
|
||||
};
|
||||
let mut item =
|
||||
Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::from_gamma_srgb_channels(1., 0.5, 0., 1.)))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(10.)));
|
||||
stamp_effect(&mut item, Effect::new(&shadow));
|
||||
let content: Arc<dyn Render + Send + Sync> = Arc::new(List::new_from_item(item));
|
||||
|
||||
let page = PdfPage::new(DVec2::splat(32.), DAffine2::IDENTITY, 1.);
|
||||
let poll = || slot.poll_pdf(content.clone(), page, RenderParams::default(), Some(executor.clone()), &runtime.handle(), SourceId(1));
|
||||
let embeds_image = |pdf: &[u8]| pdf.windows(b"/Subtype/Image".len()).any(|window| window == b"/Subtype/Image");
|
||||
|
||||
// Until the readback lands, the PDF lacks the image, and evaluating the same render again doesn't read it back again
|
||||
for _ in 0..2 {
|
||||
let Poll::Partial(RenderOutputType::Pdf { data }) = poll() else {
|
||||
panic!("expected a partial PDF")
|
||||
};
|
||||
assert!(!embeds_image(&data), "the partial PDF shouldn't have the image yet");
|
||||
}
|
||||
let spawned = tasks.take();
|
||||
assert_eq!(spawned.len(), 1, "the readback should be spawned once");
|
||||
|
||||
spawned.into_iter().for_each(futures::executor::block_on);
|
||||
let Poll::Final(RenderOutputType::Pdf { data }) = poll() else { panic!("expected a finished PDF") };
|
||||
assert!(embeds_image(&data), "the finished PDF should embed the image of the square and its shadow");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_render_for_another_view_cancels_the_readback_of_the_one_it_replaces() {
|
||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
||||
let tasks = Arc::new(HeldTasks::default());
|
||||
let runtime = AsyncRuntime::new(tasks.clone());
|
||||
let slot = SvgReadbackSlot::default();
|
||||
let slot = ReadbackSlot::default();
|
||||
let output = deferred_svg();
|
||||
let poll = |size| slot.poll(again(&output), view(size), Some(executor.clone()), &runtime.handle(), SourceId(1));
|
||||
|
||||
@@ -224,7 +339,7 @@ mod tests {
|
||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
||||
let tasks = Arc::new(HeldTasks::default());
|
||||
let runtime = AsyncRuntime::new(tasks.clone());
|
||||
let slot = SvgReadbackSlot::default();
|
||||
let slot = ReadbackSlot::default();
|
||||
|
||||
let render = slot.poll(deferred_svg(), view(32), Some(executor), &runtime.handle(), SourceId(1));
|
||||
assert!(matches!(render, Poll::Partial(_)));
|
||||
@@ -28,16 +28,8 @@ fn typography_attribute<T: Clone + 'static>(item: &Item<String>, key: &'static s
|
||||
value.downcast_ref::<T>().cloned().map(Some).ok_or(TextToVectorError::MistypedAttribute(key))
|
||||
}
|
||||
|
||||
/// Shapes a single styled string item into vector geometry, reading its font and typesetting from the item's
|
||||
/// attributes (as set by the 'Text' node) and re-applying its transform and blending attributes onto the produced
|
||||
/// paths. With `separate_glyphs`, each glyph becomes its own item; otherwise a single compound path is produced.
|
||||
pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> Result<List<Vector>, TextToVectorError> {
|
||||
let text = item.element();
|
||||
if text.is_empty() {
|
||||
return Ok(List::new());
|
||||
}
|
||||
|
||||
// Use fallback font when none is explicitly attached.
|
||||
/// The font and typesetting a styled string item's attributes set, falling back to the default font when none is attached.
|
||||
fn item_font_and_typesetting(item: &Item<String>) -> Result<(Resource, TypesettingConfig), TextToVectorError> {
|
||||
let font = typography_attribute::<Resource>(item, ATTR_FONT)?.filter(|font| !font.is_empty());
|
||||
let font = font.unwrap_or_else(|| super::FALLBACK_FONT_RESOURCE.clone());
|
||||
|
||||
@@ -52,6 +44,30 @@ pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> Result<Lis
|
||||
align: typography_attribute(item, ATTR_TEXT_ALIGN)?.unwrap_or(defaults.align),
|
||||
};
|
||||
|
||||
Ok((font, typesetting))
|
||||
}
|
||||
|
||||
/// The box a styled string item lays out in, in its own space before its transform, or `None` for empty or unreadable text.
|
||||
pub fn text_item_layout_bounds(item: &Item<String>) -> Option<[DVec2; 2]> {
|
||||
if item.element().is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (font, typesetting) = item_font_and_typesetting(item).ok()?;
|
||||
let size = bounding_box(item.element(), &font, typesetting, false);
|
||||
(size != DVec2::ZERO).then_some([DVec2::ZERO, size])
|
||||
}
|
||||
|
||||
/// Shapes a single styled string item into vector geometry, reading its font and typesetting from the item's
|
||||
/// attributes (as set by the 'Text' node) and re-applying its transform and blending attributes onto the produced
|
||||
/// paths. With `separate_glyphs`, each glyph becomes its own item; otherwise a single compound path is produced.
|
||||
pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> Result<List<Vector>, TextToVectorError> {
|
||||
let text = item.element();
|
||||
if text.is_empty() {
|
||||
return Ok(List::new());
|
||||
}
|
||||
|
||||
let (font, typesetting) = item_font_and_typesetting(item)?;
|
||||
let vectors = to_path(text, &font, typesetting, separate_glyphs)?;
|
||||
let transform = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
let layer_path = item.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).cloned();
|
||||
|
||||
@@ -29,6 +29,7 @@ graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
repeat-nodes = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
|
||||
@@ -163,6 +163,48 @@ impl VectorItemMut for Item<Graphic> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Content a paint can cover, which a gradient without its own placement spans the bounds of.
|
||||
trait PaintTarget {
|
||||
/// The union of the content's bounds in its own space, before its transform.
|
||||
fn content_bounds(&mut self) -> Option<[DVec2; 2]>;
|
||||
}
|
||||
|
||||
/// The union of the bounds of the vector content `content` reaches, or `None` without any measurable geometry.
|
||||
fn vector_content_bounds(content: &mut impl VectorItemMut) -> Option<[DVec2; 2]> {
|
||||
let mut bounds: Option<[DVec2; 2]> = None;
|
||||
content.for_each_vector_mut(|vector, vector_paths, _| {
|
||||
if let Some([min, max]) = vector.bounding_box(vector_paths) {
|
||||
bounds = Some(match bounds {
|
||||
Some([bounds_min, bounds_max]) => [bounds_min.min(min), bounds_max.max(max)],
|
||||
None => [min, max],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
bounds
|
||||
}
|
||||
|
||||
impl PaintTarget for Item<Vector> {
|
||||
fn content_bounds(&mut self) -> Option<[DVec2; 2]> {
|
||||
vector_content_bounds(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl PaintTarget for Item<Graphic> {
|
||||
fn content_bounds(&mut self) -> Option<[DVec2; 2]> {
|
||||
match self.element() {
|
||||
Graphic::Text(text) => text_nodes::text_item_layout_bounds(text),
|
||||
_ => vector_content_bounds(self),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PaintTarget for Item<String> {
|
||||
fn content_bounds(&mut self) -> Option<[DVec2; 2]> {
|
||||
text_nodes::text_item_layout_bounds(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Geometry counterpart to [`VectorItemMut`] for the element-wise modifier nodes, running a per-item transformation over
|
||||
/// every vector reachable from the content. Geometry is never inherited, so this recurses into nested groups.
|
||||
trait MapVectorItems: Sized {
|
||||
@@ -408,12 +450,12 @@ fn vary_cover_colors<T: VectorListIterMut>(
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
|
||||
/// Applies a fill style to the vector or text content, giving an appearance to the area within the interior of the geometry.
|
||||
#[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"))]
|
||||
fn fill<V>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the fill style to.
|
||||
#[implementations(Vector, Graphic)]
|
||||
/// The vector paths or text to apply the fill style to.
|
||||
#[implementations(Vector, Graphic, String)]
|
||||
content: Item<V>,
|
||||
#[default(Color::BLACK)] paint: Item<Graphic>,
|
||||
_backup_color: Item<Color>,
|
||||
@@ -423,7 +465,7 @@ fn fill<V>(
|
||||
_transform: Item<DAffine2>,
|
||||
) -> Item<V>
|
||||
where
|
||||
Item<V>: VectorItemMut + Send,
|
||||
Item<V>: PaintTarget + Send,
|
||||
{
|
||||
let _gradient_form = _gradient_form.into_element();
|
||||
let (_has_transform, _transform) = (_has_transform.into_element(), *_transform.element());
|
||||
@@ -448,18 +490,8 @@ where
|
||||
return _transform;
|
||||
}
|
||||
|
||||
let mut bounds: Option<[DVec2; 2]> = None;
|
||||
content.for_each_vector_mut(|vector, vector_paths, _| {
|
||||
if let Some([min, max]) = vector.bounding_box(vector_paths) {
|
||||
bounds = Some(match bounds {
|
||||
Some([bmin, bmax]) => [bmin.min(min), bmax.max(max)],
|
||||
None => [min, max],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Nudge a degenerate axis so the gradient transform stays invertible, matching the editor's `nonzero_bounding_box`
|
||||
let [min, mut max] = bounds.unwrap_or([DVec2::ZERO, DVec2::ONE]);
|
||||
let [min, mut max] = content.content_bounds().unwrap_or([DVec2::ZERO, DVec2::ONE]);
|
||||
if max.x - min.x < 1e-10 {
|
||||
max.x = min.x + 1.;
|
||||
}
|
||||
@@ -498,12 +530,12 @@ where
|
||||
content
|
||||
}
|
||||
|
||||
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
|
||||
/// Applies a stroke style to the vector or text content, giving an appearance to the area within the outline of the geometry.
|
||||
#[node_macro::node(category("Vector: Style"), icon("NodeStroke"), path(graphene_core::vector), inspector("stroke_inspector"))]
|
||||
fn stroke<V>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the stroke style to.
|
||||
#[implementations(Vector, Graphic)]
|
||||
/// The vector paths or text to apply the stroke style to.
|
||||
#[implementations(Vector, Graphic, String)]
|
||||
content: Item<V>,
|
||||
/// The stroke paint.
|
||||
#[default(Color::BLACK)]
|
||||
@@ -530,7 +562,7 @@ fn stroke<V>(
|
||||
dash_offset: Item<f64>,
|
||||
) -> Item<V>
|
||||
where
|
||||
Item<V>: VectorItemMut + Send,
|
||||
Item<V>: PaintTarget + Send,
|
||||
{
|
||||
let mut content = content;
|
||||
let (weight, align, cap, join, miter_limit, dash_offset) = (
|
||||
|
||||
Reference in new issue
Block a user