diff --git a/Cargo.lock b/Cargo.lock index 28b5f85218..898ec264a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2675,7 +2675,6 @@ dependencies = [ "math-nodes", "node-macro", "path-bool-nodes", - "raster-kernels", "raster-nodes", "rendering", "repeat-nodes", @@ -8080,7 +8079,6 @@ dependencies = [ "log", "node-macro", "ollev", - "raster-kernels", "raster-types", "vector-types", ] diff --git a/node-graph/nodes/gstd/Cargo.toml b/node-graph/nodes/gstd/Cargo.toml index 33c72ff641..c0af14311d 100644 --- a/node-graph/nodes/gstd/Cargo.toml +++ b/node-graph/nodes/gstd/Cargo.toml @@ -45,7 +45,6 @@ wgpu-executor = { workspace = true } core-types = { workspace = true } vector-types = { workspace = true } graphic-types = { workspace = true } -raster-kernels = { workspace = true } svg-convert = { workspace = true } blending-nodes = { workspace = true } text-nodes = { workspace = true } diff --git a/node-graph/nodes/gstd/src/platform_application_io.rs b/node-graph/nodes/gstd/src/platform_application_io.rs index 2c1aedce30..b72ede6f1a 100644 --- a/node-graph/nodes/gstd/src/platform_application_io.rs +++ b/node-graph/nodes/gstd/src/platform_application_io.rs @@ -12,7 +12,7 @@ pub use graph_craft::document::value::RenderOutputType; #[cfg(target_family = "wasm")] pub use graphene_canvas_utils as canvas_utils; use graphic_types::Graphic; -use graphic_types::raster_types::{CPU, Raster}; +use graphic_types::raster_types::{CPU, Pixels, Raster}; use graphic_types::raster_types::{Image, ImageError}; use rendering::{Render, RenderParams}; use std::sync::Arc; @@ -172,8 +172,8 @@ fn string_to_bytes(_: impl Ctx, string: Item) -> Item { /// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files. #[node_macro::node(category("Data: I/O"), icon("NodeImageToBytes"), name("Image to Bytes"))] -fn image_to_bytes(_: impl Ctx, image: Item>) -> Item { - let bytes: Vec = raster_kernels::evaluate_raster_effects(image) +fn image_to_bytes(_: impl Ctx, image: Item) -> Item { + let bytes: Vec = image .element() .data .iter() diff --git a/node-graph/nodes/raster/src/dehaze.rs b/node-graph/nodes/raster/src/dehaze.rs index 7e41632d0d..a60b4b5d0c 100644 --- a/node-graph/nodes/raster/src/dehaze.rs +++ b/node-graph/nodes/raster/src/dehaze.rs @@ -2,15 +2,14 @@ use core_types::context::Ctx; use core_types::list::Item; use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage}; use ndarray::{Array2, ArrayBase, Dim, OwnedRepr}; -use raster_kernels::evaluate_raster_effects; use raster_types::Image; -use raster_types::{CPU, Raster}; +use raster_types::{CPU, Pixels, Raster}; use std::cmp::{max, min}; #[node_macro::node(category("Raster: Filter"), icon("NodeDehaze"), memoize)] fn dehaze( _: impl Ctx, - image_frame: Item>, + image_frame: Item, #[unit("%")] #[range] #[hard(0..100)] @@ -18,7 +17,8 @@ fn dehaze( ) -> Item> { let strength = *strength.element(); - let (image, attributes) = evaluate_raster_effects(image_frame).into_parts(); + let (pixels, attributes) = image_frame.into_parts(); + let image = pixels.into_raster(); let (width, height) = (image.width, image.height); // Prepare the image data for processing diff --git a/node-graph/nodes/raster/src/image_color_palette.rs b/node-graph/nodes/raster/src/image_color_palette.rs index c6d6ff68b0..ae7fd5b679 100644 --- a/node-graph/nodes/raster/src/image_color_palette.rs +++ b/node-graph/nodes/raster/src/image_color_palette.rs @@ -2,8 +2,7 @@ use color::{ColorSpace, Oklab}; use core_types::color::Color; use core_types::context::Ctx; use core_types::list::{Item, List}; -use raster_kernels::evaluate_raster_effects; -use raster_types::{CPU, Raster}; +use raster_types::Pixels; use std::collections::BinaryHeap; use std::ops::{AddAssign, SubAssign}; @@ -19,14 +18,13 @@ const OKLAB_GAMUT_RANGES: [(f32, f32); 3] = [(0., 1.), (-0.24, 0.28), (-0.32, 0. fn image_color_palette( _: impl Ctx, /// The image to find colors in. - image: Item>, + image: Item, /// 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, ) -> List { let count = *count.element() as usize; - let image = evaluate_raster_effects(image); // 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)]; @@ -227,7 +225,7 @@ fn table_index(position: [usize; 3]) -> usize { #[cfg(test)] mod test { use super::*; - use raster_types::Image; + use raster_types::{Image, Raster}; fn palette(runs: &[(Color, usize)], count: i64) -> Vec { let data = runs.iter().flat_map(|&(color, length)| std::iter::repeat_n(color, length)).collect::>(); @@ -237,7 +235,7 @@ mod test { data, }); - let palette = image_color_palette((), Item::new_from_element(image), Item::new_from_element(count)); + let palette = image_color_palette((), Item::new_from_element(Pixels::new(image)), Item::new_from_element(count)); palette.iter_element_values().copied().collect() } diff --git a/node-graph/nodes/vectorize/Cargo.toml b/node-graph/nodes/vectorize/Cargo.toml index 79e45bdd6d..f906a16baf 100644 --- a/node-graph/nodes/vectorize/Cargo.toml +++ b/node-graph/nodes/vectorize/Cargo.toml @@ -19,7 +19,6 @@ workspace = true core-types = { workspace = true } vector-types = { workspace = true } raster-types = { workspace = true } -raster-kernels = { workspace = true } graphic-types = { workspace = true } graphene-hash = { workspace = true } node-macro = { workspace = true } diff --git a/node-graph/nodes/vectorize/src/lib.rs b/node-graph/nodes/vectorize/src/lib.rs index 61915c3492..feaf984a24 100644 --- a/node-graph/nodes/vectorize/src/lib.rs +++ b/node-graph/nodes/vectorize/src/lib.rs @@ -9,8 +9,7 @@ use core_types::runtime::Runtime; use core_types::{ATTR_TRANSFORM, CacheHash, Ctx, Poll, RuntimeHandle, SourceId}; use glam::{DAffine2, DVec2}; use graphic_types::Graphic; -use raster_kernels::evaluate_raster_effects; -use raster_types::{CPU, Raster}; +use raster_types::Pixels; use std::hash::{DefaultHasher, Hash, Hasher}; use std::time::Duration; @@ -42,7 +41,7 @@ const BROWSER_MAX_MEGABYTES: f64 = 1000.; fn vectorize( _: impl Ctx, /// The image to trace. - image: Item>, + image: Item, /// How much detail to keep, as a multiple of the default level read from how busy the image is. Higher values spend more segments on smaller features. #[default(1.)] #[hard(0.01..)] @@ -107,7 +106,7 @@ fn vectorize( } /// Runs one slice of the trace held in `slot`, starting a new trace if `slot` holds none for these inputs. -fn trace_slice(image: &Item>, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option, slot: &TraceSlot, slice: Duration) -> Poll> { +fn trace_slice(image: &Item, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option, slot: &TraceSlot, slice: Duration) -> Poll> { if image.element().width == 0 || image.element().height == 0 { slot.clear(); return Poll::Final(List::new()); @@ -118,9 +117,7 @@ fn trace_slice(image: &Item>, detail: f64, tolerance: f64, stages: o (detail.to_bits(), tolerance.to_bits(), max_pixels).hash(&mut hasher); [stages.translucency, stages.strokes, stages.primitives, stages.effects, stages.instancing, stages.path_gradients].hash(&mut hasher); - // The image's effects are carried out once for the whole trace, rather than on each slice let start = || { - let image = evaluate_raster_effects(image.clone()); let raster = image.element(); let (width, height) = (raster.width as usize, raster.height as usize); let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM); @@ -154,23 +151,23 @@ mod test { use super::*; use core_types::Color; use core_types::runtime::{AsyncRuntime, Spawn, Task}; - use raster_types::Image; + use raster_types::{Image, Raster}; use std::sync::{Arc, Mutex}; use std::task::{Context, Waker}; /// An image of `width` by `height` pixels colored by `color` at each pixel's column and row. - fn raster(width: u32, height: u32, color: impl Fn(u32, u32) -> Color) -> Item> { + fn raster(width: u32, height: u32, color: impl Fn(u32, u32) -> Color) -> Item { let data = (0..width * height).map(|index| color(index % width, index / width)).collect(); - Item::new_from_element(Raster::new_cpu(Image { width, height, data })) + Item::new_from_element(Pixels::new(Raster::new_cpu(Image { width, height, data }))) } /// One slice of `image` traced at default settings by the node holding `slot`. - fn slice(image: &Item>, slot: &TraceSlot) -> Poll> { + fn slice(image: &Item, slot: &TraceSlot) -> Poll> { trace_slice(image, 1., 1., ollev::Stages::ALL, None, slot, SLICE) } /// The shapes traced from `image` at `detail` and `tolerance` by a node of its own, slice by slice. - fn trace(image: &Item>, detail: f64, tolerance: f64) -> List { + fn trace(image: &Item, detail: f64, tolerance: f64) -> List { let slot = TraceSlot::default(); loop { match trace_slice(image, detail, tolerance, ollev::Stages::ALL, None, &slot, SLICE) { @@ -184,7 +181,7 @@ mod test { const DARK: Color = Color::from_rgbaf32_unchecked(0.05, 0.1, 0.4, 1.); /// A dark ring from `inner` to `inner + width` pixels out from the middle of a light square of `size` pixels. - fn ring(size: u32, inner: f64, width: f64) -> Item> { + fn ring(size: u32, inner: f64, width: f64) -> Item { let center = size as f64 / 2.; raster(size, size, |x, y| { let distance = DVec2::new(x as f64 + 0.5, y as f64 + 0.5).distance(DVec2::splat(center)); @@ -228,7 +225,7 @@ mod test { } /// Shapes partly over one another: rings, a disc and a ramp, enough to keep a trace busy for many short slices. - fn busy(size: u32) -> Item> { + fn busy(size: u32) -> Item { let center = DVec2::splat(size as f64 / 2.); raster(size, size, |x, y| { let point = DVec2::new(x as f64 + 0.5, y as f64 + 0.5); @@ -351,7 +348,7 @@ mod test { const SOURCE: SourceId = SourceId(7); /// One evaluation of the node holding `slot` on `image`, with every stage on. - fn evaluate(slot: &TraceSlot, image: &Item>, runtime: &AsyncRuntime) -> Poll> { + fn evaluate(slot: &TraceSlot, image: &Item, runtime: &AsyncRuntime) -> Poll> { let one = || Item::new_from_element(1.); let on = || Item::new_from_element(true); vectorize( diff --git a/node-graph/preprocessor/src/readback_tests.rs b/node-graph/preprocessor/src/readback_tests.rs index 85f4b424ac..2fba4fec3b 100644 --- a/node-graph/preprocessor/src/readback_tests.rs +++ b/node-graph/preprocessor/src/readback_tests.rs @@ -8,6 +8,7 @@ use core_types::{ATTR_TRANSFORM, Color, Ctx, ExtractIndex, OwnedContextImpl, Pol use glam::{DAffine2, DVec2}; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::graphene_compiler::Compiler; +use graphene_std::platform_application_io::Resource; use graphene_std::raster::{CPU, Image, Pixels, Raster}; use graphene_std::vector::style::StrokeAlign; use graphic_types::{Adjustment, Effect, EffectOperation, Graphic, stamp_effect}; @@ -399,3 +400,189 @@ fn a_reader_without_a_gpu_fails() { }; assert!(error.error().is::(), "the reader failed with {error}"); } + +/// An image of 32 by 32 pixels with a dark disc and a red band on a light ground, enough for every reader to find shapes and colors in, inverted by an effect if `inverted`. +fn varied_image(inverted: bool) -> Item> { + let data = (0..32 * 32) + .map(|index| { + let (x, y) = ((index % 32) as f64, (index / 32) as f64); + if DVec2::new(x - 12., y - 12.).length() < 8. { + Color::from_rgbaf32_unchecked(0.05, 0.1, 0.3, 1.) + } else if y >= 24. { + Color::from_rgbaf32_unchecked(0.8, 0.1, 0.1, 1.) + } else { + Color::from_rgbaf32_unchecked(0.9, 0.85, 0.7, 1.) + } + }) + .collect(); + + let mut image = Item::new_from_element(Raster::new_cpu(Image { width: 32, height: 32, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(32.))); + if inverted { + stamp_effect(&mut image, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert))); + } + image +} + +/// The varied image as it is. +#[node_macro::node(category(""))] +fn plain_varied_image(_: impl Ctx, _primary: ()) -> Item> { + varied_image(false) +} + +/// The varied image inverted by its effect. +#[node_macro::node(category(""))] +fn inverted_varied_image(_: impl Ctx, _primary: ()) -> Item> { + varied_image(true) +} + +/// Whether two outputs of a reader are equal, as tagged values where they convert or else as one of the types the readers output. +/// `None` for outputs of a type this can't compare. +fn outputs_equal(a: &core_types::registry::Any, b: &core_types::registry::Any) -> Option { + if let (Ok(a), Ok(b)) = (TaggedValue::try_from_std_any_ref(&**a), TaggedValue::try_from_std_any_ref(&**b)) { + return Some(a == b); + } + + macro_rules! compare_as { + ($($ty:ty),*) => {$( + if let (Some(a), Some(b)) = (a.downcast_ref::<$ty>(), b.downcast_ref::<$ty>()) { + return Some(a == b); + } + )*}; + } + compare_as!(Item>, List>, List, List); + + // Resources compare by their bytes + if let (Some(a), Some(b)) = (a.downcast_ref::>(), b.downcast_ref::>()) { + return Some(a.element().as_ref() == b.element().as_ref()); + } + + None +} + +/// Every node input taking `Pixels`, by its node's identifier and its index, besides this module's own readers. +fn pixel_reading_inputs() -> Vec<(ProtoNodeIdentifier, usize)> { + let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap(); + let metadata_registry = core_types::registry::NODE_METADATA.lock().unwrap(); + let takes_pixels = |ty: &Type| matches!(ty.clone().normalize_rank().nested_type(), Type::Item(element) | Type::List(element) if **element == concrete!(Pixels)); + + let mut inputs: Vec<_> = (node_registry.iter()) + .filter(|(identifier, _)| metadata_registry.contains_key(*identifier) && ![read_pixels::IDENTIFIER, recorded_pixels::IDENTIFIER].contains(*identifier)) + .flat_map(|(identifier, implementations)| { + let indices: HashSet = (implementations.iter()) + .flat_map(|(_, node_io)| node_io.inputs.iter().enumerate().filter(|(_, ty)| takes_pixels(ty)).map(|(index, _)| index)) + .collect(); + indices.into_iter().map(|index| (identifier.clone(), index)) + }) + .collect(); + inputs.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1))); + inputs +} + +/// Every node input taking `Pixels` reads the pixels as drawn, so an image under an effect gives a different output than the image alone. +/// A node gaining such an input has to be added to the list below on purpose. +#[test] +fn every_pixel_reading_input_reads_the_image_with_its_effects() { + let inputs = pixel_reading_inputs(); + let identifiers: Vec<&str> = inputs.iter().map(|(identifier, _)| identifier.as_str()).collect(); + let mut readers = [ + graphene_std::platform_application_io::image_to_bytes::IDENTIFIER, + graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER, + graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER, + graphene_std::vectorize_nodes::vectorize::IDENTIFIER, + ]; + readers.sort_by(|a, b| a.as_str().cmp(b.as_str())); + assert_eq!(identifiers, readers.iter().map(ProtoNodeIdentifier::as_str).collect::>(), "the nodes reading pixels"); + + for (identifier, index) in inputs { + let mut node_inputs = default_inputs(&identifier); + node_inputs[index] = wire(); + let output = |source: ProtoNodeIdentifier| { + let compiled = Compiled::new(network(source, proto_node(identifier.clone(), node_inputs.clone()), 0))?; + Some(compiled.evaluate(None).0) + }; + let (Some(plain), Some(inverted)) = (output(plain_varied_image::IDENTIFIER), output(inverted_varied_image::IDENTIFIER)) else { + return; + }; + + let equal = outputs_equal(&plain, &inverted).unwrap_or_else(|| panic!("{} gives an output this test can't compare", identifier.as_str())); + assert!(!equal, "{} gives the same output for an image whether or not it's inverted by an effect", identifier.as_str()); + } +} + +/// A 96 by 96 image of gray noise, outlined so it reads back through a render, which Vectorize traces over several evaluations. +#[node_macro::node(category(""))] +fn outlined_noise(_: impl Ctx, _primary: ()) -> Item> { + // Pseudo-random grays from an xorshift sequence, so the trace finds many small regions + let mut state = 0x2545_f491_u32; + let data = (0..96 * 96) + .map(|_| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + let gray = (state % 256) as f32 / 255.; + Color::from_rgbaf32_unchecked(gray, gray, gray, 1.) + }) + .collect(); + + let mut image = Item::new_from_element(Raster::new_cpu(Image { width: 96, height: 96, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(96.))); + stamp_effect(&mut image, Effect::new(&outline())); + image +} + +/// Each slice of a trace bumps the generation of Vectorize's source, which mustn't read the image back again and so restart the trace. +#[test] +fn a_trace_of_read_back_pixels_runs_to_its_end() { + let mut inputs = default_inputs(&graphene_std::vectorize_nodes::vectorize::IDENTIFIER); + inputs[0] = wire(); + let Some(compiled) = Compiled::new(network(outlined_noise::IDENTIFIER, proto_node(graphene_std::vectorize_nodes::vectorize::IDENTIFIER, inputs), 0)) else { + return; + }; + + let (output, evaluations) = compiled.evaluate(None); + let traced = output.downcast::>().expect("Vectorize should output graphics"); + assert!(evaluations > 1, "the trace should take several slices"); + assert!(!traced.is_empty()); +} + +/// The node `identifier` with these `inputs`, its input fed a list of a black image and one inverted to white by an effect, giving its output. +fn evaluate_on_two_images(identifier: ProtoNodeIdentifier, inputs: Vec) -> Option { + let compiled = Compiled::new(network(black_and_inverted_images::IDENTIFIER, proto_node(identifier.clone(), inputs), 0))?; + let (output, _) = compiled.evaluate(None); + Some(*output.downcast::().unwrap_or_else(|_| panic!("{} should output a list of each image's result", identifier.as_str()))) +} + +#[test] +fn dehaze_reads_back_each_image_of_a_list() { + let inputs = vec![wire(), NodeInput::value(TaggedValue::Number(0.), false)]; + let Some(images) = evaluate_on_two_images::>>(graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER, inputs) else { + return; + }; + let sizes: Vec<_> = images.iter_element_values().map(|image| (image.width, image.height)).collect(); + assert_eq!(sizes, [(2, 2), (2, 2)]); + + // Without any strength, the haze removal keeps each image's own read-back colors + let colors: Vec<_> = images + .iter_element_values() + .flat_map(|image| image.data.iter().map(|color| (color.r().round(), color.a().round()))) + .collect(); + assert_eq!(colors, [[(0., 1.); 4], [(1., 1.); 4]].concat(), "the black image stays black and the inverted one white"); +} + +#[test] +fn image_color_palette_finds_each_image_of_a_list_its_own_colors() { + let inputs = vec![wire(), NodeInput::value(TaggedValue::Integer(1), false)]; + let Some(colors) = evaluate_on_two_images::>(graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER, inputs) else { + return; + }; + let colors: Vec<_> = colors.iter_element_values().map(|color| (color.r().round(), color.a())).collect(); + assert_eq!(colors, [(0., 1.), (1., 1.)], "one color for each image, in order"); +} + +#[test] +fn image_to_bytes_reads_back_each_image_of_a_list() { + let Some(resources) = evaluate_on_two_images::>(graphene_std::platform_application_io::image_to_bytes::IDENTIFIER, vec![wire()]) else { + return; + }; + let bytes: Vec> = resources.iter_element_values().map(|resource| resource.as_ref().to_vec()).collect(); + assert_eq!(bytes, [[0, 0, 0, 255].repeat(4), [255, 255, 255, 255].repeat(4)]); +}