From 00d8a9d1886cb3a2fc97d40f8647fb1dc307189e Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 19:09:42 -0500 Subject: [PATCH] Honor distance output channels, axis wrapping and strict source cutoffs --- crates/eval/src/node_execution.rs | 5 ++- crates/eval/tests/filter_tiling.rs | 18 +++++--- crates/formats/src/sbs/filter_map.rs | 2 +- crates/formats/src/sbs/tests.rs | 17 ++++++++ crates/nodes/src/atomic/distance.rs | 10 ++++- .../nodes/src/atomic/distance/mask_field.rs | 2 +- crates/nodes/tests/distance.rs | 42 ++++++++++++++++++- docs/parity-fixes.md | 17 ++++++++ docs/sbs-root-nodes.md | 6 +-- 9 files changed, 105 insertions(+), 14 deletions(-) diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index 3686584..de2b0ec 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -126,7 +126,10 @@ pub(crate) fn cook_node( } if !node.functions.is_empty() - || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map" | "transformation" | "blur" | "directional_blur" | "sharpen") + || matches!( + node.def.as_str(), + "pixel_processor" | "value_processor" | "fx_map" | "transformation" | "blur" | "directional_blur" | "sharpen" | "distance" + ) { base.variables(variables.to_mut()); } diff --git a/crates/eval/tests/filter_tiling.rs b/crates/eval/tests/filter_tiling.rs index 4e76a42..d32a3bc 100644 --- a/crates/eval/tests/filter_tiling.rs +++ b/crates/eval/tests/filter_tiling.rs @@ -5,7 +5,7 @@ use std::sync::Mutex; #[test] fn atomic_filters_wrap_only_the_requested_axes_and_invalidate_cache() { - for operation in ["blur", "directional_blur", "sharpen"] { + for operation in ["blur", "directional_blur", "sharpen", "distance"] { let mut graph = Graph::new("Filter boundaries"); graph.size = [4; 2]; graph.format = OutputFormat::F32; @@ -13,13 +13,19 @@ fn atomic_filters_wrap_only_the_requested_axes_and_invalidate_cache() { let input = graph.add_node("input_grayscale", [0.0; 2]); graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text("source".into())); let filter = graph.add_node(operation, [100.0, 0.0]); - graph.node_mut(filter).unwrap().params.insert("intensity".into(), Value::Float(if operation == "sharpen" { 1.0 } else { 16.0 })); - graph.connect(input, "output", filter, "input").unwrap(); + let (parameter, port, center, background) = if operation == "distance" { ("distance", "mask", 1.0, 0.0) } else { ("intensity", "input", 0.5625, 0.5) }; + let strength = match operation { + "distance" => 48.0, + "sharpen" => 1.0, + _ => 16.0, + }; + graph.node_mut(filter).unwrap().params.insert(parameter.into(), Value::Float(strength)); + graph.connect(input, "output", filter, port).unwrap(); let mut package = Package::new("Filter boundaries"); package.graphs.push(graph); let resource = |_: &str| None; let mut options = Options::new(&resource); - options.inputs.insert("source".into(), Image::gray(16, 16, |x, y| if x == 0 && y == 0 { 0.5625 } else { 0.5 })); + options.inputs.insert("source".into(), Image::gray(16, 16, |x, y| if x == 0 && y == 0 { center } else { background })); let cache = Mutex::new(Cache::default()); for tiling in [[false, false], [true, false], [false, true], [true, true]] { @@ -30,8 +36,8 @@ fn atomic_filters_wrap_only_the_requested_axes_and_invalidate_cache() { assert_eq!(cooked.nodes[&filter].error, None); assert!(!cooked.nodes[&filter].cached); - assert_eq!(image.get_gray(15, 0, false) != 0.5, tiling[0], "{operation}, x, {tiling:?}"); - assert_eq!(image.get_gray(0, 15, false) != 0.5, tiling[1] && operation != "directional_blur", "{operation}, y, {tiling:?}"); + assert_eq!(image.get_gray(15, 0, false) != background, tiling[0], "{operation}, x, {tiling:?}"); + assert_eq!(image.get_gray(0, 15, false) != background, tiling[1] && operation != "directional_blur", "{operation}, y, {tiling:?}"); let cached = cook(&package, 0, &options, &cache); diff --git a/crates/formats/src/sbs/filter_map.rs b/crates/formats/src/sbs/filter_map.rs index 2f80b02..cf14404 100644 --- a/crates/formats/src/sbs/filter_map.rs +++ b/crates/formats/src/sbs/filter_map.rs @@ -32,7 +32,7 @@ pub(super) const FILTERS: &[FilterMap] = &[ sbs: "distance", def: "distance", inputs: &[("mask", "mask"), ("source", "source")], - params: &[("distance", "distance"), ("combinedistance", "combine"), ("distancemode", "metric")], + params: &[("distance", "distance"), ("combinedistance", "combine"), ("distancemode", "metric"), ("colorswitch", "color_mode")], }, FilterMap { sbs: "emboss", diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index b047ddf..b0f5590 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -381,6 +381,23 @@ fn distance_metric_survives_a_package_round_trip() { assert_eq!(metrics, [1, 2]); } +#[test] +fn distance_preserves_declared_grayscale_and_color_outputs_when_the_switch_is_omitted() { + let xml = br#" + + + + + "#; + let loaded = read_sbs(xml, "distances.sbs", &no_linked_files).unwrap().pkg; + let saved = write_sbs(&loaded).unwrap(); + let again = read_sbs(&saved, "distances.sbs", &no_linked_files).unwrap().pkg; + for package in [&loaded, &again] { + let colors: Vec<_> = package.graphs[0].nodes.iter().filter_map(|node| node.params.get("color_mode").and_then(Value::as_bool)).collect(); + assert_eq!(colors, [true, false]); + } +} + #[test] fn image_output_types_follow_color_mode_and_blended_inputs() { let mut package = Package::new("Channels"); diff --git a/crates/nodes/src/atomic/distance.rs b/crates/nodes/src/atomic/distance.rs index 5e4fb60..a29456e 100644 --- a/crates/nodes/src/atomic/distance.rs +++ b/crates/nodes/src/atomic/distance.rs @@ -1,5 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Image, Kind}; mod mask_field; @@ -9,6 +10,7 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .gray_in("mask", "Mask input") .any_in("source", "Source input") + .boolean("color_mode", "Color output", false) .float("distance", "Maximum distance", 10.0, 0.0, 256.0) .choice("metric", "Distance metric", &["Euclidean", "Manhattan", "Chebyshev"], 0) .boolean("combine", "Combine distance with source", true) @@ -19,6 +21,12 @@ pub(super) fn definition() -> NodeDefinition { fn distance(context: &CookContext) -> CookResult { let mask = context.gray_or(0, 0.0); let source = context.sized(1); + let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; + // An incompatible source produces zero channels. Only a disconnected source produces a mask ramp. + if source.as_ref().is_some_and(|image| image.kind() != kind) { + return Ok(vec![Image::filled(mask.width(), mask.height(), kind, [0.0; 4])]); + } let radius = (context.f("distance").max(0.0) * (mask.width().min(mask.height()) as f32 / 256.0)).min(f32::MAX); - Ok(vec![mask_field::render(&mask, source.as_ref(), radius, context.tiling_axes(), context.i("metric"), context.b("combine"))?]) + let image = mask_field::render(&mask, source.as_ref(), radius, context.tiling_axes(), context.i("metric"), context.b("combine"))?; + Ok(vec![if kind == Kind::Color && image.is_gray() { image.to_color() } else { image }]) } diff --git a/crates/nodes/src/atomic/distance/mask_field.rs b/crates/nodes/src/atomic/distance/mask_field.rs index f524164..2bbef7e 100644 --- a/crates/nodes/src/atomic/distance/mask_field.rs +++ b/crates/nodes/src/atomic/distance/mask_field.rs @@ -151,7 +151,7 @@ pub(super) fn render(mask: &Image, source: Option<&Image>, radius: f32, tile: [b }; Ok(Image::generate(width, height, source.kind(), |x, y| { let (site, distance) = site_distance(x, y); - let pixel = if distance <= radius { source.get(site[0].into(), site[1].into(), false) } else { source.get(x.into(), y.into(), false) }; + let pixel = if distance < radius { source.get(site[0].into(), site[1].into(), false) } else { source.get(x.into(), y.into(), false) }; if !combine { return pixel; } diff --git a/crates/nodes/tests/distance.rs b/crates/nodes/tests/distance.rs index 2119f29..ea46e42 100644 --- a/crates/nodes/tests/distance.rs +++ b/crates/nodes/tests/distance.rs @@ -9,10 +9,20 @@ fn cook(mask: Image, source: Option, tile: bool, combine: bool, distance: } fn cook_metric(mask: Image, source: Option, tile: bool, combine: bool, distance: f32, metric: u32) -> Image { + let color = source.as_ref().is_some_and(|image| !image.is_gray()); + cook_mode(mask, source, tile, combine, distance, metric, color) +} + +fn cook_mode(mask: Image, source: Option, tile: bool, combine: bool, distance: f32, metric: u32, color: bool) -> Image { let def = find("distance").unwrap(); let params = resolve_params( def, - &BTreeMap::from([("distance".into(), Value::Float(distance)), ("combine".into(), Value::Bool(combine)), ("metric".into(), Value::Enum(metric))]), + &BTreeMap::from([ + ("distance".into(), Value::Float(distance)), + ("combine".into(), Value::Bool(combine)), + ("metric".into(), Value::Enum(metric)), + ("color_mode".into(), Value::Bool(color)), + ]), ); let (w, h) = (mask.width(), mask.height()); let inputs = [Some(mask), source]; @@ -33,6 +43,23 @@ fn cook_metric(mask: Image, source: Option, tile: bool, combine: bool, di (def.cook)(&ctx).unwrap().remove(0) } +#[test] +fn distance_color_selection_controls_empty_sources_and_channel_mismatches() { + let mask = Image::gray(32, 32, |x, y| if (x, y) == (16, 16) { 1.0 } else { 0.0 }); + let gray = cook(mask.clone(), None, true, true, 31.0); + for combine in [true, false] { + let color = cook_mode(mask.clone(), None, true, combine, 31.0, 0, true); + assert_eq!(color.kind(), Kind::Color); + assert_eq!(color.data(), gray.to_color().data()); + } + for (source_kind, color) in [(Kind::Color, false), (Kind::Gray, true)] { + let source = Image::filled(32, 32, source_kind, [0.75; 4]); + let output = cook_mode(mask.clone(), Some(source), true, true, 31.0, 0, color); + assert_eq!(output.kind(), if color { Kind::Color } else { Kind::Gray }); + assert!(output.data().iter().all(|v| v.to_bits() == 0)); + } +} + #[test] fn tiled_distance_spreads_source_across_stationary_gradient() { let mask = Image::gray(32, 32, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 }); @@ -72,6 +99,19 @@ fn alternative_distance_metrics_use_the_quantized_site_center() { } } +#[test] +fn distance_keeps_the_current_source_texel_at_the_radius() { + let mask = Image::gray(32, 32, |x, y| if (x, y) == (16, 16) { 1.0 } else { 0.0 }); + let source = Image::gray(32, 32, |x, y| if (x, y) == (16, 16) { 0.8125 } else { -0.109375 }); + for tile in [false, true] { + for (combine, expected) in [(false, -0.109375f32), (true, -0.0f32)] { + let image = cook_metric(mask.clone(), Some(source.clone()), tile, combine, 16.0, 1); + assert_eq!(image.get_gray(14, 16, false).to_bits(), expected.to_bits()); + assert_eq!(image.get_gray(16, 16, false), 0.8125); + } + } +} + #[test] fn zero_distance_and_a_positive_subpixel_distance_have_distinct_site_values() { let mask = Image::gray(32, 32, |x, y| if (x, y) == (1, 2) { 1.0 } else { 0.0 }); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index cf0a4f6..d5f1899 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -392,6 +392,23 @@ For each of the three shapes, repeat the linear sweep on each axis using these s | 64 | (.8125,1,.625) | .34375 | .375 | (0,0,.25) | 269 | | 32 | (1,.3125,.75) | .75 | .21875 | (.0625,−.125,.1875) | 312 | +### Distance output channels, axis wrapping and cutoffs + +| Original controls | Renders | Exact pixels / compared | Maximum U8 / U16 levels | Maximum F16 / F32 error | +|---|---:|---:|---:|---:| +| Unconnected source, both output kinds and both Combine settings | 64 | 294,912/294,912 | 0 / 0 | 0 / 0 | +| Connected source with the opposite output kind | 14 | 21,504/21,504 | 0 / 0 | 0 / 0 | +| Connected source with static axis wrapping | 56 | 86,012/86,016 | 28 / 7,248 | .110534668 / .110588416 | +| Single-center cutoff, both settings of Combine | 168 | 258,048/258,048 | — | — / 0 | + +Without a source, grayscale returns the distance ramp and color returns the same ramp in RGB with alpha one. Connecting a grayscale source to color output, or RGBA to grayscale output, returns zeros in every requested channel. These 46 color or conflicting-source renders previously returned the wrong channel count. For the first row use 32² tiled and 64×128 open masks. Test empty, full and single-corner masks at strength zero, a sparse mask at 79.5, and a center site at 31. Use seed 179+37j, j from zero. Run F32 for each, and also U8, U16 and F16 for the sparse field. Use the [mask and source formulas](#connected-distance-sources-and-cellular-patterns). + +For the next two rows, use 32² gray and 64×32 RGBA sources. Combine is on. Use empty, full, corner and sparse F32 masks, then repeat the sparse mask as F16, U16 and U8. For the conflicting kinds retain the connected controls' strengths 31, 31, 32 and 41.375 for those four mask layouts. For static controls use a matching source, constant strength 47.25 and the four wrapping settings. Use seeds 307+19j in each group. Static tiling previously matched 77,637/86,016 pixels. The four remaining differences are the same sparse gray texel (31,18) with Y wrapping alone. Its F32 values are .113228783 in MaterialCraft and .223817199 in the reference. + +For the cutoff row place a site at the center of each source size and choose radii .25, 1, 2, 3, 4, 8 and 16 pixels at seeds 509+23j. Set strength to radius×256/min(W,H). Test Euclidean, Manhattan and Chebyshev distances with both axes open or both tiled. Exactly at the radius, the source comes from the current texel. For example, at (14,16) in the 32² Manhattan case with radius 2, the gray output with Combine off is −.109375 before gray-input conversion. With Combine on the stored F32 result is negative zero. Including the boundary in the spread previously matched 257,890/258,048 pixels with maximum error 1.1875. + +The [connected-source and cellular measurements](#connected-distance-sources-and-cellular-patterns) retain 184,320/184,320 exact pixels on the matching-source format matrix. The mixed metric matrix now matches 630,768/630,784, maximum F32 error .096614778. The 16 residuals are on sparse wrapped masks. The radius sweep retains 950,270/950,272, maximum .765625. Directional distance still matches 342,528/342,528 across both outputs. The two Cells 4 roots still match 19,151 and 15,949 of 173,312 pixels respectively, with their first difference at the scatter map. + ### Connected distance sources and cellular patterns A connected distance source supplies the nearest qualifying site's texel inside the radius and the current texel beyond it. With Combine enabled the gray channel or the alpha channel is attenuated. RGB remains the sampled site's color inside the radius and the current texel's color outside. The 120 gray and RGBA controls below previously matched 64,706/184,320 pixels. Maximum errors were 255 U8 levels, 65,535 U16 levels and 1.859375 in F16 and F32. diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index a73bb19..a58903b 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -177,7 +177,7 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard | [diffusion.sbs/impl/pass_UV](../assets/sbs/diffusion.sbs) | 1 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [diffusion.sbs/impl/pass_gray](../assets/sbs/diffusion.sbs) | 3 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [diffusion.sbs/impl/pass_normal](../assets/sbs/diffusion.sbs) | 2 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | -| [directional_distance.sbs/directional_distance](../assets/sbs/directional_distance.sbs) | 3 | No | [Parity · 32 renders, all 342,528 pixels exact](parity-fixes.md#directional-distance-and-mask-propagation) | +| [directional_distance.sbs/directional_distance](../assets/sbs/directional_distance.sbs) | 3 | No | [Parity · 32 renders, both outputs exact across 342,528 pixels](parity-fixes.md#distance-output-channels-axis-wrapping-and-cutoffs) | | [directionnal_noise.sbs/directionnal_noise](../assets/sbs/directionnal_noise.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [dirt_1.sbs/dirt_1](../assets/sbs/dirt_1.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [dirt_3.sbs/dirt_3](../assets/sbs/dirt_3.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | @@ -293,8 +293,8 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard | [noise_bnw_spots_3_v2.sbs/bnw_spots_3](../assets/sbs/noise_bnw_spots_3_v2.sbs) | 0 | No | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [noise_cells_1.sbs/cells_1](../assets/sbs/noise_cells_1.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [noise_cells_1_v2.sbs/cells_1](../assets/sbs/noise_cells_1_v2.sbs) | 0 | No | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | -| [noise_cells_4.sbs/cells_4](../assets/sbs/noise_cells_4.sbs) | 1 | Yes | [In progress · 17 renders, 19,151/173,312 exact pixels](parity-fixes.md#connected-distance-sources-and-cellular-patterns) | -| [noise_cells_4_v2.sbs/cells_4](../assets/sbs/noise_cells_4_v2.sbs) | 1 | No | [In progress · 17 renders, 15,949/173,312 exact pixels](parity-fixes.md#connected-distance-sources-and-cellular-patterns) | +| [noise_cells_4.sbs/cells_4](../assets/sbs/noise_cells_4.sbs) | 1 | Yes | [In progress · 19,151/173,312 pixels, first difference at the scatter map](parity-fixes.md#distance-output-channels-axis-wrapping-and-cutoffs) | +| [noise_cells_4_v2.sbs/cells_4](../assets/sbs/noise_cells_4_v2.sbs) | 1 | No | [In progress · 15,949/173,312 pixels, first difference at the scatter map](parity-fixes.md#distance-output-channels-axis-wrapping-and-cutoffs) | | [noise_clouds_1.sbs/clouds_1](../assets/sbs/noise_clouds_1.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [noise_clouds_1_v2.sbs/clouds_1](../assets/sbs/noise_clouds_1_v2.sbs) | 0 | No | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [noise_clouds_2.sbs/clouds_2](../assets/sbs/noise_clouds_2.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) |