Make the pixel-reading nodes take 'Pixels' instead of baking effects

This commit is contained in:
Keavon Chambers committed 2026-12-05 07:59:55 -08:00
1 parent f3dafd9dc2
commit 71e0099edd
8 files changed
+209 -31

No files matched your search

Generated
-2
View File
@@ -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",
]
-1
View File
@@ -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 }
@@ -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<String>) -> Item<Resource> {
/// 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<Raster<CPU>>) -> Item<Resource> {
let bytes: Vec<u8> = raster_kernels::evaluate_raster_effects(image)
fn image_to_bytes(_: impl Ctx, image: Item<Pixels>) -> Item<Resource> {
let bytes: Vec<u8> = image
.element()
.data
.iter()
+4 -4
View File
@@ -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<Raster<CPU>>,
image_frame: Item<Pixels>,
#[unit("%")]
#[range]
#[hard(0..100)]
@@ -18,7 +17,8 @@ fn dehaze(
) -> Item<Raster<CPU>> {
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
@@ -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<Raster<CPU>>,
image: Item<Pixels>,
/// 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;
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<Color> {
let data = runs.iter().flat_map(|&(color, length)| std::iter::repeat_n(color, length)).collect::<Vec<_>>();
@@ -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()
}
-1
View File
@@ -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 }
+11 -14
View File
@@ -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<Raster<CPU>>,
image: Item<Pixels>,
/// 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<Raster<CPU>>, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option<usize>, slot: &TraceSlot, slice: Duration) -> Poll<List<Graphic>> {
fn trace_slice(image: &Item<Pixels>, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option<usize>, slot: &TraceSlot, slice: Duration) -> Poll<List<Graphic>> {
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<Raster<CPU>>, 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<Raster<CPU>> {
fn raster(width: u32, height: u32, color: impl Fn(u32, u32) -> Color) -> Item<Pixels> {
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<Raster<CPU>>, slot: &TraceSlot) -> Poll<List<Graphic>> {
fn slice(image: &Item<Pixels>, slot: &TraceSlot) -> Poll<List<Graphic>> {
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<Raster<CPU>>, detail: f64, tolerance: f64) -> List<Graphic> {
fn trace(image: &Item<Pixels>, detail: f64, tolerance: f64) -> List<Graphic> {
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<Raster<CPU>> {
fn ring(size: u32, inner: f64, width: f64) -> Item<Pixels> {
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<Raster<CPU>> {
fn busy(size: u32) -> Item<Pixels> {
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<Raster<CPU>>, runtime: &AsyncRuntime) -> Poll<List<Graphic>> {
fn evaluate(slot: &TraceSlot, image: &Item<Pixels>, runtime: &AsyncRuntime) -> Poll<List<Graphic>> {
let one = || Item::new_from_element(1.);
let on = || Item::new_from_element(true);
vectorize(
@@ -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::<wgpu_executor::NoGpuError>(), "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<Raster<CPU>> {
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<Raster<CPU>> {
varied_image(false)
}
/// The varied image inverted by its effect.
#[node_macro::node(category(""))]
fn inverted_varied_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
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<bool> {
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<Raster<CPU>>, List<Raster<CPU>>, List<Color>, List<Graphic>);
// Resources compare by their bytes
if let (Some(a), Some(b)) = (a.downcast_ref::<Item<Resource>>(), b.downcast_ref::<Item<Resource>>()) {
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<usize> = (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::<Vec<_>>(), "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<Raster<CPU>> {
// 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::<List<Graphic>>().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<T: 'static>(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> Option<T> {
let compiled = Compiled::new(network(black_and_inverted_images::IDENTIFIER, proto_node(identifier.clone(), inputs), 0))?;
let (output, _) = compiled.evaluate(None);
Some(*output.downcast::<T>().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::<List<Raster<CPU>>>(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::<List<Color>>(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::<List<Resource>>(graphene_std::platform_application_io::image_to_bytes::IDENTIFIER, vec![wire()]) else {
return;
};
let bytes: Vec<Vec<u8>> = 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)]);
}