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

@@ -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)]);
}