Compare commits

..
Author SHA1 Message Date
Dennis Kobert 96a8e72fcf Fix Vivid Light burning and dodging the source by the backdrop instead of the backdrop by the source 2026-11-05 22:57:24 +00:00
Dennis Kobert 21910d242f Address review comments on the GPU raster kernels 2026-11-05 22:57:24 +00:00
Dennis Kobert c22fb0ec3a Add an Image to Channels GPU node for GPU rasters, since a multi-output struct can't be generic over its raster 2026-11-05 13:30:23 -08:00
Dennis Kobert 312dc1529b Version the nodes that gained GPU rasters and add their migrations 2026-11-05 13:30:23 -08:00
Dennis Kobert ccc32d6104 Test that CPU rasters stay on the CPU without a GPU, Eager opts into it, and a footprint-dependent raster warns at Dehaze 2026-11-05 13:30:22 -08:00
Dennis Kobert ba4b4812e7 Add an Eager node that uploads a raster so the nodes after it run on the GPU 2026-11-05 13:30:22 -08:00
Dennis Kobert 1642bf38ce Report a raster kernel's GPU failures and oversized outputs rather than saying a GPU is required 2026-11-05 13:30:22 -08:00
Dennis Kobert 6684bd279f Mark the Dehaze node as footprint invariant 2026-11-05 13:30:21 -08:00
Dennis Kobert 181c8e461c Fall back to half-float rasters where the GPU can't render full floats 2026-11-05 13:30:20 -08:00
Dennis Kobert 2e57be5aa1 Let list and render nodes carry GPU rasters 2026-11-05 13:30:19 -08:00
Dennis Kobert 7d6718dc67 Embed GPU rasters in SVG output by downloading them first 2026-11-05 13:30:19 -08:00
Dennis Kobert 49ecb3e695 Give GPU rasters an empty default 2026-11-05 13:30:19 -08:00
Dennis Kobert 73aeeee4d6 Run Dehaze and Image Color Palette on GPU rasters 2026-11-05 13:30:16 -08:00
Dennis Kobert 5cfe68dd32 Run raster nodes on GPU rasters through hand-written WGSL kernels 2026-11-05 13:30:15 -08:00
150 changed files with 8141 additions and 3179 deletions

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@
},
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
"containerEnv": {
"WASM_BINDGEN_CLI_VERSION": "0.2.129",
"WASM_BINDGEN_CLI_VERSION": "0.2.127",
"CARGO_ABOUT_VERSION": "0.9.2",
"BINARYEN_VERSION": "130",
"CARGO_BINSTALL_VERSION": "1.23.0"
+3 -3
View File
@@ -62,7 +62,7 @@ jobs:
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
# NOTICE: keep these tool versions in sync with the other jobs in this file, `check.yml` (sccache), `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
SCCACHE_VERSION: "v0.19.0"
WASM_BINDGEN_CLI_VERSION: "0.2.129"
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
steps:
@@ -348,7 +348,7 @@ jobs:
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.129"
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
@@ -617,7 +617,7 @@ jobs:
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.129"
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
+1 -1
View File
@@ -22,7 +22,7 @@ let
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_129
pkgs.wasm-bindgen-cli_0_2_127
deps.cargoAbout
pkgs.rustc
+1 -1
View File
@@ -83,7 +83,7 @@ deps.crane.lib.buildPackage (
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_129
pkgs.wasm-bindgen-cli_0_2_127
deps.cargoAbout
pkgs.removeReferencesTo
pkgs.importNpmLock.npmConfigHook
Generated
+2360 -1968
View File
File diff suppressed because it is too large. Load diff
+26 -26
View File
@@ -147,10 +147,10 @@ web-time = "1.1"
env_logger = "0.11"
log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
ctor = "1.0"
ctor = "0.2"
convert_case = "0.12"
titlecase = "3.6"
fancy-regex = "0.20.0"
fancy-regex = "0.18.0"
unicode-segmentation = "1.13.2"
indoc = "2.0.5"
derivative = "2.2"
@@ -176,10 +176,10 @@ wgpu = { version = "30.0", default-features = false, features = [
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
wasm-bindgen = "=0.2.129" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen = "=0.2.127" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen-futures = "0.4"
js-sys = "=0.3.106"
web-sys = { version = "=0.3.106", features = [
js-sys = "=0.3.104"
web-sys = { version = "=0.3.104", features = [
"Document",
"DomRect",
"Element",
@@ -210,25 +210,25 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
usvg = "0.49"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.12", default-features = false, features = ["std"] }
skrifa = "0.44"
parley = { version = "0.9", default-features = false, features = ["std"] }
skrifa = "0.42"
polycool = "0.4"
color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
rand_chacha = "0.10"
glam = { version = "0.34", default-features = false, features = [
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
"std",
"scalar-math",
"bytemuck",
"debug-glam-assert",
"all-types",
] }
base64 = "0.23"
base64 = "0.22"
blake3 = "1.5"
mmap-io = { version = "1.0", features = ["hugepages"] }
mmap-io = { version = "0.9", features = ["hugepages"] }
image = { version = "0.25", default-features = false, features = [
"png",
"jpeg",
@@ -245,10 +245,10 @@ image = { version = "0.25", default-features = false, features = [
pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
num_enum = { version = "0.7", default-features = false }
num-derive = "0.5"
num-derive = "0.4"
num-traits = "0.2"
tsify = { version = "0.5", default-features = false, features = ["js"] }
syn = { version = "3.0", default-features = false, features = [
syn = { version = "2.0", default-features = false, features = [
"full",
"derive",
"parsing",
@@ -262,14 +262,14 @@ syn = { version = "3.0", default-features = false, features = [
lyon_geom = "1.0"
delaunator = "1.0"
robust = "1.2"
petgraph = { version = "0.8", default-features = false, features = ["graphmap"] }
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.8", features = ["html_reports"] }
gungraun = { version = "0.20" }
ndarray = "0.17"
ollev = "0.1.2"
dirs = "7.0"
criterion = { version = "0.7", features = ["html_reports"] }
gungraun = { version = "0.18" }
ndarray = "0.16"
ollev = "0.1.1"
dirs = "6.0"
cef = "156"
cef-dll-sys = "156"
include_dir = "0.7"
@@ -277,14 +277,14 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
rfd = "0.17"
open = "5.3"
spin = "0.12"
spin = "0.10"
clap = "4.5"
qrcodegen = "1.8"
lzma-rust2 = { version = "0.25", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.29"
linesweeper = "0.5"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
linesweeper = "0.4"
smallvec = "1.13.2"
zip = { version = "9", default-features = false }
zip = { version = "8", default-features = false }
[workspace.lints]
+2 -10
View File
@@ -1,3 +1,5 @@
<a href="https://graphite.art/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/9366c148-4405-484f-909a-9a3526eb9209">
@@ -81,13 +83,3 @@ Are you a graphics programmer or Rust developer? Graphite aims to be one of the
## License
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
## Acknowledgments
We're grateful to these programs and organizations for the grants and services that help make Graphite possible.
[<img width="600" alt="European Commission, NGI Zero, and NLnet Foundation" src="https://github.com/user-attachments/assets/d5b3c623-710a-4809-916b-263e80c28184" />](https://nlnet.nl/commonsfund/)
[<img width="600" alt="Google Summer of Code" src="https://github.com/user-attachments/assets/37284dfe-fccd-4abd-904c-1165ff36da53" />](https://summerofcode.withgoogle.com/)
[<img width="300" alt="CI Powered by Blacksmith" src="https://github.com/user-attachments/assets/72bd48c2-ab21-4aed-b0a5-d440a8662128" />](https://www.blacksmith.sh/)
+1 -1
View File
@@ -1,4 +1,4 @@
use rand::RngExt;
use rand::Rng;
use rfd::AsyncFileDialog;
use std::fs;
use std::io::Read;
+1 -1
View File
@@ -34,7 +34,7 @@ serde_json = { workspace = true }
rand = { workspace = true, features = ["thread_rng"] }
cef = { workspace = true }
bytemuck = { workspace = true, optional = true }
ipc-channel = "0.23"
ipc-channel = "0.22"
# Linux-specific dependencies
[target.'cfg(target_os = "linux")'.dependencies]
+1 -1
View File
@@ -36,7 +36,7 @@ impl Archive for Zip {
if !entry.is_file() {
continue;
}
let name = entry.name().map_err(zip_err)?.to_string();
let name = entry.name().to_string();
validate_path(&name)?;
let size = checked_entry_size(&mut total_size, entry.size())?;
+2 -2
View File
@@ -91,7 +91,7 @@ impl MmappedBytes {
/// later degrading to the `&[]` fallback in [`AsRef::as_ref`], which cannot return an error.
pub fn new(file: mmap_io::mmap::MemoryMappedFile) -> Result<Self> {
let len = file.len();
file.as_slice_bytes(0, len)
file.as_slice(0, len)
.map_err(|error| ContainerError::Backend(format!("mmap slice of {:?} failed: {error}", file.path())))?;
Ok(Self(file))
}
@@ -105,7 +105,7 @@ impl MmappedBytes {
impl AsRef<[u8]> for MmappedBytes {
fn as_ref(&self) -> &[u8] {
let len = self.0.len();
match self.0.as_slice_bytes(0, len) {
match self.0.as_slice(0, len) {
Ok(slice) => slice,
Err(error) => {
log::error!("Failed to obtain mmap slice: {error}");
+1 -1
View File
@@ -244,7 +244,7 @@ fn registration(core: &TokenStream2, register: TokenStream2, migration: TokenStr
quote! {
use #core::ctor::ctor;
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = #core::ctor))]
#[cfg_attr(not(target_family = "wasm"), ctor)]
fn register() {
#core::#register(#migration);
}
+5
View File
@@ -4,3 +4,8 @@
mod graphene_core;
mod math_nodes;
mod raster_nodes;
/// The scope input of nodes that came to take the GPU pipeline, the identifier frozen as it was when they did.
fn raster_kernel_pipeline() -> migration_core::NodeInput {
migration_core::NodeInput::Scope("raster_nodes::raster_kernel::RasterKernelPipelineNode".into())
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::BlackAndWhiteNode"@1 => @2)]
pub fn black_and_white_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BlackAndWhiteV1, &contract());
check_undo(&BlackAndWhiteV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::filter::BlurNode"@1 => @2)]
pub fn blur_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BlurV1, &contract());
check_undo(&BlurV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::BrightnessContrastNode"@1 => @2)]
pub fn brightness_contrast_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BrightnessContrastV1, &contract());
check_undo(&BrightnessContrastV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ChannelMixerNode"@1 => @2)]
pub fn channel_mixer_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(19, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ChannelMixerV1, &contract());
check_undo(&ChannelMixerV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::std_nodes::ChannelsToImageNode"@1 => @2)]
pub fn channels_to_image_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ChannelsToImageV1, &contract());
check_undo(&ChannelsToImageV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ColorBalanceNode"@1 => @2)]
pub fn color_balance_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(12, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ColorBalanceV1, &contract());
check_undo(&ColorBalanceV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ColorLookupNode"@1 => @2)]
pub fn color_lookup_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ColorLookupV1, &contract());
check_undo(&ColorLookupV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => @2)]
pub fn color_overlay_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ColorOverlayV1, &contract());
check_undo(&ColorOverlayV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::CurvesNode"@1 => @2)]
pub fn curves_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&CurvesV1, &contract());
check_undo(&CurvesV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::dehaze::DehazeNode"@1 => @2)]
pub fn dehaze_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&DehazeV1, &contract());
check_undo(&DehazeV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::DesaturateNode"@1 => @2)]
pub fn desaturate_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&DesaturateV1, &contract());
check_undo(&DesaturateV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ExposureNode"@1 => @2)]
pub fn exposure_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ExposureV1, &contract());
check_undo(&ExposureV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => @2)]
pub fn extend_image_to_bounds_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ExtendImageToBoundsV1, &contract());
check_undo(&ExtendImageToBoundsV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::GammaCorrectionNode"@1 => @2)]
pub fn gamma_correction_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&GammaCorrectionV1, &contract());
check_undo(&GammaCorrectionV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::GradientMapNode"@1 => @2)]
pub fn gradient_map_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&GradientMapV1, &contract());
check_undo(&GradientMapV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::HueSaturationNode"@1 => @2)]
pub fn hue_saturation_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(51, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&HueSaturationV1, &contract());
check_undo(&HueSaturationV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::image_color_palette::ImageColorPaletteNode"@1 => @2)]
pub fn image_color_palette_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ImageColorPaletteV1, &contract());
check_undo(&ImageColorPaletteV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::InvertNode"@1 => @2)]
pub fn invert_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InvertV1, &contract());
check_undo(&InvertV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::LevelsNode"@1 => @2)]
pub fn levels_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(27, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&LevelsV1, &contract());
check_undo(&LevelsV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
pub fn make_opaque_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MakeOpaqueV1, &contract());
check_undo(&MakeOpaqueV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::std_nodes::MaskNode"@1 => @2)]
pub fn mask_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MaskV1, &contract());
check_undo(&MaskV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::filter::MedianFilterNode"@1 => @2)]
pub fn median_filter_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MedianFilterV1, &contract());
check_undo(&MedianFilterV1, &contract());
}
}
@@ -1,4 +1,31 @@
//! Migrations of the nodes in `raster_nodes`.
mod black_and_white_v1;
mod blur_v1;
mod brightness_contrast_v1;
mod channel_mixer_v1;
mod channels_to_image_v1;
mod color_balance_v1;
mod color_lookup_v1;
mod color_overlay_v1;
mod curves_v1;
mod dehaze_v1;
mod desaturate_v1;
mod exposure_v1;
mod extend_image_to_bounds_v1;
mod gamma_correction_v1;
mod gradient_map_v1;
mod hue_saturation_v1;
mod image_color_palette_v1;
mod invert_v1;
mod levels_v1;
mod make_opaque_v1;
mod mask_v1;
mod median_filter_v1;
mod mix_colors_from_mix_node;
mod photo_filter_v1;
mod posterize_v1;
mod renames;
mod selective_color_v1;
mod threshold_v1;
mod vibrance_v1;
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::PhotoFilterNode"@1 => @2)]
pub fn photo_filter_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PhotoFilterV1, &contract());
check_undo(&PhotoFilterV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::PosterizeNode"@1 => @2)]
pub fn posterize_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PosterizeV1, &contract());
check_undo(&PosterizeV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::SelectiveColorNode"@1 => @2)]
pub fn selective_color_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(39, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&SelectiveColorV1, &contract());
check_undo(&SelectiveColorV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ThresholdNode"@1 => @2)]
pub fn threshold_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ThresholdV1, &contract());
check_undo(&ThresholdV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::VibranceNode"@1 => @2)]
pub fn vibrance_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&VibranceV1, &contract());
check_undo(&VibranceV1, &contract());
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ publish.workspace = true
[dependencies]
core-types = { workspace = true }
document-graph-storage = { workspace = true }
matchbox_socket = "0.15.0"
matchbox_socket = "0.14.0"
futures = { workspace = true }
log = { workspace = true }
serde = { workspace = true }
+2 -2
View File
@@ -14,7 +14,7 @@ const FRAME_FINAL: u8 = 1;
const FRAME_MORE: u8 = 0;
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so no length prefix is needed.
fn frames(bytes: &[u8]) -> Vec<Packet> {
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
// Chunking an empty packet would yield no frame at all.
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
@@ -258,7 +258,7 @@ mod tests {
assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet");
lock(&inbox).packets.push_back((peer(1), Packet::from_static(&[FRAME_FINAL, 7])));
lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7])));
assert_eq!(incoming.wait().now_or_never(), Some(true), "an arrival resolves the wait");
assert_eq!(incoming.wait().now_or_never(), Some(true), "and keeps it resolved until the inbox is drained");
@@ -99,7 +99,7 @@ impl MessageHandler<FutureMessage, ()> for FutureMessageHandler {
}));
}
FutureMessage::Drain => {
while let Ok(message) = self.results_receiver.try_recv() {
while let Ok(Some(message)) = self.results_receiver.try_next() {
responses.push_back(message);
}
}
@@ -18,7 +18,7 @@ use graphene_std::raster::{
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::raster_types::{CPU, GPU, Raster, Storage};
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -944,9 +944,15 @@ impl TableItemLayout for Raster<GPU> {
"Raster"
}
fn identifier(&self) -> String {
format!("Raster ({} x {})", self.data().width(), self.data().height())
let size = self.size();
format!("Raster ({} x {})", size.x, size.y)
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
if self.is_empty() {
let widgets = vec![TextLabel::new("Image has no area").widget_instance()];
return vec![LayoutGroup::row(widgets)];
}
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
vec![LayoutGroup::row(widgets)]
}
@@ -650,7 +650,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
insert_node_input_index,
} => {
network_interface.insert_node_between(&node_id, &input_connector, insert_node_input_index, selection_network_path);
network_interface.connect_read_node_to_map(&node_id, selection_network_path);
}
NodeGraphMessage::InsertDotOnWire { node_id, input_connector, x, y } => {
network_interface.insert_dot_on_wire(node_id, &input_connector, IVec2::new(x, y), selection_network_path);
@@ -4,7 +4,6 @@ use super::{
};
use crate::consts::{GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::test_utils::test_prelude::*;
@@ -3548,106 +3547,3 @@ async fn cannot_preview_node_without_outputs() {
network_interface.toggle_preview(custom_node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
}
fn map_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::graphic::map::IDENTIFIER)
}
async fn layer_with_chain_and_unwired_map(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId) {
let (layer, near, ..) = layer_with_chain(editor).await;
editor
.active_document_mut()
.network_interface
.create_wire(&OutputConnector::primary_output(layer), &InputConnector::Export(0), &[]);
editor.handle_message(NodeGraphMessage::RunDocumentGraph).await;
let map = editor.create_node_by_name_at(map_definition(), 0, 30).await;
(layer, near, map)
}
async fn drop_map_onto_chain(editor: &mut EditorTestUtils, layer: NodeId, map: NodeId) {
editor
.handle_message(NodeGraphMessage::InsertNodeBetween {
node_id: map,
input_connector: InputConnector::layer_secondary_input(layer),
insert_node_input_index: 0,
})
.await;
}
#[tokio::test]
async fn dropping_a_map_node_onto_a_wire_feeds_it_the_matching_read_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, near, map) = layer_with_chain_and_unwired_map(&mut editor).await;
drop_map_onto_chain(&mut editor, layer, map).await;
let network_interface = &editor.active_document().network_interface;
let Some(NodeInput::Node { node_id: read_node, .. }) = network_interface.input_from_connector(&InputConnector::node_at_index(map, 1), &[]).cloned() else {
panic!("The Map node's mapped input should be fed by a new node");
};
assert_eq!(
network_interface.reference(&read_node, &[]),
Some(DefinitionIdentifier::ProtoNode(graphene_std::context::read_vector::IDENTIFIER))
);
let map_position = network_interface.position(&map, &[]).unwrap();
let near_position = network_interface.position(&near, &[]).unwrap();
let near_bottom = near_position.y + network_interface.node_height(&near, &[]) as i32;
let read_node_position = network_interface.position(&read_node, &[]).unwrap();
assert_eq!(read_node_position.x, map_position.x - crate::consts::NODE_CHAIN_WIDTH);
assert!(
read_node_position.y > near_bottom,
"The Read node should sit below the Map node's content source rather than overlap it"
);
assert_invariants(&editor, "after dropping a Map node onto a wire");
}
#[test]
fn map_content_types_resolve_to_the_read_node_of_their_element() {
use super::layout::read_node_for_content;
use super::resolved_types::TypeSource;
use graph_craft::{item, list};
use graphene_std::context::{read_graphic, read_number, read_vector};
use graphene_std::list::Bundle;
use graphene_std::text_nodes::read_string;
use graphene_std::{Graphic, Vector};
assert_eq!(read_node_for_content(&TypeSource::Compiled(list!(Vector))), Some(read_vector::IDENTIFIER));
assert_eq!(read_node_for_content(&TypeSource::Compiled(item!(Graphic))), Some(read_graphic::IDENTIFIER));
assert_eq!(read_node_for_content(&TypeSource::Compiled(list!(f64))), Some(read_number::IDENTIFIER));
assert_eq!(read_node_for_content(&TypeSource::TaggedValue(list!(String))), Some(read_string::IDENTIFIER));
assert_eq!(read_node_for_content(&TypeSource::Compiled(item!(Bundle<Vector>))), Some(read_vector::IDENTIFIER));
assert_eq!(
read_node_for_content(&TypeSource::Compiled(list!(i64))),
None,
"Read Number yields f64, which a Map over integers can't take"
);
assert_eq!(read_node_for_content(&TypeSource::Compiled(list!(bool))), None);
assert_eq!(read_node_for_content(&TypeSource::Unknown), None);
}
#[tokio::test]
async fn dropping_a_map_node_onto_a_wire_keeps_its_wired_mapped_input() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, _, map) = layer_with_chain_and_unwired_map(&mut editor).await;
let mapped_source = NodeId::new();
let read_vector = resolve_proto_node_type(graphene_std::context::read_vector::IDENTIFIER).unwrap().default_node_template();
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.insert_node(mapped_source, read_vector, &[]);
network_interface.create_wire(&OutputConnector::primary_output(mapped_source), &InputConnector::node_at_index(map, 1), &[]);
let node_count = editor.active_document().network_interface.document_network().nodes.len();
drop_map_onto_chain(&mut editor, layer, map).await;
let network_interface = &editor.active_document().network_interface;
assert_eq!(
network_interface.input_from_connector(&InputConnector::node_at_index(map, 1), &[]),
Some(&NodeInput::node(mapped_source, 0))
);
assert_eq!(network_interface.document_network().nodes.len(), node_count);
}
@@ -1,9 +1,4 @@
use super::resolved_types::TypeSource;
use super::*;
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::style::Gradient;
use graphene_std::{Color, Graphic};
impl NodeNetworkInterface {
/// The top left corner of a node in node graph grid coordinates.
@@ -1160,41 +1155,6 @@ impl NodeNetworkInterface {
self.create_wire(&upstream_output, &InputConnector::node_at_index(*node_id, insert_node_input_index), network_path);
}
/// Feeds an unconnected Map node's mapped input with the Read node matching the element type of its content.
pub fn connect_read_node_to_map(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
if self.reference(node_id, network_path) != Some(DefinitionIdentifier::ProtoNode(graphene_std::graphic::map::IDENTIFIER)) {
return;
}
let mapped_input = InputConnector::node_at_index(*node_id, 1);
if !matches!(self.input_from_connector(&mapped_input, network_path), Some(NodeInput::Value { .. })) {
return;
}
let Some(content_source) = self.upstream_output_connector(&InputConnector::primary_input(*node_id), network_path) else {
return;
};
let Some(mut read_node_template) = read_node_for_content(&self.output_type(&content_source, network_path))
.and_then(resolve_proto_node_type)
.map(|definition| definition.default_node_template())
else {
return;
};
let Some(map_position) = self.position(node_id, network_path) else {
return;
};
let below_content_source = content_source
.node_id()
.and_then(|source| Some(self.position(&source, network_path)?.y + self.node_height(&source, network_path) as i32 + 1));
let read_node_position = IVec2::new(map_position.x - NODE_CHAIN_WIDTH, below_content_source.unwrap_or(map_position.y + 2));
read_node_template.node_type_metadata = NodeTypePersistentMetadata::node(read_node_position);
let read_node_id = NodeId::new();
self.insert_node(read_node_id, read_node_template, network_path);
self.create_wire(&OutputConnector::primary_output(read_node_id), &mapped_input, network_path);
}
/// Inserts the freshly-created `node_id` onto the wire feeding `input_connector`: the previous upstream becomes the
/// new node's primary (index 0) input, and the new node feeds `input_connector`.
///
@@ -1615,30 +1575,3 @@ impl NodeNetworkInterface {
self.layer_chain(layer, network_path) == intended_chain
}
}
/// The Read node yielding each element of a Map node's content, unbundling a whole-list `Item<Bundle<T>>` wire to its `T`.
pub(super) fn read_node_for_content(content_type: &TypeSource) -> Option<ProtoNodeIdentifier> {
use graphene_std::context::{read_color, read_gradient, read_graphic, read_number, read_raster, read_vector};
use graphene_std::text_nodes::read_string;
let bundle_element = content_type.compiled_nested_type().and_then(Type::bundle_element_name);
let element_type = content_type.compiled_element_type()?;
[
(concrete!(Vector), read_vector::IDENTIFIER),
(concrete!(Graphic), read_graphic::IDENTIFIER),
(concrete!(Raster<CPU>), read_raster::IDENTIFIER),
(concrete!(Color), read_color::IDENTIFIER),
(concrete!(Gradient), read_gradient::IDENTIFIER),
(concrete!(f64), read_number::IDENTIFIER),
(concrete!(String), read_string::IDENTIFIER),
]
.into_iter()
.find_map(|(candidate, read_node)| {
let matches = match (bundle_element, &candidate) {
(Some(bundle_element), Type::Concrete(descriptor)) => descriptor.name == bundle_element,
_ => candidate == *element_type,
};
matches.then_some(read_node)
})
}
@@ -3519,6 +3519,49 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
let raster_kernel_pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
let raster_kernel_nodes = {
use graphene_std::raster_nodes::adjustments::*;
[
desaturate::IDENTIFIER,
gamma_correction::IDENTIFIER,
make_opaque::IDENTIFIER,
brightness_contrast::IDENTIFIER,
levels::IDENTIFIER,
curves::IDENTIFIER,
black_and_white::IDENTIFIER,
hue_saturation::IDENTIFIER,
invert::IDENTIFIER,
threshold::IDENTIFIER,
gradient_map::IDENTIFIER,
vibrance::IDENTIFIER,
channel_mixer::IDENTIFIER,
selective_color::IDENTIFIER,
posterize::IDENTIFIER,
exposure::IDENTIFIER,
color_balance::IDENTIFIER,
photo_filter::IDENTIFIER,
color_lookup::IDENTIFIER,
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
graphene_std::raster_nodes::filter::blur::IDENTIFIER,
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
]
};
if raster_kernel_nodes.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && !node.inputs.contains(&raster_kernel_pipeline) {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let value_inputs = node_template.inputs.iter().position(|input| *input == raster_kernel_pipeline)?;
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().take(value_inputs).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// A value input stored as a List-form TypeDefault adopts the definition's current default when the connector's declared default has since changed (e.g. the connector was ranked down to Item).
// The red-slash no-paint choice shares that stored form but is a deliberate value, not a stale disconnect default, so it is exempt.
if let Some(definition) = resolve_document_node_type(&reference) {
@@ -4478,7 +4521,8 @@ mod tests {
let desaturate_node = node(1);
assert_eq!(desaturate_node.implementation, DocumentNodeImplementation::ProtoNode(desaturate::IDENTIFIER));
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method]);
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method, pipeline]);
let brightness_contrast = node(2);
assert_eq!(
@@ -1478,9 +1478,7 @@ impl PenToolData {
/// Perform extension of an existing path
fn extend_existing_path(&mut self, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, point: PointId, position: DVec2) {
let vector: Option<VectorGeometry> = document.network_interface.compute_modified_vector(layer);
let (handle_start, in_segment) = if let Some(vector) = &vector
&& vector.connected_count(point) <= 1
{
let (handle_start, in_segment) = if let Some(vector) = &vector {
vector
.segment_iter()
.find_map(|(segment_id, bezier, start, end)| {
@@ -2498,30 +2496,13 @@ impl Fsm for PenToolFsmState {
#[cfg(test)]
mod test_pen_tool {
use super::is_almost_colinear;
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::tool::common_functionality::snap_session::WAKE_DWELL_ON_APPROACH;
use crate::test_utils::EditorTestUtils;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, DVec2};
use graphene_std::vector::misc::{BooleanOperation, HandleId, ManipulatorPointId};
use graphene_std::vector::{PointId, SegmentId, VectorGeometry};
fn assert_expected_anchors(editor: &EditorTestUtils, expected_anchors: &[DVec2]) {
let (layer, vector) = drawn_path(editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let mut viewport_points: Vec<DVec2> = vector.anchor_positions().into_iter().map(|pos| layer_to_viewport.transform_point2(pos)).collect();
for (expected_index, &expected_position) in expected_anchors.iter().enumerate() {
let Some(viewport_index) = viewport_points.iter().position(|viewport| viewport.distance_squared(expected_position) < 1e-10) else {
panic!("The expected anchor index {expected_index} and position {expected_position} was not found in the actual anchors {viewport_points:?}");
};
viewport_points.remove(viewport_index);
}
assert!(viewport_points.is_empty(), "Viewport point(s) were not matched: {viewport_points:?}");
}
use glam::DAffine2;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId};
use graphene_std::vector::{SegmentId, VectorGeometry};
/// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away.
fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, VectorGeometry)> {
@@ -2584,267 +2565,6 @@ mod test_pen_tool {
const C: DVec2 = DVec2::new(200., 200.);
const D: DVec2 = DVec2::new(100., 200.);
async fn create_a_rectangle() -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.select_primary_color(Color::RED).await;
// Draw a rectangle not at the origin (so will end up with a non-identity transform)
editor.draw_rect(A.x, A.y, C.x, C.y).await;
editor
}
/// Using the path tool to merge layers (by setting the endpoint to an anchor of another layer) should produce only expected anchor positions.
#[tokio::test]
async fn merging_layers_simple() {
let mut editor = create_a_rectangle().await;
// Start the pen somewhere random
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
// Connect to the top right of the rectangle
click_pen(&mut editor, B).await;
// Validate that these anchors are the only ones that exist
let expected_anchors = [A, B, C, D, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_two_pen_paths() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Create First Pen path
click_pen(&mut editor, A).await;
click_pen(&mut editor, C).await;
// Abort the first pen process
editor.handle_message(ToolMessage::Pen(PenToolMessage::Abort)).await;
// Create a second pen stroke
click_pen(&mut editor, B).await;
click_pen(&mut editor, C).await;
// Validate that these anchors are the only ones that exist
let expected_anchors = [A, B, C];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_group_with_offset() {
let mut editor = create_a_rectangle().await;
// Group rectangle
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group = editor.active_document().metadata().all_layers().next().unwrap();
let offset = DVec2::new(50., 60.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: group,
transform: DAffine2::from_translation(offset),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Start the pen somewhere random
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
// Connect to the top right of the rectangle (offset by the group transform)
click_pen(&mut editor, B + offset).await;
let expected_anchors = [A + offset, B + offset, C + offset, D + offset, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_different_groups_with_offsets() {
let mut editor = create_a_rectangle().await;
// Group rectangle into Group 1
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group1 = editor.active_document().metadata().all_layers().next().unwrap();
let offset1 = DVec2::new(50., 60.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: group1,
transform: DAffine2::from_translation(offset1),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Nest Group 1 inside Group 2 with a different offset
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group2 = editor.active_document().metadata().all_layers().next().unwrap();
let offset2 = DVec2::new(30., -20.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: group2,
transform: DAffine2::from_translation(offset2),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
let total_offset = offset1 + offset2;
// Start the pen somewhere random
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
// Connect to the top right of the rectangle (offset by the nested group transforms)
click_pen(&mut editor, B + total_offset).await;
let expected_anchors = [A + total_offset, B + total_offset, C + total_offset, D + total_offset, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_artboard_with_offset() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let offset = DVec2::new(60., 70.);
editor.drag_tool(ToolType::Artboard, 0., 0., 500., 500., ModifierKeys::empty()).await;
let artboard = editor.active_document().metadata().all_layers().next().unwrap();
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard,
transform: DAffine2::from_translation(offset),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
editor.select_primary_color(Color::RED).await;
editor.draw_rect(A.x + offset.x, A.y + offset.y, C.x + offset.x, C.y + offset.y).await;
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
click_pen(&mut editor, B + offset).await;
let expected_anchors = [A + offset, B + offset, C + offset, D + offset, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_artboards_with_different_offsets() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Create first artboard with offset
editor.drag_tool(ToolType::Artboard, 0., 0., 400., 400., ModifierKeys::empty()).await;
let artboard1 = editor.active_document().metadata().all_layers().next().unwrap();
let offset1 = DVec2::new(50., 60.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard1,
transform: DAffine2::from_translation(offset1),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Draw rectangle in first artboard
editor.select_primary_color(Color::RED).await;
editor.draw_rect(A.x + offset1.x, A.y + offset1.y, C.x + offset1.x, C.y + offset1.y).await;
// Create second artboard with different offset
let offset2 = DVec2::new(-30., 40.);
let artboard2_origin = DVec2::new(600., 600.);
editor
.drag_tool(
ToolType::Artboard,
artboard2_origin.x,
artboard2_origin.y,
artboard2_origin.x + 400.,
artboard2_origin.y + 400.,
ModifierKeys::empty(),
)
.await;
let artboard2 = editor.active_document().metadata().all_layers().next().unwrap();
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard2,
transform: DAffine2::from_translation(offset2),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Start pen in second artboard
let pen_start = artboard2_origin + offset2 + DVec2::new(50., 50.);
click_pen(&mut editor, pen_start).await;
// Connect to anchor B of the rectangle in the first artboard
click_pen(&mut editor, B + offset1).await;
let expected_anchors = [A + offset1, B + offset1, C + offset1, D + offset1, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
async fn test_boolean_operation(operation: BooleanOperation) {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.select_primary_color(Color::RED).await;
editor.draw_rect(A.x, A.y, C.x, C.y).await;
editor.draw_rect(150., 150., 250., 250.).await;
// Select both rectangles and create boolean operation layer
let layers: Vec<_> = editor.active_document().metadata().all_layers().collect();
editor
.handle_message(NodeGraphMessage::SelectedNodesSet {
nodes: layers.iter().map(|l| l.to_node()).collect(),
})
.await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::BooleanOperation(operation),
})
.await;
let bool_layer = editor.active_document().metadata().all_layers().next().unwrap();
let bool_vector = editor.active_document().network_interface.compute_modified_vector(bool_layer).expect("Boolean layer vector");
let bool_to_viewport = editor.active_document().metadata().transform_to_viewport(bool_layer);
let mut expected_anchors: Vec<DVec2> = bool_vector.anchor_positions().into_iter().map(|pos| bool_to_viewport.transform_point2(pos)).collect();
// Connect pen to one of the anchors of the boolean operation
let connect_anchor = expected_anchors[0];
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
click_pen(&mut editor, connect_anchor).await;
expected_anchors.push(pen_start);
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_with_different_boolean_outputs() {
for operation in [BooleanOperation::Union, BooleanOperation::SubtractFront, BooleanOperation::Intersect, BooleanOperation::Difference] {
test_boolean_operation(operation).await;
}
}
#[tokio::test]
async fn enter_or_esc_after_a_single_click_leaves_no_layer() {
for key in [Key::Enter, Key::Escape] {
@@ -3425,37 +3145,6 @@ mod test_pen_tool {
assert!(leaving.distance(handle) < 1e-6, "the joining segment's handle is at {leaving}");
}
/// Finds the point ID whose viewport position is within tolerance of `target`.
fn get_anchor_near(vector: &VectorGeometry, layer_to_viewport: DAffine2, target: DVec2) -> PointId {
vector
.anchors()
.find(|&(_id, pos)| layer_to_viewport.transform_point2(pos).distance(target) < 1e-6)
.map(|(id, _pos)| id)
.unwrap_or_else(|| panic!("No anchor found near {target}"))
}
/// Finds the segment that connects two given point IDs (in either direction).
fn get_segment_between(vector: &VectorGeometry, point_a: PointId, point_b: PointId) -> SegmentId {
vector
.segment_ids()
.into_iter()
.find(|&segment| {
let start = vector.segment_start_from_id(segment);
let end = vector.segment_end_from_id(segment);
(start == Some(point_a) && end == Some(point_b)) || (start == Some(point_b) && end == Some(point_a))
})
.unwrap_or_else(|| panic!("No segment found between the given anchors"))
}
/// Finds the handle position on `segment` that corresponds to `point`.
fn get_handle_at(vector: &VectorGeometry, segment: SegmentId, point: PointId) -> Option<DVec2> {
if vector.segment_start_from_id(segment) == Some(point) {
vector.position_of(ManipulatorPointId::PrimaryHandle(segment))
} else {
vector.position_of(ManipulatorPointId::EndHandle(segment))
}
}
#[tokio::test]
async fn an_anchor_moved_with_space_lands_on_a_corner_and_carries_its_handles_along() {
let mut editor = EditorTestUtils::create();
@@ -3743,83 +3432,4 @@ mod test_pen_tool {
let stroke = position(graphene_std::vector_nodes::stroke::IDENTIFIER).expect("The path should have a Stroke node");
assert!(transform > fill && transform > stroke, "the Transform should be upstream of the Fill and Stroke in {chain:?}");
}
#[tokio::test]
async fn extending_from_anchor_with_multiple_segments_does_not_create_colinear_handle() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// 1. Draw a path through A, B, and C with curved handles dragged out at B
click_pen(&mut editor, A).await;
let handle = B + DVec2::new(50., 0.);
editor.drag_path(&[B, handle], ModifierKeys::empty()).await;
click_pen(&mut editor, C).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
assert_path_shape(&editor, 3, 2);
// 2. Extend from anchor B to D by clicking on B and then D (without dragging)
click_pen(&mut editor, B).await;
click_pen(&mut editor, D).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
assert_path_shape(&editor, 4, 3);
// 3. Verify the new branch leaving B does not create a mirrored/colinear handle
let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let b_id = get_anchor_near(&vector, layer_to_viewport, B);
let d_id = get_anchor_near(&vector, layer_to_viewport, D);
let bd_segment = get_segment_between(&vector, b_id, d_id);
if let Some(handle_pos) = get_handle_at(&vector, bd_segment, b_id) {
let handle_pos = layer_to_viewport.transform_point2(handle_pos);
assert!(handle_pos.distance(B) < 1e-4, "Handle at B for the new segment should remain at the anchor");
}
}
#[tokio::test]
async fn extending_from_anchor_with_single_segment_uses_colinear_handle() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// 1. Draw a single segment A→B with a curved handle dragged out at B
click_pen(&mut editor, A).await;
let handle = B + DVec2::new(50., 0.);
editor.drag_path(&[B, handle], ModifierKeys::empty()).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
assert_path_shape(&editor, 2, 1);
// 2. Extend from B to C by clicking B then C (only one segment is attached to B)
click_pen(&mut editor, B).await;
click_pen(&mut editor, C).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
assert_path_shape(&editor, 3, 2);
// 3. Verify the new segment leaving B carries a mirrored/colinear handle
let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let b_id = get_anchor_near(&vector, layer_to_viewport, B);
let c_id = get_anchor_near(&vector, layer_to_viewport, C);
let bc_segment = get_segment_between(&vector, b_id, c_id);
let a_id = get_anchor_near(&vector, layer_to_viewport, A);
let ab_segment = get_segment_between(&vector, a_id, b_id);
let existing_handle_at_b = get_handle_at(&vector, ab_segment, b_id).expect("Segment AB should have a handle at B");
let existing_handle_pos = layer_to_viewport.transform_point2(existing_handle_at_b);
let new_handle_at_b = get_handle_at(&vector, bc_segment, b_id).expect("The new segment should have a handle at B");
let new_handle_pos = layer_to_viewport.transform_point2(new_handle_at_b);
// When only one segment is connected, the handle should not collapse to the
// anchor, and must be colinear with the existing handle at B.
assert!(
new_handle_pos.distance(B) > 1e-4,
"Handle at B should not collapse to the anchor when only one segment is connected (got {new_handle_pos})"
);
assert!(
is_almost_colinear(B, existing_handle_pos, new_handle_pos),
"New handle should be colinear with the existing handle at B (existing: {existing_handle_pos}, new: {new_handle_pos})"
);
}
}
+68
View File
@@ -1236,3 +1236,71 @@ mod test {
}
}
}
#[cfg(test)]
mod raster_path_tests {
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::test_utils::test_prelude::*;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
use graphene_std::list::Item;
use graphene_std::raster_nodes::adjustments::invert;
use graphene_std::raster_nodes::dehaze::dehaze;
use graphene_std::raster_nodes::filter::median_filter;
use graphene_std::raster_nodes::std_nodes::eager;
use graphene_std::raster_types::{CPU, Raster};
/// A document whose image feeds `nodes` in turn, ending in the export.
async fn image_through(editor: &mut EditorTestUtils, color: Color, nodes: &[ProtoNodeIdentifier]) {
editor.new_document().await;
editor.create_raster_image(Image::new(4, 4, color), None).await;
let image = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
.map(|(id, _)| *id)
.expect("the pasted image should be an Image node");
let mut previous = OutputConnector::node(image, 0);
for (index, identifier) in nodes.iter().enumerate() {
let id: NodeId = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(identifier.clone()), (index as i32 + 1) * 10, 0).await;
let input = InputConnector::node_at_index(id, 0);
editor.active_document_mut().network_interface.create_wire(&previous, &input, &[]);
previous = OutputConnector::node(id, 0);
}
editor.active_document_mut().network_interface.create_wire(&previous, &InputConnector::Export(0), &[]);
}
#[tokio::test]
async fn an_image_reaches_a_filter_as_a_cpu_raster() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::WHITE, &[median_filter::IDENTIFIER]).await;
let instrumented = editor.eval_graph_until_finished().await.expect("the image should render through Median");
let _: Item<Raster<CPU>> = instrumented
.grab_all_input::<median_filter::ImageFrameInput, Item<Raster<CPU>>>(&editor.runtime)
.next()
.expect("the image should arrive at Median as a CPU raster");
}
#[tokio::test]
async fn an_image_feeding_dehaze_renders() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::from_rgbaf32_unchecked(0.5, 0.6, 0.7, 1.), &[dehaze::IDENTIFIER]).await;
// A compile error or a failed render fails this
editor.eval_graph_uninstrumented().await.expect("the image should render through Dehaze");
}
#[tokio::test]
async fn an_image_uploaded_by_eager_renders_through_a_kernel() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::WHITE, &[eager::IDENTIFIER, invert::IDENTIFIER]).await;
// A compile error or a failed render fails this
editor.eval_graph_uninstrumented().await.expect("the image should render through Eager and Invert");
}
}
+27 -9
View File
@@ -66,22 +66,30 @@ impl EditorTestUtils {
}
/// Submit an evaluation to the executor, run the runtime, and process the results.
/// With `instrument`, the graph is compiled with the monitors of [`Instrumented`], which can't wrap the runtime handle that asynchronous nodes take.
///
/// If a deferred message triggers a second graph run, this will not occur. See [`Self::eval_graph_until_finished`] for this behaviour.
async fn eval_graph_once(&mut self) -> Result<Instrumented, TestGraphError> {
async fn eval_graph_once(&mut self, instrument: bool) -> Result<Option<Instrumented>, TestGraphError> {
let portfolio = &mut self.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
let instrumented = match executor.update_node_graph_instrumented(document) {
Ok(instrumented) => instrumented,
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
let instrumented = if instrument {
let instrumented = match executor.update_node_graph_instrumented(document) {
Ok(instrumented) => instrumented,
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
};
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
}
Some(instrumented)
} else {
if let Err(e) = executor.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, DVec2::ZERO) {
return Err(TestGraphError::Other(format!("submit_node_graph_evaluation failed\n\n{e}")));
}
None
};
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
}
self.runtime.update();
self.runtime.run().await;
@@ -105,10 +113,20 @@ impl EditorTestUtils {
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
let instrumented = self.eval_graph_repeatedly(true).await?;
Ok(instrumented.expect("an instrumented evaluation returns its monitors"))
}
/// Like [`Self::eval_graph_until_finished`], but compiles the graph without monitors so that it can contain asynchronous nodes.
pub async fn eval_graph_uninstrumented(&mut self) -> Result<(), TestGraphError> {
self.eval_graph_repeatedly(false).await.map(|_| ())
}
async fn eval_graph_repeatedly(&mut self, instrument: bool) -> Result<Option<Instrumented>, TestGraphError> {
const MAX_ITERATIONS: usize = 16;
for _iteration in 0..MAX_ITERATIONS {
let execution_id = self.portfolio_message_handler().executor.current_execution_id();
let result = self.eval_graph_once().await?;
let result = self.eval_graph_once(instrument).await?;
// If there have been no other executions queued (other than the one we just queued ourselves above) then finish
if execution_id + 1 >= self.portfolio_message_handler().executor.current_execution_id() {
return Ok(result);
+2
View File
@@ -377,6 +377,7 @@ import NodeTransform from "/../branding/assets/16x16-nodes/node-transform.svg";
import NodeTriangulate from "/../branding/assets/16x16-nodes/node-triangulate.svg";
import NodeUngroup from "/../branding/assets/16x16-nodes/node-ungroup.svg";
import NodeUnweld from "/../branding/assets/16x16-nodes/node-unweld.svg";
import NodeUploadTexture from "/../branding/assets/16x16-nodes/node-upload-texture.svg";
import NodeVaryFillColors from "/../branding/assets/16x16-nodes/node-vary-fill-colors.svg";
import NodeVaryStrokeColors from "/../branding/assets/16x16-nodes/node-vary-stroke-colors.svg";
import NodeVec2ToNumbers from "/../branding/assets/16x16-nodes/node-vec2-to-numbers.svg";
@@ -659,6 +660,7 @@ export const ICON_16X16_NODES = {
NodeTriangulate: { svg: NodeTriangulate, size: 16 },
NodeUngroup: { svg: NodeUngroup, size: 16 },
NodeUnweld: { svg: NodeUnweld, size: 16 },
NodeUploadTexture: { svg: NodeUploadTexture, size: 16 },
NodeVaryFillColors: { svg: NodeVaryFillColors, size: 16 },
NodeVaryRotations: { svg: NodeVaryRotations, size: 16 },
NodeVaryScales: { svg: NodeVaryScales, size: 16 },
+1 -1
View File
@@ -30,7 +30,7 @@ glam = ["dep:glam"]
dyn-any-derive = { path = "derive", optional = true }
# Optional dependencies
glam = { version = "0.34", optional = true, default-features = false, features = ["all-types"] }
glam = { version = "0.33", optional = true, default-features = false, features = ["all-types"] }
reqwest = { version = "0.13", optional = true, default-features = false }
[package.metadata.docs.rs]
-1
View File
@@ -18,7 +18,6 @@ workspace = true
thiserror = "2.0"
num-complex = "0.4"
unicode-ident = "1.0"
# This is intentionally not upgraded since the cache API was removed for soundness https://codeberg.org/zesterer/chumsky/pulls/980
chumsky = { version = "0.10", default-features = false, features = ["std", "unstable"] }
[dev-dependencies]
@@ -149,7 +149,7 @@ struct MmappedBytes(MemoryMappedFile);
impl AsRef<[u8]> for MmappedBytes {
fn as_ref(&self) -> &[u8] {
let len = self.0.len();
match self.0.as_slice_bytes(0, len) {
match self.0.as_slice(0, len) {
Ok(slice) => slice,
Err(error) => {
log::error!("Failed to obtain mmap slice: {error}");
+3 -1
View File
@@ -13,7 +13,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2};
use graphene_animation::AnimationCurve;
use graphene_application_io::resource::ResourceHash;
use graphene_application_io::resource::ResourceId;
use graphic_types::raster_types::{CPU, Image, Raster};
use graphic_types::raster_types::{CPU, GPU, Image, Raster};
use graphic_types::vector_types::vector::misc::BoxCorners;
use graphic_types::vector_types::vector::style::DashPattern;
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
@@ -36,6 +36,7 @@ macro_rules! for_each_item_type_default {
$action!(Vector);
$action!(f64);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Graphic);
$action!(Color);
$action!(Gradient);
@@ -52,6 +53,7 @@ macro_rules! for_each_list_type_default {
$action!(Graphic);
$action!(Artboard);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Vector);
$action!(String);
$action!(Color);
+1 -1
View File
@@ -43,7 +43,7 @@ winit = { workspace = true }
clap = { workspace = true, features = ["cargo", "derive"] }
image = { workspace = true }
serde_json = { workspace = true }
getrandom = "0.4"
getrandom = "0.3"
wgpu-executor = { workspace = true, optional = true }
[package.metadata.cargo-shear]
@@ -51,6 +51,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<CPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
@@ -90,6 +91,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::SourceId>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Option<wgpu_executor::WgpuExecutor>>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>, Context => Item<graphene_std::ContextModification>]),
// ==========
// MEMO NODES
@@ -142,6 +144,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::brush::Stroke>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<RenderIntermediate>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuExecutor>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Option<wgpu_executor::WgpuExecutor>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
];
// The per-connector input adapter, registered per element type: an `Item` or `List` wire passes through unchanged.
+23 -7
View File
@@ -1,6 +1,6 @@
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeInput, NodeNetwork};
use graph_craft::generic;
use graph_craft::{concrete, item};
use graphene_std::Context;
@@ -27,7 +27,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
let render_node = DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::Network(NodeNetwork {
exports: vec![NodeInput::node(NodeId(5), 0)],
exports: vec![NodeInput::node(NodeId(6), 0)],
nodes: [
DocumentNode {
call_argument: concrete!(Context),
@@ -42,7 +42,23 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
inputs: vec![
NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER),
NodeInput::node(NodeId(0), 0),
NodeInput::scope("runtime"),
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::download_gpu_rasters::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
..Default::default()
}),
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -53,7 +69,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -64,7 +80,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(3), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -77,7 +93,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
call_argument: concrete!(Context),
inputs: vec![
NodeInput::scope(graphene_std::render_background::composite_background_pipeline::IDENTIFIER),
NodeInput::node(NodeId(3), 0),
NodeInput::node(NodeId(4), 0),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
@@ -89,7 +105,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::node(NodeId(4), 0)],
inputs: vec![NodeInput::node(NodeId(5), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
// INDEX is never read; it forces a nullification and cache pair onto the `data` parameter's wire so the render cache keys on a stable context
@@ -694,12 +694,12 @@ impl Color {
Color::blend_hardlight(c_s, c_b)
}
/// Per-channel "Vivid Light" blend.
/// Per-channel "Vivid Light" blend: "Color Burn" of the backdrop by the doubled source in its darker half, and "Color Dodge" in its lighter half.
pub fn blend_vivid_light(c_b: f32, c_s: f32) -> f32 {
if c_s <= 0.5 {
Color::blend_color_burn(2. * c_s, c_b)
Color::blend_color_burn(c_b, 2. * c_s)
} else {
Color::blend_color_dodge(2. * c_s - 1., c_b)
Color::blend_color_dodge(c_b, 2. * c_s - 1.)
}
}
@@ -1016,6 +1016,18 @@ impl Color {
mod tests {
use super::*;
#[test]
fn vivid_light_burns_and_dodges_the_backdrop_by_the_doubled_source() {
// The darker half is Color Burn of the backdrop by twice the source: 1 - (1 - 0.8) / 0.5
assert!((Color::blend_vivid_light(0.8, 0.25) - 0.6).abs() < 1e-6);
// The lighter half is Color Dodge of the backdrop by twice the source less one: 0.4 / (1 - 0.5)
assert!((Color::blend_vivid_light(0.4, 0.75) - 0.8).abs() < 1e-6);
// A mid-gray source leaves the backdrop unchanged, and the extremes saturate
assert!((Color::blend_vivid_light(0.3, 0.5) - 0.3).abs() < 1e-6);
assert_eq!(Color::blend_vivid_light(0.3, 0.), 0.);
assert_eq!(Color::blend_vivid_light(0.3, 1.), 1.);
}
#[test]
fn oklab_lightness_spans_black_to_white() {
assert!(Color::BLACK.lightness_oklab().abs() < 1e-4);
@@ -1,4 +1,4 @@
use rand::{RngExt, SeedableRng};
use rand::{Rng, SeedableRng};
/// Gives each of `count` items a factor from 0 to 1, either spread evenly in item order or drawn at random from the `seed`.
/// The even spread restarts after every `repeat_every` items, unless it is 0 to span all the items once.
+1 -1
View File
@@ -42,7 +42,7 @@ mod u64_string {
mod uuid_generation {
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::{Rng, SeedableRng};
use rand_chacha::rand_core::{RngCore, SeedableRng};
use std::cell::Cell;
use std::sync::Mutex;
@@ -360,6 +360,16 @@ impl TryFromGraphic for Raster<CPU> {
}
}
impl TryFromGraphic for Raster<GPU> {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
Graphic::RasterGPU(item) => Some(List::new_from_item(item)),
Graphic::RasterGPUList(list) => Some(list),
_ => None,
}
}
}
impl TryFromGraphic for Color {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
@@ -285,6 +285,7 @@ pub use gpu::{Texture, TextureWeakRef};
mod gpu {
use super::*;
use crate::raster_types::__private::Sealed;
use glam::UVec2;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Eq, Hash, DynAny)]
@@ -349,9 +350,9 @@ mod gpu {
}
}
#[derive(Clone, Debug, PartialEq, Hash)]
#[derive(Clone, Debug, Default, PartialEq, Hash)]
pub struct GPU {
pub texture: Texture,
texture: Option<Texture>,
}
impl core_types::CacheHash for GPU {
@@ -365,17 +366,22 @@ mod gpu {
impl Storage for Raster<GPU> {
fn is_empty(&self) -> bool {
self.texture.width() == 0 || self.texture.height() == 0
let size = self.size();
size.x == 0 || size.y == 0
}
}
impl Raster<GPU> {
pub fn new_gpu(texture: impl Into<Texture>) -> Self {
Self::new(GPU { texture: texture.into() })
Self::new(GPU { texture: Some(texture.into()) })
}
pub fn data(&self) -> &wgpu::Texture {
&self.texture
pub fn texture(&self) -> Option<&Texture> {
self.texture.as_ref()
}
pub fn size(&self) -> UVec2 {
self.texture.as_ref().map_or(UVec2::ZERO, |texture| UVec2::new(texture.width(), texture.height()))
}
}
}
@@ -385,7 +391,7 @@ mod gpu {
use super::*;
use crate::raster_types::__private::Sealed;
#[derive(Clone, Debug, PartialEq, Hash, core_types::CacheHash)]
#[derive(Clone, Debug, Default, PartialEq, Hash, core_types::CacheHash)]
pub struct GPU;
impl Sealed for Raster<GPU> {}
+101 -10
View File
@@ -23,7 +23,7 @@ use core_types::{
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2};
use graphene_resource::Resource;
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::raster_types::{CPU, GPU, Raster, Texture};
use graphic_types::vector_types::gradient::{Gradient, GradientForm};
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath};
use graphic_types::vector_types::vector::misc::dvec2_to_point;
@@ -377,6 +377,9 @@ pub struct RenderParams {
pub canvas_image_scale: f64,
/// The nearest ancestor's appearance, cascading to items that lack their own.
pub inherited_appearance: Option<Appearance>,
/// Downloaded images of GPU raster textures, which SVG output embeds in place of the textures it can't reference. GPU rasters without one are not drawn.
#[cache_hash(skip)]
pub gpu_raster_downloads: Arc<HashMap<Texture, Raster<CPU>>>,
}
impl RenderParams {
@@ -775,6 +778,9 @@ pub trait Render: BoundingBox {
false
}
/// Recursively collects the textures of the GPU rasters this content draws, including those painting its appearances, so SVG output can download them first.
fn collect_gpu_textures(&self, _textures: &mut Vec<Texture>) {}
fn new_ids_from_hash(&mut self, _reference: Option<NodeId>) {}
}
@@ -1042,6 +1048,20 @@ fn add_graphic_item_outline_targets(item: ItemRef<'_, Graphic>, outlines: &mut V
outlines.extend(new_outlines);
}
/// Collects the textures of the GPU rasters painting an appearance's coverages.
fn collect_appearance_gpu_textures(appearance: Option<&Appearance>, textures: &mut Vec<Texture>) {
for paint in appearance.into_iter().flat_map(Appearance::covers_with_paints).filter_map(|(_, paint)| paint) {
paint.collect_gpu_textures(textures);
}
}
/// Collects the textures of the GPU rasters painting the appearances of a list's items.
fn collect_list_appearance_gpu_textures<T>(list: &List<T>, textures: &mut Vec<Texture>) {
for appearance in list.iter_attribute_values::<Appearance>(ATTR_APPEARANCE).into_iter().flatten() {
collect_appearance_gpu_textures(Some(appearance), textures);
}
}
impl Render for Graphic {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
match self {
@@ -1049,14 +1069,14 @@ impl Render for Graphic {
Graphic::Graphic(item) => render_graphic_item_svg(ItemRef::Item(item), false, &mut None, render, render_params),
Graphic::Vector(item) => render_vector_item_svg(ItemRef::Item(item), false, &mut None, render, render_params),
Graphic::RasterCPU(item) => render_raster_cpu_item_svg(ItemRef::Item(item), render, render_params),
Graphic::RasterGPU(_) => (),
Graphic::RasterGPU(item) => render_raster_gpu_item_svg(ItemRef::Item(item), render, render_params),
Graphic::Color(item) => render_color_item_svg(ItemRef::Item(item), render, render_params),
Graphic::Gradient(item) => render_gradient_item_svg(ItemRef::Item(item), render, render_params),
Graphic::Text(item) => render_text_item_svg(ItemRef::Item(item), render, render_params),
Graphic::GraphicList(list) => list.render_svg(render, render_params),
Graphic::VectorList(list) => list.render_svg(render, render_params),
Graphic::RasterCPUList(list) => list.render_svg(render, render_params),
Graphic::RasterGPUList(_) => (),
Graphic::RasterGPUList(list) => list.render_svg(render, render_params),
Graphic::ColorList(list) => list.render_svg(render, render_params),
Graphic::GradientList(list) => list.render_svg(render, render_params),
Graphic::TextList(list) => list.render_svg(render, render_params),
@@ -1092,6 +1112,31 @@ impl Render for Graphic {
}
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
match self {
Graphic::Graphic(item) => {
item.element().collect_gpu_textures(textures);
collect_appearance_gpu_textures(item.attribute(ATTR_APPEARANCE), textures);
}
Graphic::Vector(item) => collect_appearance_gpu_textures(item.attribute(ATTR_APPEARANCE), textures),
Graphic::RasterGPU(item) => collect_raster_gpu_texture(item.element(), textures),
Graphic::GraphicList(list) => list.collect_gpu_textures(textures),
Graphic::VectorList(list) => list.collect_gpu_textures(textures),
Graphic::RasterGPUList(list) => list.collect_gpu_textures(textures),
Graphic::None(_)
| Graphic::NoneList(_)
| Graphic::RasterCPU(_)
| Graphic::Color(_)
| Graphic::Gradient(_)
| Graphic::Text(_)
| Graphic::RasterCPUList(_)
| Graphic::ColorList(_)
| Graphic::GradientList(_)
| Graphic::TextList(_)
| Graphic::StrokeList(_) => {}
}
}
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>, inherited_appearance: Option<&Appearance>) {
if let Some(element_id) = element_id {
// The footprint always lands; the transform (and for vectors the source layer) comes from the first item when one exists
@@ -1388,6 +1433,12 @@ impl Render for List<Artboard> {
}
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
for artboard in self.iter_element_values() {
artboard.as_graphic_list().collect_gpu_textures(textures);
}
}
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>, _inherited_appearance: Option<&Appearance>) {
for index in 0..self.len() {
let dimensions: DVec2 = self.attribute_cloned_or_default(ATTR_DIMENSIONS, index);
@@ -1439,6 +1490,13 @@ impl Render for List<Graphic> {
self.iter_element_values().any(|element| element.contains_artboard())
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
for element in self.iter_element_values() {
element.collect_gpu_textures(textures);
}
collect_list_appearance_gpu_textures(self, textures);
}
fn new_ids_from_hash(&mut self, _reference: Option<NodeId>) {
let (elements, layers) = self.element_and_attribute_slices_mut::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH);
for (element, layer) in elements.iter_mut().zip(layers.iter()) {
@@ -2242,6 +2300,10 @@ impl Render for List<Vector> {
}
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
collect_list_appearance_gpu_textures(self, textures);
}
fn new_ids_from_hash(&mut self, reference: Option<NodeId>) {
for index in 0..self.len() {
edit_list_row_geometry(self, index, |vector, paths| vector.vector_new_ids_from_hash(paths, reference.map(|id| id.0).unwrap_or_default()));
@@ -2357,7 +2419,19 @@ fn canvas_image_id(buffer_id: u64, halvings: u32) -> 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 };
render_raster_image_svg(item, image, render, render_params);
}
/// Emits one item of GPU raster content as SVG from its texture's downloaded image, exactly as CPU raster content.
fn render_raster_gpu_item_svg(item: ItemRef<'_, Raster<GPU>>, render: &mut SvgRender, render_params: &RenderParams) {
let Some(image) = item.element().and_then(Raster::texture).and_then(|texture| render_params.gpu_raster_downloads.get(texture)) else {
return;
};
render_raster_image_svg(item, image, render, render_params);
}
/// Emits a raster image as SVG, placed and styled by the attributes of the item it's drawn for.
fn render_raster_image_svg<T>(item: ItemRef<'_, T>, image: &Raster<CPU>, render: &mut SvgRender, render_params: &RenderParams) {
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.);
@@ -2547,8 +2621,10 @@ impl Render for List<Raster<CPU>> {
}
impl Render for List<Raster<GPU>> {
fn render_svg(&self, _render: &mut SvgRender, _render_params: &RenderParams) {
log::warn!("tried to render texture as an svg");
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
for index in 0..self.len() {
render_raster_gpu_item_svg(ItemRef::ListItem(self, index), render, render_params);
}
}
fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
@@ -2566,11 +2642,26 @@ impl Render for List<Raster<GPU>> {
add_unit_square_click_target(self.attribute_cloned_or_default(ATTR_TRANSFORM, index), click_targets);
}
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
for raster in self.iter_element_values() {
collect_raster_gpu_texture(raster, textures);
}
}
}
/// Collects a GPU raster's texture unless it's empty or already collected.
fn collect_raster_gpu_texture(raster: &Raster<GPU>, textures: &mut Vec<Texture>) {
if let Some(texture) = raster.texture()
&& !textures.contains(texture)
{
textures.push(texture.clone());
}
}
/// Draws one item of GPU raster content into the Vello scene.
fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster<GPU>>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
let Some(raster) = item.element() else { return };
let Some(texture) = item.element().and_then(|raster| raster.texture()) else { return };
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.);
let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
@@ -2610,12 +2701,12 @@ fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster<GPU>>, scene: &mut V
return;
}
let width = raster.data().width();
let height = raster.data().height();
let width = texture.width();
let height = texture.height();
let sampler = peniko::ImageSampler::new().with_extend(peniko::Extend::Pad);
let image_transform = transform * transform_attribute * DAffine2::from_scale(1. / DVec2::new(width as f64, height as f64));
scene.draw_texture(raster.texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array()));
scene.draw_texture(texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array()));
if layer {
scene.pop_layer()
@@ -3016,7 +3107,7 @@ fn draw_glyph_run_to_bezpaths(glyph_run: &parley::GlyphRun<'_, ()>, x_offset: f3
let run = glyph_run.run();
let font = run.font();
let font_size_pts = run.font_size();
let normalized_coords: Vec<NormalizedCoord> = run.normalized_coords().iter().map(|c| NormalizedCoord::from_bits(c.to_bits())).collect();
let normalized_coords: Vec<NormalizedCoord> = run.normalized_coords().iter().map(|c| NormalizedCoord::from_bits(*c)).collect();
let Ok(font_ref) = SkrifaFontRef::from_index(font.data.as_ref(), font.index) else { return };
let outlines = font_ref.outline_glyphs();
@@ -33,7 +33,7 @@ impl WeldExt for Vector {
// TODO: We lose information on the winding order by using an undirected graph. Switch to a directed graph and fix the algorithm to handle that.
// Graph containing only short edges, referencing the data graph
let mut short_edges = UnGraphMap::<_, _, rustc_hash::FxBuildHasher>::new();
let mut short_edges = UnGraphMap::new();
for segment_id in working.segment_ids.iter().copied() {
let length = indices.segment_chord_length(segment_id);
@@ -33,3 +33,4 @@ web-sys = { workspace = true }
vello_gpu = { workspace = true }
bytemuck = { workspace = true }
thiserror = { workspace = true }
half = { workspace = true }
@@ -1,6 +1,7 @@
mod buffer;
mod context;
mod pipeline;
pub mod shader_runtime;
mod texture_cache;
pub mod texture_conversion;
mod vello_render;
@@ -25,6 +26,7 @@ pub use raster_types::Texture;
pub use rendering::vello_scene_builder::VelloSceneBuilder;
pub use wgpu::Backends as WgpuBackends;
pub use wgpu::Features as WgpuFeatures;
pub use wgpu::TextureFormat as WgpuTextureFormat;
pub use wgpu_sync::CurrentSurfaceTexture as WgpuCurrentSurfaceTexture;
pub use wgpu_sync::Instance as WgpuInstance;
pub use wgpu_sync::Queue as WgpuQueue;
@@ -35,6 +37,11 @@ const TEXTURE_CACHE_SIZE: u64 = 1024 * 1024 * 1024; // 1GB
#[cfg(target_family = "wasm")]
const TEXTURE_CACHE_SIZE: u64 = 512 * 1024 * 1024; // 512MB
/// The preferred format of raster textures, holding linear-light straight-alpha values.
pub const RASTER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
/// The raster texture format on adapters that can't render to [`RASTER_FORMAT`], or when `GRAPHITE_RASTER_FORMAT=f16` forces it.
pub const FALLBACK_RASTER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
#[derive(dyn_any::DynAny, Clone)]
pub struct WgpuExecutor {
inner: Arc<WgpuExecutorInner>,
@@ -44,12 +51,18 @@ impl WgpuExecutor {
pub fn context(&self) -> &WgpuContext {
&self.inner.context
}
/// The format of every raster texture this executor creates, either [`RASTER_FORMAT`] or [`FALLBACK_RASTER_FORMAT`].
pub fn raster_format(&self) -> wgpu::TextureFormat {
self.inner.raster_format
}
}
#[derive(dyn_any::DynAny)]
pub struct WgpuExecutorInner {
context: WgpuContext,
texture_cache: std::sync::Mutex<TextureCache>,
raster_format: wgpu::TextureFormat,
vello_renderer: VelloRenderer,
/// The canvas the node graph renders documents on.
document_canvas: Mutex<VelloCanvas>,
@@ -177,6 +190,7 @@ impl WgpuExecutor {
}
pub fn with_context(context: WgpuContext) -> Option<Self> {
let raster_format = choose_raster_format(&context.adapter);
let vello_renderer = VelloRenderer::new(&context.device);
let texture_cache = TextureCache::new(TEXTURE_CACHE_SIZE);
@@ -185,6 +199,7 @@ impl WgpuExecutor {
inner: Arc::new(WgpuExecutorInner {
context,
texture_cache: texture_cache.into(),
raster_format,
vello_renderer,
document_canvas: Mutex::default(),
}),
@@ -195,3 +210,16 @@ impl WgpuExecutor {
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("No GPU is available")]
pub struct NoGpuError;
fn choose_raster_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat {
if std::env::var("GRAPHITE_RASTER_FORMAT").is_ok_and(|format| format == "f16") {
return FALLBACK_RASTER_FORMAT;
}
if adapter.get_texture_format_features(RASTER_FORMAT).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) {
RASTER_FORMAT
} else {
log::warn!("The GPU can't render to {RASTER_FORMAT:?}, so rasters fall back to {FALLBACK_RASTER_FORMAT:?}");
FALLBACK_RASTER_FORMAT
}
}
@@ -32,6 +32,11 @@ impl PipelineCache {
let pipeline = (**entry).downcast_ref::<P>().ok_or(PipelineError::TypeMismatch { expected: std::any::type_name::<P>() })?;
Ok(pipeline.run(executor, args))
}
/// The executor the cache was initialized with, or `None` when no GPU is available.
pub fn executor(&self) -> Option<&WgpuExecutor> {
self.executor.get()
}
}
impl std::fmt::Debug for PipelineCache {
@@ -0,0 +1 @@
pub mod raster_kernel_runtime;
@@ -0,0 +1,10 @@
@vertex
fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
let corner = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u));
return vec4<f32>(corner * 2. - 1., 0., 1.);
}
@fragment
fn fragment(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
return kernel(vec2<i32>(position.xy));
}
@@ -0,0 +1,34 @@
@group(0) @binding(BINDING) var INPUT_texture: texture_2d<f32>;
fn INPUT_size() -> vec2<i32> {
return vec2<i32>(kernel_frame[PLACEMENT].zw);
}
fn INPUT_load(coord: vec2<i32>) -> vec4<f32> {
return textureLoad(INPUT_texture, clamp(coord, vec2<i32>(0), INPUT_size() - 1), 0);
}
fn INPUT_premultiplied(texel: vec2<i32>) -> vec4<f32> {
if any(texel < vec2<i32>(0)) || any(texel >= INPUT_size()) {
return vec4<f32>(0.);
}
let color = textureLoad(INPUT_texture, texel, 0);
return vec4<f32>(color.rgb * color.a, color.a);
}
fn INPUT_at(coord: vec2<i32>) -> vec4<f32> {
let axes = kernel_frame[AXES];
let center = vec2<f32>(coord) + 0.5;
let texel = axes.xy * center.x + axes.zw * center.y + kernel_frame[PLACEMENT].xy - 0.5;
let base = floor(texel);
let t = texel - base;
let corner = vec2<i32>(base);
let top = mix(INPUT_premultiplied(corner), INPUT_premultiplied(corner + vec2<i32>(1, 0)), t.x);
let bottom = mix(INPUT_premultiplied(corner + vec2<i32>(0, 1)), INPUT_premultiplied(corner + vec2<i32>(1, 1)), t.x);
let premultiplied = mix(top, bottom, t.y);
if premultiplied.a <= 0. {
return vec4<f32>(0.);
}
return vec4<f32>(premultiplied.rgb / premultiplied.a, premultiplied.a);
}
@@ -0,0 +1,3 @@
fn INPUT_sample(texel: vec2<f32>) -> vec4<f32> {
return textureSampleLevel(INPUT_texture, raster_kernel_sampler, texel / vec2<f32>(INPUT_size()), 0.);
}
@@ -0,0 +1,390 @@
use crate::{WgpuExecutor, WgpuPipeline};
use core_types::Color;
use glam::{DAffine2, UVec2};
use raster_types::{GPU, Raster};
use std::any::TypeId;
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, VecDeque};
use std::hash::{Hash, Hasher};
use std::sync::Mutex;
use wgpu::util::BufferInitDescriptor;
/// An input raster of a kernel, with the affine mapping output pixel coordinates to the input's texel coordinates.
pub struct RasterKernelInput<'a> {
pub raster: &'a Raster<GPU>,
pub output_to_texel: DAffine2,
}
/// A lookup table of a kernel, bound as an `Rgba32Float` texture after its inputs.
pub enum RasterKernelLookup<'a> {
/// A `width x 1` 2D texture of at most 4096 entries.
Lut1d(&'a [Color]),
/// A `size x size x size` 3D texture, its entries ordered with x fastest, then y, then z.
Lut3d { size: u32, data: &'a [Color] },
}
impl RasterKernelLookup<'_> {
fn data(&self) -> &[Color] {
match self {
Self::Lut1d(data) | Self::Lut3d { data, .. } => data,
}
}
fn extent(&self) -> wgpu::Extent3d {
match self {
Self::Lut1d(data) => wgpu::Extent3d {
width: data.len() as u32,
height: 1,
depth_or_array_layers: 1,
},
Self::Lut3d { size, .. } => wgpu::Extent3d {
width: *size,
height: *size,
depth_or_array_layers: *size,
},
}
}
fn dimension(&self) -> (wgpu::TextureDimension, wgpu::TextureViewDimension) {
match self {
Self::Lut1d(_) => (wgpu::TextureDimension::D2, wgpu::TextureViewDimension::D2),
Self::Lut3d { .. } => (wgpu::TextureDimension::D3, wgpu::TextureViewDimension::D3),
}
}
fn content_hash(&self) -> u64 {
let mut hasher = DefaultHasher::new();
let extent = self.extent();
(extent.width, extent.height, extent.depth_or_array_layers, matches!(self, Self::Lut3d { .. })).hash(&mut hasher);
bytemuck::cast_slice::<Color, u8>(self.data()).hash(&mut hasher);
hasher.finish()
}
}
/// One run of a raster kernel, writing a texture of `output_size` in `output_format`.
///
/// `wgsl` must define `fn kernel(coord: vec2<i32>) -> vec4<f32>`, and reads its parameters from `uniform_params`, the 32-bit `params` packed into `vec4<u32>` slots.
/// It may call `output_size()` and, for each input `i`, `input_i_size()`, `input_i_load(coord)` reading the input's own texel clamped to its edge,
/// and `input_i_at(coord)` sampling the input bilinearly where the output pixel's center lies, transparent beyond the input.
/// With `filtered`, it may also call `input_i_sample(texel)`, sampling the input bilinearly at texel coordinates, whose texel centers lie at +0.5, clamped to its edge,
/// which requires every input to be in a filterable format such as `Rgba16Float` rather than [`crate::RASTER_FORMAT`].
/// It declares the texture of each of the `lookups` itself, the `k`th at binding `2 + inputs + k`.
/// An empty input reads as transparent with a size of zero, and an empty `output_size` gives the empty raster without running the kernel.
/// Every run of the same `kernel` must have the same number of inputs, the same kinds of lookups, and the same `filtered`.
pub struct RasterKernelArgs<'a> {
pub kernel: TypeId,
pub label: &'static str,
pub wgsl: fn() -> String,
pub params: Vec<u32>,
pub inputs: Vec<RasterKernelInput<'a>>,
pub lookups: Vec<RasterKernelLookup<'a>>,
pub filtered: bool,
pub output_size: UVec2,
pub output_format: wgpu::TextureFormat,
}
struct KernelPipeline {
bind_group_layout: wgpu::BindGroupLayout,
pipeline: wgpu::RenderPipeline,
}
/// The number of lookup textures kept uploaded, the most recently used first, so a kernel run again with the same table skips the upload.
const LOOKUP_CACHE_SIZE: usize = 16;
pub struct RasterKernelRuntime {
pipelines: Mutex<HashMap<(TypeId, wgpu::TextureFormat), KernelPipeline>>,
lookups: Mutex<VecDeque<(u64, wgpu::Texture)>>,
sampler: wgpu::Sampler,
empty_input: wgpu::Texture,
}
impl RasterKernelRuntime {
fn lookup_texture(&self, executor: &WgpuExecutor, lookup: &RasterKernelLookup<'_>) -> wgpu::Texture {
let hash = lookup.content_hash();
let mut lookups = self.lookups.lock().unwrap();
if let Some(index) = lookups.iter().position(|(cached, _)| *cached == hash) {
let entry = lookups.remove(index).unwrap();
let texture = entry.1.clone();
lookups.push_front(entry);
return texture;
}
let size = lookup.extent();
let texture = executor.context().device.create_texture(&wgpu::TextureDescriptor {
label: Some("raster_kernel_lookup"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: lookup.dimension().0,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
executor.context().queue.write_texture(
texture.as_image_copy(),
bytemuck::cast_slice(lookup.data()),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(16 * size.width),
rows_per_image: Some(size.height),
},
size,
);
lookups.push_front((hash, texture.clone()));
lookups.truncate(LOOKUP_CACHE_SIZE);
texture
}
}
impl WgpuPipeline for RasterKernelRuntime {
type Args<'a> = RasterKernelArgs<'a>;
type Out = Raster<GPU>;
fn create(executor: &WgpuExecutor) -> Self {
let sampler = executor.context().device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("raster_kernel_sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let empty_input = executor.context().device.create_texture(&wgpu::TextureDescriptor {
label: Some("raster_kernel_empty_input"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
Self {
pipelines: Mutex::default(),
lookups: Mutex::default(),
sampler,
empty_input,
}
}
fn run(&self, executor: &WgpuExecutor, args: &RasterKernelArgs<'_>) -> Raster<GPU> {
if args.output_size.x == 0 || args.output_size.y == 0 {
return Raster::default();
}
let device = &executor.context().device;
let param_slots = slots(args.params.len());
let mut pipelines = self.pipelines.lock().unwrap();
let kernel_pipeline = pipelines.entry((args.kernel, args.output_format)).or_insert_with(|| create_pipeline(device, args, param_slots));
let mut params = args.params.clone();
params.resize(param_slots * 4, 0);
let params = executor.create_buffer_init(&BufferInitDescriptor {
label: Some(args.label),
contents: bytemuck::cast_slice(&params),
usage: wgpu::BufferUsages::UNIFORM,
});
let frame = executor.create_buffer_init(&BufferInitDescriptor {
label: Some(args.label),
contents: bytemuck::cast_slice(&frame_data(args)),
usage: wgpu::BufferUsages::UNIFORM,
});
let input_views = args
.inputs
.iter()
.map(|input| input.raster.texture().map_or(&self.empty_input, |texture| texture).create_view(&wgpu::TextureViewDescriptor::default()))
.collect::<Vec<_>>();
let lookup_views = args
.lookups
.iter()
.map(|lookup| self.lookup_texture(executor, lookup).create_view(&wgpu::TextureViewDescriptor::default()))
.collect::<Vec<_>>();
let mut entries = vec![
wgpu::BindGroupEntry {
binding: 0,
resource: params.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: frame.as_entire_binding(),
},
];
entries.extend(input_views.iter().enumerate().map(|(index, view)| wgpu::BindGroupEntry {
binding: 2 + index as u32,
resource: wgpu::BindingResource::TextureView(view),
}));
entries.extend(lookup_views.iter().enumerate().map(|(index, view)| wgpu::BindGroupEntry {
binding: (2 + args.inputs.len() + index) as u32,
resource: wgpu::BindingResource::TextureView(view),
}));
if args.filtered {
entries.push(wgpu::BindGroupEntry {
binding: sampler_binding(args),
resource: wgpu::BindingResource::Sampler(&self.sampler),
});
}
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some(args.label),
layout: &kernel_pipeline.bind_group_layout,
entries: &entries,
});
let output = executor.request_texture_with_format(args.output_size, args.output_format);
let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(args.label) });
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some(args.label),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &output_view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
..Default::default()
});
pass.set_pipeline(&kernel_pipeline.pipeline);
pass.set_bind_group(0, &bind_group, &[]);
pass.draw(0..3, 0..1);
}
executor.context().queue.submit([encoder.finish()]);
Raster::new_gpu(output)
}
}
fn create_pipeline(device: &wgpu::Device, args: &RasterKernelArgs<'_>, param_slots: usize) -> KernelPipeline {
let uniform = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let texture = |binding, view_dimension, filterable| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable },
view_dimension,
multisampled: false,
},
count: None,
};
let mut entries = vec![uniform(0), uniform(1)];
entries.extend((0..args.inputs.len()).map(|index| texture(2 + index as u32, wgpu::TextureViewDimension::D2, args.filtered)));
entries.extend(
args.lookups
.iter()
.enumerate()
.map(|(index, lookup)| texture((2 + args.inputs.len() + index) as u32, lookup.dimension().1, false)),
);
if args.filtered {
entries.push(wgpu::BindGroupLayoutEntry {
binding: sampler_binding(args),
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
});
}
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some(args.label),
entries: &entries,
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some(args.label),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let source = format!("{}\n{}\n\n{}", bindings_wgsl(param_slots, args), (args.wgsl)(), include_str!("raster_kernel_entry.wgsl"));
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(args.label),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(args.label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vertex"),
compilation_options: Default::default(),
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fragment"),
compilation_options: Default::default(),
targets: &[Some(args.output_format.into())],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
KernelPipeline { bind_group_layout, pipeline }
}
/// The frame uniform: the output size, then for each input its affine's matrix columns, translation, and size.
fn frame_data(args: &RasterKernelArgs<'_>) -> Vec<f32> {
let mut data = vec![args.output_size.x as f32, args.output_size.y as f32, 0., 0.];
for input in &args.inputs {
let affine = input.output_to_texel;
let size = input.raster.size();
data.extend([affine.matrix2.x_axis.x, affine.matrix2.x_axis.y, affine.matrix2.y_axis.x, affine.matrix2.y_axis.y].map(|value| value as f32));
data.extend([affine.translation.x as f32, affine.translation.y as f32, size.x as f32, size.y as f32]);
}
data
}
/// The binding of the sampler of a `filtered` kernel's inputs, after its lookups.
fn sampler_binding(args: &RasterKernelArgs<'_>) -> u32 {
(2 + args.inputs.len() + args.lookups.len()) as u32
}
fn bindings_wgsl(param_slots: usize, args: &RasterKernelArgs<'_>) -> String {
let inputs = args.inputs.len();
let frame_slots = 1 + 2 * inputs;
let mut source = format!(
"@group(0) @binding(0) var<uniform> uniform_params: array<vec4<u32>, {param_slots}>;\n@group(0) @binding(1) var<uniform> kernel_frame: array<vec4<f32>, {frame_slots}>;\n\nfn output_size() -> vec2<i32> {{\n\treturn vec2<i32>(kernel_frame[0].xy);\n}}\n"
);
if args.filtered {
source += &format!("\n@group(0) @binding({}) var raster_kernel_sampler: sampler;\n", sampler_binding(args));
}
for index in 0..inputs {
let mut input = include_str!("raster_kernel_input.wgsl").to_string();
if args.filtered {
input += include_str!("raster_kernel_input_sample.wgsl");
}
source += &input
.replace("INPUT", &format!("input_{index}"))
.replace("BINDING", &(2 + index).to_string())
.replace("AXES", &(1 + 2 * index).to_string())
.replace("PLACEMENT", &(2 + 2 * index).to_string());
}
source
}
/// The `vec4<u32>` slot count holding `params` 32-bit values, at least one since WGSL arrays can't be empty.
fn slots(params: usize) -> usize {
params.div_ceil(4).max(1)
}
@@ -2,32 +2,71 @@ use crate::{Buffer, WgpuExecutor};
use core_types::Color;
use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::ops::ConvertAsync;
use core_types::ops::{Convert, ConvertAsync};
use core_types::transform::Footprint;
use half::f16;
use raster_types::Image;
use raster_types::{CPU, GPU, Raster};
use raster_types::{CPU, GPU, Raster, Storage};
use wgpu::Extent3d;
/// Uploads CPU image data to a GPU texture
fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raster<CPU>) -> Raster<GPU> {
if image.is_empty() {
return Raster::default();
}
let format = executor.raster_format();
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), format);
let half_floats: Vec<[f16; 4]>;
let (bytes, bytes_per_pixel) = if format == crate::FALLBACK_RASTER_FORMAT {
half_floats = image.data.iter().map(|color| color.to_vec4().to_array().map(f16::from_f32)).collect();
(bytemuck::cast_slice(half_floats.as_slice()), 8)
} else {
(bytemuck::cast_slice(image.data.as_slice()), 16)
};
queue.write_texture(
texture.as_image_copy(),
bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(bytes_per_pixel * image.width),
rows_per_image: Some(image.height),
},
Extent3d {
width: image.width,
height: image.height,
depth_or_array_layers: 1,
},
);
Raster::new_gpu(texture)
}
/// Converts a Raster<GPU> texture to Raster<CPU> by downloading the underlying texture data.
///
/// Assumptions:
/// - 2D texture, mip level 0
/// - 4 bytes-per-pixel RGBA8
/// - 4 bytes-per-pixel RGBA8, or `RASTER_FORMAT` or `FALLBACK_RASTER_FORMAT`
/// - Texture has COPY_SRC usage
struct RasterGpuToRasterCpuConverter {
buffer: Buffer,
width: u32,
height: u32,
format: wgpu::TextureFormat,
unpadded_bytes_per_row: u32,
padded_bytes_per_row: u32,
_source: raster_types::Texture,
}
impl RasterGpuToRasterCpuConverter {
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
let texture = data_gpu.data();
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Option<Self> {
let texture = data_gpu.texture()?;
let width = texture.width();
let height = texture.height();
let bytes_per_pixel = 4; // RGBA8
let format = texture.format();
let bytes_per_pixel = match format {
crate::RASTER_FORMAT => 16,
crate::FALLBACK_RASTER_FORMAT => 8,
_ => 4,
};
let unpadded_bytes_per_row = width * bytes_per_pixel;
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
@@ -62,15 +101,16 @@ impl RasterGpuToRasterCpuConverter {
},
);
Self {
Some(Self {
buffer,
width,
height,
format,
unpadded_bytes_per_row,
padded_bytes_per_row,
// Keep source texture alive
_source: data_gpu.texture.clone(),
}
_source: texture.clone(),
})
}
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
@@ -114,8 +154,20 @@ impl RasterGpuToRasterCpuConverter {
for row in 0..self.height as usize {
let start = row * row_stride;
let row_slice = &view[start..start + row_bytes];
for &[red, green, blue, alpha] in row_slice.as_chunks::<4>().0 {
cpu_data.push(SRGBA8::new(red, green, blue, alpha).into());
match self.format {
crate::RASTER_FORMAT => cpu_data.extend(bytemuck::pod_collect_to_vec::<u8, Color>(row_slice)),
crate::FALLBACK_RASTER_FORMAT => {
let pixels = bytemuck::pod_collect_to_vec::<u8, [f16; 4]>(row_slice);
cpu_data.extend(pixels.iter().map(|pixel| {
let [red, green, blue, alpha] = pixel.map(f16::to_f32);
Color::from_rgbaf32_unchecked(red, green, blue, alpha)
}));
}
_ => {
for &[red, green, blue, alpha] in row_slice.as_chunks::<4>().0 {
cpu_data.push(SRGBA8::new(red, green, blue, alpha).into());
}
}
}
}
@@ -171,6 +223,48 @@ async fn yield_to_event_loop() -> bool {
.await
}
/// Passthrough conversion for GPU `List`s - no conversion needed
impl Convert<List<Raster<GPU>>, WgpuExecutor> for List<Raster<GPU>> {
fn convert(self, _: Footprint, _converter: WgpuExecutor) -> List<Raster<GPU>> {
self
}
}
/// Converts a `List<Raster<CPU>>` to `List<Raster<GPU>>` by uploading each image to a texture
impl Convert<List<Raster<GPU>>, WgpuExecutor> for List<Raster<CPU>> {
fn convert(self, _: Footprint, executor: WgpuExecutor) -> List<Raster<GPU>> {
let queue = executor.context().queue.lock();
let list = self
.into_iter()
.map(|row| {
let (image, attributes) = row.into_parts();
Item::from_parts(upload_to_texture(&executor, &queue, &image), attributes)
})
.collect();
queue.submit([]);
list
}
}
/// Converts single CPU raster to GPU by uploading to texture
impl Convert<Raster<GPU>, WgpuExecutor> for Raster<CPU> {
fn convert(self, _: Footprint, executor: WgpuExecutor) -> Raster<GPU> {
let queue = executor.context().queue.lock();
let raster = upload_to_texture(&executor, &queue, &self);
queue.submit([]);
raster
}
}
/// Passthrough conversion for CPU `List`s - no conversion needed
impl Convert<List<Raster<CPU>>, WgpuExecutor> for List<Raster<CPU>> {
fn convert(self, _: Footprint, _converter: WgpuExecutor) -> List<Raster<CPU>> {
self
}
}
/// Converts a `List<Raster<GPU>>` to `List<Raster<CPU>>` by downloading texture data in one go then asynchronously maps all buffers and processes the results.
impl ConvertAsync<List<Raster<CPU>>, WgpuExecutor> for List<Raster<GPU>> {
async fn convert(self, _: Footprint, executor: WgpuExecutor) -> List<Raster<CPU>> {
@@ -194,7 +288,12 @@ impl ConvertAsync<List<Raster<CPU>>, WgpuExecutor> for List<Raster<GPU>> {
let mut map_futures = Vec::new();
for converter in converters {
map_futures.push(converter.convert(device));
map_futures.push(async move {
match converter {
Some(converter) => converter.convert(device).await,
None => Ok(Raster::default()),
}
});
}
let map_results = futures::future::try_join_all(map_futures)
@@ -227,6 +326,7 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutor> for Raster<GPU> {
queue.submit([encoder.finish()]);
let Some(converter) = converter else { return Raster::default() };
converter.convert(device).await.expect("Failed to download texture data")
}
}
@@ -361,7 +361,8 @@ impl ImageTextures {
if let SceneImage::Texture(source) = image {
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
alpha_conversion.premultiply(device, encoder, &source_view, source.format().is_srgb(), &view);
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
alpha_conversion.premultiply(device, encoder, &source_view, loads_linear_light, &view);
}
Some(view)
+2 -2
View File
@@ -24,8 +24,8 @@ quote = { workspace = true }
convert_case = { workspace = true }
indoc = { workspace = true }
proc-macro-crate = "3.1"
proc-macro-error3 = "3.1"
proc-macro-crate = "3.1.0"
proc-macro-error2 = "2"
[dev-dependencies]
core-types = { workspace = true }
+2 -2
View File
@@ -1057,7 +1057,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
#register_node_impl
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))]
#[cfg_attr(not(target_family = "wasm"), ctor)]
fn register_metadata() {
let metadata = NodeMetadata {
display_name: #display_name,
@@ -1429,7 +1429,7 @@ fn generate_register_node_impl(
}
}
Ok(quote! {
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))]
#[cfg_attr(not(target_family = "wasm"), ctor)]
fn register_node() {
let mut registry = NODE_REGISTRY.lock().unwrap();
registry.insert(
+1 -1
View File
@@ -245,7 +245,7 @@ pub fn derive_destructure_impl(item: TokenStream2) -> syn::Result<TokenStream2>
use super::*;
use #gcore::ctor::ctor;
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = core_types::ctor))]
#[cfg_attr(not(target_family = "wasm"), ctor)]
fn register_memoize_and_monitor() {
#graphene_core::memo::register_memoize_and_monitor::<#struct_ident>();
#graphene_core::memo::register_memoize_and_monitor::<#mapped_ident>();
+1 -1
View File
@@ -1,5 +1,5 @@
use proc_macro::TokenStream;
use proc_macro_error3::proc_macro_error;
use proc_macro_error2::proc_macro_error;
mod codegen;
mod crate_ident;
+1
View File
@@ -1172,6 +1172,7 @@ impl ParsedNodeFn {
ident: ident.clone(),
colon_token: Some(Default::default()),
bounds,
eq_token: None,
default: None,
}));
self.input.ty = parse_quote!(#ident);
+1 -1
View File
@@ -1,5 +1,5 @@
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
use proc_macro_error3::{abort_if_dirty, emit_error};
use proc_macro_error2::{abort_if_dirty, emit_error};
use quote::quote;
use syn::spanned::Spanned;
use syn::{GenericParam, Type};
@@ -4,7 +4,7 @@ pub(super) struct Convert {
}
impl Convert {
pub(super) fn new(device: &wgpu::Device) -> Self {
pub(super) fn new(device: &wgpu::Device, raster_format: wgpu::TextureFormat) -> Self {
let shader = device.create_shader_module(wgpu::include_wgsl!("convert.wgsl"));
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("basic_brush_convert_bind_group_layout"),
@@ -37,7 +37,7 @@ impl Convert {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())],
targets: &[Some(raster_format.into())],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
@@ -19,13 +19,6 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> @builtin(position) vec4<
@group(0) @binding(0)
var t_composite: texture_2d<f32>;
fn linear_to_srgb(channel: f32) -> f32 {
if (channel <= 0.0031308) {
return channel * 12.92;
}
return 1.055 * pow(channel, 1.0 / 2.4) - 0.055;
}
@fragment
fn fs_main(@builtin(position) frag: vec4<f32>) -> @location(0) vec4<f32> {
let premultiplied = textureLoad(t_composite, vec2<i32>(frag.xy), 0);
@@ -33,5 +26,5 @@ fn fs_main(@builtin(position) frag: vec4<f32>) -> @location(0) vec4<f32> {
if (premultiplied.a > 0.0) {
straight = premultiplied.rgb / premultiplied.a;
}
return vec4<f32>(linear_to_srgb(straight.r), linear_to_srgb(straight.g), linear_to_srgb(straight.b), premultiplied.a);
return vec4<f32>(straight, premultiplied.a);
}
@@ -80,7 +80,7 @@ impl WgpuPipeline for BasicBrushPipeline {
Self {
scatter: Scatter::new(device),
resolve: Resolve::new(device),
convert: Convert::new(device),
convert: Convert::new(device, executor.raster_format()),
kernels: KernelCache::default(),
}
}
@@ -183,7 +183,7 @@ pub(super) fn render(pipeline: &BasicBrushPipeline, executor: &WgpuExecutor, fra
let updated = (!missing.is_empty()).then(|| executor.request_texture_with_format(crop.size, COMPOSITE_FORMAT));
let composite = executor.request_texture_with_format(crop.size, COMPOSITE_FORMAT);
let scratch = Field::request(executor, region.size);
let output = executor.request_texture(crop.size);
let output = executor.request_texture_with_format(crop.size, executor.raster_format());
let mut recorder = Recorder::new(pipeline, executor, &region);
if let Some(updated) = &updated {
+1
View File
@@ -62,6 +62,7 @@ fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
List<Vector>,
List<Graphic>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -301,6 +301,13 @@ fn wgpu_executor(_: impl Ctx, #[scope(application_io::IDENTIFIER)] application_i
application_io.element().gpu_executor().cloned().map(Item::new_from_element).ok_or(::wgpu_executor::NoGpuError)
}
/// The GPU executor if there is one, for nodes that also work without it.
#[node_macro::node(category(""), inject_scope)]
fn try_wgpu_executor(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<Arc<PlatformEditorApi>>) -> Item<Option<::wgpu_executor::WgpuExecutor>> {
let executor = editor_api.into_element().application_io.as_ref().and_then(|application_io| application_io.gpu_executor()).cloned();
Item::new_from_element(executor)
}
#[cfg(test)]
mod tests {
use super::*;
+65 -38
View File
@@ -1,26 +1,25 @@
use core_types::list::{Item, List};
use core_types::ops::ConvertAsync;
use core_types::transform::{Footprint, Transform};
use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs};
use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, NodeError, OwnedContextImpl, WasmNotSend};
use graph_craft::document::value::{RenderOutput, RenderOutputType};
use graphene_application_io::{ExportFormat, RenderConfig};
use graphic_types::raster_types::{CPU, Raster};
use graphic_types::raster_types::{CPU, GPU, Raster, Texture};
use graphic_types::{Artboard, Graphic, Vector};
use rendering::vello_scene_builder::VelloSceneBuilder;
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
use std::collections::HashMap;
use std::sync::Arc;
use vector_types::Gradient;
use wgpu_executor::WgpuExecutor;
#[derive(Clone, dyn_any::DynAny)]
pub enum RenderIntermediateType {
/// The content itself, drawn into a Vello scene at each render since the scene depends on the render's size and placement
Vello(Arc<dyn Render + Send + Sync>),
Svg(Arc<SvgRenderOutput>),
}
#[derive(Clone, dyn_any::DynAny)]
pub struct RenderIntermediate {
pub(crate) ty: RenderIntermediateType,
/// The content itself, drawn at each render since a Vello scene depends on the render's size and placement and SVG output on the GPU raster downloads
pub(crate) content: Arc<dyn Render + Send + Sync>,
/// Images of the content's GPU raster textures, downloaded only for SVG output, which can't reference textures
pub(crate) gpu_raster_downloads: Arc<HashMap<Texture, Raster<CPU>>>,
pub(crate) metadata: RenderMetadata,
}
@@ -32,44 +31,62 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
Context -> List<Graphic>,
Context -> List<Vector>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<String>,
)]
data: impl Node<Context<'static>, Output = T>,
) -> Result<Item<RenderIntermediate>, Interrupt> {
let render_params = ctx
.vararg(0)
.expect("Did not find var args")
.downcast_ref::<RenderParams>()
.expect("Downcasting render params yielded invalid type");
let ctx = OwnedContextImpl::from(ctx.clone()).into_context();
let data = data.eval(ctx)?;
let footprint = Footprint::default();
let mut metadata = RenderMetadata::default();
data.collect_metadata(&mut metadata, footprint, None, None);
let intermediate = match &render_params.render_output_type {
RenderOutputTypeRequest::Vello => RenderIntermediate {
ty: RenderIntermediateType::Vello(Arc::new(data)),
metadata,
},
RenderOutputTypeRequest::Svg => {
let mut render = SvgRender::new();
data.render_svg(&mut render, render_params);
RenderIntermediate {
ty: RenderIntermediateType::Svg(Arc::new(render.into())),
metadata,
}
}
let intermediate = RenderIntermediate {
content: Arc::new(data),
gpu_raster_downloads: Arc::default(),
metadata,
};
Ok(Item::new_from_element(intermediate))
}
/// Downloads the content's GPU raster textures for SVG output to embed, leaving them undrawn without a GPU executor.
#[node_macro::node(category(""), placeholder = pending_gpu_raster_downloads)]
async fn download_gpu_rasters(
ctx: impl Ctx + ExtractVarArgs,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<WgpuExecutor>>,
mut data: Item<RenderIntermediate>,
) -> Item<RenderIntermediate> {
let render_output_type = ctx
.vararg(0)
.expect("Did not find var args")
.downcast_ref::<RenderParams>()
.expect("Downcasting render params yielded invalid type")
.render_output_type;
let (RenderOutputTypeRequest::Svg, Some(executor)) = (render_output_type, executor.into_element()) else {
return data;
};
let mut textures = Vec::new();
data.element().content.collect_gpu_textures(&mut textures);
if textures.is_empty() {
return data;
}
let rasters: List<Raster<GPU>> = textures.iter().map(|texture| Item::new_from_element(Raster::new_gpu(texture.clone()))).collect();
let downloads = rasters.convert(Footprint::DEFAULT, executor).await;
data.element_mut().gpu_raster_downloads = Arc::new(textures.into_iter().zip(downloads.into_iter().map(Item::into_element)).collect());
data
}
fn pending_gpu_raster_downloads(_executor: &Item<Option<WgpuExecutor>>, data: &Item<RenderIntermediate>) -> Item<RenderIntermediate> {
data.clone()
}
#[node_macro::node(category(""))]
fn render(
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
@@ -82,18 +99,25 @@ fn render(
.expect("Did not find var args")
.downcast_ref::<RenderParams>()
.expect("Downcasting render params yielded invalid type");
let mut render_params = render_params.clone();
render_params.footprint = *footprint;
let RenderIntermediate { ty, mut metadata } = data.into_element();
let RenderIntermediate {
content,
gpu_raster_downloads,
mut metadata,
} = data.into_element();
metadata.apply_transform(footprint.transform);
let data = match (render_params.render_output_type, ty) {
(RenderOutputTypeRequest::Svg, RenderIntermediateType::Svg(data)) => {
let data = match render_params.render_output_type {
RenderOutputTypeRequest::Svg => {
let render_params = RenderParams {
gpu_raster_downloads,
..render_params.clone()
};
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 mut render = SvgRender::from(data.as_ref());
let mut render = SvgRender::new();
content.render_svg(&mut render, &render_params);
render.wrap_with_transform(logical_transform, Some(logical_resolution));
let output = SvgRenderOutput::from(render);
@@ -104,10 +128,14 @@ fn render(
image_data: output.image_data.into_iter().collect(),
}
}
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
RenderOutputTypeRequest::Vello => {
let render_params = RenderParams {
footprint: *footprint,
..render_params.clone()
};
let executor = executor.eval(Context::default())?.into_element();
let mut draw = |scene: &mut VelloSceneBuilder| data.render_to_vello(scene, Default::default(), &render_params);
let mut draw = |scene: &mut VelloSceneBuilder| content.render_to_vello(scene, Default::default(), &render_params);
let texture = match executor.render_vello(footprint.resolution, footprint.transform, &mut draw) {
Ok(texture) => texture,
// Leave the output transparent, at a size the GPU can hold, rather than taking down the editor
@@ -119,7 +147,6 @@ fn render(
};
RenderOutputType::Texture(texture)
}
_ => unreachable!("Render node did not receive its requested data type"),
};
Ok(Item::new_from_element(RenderOutput { data, metadata }))
+1 -1
View File
@@ -15,7 +15,7 @@ use math_parser::object::Object;
use math_parser::parser::{MessagePart, ParseError};
use math_parser::reducer::{Reducer, classify_reducer};
use math_parser::value::{Value, Vector2, Vector3};
use rand::{RngExt, SeedableRng};
use rand::{Rng, SeedableRng};
use std::sync::{Arc, Mutex, PoisonError};
use vector_types::Gradient;
+1
View File
@@ -35,6 +35,7 @@ graphene-resource = { workspace = true }
graphene-hash = { workspace = true }
raster-types = { workspace = true }
vector-types = { workspace = true }
wgpu-executor = { workspace = true }
# Workspace dependencies
bytemuck = { workspace = true }
-27
View File
@@ -1,27 +0,0 @@
use core_types::color::Color;
use raster_types::{CPU, Raster};
use vector_types::Gradient;
pub trait Adjust<P> {
fn adjust(&mut self, map_fn: impl Fn(&P) -> P);
}
impl Adjust<Color> for Color {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
*self = map_fn(self);
}
}
impl Adjust<Color> for Raster<CPU> {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for color in self.data_mut().data.iter_mut() {
*color = map_fn(color);
}
}
}
impl Adjust<Color> for Gradient {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
*self = self.map_colors(map_fn);
}
}
File diff suppressed because it is too large. Load diff
+76 -16
View File
@@ -1,10 +1,12 @@
use crate::adjust::Adjust;
use core_types::Ctx;
use crate::raster_kernel::{Adjust, MapColor, Wgsl, raster_kernel_pipeline};
use crate::{gpu_param_enum, gpu_params};
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::list::Item;
use raster_types::{CPU, Raster};
use core_types::{Ctx, Interrupt};
use raster_types::{CPU, GPU, Raster};
use vector_types::Gradient;
use wgpu_executor::WgpuPipelineCache;
pub use core_types::blending::{apply_blend_mode, blend_colors};
@@ -30,11 +32,12 @@ fn mix_colors(
}
// TODO: Rename to "Paint Overlay" and take a `Graphic` paint like the `Fill` node, enabling this to serve the cases of Color Overlay, Gradient Overlay, and Pattern Overlay.
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))]
fn color_overlay<T: Adjust<Color>>(
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"), version(2))]
fn color_overlay<T: Adjust>(
_: impl Ctx,
#[implementations(
Raster<CPU>,
Raster<GPU>,
Color,
Gradient,
)]
@@ -46,19 +49,38 @@ fn color_overlay<T: Adjust<Color>>(
#[hard(0..100)]
#[default(100.)]
opacity: Item<f64>,
) -> Item<T> {
let mut image = image;
let color = color.into_element();
let blend_mode = blend_mode.into_element();
let opacity = (opacity.into_element() / 100.) as f32;
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
let kernel = ColorOverlay {
color: color.into_element(),
blend_mode: blend_mode.into_element(),
opacity: (opacity.into_element() / 100.) as f32,
};
Ok(image.adjust(&kernel, pipeline.element())?)
}
image.element_mut().adjust(|pixel| {
let overlay = apply_blend_mode(color, *pixel, blend_mode);
let mix = |image: f32, overlay: f32| image + (overlay - image) * opacity;
gpu_param_enum!(i32: BlendMode);
gpu_params! {
#[derive(Clone)]
struct ColorOverlay {
color: Color,
blend_mode: BlendMode,
opacity: f32,
}
}
impl MapColor for ColorOverlay {
fn map_cpu(&self, pixel: Color) -> Color {
let overlay = apply_blend_mode(self.color, pixel, self.blend_mode);
let mix = |image: f32, overlay: f32| image + (overlay - image) * self.opacity;
Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a())
});
image
}
fn wgsl() -> Wgsl {
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/color_overlay.wgsl")))
}
}
#[cfg(test)]
@@ -86,13 +108,51 @@ mod test {
overlay_color.into(),
BlendMode::Multiply.into(),
opacity.into(),
Item::default(),
);
let result = result.into_element();
let result = result.unwrap().into_element();
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
assert_eq!(result.data[0], Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
}
#[test]
fn vivid_light_overlays_match_on_the_cpu_and_gpu() {
use core_types::ops::{Convert, ConvertAsync};
use core_types::transform::Footprint;
use raster_types::{CPU, GPU};
use wgpu_executor::shader_runtime::raster_kernel_runtime::RasterKernelRuntime;
use wgpu_executor::{WgpuExecutor, WgpuPipelineCache};
futures::executor::block_on(async {
let Some(executor) = WgpuExecutor::new().await else { return };
let pipeline = WgpuPipelineCache::default();
executor.pipeline_init::<RasterKernelRuntime>(&pipeline);
let pipeline = Item::new_from_element(pipeline);
// A row of backdrops from black to white, overlaid by sources across both halves of Vivid Light
let steps = 11;
let backdrops = (0..steps).map(|step| step as f32 / (steps - 1) as f32);
let image = Image {
width: steps,
height: 1,
data: backdrops.map(|value| Color::from_rgbaf32_unchecked(value, value, value, 1.)).collect(),
};
for source in [0., 0.1, 0.25, 0.4, 0.5, 0.6, 0.75, 0.9, 1.] {
let color = Color::from_rgbaf32_unchecked(source, source, source, 1.);
let cpu = Item::new_from_element(Raster::new_cpu(image.clone()));
let cpu = super::color_overlay((), cpu, color.into(), BlendMode::VividLight.into(), 100_f64.into(), pipeline.clone()).unwrap();
let uploaded: Raster<GPU> = Raster::new_cpu(image.clone()).convert(Footprint::DEFAULT, executor.clone());
let gpu = super::color_overlay((), Item::new_from_element(uploaded), color.into(), BlendMode::VividLight.into(), 100_f64.into(), pipeline.clone()).unwrap();
let gpu: Raster<CPU> = gpu.into_element().convert(Footprint::DEFAULT, executor.clone()).await;
for (cpu, gpu) in cpu.element().data.iter().zip(&gpu.data) {
assert!((cpu.r() - gpu.r()).abs() < 2e-3, "source {source}: CPU {cpu:?} against GPU {gpu:?}");
}
}
});
}
#[test]
fn mix_colors_paints_over_at_its_opacity() {
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
@@ -348,6 +348,55 @@ impl Lut {
None => result,
}
}
/// The mapping as one grid, which [`Lut::apply`] matches by tetrahedral interpolation of the input normalized over the grid's domain:
/// the 3D table itself when the mapping is nothing more, otherwise the whole mapping sampled at `GRID_SIZE` points per axis across 0 to 1.
pub fn grid(&self) -> LutGrid {
if self.lab_encoding.is_none()
&& self.input_curves.is_none()
&& self.output_stages.is_empty()
&& let Some(LutTable::ThreeDimensional { size, red_fastest, entries }) = &self.table
&& size[0] == size[1]
&& size[1] == size[2]
{
let size = size[0];
let entries = if *red_fastest {
entries.clone()
} else {
(0..size.pow(3))
.map(|index| entries[((index % size) * size + index / size % size) * size + index / (size * size)])
.collect()
};
return LutGrid {
domain_min: self.domain_min,
domain_max: self.domain_max,
size,
entries,
};
}
let last = (GRID_SIZE - 1) as f32;
let entries = (0..GRID_SIZE.pow(3))
.map(|index| self.apply([index % GRID_SIZE, index / GRID_SIZE % GRID_SIZE, index / (GRID_SIZE * GRID_SIZE)].map(|step| step as f32 / last)))
.collect();
LutGrid {
domain_min: [0.; 3],
domain_max: [1.; 3],
size: GRID_SIZE,
entries,
}
}
}
/// The points per axis of the grid that samples a mapping holding more than one 3D table.
const GRID_SIZE: usize = 33;
/// A cube of `size` entries per axis, red fastest, then green, then blue, spanning the input range `domain_min..domain_max`.
pub struct LutGrid {
pub domain_min: [f32; 3],
pub domain_max: [f32; 3],
pub size: usize,
pub entries: Vec<[f32; 3]>,
}
/// Gamma-encoded sRGB to CIELAB against the D50 white of the ICC profile connection space.
+186 -5
View File
@@ -1,22 +1,39 @@
use crate::gpu_params;
use crate::raster_kernel::{RasterKernel, Wgsl, raster_kernel_pipeline, run_raster_kernel};
use core_types::NodeError;
use core_types::color::Color;
use core_types::context::Ctx;
use core_types::list::Item;
use core_types::ops::ConvertAsync;
use core_types::transform::Footprint;
use glam::DAffine2;
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
use raster_types::Image;
use raster_types::{CPU, Raster};
use raster_types::{CPU, GPU, Raster, Storage};
use std::cmp::{max, min};
use wgpu_executor::WgpuPipelineCache;
use wgpu_executor::shader_runtime::raster_kernel_runtime::RasterKernelInput;
#[node_macro::node(category("Raster: Filter"), icon("NodeDehaze"), memoize)]
fn dehaze(
#[node_macro::node(category("Raster: Filter"), icon("NodeDehaze"), memoize, footprint_invariant, placeholder = pending_dehaze, version(2))]
async fn dehaze<T: DehazeRaster + Clone>(
_: impl Ctx,
image_frame: Item<Raster<CPU>>,
#[implementations(Raster<CPU>, Raster<GPU>)] image_frame: Item<T>,
#[unit("%")]
#[range]
#[hard(0..100)]
strength: Item<f64>,
) -> Item<Raster<CPU>> {
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, NodeError> {
let strength = *strength.element();
T::dehaze(image_frame, strength, pipeline.element()).await
}
fn pending_dehaze<T: Clone>(image_frame: &Item<T>, _strength: &Item<f64>, _pipeline: &Item<WgpuPipelineCache>) -> Item<T> {
image_frame.clone()
}
fn dehaze_cpu(image_frame: Item<Raster<CPU>>, strength: f64) -> Item<Raster<CPU>> {
let (image, attributes) = image_frame.into_parts();
let (width, height) = (image.width, image.height);
@@ -36,6 +53,161 @@ fn dehaze(
Item::from_parts(Raster::new_cpu(dehazed_image), attributes)
}
/// A raster the Dehaze node processes, on the CPU or the GPU.
pub trait DehazeRaster: Sized {
fn dehaze(image: Item<Self>, strength: f64, pipeline: &WgpuPipelineCache) -> impl Future<Output = Result<Item<Self>, NodeError>> + Send;
}
impl DehazeRaster for Raster<CPU> {
async fn dehaze(image: Item<Self>, strength: f64, _: &WgpuPipelineCache) -> Result<Item<Self>, NodeError> {
Ok(dehaze_cpu(image, strength))
}
}
fn dehaze_input(raster: &Raster<GPU>) -> RasterKernelInput<'_> {
RasterKernelInput {
raster,
output_to_texel: DAffine2::IDENTITY,
}
}
impl DehazeRaster for Raster<GPU> {
/// Runs the CPU's algorithm in float without its 8-bit quantization, downloading the dark channel to choose the atmospheric light exactly as the CPU does.
/// The guided filter's intermediates stay in the executor's raster format rather than `FILTERABLE_FORMAT` since its variances lose their precision at half-float.
async fn dehaze(image: Item<Self>, strength: f64, pipeline: &WgpuPipelineCache) -> Result<Item<Self>, NodeError> {
if image.element().is_empty() {
return Ok(image);
}
let executor = pipeline.executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to process a GPU raster"))?;
let (raster, attributes) = image.into_parts();
let size = raster.size();
let radius = (PATCH_SIZE / 2) as i32;
let eroded = run_raster_kernel(&DehazeErode { radius, vertical: false }, vec![dehaze_input(&raster)], size, pipeline)?;
let dark_channel = run_raster_kernel(&DehazeErode { radius, vertical: true }, vec![dehaze_input(&eroded)], size, pipeline)?;
let atmospheric_light = estimate_atmospheric_light_gpu(&dark_channel.clone().convert(Footprint::DEFAULT, executor).await);
let radius = RADIUS as i32;
let guide = DehazeGuideHorizontal {
radius,
strength: (strength / 100.) as f32,
};
let guide = run_raster_kernel(&guide, vec![dehaze_input(&dark_channel)], size, pipeline)?;
let coefficients = DehazeGuideVertical { radius, epsilon: EPSILON as f32 };
let coefficients = run_raster_kernel(&coefficients, vec![dehaze_input(&guide)], size, pipeline)?;
let coefficients = run_raster_kernel(&DehazeCoefficientsHorizontal { radius }, vec![dehaze_input(&coefficients)], size, pipeline)?;
let recover = DehazeRecover {
radius,
minimum_transmission: TX,
atmospheric_light,
};
let dehazed = run_raster_kernel(&recover, vec![dehaze_input(&coefficients), dehaze_input(&raster)], size, pipeline)?;
Ok(Item::from_parts(dehazed, attributes))
}
}
/// The average color of the pixels with the brightest dark channel, chosen like [`estimate_atmospheric_light`], from each pixel's color with its dark channel as alpha.
fn estimate_atmospheric_light_gpu(dark_channel: &Raster<CPU>) -> Color {
let pixels = &dark_channel.data;
let num_pixels = ((TOP_PERCENT / 100.) * pixels.len() as f64).ceil() as usize;
let mut order: Vec<usize> = (0..pixels.len()).collect();
order.select_nth_unstable_by(num_pixels - 1, |&a, &b| pixels[b].a().total_cmp(&pixels[a].a()).then(a.cmp(&b)));
let mut atm_sum = [0., 0., 0.];
for &index in &order[..num_pixels] {
let pixel = pixels[index];
atm_sum[0] += pixel.r() as f64;
atm_sum[1] += pixel.g() as f64;
atm_sum[2] += pixel.b() as f64;
}
let num_pixels = num_pixels as f64;
Color::from_rgbaf32_unchecked((atm_sum[0] / num_pixels) as f32, (atm_sum[1] / num_pixels) as f32, (atm_sum[2] / num_pixels) as f32, 1.)
}
gpu_params! {
/// One axis of the dark channel's erosion, the horizontal pass eroding each pixel's darkest channel and the vertical pass the horizontal pass's alpha,
/// both writing the pixel's color clamped to 0 to 1 with the eroded value as alpha.
#[derive(Clone)]
struct DehazeErode {
radius: i32,
vertical: bool,
}
}
impl RasterKernel for DehazeErode {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/dehaze_erode.wgsl"))
}
}
gpu_params! {
/// Horizontal means of the guidance luma, the transmission, the luma squared, and the luma times the transmission.
#[derive(Clone)]
struct DehazeGuideHorizontal {
radius: i32,
strength: f32,
}
}
impl RasterKernel for DehazeGuideHorizontal {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/dehaze_guide_horizontal.wgsl"))
}
}
gpu_params! {
/// Completes the guided filter's means vertically into its linear coefficients.
#[derive(Clone)]
struct DehazeGuideVertical {
radius: i32,
epsilon: f32,
}
}
impl RasterKernel for DehazeGuideVertical {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/dehaze_guide_vertical.wgsl"))
}
}
gpu_params! {
#[derive(Clone)]
struct DehazeCoefficientsHorizontal {
radius: i32,
}
}
impl RasterKernel for DehazeCoefficientsHorizontal {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/dehaze_coefficients_horizontal.wgsl"))
}
}
gpu_params! {
/// Completes the coefficients' means vertically into the refined transmission, recovering the image from its haze.
#[derive(Clone)]
struct DehazeRecover {
radius: i32,
minimum_transmission: f32,
atmospheric_light: Color,
}
}
impl RasterKernel for DehazeRecover {
const INPUTS: usize = 2;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/dehaze_recover.wgsl"))
}
}
// There is no real point in modifying these values because they do not change the final result all that much.
// The authors of the paper recommended using these values to get a reasonable balance of performance and quality.
// TODO: The patch size and guided filter radius are whole source pixels, so the effect's scale follows the image's resolution.
@@ -283,4 +455,13 @@ mod tests {
}
}
}
#[test]
fn dehaze_runs_on_a_cpu_raster_without_a_gpu() {
let image = Item::new_from_element(Raster::new_cpu(Image::new(4, 4, Color::WHITE)));
let dehazed = futures::executor::block_on(Raster::<CPU>::dehaze(image, 50., &WgpuPipelineCache::default())).unwrap();
assert_eq!((dehazed.element().width, dehazed.element().height), (4, 4));
}
}
+261 -11
View File
@@ -1,11 +1,18 @@
use crate::parallel_rows::fill_rows;
use crate::raster_kernel::{FILTERABLE_FORMAT, RasterKernel, ToGpuParams, Wgsl, raster_kernel_pipeline, run_raster_kernel, run_raster_kernel_with_format};
use crate::{gpu_param_enum, gpu_params};
use bytemuck::{Pod, Zeroable};
use core_types::color::{Alpha, Color, Pixel, RGB};
use core_types::context::Ctx;
use core_types::list::Item;
use core_types::{Interrupt, NodeError};
use glam::DAffine2;
use num_enum::IntoPrimitive;
use raster_types::Image;
use raster_types::{Bitmap, BitmapMut};
use raster_types::{CPU, Raster};
use raster_types::{CPU, GPU, Raster, Storage};
use wgpu_executor::WgpuPipelineCache;
use wgpu_executor::shader_runtime::raster_kernel_runtime::RasterKernelInput;
/// Working-buffer pixel for the blur algorithms' `gamma` mode: premultiplied sRGB-gamma `f32` channels.
/// Only used internally so the working buffer's color space is reflected in the type instead of stuffed into `Color` (which is linear-light by invariant).
@@ -84,11 +91,12 @@ fn unpremultiply_gamma_to_linear(buffer: Image<PremultipliedGammaPixel>) -> Imag
}
/// Blurs the image with a Gaussian or box blur kernel filter.
#[node_macro::node(category("Raster: Filter"), icon("NodeBlur"))]
fn blur(
#[node_macro::node(category("Raster: Filter"), icon("NodeBlur"), version(2))]
fn blur<T: BlurRaster>(
_: impl Ctx,
/// The image to be blurred.
image_frame: Item<Raster<CPU>>,
#[implementations(Raster<CPU>, Raster<GPU>)]
image_frame: Item<T>,
/// The radius of the blur kernel.
#[unit(" px")]
#[range]
@@ -99,9 +107,13 @@ fn blur(
box_blur: Item<bool>,
/// Opt to incorrectly apply the filter with color calculations in gamma space for compatibility with the results from other software.
gamma: Item<bool>,
) -> Item<Raster<CPU>> {
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
let (radius, box_blur, gamma) = (*radius.element(), *box_blur.element(), *gamma.element());
Ok(T::blur(image_frame, radius, box_blur, gamma, pipeline.element())?)
}
fn blur_cpu(image_frame: Item<Raster<CPU>>, radius: f64, box_blur: bool, gamma: bool) -> Item<Raster<CPU>> {
let (image, attributes) = image_frame.into_parts();
// TODO: Scale the radius through the footprint so it acts as the document-space length its Pixels unit promises, with a
@@ -119,18 +131,20 @@ fn blur(
}
/// Applies a median filter to reduce noise while preserving edges.
#[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), memoize)]
fn median_filter(
#[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), memoize, version(2))]
fn median_filter<T: MedianFilterRaster>(
_: impl Ctx,
/// The image to be filtered.
image_frame: Item<Raster<CPU>>,
#[implementations(Raster<CPU>, Raster<GPU>)]
image_frame: Item<T>,
/// The radius of the filter kernel. Larger values remove more noise but may blur fine details.
#[unit(" px")]
#[range]
#[hard(0..)]
#[soft(..50)]
radius: Item<f64>,
) -> Item<Raster<CPU>> {
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
let radius = *radius.element();
let (image, attributes) = image_frame.into_parts();
@@ -141,10 +155,53 @@ fn median_filter(
// Minimum filter radius
image
} else {
Raster::new_cpu(median_filter_algorithm(image.into_data(), radius as u32))
T::median_filter(image, radius as u32, pipeline.element())?
};
Item::from_parts(filtered_image, attributes)
Ok(Item::from_parts(filtered_image, attributes))
}
/// A raster the Median Filter node processes, on the CPU or the GPU.
pub trait MedianFilterRaster: Sized {
fn median_filter(image: Self, radius: u32, pipeline: &WgpuPipelineCache) -> Result<Self, NodeError>;
}
impl MedianFilterRaster for Raster<CPU> {
fn median_filter(image: Self, radius: u32, _: &WgpuPipelineCache) -> Result<Self, NodeError> {
Ok(Raster::new_cpu(median_filter_algorithm(image.into_data(), radius)))
}
}
impl MedianFilterRaster for Raster<GPU> {
fn median_filter(image: Self, radius: u32, pipeline: &WgpuPipelineCache) -> Result<Self, NodeError> {
if image.is_empty() {
return Ok(image);
}
let size = image.size();
let kernel = MedianWindow {
radius: radius.min(size.max_element()),
};
let input = RasterKernelInput {
raster: &image,
output_to_texel: DAffine2::IDENTITY,
};
run_raster_kernel(&kernel, vec![input], size, pipeline)
}
}
gpu_params! {
#[derive(Clone)]
struct MedianWindow {
radius: u32,
}
}
impl RasterKernel for MedianWindow {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/median_filter.wgsl"))
}
}
// 1D gaussian kernel
@@ -296,6 +353,183 @@ where
y_axis
}
/// A raster the Blur node processes, on the CPU or the GPU.
pub trait BlurRaster: Sized {
fn blur(image: Item<Self>, radius: f64, box_blur: bool, gamma: bool, pipeline: &WgpuPipelineCache) -> Result<Item<Self>, NodeError>;
}
impl BlurRaster for Raster<CPU> {
fn blur(image: Item<Self>, radius: f64, box_blur: bool, gamma: bool, _: &WgpuPipelineCache) -> Result<Item<Self>, NodeError> {
Ok(blur_cpu(image, radius, box_blur, gamma))
}
}
/// The farthest texel from the center a blur pass weighs, beyond which the image is first halved until the kernel fits.
const MAX_BLUR_REACH: i32 = 64;
/// The radius of a blur over texels `scale` image pixels wide, and the farthest texel from the center it weighs, as the CPU kernels size them at a `scale` of 1.
///
/// A box covers its whole texels and a fraction of the texel at each end, which keeps the window as wide as the CPU's whole pixel window once halved,
/// and a Gaussian leaves out the blur that halving and doubling the image add.
fn blur_extent(radius: f64, box_blur: bool, scale: u32) -> (f32, i32) {
let scale = scale as f64;
if box_blur {
let radius = ((radius as i32) as f64 + 0.5) / scale - 0.5;
(radius as f32, radius.ceil() as i32)
} else {
let radius = (radius * radius - (scale * scale - 1.) / 3.).max(0.).sqrt() / scale;
(radius as f32, (3. * radius).ceil() as i32)
}
}
fn blur_input(raster: &Raster<GPU>) -> Vec<RasterKernelInput<'_>> {
vec![RasterKernelInput {
raster,
output_to_texel: DAffine2::IDENTITY,
}]
}
impl BlurRaster for Raster<GPU> {
/// Each pass sums premultiplied colors into a [`FILTERABLE_FORMAT`] intermediate, and a kernel reaching past [`MAX_BLUR_REACH`] runs on the image halved
/// until it fits, weighing each halved texel by how much of the image it covers, then is scaled back up bilinearly, approximating the CPU's blur.
fn blur(image: Item<Self>, radius: f64, box_blur: bool, gamma: bool, pipeline: &WgpuPipelineCache) -> Result<Item<Self>, NodeError> {
if radius < 0.1 || image.element().is_empty() {
return Ok(image);
}
let (raster, attributes) = image.into_parts();
let space = if gamma { BlurSpace::Gamma } else { BlurSpace::Linear };
let size = raster.size();
let full_size = size.as_ivec2().to_array();
let mut levels = 0;
while blur_extent(radius, box_blur, 1 << levels).1 > MAX_BLUR_REACH {
levels += 1;
}
let level_size = |level: u32| size.map(|side| side.div_ceil(1 << level));
let mut source = raster;
for level in 1..=levels {
let kernel = BlurHalve {
space: if level == 1 { space } else { BlurSpace::Premultiplied },
scale: 1 << (level - 1),
full_size,
};
source = run_raster_kernel_with_format(&kernel, blur_input(&source), level_size(level), FILTERABLE_FORMAT, pipeline)?;
}
let (radius, reach) = blur_extent(radius, box_blur, 1 << levels);
let pass = BlurPass {
radius,
reach,
box_blur,
space: if levels == 0 { space } else { BlurSpace::Premultiplied },
scale: 1 << levels,
full_size,
};
let horizontal = run_raster_kernel_with_format(&BlurHorizontal(pass.clone()), blur_input(&source), level_size(levels), FILTERABLE_FORMAT, pipeline)?;
if levels == 0 {
let blurred = run_raster_kernel(&BlurVertical(pass), blur_input(&horizontal), size, pipeline)?;
return Ok(Item::from_parts(blurred, attributes));
}
let vertical = run_raster_kernel_with_format(&BlurVertical(pass), blur_input(&horizontal), level_size(levels), FILTERABLE_FORMAT, pipeline)?;
let upsample = BlurUpsample { scale: (1 << levels) as f32, space };
let blurred = run_raster_kernel(&upsample, blur_input(&vertical), size, pipeline)?;
Ok(Item::from_parts(blurred, attributes))
}
}
/// The colors a blur pass reads from its input or writes to its output, around the premultiplied colors it sums.
#[derive(Clone, Copy, IntoPrimitive)]
#[repr(u32)]
enum BlurSpace {
Premultiplied,
Linear,
Gamma,
}
gpu_param_enum!(u32: BlurSpace);
gpu_params! {
/// Averages each 2x2 block of texels `scale` image pixels wide, weighed by how much of the `full_size` image each covers.
#[derive(Clone)]
struct BlurHalve {
space: BlurSpace,
scale: i32,
full_size: [i32; 2],
}
}
impl RasterKernel for BlurHalve {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_halve.wgsl")))
}
}
gpu_params! {
/// One axis of a blur over texels `scale` image pixels wide, each weighed by how much of the `full_size` image it covers.
#[derive(Clone)]
struct BlurPass {
radius: f32,
reach: i32,
box_blur: bool,
space: BlurSpace,
scale: i32,
full_size: [i32; 2],
}
}
struct BlurHorizontal(BlurPass);
impl ToGpuParams for BlurHorizontal {
type Params = BlurPass;
fn to_params(&self) -> BlurPass {
self.0.clone()
}
}
impl RasterKernel for BlurHorizontal {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_horizontal.wgsl")))
}
}
/// Reads its input in pairs of texels sampled bilinearly between them, so the input must be in [`FILTERABLE_FORMAT`].
struct BlurVertical(BlurPass);
impl ToGpuParams for BlurVertical {
type Params = BlurPass;
fn to_params(&self) -> BlurPass {
self.0.clone()
}
}
impl RasterKernel for BlurVertical {
const INPUTS: usize = 1;
const FILTERED: bool = true;
fn wgsl() -> Wgsl {
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_vertical.wgsl")))
}
}
gpu_params! {
#[derive(Clone)]
struct BlurUpsample {
scale: f32,
space: BlurSpace,
}
}
impl RasterKernel for BlurUpsample {
const INPUTS: usize = 1;
const FILTERED: bool = true;
fn wgsl() -> Wgsl {
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_upsample.wgsl")))
}
}
fn median_filter_algorithm(original_buffer: Image<Color>, radius: u32) -> Image<Color> {
let (width, height) = original_buffer.dimensions();
let mut output = Image::new(width, height, Color::TRANSPARENT);
@@ -353,3 +587,19 @@ fn median_quickselect(values: &mut [f32]) -> f32 {
// Use total_cmp for safe NaN handling instead of partial_cmp().unwrap()
*values.select_nth_unstable_by(mid, |a, b| a.total_cmp(b)).1
}
#[cfg(test)]
mod tests {
use super::*;
use raster_types::Image;
#[test]
fn blur_runs_on_a_cpu_raster_without_a_gpu() {
let image = Item::new_from_element(Raster::new_cpu(Image::new(4, 4, Color::WHITE)));
let pipeline = Item::new_from_element(WgpuPipelineCache::default());
let blurred: Item<Raster<CPU>> = blur((), image, Item::new_from_element(2.), Item::new_from_element(false), Item::new_from_element(false), pipeline).unwrap();
assert_eq!((blurred.element().width, blurred.element().height), (4, 4));
}
}
@@ -1,10 +1,13 @@
use crate::raster_kernel::{ReadPixels, raster_kernel_pipeline};
use color::{ColorSpace, Oklab};
use core_types::NodeError;
use core_types::color::Color;
use core_types::context::Ctx;
use core_types::list::{Item, List};
use raster_types::{CPU, Raster};
use raster_types::{CPU, GPU, Image, Raster};
use std::collections::BinaryHeap;
use std::ops::{AddAssign, SubAssign};
use wgpu_executor::WgpuPipelineCache;
/// Histogram resolution along each OkLab axis.
const CELLS_PER_AXIS: usize = 32;
@@ -14,21 +17,31 @@ const TABLE_SIDE: usize = CELLS_PER_AXIS + 1;
const OKLAB_GAMUT_RANGES: [(f32, f32); 3] = [(0., 1.), (-0.24, 0.28), (-0.32, 0.2)];
/// Finds the colors that best represent the distinct color ranges in an image, ignoring transparent areas.
#[node_macro::node(category("Color"), icon("NodeImageColorPalette"), memoize, footprint_invariant)]
fn image_color_palette(
#[node_macro::node(category("Color"), icon("NodeImageColorPalette"), memoize, footprint_invariant, placeholder = pending_palette, version(2))]
async fn image_color_palette<T: ReadPixels + Send + 'static>(
_: impl Ctx,
/// The image to find colors in.
image: Item<Raster<CPU>>,
#[implementations(Raster<CPU>, Raster<GPU>)]
image: Item<T>,
/// How many colors to find. Raising it adds a color at the end and may adjust one existing color, leaving the rest as they were.
#[default(4)]
#[hard(1..)]
count: Item<i64>,
) -> List<Color> {
let count = *count.element() as usize;
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<List<Color>, NodeError> {
let image = image.into_element().read_pixels(pipeline.element()).await?;
Ok(palette_colors(image.data(), *count.element() as usize))
}
fn pending_palette<T>(_image: &Item<T>, _count: &Item<i64>, _pipeline: &Item<WgpuPipelineCache>) -> List<Color> {
List::new()
}
/// The colors that best represent the distinct color ranges in `image`, ignoring transparent areas.
fn palette_colors(image: &Image<Color>, count: usize) -> List<Color> {
// O(n) binning of the image's n pixels into an OkLab histogram, weighted by alpha so transparent pixels are ignored
let mut cumulative = vec![Moments::default(); TABLE_SIDE.pow(3)];
for pixel in image.element().data.iter() {
for pixel in image.data.iter() {
let weight = (pixel.a().clamp(0., 1.) * f32::from(u16::MAX)).round() as i64;
if weight == 0 {
continue;
@@ -235,7 +248,7 @@ mod test {
data,
});
let palette = image_color_palette((), Item::new_from_element(image), Item::new_from_element(count));
let palette = palette_colors(image.data(), count as usize);
palette.iter_element_values().copied().collect()
}
@@ -325,4 +338,13 @@ mod test {
let colors = palette(&[(Color::BLACK, 50), (Color::WHITE, 50)], 1);
assert_colors_near(&colors, &[Color::from_rgbf32_unchecked(0.125, 0.125, 0.125)]);
}
#[test]
fn the_palette_reads_a_cpu_raster_without_a_gpu() {
let image = Raster::new_cpu(Image::new(4, 4, Color::WHITE));
let pixels = futures::executor::block_on(image.read_pixels(&WgpuPipelineCache::default())).unwrap();
assert_eq!(palette_colors(&pixels, 1).len(), 1);
}
}
+1 -1
View File
@@ -1,4 +1,3 @@
pub mod adjust;
pub mod adjustments;
pub mod blending_nodes;
pub mod color_lookup_table;
@@ -6,4 +5,5 @@ pub mod dehaze;
pub mod filter;
pub mod image_color_palette;
pub mod parallel_rows;
pub mod raster_kernel;
pub mod std_nodes;
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more